From 54ea182f493d371c53db580aca462d2faa5f255c Mon Sep 17 00:00:00 2001 From: Danno Ferrin Date: Mon, 2 Nov 2026 14:52:27 -0700 Subject: [PATCH 01/44] docs(giga-storage): propose staking, distribution and slashing storage Draft storage layouts for the EVM-only staking, distribution and slashing precompiles, and the rationale behind them, taken from ffd15bb, which is not merged on its own. - staking-design-rationale.md: the proposal, built from three principles (Solidity slot layout, V2 structures for migration, rewards undesigned) - StakingStorage, DistributionStorage, SlashingStorage: draft layouts - Sets.sol: dependency-free AddressSet/UintSet with EnumerableSet's layout --- docs/giga-storage/DistributionStorage.sol | 43 ++ docs/giga-storage/Sets.sol | 16 + docs/giga-storage/SlashingStorage.sol | 29 + docs/giga-storage/StakingStorage.sol | 128 +++++ docs/giga-storage/staking-design-rationale.md | 534 ++++++++++++++++++ 5 files changed, 750 insertions(+) create mode 100644 docs/giga-storage/DistributionStorage.sol create mode 100644 docs/giga-storage/Sets.sol create mode 100644 docs/giga-storage/SlashingStorage.sol create mode 100644 docs/giga-storage/StakingStorage.sol create mode 100644 docs/giga-storage/staking-design-rationale.md diff --git a/docs/giga-storage/DistributionStorage.sol b/docs/giga-storage/DistributionStorage.sol new file mode 100644 index 0000000000..80a272a19a --- /dev/null +++ b/docs/giga-storage/DistributionStorage.sol @@ -0,0 +1,43 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.30; + +/// @notice Storage schema of the evmonly distribution precompile (0x1007), held as +/// that address's contract storage. Each state variable is an x/distribution +/// store prefix, named in its comment. +/// @dev Params are `ParamsStorage.distribution`. Outstanding rewards and the +/// community pool sit in the balance of `DistributionEscrow`, a derived address +/// in `distribution/layout.go`. Amounts and stakes are wei; reward ratios and +/// slash fractions are 1e18-scaled. +contract DistributionStorage { + struct ValidatorHistoricalRewards { + uint256 cumulativeRewardRatio; + uint32 referenceCount; + } + + struct ValidatorCurrentRewards { + uint256 rewards; + uint64 period; + } + + struct DelegatorStartingInfo { + uint64 previousPeriod; + uint64 height; + uint256 stake; + } + + struct ValidatorSlashEvent { + uint64 height; + uint64 validatorPeriod; + uint256 fraction; + } + + uint256 internal communityPool; // 0x00: FeePool.community_pool + address internal previousProposer; // 0x01: consensus address + mapping(address => uint256) internal validatorOutstandingRewards; // 0x02: validator => + mapping(address => address) internal delegatorWithdrawAddr; // 0x03: delegator => payee; zero is the delegator + mapping(address => mapping(address => DelegatorStartingInfo)) internal delegatorStartingInfo; // 0x04: validator => delegator => + mapping(address => mapping(uint64 => ValidatorHistoricalRewards)) internal validatorHistoricalRewards; // 0x05: validator => period => + mapping(address => ValidatorCurrentRewards) internal validatorCurrentRewards; // 0x06: validator => + mapping(address => uint256) internal validatorAccumulatedCommission; // 0x07: validator => + mapping(address => ValidatorSlashEvent[]) internal validatorSlashEvents; // 0x08: validator => ascending by height +} diff --git a/docs/giga-storage/Sets.sol b/docs/giga-storage/Sets.sol new file mode 100644 index 0000000000..89dba29bea --- /dev/null +++ b/docs/giga-storage/Sets.sol @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.30; + +/// @notice A set of addresses. positions holds each member's 1-based index into +/// values, 0 when absent; removal moves the last value into the gap. Read and +/// written by solstorage.Set. +struct AddressSet { + address[] values; + mapping(address => uint256) positions; +} + +/// @notice A set of uint256 values, laid out as AddressSet. +struct UintSet { + uint256[] values; + mapping(uint256 => uint256) positions; +} diff --git a/docs/giga-storage/SlashingStorage.sol b/docs/giga-storage/SlashingStorage.sol new file mode 100644 index 0000000000..671c3a0394 --- /dev/null +++ b/docs/giga-storage/SlashingStorage.sol @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.30; + +import "./Sets.sol"; + +/// @notice Storage schema of the evmonly slashing precompile (0x1014), held as that +/// address's contract storage. Each state variable is an x/slashing store prefix, +/// named in its comment. +/// @dev Params are `ParamsStorage.slashing`. Keys are consensus addresses, +/// sha256(consensusPubkey)[:20]. Times are Unix nanoseconds. +contract SlashingStorage { + struct ValidatorSigningInfo { + uint64 startHeight; + uint64 indexOffset; + uint64 jailedUntil; + bool tombstoned; + uint64 missedBlocksCounter; + } + + struct ValidatorMissedBlockArray { + uint64 windowSize; + uint64[] missedBlocks; // bit i of the window is bit i%64 of word i/64 + } + + mapping(address => ValidatorSigningInfo) internal validatorSigningInfo; // 0x01: consensus address => + AddressSet internal signingInfoSet; // every consensus address in validatorSigningInfo + mapping(address => ValidatorMissedBlockArray) internal validatorMissedBlocks; // 0x02: consensus address => + mapping(address => bytes32) internal addrPubkeyRelation; // 0x03: consensus address => ed25519 key +} diff --git a/docs/giga-storage/StakingStorage.sol b/docs/giga-storage/StakingStorage.sol new file mode 100644 index 0000000000..c08dd14947 --- /dev/null +++ b/docs/giga-storage/StakingStorage.sol @@ -0,0 +1,128 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.30; + +import "./Sets.sol"; + +/// @notice Storage schema of the evmonly staking precompile (0x1005), held as that +/// address's contract storage. Each state variable is an x/staking store prefix, +/// named in its comment. +/// @dev Params are `ParamsStorage.staking`. Bonded tokens sit in the balance of +/// `BondedEscrow` and unbonded and unbonding tokens in `NotBondedEscrow`, derived +/// addresses in `staking/layout.go`. Tokens and balances are wei; shares and +/// rates are 1e18-scaled; times are Unix nanoseconds. Accounts and operators are EVM +/// addresses; a consensus address is sha256(consensusPubkey)[:20]. +contract StakingStorage { + struct Description { + string moniker; + string identity; + string website; + string securityContact; + string details; + } + + struct CommissionRates { + uint256 rate; + uint256 maxRate; + uint256 maxChangeRate; + } + + struct Commission { + CommissionRates commissionRates; + uint64 updateTime; + } + + struct Validator { + bytes32 consensusPubkey; // ed25519 + bool jailed; + uint8 status; // 1=Unbonded, 2=Unbonding, 3=Bonded + uint256 tokens; + uint256 delegatorShares; + Description description; + uint64 unbondingHeight; + uint64 unbondingTime; + Commission commission; + uint256 minSelfDelegation; + uint256[8] __gap; + } + + struct Delegation { + uint256 shares; + } + + struct UnbondingDelegationEntry { + uint64 creationHeight; + uint64 completionTime; + uint256 initialBalance; + uint256 balance; + } + + struct RedelegationEntry { + uint64 creationHeight; + uint64 completionTime; + uint256 initialBalance; + uint256 sharesDst; + } + + /// @dev A queue entry's completionTime is never earlier than the one before it. + struct UnbondingQueueEntry { + uint64 completionTime; + address delegator; + address validator; + } + + struct RedelegationQueueEntry { + uint64 completionTime; + address delegator; + address srcValidator; + address dstValidator; + } + + struct ValidatorQueueEntry { + uint64 completionTime; + uint64 completionHeight; + address operator; + } + + /// @dev A first-in first-out queue: entries are at indexes [head, tail). + struct QueueBounds { + uint64 head; + uint64 tail; + } + + mapping(address => uint64) internal lastValidatorPower; // 0x11: operator => power + AddressSet internal lastValidatorPowerSet; // operators with a lastValidatorPower + uint256 internal lastTotalPower; // 0x12 + + mapping(address => Validator) internal validators; // 0x21: operator => + AddressSet internal validatorSet; // every operator in validators + mapping(address => address) internal validatorsByConsAddr; // 0x22: consensus address => operator + address[] internal validatorsByPower; // 0x23: unjailed operators, descending by power, ties to the lower address + + mapping(address => mapping(address => Delegation)) internal delegations; // 0x31: delegator => validator => + mapping(address => AddressSet) internal delegationsByValidator; // 0x37: validator => delegators + mapping(address => AddressSet) internal delegationsByDelegator; // delegator => validators + + mapping(address => mapping(address => UnbondingDelegationEntry[])) internal unbondingDelegations; // 0x32: delegator => validator => entries, at most maxEntries + mapping(address => AddressSet) internal unbondingDelegationsByValidator; // 0x33: validator => delegators + mapping(address => AddressSet) internal unbondingDelegationsByDelegator; // delegator => validators + + mapping(address => mapping(address => mapping(address => RedelegationEntry[]))) internal redelegations; // 0x34: delegator => src => dst => entries, at most maxEntries + mapping(address => mapping(address => AddressSet)) internal redelegationsByValSrc; // 0x35: src => delegator => dsts + mapping(address => AddressSet) internal redelegationDelegatorsByValSrc; // src => delegators + mapping(address => mapping(address => uint256)) internal redelegationsByValDst; // 0x36: dst => delegator => open entries into dst + mapping(address => mapping(address => AddressSet)) internal redelegationsByDelegator; // delegator => src => dsts + mapping(address => AddressSet) internal redelegationSrcsByDelegator; // delegator => srcs + + QueueBounds internal unbondingQueueBounds; + mapping(uint64 => UnbondingQueueEntry) internal unbondingQueue; // 0x41: index => + QueueBounds internal redelegationQueueBounds; + mapping(uint64 => RedelegationQueueEntry) internal redelegationQueue; // 0x42: index => + QueueBounds internal validatorQueueBounds; + mapping(uint64 => ValidatorQueueEntry) internal validatorQueue; // 0x43: index => + + /// @dev V2 to giga migration. The phase runs from the cutover height until + /// migrationCursor passes the last V2 key. + bool internal migrating; + bytes internal migrationCursor; // last V2 store key copied + bytes[] internal migrationFailures; // V2 store keys that could not be copied +} diff --git a/docs/giga-storage/staking-design-rationale.md b/docs/giga-storage/staking-design-rationale.md new file mode 100644 index 0000000000..54acc305e0 --- /dev/null +++ b/docs/giga-storage/staking-design-rationale.md @@ -0,0 +1,534 @@ +# Giga staking, distribution and slashing: storage proposal + +This is a proposal for how state for the EVM-only staking (`0x1005`), +distribution (`0x1007`) and slashing (`0x1014`) precompiles could be stored. It +is not a settled design. It starts from three principles and works forward, so +each choice can be traced back to the principle behind it, and it calls out the +places where the principles pull against each other and the choice is still +open. + +The draft layouts are the `.sol` files in this directory: `StakingStorage.sol`, +`DistributionStorage.sol`, `SlashingStorage.sol`, and the shared `Sets.sol`. +`staking-design.md` is a terser working draft of the same proposal. Nothing here +is implemented. + +The three principles: + +1. **Storage follows Solidity's layout rules**, ideally declared in a `.sol` + file. +2. **Migration from V2 should be easy**, so the proposal copies V2's record + structures wherever it can, while using Ethereum-native data types. V2's + precompiles would be shut off before the migration and the giga precompiles + turned on after it. +3. **How staking rewards are applied during execution is not designed yet.** + The storage should be able to support that design without presuming it. + +--- + +## Principle 1: storage follows Solidity's layout rules + +### What it means + +Each precompile would keep its state as the contract storage of its own +address, as a deployed contract does. The slot for every value is the slot the +Solidity compiler would assign if the `.sol` file in this directory were +compiled. Go code reads and writes those slots through the `solstorage` +helpers, the same way gov and params do today. + +Solidity's rules, briefly: + +- State variables take slots in declaration order, starting at 0. +- Small fields (`bool`, `uint8`, `uint64`, `address`) are packed into one + 32-byte slot when they fit next to each other. +- A struct starts on a fresh slot and takes consecutive slots for its fields. +- A static array (`uint256[8]`) is laid out inline, like a struct. +- A dynamic array keeps its length in its own slot; its elements start at + `keccak256(slot)`. +- A mapping's own slot stays empty; the value for key `k` lives at + `keccak256(k . slot)`. Nested mappings apply this once per level. +- `string` and `bytes` are stored inline when short and spill out to + `keccak256(slot)` when long. + +For example, a delegation's shares would live at +`delegations[delegator][validator].shares`. In the draft, `delegations` sits at +slot 9 of `StakingStorage` (the two sets before it take two slots each), so the +shares are at `keccak256(validator . keccak256(delegator . 9))`, with each key +padded to 32 bytes. + +`Validator` shows the struct rules on a larger record. In the draft it takes 23 +slots: + +| Slot offset | Fields | +|---|---| +| 0 | `consensusPubkey` | +| 1 | `jailed`, `status` (packed) | +| 2 | `tokens` | +| 3 | `delegatorShares` | +| 4–8 | `description` (five strings) | +| 9 | `unbondingHeight`, `unbondingTime` (packed) | +| 10–13 | `commission` (three rates, then `updateTime`) | +| 14 | `minSelfDelegation` | +| 15–22 | `__gap` (reserved) | + +### Why + +- **The `.sol` file is the spec.** `solc --storage-layout` or `forge inspect` + on it gives the exact slot of every field, so there is no second, + hand-written description of the storage to drift out of date. +- **Standard tooling can read the state.** `eth_getStorageAt`, explorers and + debuggers already understand this layout, and a contract could be written + against the same file to read it. +- **It matches gov and params**, so all giga precompiles would share one + storage model and one set of helpers. + +### Consequences + +**Layouts only grow.** Once a public network runs a layout, a state variable or +field cannot move. New fields would take slots from a struct's `__gap`, and new +state variables would go after the last one. The draft `Validator` reserves +eight slots for this, and `layout_test.go` pins would catch an accidental +reorder. + +**No library dependencies.** The draft layouts import nothing from outside this +directory, including OpenZeppelin. The precompiles need enumerable sets, and +OpenZeppelin's `EnumerableSet` has the right shape, but importing it would tie +the storage to a third-party version. `Sets.sol` instead declares `AddressSet` +and `UintSet` as plain structs with the same slot layout: + +```solidity +struct AddressSet { + address[] values; // members, in insertion order + mapping(address => uint256) positions; // 1-based index into values; 0 = absent +} +``` + +Removing a member moves the last value into the gap, so each operation is a +constant number of writes. `solstorage.Set` already reads this layout. + +**Some things IAVL can do, slots cannot.** V2 stores state in an ordered key +value store. It can walk keys in sorted order, walk every key under a prefix, +delete every key under a prefix, and ask whether any key under a prefix exists. +Contract storage is a hash map with none of those operations. Each place this +proposal departs from V2's structures comes from that gap. The largest, the +prefix walks, may argue for relaxing Principle 1 in places; see below. + +--- + +## Principle 2: copy V2's structures + +### What it means + +The migration from V2 is likely the riskiest step in this work. It moves the +stake and pending rewards of every delegator on the chain, and it has to finish +while blocks keep coming. One way to keep it manageable is to make it close to +a transcription: each V2 record becomes one giga record with the same shape, so +the migration code is a field-by-field conversion and a test can compare V2 and +giga record for record. + +The proposal copies **structure**, not data types: + +- **Each V2 store prefix becomes one state variable**, named after the V2 + record and commented with the prefix it came from. +- **Each record keeps V2's fields, field order and names.** +- **Data types are Ethereum-native.** Amounts are wei, not usei. Shares, rates + and reward ratios are 1e18-scaled fixed point, which is also V2's `sdk.Dec` + scale. Addresses are EVM addresses, times are Unix nanoseconds. +- **The rewards accounting stays F1.** + +**Converting amounts to wei.** One usei is 10¹² wei, so the migration would +multiply token amounts by 10¹². To keep each validator's exchange rate between +tokens and shares unchanged, shares would be multiplied by the same factor, as +would delegations' starting stake. F1's reward ratios are rewards per token, so +they are unchanged when both sides scale. V2 keeps rewards as `Dec` because usei +is coarse. In wei the fractional part is far smaller; one option is to store +reward and pool amounts as whole wei and drop the sub-wei remainder (under one +wei per record) at migration, another is to keep them 1e18-scaled as V2 does. +This needs a decision. + +**Why F1.** V2 does not credit each delegator every block. It credits each +*validator* with a running "rewards per token" total, and records, for each +delegation, the period of that total it started in. When a delegator acts, their +rewards are `stake × (current total − total when they started)`. Nothing +per-delegation is written until the delegator does something. A simpler +rewards-per-share model was considered, but it would mean settling every +delegation's pending rewards at cutover, which with something on the order of a +million delegations is not a single-block operation. Keeping F1 lets pending +rewards carry over in the same shape. + +### The mapping + +Staking: + +| V2 prefix | V2 record | Proposed giga state variable | +|---|---|---| +| `0x11` | last validator power | `lastValidatorPower` (+ set) | +| `0x12` | last total power | `lastTotalPower` | +| `0x21` | validators | `validators` (+ set) | +| `0x22` | validator by consensus address | `validatorsByConsAddr` | +| `0x23` | validators by power | `validatorsByPower` (sorted array) | +| `0x31` | delegations | `delegations` (+ set per delegator) | +| `0x37` | delegations by validator | `delegationsByValidator` | +| `0x32`, `0x33` | unbonding delegations and their index | `unbondingDelegations` (+ sets) | +| `0x34`–`0x36` | redelegations and their indexes | `redelegations` (+ sets, a count) | +| `0x41`–`0x43` | unbonding, redelegation, validator queues | three queues | +| `0x50` | historical info | not carried over (see below) | + +Distribution: prefixes `0x00`–`0x08` map one to one onto the nine state +variables in `DistributionStorage.sol`, from `communityPool` to +`validatorSlashEvents`. + +Slashing: signing info (`0x01`), Sei's packed missed-block array (`0x02`) and +the address-to-pubkey relation (`0x03`) map one to one. The missed-block +`uint64[]` packs four words per slot, so the bits are V2's bits. + +### The power index + +V2 keeps validators sorted by power under `0x23`, and EndBlock walks that range +from the top to pick the active set. The proposal keeps the same structure: a +stored index, `validatorsByPower`, holding the same validators V2 indexes +(jailed validators are left out), in V2's order: descending by consensus power, +ties to the lower address. Because it is committed state, the index is the same +on every node, survives restarts and state sync without a rebuild, and can be +copied from V2's `0x23` range in order at cutover. + +Slots cannot keep keys sorted for free, so the index is an `address[]` that the +precompile keeps in order. When a validator's power changes, its old position is +found by binary search over the array (reading each probed validator's power), +and it moves up or down until it is in order again, one slot write for each +place it passes. A change that does not pass a neighbour costs reads only, since +the validator's tokens are written anyway. + +**How often that happens.** Over about 28 hours of pacific-1 (216,000 blocks, +ending at height 241,156,163), the 40 bonded validators saw 60 delegations, 29 +undelegations and 2 incoming redelegations, about one power change every 2,400 +blocks, touching 23 validators. The gaps between neighbours in the ranking are +large: the smallest gap between adjacent bonded validators is about 225k SEI, +the median 1.9M SEI, and 40th place sits 27.8M SEI above 41st. Almost every +change moves its validator zero places; a full re-sort never happens. + +**The worst case and whether it can be abused.** The most a single transaction +can cost is moving one validator from last to first: about N slot writes, where +N is the number of indexed validators (88 today). The precompile would charge +gas for each place moved, so whoever causes a reorder pays for it, and the cost +of a transaction is bounded by N. + +Flipping a validator between first and last repeatedly is not a cheap way to +load the chain: + +- Moving from 41st to 1st today needs more than the top validator's stake, + about 183M SEI on top of the 17.6M already there. Even a one-place move needs + at least the smallest gap, about 225k SEI. +- Moving the stake back is rate-limited. Undelegating locks funds for 21 days. + A redelegation's destination cannot be redelegated out of until that entry + matures, and `maxEntries` caps open entries at 7 per pair. Each tranche of + capital gets roughly two large moves per unbonding period. +- The capital is not lost; it stays staked and earns rewards. The limit on the + attacker is the capital needed and the lock-ups, and the cost is the gas, + which is no worse than a contract writing N slots. + +A cheaper variant would be to register many validators with small, nearly equal +stakes, so that small delegations cause long moves. That is bounded by a cap on +validator records (a `maxValidatorRecords` param) and a minimum self-delegation +to create a validator, together with the per-place gas charge. V2's index has +the same economics for active-set churn; the difference is that V2 pays a fixed +IAVL delete and insert, where slots pay per place moved. + +**Scaling.** At tens of thousands of validator records, gaps shrink and changes +move further, so the per-place cost grows. The cap keeps N in the range where +that cost is small. + +**Alternatives considered:** + +- **Rank in memory at EndBlock.** Read every validator, sort, take the top + `maxValidators`. Nothing extra is stored, but every validator is read every + block. +- **A node-local cache.** The same sorted list held in memory instead of slots. + The reorder is not gas-metered, and the cache must be rebuilt identically on + every node, follow tx reverts and snapshots, and be rebuilt after state sync. +- **Ordered flatkv keys**, V2's approach exactly. See *Prefix walks*. + +### Where the structures don't carry over + +Each of these is a place where slot storage, or a deliberate simplification, +forces a change from V2. The first is the hardest. + +#### Prefix walks + +Anywhere V2 walks every key under a prefix ("all delegations of this delegator", +"all delegators of this validator", "all validators"), slot storage needs an +explicit enumeration set. The draft layouts do this: V2's own index prefixes +(`0x33`, `0x35`, `0x37`) become sets of the same shape, and new sets cover walks +V2 did over the primary key (`validatorSet`, `delegationsByDelegator` and so +on). + +This may not hold up. Each set adds two or three slot writes whenever a member +joins or leaves, and the sets roughly double the writes for every delegation +created or removed. Across a million delegations the sets themselves are a large +share of the state, and of what the migration has to write. Removing a validator +or a delegator with many entries means walking and clearing large sets. + +The alternative is to store the indexes, and possibly the primary records, as +ordered flatkv keys and use flatkv's prefix reads, which is what V2 does on IAVL. +That would give back ordered and prefix iteration, prefix delete and existence +checks, and could also hold the power index. It gives up +Principle 1 for those records: they would not be described by a `.sol` file and +would not be readable through `eth_getStorageAt`. It also depends on flatkv +exposing ordered prefix iteration to the precompiles, as part of committed state. +A middle ground is to keep primary records in slots and move only the indexes +to flatkv. A further option, for indexes that only queries use, is to leave them +to an off-chain indexer. Which of these to pursue is open. + +#### Smaller changes + +**"Does any key exist under this prefix" becomes a counter.** V2 refuses to +chain redelegations by checking whether any key exists under +`0x36 ‖ dst ‖ delegator`. The draft counts open entries in +`redelegationsByValDst` instead. + +**Time-ordered queues become first-in, first-out lists.** V2 keys its maturity +queues by completion time and walks them up to the current time. The draft +makes each queue an array read from its head, with each new entry's completion +time clamped to be no earlier than the entry before it. While `unbondingTime` +stays constant this changes nothing. If governance shortens `unbondingTime`, new +unbondings would wait behind older ones rather than overtaking them. A validator +that re-bonds before its unbonding finishes would leave a stale queue entry, +which EndBlock skips. Ordered flatkv keys would avoid the clamp. + +**Slash events become an array ordered by height**, found by binary search, +where V2 uses a key range by height. + +**No prefix delete.** When a validator is removed, V2 deletes its whole +historical-rewards prefix. The draft deletes the periods that can still be +referenced (the slash events' periods and the last period); F1's reference +counts mean no others are live. + +**One denomination.** V2's rewards are `DecCoins`, a list of amounts by denom. +Multi-denom rewards are going away, so each amount is a single `uint256` of wei. +On pacific-1 the community pool and the outstanding rewards sampled are usei +only today; the pre-migration checklist would confirm it for everything. + +**Typed keys.** Bech32 strings become EVM addresses, and the consensus public key +(a protobuf `Any` in V2) becomes a `bytes32` ed25519 key. All 88 validators on +pacific-1 use ed25519. + +**Historical info is not carried over.** V2 writes the full validator set into +`0x50` every block, and its only reader is IBC, which giga does not run. + +### A consequence for gov + +V2 tallies a proposal inside one EndBlock, so it sees state at one instant. Gov +on giga counts votes under a per-block budget, so a proposal with many voters is +counted over several blocks, and a delegation that changes mid-count could be +counted on both sides. + +One way to handle this without giving staking a history is to freeze the inputs +while gov counts: + +- staking refuses delegate, undelegate and redelegate while a tally is being + counted, with a revert naming the tally; +- gov stores the bonded validator set (at most `maxValidators` records) when + counting starts, since jailing can change the set without any delegation + write. + +That would reproduce V2's single-instant tally. The lock would last a few blocks +for a typical proposal and about two minutes for one with a million voters. Both +are small changes to gov's existing tally code. + +### Principle 2.1: precompiles are off during the migration + +V2's staking, distribution and slashing precompiles would be shut down ahead of +the migration, and the giga precompiles turned on only once it finishes. In +between, no user transaction can touch this state. + +That keeps the migration simple. If nothing writes a delegation while it runs, a +V2 record has been migrated exactly when it lies behind the migration cursor. +There is no promote-on-write path, no "already migrated" marker, and no conflict +between a user's write and the copy. + +A possible sequence: + +1. **At the cutover height, copy everything per validator in one go**: + validator records, power, the validator queue, every per-validator rewards + record, slash events, the community pool, signing info and missed blocks, + params and escrow balances. This is about a hundred validators' worth of + state. +2. **Sweep the per-delegation state over the following blocks.** Staking's + EndBlock copies V2 records in V2 key order, a budgeted number per block, and + saves its position in `migrationCursor`. Delegations first, each with its F1 + starting info, the historical rewards entry it references, and the + delegator's withdraw address; then unbonding entries, redelegation entries + and the two remaining queues. A record that cannot be copied goes into + `migrationFailures` and is skipped, so one bad record does not stall the + sweep. +3. **Finish.** When the cursor passes the last V2 key, `migrating` clears, V2 + state is no longer read, and the giga precompiles turn on. + +Sei has done something similar in V2: the `0x37` delegation-by-validator index +was backfilled with a cursor key and a ready marker. + +**How long it might take.** Roughly V2 keys × writes per key ÷ the per-block +budget. V2 holds about three or four keys per delegation, and with the draft's +sets each takes about three or four slot writes. At a million delegations and +10,000 keys per block, that is about 1,500 blocks, or ten minutes at 400 ms +blocks; at 100,000 delegations, about a minute. Fewer sets (see *Prefix walks*) +would shorten it. The real delegation count is not known yet. + +**Where V2 state is read from.** The sweep would read V2 through an interface +implemented in `evmonlyapp`, which may import sei-cosmos, so `giga/evmonly` +only sees typed records. Every node needs the frozen V2 state as of the cutover +for the whole sweep, including nodes that state-sync during it. If the existing +memiavl-to-flatkv migration has moved staking and distribution into flatkv by +then, that store may serve as the source. + +**What still runs during the migration.** Turning the precompiles off stops +user writes, but some work is driven by the chain itself: + +- Unbonding and redelegation maturity could pause, with entries that come due + paid on the first block after the migration. +- Gov could defer any tally that would start during the migration. +- Whether the validator set can change during the window (jailing for downtime, + validators finishing their unbonding) is open. The per-validator records are + migrated first, so it is possible, but freezing the set is simpler. +- Whether rewards accrue during the window depends on Principle 3. + +--- + +## Principle 3: applying rewards during execution is not designed yet + +How fees and inflation are collected and credited each block is a separate +design. This proposal does not try to answer it; it aims to keep the storage +able to carry whatever that design decides, and lists the assumptions it would +need to confirm. + +**What the storage would support.** With F1, crediting rewards only touches +per-validator records: the validator's outstanding rewards, current rewards and +commission. Distribution could expose two Go entry points for that: + +- `AllocateTokensToValidator(state, from, validator, amount)`: moves funds into + the distribution escrow and splits commission as V2 does; +- `FundCommunityPool(state, from, amount)`. + +The rewards code would call these and write no distribution slots directly. + +**What it would not support cheaply.** Anything that writes to every delegation +on a schedule. With F1, a delegation is written only when its owner acts. A +design that pushes rewards to each delegator every epoch would be on the order +of a million state writes per epoch. + +**Assumptions for the rewards design to confirm or replace:** + +- Rewards are allocated in a new BeginBlock step, before slashing and before any + transaction, using the previous block's votes. The giga executor has no + BeginBlock hook today. +- The fee pot is for the rewards design to define. Giga's coinbase and base fee + are zero today. +- Minting belongs to the rewards design. pacific-1's release schedule is empty. +- Power and the bonded set are read from staking, not copied. +- `communityTax` and the proposer reward params stay in distribution's params + (all zero on pacific-1). + +--- + +## How the pieces could fit together + +**Funds in escrow addresses.** The tokens would be the balances of derived +addresses, the pattern gov uses for deposits: + +| Escrow | V2 module account | Holds | +|---|---|---| +| staking bonded escrow | `bonded_tokens_pool` | bonded validators' tokens | +| staking not-bonded escrow | `not_bonded_tokens_pool` | unbonded validators' tokens and unbonding entries | +| distribution escrow | `distribution` | outstanding rewards and the community pool | + +Escrows and records both hold wei. Each payout would check the escrow balance +before moving funds. + +**Precompiles call each other in Go.** Staking would define a hooks interface +equivalent to V2's `StakingHooks`, and `evmonlyapp` would wire distribution and +slashing into it. Gov would read staking through an adapter, so no precompile +package imports another. + +**Block order follows V2.** BeginBlock would run rewards, then slashing. +EndBlock would run gov, then staking: the migration sweep while it is running, +then the validator set update, then the three queues. Each EndBlock step would +follow gov's fail-safe rule: each item runs in its own snapshot, a failure +reverts that item and is reported, and the block does not halt. Two guards +would sit where every path passes: the validator set update never sends a set +with zero total power, and a payout that finds its escrow short leaves the +funds where they are and reports it. + +--- + +## Checklist before the migration + +Proposed steps on pacific-1 before a cutover height is chosen. + +1. **Confirm there are no CosmWasm delegators.** The proposal keys everything by + EVM address. A CosmWasm contract has a 32-byte address with no EVM + equivalent, so its delegations would have no owner on giga. Walk every + delegator in `0x31`, `0x32` and `0x34` and flag any 32-byte address. The same + walk can flag multisig and module accounts, and any account that has never + signed a transaction (no public key in x/auth, so no derivable EVM address). + Each one found needs a decision: undelegate it before cutover, or map it some + other way. +2. **Confirm every reward balance is usei.** Multi-denom rewards are going away, + and the proposal stores a single amount. Check the community pool and every + validator's outstanding rewards and accumulated commission. If another denom + is present, one fix is to force a distribution before cutover: withdraw all + delegator rewards and validator commission so non-usei amounts are paid out + in V2, leaving only usei to migrate. +3. **Get a real delegation count, then shadow-migrate.** The count sets how long + the sweep runs and how much the set overhead matters. Count `0x31` keys on a + pacific-1 snapshot, then run the migration against snapshots, more than once, + before doing it for real. Each shadow run could report how many blocks the + sweep took, any entries in `migrationFailures`, and these invariants: + - each validator's `delegatorShares` equals the sum of its delegations' + shares; + - the bonded escrow equals the total tokens of bonded validators, and the + not-bonded escrow equals unbonded validators' tokens plus every unbonding + balance; + - the distribution escrow covers every outstanding reward plus the community + pool; + - a sample of delegators' pending rewards computed on giga matches V2, ×10¹². + +--- + +## Not yet covered + +Known gaps that need an owner or a decision. + +- **Vesting accounts.** V2 tracks delegated vesting and delegated free amounts + on vesting accounts. Giga has no vesting accounts; what happens when a + vesting delegator undelegates is undecided. +- **Bank balances and escrow funding** at cutover belong to the bank migration. +- **Dynamic validator sets in autobahn.** The giga application returns the + genesis validator set today, and validator updates have nowhere to go. +- **Validator operations through authz.** Some operators run validator + operations through authz grants, which the giga precompiles would not + support. +- **Signing state at cutover.** Whether missed-block windows, jail times and + tombstones copy as they are, or liveness windows restart, is undecided. +- **Slashing stake.** Both slash fractions are zero on pacific-1. The proposal + pins them at zero and defers slashing unbonding and redelegation entries. +- **Existing callers of the V2 precompiles.** Contracts calling the V2 + selectors would get a revert naming the method to use instead. +- **Events.** Indexers and explorers would move from Cosmos events to EVM logs. +- **Parallel execution.** The escrows, `lastTotalPower` and the validator + records make staking transactions conflict with each other. Custom + precompiles run sequentially today. +- **In-flight gov proposals** at cutover belong to gov's migration. + +## Open questions + +1. Power index: what cap on validator records, and what minimum to create + one? And is gas per place moved the right charge for a reorder? +2. Prefix walks: enumeration sets in slots, ordered flatkv keys (for indexes + only, or for records too), or off-chain indexing for query-only walks? +3. Reward and pool amounts: whole wei, or 1e18-scaled wei? +4. Is the queue behaviour after a shortened `unbondingTime` acceptable, or does + the queue answer change with question 2? +5. Do the gov changes (counting lock and stored bonded set) land in the gov PR + stack or with the staking work, and is a tally lock of a couple of minutes + acceptable for very large proposals? +6. Is the validator set frozen during the migration, or can it change? +7. Who owns the V2 read side of the sweep, and can the flatkv copy serve it? From 701b205f30c947a2db0abb2f89efb8f9ecf6c154 Mon Sep 17 00:00:00 2001 From: Tony Chen Date: Tue, 3 Nov 2026 10:23:07 +0800 Subject: [PATCH 02/44] docs(giga-storage): keep only the staking structures an on-chain path reads - Drop the consensus address: validators are keyed by operator in staking, distribution and slashing. 0x22 is keyed by the ed25519 key, for the duplicate-key check and key lookups; slashing's 0x03 relation is dropped. - Drop the enumeration sets read only by queries (0x37, unbonding and redelegations by delegator) or by entry slashing (0x33, 0x35). - Keep redelegation entries in the redelegation queue, with a per-triple count for maxEntries. - Store the bonded set as one ValidatorPower array instead of a mapping and a set. - Update the rationale doc to match, including which queue entries the FIFO clamp delays. Co-Authored-By: Claude Opus 5.5 --- docs/giga-storage/DistributionStorage.sol | 2 +- docs/giga-storage/SlashingStorage.sol | 12 +- docs/giga-storage/StakingStorage.sol | 37 +++-- docs/giga-storage/staking-design-rationale.md | 140 +++++++++++------- giga/evmonly/precompiles/gov/electorate.go | 2 +- 5 files changed, 114 insertions(+), 79 deletions(-) diff --git a/docs/giga-storage/DistributionStorage.sol b/docs/giga-storage/DistributionStorage.sol index 80a272a19a..9e2404d9a7 100644 --- a/docs/giga-storage/DistributionStorage.sol +++ b/docs/giga-storage/DistributionStorage.sol @@ -32,7 +32,7 @@ contract DistributionStorage { } uint256 internal communityPool; // 0x00: FeePool.community_pool - address internal previousProposer; // 0x01: consensus address + address internal previousProposer; // 0x01: operator mapping(address => uint256) internal validatorOutstandingRewards; // 0x02: validator => mapping(address => address) internal delegatorWithdrawAddr; // 0x03: delegator => payee; zero is the delegator mapping(address => mapping(address => DelegatorStartingInfo)) internal delegatorStartingInfo; // 0x04: validator => delegator => diff --git a/docs/giga-storage/SlashingStorage.sol b/docs/giga-storage/SlashingStorage.sol index 671c3a0394..7450ac9890 100644 --- a/docs/giga-storage/SlashingStorage.sol +++ b/docs/giga-storage/SlashingStorage.sol @@ -6,8 +6,9 @@ import "./Sets.sol"; /// @notice Storage schema of the evmonly slashing precompile (0x1014), held as that /// address's contract storage. Each state variable is an x/slashing store prefix, /// named in its comment. -/// @dev Params are `ParamsStorage.slashing`. Keys are consensus addresses, -/// sha256(consensusPubkey)[:20]. Times are Unix nanoseconds. +/// @dev Params are `ParamsStorage.slashing`. Keys are validator operators. A +/// validator's ed25519 key is `StakingStorage.validators[operator].consensusPubkey`. +/// Times are Unix nanoseconds. contract SlashingStorage { struct ValidatorSigningInfo { uint64 startHeight; @@ -22,8 +23,7 @@ contract SlashingStorage { uint64[] missedBlocks; // bit i of the window is bit i%64 of word i/64 } - mapping(address => ValidatorSigningInfo) internal validatorSigningInfo; // 0x01: consensus address => - AddressSet internal signingInfoSet; // every consensus address in validatorSigningInfo - mapping(address => ValidatorMissedBlockArray) internal validatorMissedBlocks; // 0x02: consensus address => - mapping(address => bytes32) internal addrPubkeyRelation; // 0x03: consensus address => ed25519 key + mapping(address => ValidatorSigningInfo) internal validatorSigningInfo; // 0x01: operator => + AddressSet internal signingInfoSet; // every operator in validatorSigningInfo + mapping(address => ValidatorMissedBlockArray) internal validatorMissedBlocks; // 0x02: operator => } diff --git a/docs/giga-storage/StakingStorage.sol b/docs/giga-storage/StakingStorage.sol index c08dd14947..ce6b1a04d7 100644 --- a/docs/giga-storage/StakingStorage.sol +++ b/docs/giga-storage/StakingStorage.sol @@ -9,8 +9,9 @@ import "./Sets.sol"; /// @dev Params are `ParamsStorage.staking`. Bonded tokens sit in the balance of /// `BondedEscrow` and unbonded and unbonding tokens in `NotBondedEscrow`, derived /// addresses in `staking/layout.go`. Tokens and balances are wei; shares and -/// rates are 1e18-scaled; times are Unix nanoseconds. Accounts and operators are EVM -/// addresses; a consensus address is sha256(consensusPubkey)[:20]. +/// rates are 1e18-scaled; times are Unix nanoseconds. Accounts are EVM addresses, +/// and a validator is keyed by its operator's. An enumeration is kept only where an +/// on-chain path walks it. contract StakingStorage { struct Description { string moniker; @@ -45,6 +46,12 @@ contract StakingStorage { uint256[8] __gap; } + /// @dev A bonded validator and the consensus power last sent for it. + struct ValidatorPower { + address operator; + uint64 power; + } + struct Delegation { uint256 shares; } @@ -56,13 +63,6 @@ contract StakingStorage { uint256 balance; } - struct RedelegationEntry { - uint64 creationHeight; - uint64 completionTime; - uint256 initialBalance; - uint256 sharesDst; - } - /// @dev A queue entry's completionTime is never earlier than the one before it. struct UnbondingQueueEntry { uint64 completionTime; @@ -70,11 +70,16 @@ contract StakingStorage { address validator; } + /// @dev A redelegation entry's only record: V2's queue triplet and its + /// RedelegationEntry together. struct RedelegationQueueEntry { uint64 completionTime; address delegator; + uint64 creationHeight; address srcValidator; address dstValidator; + uint256 initialBalance; + uint256 sharesDst; } struct ValidatorQueueEntry { @@ -89,29 +94,21 @@ contract StakingStorage { uint64 tail; } - mapping(address => uint64) internal lastValidatorPower; // 0x11: operator => power - AddressSet internal lastValidatorPowerSet; // operators with a lastValidatorPower + ValidatorPower[] internal lastValidators; // 0x11: the bonded set, as last sent to consensus uint256 internal lastTotalPower; // 0x12 mapping(address => Validator) internal validators; // 0x21: operator => AddressSet internal validatorSet; // every operator in validators - mapping(address => address) internal validatorsByConsAddr; // 0x22: consensus address => operator + mapping(bytes32 => address) internal validatorsByConsensusPubkey; // 0x22, keyed by the key itself: consensusPubkey => operator address[] internal validatorsByPower; // 0x23: unjailed operators, descending by power, ties to the lower address mapping(address => mapping(address => Delegation)) internal delegations; // 0x31: delegator => validator => - mapping(address => AddressSet) internal delegationsByValidator; // 0x37: validator => delegators mapping(address => AddressSet) internal delegationsByDelegator; // delegator => validators mapping(address => mapping(address => UnbondingDelegationEntry[])) internal unbondingDelegations; // 0x32: delegator => validator => entries, at most maxEntries - mapping(address => AddressSet) internal unbondingDelegationsByValidator; // 0x33: validator => delegators - mapping(address => AddressSet) internal unbondingDelegationsByDelegator; // delegator => validators - mapping(address => mapping(address => mapping(address => RedelegationEntry[]))) internal redelegations; // 0x34: delegator => src => dst => entries, at most maxEntries - mapping(address => mapping(address => AddressSet)) internal redelegationsByValSrc; // 0x35: src => delegator => dsts - mapping(address => AddressSet) internal redelegationDelegatorsByValSrc; // src => delegators + mapping(address => mapping(address => mapping(address => uint256))) internal redelegationEntryCounts; // 0x34: delegator => src => dst => open entries, at most maxEntries mapping(address => mapping(address => uint256)) internal redelegationsByValDst; // 0x36: dst => delegator => open entries into dst - mapping(address => mapping(address => AddressSet)) internal redelegationsByDelegator; // delegator => src => dsts - mapping(address => AddressSet) internal redelegationSrcsByDelegator; // delegator => srcs QueueBounds internal unbondingQueueBounds; mapping(uint64 => UnbondingQueueEntry) internal unbondingQueue; // 0x41: index => diff --git a/docs/giga-storage/staking-design-rationale.md b/docs/giga-storage/staking-design-rationale.md index 54acc305e0..79554e66e1 100644 --- a/docs/giga-storage/staking-design-rationale.md +++ b/docs/giga-storage/staking-design-rationale.md @@ -51,9 +51,9 @@ Solidity's rules, briefly: For example, a delegation's shares would live at `delegations[delegator][validator].shares`. In the draft, `delegations` sits at -slot 9 of `StakingStorage` (the two sets before it take two slots each), so the -shares are at `keccak256(validator . keccak256(delegator . 9))`, with each key -padded to 32 bytes. +slot 7 of `StakingStorage` (the set before it takes two slots), so the shares +are at `keccak256(validator . keccak256(delegator . 7))`, with each key padded +to 32 bytes. `Validator` shows the struct rules on a larger record. In the draft it takes 23 slots: @@ -108,9 +108,10 @@ constant number of writes. `solstorage.Set` already reads this layout. **Some things IAVL can do, slots cannot.** V2 stores state in an ordered key value store. It can walk keys in sorted order, walk every key under a prefix, delete every key under a prefix, and ask whether any key under a prefix exists. -Contract storage is a hash map with none of those operations. Each place this -proposal departs from V2's structures comes from that gap. The largest, the -prefix walks, may argue for relaxing Principle 1 in places; see below. +Contract storage is a hash map with none of those operations. Most places this +proposal departs from V2's structures come from that gap. The largest, the +prefix walks, is answered by keeping only the walks an on-chain path needs; see +below. --- @@ -127,8 +128,10 @@ giga record for record. The proposal copies **structure**, not data types: -- **Each V2 store prefix becomes one state variable**, named after the V2 - record and commented with the prefix it came from. +- **Each V2 store prefix that an on-chain path reads becomes one state + variable**, named after the V2 record and commented with the prefix it came + from. Indexes that only queries or entry slashing read are left out; see + *Prefix walks*. - **Each record keeps V2's fields, field order and names.** - **Data types are Ethereum-native.** Amounts are wei, not usei. Shares, rates and reward ratios are 1e18-scaled fixed point, which is also V2's `sdk.Dec` @@ -161,15 +164,15 @@ Staking: | V2 prefix | V2 record | Proposed giga state variable | |---|---|---| -| `0x11` | last validator power | `lastValidatorPower` (+ set) | +| `0x11` | last validator power | `lastValidators` (array, one slot per bonded validator) | | `0x12` | last total power | `lastTotalPower` | | `0x21` | validators | `validators` (+ set) | -| `0x22` | validator by consensus address | `validatorsByConsAddr` | +| `0x22` | validator by consensus address | `validatorsByConsensusPubkey`, keyed by the key itself | | `0x23` | validators by power | `validatorsByPower` (sorted array) | | `0x31` | delegations | `delegations` (+ set per delegator) | -| `0x37` | delegations by validator | `delegationsByValidator` | -| `0x32`, `0x33` | unbonding delegations and their index | `unbondingDelegations` (+ sets) | -| `0x34`–`0x36` | redelegations and their indexes | `redelegations` (+ sets, a count) | +| `0x37` | delegations by validator | not carried over (queries only) | +| `0x32`, `0x33` | unbonding delegations and their index | `unbondingDelegations`; the index is not carried over | +| `0x34`–`0x36` | redelegations and their indexes | `redelegationEntryCounts` and `redelegationsByValDst`; entries live in the redelegation queue, and `0x35` is not carried over | | `0x41`–`0x43` | unbonding, redelegation, validator queues | three queues | | `0x50` | historical info | not carried over (see below) | @@ -177,9 +180,11 @@ Distribution: prefixes `0x00`–`0x08` map one to one onto the nine state variables in `DistributionStorage.sol`, from `communityPool` to `validatorSlashEvents`. -Slashing: signing info (`0x01`), Sei's packed missed-block array (`0x02`) and -the address-to-pubkey relation (`0x03`) map one to one. The missed-block -`uint64[]` packs four words per slot, so the bits are V2's bits. +Slashing: signing info (`0x01`) and Sei's packed missed-block array (`0x02`) +map one to one, keyed by operator rather than consensus address. The missed-block +`uint64[]` packs four words per slot, so the bits are V2's bits. The +address-to-pubkey relation (`0x03`) is not carried over, since the key is on the +staking `Validator`. ### The power index @@ -256,27 +261,35 @@ forces a change from V2. The first is the hardest. Anywhere V2 walks every key under a prefix ("all delegations of this delegator", "all delegators of this validator", "all validators"), slot storage needs an -explicit enumeration set. The draft layouts do this: V2's own index prefixes -(`0x33`, `0x35`, `0x37`) become sets of the same shape, and new sets cover walks -V2 did over the primary key (`validatorSet`, `delegationsByDelegator` and so -on). - -This may not hold up. Each set adds two or three slot writes whenever a member -joins or leaves, and the sets roughly double the writes for every delegation -created or removed. Across a million delegations the sets themselves are a large -share of the state, and of what the migration has to write. Removing a validator -or a delegator with many entries means walking and clearing large sets. - -The alternative is to store the indexes, and possibly the primary records, as -ordered flatkv keys and use flatkv's prefix reads, which is what V2 does on IAVL. -That would give back ordered and prefix iteration, prefix delete and existence -checks, and could also hold the power index. It gives up -Principle 1 for those records: they would not be described by a `.sol` file and -would not be readable through `eth_getStorageAt`. It also depends on flatkv -exposing ordered prefix iteration to the precompiles, as part of committed state. -A middle ground is to keep primary records in slots and move only the indexes -to flatkv. A further option, for indexes that only queries use, is to leave them -to an off-chain indexer. Which of these to pursue is open. +explicit enumeration set, and each set adds two or three slot writes whenever a +member joins or leaves. The draft keeps two: + +- `delegationsByDelegator`, which gov's tally walks for each voter. +- `validatorSet`, every validator record. Nothing on chain walks it while + `validatorsByPower` holds the unjailed validators, so whether it stays is + open. + +V2's other walks have no on-chain reader in giga: + +| V2 walk | Read by | +|---|---| +| `0x37`, delegations by validator | queries | +| `0x33`, unbonding delegations by validator | slashing unbonding entries | +| `0x35`, redelegations by source validator | slashing redelegation entries | +| unbonding delegations and redelegations by delegator | queries | + +Queries would be served by an off-chain indexer reading the precompile's logs. +Slashing unbonding and redelegation entries is deferred (see *Not yet covered*). +Both kinds of entry keep their creation height and amounts, so turning it on +needs only a way to find a validator's entries: these walks back, or a check +made as each entry matures. + +Ordered flatkv keys, V2's approach on IAVL, are the alternative for the walks +that remain and for the power index. They would give back ordered and prefix +iteration, prefix delete and existence checks, but give up Principle 1 for +those records: they would not be described by a `.sol` file or readable through +`eth_getStorageAt`. They also depend on flatkv exposing ordered prefix +iteration to the precompiles, as part of committed state. #### Smaller changes @@ -285,14 +298,30 @@ chain redelegations by checking whether any key exists under `0x36 ‖ dst ‖ delegator`. The draft counts open entries in `redelegationsByValDst` instead. +**Redelegation entries live in the queue.** On chain, V2 reads a redelegation +entry's fields only to slash it. Completing one moves no funds, since the stake +moved when the redelegation began. The draft keeps each entry's fields in its +`redelegationQueue` entry, and counts open entries per delegator, source and +destination in `redelegationEntryCounts` for `maxEntries`. A matured entry pops +off the queue and decrements that count and `redelegationsByValDst`. + **Time-ordered queues become first-in, first-out lists.** V2 keys its maturity queues by completion time and walks them up to the current time. The draft makes each queue an array read from its head, with each new entry's completion -time clamped to be no earlier than the entry before it. While `unbondingTime` -stays constant this changes nothing. If governance shortens `unbondingTime`, new -unbondings would wait behind older ones rather than overtaking them. A validator -that re-bonds before its unbonding finishes would leave a stale queue entry, -which EndBlock skips. Ordered flatkv keys would avoid the clamp. +time clamped to be no earlier than the entry before it. Two kinds of entry are +clamped: + +- A redelegation from an unbonding validator. V2 completes it when that + validator finishes unbonding. The clamp moves it to the completion time of the + entry queued before it, up to one unbonding period from now. The stake moves + at once either way, so the entry only holds the delegator to the chaining rule + and `maxEntries` for longer, by at most the time since the source began + unbonding. +- Every new entry after governance shortens `unbondingTime`, which waits behind + older ones rather than overtaking them. + +A validator that re-bonds before its unbonding finishes would leave a stale +queue entry, which EndBlock skips. Ordered flatkv keys would avoid the clamp. **Slash events become an array ordered by height**, found by binary search, where V2 uses a key range by height. @@ -311,6 +340,14 @@ only today; the pre-migration checklist would confirm it for everything. (a protobuf `Any` in V2) becomes a `bytes32` ed25519 key. All 88 validators on pacific-1 use ed25519. +**No consensus address.** Staking, distribution and slashing key a validator by +its operator. The one lookup by key, `validatorsByConsensusPubkey`, rejects a +key another validator already uses, as V2's `0x22` does, and resolves a key that +consensus names; autobahn names committee members by key. Keying validators by +an address derived from the key would make the duplicate check free, but nobody +could sign for that address, so a validator would still need a separate +operator, and could never change its key. + **Historical info is not carried over.** V2 writes the full validator set into `0x50` every block, and its only reader is IBC, which giga does not run. @@ -367,11 +404,11 @@ Sei has done something similar in V2: the `0x37` delegation-by-validator index was backfilled with a cursor key and a ready marker. **How long it might take.** Roughly V2 keys × writes per key ÷ the per-block -budget. V2 holds about three or four keys per delegation, and with the draft's -sets each takes about three or four slot writes. At a million delegations and -10,000 keys per block, that is about 1,500 blocks, or ten minutes at 400 ms -blocks; at 100,000 delegations, about a minute. Fewer sets (see *Prefix walks*) -would shorten it. The real delegation count is not known yet. +budget. V2 holds about three or four keys per delegation, and each takes at +most three or four slot writes; the index keys giga does not carry over +(`0x33`, `0x35`, `0x37`) take none. At a million delegations and 10,000 keys per +block, that is about 1,500 blocks, or ten minutes at 400 ms blocks; at 100,000 +delegations, about a minute. The real delegation count is not known yet. **Where V2 state is read from.** The sweep would read V2 through an interface implemented in `evmonlyapp`, which may import sei-cosmos, so `giga/evmonly` @@ -522,11 +559,12 @@ Known gaps that need an owner or a decision. 1. Power index: what cap on validator records, and what minimum to create one? And is gas per place moved the right charge for a reorder? -2. Prefix walks: enumeration sets in slots, ordered flatkv keys (for indexes - only, or for records too), or off-chain indexing for query-only walks? +2. Prefix walks: does `validatorSet` stay? And do the remaining set and the + power index stay in slots, or move to ordered flatkv keys? 3. Reward and pool amounts: whole wei, or 1e18-scaled wei? -4. Is the queue behaviour after a shortened `unbondingTime` acceptable, or does - the queue answer change with question 2? +4. Is the clamped queue behaviour acceptable: a redelegation from an unbonding + validator held to the chaining rule for longer, and new entries waiting + behind older ones after a shortened `unbondingTime`? 5. Do the gov changes (counting lock and stored bonded set) land in the gov PR stack or with the staking work, and is a tally lock of a couple of minutes acceptable for very large proposals? diff --git a/giga/evmonly/precompiles/gov/electorate.go b/giga/evmonly/precompiles/gov/electorate.go index 81c75b3c7f..0fe3307a45 100644 --- a/giga/evmonly/precompiles/gov/electorate.go +++ b/giga/evmonly/precompiles/gov/electorate.go @@ -29,7 +29,7 @@ type Delegation struct { // gives it to x/gov. Tallies are in the unit of its tokens. // // TODO(giga staking): add an Electorate reading StakingStorage at 0x1005, from -// bondedValidatorSet, validators[operator].tokens and .delegatorShares, +// lastValidators, validators[operator].tokens and .delegatorShares, // delegationsByDelegator[voter] and delegations[voter][validator].shares, with // TotalBonded the bonded escrow's balance. It replaces GenesisElectorate. type Electorate interface { From dcce426f339975f020269050c15de1c9ee0591aa Mon Sep 17 00:00:00 2001 From: Tony Chen Date: Thu, 5 Nov 2026 13:08:04 +0800 Subject: [PATCH 03/44] docs(giga-storage): say where each kind of struct can grow A mapping value grows at its end and needs no reserved slots. A struct inside another, a top-level struct with variables after it, and an array element cannot grow at their end; say what each can do instead, and add an open question on validatorSlashEvents, the one array of structs kept for good. Co-Authored-By: Claude Opus 5.5 --- docs/giga-storage/staking-design-rationale.md | 35 ++++++++++++++++--- 1 file changed, 30 insertions(+), 5 deletions(-) diff --git a/docs/giga-storage/staking-design-rationale.md b/docs/giga-storage/staking-design-rationale.md index 79554e66e1..c12c451967 100644 --- a/docs/giga-storage/staking-design-rationale.md +++ b/docs/giga-storage/staking-design-rationale.md @@ -83,11 +83,33 @@ slots: ### Consequences -**Layouts only grow.** Once a public network runs a layout, a state variable or -field cannot move. New fields would take slots from a struct's `__gap`, and new -state variables would go after the last one. The draft `Validator` reserves -eight slots for this, and `layout_test.go` pins would catch an accidental -reorder. +**Layouts only grow.** Once a public network runs a layout, no state variable +or field can move, change type or go away. A retired field keeps its slot, and +the slot is not reused for anything else, since records written before still +hold the old values. New state variables go after the last one. A new field +reads as zero in every record written before it, so zero has to mean what the +code did before, or the upgrade that adds the field writes it. Where a new field +can go depends on where its struct is stored: + +- **A mapping value** (`Validator`, `Delegation`, the queue entries, + `DelegatorStartingInfo`, `ValidatorSigningInfo`) grows at its end. Each value + starts at its own hashed slot, so the slots after it are free, and no + reserved slots are needed: `Validator`'s `__gap` is optional. +- **A struct inside another** (`Description` and `Commission` in `Validator`) + cannot grow without moving the fields after it. A new field goes at the end + of the outer struct instead. +- **A top-level struct with state variables after it** grows only into room it + already has: `ParamsStorage`'s subspaces into their `__gap`, a `QueueBounds` + into the 16 free bytes of its slot. +- **An array element** cannot grow, since a larger element moves every element + after the first. `lastValidators` holds at most 100, so the upgrade can + rewrite it. Unbonding entries complete within the unbonding time, so a new + layout can start in a new state variable while the old one drains. + `validatorSlashEvents` is kept for good, so its element has to be settled + before launch (see *Open questions*). + +`layout_test.go` pins every slot and offset, so a change that moves one fails +it. **No library dependencies.** The draft layouts import nothing from outside this directory, including OpenZeppelin. The precompiles need enumerable sets, and @@ -570,3 +592,6 @@ Known gaps that need an owner or a decision. acceptable for very large proposals? 6. Is the validator set frozen during the migration, or can it change? 7. Who owns the V2 read side of the sweep, and can the flatkv copy serve it? +8. `validatorSlashEvents` is the one array of structs kept for good, so its + element can never grow. Should it be a mapping by index with a count, whose + values can? From 269733b03d2a3ef27adfd0556d4214435f11ab6e Mon Sep 17 00:00:00 2001 From: Tony Chen Date: Thu, 5 Nov 2026 13:10:19 +0800 Subject: [PATCH 04/44] docs(giga-storage): drop Validator's reserved slots Validator is a mapping value, so it grows at its end and needs no __gap. Co-Authored-By: Claude Opus 5.5 --- docs/giga-storage/StakingStorage.sol | 1 - docs/giga-storage/staking-design-rationale.md | 5 ++--- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/docs/giga-storage/StakingStorage.sol b/docs/giga-storage/StakingStorage.sol index ce6b1a04d7..c727f99c80 100644 --- a/docs/giga-storage/StakingStorage.sol +++ b/docs/giga-storage/StakingStorage.sol @@ -43,7 +43,6 @@ contract StakingStorage { uint64 unbondingTime; Commission commission; uint256 minSelfDelegation; - uint256[8] __gap; } /// @dev A bonded validator and the consensus power last sent for it. diff --git a/docs/giga-storage/staking-design-rationale.md b/docs/giga-storage/staking-design-rationale.md index c12c451967..38e720ce01 100644 --- a/docs/giga-storage/staking-design-rationale.md +++ b/docs/giga-storage/staking-design-rationale.md @@ -55,7 +55,7 @@ slot 7 of `StakingStorage` (the set before it takes two slots), so the shares are at `keccak256(validator . keccak256(delegator . 7))`, with each key padded to 32 bytes. -`Validator` shows the struct rules on a larger record. In the draft it takes 23 +`Validator` shows the struct rules on a larger record. In the draft it takes 15 slots: | Slot offset | Fields | @@ -68,7 +68,6 @@ slots: | 9 | `unbondingHeight`, `unbondingTime` (packed) | | 10–13 | `commission` (three rates, then `updateTime`) | | 14 | `minSelfDelegation` | -| 15–22 | `__gap` (reserved) | ### Why @@ -94,7 +93,7 @@ can go depends on where its struct is stored: - **A mapping value** (`Validator`, `Delegation`, the queue entries, `DelegatorStartingInfo`, `ValidatorSigningInfo`) grows at its end. Each value starts at its own hashed slot, so the slots after it are free, and no - reserved slots are needed: `Validator`'s `__gap` is optional. + reserved slots are needed. - **A struct inside another** (`Description` and `Commission` in `Validator`) cannot grow without moving the fields after it. A new field goes at the end of the outer struct instead. From ea164b719f62a88907be960a2bc7952cda507dde Mon Sep 17 00:00:00 2001 From: Tony Chen Date: Thu, 5 Nov 2026 13:10:59 +0800 Subject: [PATCH 05/44] docs(giga-storage): let an array element grow into a gap of its own Co-Authored-By: Claude Opus 5.5 --- docs/giga-storage/staking-design-rationale.md | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/docs/giga-storage/staking-design-rationale.md b/docs/giga-storage/staking-design-rationale.md index 38e720ce01..8bba269a33 100644 --- a/docs/giga-storage/staking-design-rationale.md +++ b/docs/giga-storage/staking-design-rationale.md @@ -100,10 +100,13 @@ can go depends on where its struct is stored: - **A top-level struct with state variables after it** grows only into room it already has: `ParamsStorage`'s subspaces into their `__gap`, a `QueueBounds` into the 16 free bytes of its slot. -- **An array element** cannot grow, since a larger element moves every element - after the first. `lastValidators` holds at most 100, so the upgrade can - rewrite it. Unbonding entries complete within the unbonding time, so a new - layout can start in a new state variable while the old one drains. +- **An array element** grows only into a `__gap` of its own, since a larger + element moves every element after the first. A gap costs nothing to store, as + a zero slot is not stored, provided adding, moving and clearing elements + write only the fields in use: Solidity's `delete` and `pop` zero every slot. + Without a gap, `lastValidators` holds at most 100, so the upgrade can rewrite + it, and unbonding entries complete within the unbonding time, so a new layout + can start in a new state variable while the old one drains. `validatorSlashEvents` is kept for good, so its element has to be settled before launch (see *Open questions*). @@ -591,6 +594,6 @@ Known gaps that need an owner or a decision. acceptable for very large proposals? 6. Is the validator set frozen during the migration, or can it change? 7. Who owns the V2 read side of the sweep, and can the flatkv copy serve it? -8. `validatorSlashEvents` is the one array of structs kept for good, so its - element can never grow. Should it be a mapping by index with a count, whose - values can? +8. `validatorSlashEvents` is the one array of structs kept for good. Should its + element get a `__gap`, or should it be a mapping by index with a count, + whose values grow at their end? From 2c812ee0b47c1c55770cf980b89f2b0459193b8c Mon Sep 17 00:00:00 2001 From: Tony Chen Date: Thu, 5 Nov 2026 19:51:30 +0800 Subject: [PATCH 06/44] docs(giga-storage): cover deletes, top-level values, scalar mapping values and sets in the growth rule Co-Authored-By: Claude Opus 5.5 --- docs/giga-storage/staking-design-rationale.md | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/docs/giga-storage/staking-design-rationale.md b/docs/giga-storage/staking-design-rationale.md index 8bba269a33..2d4dd15821 100644 --- a/docs/giga-storage/staking-design-rationale.md +++ b/docs/giga-storage/staking-design-rationale.md @@ -87,13 +87,21 @@ or field can move, change type or go away. A retired field keeps its slot, and the slot is not reused for anything else, since records written before still hold the old values. New state variables go after the last one. A new field reads as zero in every record written before it, so zero has to mean what the -code did before, or the upgrade that adds the field writes it. Where a new field -can go depends on where its struct is stored: - +code did before, or the upgrade that adds the field writes it. A delete has to +clear every slot the record has used, fields added since included, or a record +later created under the same key reads the old values. What can change depends +on where the state is stored: + +- **A top-level value** (`lastTotalPower`, `communityPool`, `previousProposer`) + cannot change type. A new state variable replaces it, and the upgrade copies + the value over. - **A mapping value** (`Validator`, `Delegation`, the queue entries, `DelegatorStartingInfo`, `ValidatorSigningInfo`) grows at its end. Each value starts at its own hashed slot, so the slots after it are free, and no reserved slots are needed. +- **A mapping value that is not a struct** (`validatorOutstandingRewards`, + `delegatorWithdrawAddr`, `redelegationEntryCounts`) can become a struct whose + first field is the old value, which stays in the same slot. - **A struct inside another** (`Description` and `Commission` in `Validator`) cannot grow without moving the fields after it. A new field goes at the end of the outer struct instead. @@ -109,6 +117,11 @@ can go depends on where its struct is stored: can start in a new state variable while the old one drains. `validatorSlashEvents` is kept for good, so its element has to be settled before launch (see *Open questions*). +- **An enumeration set** keeps its shape, and dropping one only stops its + writes. Adding one after launch means filling it with the existing members, + and a mapping's keys cannot be listed from its slots, so a set can be added + only where its members can be found another way. The sets a later upgrade may + need are decided before launch (see *Prefix walks*). `layout_test.go` pins every slot and offset, so a change that moves one fails it. From 6994facdf73169109b6896aebd10320a3f3def2a Mon Sep 17 00:00:00 2001 From: Tony Chen Date: Thu, 5 Nov 2026 19:51:30 +0800 Subject: [PATCH 07/44] docs(giga-storage): give ValidatorSlashEvent a __gap Co-Authored-By: Claude Opus 5.5 --- docs/giga-storage/DistributionStorage.sol | 1 + docs/giga-storage/staking-design-rationale.md | 13 +++++-------- 2 files changed, 6 insertions(+), 8 deletions(-) diff --git a/docs/giga-storage/DistributionStorage.sol b/docs/giga-storage/DistributionStorage.sol index 9e2404d9a7..23fdad6aca 100644 --- a/docs/giga-storage/DistributionStorage.sol +++ b/docs/giga-storage/DistributionStorage.sol @@ -29,6 +29,7 @@ contract DistributionStorage { uint64 height; uint64 validatorPeriod; uint256 fraction; + uint256[8] __gap; } uint256 internal communityPool; // 0x00: FeePool.community_pool diff --git a/docs/giga-storage/staking-design-rationale.md b/docs/giga-storage/staking-design-rationale.md index 2d4dd15821..11234f148b 100644 --- a/docs/giga-storage/staking-design-rationale.md +++ b/docs/giga-storage/staking-design-rationale.md @@ -112,11 +112,11 @@ on where the state is stored: element moves every element after the first. A gap costs nothing to store, as a zero slot is not stored, provided adding, moving and clearing elements write only the fields in use: Solidity's `delete` and `pop` zero every slot. - Without a gap, `lastValidators` holds at most 100, so the upgrade can rewrite - it, and unbonding entries complete within the unbonding time, so a new layout - can start in a new state variable while the old one drains. - `validatorSlashEvents` is kept for good, so its element has to be settled - before launch (see *Open questions*). + `ValidatorSlashEvent` has one, since `validatorSlashEvents` is kept for good. + The other arrays have none: `lastValidators` holds at most 100, so the + upgrade can rewrite it, and unbonding entries complete within the unbonding + time, so a new layout can start in a new state variable while the old one + drains. - **An enumeration set** keeps its shape, and dropping one only stops its writes. Adding one after launch means filling it with the existing members, and a mapping's keys cannot be listed from its slots, so a set can be added @@ -607,6 +607,3 @@ Known gaps that need an owner or a decision. acceptable for very large proposals? 6. Is the validator set frozen during the migration, or can it change? 7. Who owns the V2 read side of the sweep, and can the flatkv copy serve it? -8. `validatorSlashEvents` is the one array of structs kept for good. Should its - element get a `__gap`, or should it be a mapping by index with a count, - whose values grow at their end? From 717798f2bea22001a6b36f875c3524df69795d49 Mon Sep 17 00:00:00 2001 From: Tony Chen Date: Mon, 9 Nov 2026 12:00:17 +0800 Subject: [PATCH 08/44] docs(giga-storage): drop signingInfoSet Only queries walk signing infos, so the slashing layout keeps no enumeration of them, as the rule for enumerations says. Co-Authored-By: Claude Opus 5.5 --- docs/giga-storage/SlashingStorage.sol | 3 --- docs/giga-storage/staking-design-rationale.md | 1 + 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/docs/giga-storage/SlashingStorage.sol b/docs/giga-storage/SlashingStorage.sol index 7450ac9890..438f640efa 100644 --- a/docs/giga-storage/SlashingStorage.sol +++ b/docs/giga-storage/SlashingStorage.sol @@ -1,8 +1,6 @@ // SPDX-License-Identifier: MIT pragma solidity 0.8.30; -import "./Sets.sol"; - /// @notice Storage schema of the evmonly slashing precompile (0x1014), held as that /// address's contract storage. Each state variable is an x/slashing store prefix, /// named in its comment. @@ -24,6 +22,5 @@ contract SlashingStorage { } mapping(address => ValidatorSigningInfo) internal validatorSigningInfo; // 0x01: operator => - AddressSet internal signingInfoSet; // every operator in validatorSigningInfo mapping(address => ValidatorMissedBlockArray) internal validatorMissedBlocks; // 0x02: operator => } diff --git a/docs/giga-storage/staking-design-rationale.md b/docs/giga-storage/staking-design-rationale.md index 11234f148b..6a1b5aa0aa 100644 --- a/docs/giga-storage/staking-design-rationale.md +++ b/docs/giga-storage/staking-design-rationale.md @@ -314,6 +314,7 @@ V2's other walks have no on-chain reader in giga: | `0x33`, unbonding delegations by validator | slashing unbonding entries | | `0x35`, redelegations by source validator | slashing redelegation entries | | unbonding delegations and redelegations by delegator | queries | +| slashing `0x01`, signing infos | queries; liveness reads each voter's by key | Queries would be served by an off-chain indexer reading the precompile's logs. Slashing unbonding and redelegation entries is deferred (see *Not yet covered*). From 81c182a9765c6490282afe0d52750f43f2926039 Mon Sep 17 00:00:00 2001 From: Tony Chen Date: Tue, 3 Nov 2026 17:23:28 +0800 Subject: [PATCH 09/44] feat(params): add the staking subspace - Add a Staking struct to ParamsStorage at slot 16: unbondingTime, maxValidators, maxEntries, maxVotingPowerRatio and maxVotingPowerEnforcementThreshold. - ReadStaking, HasStaking and WriteStaking, which writes them once at genesis; later changes go through gov. - Bound them so a change cannot wedge staking: unbonding time within the period bounds, 1..100 bonded validators (an autobahn committee's limit), at least one entry, and a ratio in (0, 1]. - Regenerate the harness and layout testdata, and keep the gov param-change test to gov's own keys. Co-Authored-By: Claude Opus 5.5 --- docs/giga-storage/ParamsStorage.sol | 13 ++ docs/giga-storage/params-design.md | 25 +++- .../precompiles/gov/paramchange_test.go | 4 +- giga/evmonly/precompiles/params/layout.go | 12 +- .../evmonly/precompiles/params/layout_test.go | 49 +++++-- .../evmonly/precompiles/params/params_test.go | 67 +++++++++ giga/evmonly/precompiles/params/staking.go | 120 ++++++++++++++++ giga/evmonly/precompiles/params/table.go | 4 +- .../testdata/ParamsStorageHarness.bin-runtime | 2 +- .../params/testdata/ParamsStorageHarness.sol | 8 ++ .../testdata/params_storage_layout.json | 128 ++++++++++++++---- 11 files changed, 380 insertions(+), 52 deletions(-) create mode 100644 giga/evmonly/precompiles/params/staking.go diff --git a/docs/giga-storage/ParamsStorage.sol b/docs/giga-storage/ParamsStorage.sol index df39f78580..4a7dfe2d6f 100644 --- a/docs/giga-storage/ParamsStorage.sol +++ b/docs/giga-storage/ParamsStorage.sol @@ -8,6 +8,8 @@ pragma solidity 0.8.30; /// - Dec: uint256, fixed point with 18 decimal places (1e18 is 1). /// - Duration: uint64 nanoseconds. /// - Coins: uint256 wei, a whole number of usei; only the usei denom exists. +/// - Int: uint256. +/// - uint32: uint32. /// Other V2 types have no stored form until a param needs one. /// /// Once a public network runs this, the layout only grows: a new param takes @@ -29,5 +31,16 @@ contract ParamsStorage { uint256[8] __gap; } + /// @dev x/staking's params. The enforcement threshold is consensus power. + struct Staking { + uint64 unbondingTime; // UnbondingTime + uint32 maxValidators; // MaxValidators + uint32 maxEntries; // MaxEntries + uint256 maxVotingPowerRatio; // MaxVotingPower + uint256 maxVotingPowerEnforcementThreshold; // MaxVotingPowerEnforcementThreshold + uint256[8] __gap; + } + Gov internal gov; // subspace "gov" + Staking internal staking; // subspace "staking" } diff --git a/docs/giga-storage/params-design.md b/docs/giga-storage/params-design.md index f3b732b541..2dfee1ab4b 100644 --- a/docs/giga-storage/params-design.md +++ b/docs/giga-storage/params-design.md @@ -28,6 +28,8 @@ subspace. | Dec | `uint256`, fixed point with 18 decimal places | | Duration | `uint64` nanoseconds; every period, read or written, is nanoseconds | | Coins | `uint256` wei, a whole number of usei; only the usei denom exists | + | Int | `uint256` | + | uint32 | `uint32` | Another V2 type gets a stored form when a param first needs one. A value of any unsigned width is stored in the bytes of its slot that solc gives its @@ -35,11 +37,12 @@ subspace. signed type needs a decoder before a param can use it. - Owners read their params from 0x1013's storage with the `params` package's - Go readers (`ReadGov`). Gov reads `gov`. Nothing keeps a second copy. + Go readers (`ReadGov`, `ReadStaking`). Gov reads `gov` and staking reads + `staking`. Nothing keeps a second copy. Planned readers for other subspaces are in *Later subspaces*. -- Params are written only at genesis (`WriteGov`, which refuses once gov's - params exist) and by a passed gov proposal (`Apply`). Both check the whole - subspace first. +- Params are written only at genesis (`WriteGov` and `WriteStaking`, which + refuse once their subspace's params exist) and by a passed gov proposal + (`Apply`). Both check the whole subspace first. ## Declaration table @@ -165,6 +168,19 @@ naming `param`. - Autobahn registers the params precompile next to gov when `evm_governance` is set. Like gov, it refuses calls until the first block writes gov's params. +## Staking + +- `staking` holds x/staking's `UnbondingTime`, `MaxValidators`, `MaxEntries`, + `MaxVotingPower` (the max voting power ratio) and + `MaxVotingPowerEnforcementThreshold`, in consensus power. `BondDenom` has no + param, since only usei exists; `HistoricalEntries` has none, since giga keeps + no historical info; `MinCommissionRate` comes with validator creation. +- Its check is x/staking's validation plus an unbonding time of `MinPeriod` to + `MaxPeriod`, and `MaxValidators` at most 100 (`MaxBondedValidators`), the + most members an autobahn committee holds. +- `HasStaking` reads `UnbondingTime`, which the check keeps nonzero. Staking + refuses calls, and its EndBlock does nothing, until the params are written. + ## Tests - Layout: every `ParamsStorage.sol` slot, offset and field type, and values the @@ -193,5 +209,4 @@ has eleven today. | baseapp | `BlockParams.max_gas` (and the other BlockParams fields) | evmonlyapp, per block | | evm | `KeyMinFeePerGas`, `KeySeiSstoreSetGasEIP2200`, later the EIP-1559 set | executor, per block | | migration | `NumKeysToMigratePerBlock`, `MigrateCosmosEnabled` | as needed | -| staking | the staking params | native staking | | slashing | the slashing params | native slashing | diff --git a/giga/evmonly/precompiles/gov/paramchange_test.go b/giga/evmonly/precompiles/gov/paramchange_test.go index 13d6daae06..a0a13f384a 100644 --- a/giga/evmonly/precompiles/gov/paramchange_test.go +++ b/giga/evmonly/precompiles/gov/paramchange_test.go @@ -280,7 +280,9 @@ func TestEveryGovParamChangesThroughAProposal(t *testing.T) { } var changes []paramChange for _, k := range chainparams.Keys() { - changes = append(changes, paramChange{k.Subspace, k.Key, wantValues[k.Key]}) + if k.Subspace == "gov" { + changes = append(changes, paramChange{k.Subspace, k.Key, wantValues[k.Key]}) + } } require.Len(t, changes, len(wantValues), "every declared gov param") id, err := h.submitParamChange(false, changes...) diff --git a/giga/evmonly/precompiles/params/layout.go b/giga/evmonly/precompiles/params/layout.go index f9ee637f3b..32aa48cc11 100644 --- a/giga/evmonly/precompiles/params/layout.go +++ b/giga/evmonly/precompiles/params/layout.go @@ -9,7 +9,8 @@ var Address = common.HexToAddress("0x0000000000000000000000000000000000001013") // Top-level slots of docs/giga-storage/ParamsStorage.sol. const ( - slotGov = 0 + slotGov = 0 + slotStaking = 16 ) // member is a struct member's position relative to the struct's base slot. @@ -31,3 +32,12 @@ var ( govExpeditedQuorum = member{6, 0} govExpeditedThreshold = member{7, 0} ) + +// ParamsStorage.Staking members. +var ( + stakingUnbondingTime = member{0, 0} + stakingMaxValidators = member{0, 8} + stakingMaxEntries = member{0, 12} + stakingMaxVotingPowerRatio = member{1, 0} + stakingMaxVotingPowerEnforcementThreshold = member{2, 0} +) diff --git a/giga/evmonly/precompiles/params/layout_test.go b/giga/evmonly/precompiles/params/layout_test.go index bbea01c5ee..eecc060368 100644 --- a/giga/evmonly/precompiles/params/layout_test.go +++ b/giga/evmonly/precompiles/params/layout_test.go @@ -43,7 +43,7 @@ func TestLayoutMatchesForge(t *testing.T) { for _, e := range layout.Storage { got[e.Label] = member{slot: mustUint(t, e.Slot), offset: e.Offset} } - require.Equal(t, map[string]member{"gov": {slotGov, 0}}, got) + require.Equal(t, map[string]member{"gov": {slotGov, 0}, "staking": {slotStaking, 0}}, got) structs := map[string]map[string]member{ "Gov": { @@ -59,7 +59,16 @@ func TestLayoutMatchesForge(t *testing.T) { "expeditedThreshold": govExpeditedThreshold, "__gap": {8, 0}, }, + "Staking": { + "unbondingTime": stakingUnbondingTime, + "maxValidators": stakingMaxValidators, + "maxEntries": stakingMaxEntries, + "maxVotingPowerRatio": stakingMaxVotingPowerRatio, + "maxVotingPowerEnforcementThreshold": stakingMaxVotingPowerEnforcementThreshold, + "__gap": {3, 0}, + }, } + subspaceOf := map[string]*subspace{"Gov": &govSubspace, "Staking": &stakingSubspace} seen := 0 for typeID, typ := range layout.Types { name, ok := strings.CutPrefix(typeID, "t_struct(") @@ -73,7 +82,7 @@ func TestLayoutMatchesForge(t *testing.T) { for _, e := range typ.Members { at := member{slot: mustUint(t, e.Slot), offset: e.Offset} got[e.Label] = at - for _, p := range govSubspace.params { + for _, p := range subspaceOf[name].params { if p.at == at { require.Equal(t, "t_"+p.kind.solType, e.Type, p.key) } @@ -88,16 +97,23 @@ func TestLayoutMatchesForge(t *testing.T) { // TestLayoutCoversEveryDeclaredParam checks each declared param sits at a // member of its subspace's struct. func TestLayoutCoversEveryDeclaredParam(t *testing.T) { - members := map[member]bool{ - govMaxDepositPeriod: true, govVotingPeriod: true, govExpeditedVotingPeriod: true, - govMinDeposit: true, govMinExpeditedDeposit: true, govQuorum: true, govThreshold: true, - govVetoThreshold: true, govExpeditedQuorum: true, govExpeditedThreshold: true, - } - for _, p := range govSubspace.params { - require.True(t, members[p.at], p.key) - delete(members, p.at) + for ss, members := range map[*subspace]map[member]bool{ + &govSubspace: { + govMaxDepositPeriod: true, govVotingPeriod: true, govExpeditedVotingPeriod: true, + govMinDeposit: true, govMinExpeditedDeposit: true, govQuorum: true, govThreshold: true, + govVetoThreshold: true, govExpeditedQuorum: true, govExpeditedThreshold: true, + }, + &stakingSubspace: { + stakingUnbondingTime: true, stakingMaxValidators: true, stakingMaxEntries: true, + stakingMaxVotingPowerRatio: true, stakingMaxVotingPowerEnforcementThreshold: true, + }, + } { + for _, p := range ss.params { + require.True(t, members[p.at], p.key) + delete(members, p.at) + } + require.Empty(t, members, "every %s member is declared once", ss.name) } - require.Empty(t, members, "every member is declared once") } func mustUint(t *testing.T, s string) uint64 { @@ -117,7 +133,7 @@ func TestReadsCompilerWrites(t *testing.T) { _, db, err := runtime.Execute(common.FromHex(strings.TrimSpace(string(code))), seed, &runtime.Config{GasLimit: 10_000_000}) require.NoError(t, err) // runtime.Execute deploys the code at the zero-padded address of "contract". - values := govSubspace.read(solstorage.Store{State: stateDBView{db}, Address: common.BytesToAddress([]byte("contract"))}) + s := solstorage.Store{State: stateDBView{db}, Address: common.BytesToAddress([]byte("contract"))} require.Equal(t, Gov{ MaxDepositPeriod: 172_800_000_000_000, VotingPeriod: 259_200_000_000_000, @@ -129,5 +145,12 @@ func TestReadsCompilerWrites(t *testing.T) { VetoThreshold: big.NewInt(334_000_000_000_000_000), ExpeditedQuorum: big.NewInt(667_000_000_000_000_000), ExpeditedThreshold: big.NewInt(667_000_000_000_000_000), - }, govFrom(values)) + }, govFrom(govSubspace.read(s))) + require.Equal(t, Staking{ + UnbondingTime: 1_814_400_000_000_000, + MaxValidators: 35, + MaxEntries: 7, + MaxVotingPowerRatio: big.NewInt(200_000_000_000_000_000), + MaxVotingPowerEnforcementThreshold: big.NewInt(1_000_001), + }, stakingFrom(stakingSubspace.read(s))) } diff --git a/giga/evmonly/precompiles/params/params_test.go b/giga/evmonly/precompiles/params/params_test.go index 0e95797227..a9e8fe45fb 100644 --- a/giga/evmonly/precompiles/params/params_test.go +++ b/giga/evmonly/precompiles/params/params_test.go @@ -79,6 +79,11 @@ func TestKeys(t *testing.T) { {"gov", "tallyparams.veto_threshold", "uint256"}, {"gov", "tallyparams.expedited_quorum", "uint256"}, {"gov", "tallyparams.expedited_threshold", "uint256"}, + {"staking", "UnbondingTime", "uint64"}, + {"staking", "MaxValidators", "uint32"}, + {"staking", "MaxEntries", "uint32"}, + {"staking", "MaxVotingPower", "uint256"}, + {"staking", "MaxVotingPowerEnforcementThreshold", "uint256"}, }, Keys()) } @@ -351,3 +356,65 @@ func TestABIKeepsV2Methods(t *testing.T) { require.Equal(t, m.ID, ABI.Methods[m.Name].ID, m.Sig) } } + +// testStaking is x/staking's default params. +var testStaking = Staking{ + UnbondingTime: 1_814_400_000_000_000, + MaxValidators: 35, + MaxEntries: 7, + MaxVotingPowerRatio: big.NewInt(200_000_000_000_000_000), + MaxVotingPowerEnforcementThreshold: big.NewInt(1_000_000), +} + +func TestStakingValuesRoundTrip(t *testing.T) { + v := testStaking.values() + require.Len(t, v, len(stakingSubspace.params), "values() has one entry per declared staking param") + for _, p := range stakingSubspace.params { + require.Contains(t, v, p.key) + } + require.Equal(t, testStaking, stakingFrom(v), "Staking, the table, stakingFrom and values() agree") +} + +func TestWriteStakingRefusesOnceWritten(t *testing.T) { + state := newMemState() + require.False(t, HasStaking(state)) + require.NoError(t, WriteStaking(state, testStaking)) + require.True(t, HasStaking(state)) + require.Equal(t, testStaking, ReadStaking(state)) + require.ErrorIs(t, WriteStaking(state, testStaking), errStakingWritten) +} + +func TestStakingBounds(t *testing.T) { + for name, edit := range map[string]func(*Staking){ + "zero unbonding time": func(s *Staking) { s.UnbondingTime = 0 }, + "unbonding time too long": func(s *Staking) { s.UnbondingTime = MaxPeriod + 1 }, + "no validators": func(s *Staking) { s.MaxValidators = 0 }, + "more than a committee": func(s *Staking) { s.MaxValidators = MaxBondedValidators + 1 }, + "no entries": func(s *Staking) { s.MaxEntries = 0 }, + "zero voting power ratio": func(s *Staking) { s.MaxVotingPowerRatio = new(big.Int) }, + "voting power ratio above": func(s *Staking) { s.MaxVotingPowerRatio = new(big.Int).Add(decOne, big.NewInt(1)) }, + } { + s := testStaking + edit(&s) + require.Error(t, s.Validate(), name) + state := newMemState() + require.Error(t, WriteStaking(state, s), name) + require.False(t, HasStaking(state), "%s: nothing is written", name) + } + s := testStaking + s.MaxValidators = MaxBondedValidators + s.MaxVotingPowerRatio = decOne + s.MaxVotingPowerEnforcementThreshold = new(big.Int) + require.NoError(t, s.Validate()) +} + +func TestApplyChangesAStakingParam(t *testing.T) { + state := newMemState() + require.NoError(t, WriteStaking(state, testStaking)) + require.NoError(t, Apply(state, []Change{{"staking", "MaxValidators", word(50)}})) + want := testStaking + want.MaxValidators = 50 + require.Equal(t, want, ReadStaking(state)) + require.ErrorIs(t, Apply(state, []Change{{"staking", "MaxValidators", word(uint64(MaxBondedValidators) + 1)}}), errInvalidValue) + require.Equal(t, want, ReadStaking(state), "a change failing the whole-struct check writes nothing") +} diff --git a/giga/evmonly/precompiles/params/staking.go b/giga/evmonly/precompiles/params/staking.go new file mode 100644 index 0000000000..35c8772e98 --- /dev/null +++ b/giga/evmonly/precompiles/params/staking.go @@ -0,0 +1,120 @@ +package params + +import ( + "errors" + "fmt" + "math/big" + + "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles" +) + +// Staking's flat keys. +const ( + keyUnbondingTime = "UnbondingTime" + keyMaxValidators = "MaxValidators" + keyMaxEntries = "MaxEntries" + keyMaxVotingPowerRatio = "MaxVotingPower" + keyMaxVotingPowerEnforcementThreshold = "MaxVotingPowerEnforcementThreshold" +) + +var stakingSubspace = subspace{ + name: "staking", + slot: slotStaking, + params: []param{ + {key: keyUnbondingTime, kind: durationKind, at: stakingUnbondingTime}, + {key: keyMaxValidators, kind: uint32Kind, at: stakingMaxValidators}, + {key: keyMaxEntries, kind: uint32Kind, at: stakingMaxEntries}, + {key: keyMaxVotingPowerRatio, kind: decKind, at: stakingMaxVotingPowerRatio}, + {key: keyMaxVotingPowerEnforcementThreshold, kind: intKind, at: stakingMaxVotingPowerEnforcementThreshold}, + }, + check: func(v values) error { return stakingFrom(v).Validate() }, +} + +// Staking is ParamsStorage.Staking. The unbonding time is nanoseconds, the max +// voting power ratio is a 1e18-scaled decimal, and its enforcement threshold is +// consensus power. +type Staking struct { + UnbondingTime uint64 + MaxValidators uint32 + MaxEntries uint32 + MaxVotingPowerRatio *big.Int + MaxVotingPowerEnforcementThreshold *big.Int +} + +// ReadStaking returns staking's params. +func ReadStaking(state precompiles.State) Staking { + return stakingFrom(stakingSubspace.read(newStore(state))) +} + +// stakingUnbondingTimeParam is the param HasStaking reads. +var stakingUnbondingTimeParam = stakingSubspace.mustParam(keyUnbondingTime) + +// HasStaking reports whether staking's params have been written. +func HasStaking(state precompiles.State) bool { + return stakingSubspace.get(newStore(state), stakingUnbondingTimeParam).Sign() != 0 +} + +var errStakingWritten = errors.New("staking's params are already written") + +// WriteStaking writes s as staking's params, for genesis, if s is valid and +// staking's params have not been written. +func WriteStaking(state precompiles.State, s Staking) error { + if HasStaking(state) { + return errStakingWritten + } + v := s.values() + if err := stakingSubspace.validate(v); err != nil { + return err + } + store := newStore(state) + for _, p := range stakingSubspace.params { + stakingSubspace.set(store, p, v[p.key]) + } + return nil +} + +func stakingFrom(v values) Staking { + return Staking{ + UnbondingTime: v[keyUnbondingTime].Uint64(), + MaxValidators: uint32(v[keyMaxValidators].Uint64()), //nolint:gosec // validate bounds it to 32 bits + MaxEntries: uint32(v[keyMaxEntries].Uint64()), //nolint:gosec // validate bounds it to 32 bits + MaxVotingPowerRatio: v[keyMaxVotingPowerRatio], + MaxVotingPowerEnforcementThreshold: v[keyMaxVotingPowerEnforcementThreshold], + } +} + +func (s Staking) values() values { + return values{ + keyUnbondingTime: new(big.Int).SetUint64(s.UnbondingTime), + keyMaxValidators: new(big.Int).SetUint64(uint64(s.MaxValidators)), + keyMaxEntries: new(big.Int).SetUint64(uint64(s.MaxEntries)), + keyMaxVotingPowerRatio: s.MaxVotingPowerRatio, + keyMaxVotingPowerEnforcementThreshold: s.MaxVotingPowerEnforcementThreshold, + } +} + +// MaxBondedValidators is the most validators MaxValidators may bond: the most +// members an autobahn committee holds. +const MaxBondedValidators uint32 = 100 + +// Validate checks s as x/staking checks its params, and also requires an +// unbonding time of MinPeriod to MaxPeriod and at most MaxBondedValidators +// bonded validators. +func (s Staking) Validate() error { + if s.UnbondingTime < MinPeriod || s.UnbondingTime > MaxPeriod { + return fmt.Errorf("unbonding_time must be in %d..%d nanoseconds", MinPeriod, MaxPeriod) + } + if s.MaxValidators == 0 || s.MaxValidators > MaxBondedValidators { + return fmt.Errorf("max_validators must be in 1..%d", MaxBondedValidators) + } + if s.MaxEntries == 0 { + return errors.New("max_entries must be positive") + } + if r := s.MaxVotingPowerRatio; r == nil || r.Sign() <= 0 || r.Cmp(decOne) > 0 { + return errors.New("max_voting_power_ratio must be above 0 and at most 1") + } + if s.MaxVotingPowerEnforcementThreshold == nil || s.MaxVotingPowerEnforcementThreshold.Sign() < 0 { + return errors.New("max_voting_power_enforcement_threshold must not be negative") + } + return nil +} diff --git a/giga/evmonly/precompiles/params/table.go b/giga/evmonly/precompiles/params/table.go index ad45e05eb4..6f969253ba 100644 --- a/giga/evmonly/precompiles/params/table.go +++ b/giga/evmonly/precompiles/params/table.go @@ -21,6 +21,8 @@ var ( decKind = valueKind{solType: "uint256", bits: 256} durationKind = valueKind{solType: "uint64", bits: 64} coinsKind = valueKind{solType: "uint256", bits: 256} + intKind = valueKind{solType: "uint256", bits: 256} + uint32Kind = valueKind{solType: "uint32", bits: 32} ) // param is one declared param. @@ -48,7 +50,7 @@ type subspace struct { } // subspaces are the declared subspaces, in ParamsStorage order. -var subspaces = []*subspace{&govSubspace} +var subspaces = []*subspace{&govSubspace, &stakingSubspace} // Key is a declared param: its subspace, flat key, and the Solidity type of its // value. diff --git a/giga/evmonly/precompiles/params/testdata/ParamsStorageHarness.bin-runtime b/giga/evmonly/precompiles/params/testdata/ParamsStorageHarness.bin-runtime index 7ab25722fa..da6bd015cd 100644 --- a/giga/evmonly/precompiles/params/testdata/ParamsStorageHarness.bin-runtime +++ b/giga/evmonly/precompiles/params/testdata/ParamsStorageHarness.bin-runtime @@ -1 +1 @@ -0x608060405234801561000f575f5ffd5b5060043610610029575f3560e01c80637d94792a1461002d575b5f5ffd5b610035610037565b005b604051806101600160405280659d29229e000067ffffffffffffffff16815260200165ebbdb3ed000067ffffffffffffffff168152602001654e94914f000167ffffffffffffffff16815260200163d09dc30081526020016401a13b860081526020016704a29b3afafb000081526020016706f05b59d3b2000081526020016704a29b3afafb00008152602001670941a8f7512f80008152602001670941a8f7512f800081526020016040518061010001604052805f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f8152508152505f5f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506040820151815f0160106101000a81548167ffffffffffffffff021916908367ffffffffffffffff160217905550606082015181600101556080820151816002015560a0820151816003015560c0820151816004015560e082015181600501556101008201518160060155610120820151816007015561014082015181600801908161020491906103f7565b50905050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52604160045260245ffd5b5f60089050919050565b5f819050919050565b5f8190506001806001038301049050919050565b5f819050919050565b5f82821b905092915050565b5f600883026102a27fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff82610267565b6102ac8683610267565b95508019841693508086168417925050509392505050565b5f819050919050565b5f6102e76102e26102dd84610241565b6102c4565b610241565b9050919050565b5f819050919050565b610300836102cd565b61031461030c826102ee565b848454610273565b825550505050565b5f5f905090565b61032b61031c565b6103368184846102f7565b505050565b5f5b8281101561035c576103515f828401610323565b60018101905061033d565b505050565b81831015610398576103728261024a565b61037b8461024a565b6103848361025e565b8181016103938385038261033b565b505050505b505050565b680100000000000000008211156103b7576103b661020a565b5b6103c081610237565b6103cb838284610361565b505050565b5f60089050919050565b5f6103e58251610241565b80915050919050565b5f819050919050565b610400826103d0565b67ffffffffffffffff8111156104195761041861020a565b5b610423818361039d565b61042c836103ee565b6104358361025e565b600183045f5b81811015610472575f61044d856103da565b610456816102ee565b809250602087019650505080828501555060018101905061043b565b5050505050505056fea2646970667358221220bd1fcc757b106affb90cca31b88103893e1aed75be624c1d0f20cf1ba7bbb75b64736f6c63430008250033 +608060405234801561000f575f5ffd5b5060043610610029575f3560e01c80637d94792a1461002d575b5f5ffd5b610035610037565b005b604051806101600160405280659d29229e000067ffffffffffffffff16815260200165ebbdb3ed000067ffffffffffffffff168152602001654e94914f000167ffffffffffffffff16815260200163d09dc30081526020016401a13b860081526020016704a29b3afafb000081526020016706f05b59d3b2000081526020016704a29b3afafb00008152602001670941a8f7512f80008152602001670941a8f7512f800081526020016040518061010001604052805f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f8152508152505f5f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506040820151815f0160106101000a81548167ffffffffffffffff021916908367ffffffffffffffff160217905550606082015181600101556080820151816002015560a0820151816003015560c0820151816004015560e082015181600501556101008201518160060155610120820151816007015561014082015181600801906008610206929190610307565b50506040805160c080820183526606722feb7b000082526023602080840191825260078486019081526702c68af0bb1400006060808701918252620f42416080808901918252895161010081018b525f808252968101879052998a0186905291890185905290880184905260a080890185905295880184905260e08801939093529385018690528451601080549451925167ffffffffffffffff9092166bffffffffffffffffffffffff19909516949094176801000000000000000063ffffffff938416021763ffffffff60601b1916600160601b92909116919091021782559151601155905160125590925090610302906013906008610307565b505050565b8260088101928215610335579160200282015b8281111561033557825182559160200191906001019061031a565b50610341929150610345565b5090565b5b80821115610341575f815560010161034656fea2646970667358221220c06f3b49d1a7d0d9ccf807b93c6b5be715e0db9f8a8857759423af51b7af943d64736f6c634300081c0033 diff --git a/giga/evmonly/precompiles/params/testdata/ParamsStorageHarness.sol b/giga/evmonly/precompiles/params/testdata/ParamsStorageHarness.sol index d492af1a9d..16ba9f6c8e 100644 --- a/giga/evmonly/precompiles/params/testdata/ParamsStorageHarness.sol +++ b/giga/evmonly/precompiles/params/testdata/ParamsStorageHarness.sol @@ -20,5 +20,13 @@ contract ParamsStorageHarness is ParamsStorage { expeditedThreshold: 0.667e18, __gap: [uint256(0), 0, 0, 0, 0, 0, 0, 0] }); + staking = Staking({ + unbondingTime: 1_814_400e9, + maxValidators: 35, + maxEntries: 7, + maxVotingPowerRatio: 0.2e18, + maxVotingPowerEnforcementThreshold: 1_000_001, + __gap: [uint256(0), 0, 0, 0, 0, 0, 0, 0] + }); } } diff --git a/giga/evmonly/precompiles/params/testdata/params_storage_layout.json b/giga/evmonly/precompiles/params/testdata/params_storage_layout.json index cb8ad9dc91..46833bde93 100644 --- a/giga/evmonly/precompiles/params/testdata/params_storage_layout.json +++ b/giga/evmonly/precompiles/params/testdata/params_storage_layout.json @@ -1,121 +1,189 @@ { "storage": [ { - "astId": 99, - "contract": "src/storage/ParamsStorage.sol:ParamsStorage", + "astId": 109, + "contract": "giga-storage/ParamsStorage.sol:ParamsStorage", "label": "gov", "offset": 0, "slot": "0", - "type": "t_struct(Gov)96_storage" + "type": "t_struct(Gov)90_storage" + }, + { + "astId": 112, + "contract": "giga-storage/ParamsStorage.sol:ParamsStorage", + "label": "staking", + "offset": 0, + "slot": "16", + "type": "t_struct(Staking)106_storage" } ], "types": { "t_array(t_uint256)8_storage": { + "base": "t_uint256", "encoding": "inplace", "label": "uint256[8]", - "numberOfBytes": "256", - "base": "t_uint256" + "numberOfBytes": "256" }, - "t_struct(Gov)96_storage": { + "t_struct(Gov)90_storage": { "encoding": "inplace", "label": "struct ParamsStorage.Gov", - "numberOfBytes": "512", "members": [ { - "astId": 73, - "contract": "src/storage/ParamsStorage.sol:ParamsStorage", + "astId": 67, + "contract": "giga-storage/ParamsStorage.sol:ParamsStorage", "label": "maxDepositPeriod", "offset": 0, "slot": "0", "type": "t_uint64" }, { - "astId": 75, - "contract": "src/storage/ParamsStorage.sol:ParamsStorage", + "astId": 69, + "contract": "giga-storage/ParamsStorage.sol:ParamsStorage", "label": "votingPeriod", "offset": 8, "slot": "0", "type": "t_uint64" }, { - "astId": 77, - "contract": "src/storage/ParamsStorage.sol:ParamsStorage", + "astId": 71, + "contract": "giga-storage/ParamsStorage.sol:ParamsStorage", "label": "expeditedVotingPeriod", "offset": 16, "slot": "0", "type": "t_uint64" }, { - "astId": 79, - "contract": "src/storage/ParamsStorage.sol:ParamsStorage", + "astId": 73, + "contract": "giga-storage/ParamsStorage.sol:ParamsStorage", "label": "minDeposit", "offset": 0, "slot": "1", "type": "t_uint256" }, { - "astId": 81, - "contract": "src/storage/ParamsStorage.sol:ParamsStorage", + "astId": 75, + "contract": "giga-storage/ParamsStorage.sol:ParamsStorage", "label": "minExpeditedDeposit", "offset": 0, "slot": "2", "type": "t_uint256" }, { - "astId": 83, - "contract": "src/storage/ParamsStorage.sol:ParamsStorage", + "astId": 77, + "contract": "giga-storage/ParamsStorage.sol:ParamsStorage", "label": "quorum", "offset": 0, "slot": "3", "type": "t_uint256" }, { - "astId": 85, - "contract": "src/storage/ParamsStorage.sol:ParamsStorage", + "astId": 79, + "contract": "giga-storage/ParamsStorage.sol:ParamsStorage", "label": "threshold", "offset": 0, "slot": "4", "type": "t_uint256" }, { - "astId": 87, - "contract": "src/storage/ParamsStorage.sol:ParamsStorage", + "astId": 81, + "contract": "giga-storage/ParamsStorage.sol:ParamsStorage", "label": "vetoThreshold", "offset": 0, "slot": "5", "type": "t_uint256" }, { - "astId": 89, - "contract": "src/storage/ParamsStorage.sol:ParamsStorage", + "astId": 83, + "contract": "giga-storage/ParamsStorage.sol:ParamsStorage", "label": "expeditedQuorum", "offset": 0, "slot": "6", "type": "t_uint256" }, { - "astId": 91, - "contract": "src/storage/ParamsStorage.sol:ParamsStorage", + "astId": 85, + "contract": "giga-storage/ParamsStorage.sol:ParamsStorage", "label": "expeditedThreshold", "offset": 0, "slot": "7", "type": "t_uint256" }, { - "astId": 95, - "contract": "src/storage/ParamsStorage.sol:ParamsStorage", + "astId": 89, + "contract": "giga-storage/ParamsStorage.sol:ParamsStorage", "label": "__gap", "offset": 0, "slot": "8", "type": "t_array(t_uint256)8_storage" } - ] + ], + "numberOfBytes": "512" + }, + "t_struct(Staking)106_storage": { + "encoding": "inplace", + "label": "struct ParamsStorage.Staking", + "members": [ + { + "astId": 93, + "contract": "giga-storage/ParamsStorage.sol:ParamsStorage", + "label": "unbondingTime", + "offset": 0, + "slot": "0", + "type": "t_uint64" + }, + { + "astId": 95, + "contract": "giga-storage/ParamsStorage.sol:ParamsStorage", + "label": "maxValidators", + "offset": 8, + "slot": "0", + "type": "t_uint32" + }, + { + "astId": 97, + "contract": "giga-storage/ParamsStorage.sol:ParamsStorage", + "label": "maxEntries", + "offset": 12, + "slot": "0", + "type": "t_uint32" + }, + { + "astId": 99, + "contract": "giga-storage/ParamsStorage.sol:ParamsStorage", + "label": "maxVotingPowerRatio", + "offset": 0, + "slot": "1", + "type": "t_uint256" + }, + { + "astId": 101, + "contract": "giga-storage/ParamsStorage.sol:ParamsStorage", + "label": "maxVotingPowerEnforcementThreshold", + "offset": 0, + "slot": "2", + "type": "t_uint256" + }, + { + "astId": 105, + "contract": "giga-storage/ParamsStorage.sol:ParamsStorage", + "label": "__gap", + "offset": 0, + "slot": "3", + "type": "t_array(t_uint256)8_storage" + } + ], + "numberOfBytes": "352" }, "t_uint256": { "encoding": "inplace", "label": "uint256", "numberOfBytes": "32" }, + "t_uint32": { + "encoding": "inplace", + "label": "uint32", + "numberOfBytes": "4" + }, "t_uint64": { "encoding": "inplace", "label": "uint64", From f30ab466175823eda80a597c4197874c1f85d894 Mon Sep 17 00:00:00 2001 From: Tony Chen Date: Wed, 4 Nov 2026 17:15:15 +0800 Subject: [PATCH 10/44] feat(staking): read and write the staking precompile's storage - Add the staking precompile's storage layer over StakingStorage.sol: the slot layout, typed accessors for validators, delegations, unbonding and redelegation records and the three queues, the power index, and the 1e18 fixed-point share math. - Add solstorage AddressAt/SetAddressAt for packed addresses, and rename ValidatorQueueEntry.completionHeight to unbondingHeight. - Tests check the layout against solc's, read state a compiled harness wrote, and compare the share math with sdk.Dec. Co-Authored-By: Claude Opus 5.5 --- docs/giga-storage/StakingStorage.sol | 4 +- giga/evmonly/precompiles/solstorage/store.go | 9 + .../precompiles/solstorage/store_test.go | 18 + giga/evmonly/precompiles/staking/dec.go | 55 ++ giga/evmonly/precompiles/staking/dec_test.go | 55 ++ .../precompiles/staking/helpers_test.go | 125 +++ giga/evmonly/precompiles/staking/layout.go | 127 +++ .../precompiles/staking/layout_test.go | 314 +++++++ giga/evmonly/precompiles/staking/storage.go | 440 ++++++++++ .../precompiles/staking/storage_test.go | 32 + .../StakingStorageHarness.bin-runtime | 1 + .../testdata/StakingStorageHarness.sol | 67 ++ .../testdata/staking_storage_layout.json | 771 ++++++++++++++++++ giga/evmonly/precompiles/staking/validator.go | 132 +++ 14 files changed, 2149 insertions(+), 1 deletion(-) create mode 100644 giga/evmonly/precompiles/staking/dec.go create mode 100644 giga/evmonly/precompiles/staking/dec_test.go create mode 100644 giga/evmonly/precompiles/staking/helpers_test.go create mode 100644 giga/evmonly/precompiles/staking/layout.go create mode 100644 giga/evmonly/precompiles/staking/layout_test.go create mode 100644 giga/evmonly/precompiles/staking/storage.go create mode 100644 giga/evmonly/precompiles/staking/storage_test.go create mode 100644 giga/evmonly/precompiles/staking/testdata/StakingStorageHarness.bin-runtime create mode 100644 giga/evmonly/precompiles/staking/testdata/StakingStorageHarness.sol create mode 100644 giga/evmonly/precompiles/staking/testdata/staking_storage_layout.json create mode 100644 giga/evmonly/precompiles/staking/validator.go diff --git a/docs/giga-storage/StakingStorage.sol b/docs/giga-storage/StakingStorage.sol index c727f99c80..92c44eb5b5 100644 --- a/docs/giga-storage/StakingStorage.sol +++ b/docs/giga-storage/StakingStorage.sol @@ -81,9 +81,11 @@ contract StakingStorage { uint256 sharesDst; } + /// @dev completionTime and unbondingHeight are the operator's validator's + /// unbondingTime and unbondingHeight when it began unbonding. struct ValidatorQueueEntry { uint64 completionTime; - uint64 completionHeight; + uint64 unbondingHeight; address operator; } diff --git a/giga/evmonly/precompiles/solstorage/store.go b/giga/evmonly/precompiles/solstorage/store.go index c2a199f837..cdfde65380 100644 --- a/giga/evmonly/precompiles/solstorage/store.go +++ b/giga/evmonly/precompiles/solstorage/store.go @@ -81,6 +81,15 @@ func (s Store) SetUint8(slot common.Hash, offset int, v uint8) { s.setPacked(slot, offset, []byte{v}) } +func (s Store) AddressAt(slot common.Hash, offset int) common.Address { + w := s.Word(slot) + return common.BytesToAddress(w[32-offset-common.AddressLength : 32-offset]) +} + +func (s Store) SetAddressAt(slot common.Hash, offset int, a common.Address) { + s.setPacked(slot, offset, a[:]) +} + func (s Store) Bool(slot common.Hash, offset int) bool { w := s.Word(slot) return w[31-offset] != 0 diff --git a/giga/evmonly/precompiles/solstorage/store_test.go b/giga/evmonly/precompiles/solstorage/store_test.go index cb1f896eb0..fdb150048c 100644 --- a/giga/evmonly/precompiles/solstorage/store_test.go +++ b/giga/evmonly/precompiles/solstorage/store_test.go @@ -68,6 +68,24 @@ func TestPackedFieldsLeaveNeighboursIntact(t *testing.T) { require.Equal(t, uint64(1<<63+7), s.Uint64(slot, 5)) } +func TestPackedAddressLeavesNeighboursIntact(t *testing.T) { + s := Store{State: mapState{}} + slot := Slot(1) + a := common.HexToAddress("0xffeeddccbbaa99887766554433221100ffeeddcc") + s.SetUint64(slot, 0, 1<<63+7) + s.SetAddressAt(slot, 8, a) + s.SetInt32(slot, 28, -9) + + require.Equal(t, a, s.AddressAt(slot, 8)) + require.Equal(t, uint64(1<<63+7), s.Uint64(slot, 0)) + require.Equal(t, int32(-9), s.Int32(slot, 28)) + + s.SetAddressAt(slot, 8, common.Address{}) + require.Equal(t, common.Address{}, s.AddressAt(slot, 8)) + require.Equal(t, uint64(1<<63+7), s.Uint64(slot, 0)) + require.Equal(t, int32(-9), s.Int32(slot, 28)) +} + func TestSetSwapAndPop(t *testing.T) { state := mapState{} set := Set{Store: Store{State: state}, Base: Slot(9)} diff --git a/giga/evmonly/precompiles/staking/dec.go b/giga/evmonly/precompiles/staking/dec.go new file mode 100644 index 0000000000..0e4a462b72 --- /dev/null +++ b/giga/evmonly/precompiles/staking/dec.go @@ -0,0 +1,55 @@ +package staking + +import ( + "math/big" +) + +var ( + // decOne is 1 as a 1e18-scaled decimal, the scale of shares and ratios. + decOne = big.NewInt(1_000_000_000_000_000_000) + + // weiPerUsei is the wei in one usei, the smallest unit an amount may hold. + weiPerUsei = big.NewInt(1_000_000_000_000) + + // powerReduction is the tokens in one unit of consensus power: one SEI, as + // x/staking's DefaultPowerReduction of 1e6 usei is. + powerReduction = new(big.Int).Mul(big.NewInt(1_000_000), weiPerUsei) +) + +// consensusPower returns the consensus power tokens are worth. +func consensusPower(tokens *big.Int) *big.Int { + return new(big.Int).Quo(tokens, powerReduction) +} + +// intToDec returns integer i as a decimal. +func intToDec(i *big.Int) *big.Int { + return new(big.Int).Mul(i, decOne) +} + +// truncateDec returns non-negative decimal d with its fraction dropped. +func truncateDec(d *big.Int) *big.Int { + return new(big.Int).Quo(d, decOne) +} + +// quoDec divides decimal a by decimal b, both non-negative, as sdk.Dec's Quo +// does: truncated to 36 places, then rounded half to even to 18. +func quoDec(a, b *big.Int) *big.Int { + q := new(big.Int).Mul(a, decOne) + q.Mul(q, decOne) + return roundDec(q.Quo(q, b)) +} + +// roundDec divides non-negative x by 1e18, rounding half to even, as +// sdk.Dec's chopPrecisionAndRound does. +func roundDec(x *big.Int) *big.Int { + q, r := new(big.Int).QuoRem(x, decOne, new(big.Int)) + switch r.Lsh(r, 1).Cmp(decOne) { + case 1: + q.Add(q, big.NewInt(1)) + case 0: + if q.Bit(0) == 1 { + q.Add(q, big.NewInt(1)) + } + } + return q +} diff --git a/giga/evmonly/precompiles/staking/dec_test.go b/giga/evmonly/precompiles/staking/dec_test.go new file mode 100644 index 0000000000..62102bebd7 --- /dev/null +++ b/giga/evmonly/precompiles/staking/dec_test.go @@ -0,0 +1,55 @@ +package staking + +import ( + "math/big" + "math/rand" + "testing" + + "github.com/stretchr/testify/require" + + sdk "github.com/sei-protocol/sei-chain/sei-cosmos/types" + stakingtypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/staking/types" +) + +// TestShareMathMatchesSDK pins the exchange between tokens and shares to +// x/staking's Validator, rounding included. +func TestShareMathMatchesSDK(t *testing.T) { + rng := rand.New(rand.NewSource(7)) //nolint:gosec // deterministic test data + random := func(bits int) *big.Int { + v := new(big.Int).Rand(rng, new(big.Int).Lsh(big.NewInt(1), uint(rng.Intn(bits)+1))) //nolint:gosec // bounded + return v.Add(v, big.NewInt(1)) + } + for range 2_000 { + v := validator{tokens: random(100), delegatorShares: random(160)} + sv := stakingtypes.Validator{ + Tokens: sdk.NewIntFromBigInt(v.tokens), + DelegatorShares: sdk.NewDecFromBigIntWithPrec(v.delegatorShares, sdk.Precision), + } + + amount := random(100) + got, err := v.sharesFromTokens(amount) + require.NoError(t, err) + want, err := sv.SharesFromTokens(sdk.NewIntFromBigInt(amount)) + require.NoError(t, err) + require.Equal(t, want.BigInt().String(), got.String(), "shares for %s tokens", amount) + truncated, err := sv.SharesFromTokensTruncated(sdk.NewIntFromBigInt(amount)) + require.NoError(t, err) + require.Equal(t, truncated.BigInt().String(), got.String(), "x/staking's truncated shares are the same") + + shares := new(big.Int).Rand(rng, v.delegatorShares) + decTokens := v.tokensFromShares(shares) + wantTokens := sv.TokensFromShares(sdk.NewDecFromBigIntWithPrec(shares, sdk.Precision)) + require.Equal(t, wantTokens.BigInt().String(), decTokens.String(), "tokens for %s shares", shares) + require.Equal(t, wantTokens.TruncateInt().BigInt().String(), truncateDec(decTokens).String()) + } +} + +func TestVotingPowerRatioMatchesSDK(t *testing.T) { + rng := rand.New(rand.NewSource(11)) //nolint:gosec // deterministic test data + for range 2_000 { + total := big.NewInt(rng.Int63n(1<<40) + 1) + power := new(big.Int).Rand(rng, total) + want := sdk.NewIntFromBigInt(power).ToDec().Quo(sdk.NewIntFromBigInt(total).ToDec()) + require.Equal(t, want.BigInt().String(), quoDec(intToDec(power), intToDec(total)).String(), "%s / %s", power, total) + } +} diff --git a/giga/evmonly/precompiles/staking/helpers_test.go b/giga/evmonly/precompiles/staking/helpers_test.go new file mode 100644 index 0000000000..d62c3134fd --- /dev/null +++ b/giga/evmonly/precompiles/staking/helpers_test.go @@ -0,0 +1,125 @@ +package staking + +import ( + "errors" + "maps" + "math/big" + "time" + + "github.com/ethereum/go-ethereum/common" + ethtypes "github.com/ethereum/go-ethereum/core/types" + + "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles" +) + +// memState is a map-backed precompiles.State and LogSink. +type memState struct { + balances map[common.Address]*big.Int + storage map[common.Address]map[common.Hash]common.Hash + logs []*ethtypes.Log + snapshots []memSnapshot +} + +// memSnapshot is a copy of memState's balances, storage and log count. +type memSnapshot struct { + balances map[common.Address]*big.Int + storage map[common.Address]map[common.Hash]common.Hash + logs int +} + +var ( + _ precompiles.State = (*memState)(nil) + _ precompiles.LogSink = (*memState)(nil) +) + +func newMemState() *memState { + return &memState{ + balances: map[common.Address]*big.Int{}, + storage: map[common.Address]map[common.Hash]common.Hash{}, + } +} + +func (m *memState) Snapshot() int { + snap := memSnapshot{balances: map[common.Address]*big.Int{}, storage: map[common.Address]map[common.Hash]common.Hash{}, logs: len(m.logs)} + for a, b := range m.balances { + snap.balances[a] = new(big.Int).Set(b) + } + for a, slots := range m.storage { + snap.storage[a] = maps.Clone(slots) + } + m.snapshots = append(m.snapshots, snap) + return len(m.snapshots) - 1 +} + +func (m *memState) RevertToSnapshot(id int) { + snap := m.snapshots[id] + m.balances, m.storage, m.logs = snap.balances, snap.storage, m.logs[:snap.logs] + m.snapshots = m.snapshots[:id] +} + +func (m *memState) GetBalance(a common.Address) *big.Int { + if b, ok := m.balances[a]; ok { + return new(big.Int).Set(b) + } + return new(big.Int) +} + +func (m *memState) AddBalance(a common.Address, v *big.Int) { + m.balances[a] = new(big.Int).Add(m.GetBalance(a), v) +} + +func (m *memState) SubBalance(a common.Address, v *big.Int) error { + b := m.GetBalance(a) + if b.Cmp(v) < 0 { + return errors.New("insufficient balance") + } + m.balances[a] = b.Sub(b, v) + return nil +} + +func (m *memState) GetNonce(common.Address) uint64 { return 0 } +func (m *memState) SetNonce(common.Address, uint64) {} +func (m *memState) GetCode(common.Address) []byte { return nil } +func (m *memState) Failed() bool { return false } +func (m *memState) AddLog(l *ethtypes.Log) { m.logs = append(m.logs, l) } + +func (m *memState) GetState(a common.Address, k common.Hash) common.Hash { + return m.storage[a][k] +} + +func (m *memState) SetState(a common.Address, k, v common.Hash) { + if m.storage[a] == nil { + m.storage[a] = map[common.Hash]common.Hash{} + } + if v == (common.Hash{}) { + delete(m.storage[a], k) + return + } + m.storage[a][k] = v +} + +const ( + second = uint64(time.Second) + startTime = 1_700_000_000 * second +) + +var ( + val1 = common.HexToAddress("0x0000000000000000000000000000000000000a01") + val2 = common.HexToAddress("0x0000000000000000000000000000000000000a02") + val3 = common.HexToAddress("0x0000000000000000000000000000000000000a03") + alice = common.HexToAddress("0x00000000000000000000000000000000000a11ce") + bob = common.HexToAddress("0x0000000000000000000000000000000000000b0b") +) + +// sei returns n SEI in wei. +func sei(n int64) *big.Int { + return new(big.Int).Mul(big.NewInt(n), powerReduction) +} + +// must returns v, panicking on err, for test reads that cannot fail. +func must[T any](v T, err error) T { + if err != nil { + panic(err) + } + return v +} diff --git a/giga/evmonly/precompiles/staking/layout.go b/giga/evmonly/precompiles/staking/layout.go new file mode 100644 index 0000000000..331bb3e115 --- /dev/null +++ b/giga/evmonly/precompiles/staking/layout.go @@ -0,0 +1,127 @@ +package staking + +import ( + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/crypto" +) + +// Address is the staking precompile's address. +var Address = common.HexToAddress("0x0000000000000000000000000000000000001005") + +// Top-level slots of docs/giga-storage/StakingStorage.sol. +const ( + slotLastValidators = 0 + slotLastTotalPower = 1 + slotValidators = 2 + slotValidatorSet = 3 + slotValidatorsByConsensusPubkey = 5 + slotValidatorsByPower = 6 + slotDelegations = 7 + slotDelegationsByDelegator = 8 + slotUnbondingDelegations = 9 + slotRedelegationEntryCounts = 10 + slotRedelegationsByValDst = 11 + slotUnbondingQueueBounds = 12 + slotUnbondingQueue = 13 + slotRedelegationQueueBounds = 14 + slotRedelegationQueue = 15 + slotValidatorQueueBounds = 16 + slotValidatorQueue = 17 +) + +// member is a struct member's position relative to the struct's base slot. +type member struct { + slot uint64 + offset int +} + +// StakingStorage.Validator members. +var ( + validatorConsensusPubkey = member{0, 0} + validatorJailed = member{1, 0} + validatorStatus = member{1, 1} + validatorTokens = member{2, 0} + validatorDelegatorShares = member{3, 0} + validatorMoniker = member{4, 0} + validatorIdentity = member{5, 0} + validatorWebsite = member{6, 0} + validatorSecurityContact = member{7, 0} + validatorDetails = member{8, 0} + validatorUnbondingHeight = member{9, 0} + validatorUnbondingTime = member{9, 8} + validatorCommissionRate = member{10, 0} + validatorCommissionMaxRate = member{11, 0} + validatorCommissionMaxChange = member{12, 0} + validatorCommissionUpdate = member{13, 0} + validatorMinSelfDelegation = member{14, 0} + validatorGap = member{15, 0} +) + +// validatorSlots is how many slots a StakingStorage.Validator takes. +const validatorSlots = 23 + +// StakingStorage.ValidatorPower members. +var ( + validatorPowerOperator = member{0, 0} + validatorPowerPower = member{0, 20} +) + +// StakingStorage.UnbondingDelegationEntry members. +var ( + unbondingEntryCreationHeight = member{0, 0} + unbondingEntryCompletionTime = member{0, 8} + unbondingEntryInitialBalance = member{1, 0} + unbondingEntryBalance = member{2, 0} +) + +// unbondingEntrySlots is how many slots a StakingStorage.UnbondingDelegationEntry takes. +const unbondingEntrySlots = 3 + +// StakingStorage.QueueBounds members. +var ( + queueHead = member{0, 0} + queueTail = member{0, 8} +) + +// queueCompletionTime is the completionTime member every queue entry begins with. +var queueCompletionTime = member{0, 0} + +// StakingStorage.UnbondingQueueEntry members. +var ( + unbondingQueueDelegator = member{0, 8} + unbondingQueueValidator = member{1, 0} +) + +// StakingStorage.RedelegationQueueEntry members. +var ( + redelegationQueueDelegator = member{0, 8} + redelegationQueueCreationHeight = member{1, 0} + redelegationQueueSrcValidator = member{1, 8} + redelegationQueueDstValidator = member{2, 0} + redelegationQueueInitialBalance = member{3, 0} + redelegationQueueSharesDst = member{4, 0} +) + +// StakingStorage.ValidatorQueueEntry members. +var ( + validatorQueueUnbondingHeight = member{0, 8} + validatorQueueOperator = member{1, 0} +) + +// How many slots each queue's entries take. +const ( + unbondingQueueEntrySlots = 2 + redelegationQueueEntrySlots = 5 + validatorQueueEntrySlots = 2 +) + +// BondedEscrow holds the tokens of bonded validators. +var BondedEscrow = escrow("bonded") + +// NotBondedEscrow holds the tokens of unbonded and unbonding validators and the +// balance of every unbonding entry. +var NotBondedEscrow = escrow("not_bonded") + +func escrow(name string) common.Address { + return common.BytesToAddress(crypto.Keccak256([]byte("sei.evmonly.escrow"), Address[:], []byte(name))[12:]) +} diff --git a/giga/evmonly/precompiles/staking/layout_test.go b/giga/evmonly/precompiles/staking/layout_test.go new file mode 100644 index 0000000000..722468f085 --- /dev/null +++ b/giga/evmonly/precompiles/staking/layout_test.go @@ -0,0 +1,314 @@ +package staking + +import ( + "encoding/json" + "math/big" + "os" + "strconv" + "strings" + "testing" + + "github.com/ethereum/go-ethereum/accounts/abi" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/vm" + "github.com/ethereum/go-ethereum/core/vm/runtime" + "github.com/stretchr/testify/require" + + "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles/solstorage" +) + +// solcLayout is `solc --storage-layout` of StakingStorage. +type solcLayout struct { + Storage []solcEntry `json:"storage"` + Types map[string]struct { + Label string `json:"label"` + NumberOfBytes string `json:"numberOfBytes"` + Members []solcEntry `json:"members"` + } `json:"types"` +} + +type solcEntry struct { + Label string `json:"label"` + Offset int `json:"offset"` + Slot string `json:"slot"` +} + +// TestLayoutMatchesSolc pins every slot and member offset to the compiler's +// layout of docs/giga-storage/StakingStorage.sol. Regenerate testdata with +// `solc --storage-layout` or `forge inspect StakingStorage storage-layout --json` +// after editing the schema. +func TestLayoutMatchesSolc(t *testing.T) { + bz, err := os.ReadFile("testdata/staking_storage_layout.json") + require.NoError(t, err) + var layout solcLayout + require.NoError(t, json.Unmarshal(bz, &layout)) + + got := map[string]uint64{} + for _, e := range layout.Storage { + require.Zero(t, e.Offset, e.Label) + got[e.Label] = mustUint(t, e.Slot) + } + require.Equal(t, map[string]uint64{ + "lastValidators": slotLastValidators, + "lastTotalPower": slotLastTotalPower, + "validators": slotValidators, + "validatorSet": slotValidatorSet, + "validatorsByConsensusPubkey": slotValidatorsByConsensusPubkey, + "validatorsByPower": slotValidatorsByPower, + "delegations": slotDelegations, + "delegationsByDelegator": slotDelegationsByDelegator, + "unbondingDelegations": slotUnbondingDelegations, + "redelegationEntryCounts": slotRedelegationEntryCounts, + "redelegationsByValDst": slotRedelegationsByValDst, + "unbondingQueueBounds": slotUnbondingQueueBounds, + "unbondingQueue": slotUnbondingQueue, + "redelegationQueueBounds": slotRedelegationQueueBounds, + "redelegationQueue": slotRedelegationQueue, + "validatorQueueBounds": slotValidatorQueueBounds, + "validatorQueue": slotValidatorQueue, + "migrating": 18, + "migrationCursor": 19, + "migrationFailures": 20, + }, got) + + // Each struct's Go members, and how many slots it takes. Description and + // Commission are read through Validator's flattened members. + structs := map[string]struct { + members map[string]member + slots uint64 + }{ + "struct StakingStorage.Validator": {map[string]member{ + "consensusPubkey": validatorConsensusPubkey, + "jailed": validatorJailed, + "status": validatorStatus, + "tokens": validatorTokens, + "delegatorShares": validatorDelegatorShares, + "description": validatorMoniker, + "unbondingHeight": validatorUnbondingHeight, + "unbondingTime": validatorUnbondingTime, + "commission": validatorCommissionRate, + "minSelfDelegation": validatorMinSelfDelegation, + "__gap": validatorGap, + }, validatorSlots}, + "struct StakingStorage.Description": {map[string]member{ + "moniker": sub(validatorMoniker, validatorMoniker), + "identity": sub(validatorIdentity, validatorMoniker), + "website": sub(validatorWebsite, validatorMoniker), + "securityContact": sub(validatorSecurityContact, validatorMoniker), + "details": sub(validatorDetails, validatorMoniker), + }, 5}, + "struct StakingStorage.Commission": {map[string]member{ + "commissionRates": sub(validatorCommissionRate, validatorCommissionRate), + "updateTime": sub(validatorCommissionUpdate, validatorCommissionRate), + }, 4}, + "struct StakingStorage.CommissionRates": {map[string]member{ + "rate": sub(validatorCommissionRate, validatorCommissionRate), + "maxRate": sub(validatorCommissionMaxRate, validatorCommissionRate), + "maxChangeRate": sub(validatorCommissionMaxChange, validatorCommissionRate), + }, 3}, + "struct StakingStorage.ValidatorPower": {map[string]member{ + "operator": validatorPowerOperator, + "power": validatorPowerPower, + }, 1}, + "struct StakingStorage.Delegation": {map[string]member{"shares": {0, 0}}, 1}, + "struct StakingStorage.UnbondingDelegationEntry": {map[string]member{ + "creationHeight": unbondingEntryCreationHeight, + "completionTime": unbondingEntryCompletionTime, + "initialBalance": unbondingEntryInitialBalance, + "balance": unbondingEntryBalance, + }, unbondingEntrySlots}, + "struct StakingStorage.UnbondingQueueEntry": {map[string]member{ + "completionTime": queueCompletionTime, + "delegator": unbondingQueueDelegator, + "validator": unbondingQueueValidator, + }, unbondingQueueEntrySlots}, + "struct StakingStorage.RedelegationQueueEntry": {map[string]member{ + "completionTime": queueCompletionTime, + "delegator": redelegationQueueDelegator, + "creationHeight": redelegationQueueCreationHeight, + "srcValidator": redelegationQueueSrcValidator, + "dstValidator": redelegationQueueDstValidator, + "initialBalance": redelegationQueueInitialBalance, + "sharesDst": redelegationQueueSharesDst, + }, redelegationQueueEntrySlots}, + "struct StakingStorage.ValidatorQueueEntry": {map[string]member{ + "completionTime": queueCompletionTime, + "unbondingHeight": validatorQueueUnbondingHeight, + "operator": validatorQueueOperator, + }, validatorQueueEntrySlots}, + "struct StakingStorage.QueueBounds": {map[string]member{ + "head": queueHead, + "tail": queueTail, + }, 1}, + "struct AddressSet": {map[string]member{ + "values": {0, 0}, + "positions": {1, 0}, + }, 2}, + } + seen := 0 + for _, typ := range layout.Types { + if len(typ.Members) == 0 { + continue + } + want, ok := structs[typ.Label] + require.True(t, ok, "%s has no Go layout", typ.Label) + members := map[string]member{} + for _, e := range typ.Members { + members[e.Label] = member{slot: mustUint(t, e.Slot), offset: e.Offset} + } + require.Equal(t, want.members, members, typ.Label) + require.Equal(t, want.slots*32, mustUint(t, typ.NumberOfBytes), typ.Label) + seen++ + } + require.Equal(t, len(structs), seen) +} + +// sub returns m's position within the nested struct that starts at base. +func sub(m, base member) member { + return member{slot: m.slot - base.slot, offset: m.offset} +} + +func mustUint(t *testing.T, s string) uint64 { + v, err := strconv.ParseUint(s, 10, 64) + require.NoError(t, err) + return v +} + +// TestStoreReadsCompilerWrites runs StakingStorageHarness, which writes +// StakingStorage with solc's codegen, and reads the result back through store. +// Rebuild testdata with `solc --bin-runtime` of the harness and the remapping +// giga-storage/=docs/giga-storage/. +func TestStoreReadsCompilerWrites(t *testing.T) { + code, err := os.ReadFile("testdata/StakingStorageHarness.bin-runtime") + require.NoError(t, err) + op := common.HexToAddress("0x00000000000000000000000000000000000000a1") + other := common.HexToAddress("0x00000000000000000000000000000000000000b2") + delegator := common.HexToAddress("0x00000000000000000000000000000000000000c3") + pubkey := common.HexToHash("0xed25519") + + seed, err := seedABI.Pack("seed", op, other, delegator, pubkey) + require.NoError(t, err) + _, db, err := runtime.Execute(common.FromHex(strings.TrimSpace(string(code))), seed, &runtime.Config{GasLimit: 10_000_000}) + require.NoError(t, err) + // runtime.Execute deploys the code at the zero-padded address of "contract". + s := store{solstorage.Store{State: stateDBView{db}, Address: common.BytesToAddress([]byte("contract"))}} + + set, err := s.lastValidators() + require.NoError(t, err) + require.Equal(t, []validatorPower{{op, 30}, {other, 20}}, set) + require.Equal(t, big.NewInt(50), s.lastTotalPower()) + + v, ok := s.validator(op) + require.True(t, ok) + require.Equal(t, validator{ + consensusPubkey: pubkey, + jailed: true, + status: statusUnbonding, + tokens: sei(31), + delegatorShares: intToDec(sei(32)), + unbondingHeight: 33, + unbondingTime: 34, + minSelfDelegation: big.NewInt(37), + }, v) + base := validatorBase(op) + moniker, err := s.String(at(base, validatorMoniker)) + require.NoError(t, err) + require.Equal(t, "a moniker long enough to spill past one storage word", moniker) + details, err := s.String(at(base, validatorDetails)) + require.NoError(t, err) + require.Equal(t, "d", details) + require.Equal(t, big.NewInt(35), s.Uint256(at(base, validatorCommissionRate))) + require.Equal(t, uint64(36), s.Uint64(at(base, validatorCommissionUpdate), validatorCommissionUpdate.offset)) + require.Equal(t, uint64(2), s.validatorSet().Len()) + require.True(t, s.validatorSet().Contains(solstorage.AddressKey(other))) + require.Equal(t, op, s.validatorByPubkey(pubkey)) + index := s.powerIndex() + require.Equal(t, uint64(2), index.len()) + require.Equal(t, other, index.at(0)) + require.Equal(t, op, index.at(1)) + + shares, found := s.delegation(delegator, op) + require.True(t, found) + require.Equal(t, big.NewInt(41), shares) + require.True(t, s.delegatedValidators(delegator).Contains(solstorage.AddressKey(op))) + require.Equal(t, []unbondingEntry{ + {creationHeight: 51, completionTime: 52, initialBalance: big.NewInt(53), balance: big.NewInt(54)}, + {creationHeight: 55, completionTime: 56, initialBalance: big.NewInt(57), balance: big.NewInt(58)}, + }, must(s.unbondingEntries(delegator, op))) + require.Equal(t, big.NewInt(2), s.redelegationEntryCount(delegator, op, other)) + require.Equal(t, big.NewInt(3), s.receivingRedelegations(other, delegator)) + + q := s.unbondingQueue() + require.Equal(t, uint64(1), q.head()) + require.Equal(t, uint64(2), q.tail()) + e, due := q.due(61) + require.True(t, due) + gotDelegator, gotOp := unbondingQueueEntry(s, e) + require.Equal(t, delegator, gotDelegator) + require.Equal(t, op, gotOp) + _, due = q.due(60) + require.False(t, due) + + e, due = s.redelegationQueue().due(71) + require.True(t, due) + require.Equal(t, delegator, s.AddressAt(at(e, redelegationQueueDelegator), redelegationQueueDelegator.offset)) + require.Equal(t, uint64(72), s.Uint64(at(e, redelegationQueueCreationHeight), redelegationQueueCreationHeight.offset)) + require.Equal(t, op, s.AddressAt(at(e, redelegationQueueSrcValidator), redelegationQueueSrcValidator.offset)) + require.Equal(t, other, s.AddressAt(at(e, redelegationQueueDstValidator), redelegationQueueDstValidator.offset)) + require.Equal(t, big.NewInt(73), s.Uint256(at(e, redelegationQueueInitialBalance))) + require.Equal(t, big.NewInt(74), s.Uint256(at(e, redelegationQueueSharesDst))) + + vq := s.validatorQueue() + require.Equal(t, uint64(4), vq.head()) + e, due = vq.due(81) + require.True(t, due) + require.Equal(t, uint64(82), s.Uint64(at(e, validatorQueueUnbondingHeight), validatorQueueUnbondingHeight.offset)) + require.Equal(t, other, s.AddressAt(at(e, validatorQueueOperator), validatorQueueOperator.offset)) +} + +var seedABI = func() abi.ABI { + parsed, err := abi.JSON(strings.NewReader(`[{"type":"function","name":"seed","inputs":[ + {"name":"op","type":"address"},{"name":"other","type":"address"}, + {"name":"delegator","type":"address"},{"name":"pubkey","type":"bytes32"}],"outputs":[]}]`)) + if err != nil { + panic(err) + } + return parsed +}() + +// TestDeleteValidatorClearsTheRecord checks that deleting a validator leaves +// none of its slots, including its description's spilled strings. +func TestDeleteValidatorClearsTheRecord(t *testing.T) { + state := newMemState() + s := newStore(state) + op := common.HexToAddress("0xa1") + base := validatorBase(op) + s.setValidator(op, validator{consensusPubkey: common.HexToHash("0x01"), status: statusUnbonded, tokens: big.NewInt(1), delegatorShares: big.NewInt(2), unbondingTime: 3, minSelfDelegation: big.NewInt(4)}) + for _, m := range []member{validatorMoniker, validatorIdentity, validatorWebsite, validatorSecurityContact, validatorDetails} { + require.NoError(t, s.SetString(at(base, m), strings.Repeat("x", 100))) + } + s.SetUint256(at(base, validatorCommissionMaxChange), big.NewInt(5)) + s.SetUint256(solstorage.Offset(base, validatorSlots-1), big.NewInt(6)) + require.NoError(t, s.deleteValidator(op)) + require.Empty(t, state.storage[Address]) +} + +// stateDBView reads storage from a geth StateDB. Only GetState is supported. +type stateDBView struct { + db vm.StateDB +} + +func (v stateDBView) GetState(a common.Address, k common.Hash) common.Hash { + return v.db.GetState(a, k) +} + +func (v stateDBView) SetState(common.Address, common.Hash, common.Hash) { panic("read-only") } +func (v stateDBView) GetBalance(common.Address) *big.Int { panic("unsupported") } +func (v stateDBView) AddBalance(common.Address, *big.Int) { panic("unsupported") } +func (v stateDBView) SubBalance(common.Address, *big.Int) error { panic("unsupported") } +func (v stateDBView) GetNonce(common.Address) uint64 { panic("unsupported") } +func (v stateDBView) SetNonce(common.Address, uint64) { panic("unsupported") } +func (v stateDBView) GetCode(common.Address) []byte { panic("unsupported") } +func (v stateDBView) Failed() bool { return false } +func (v stateDBView) Snapshot() int { panic("unsupported") } +func (v stateDBView) RevertToSnapshot(int) { panic("unsupported") } diff --git a/giga/evmonly/precompiles/staking/storage.go b/giga/evmonly/precompiles/staking/storage.go new file mode 100644 index 0000000000..3cee6cbc8f --- /dev/null +++ b/giga/evmonly/precompiles/staking/storage.go @@ -0,0 +1,440 @@ +package staking + +import ( + "errors" + "fmt" + "math" + "math/big" + + "github.com/ethereum/go-ethereum/common" + + "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles" + chainparams "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles/params" + "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles/solstorage" +) + +// Validator statuses, numbered as x/staking's BondStatus. +const ( + statusUnbonded uint8 = 1 + statusUnbonding uint8 = 2 + statusBonded uint8 = 3 +) + +var ( + errInvalidStoredSet = errors.New("invalid stored bonded set") + errQueueCorrupt = errors.New("queue head is past its tail") + errQueueExhausted = errors.New("queue has used every index") + errPowerIndexCorrupt = errors.New("validator is not where the power index orders it") + errInsufficientShares = errors.New("insufficient delegation shares") + errInvalidStoredEntries = errors.New("invalid stored unbonding entries") +) + +// validator is the StakingStorage.Validator fields staking's rules read and +// write. Its description and commission are left to the methods that set them. +type validator struct { + consensusPubkey common.Hash + jailed bool + status uint8 + tokens *big.Int + delegatorShares *big.Int + unbondingHeight uint64 + unbondingTime uint64 + minSelfDelegation *big.Int +} + +func (v validator) bonded() bool { + return v.status == statusBonded +} + +// invalidExRate reports whether v has shares but no tokens to price them. +func (v validator) invalidExRate() bool { + return v.tokens.Sign() == 0 && v.delegatorShares.Sign() > 0 +} + +// sharesFromTokens returns the shares amount is worth at v's exchange rate, +// truncated, as x/staking's SharesFromTokens does. It fails when v has no +// tokens. +func (v validator) sharesFromTokens(amount *big.Int) (*big.Int, error) { + if v.tokens.Sign() == 0 { + return nil, errInsufficientShares + } + shares := new(big.Int).Mul(v.delegatorShares, amount) + return shares.Quo(shares, v.tokens), nil +} + +// tokensFromShares returns the decimal tokens shares are worth at v's exchange +// rate, as x/staking's TokensFromShares does, or zero when v has no shares. +func (v validator) tokensFromShares(shares *big.Int) *big.Int { + if v.delegatorShares.Sign() == 0 { + return new(big.Int) + } + return quoDec(new(big.Int).Mul(shares, v.tokens), v.delegatorShares) +} + +// store is StakingStorage at the staking precompile's address. +type store struct { + solstorage.Store +} + +func newStore(state precompiles.State) store { + return store{solstorage.Store{State: state, Address: Address}} +} + +func at(base common.Hash, m member) common.Hash { + return solstorage.Offset(base, m.slot) +} + +// params returns staking's params from the params precompile. +func (s store) params() chainparams.Staking { + return chainparams.ReadStaking(s.State) +} + +func validatorBase(op common.Address) common.Hash { + return solstorage.MapAddress(solstorage.Slot(slotValidators), op) +} + +// validator returns operator op's validator, reporting whether it exists. +func (s store) validator(op common.Address) (validator, bool) { + base := validatorBase(op) + status := s.Uint8(at(base, validatorStatus), validatorStatus.offset) + if status == 0 { + return validator{}, false + } + return validator{ + consensusPubkey: s.Word(at(base, validatorConsensusPubkey)), + jailed: s.Bool(at(base, validatorJailed), validatorJailed.offset), + status: status, + tokens: s.Uint256(at(base, validatorTokens)), + delegatorShares: s.Uint256(at(base, validatorDelegatorShares)), + unbondingHeight: s.Uint64(at(base, validatorUnbondingHeight), validatorUnbondingHeight.offset), + unbondingTime: s.Uint64(at(base, validatorUnbondingTime), validatorUnbondingTime.offset), + minSelfDelegation: s.Uint256(at(base, validatorMinSelfDelegation)), + }, true +} + +func (s store) setValidator(op common.Address, v validator) { + base := validatorBase(op) + s.SetWord(at(base, validatorConsensusPubkey), v.consensusPubkey) + s.SetBool(at(base, validatorJailed), validatorJailed.offset, v.jailed) + s.SetUint8(at(base, validatorStatus), validatorStatus.offset, v.status) + s.SetUint256(at(base, validatorTokens), v.tokens) + s.SetUint256(at(base, validatorDelegatorShares), v.delegatorShares) + s.SetUint64(at(base, validatorUnbondingHeight), validatorUnbondingHeight.offset, v.unbondingHeight) + s.SetUint64(at(base, validatorUnbondingTime), validatorUnbondingTime.offset, v.unbondingTime) + s.SetUint256(at(base, validatorMinSelfDelegation), v.minSelfDelegation) +} + +// deleteValidator zeroes every slot of op's validator, including its +// description's spilled strings. +func (s store) deleteValidator(op common.Address) error { + base := validatorBase(op) + for _, m := range []member{validatorMoniker, validatorIdentity, validatorWebsite, validatorSecurityContact, validatorDetails} { + if err := s.SetString(at(base, m), ""); err != nil { + return err + } + } + for i := uint64(0); i < validatorSlots; i++ { + s.SetWord(solstorage.Offset(base, i), common.Hash{}) + } + return nil +} + +// validatorPower returns the consensus power of op's stored tokens. +func (s store) validatorPower(op common.Address) *big.Int { + return consensusPower(s.Uint256(at(validatorBase(op), validatorTokens))) +} + +func (s store) validatorSet() solstorage.Set { + return solstorage.Set{Store: s.Store, Base: solstorage.Slot(slotValidatorSet)} +} + +func validatorByPubkeySlot(pubkey common.Hash) common.Hash { + return solstorage.MapWord(solstorage.Slot(slotValidatorsByConsensusPubkey), pubkey) +} + +// validatorByPubkey returns the operator whose validator has consensus key +// pubkey, or the zero address. +func (s store) validatorByPubkey(pubkey common.Hash) common.Address { + return s.AddressAt(validatorByPubkeySlot(pubkey), 0) +} + +func (s store) setValidatorByPubkey(pubkey common.Hash, op common.Address) { + s.SetAddressAt(validatorByPubkeySlot(pubkey), 0, op) +} + +// validatorPower is StakingStorage.ValidatorPower. +type validatorPower struct { + operator common.Address + power uint64 +} + +// lastValidators returns the bonded set as last stored, failing on a set longer +// than any MaxValidators allows. +func (s store) lastValidators() ([]validatorPower, error) { + base := solstorage.Slot(slotLastValidators) + n := s.Uint64(base, 0) + if n > uint64(chainparams.MaxBondedValidators) { + return nil, fmt.Errorf("%w: %d validators", errInvalidStoredSet, n) + } + data := solstorage.ArrayData(base) + out := make([]validatorPower, n) + for i := range out { + slot := solstorage.Offset(data, uint64(i)) //nolint:gosec // i is below n + out[i] = validatorPower{ + operator: s.AddressAt(slot, validatorPowerOperator.offset), + power: s.Uint64(slot, validatorPowerPower.offset), + } + } + return out, nil +} + +// setLastValidators replaces the bonded set, zeroing elements the new set no +// longer covers. +func (s store) setLastValidators(set []validatorPower) { + base := solstorage.Slot(slotLastValidators) + old := min(s.Uint64(base, 0), uint64(chainparams.MaxBondedValidators)) + data := solstorage.ArrayData(base) + for i, v := range set { + slot := solstorage.Offset(data, uint64(i)) //nolint:gosec // i is non-negative + s.SetWord(slot, common.Hash{}) + s.SetAddressAt(slot, validatorPowerOperator.offset, v.operator) + s.SetUint64(slot, validatorPowerPower.offset, v.power) + } + for i := uint64(len(set)); i < old; i++ { + s.SetWord(solstorage.Offset(data, i), common.Hash{}) + } + s.SetWord(base, solstorage.Slot(uint64(len(set)))) +} + +// lastTotalPower returns the consensus power of the bonded set as last stored. +func (s store) lastTotalPower() *big.Int { + return s.Uint256(solstorage.Slot(slotLastTotalPower)) +} + +func (s store) setLastTotalPower(power *big.Int) { + s.SetUint256(solstorage.Slot(slotLastTotalPower), power) +} + +func delegationSlot(delegator, op common.Address) common.Hash { + return solstorage.MapAddress(solstorage.MapAddress(solstorage.Slot(slotDelegations), delegator), op) +} + +// delegatedValidators is the validators delegator delegates to. +func (s store) delegatedValidators(delegator common.Address) solstorage.Set { + return solstorage.Set{Store: s.Store, Base: solstorage.MapAddress(solstorage.Slot(slotDelegationsByDelegator), delegator)} +} + +// delegation returns delegator's shares in op and whether delegator delegates +// to op; a delegation can exist with no shares, as x/staking's can. +func (s store) delegation(delegator, op common.Address) (*big.Int, bool) { + shares := s.Uint256(delegationSlot(delegator, op)) + if shares.Sign() > 0 { + return shares, true + } + return shares, s.delegatedValidators(delegator).Contains(solstorage.AddressKey(op)) +} + +func (s store) setDelegation(delegator, op common.Address, shares *big.Int) { + s.SetUint256(delegationSlot(delegator, op), shares) + s.delegatedValidators(delegator).Add(solstorage.AddressKey(op)) +} + +func (s store) removeDelegation(delegator, op common.Address) { + s.SetUint256(delegationSlot(delegator, op), nil) + s.delegatedValidators(delegator).Remove(solstorage.AddressKey(op)) +} + +// unbondingEntry is StakingStorage.UnbondingDelegationEntry. +type unbondingEntry struct { + creationHeight uint64 + completionTime uint64 + initialBalance *big.Int + balance *big.Int +} + +func unbondingBase(delegator, op common.Address) common.Hash { + return solstorage.MapAddress(solstorage.MapAddress(solstorage.Slot(slotUnbondingDelegations), delegator), op) +} + +// unbondingEntryCount returns how many entries delegator's unbonding from op +// holds. +func (s store) unbondingEntryCount(delegator, op common.Address) uint64 { + return s.Uint64(unbondingBase(delegator, op), 0) +} + +// unbondingEntries returns delegator's unbonding entries from op, oldest first, +// failing on more entries than any MaxEntries allows. +func (s store) unbondingEntries(delegator, op common.Address) ([]unbondingEntry, error) { + base := unbondingBase(delegator, op) + data := solstorage.ArrayData(base) + n := s.Uint64(base, 0) + if n > math.MaxUint32 { + return nil, fmt.Errorf("%w: %d entries", errInvalidStoredEntries, n) + } + var out []unbondingEntry + for i := uint64(0); i < n && !s.State.Failed(); i++ { + e := solstorage.Offset(data, i*unbondingEntrySlots) + out = append(out, unbondingEntry{ + creationHeight: s.Uint64(at(e, unbondingEntryCreationHeight), unbondingEntryCreationHeight.offset), + completionTime: s.Uint64(at(e, unbondingEntryCompletionTime), unbondingEntryCompletionTime.offset), + initialBalance: s.Uint256(at(e, unbondingEntryInitialBalance)), + balance: s.Uint256(at(e, unbondingEntryBalance)), + }) + } + return out, nil +} + +// setUnbondingEntries replaces delegator's unbonding entries from op, zeroing +// the elements of the old entries that the new ones no longer cover. +func (s store) setUnbondingEntries(delegator, op common.Address, entries []unbondingEntry) { + base := unbondingBase(delegator, op) + data := solstorage.ArrayData(base) + old := s.Uint64(base, 0) + for i, entry := range entries { + s.setUnbondingEntry(solstorage.Offset(data, uint64(i)*unbondingEntrySlots), entry) //nolint:gosec // i is non-negative + } + for i := uint64(len(entries)) * unbondingEntrySlots; i < old*unbondingEntrySlots && !s.State.Failed(); i++ { + s.SetWord(solstorage.Offset(data, i), common.Hash{}) + } + s.SetWord(base, solstorage.Slot(uint64(len(entries)))) +} + +// appendUnbondingEntry adds entry after delegator's other unbonding entries +// from op. +func (s store) appendUnbondingEntry(delegator, op common.Address, entry unbondingEntry) { + base := unbondingBase(delegator, op) + n := s.Uint64(base, 0) + s.setUnbondingEntry(solstorage.Offset(solstorage.ArrayData(base), n*unbondingEntrySlots), entry) + s.SetWord(base, solstorage.Slot(n+1)) +} + +func (s store) setUnbondingEntry(e common.Hash, entry unbondingEntry) { + s.SetWord(at(e, unbondingEntryCreationHeight), common.Hash{}) + s.SetUint64(at(e, unbondingEntryCreationHeight), unbondingEntryCreationHeight.offset, entry.creationHeight) + s.SetUint64(at(e, unbondingEntryCompletionTime), unbondingEntryCompletionTime.offset, entry.completionTime) + s.SetUint256(at(e, unbondingEntryInitialBalance), entry.initialBalance) + s.SetUint256(at(e, unbondingEntryBalance), entry.balance) +} + +func redelegationCountSlot(delegator, src, dst common.Address) common.Hash { + return solstorage.MapAddress(solstorage.MapAddress(solstorage.MapAddress(solstorage.Slot(slotRedelegationEntryCounts), delegator), src), dst) +} + +// redelegationEntryCount returns how many of delegator's redelegations from +// src to dst have not completed. +func (s store) redelegationEntryCount(delegator, src, dst common.Address) *big.Int { + return s.Uint256(redelegationCountSlot(delegator, src, dst)) +} + +func (s store) setRedelegationEntryCount(delegator, src, dst common.Address, n *big.Int) { + s.SetUint256(redelegationCountSlot(delegator, src, dst), n) +} + +func receivingSlot(dst, delegator common.Address) common.Hash { + return solstorage.MapAddress(solstorage.MapAddress(solstorage.Slot(slotRedelegationsByValDst), dst), delegator) +} + +// receivingRedelegations returns how many of delegator's redelegations into dst +// have not completed. +func (s store) receivingRedelegations(dst, delegator common.Address) *big.Int { + return s.Uint256(receivingSlot(dst, delegator)) +} + +func (s store) setReceivingRedelegations(dst, delegator common.Address, n *big.Int) { + s.SetUint256(receivingSlot(dst, delegator), n) +} + +// queue is one of StakingStorage's first-in first-out queues: the entries at +// indexes [head, tail) of a mapping, each width slots and each beginning with +// its completion time, which never decreases along the queue. +type queue struct { + s store + bounds common.Hash + entries common.Hash + width uint64 +} + +func (s store) unbondingQueue() queue { + return queue{s, solstorage.Slot(slotUnbondingQueueBounds), solstorage.Slot(slotUnbondingQueue), unbondingQueueEntrySlots} +} + +// unbondingQueueEntry returns the delegator and validator unbonding queue entry +// e names. +func unbondingQueueEntry(s store, e common.Hash) (delegator, op common.Address) { + return s.AddressAt(at(e, unbondingQueueDelegator), unbondingQueueDelegator.offset), + s.AddressAt(at(e, unbondingQueueValidator), unbondingQueueValidator.offset) +} + +func (s store) redelegationQueue() queue { + return queue{s, solstorage.Slot(slotRedelegationQueueBounds), solstorage.Slot(slotRedelegationQueue), redelegationQueueEntrySlots} +} + +func (s store) validatorQueue() queue { + return queue{s, solstorage.Slot(slotValidatorQueueBounds), solstorage.Slot(slotValidatorQueue), validatorQueueEntrySlots} +} + +func (q queue) head() uint64 { + return q.s.Uint64(at(q.bounds, queueHead), queueHead.offset) +} + +func (q queue) tail() uint64 { + return q.s.Uint64(at(q.bounds, queueTail), queueTail.offset) +} + +// check fails when the queue's head is past its tail. +func (q queue) check() error { + if head, tail := q.head(), q.tail(); head > tail { + return fmt.Errorf("%w: head %d, tail %d", errQueueCorrupt, head, tail) + } + return nil +} + +func (q queue) entry(i uint64) common.Hash { + return solstorage.MapUint64(q.entries, i) +} + +// due returns the head entry's base slot if it completes at or before now. +func (q queue) due(now uint64) (common.Hash, bool) { + head := q.head() + if head >= q.tail() { + return common.Hash{}, false + } + e := q.entry(head) + if q.s.Uint64(at(e, queueCompletionTime), queueCompletionTime.offset) > now { + return common.Hash{}, false + } + return e, true +} + +// clamp returns t, or the last entry's completion time when that is later, so +// an entry pushed at the result keeps the queue in completion order. +func (q queue) clamp(t uint64) uint64 { + head, tail := q.head(), q.tail() + if tail <= head { + return t + } + return max(t, q.s.Uint64(at(q.entry(tail-1), queueCompletionTime), queueCompletionTime.offset)) +} + +// push appends an entry completing at t, which clamp must have returned, and +// returns its base slot for the caller to write the rest of. +func (q queue) push(t uint64) (common.Hash, error) { + tail := q.tail() + if tail == math.MaxUint64 { + return common.Hash{}, errQueueExhausted + } + e := q.entry(tail) + q.s.SetUint64(at(e, queueCompletionTime), queueCompletionTime.offset, t) + q.s.SetUint64(at(q.bounds, queueTail), queueTail.offset, tail+1) + return e, nil +} + +// pop zeroes the head entry and moves the head past it. +func (q queue) pop() { + head := q.head() + e := q.entry(head) + for i := uint64(0); i < q.width; i++ { + q.s.SetWord(solstorage.Offset(e, i), common.Hash{}) + } + q.s.SetUint64(at(q.bounds, queueHead), queueHead.offset, head+1) +} diff --git a/giga/evmonly/precompiles/staking/storage_test.go b/giga/evmonly/precompiles/staking/storage_test.go new file mode 100644 index 0000000000..855cc52c20 --- /dev/null +++ b/giga/evmonly/precompiles/staking/storage_test.go @@ -0,0 +1,32 @@ +package staking + +import ( + "testing" + + "github.com/ethereum/go-ethereum/common" + "github.com/stretchr/testify/require" + + "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles/solstorage" +) + +func TestUnbondingEntriesRejectAnImpossibleLength(t *testing.T) { + s := newStore(newMemState()) + s.SetWord(unbondingBase(alice, val1), solstorage.Slot(1<<32)) + _, err := s.unbondingEntries(alice, val1) + require.ErrorIs(t, err, errInvalidStoredEntries) +} + +func TestQueueClampsToItsLastEntry(t *testing.T) { + q := newStore(newMemState()).unbondingQueue() + require.Equal(t, uint64(5), q.clamp(5), "an empty queue takes any time") + _, err := q.push(10) + require.NoError(t, err) + require.Equal(t, uint64(10), q.clamp(5)) + require.Equal(t, uint64(11), q.clamp(11)) + q.pop() + require.Equal(t, q.head(), q.tail()) + require.Equal(t, uint64(5), q.clamp(5), "a drained queue takes any time") + _, ok := q.due(100) + require.False(t, ok) + require.Equal(t, common.Hash{}, q.s.Word(q.entry(0)), "pop zeroes the entry") +} diff --git a/giga/evmonly/precompiles/staking/testdata/StakingStorageHarness.bin-runtime b/giga/evmonly/precompiles/staking/testdata/StakingStorageHarness.bin-runtime new file mode 100644 index 0000000000..8a99b869d8 --- /dev/null +++ b/giga/evmonly/precompiles/staking/testdata/StakingStorageHarness.bin-runtime @@ -0,0 +1 @@ +608060405234801561000f575f5ffd5b5060043610610029575f3560e01c80633afaaf0e1461002d575b5f5ffd5b61004061003b366004610aa7565b610042565b005b6040805180820182526001600160a01b03868116808352601e60208085019182525f80546001808201835582805296517f290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563918201805495519188166001600160e01b031996871617600160a01b6001600160401b039384168102919091179091558951808b018b528d8916815260148187019081528554808c018755868052915191909401805494519190991693909616929092179416029290921790935560328455908152600280835290849020858155928301805461ffff19166102011790556801ae361fc1451c0000908301556f1812f9cf7920e2b66973e200000000006003830155825160608101909352603480845291929190610c429083013960048201906101709082610b87565b506040805180820190915260018152601960fa1b602082015260088201906101989082610b87565b506009810180546fffffffffffffffffffffffffffffffff1916682200000000000000211790556023600a820155600d81018054602467ffffffffffffffff199091161790556025600e8201556001600160a01b0384165f908152600260205260409020600101805461ff001916610300179055610217600386610a49565b610222600385610a49565b5f82815260056020908152604080832080546001600160a01b03808b166001600160a01b0319928316811790935560068054600181810183557ff652222313e28459528d920b65115c16c04f3efc82aaedc97be59f3f377c0d3f91820180548e861690871617905582549081019092550180549092168317909155871680855260078452828520918552908352818420602990558352600890915290206102c99086610a49565b60095f846001600160a01b03166001600160a01b031681526020019081526020015f205f866001600160a01b03166001600160a01b031681526020019081526020015f20604051806080016040528060336001600160401b0316815260200160346001600160401b03168152602001603581526020016036815250908060018154018082558091505060019003905f5260205f2090600302015f909190919091505f820151815f015f6101000a8154816001600160401b0302191690836001600160401b031602179055506020820151815f0160086101000a8154816001600160401b0302191690836001600160401b031602179055506040820151816001015560608201518160020155505060095f846001600160a01b03166001600160a01b031681526020019081526020015f205f866001600160a01b03166001600160a01b031681526020019081526020015f20604051806080016040528060376001600160401b0316815260200160386001600160401b0316815260200160398152602001603a815250908060018154018082558091505060019003905f5260205f2090600302015f909190919091505f820151815f015f6101000a8154816001600160401b0302191690836001600160401b031602179055506020820151815f0160086101000a8154816001600160401b0302191690836001600160401b03160217905550604082015181600101556060820151816002015550506002600a5f856001600160a01b03166001600160a01b031681526020019081526020015f205f876001600160a01b03166001600160a01b031681526020019081526020015f205f866001600160a01b03166001600160a01b031681526020019081526020015f20819055506003600b5f866001600160a01b03166001600160a01b031681526020019081526020015f205f856001600160a01b03166001600160a01b031681526020019081526020015f2081905550604051806040016040528060016001600160401b0316815260200160026001600160401b0316815250600c5f820151815f015f6101000a8154816001600160401b0302191690836001600160401b031602179055506020820151815f0160086101000a8154816001600160401b0302191690836001600160401b031602179055509050506040518060600160405280603d6001600160401b03168152602001846001600160a01b03168152602001866001600160a01b0316815250600d5f60016001600160401b031681526020019081526020015f205f820151815f015f6101000a8154816001600160401b0302191690836001600160401b031602179055506020820151815f0160086101000a8154816001600160a01b0302191690836001600160a01b031602179055506040820151816001015f6101000a8154816001600160a01b0302191690836001600160a01b0316021790555090505060405180604001604052805f6001600160401b0316815260200160016001600160401b0316815250600e5f820151815f015f6101000a8154816001600160401b0302191690836001600160401b031602179055506020820151815f0160086101000a8154816001600160401b0302191690836001600160401b031602179055509050506040518060e0016040528060476001600160401b03168152602001846001600160a01b0316815260200160486001600160401b03168152602001866001600160a01b03168152602001856001600160a01b0316815260200160498152602001604a815250600f5f5f6001600160401b031681526020019081526020015f205f820151815f015f6101000a8154816001600160401b0302191690836001600160401b031602179055506020820151815f0160086101000a8154816001600160a01b0302191690836001600160a01b031602179055506040820151816001015f6101000a8154816001600160401b0302191690836001600160401b0316021790555060608201518160010160086101000a8154816001600160a01b0302191690836001600160a01b031602179055506080820151816002015f6101000a8154816001600160a01b0302191690836001600160a01b0316021790555060a0820151816003015560c08201518160040155905050604051806040016040528060046001600160401b0316815260200160056001600160401b031681525060105f820151815f015f6101000a8154816001600160401b0302191690836001600160401b031602179055506020820151815f0160086101000a8154816001600160401b0302191690836001600160401b03160217905550905050604051806060016040528060516001600160401b0316815260200160526001600160401b03168152602001856001600160a01b031681525060115f60046001600160401b031681526020019081526020015f205f820151815f015f6101000a8154816001600160401b0302191690836001600160401b031602179055506020820151815f0160086101000a8154816001600160401b0302191690836001600160401b031602179055506040820151816001015f6101000a8154816001600160a01b0302191690836001600160a01b031602179055509050505050505050565b8154600181810184555f848152602080822090930180546001600160a01b039095166001600160a01b031990951685179055845493815293019052604090912055565b80356001600160a01b0381168114610aa2575f5ffd5b919050565b5f5f5f5f60808587031215610aba575f5ffd5b610ac385610a8c565b9350610ad160208601610a8c565b9250610adf60408601610a8c565b9396929550929360600135925050565b634e487b7160e01b5f52604160045260245ffd5b600181811c90821680610b1757607f821691505b602082108103610b3557634e487b7160e01b5f52602260045260245ffd5b50919050565b601f821115610b8257805f5260205f20601f840160051c81016020851015610b605750805b601f840160051c820191505b81811015610b7f575f8155600101610b6c565b50505b505050565b81516001600160401b03811115610ba057610ba0610aef565b610bb481610bae8454610b03565b84610b3b565b6020601f821160018114610be6575f8315610bcf5750848201515b5f19600385901b1c1916600184901b178455610b7f565b5f84815260208120601f198516915b82811015610c155787850151825560209485019460019092019101610bf5565b5084821015610c3257868401515f19600387901b60f8161c191681555b50505050600190811b0190555056fe61206d6f6e696b6572206c6f6e6720656e6f75676820746f207370696c6c2070617374206f6e652073746f7261676520776f7264a26469706673582212200bd261bbd131367b0cd28e69d1cce95e169395bac03866effa024dcaf4e3fe3f64736f6c634300081c0033 diff --git a/giga/evmonly/precompiles/staking/testdata/StakingStorageHarness.sol b/giga/evmonly/precompiles/staking/testdata/StakingStorageHarness.sol new file mode 100644 index 0000000000..77cabb347a --- /dev/null +++ b/giga/evmonly/precompiles/staking/testdata/StakingStorageHarness.sol @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.30; + +import "giga-storage/StakingStorage.sol"; + +/// @notice Writes known values into StakingStorage with solc's own codegen, so +/// the Go reader can be checked against the compiler's slot derivation. +contract StakingStorageHarness is StakingStorage { + function seed(address op, address other, address delegator, bytes32 pubkey) external { + lastValidators.push(ValidatorPower({operator: op, power: 30})); + lastValidators.push(ValidatorPower({operator: other, power: 20})); + lastTotalPower = 50; + + Validator storage v = validators[op]; + v.consensusPubkey = pubkey; + v.jailed = true; + v.status = 2; + v.tokens = 31e18; + v.delegatorShares = 32e36; + v.description.moniker = "a moniker long enough to spill past one storage word"; + v.description.details = "d"; + v.unbondingHeight = 33; + v.unbondingTime = 34; + v.commission.commissionRates.rate = 35; + v.commission.updateTime = 36; + v.minSelfDelegation = 37; + validators[other].status = 3; + add(validatorSet, op); + add(validatorSet, other); + validatorsByConsensusPubkey[pubkey] = op; + validatorsByPower.push(other); + validatorsByPower.push(op); + + delegations[delegator][op].shares = 41; + add(delegationsByDelegator[delegator], op); + + unbondingDelegations[delegator][op].push( + UnbondingDelegationEntry({creationHeight: 51, completionTime: 52, initialBalance: 53, balance: 54}) + ); + unbondingDelegations[delegator][op].push( + UnbondingDelegationEntry({creationHeight: 55, completionTime: 56, initialBalance: 57, balance: 58}) + ); + + redelegationEntryCounts[delegator][op][other] = 2; + redelegationsByValDst[other][delegator] = 3; + + unbondingQueueBounds = QueueBounds({head: 1, tail: 2}); + unbondingQueue[1] = UnbondingQueueEntry({completionTime: 61, delegator: delegator, validator: op}); + redelegationQueueBounds = QueueBounds({head: 0, tail: 1}); + redelegationQueue[0] = RedelegationQueueEntry({ + completionTime: 71, + delegator: delegator, + creationHeight: 72, + srcValidator: op, + dstValidator: other, + initialBalance: 73, + sharesDst: 74 + }); + validatorQueueBounds = QueueBounds({head: 4, tail: 5}); + validatorQueue[4] = ValidatorQueueEntry({completionTime: 81, unbondingHeight: 82, operator: other}); + } + + function add(AddressSet storage set, address a) internal { + set.values.push(a); + set.positions[a] = set.values.length; + } +} diff --git a/giga/evmonly/precompiles/staking/testdata/staking_storage_layout.json b/giga/evmonly/precompiles/staking/testdata/staking_storage_layout.json new file mode 100644 index 0000000000..9db0bef26d --- /dev/null +++ b/giga/evmonly/precompiles/staking/testdata/staking_storage_layout.json @@ -0,0 +1,771 @@ +{ + "storage": [ + { + "astId": 423, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "lastValidators", + "offset": 0, + "slot": "0", + "type": "t_array(t_struct(ValidatorPower)369_storage)dyn_storage" + }, + { + "astId": 425, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "lastTotalPower", + "offset": 0, + "slot": "1", + "type": "t_uint256" + }, + { + "astId": 430, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "validators", + "offset": 0, + "slot": "2", + "type": "t_mapping(t_address,t_struct(Validator)363_storage)" + }, + { + "astId": 433, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "validatorSet", + "offset": 0, + "slot": "3", + "type": "t_struct(AddressSet)518_storage" + }, + { + "astId": 437, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "validatorsByConsensusPubkey", + "offset": 0, + "slot": "5", + "type": "t_mapping(t_bytes32,t_address)" + }, + { + "astId": 440, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "validatorsByPower", + "offset": 0, + "slot": "6", + "type": "t_array(t_address)dyn_storage" + }, + { + "astId": 447, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "delegations", + "offset": 0, + "slot": "7", + "type": "t_mapping(t_address,t_mapping(t_address,t_struct(Delegation)372_storage))" + }, + { + "astId": 452, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "delegationsByDelegator", + "offset": 0, + "slot": "8", + "type": "t_mapping(t_address,t_struct(AddressSet)518_storage)" + }, + { + "astId": 460, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "unbondingDelegations", + "offset": 0, + "slot": "9", + "type": "t_mapping(t_address,t_mapping(t_address,t_array(t_struct(UnbondingDelegationEntry)381_storage)dyn_storage))" + }, + { + "astId": 468, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "redelegationEntryCounts", + "offset": 0, + "slot": "10", + "type": "t_mapping(t_address,t_mapping(t_address,t_mapping(t_address,t_uint256)))" + }, + { + "astId": 474, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "redelegationsByValDst", + "offset": 0, + "slot": "11", + "type": "t_mapping(t_address,t_mapping(t_address,t_uint256))" + }, + { + "astId": 477, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "unbondingQueueBounds", + "offset": 0, + "slot": "12", + "type": "t_struct(QueueBounds)419_storage" + }, + { + "astId": 482, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "unbondingQueue", + "offset": 0, + "slot": "13", + "type": "t_mapping(t_uint64,t_struct(UnbondingQueueEntry)389_storage)" + }, + { + "astId": 485, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "redelegationQueueBounds", + "offset": 0, + "slot": "14", + "type": "t_struct(QueueBounds)419_storage" + }, + { + "astId": 490, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "redelegationQueue", + "offset": 0, + "slot": "15", + "type": "t_mapping(t_uint64,t_struct(RedelegationQueueEntry)405_storage)" + }, + { + "astId": 493, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "validatorQueueBounds", + "offset": 0, + "slot": "16", + "type": "t_struct(QueueBounds)419_storage" + }, + { + "astId": 498, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "validatorQueue", + "offset": 0, + "slot": "17", + "type": "t_mapping(t_uint64,t_struct(ValidatorQueueEntry)413_storage)" + }, + { + "astId": 501, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "migrating", + "offset": 0, + "slot": "18", + "type": "t_bool" + }, + { + "astId": 503, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "migrationCursor", + "offset": 0, + "slot": "19", + "type": "t_bytes_storage" + }, + { + "astId": 506, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "migrationFailures", + "offset": 0, + "slot": "20", + "type": "t_array(t_bytes_storage)dyn_storage" + } + ], + "types": { + "t_address": { + "encoding": "inplace", + "label": "address", + "numberOfBytes": "20" + }, + "t_array(t_address)dyn_storage": { + "base": "t_address", + "encoding": "dynamic_array", + "label": "address[]", + "numberOfBytes": "32" + }, + "t_array(t_bytes_storage)dyn_storage": { + "base": "t_bytes_storage", + "encoding": "dynamic_array", + "label": "bytes[]", + "numberOfBytes": "32" + }, + "t_array(t_struct(UnbondingDelegationEntry)381_storage)dyn_storage": { + "base": "t_struct(UnbondingDelegationEntry)381_storage", + "encoding": "dynamic_array", + "label": "struct StakingStorage.UnbondingDelegationEntry[]", + "numberOfBytes": "32" + }, + "t_array(t_struct(ValidatorPower)369_storage)dyn_storage": { + "base": "t_struct(ValidatorPower)369_storage", + "encoding": "dynamic_array", + "label": "struct StakingStorage.ValidatorPower[]", + "numberOfBytes": "32" + }, + "t_array(t_uint256)8_storage": { + "base": "t_uint256", + "encoding": "inplace", + "label": "uint256[8]", + "numberOfBytes": "256" + }, + "t_bool": { + "encoding": "inplace", + "label": "bool", + "numberOfBytes": "1" + }, + "t_bytes32": { + "encoding": "inplace", + "label": "bytes32", + "numberOfBytes": "32" + }, + "t_bytes_storage": { + "encoding": "bytes", + "label": "bytes", + "numberOfBytes": "32" + }, + "t_mapping(t_address,t_array(t_struct(UnbondingDelegationEntry)381_storage)dyn_storage)": { + "encoding": "mapping", + "key": "t_address", + "label": "mapping(address => struct StakingStorage.UnbondingDelegationEntry[])", + "numberOfBytes": "32", + "value": "t_array(t_struct(UnbondingDelegationEntry)381_storage)dyn_storage" + }, + "t_mapping(t_address,t_mapping(t_address,t_array(t_struct(UnbondingDelegationEntry)381_storage)dyn_storage))": { + "encoding": "mapping", + "key": "t_address", + "label": "mapping(address => mapping(address => struct StakingStorage.UnbondingDelegationEntry[]))", + "numberOfBytes": "32", + "value": "t_mapping(t_address,t_array(t_struct(UnbondingDelegationEntry)381_storage)dyn_storage)" + }, + "t_mapping(t_address,t_mapping(t_address,t_mapping(t_address,t_uint256)))": { + "encoding": "mapping", + "key": "t_address", + "label": "mapping(address => mapping(address => mapping(address => uint256)))", + "numberOfBytes": "32", + "value": "t_mapping(t_address,t_mapping(t_address,t_uint256))" + }, + "t_mapping(t_address,t_mapping(t_address,t_struct(Delegation)372_storage))": { + "encoding": "mapping", + "key": "t_address", + "label": "mapping(address => mapping(address => struct StakingStorage.Delegation))", + "numberOfBytes": "32", + "value": "t_mapping(t_address,t_struct(Delegation)372_storage)" + }, + "t_mapping(t_address,t_mapping(t_address,t_uint256))": { + "encoding": "mapping", + "key": "t_address", + "label": "mapping(address => mapping(address => uint256))", + "numberOfBytes": "32", + "value": "t_mapping(t_address,t_uint256)" + }, + "t_mapping(t_address,t_struct(AddressSet)518_storage)": { + "encoding": "mapping", + "key": "t_address", + "label": "mapping(address => struct AddressSet)", + "numberOfBytes": "32", + "value": "t_struct(AddressSet)518_storage" + }, + "t_mapping(t_address,t_struct(Delegation)372_storage)": { + "encoding": "mapping", + "key": "t_address", + "label": "mapping(address => struct StakingStorage.Delegation)", + "numberOfBytes": "32", + "value": "t_struct(Delegation)372_storage" + }, + "t_mapping(t_address,t_struct(Validator)363_storage)": { + "encoding": "mapping", + "key": "t_address", + "label": "mapping(address => struct StakingStorage.Validator)", + "numberOfBytes": "32", + "value": "t_struct(Validator)363_storage" + }, + "t_mapping(t_address,t_uint256)": { + "encoding": "mapping", + "key": "t_address", + "label": "mapping(address => uint256)", + "numberOfBytes": "32", + "value": "t_uint256" + }, + "t_mapping(t_bytes32,t_address)": { + "encoding": "mapping", + "key": "t_bytes32", + "label": "mapping(bytes32 => address)", + "numberOfBytes": "32", + "value": "t_address" + }, + "t_mapping(t_uint64,t_struct(RedelegationQueueEntry)405_storage)": { + "encoding": "mapping", + "key": "t_uint64", + "label": "mapping(uint64 => struct StakingStorage.RedelegationQueueEntry)", + "numberOfBytes": "32", + "value": "t_struct(RedelegationQueueEntry)405_storage" + }, + "t_mapping(t_uint64,t_struct(UnbondingQueueEntry)389_storage)": { + "encoding": "mapping", + "key": "t_uint64", + "label": "mapping(uint64 => struct StakingStorage.UnbondingQueueEntry)", + "numberOfBytes": "32", + "value": "t_struct(UnbondingQueueEntry)389_storage" + }, + "t_mapping(t_uint64,t_struct(ValidatorQueueEntry)413_storage)": { + "encoding": "mapping", + "key": "t_uint64", + "label": "mapping(uint64 => struct StakingStorage.ValidatorQueueEntry)", + "numberOfBytes": "32", + "value": "t_struct(ValidatorQueueEntry)413_storage" + }, + "t_string_storage": { + "encoding": "bytes", + "label": "string", + "numberOfBytes": "32" + }, + "t_struct(AddressSet)518_storage": { + "encoding": "inplace", + "label": "struct AddressSet", + "members": [ + { + "astId": 513, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "values", + "offset": 0, + "slot": "0", + "type": "t_array(t_address)dyn_storage" + }, + { + "astId": 517, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "positions", + "offset": 0, + "slot": "1", + "type": "t_mapping(t_address,t_uint256)" + } + ], + "numberOfBytes": "64" + }, + "t_struct(Commission)336_storage": { + "encoding": "inplace", + "label": "struct StakingStorage.Commission", + "members": [ + { + "astId": 333, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "commissionRates", + "offset": 0, + "slot": "0", + "type": "t_struct(CommissionRates)330_storage" + }, + { + "astId": 335, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "updateTime", + "offset": 0, + "slot": "3", + "type": "t_uint64" + } + ], + "numberOfBytes": "128" + }, + "t_struct(CommissionRates)330_storage": { + "encoding": "inplace", + "label": "struct StakingStorage.CommissionRates", + "members": [ + { + "astId": 325, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "rate", + "offset": 0, + "slot": "0", + "type": "t_uint256" + }, + { + "astId": 327, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "maxRate", + "offset": 0, + "slot": "1", + "type": "t_uint256" + }, + { + "astId": 329, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "maxChangeRate", + "offset": 0, + "slot": "2", + "type": "t_uint256" + } + ], + "numberOfBytes": "96" + }, + "t_struct(Delegation)372_storage": { + "encoding": "inplace", + "label": "struct StakingStorage.Delegation", + "members": [ + { + "astId": 371, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "shares", + "offset": 0, + "slot": "0", + "type": "t_uint256" + } + ], + "numberOfBytes": "32" + }, + "t_struct(Description)323_storage": { + "encoding": "inplace", + "label": "struct StakingStorage.Description", + "members": [ + { + "astId": 314, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "moniker", + "offset": 0, + "slot": "0", + "type": "t_string_storage" + }, + { + "astId": 316, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "identity", + "offset": 0, + "slot": "1", + "type": "t_string_storage" + }, + { + "astId": 318, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "website", + "offset": 0, + "slot": "2", + "type": "t_string_storage" + }, + { + "astId": 320, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "securityContact", + "offset": 0, + "slot": "3", + "type": "t_string_storage" + }, + { + "astId": 322, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "details", + "offset": 0, + "slot": "4", + "type": "t_string_storage" + } + ], + "numberOfBytes": "160" + }, + "t_struct(QueueBounds)419_storage": { + "encoding": "inplace", + "label": "struct StakingStorage.QueueBounds", + "members": [ + { + "astId": 416, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "head", + "offset": 0, + "slot": "0", + "type": "t_uint64" + }, + { + "astId": 418, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "tail", + "offset": 8, + "slot": "0", + "type": "t_uint64" + } + ], + "numberOfBytes": "32" + }, + "t_struct(RedelegationQueueEntry)405_storage": { + "encoding": "inplace", + "label": "struct StakingStorage.RedelegationQueueEntry", + "members": [ + { + "astId": 392, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "completionTime", + "offset": 0, + "slot": "0", + "type": "t_uint64" + }, + { + "astId": 394, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "delegator", + "offset": 8, + "slot": "0", + "type": "t_address" + }, + { + "astId": 396, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "creationHeight", + "offset": 0, + "slot": "1", + "type": "t_uint64" + }, + { + "astId": 398, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "srcValidator", + "offset": 8, + "slot": "1", + "type": "t_address" + }, + { + "astId": 400, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "dstValidator", + "offset": 0, + "slot": "2", + "type": "t_address" + }, + { + "astId": 402, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "initialBalance", + "offset": 0, + "slot": "3", + "type": "t_uint256" + }, + { + "astId": 404, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "sharesDst", + "offset": 0, + "slot": "4", + "type": "t_uint256" + } + ], + "numberOfBytes": "160" + }, + "t_struct(UnbondingDelegationEntry)381_storage": { + "encoding": "inplace", + "label": "struct StakingStorage.UnbondingDelegationEntry", + "members": [ + { + "astId": 374, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "creationHeight", + "offset": 0, + "slot": "0", + "type": "t_uint64" + }, + { + "astId": 376, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "completionTime", + "offset": 8, + "slot": "0", + "type": "t_uint64" + }, + { + "astId": 378, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "initialBalance", + "offset": 0, + "slot": "1", + "type": "t_uint256" + }, + { + "astId": 380, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "balance", + "offset": 0, + "slot": "2", + "type": "t_uint256" + } + ], + "numberOfBytes": "96" + }, + "t_struct(UnbondingQueueEntry)389_storage": { + "encoding": "inplace", + "label": "struct StakingStorage.UnbondingQueueEntry", + "members": [ + { + "astId": 384, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "completionTime", + "offset": 0, + "slot": "0", + "type": "t_uint64" + }, + { + "astId": 386, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "delegator", + "offset": 8, + "slot": "0", + "type": "t_address" + }, + { + "astId": 388, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "validator", + "offset": 0, + "slot": "1", + "type": "t_address" + } + ], + "numberOfBytes": "64" + }, + "t_struct(Validator)363_storage": { + "encoding": "inplace", + "label": "struct StakingStorage.Validator", + "members": [ + { + "astId": 338, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "consensusPubkey", + "offset": 0, + "slot": "0", + "type": "t_bytes32" + }, + { + "astId": 340, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "jailed", + "offset": 0, + "slot": "1", + "type": "t_bool" + }, + { + "astId": 342, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "status", + "offset": 1, + "slot": "1", + "type": "t_uint8" + }, + { + "astId": 344, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "tokens", + "offset": 0, + "slot": "2", + "type": "t_uint256" + }, + { + "astId": 346, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "delegatorShares", + "offset": 0, + "slot": "3", + "type": "t_uint256" + }, + { + "astId": 349, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "description", + "offset": 0, + "slot": "4", + "type": "t_struct(Description)323_storage" + }, + { + "astId": 351, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "unbondingHeight", + "offset": 0, + "slot": "9", + "type": "t_uint64" + }, + { + "astId": 353, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "unbondingTime", + "offset": 8, + "slot": "9", + "type": "t_uint64" + }, + { + "astId": 356, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "commission", + "offset": 0, + "slot": "10", + "type": "t_struct(Commission)336_storage" + }, + { + "astId": 358, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "minSelfDelegation", + "offset": 0, + "slot": "14", + "type": "t_uint256" + }, + { + "astId": 362, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "__gap", + "offset": 0, + "slot": "15", + "type": "t_array(t_uint256)8_storage" + } + ], + "numberOfBytes": "736" + }, + "t_struct(ValidatorPower)369_storage": { + "encoding": "inplace", + "label": "struct StakingStorage.ValidatorPower", + "members": [ + { + "astId": 366, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "operator", + "offset": 0, + "slot": "0", + "type": "t_address" + }, + { + "astId": 368, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "power", + "offset": 20, + "slot": "0", + "type": "t_uint64" + } + ], + "numberOfBytes": "32" + }, + "t_struct(ValidatorQueueEntry)413_storage": { + "encoding": "inplace", + "label": "struct StakingStorage.ValidatorQueueEntry", + "members": [ + { + "astId": 408, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "completionTime", + "offset": 0, + "slot": "0", + "type": "t_uint64" + }, + { + "astId": 410, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "unbondingHeight", + "offset": 8, + "slot": "0", + "type": "t_uint64" + }, + { + "astId": 412, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "operator", + "offset": 0, + "slot": "1", + "type": "t_address" + } + ], + "numberOfBytes": "64" + }, + "t_uint256": { + "encoding": "inplace", + "label": "uint256", + "numberOfBytes": "32" + }, + "t_uint64": { + "encoding": "inplace", + "label": "uint64", + "numberOfBytes": "8" + }, + "t_uint8": { + "encoding": "inplace", + "label": "uint8", + "numberOfBytes": "1" + } + } +} diff --git a/giga/evmonly/precompiles/staking/validator.go b/giga/evmonly/precompiles/staking/validator.go new file mode 100644 index 0000000000..aa07b9e80e --- /dev/null +++ b/giga/evmonly/precompiles/staking/validator.go @@ -0,0 +1,132 @@ +package staking + +import ( + "bytes" + "fmt" + "math/big" + + "github.com/ethereum/go-ethereum/common" + + "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles/solstorage" +) + +// powerIndex is StakingStorage.validatorsByPower: every unjailed validator, +// highest consensus power first, ties to the lower address, as x/staking's +// power index iterates. Each operation takes the indexed power of the +// validator it moves, so it never reads that validator's tokens. +type powerIndex struct { + s store +} + +func (s store) powerIndex() powerIndex { + return powerIndex{s} +} + +func (p powerIndex) base() common.Hash { + return solstorage.Slot(slotValidatorsByPower) +} + +func (p powerIndex) len() uint64 { + return p.s.Uint64(p.base(), 0) +} + +// at returns the operator at index i, which must be below len. +func (p powerIndex) at(i uint64) common.Address { + return p.s.AddressAt(solstorage.Offset(solstorage.ArrayData(p.base()), i), 0) +} + +func (p powerIndex) set(i uint64, op common.Address) { + p.s.SetWord(solstorage.Offset(solstorage.ArrayData(p.base()), i), solstorage.AddressKey(op)) +} + +// ranksBefore reports whether a validator of power pa at a comes before one of +// power pb at b. +func ranksBefore(pa *big.Int, a common.Address, pb *big.Int, b common.Address) bool { + if c := pa.Cmp(pb); c != 0 { + return c > 0 + } + return bytes.Compare(a[:], b[:]) < 0 +} + +// search returns the first index whose validator does not rank before op at +// power, reading each probed validator's power from its tokens. +func (p powerIndex) search(op common.Address, power *big.Int) uint64 { + lo, hi := uint64(0), p.len() + for lo < hi && !p.s.State.Failed() { + mid := lo + (hi-lo)/2 + if v := p.at(mid); v != op && ranksBefore(p.s.validatorPower(v), v, power, op) { + lo = mid + 1 + } else { + hi = mid + } + } + return lo +} + +// find returns op's index, where its indexed power places it. +func (p powerIndex) find(op common.Address, indexed *big.Int) (uint64, error) { + i := p.search(op, indexed) + if i >= p.len() || p.at(i) != op { + return 0, fmt.Errorf("%w: %s", errPowerIndexCorrupt, op) + } + return i, nil +} + +// insert adds op at power. +func (p powerIndex) insert(op common.Address, power *big.Int) { + i, n := p.search(op, power), p.len() + for j := n; j > i && !p.s.State.Failed(); j-- { + p.set(j, p.at(j-1)) + } + p.set(i, op) + p.s.SetWord(p.base(), solstorage.Slot(n+1)) +} + +// remove takes out op, indexed at power. +func (p powerIndex) remove(op common.Address, indexed *big.Int) error { + i, err := p.find(op, indexed) + if err != nil { + return err + } + n := p.len() + for j := i; j+1 < n && !p.s.State.Failed(); j++ { + p.set(j, p.at(j+1)) + } + p.s.SetWord(solstorage.Offset(solstorage.ArrayData(p.base()), n-1), common.Hash{}) + p.s.SetWord(p.base(), solstorage.Slot(n-1)) + return nil +} + +// move reorders op from indexed power from to power to, one write per +// validator it passes. +func (p powerIndex) move(op common.Address, from, to *big.Int) error { + if from.Cmp(to) == 0 { + return nil + } + start, err := p.find(op, from) + if err != nil { + return err + } + i := start + if to.Cmp(from) > 0 { + for ; i > 0 && !p.s.State.Failed(); i-- { + prev := p.at(i - 1) + if !ranksBefore(to, op, p.s.validatorPower(prev), prev) { + break + } + p.set(i, prev) + } + } else { + for n := p.len(); i+1 < n && !p.s.State.Failed(); i++ { + next := p.at(i + 1) + if !ranksBefore(p.s.validatorPower(next), next, to, op) { + break + } + p.set(i, next) + } + } + if i != start { + p.set(i, op) + } + return nil +} From edf039078f566133519ead50dd0bc00680607a46 Mon Sep 17 00:00:00 2001 From: Tony Chen Date: Mon, 9 Nov 2026 12:00:00 +0800 Subject: [PATCH 11/44] refactor(params): take MaxBondedValidators from autobahn's committee cap Co-Authored-By: Claude Opus 5.5 --- giga/evmonly/precompiles/params/staking.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/giga/evmonly/precompiles/params/staking.go b/giga/evmonly/precompiles/params/staking.go index 35c8772e98..ddb16282f1 100644 --- a/giga/evmonly/precompiles/params/staking.go +++ b/giga/evmonly/precompiles/params/staking.go @@ -6,6 +6,7 @@ import ( "math/big" "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles" + atypes "github.com/sei-protocol/sei-chain/sei-tendermint/autobahn/types" ) // Staking's flat keys. @@ -95,7 +96,7 @@ func (s Staking) values() values { // MaxBondedValidators is the most validators MaxValidators may bond: the most // members an autobahn committee holds. -const MaxBondedValidators uint32 = 100 +const MaxBondedValidators uint32 = atypes.MaxValidators // Validate checks s as x/staking checks its params, and also requires an // unbonding time of MinPeriod to MaxPeriod and at most MaxBondedValidators From 8bafe18b7da6e58e82808989053b7adff7afea01 Mon Sep 17 00:00:00 2001 From: Tony Chen Date: Thu, 5 Nov 2026 13:12:33 +0800 Subject: [PATCH 12/44] feat(staking): store a validator in 15 slots Validator no longer reserves a __gap, so it takes 15 slots and deleteValidator zeroes those. The layout testdata is regenerated; the harness bytecode never writes the gap and is unchanged. Co-Authored-By: Claude Opus 5.5 --- giga/evmonly/precompiles/staking/layout.go | 3 +- .../precompiles/staking/layout_test.go | 1 - .../testdata/staking_storage_layout.json | 190 ++++++++---------- 3 files changed, 89 insertions(+), 105 deletions(-) diff --git a/giga/evmonly/precompiles/staking/layout.go b/giga/evmonly/precompiles/staking/layout.go index 331bb3e115..a8a4bf8eb9 100644 --- a/giga/evmonly/precompiles/staking/layout.go +++ b/giga/evmonly/precompiles/staking/layout.go @@ -54,11 +54,10 @@ var ( validatorCommissionMaxChange = member{12, 0} validatorCommissionUpdate = member{13, 0} validatorMinSelfDelegation = member{14, 0} - validatorGap = member{15, 0} ) // validatorSlots is how many slots a StakingStorage.Validator takes. -const validatorSlots = 23 +const validatorSlots = 15 // StakingStorage.ValidatorPower members. var ( diff --git a/giga/evmonly/precompiles/staking/layout_test.go b/giga/evmonly/precompiles/staking/layout_test.go index 722468f085..bd5933ba76 100644 --- a/giga/evmonly/precompiles/staking/layout_test.go +++ b/giga/evmonly/precompiles/staking/layout_test.go @@ -88,7 +88,6 @@ func TestLayoutMatchesSolc(t *testing.T) { "unbondingTime": validatorUnbondingTime, "commission": validatorCommissionRate, "minSelfDelegation": validatorMinSelfDelegation, - "__gap": validatorGap, }, validatorSlots}, "struct StakingStorage.Description": {map[string]member{ "moniker": sub(validatorMoniker, validatorMoniker), diff --git a/giga/evmonly/precompiles/staking/testdata/staking_storage_layout.json b/giga/evmonly/precompiles/staking/testdata/staking_storage_layout.json index 9db0bef26d..31556305d8 100644 --- a/giga/evmonly/precompiles/staking/testdata/staking_storage_layout.json +++ b/giga/evmonly/precompiles/staking/testdata/staking_storage_layout.json @@ -1,15 +1,15 @@ { "storage": [ { - "astId": 423, + "astId": 419, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "lastValidators", "offset": 0, "slot": "0", - "type": "t_array(t_struct(ValidatorPower)369_storage)dyn_storage" + "type": "t_array(t_struct(ValidatorPower)365_storage)dyn_storage" }, { - "astId": 425, + "astId": 421, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "lastTotalPower", "offset": 0, @@ -17,23 +17,23 @@ "type": "t_uint256" }, { - "astId": 430, + "astId": 426, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "validators", "offset": 0, "slot": "2", - "type": "t_mapping(t_address,t_struct(Validator)363_storage)" + "type": "t_mapping(t_address,t_struct(Validator)359_storage)" }, { - "astId": 433, + "astId": 429, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "validatorSet", "offset": 0, "slot": "3", - "type": "t_struct(AddressSet)518_storage" + "type": "t_struct(AddressSet)514_storage" }, { - "astId": 437, + "astId": 433, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "validatorsByConsensusPubkey", "offset": 0, @@ -41,7 +41,7 @@ "type": "t_mapping(t_bytes32,t_address)" }, { - "astId": 440, + "astId": 436, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "validatorsByPower", "offset": 0, @@ -49,31 +49,31 @@ "type": "t_array(t_address)dyn_storage" }, { - "astId": 447, + "astId": 443, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "delegations", "offset": 0, "slot": "7", - "type": "t_mapping(t_address,t_mapping(t_address,t_struct(Delegation)372_storage))" + "type": "t_mapping(t_address,t_mapping(t_address,t_struct(Delegation)368_storage))" }, { - "astId": 452, + "astId": 448, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "delegationsByDelegator", "offset": 0, "slot": "8", - "type": "t_mapping(t_address,t_struct(AddressSet)518_storage)" + "type": "t_mapping(t_address,t_struct(AddressSet)514_storage)" }, { - "astId": 460, + "astId": 456, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "unbondingDelegations", "offset": 0, "slot": "9", - "type": "t_mapping(t_address,t_mapping(t_address,t_array(t_struct(UnbondingDelegationEntry)381_storage)dyn_storage))" + "type": "t_mapping(t_address,t_mapping(t_address,t_array(t_struct(UnbondingDelegationEntry)377_storage)dyn_storage))" }, { - "astId": 468, + "astId": 464, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "redelegationEntryCounts", "offset": 0, @@ -81,7 +81,7 @@ "type": "t_mapping(t_address,t_mapping(t_address,t_mapping(t_address,t_uint256)))" }, { - "astId": 474, + "astId": 470, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "redelegationsByValDst", "offset": 0, @@ -89,55 +89,55 @@ "type": "t_mapping(t_address,t_mapping(t_address,t_uint256))" }, { - "astId": 477, + "astId": 473, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "unbondingQueueBounds", "offset": 0, "slot": "12", - "type": "t_struct(QueueBounds)419_storage" + "type": "t_struct(QueueBounds)415_storage" }, { - "astId": 482, + "astId": 478, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "unbondingQueue", "offset": 0, "slot": "13", - "type": "t_mapping(t_uint64,t_struct(UnbondingQueueEntry)389_storage)" + "type": "t_mapping(t_uint64,t_struct(UnbondingQueueEntry)385_storage)" }, { - "astId": 485, + "astId": 481, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "redelegationQueueBounds", "offset": 0, "slot": "14", - "type": "t_struct(QueueBounds)419_storage" + "type": "t_struct(QueueBounds)415_storage" }, { - "astId": 490, + "astId": 486, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "redelegationQueue", "offset": 0, "slot": "15", - "type": "t_mapping(t_uint64,t_struct(RedelegationQueueEntry)405_storage)" + "type": "t_mapping(t_uint64,t_struct(RedelegationQueueEntry)401_storage)" }, { - "astId": 493, + "astId": 489, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "validatorQueueBounds", "offset": 0, "slot": "16", - "type": "t_struct(QueueBounds)419_storage" + "type": "t_struct(QueueBounds)415_storage" }, { - "astId": 498, + "astId": 494, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "validatorQueue", "offset": 0, "slot": "17", - "type": "t_mapping(t_uint64,t_struct(ValidatorQueueEntry)413_storage)" + "type": "t_mapping(t_uint64,t_struct(ValidatorQueueEntry)409_storage)" }, { - "astId": 501, + "astId": 497, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "migrating", "offset": 0, @@ -145,7 +145,7 @@ "type": "t_bool" }, { - "astId": 503, + "astId": 499, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "migrationCursor", "offset": 0, @@ -153,7 +153,7 @@ "type": "t_bytes_storage" }, { - "astId": 506, + "astId": 502, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "migrationFailures", "offset": 0, @@ -179,24 +179,18 @@ "label": "bytes[]", "numberOfBytes": "32" }, - "t_array(t_struct(UnbondingDelegationEntry)381_storage)dyn_storage": { - "base": "t_struct(UnbondingDelegationEntry)381_storage", + "t_array(t_struct(UnbondingDelegationEntry)377_storage)dyn_storage": { + "base": "t_struct(UnbondingDelegationEntry)377_storage", "encoding": "dynamic_array", "label": "struct StakingStorage.UnbondingDelegationEntry[]", "numberOfBytes": "32" }, - "t_array(t_struct(ValidatorPower)369_storage)dyn_storage": { - "base": "t_struct(ValidatorPower)369_storage", + "t_array(t_struct(ValidatorPower)365_storage)dyn_storage": { + "base": "t_struct(ValidatorPower)365_storage", "encoding": "dynamic_array", "label": "struct StakingStorage.ValidatorPower[]", "numberOfBytes": "32" }, - "t_array(t_uint256)8_storage": { - "base": "t_uint256", - "encoding": "inplace", - "label": "uint256[8]", - "numberOfBytes": "256" - }, "t_bool": { "encoding": "inplace", "label": "bool", @@ -212,19 +206,19 @@ "label": "bytes", "numberOfBytes": "32" }, - "t_mapping(t_address,t_array(t_struct(UnbondingDelegationEntry)381_storage)dyn_storage)": { + "t_mapping(t_address,t_array(t_struct(UnbondingDelegationEntry)377_storage)dyn_storage)": { "encoding": "mapping", "key": "t_address", "label": "mapping(address => struct StakingStorage.UnbondingDelegationEntry[])", "numberOfBytes": "32", - "value": "t_array(t_struct(UnbondingDelegationEntry)381_storage)dyn_storage" + "value": "t_array(t_struct(UnbondingDelegationEntry)377_storage)dyn_storage" }, - "t_mapping(t_address,t_mapping(t_address,t_array(t_struct(UnbondingDelegationEntry)381_storage)dyn_storage))": { + "t_mapping(t_address,t_mapping(t_address,t_array(t_struct(UnbondingDelegationEntry)377_storage)dyn_storage))": { "encoding": "mapping", "key": "t_address", "label": "mapping(address => mapping(address => struct StakingStorage.UnbondingDelegationEntry[]))", "numberOfBytes": "32", - "value": "t_mapping(t_address,t_array(t_struct(UnbondingDelegationEntry)381_storage)dyn_storage)" + "value": "t_mapping(t_address,t_array(t_struct(UnbondingDelegationEntry)377_storage)dyn_storage)" }, "t_mapping(t_address,t_mapping(t_address,t_mapping(t_address,t_uint256)))": { "encoding": "mapping", @@ -233,12 +227,12 @@ "numberOfBytes": "32", "value": "t_mapping(t_address,t_mapping(t_address,t_uint256))" }, - "t_mapping(t_address,t_mapping(t_address,t_struct(Delegation)372_storage))": { + "t_mapping(t_address,t_mapping(t_address,t_struct(Delegation)368_storage))": { "encoding": "mapping", "key": "t_address", "label": "mapping(address => mapping(address => struct StakingStorage.Delegation))", "numberOfBytes": "32", - "value": "t_mapping(t_address,t_struct(Delegation)372_storage)" + "value": "t_mapping(t_address,t_struct(Delegation)368_storage)" }, "t_mapping(t_address,t_mapping(t_address,t_uint256))": { "encoding": "mapping", @@ -247,26 +241,26 @@ "numberOfBytes": "32", "value": "t_mapping(t_address,t_uint256)" }, - "t_mapping(t_address,t_struct(AddressSet)518_storage)": { + "t_mapping(t_address,t_struct(AddressSet)514_storage)": { "encoding": "mapping", "key": "t_address", "label": "mapping(address => struct AddressSet)", "numberOfBytes": "32", - "value": "t_struct(AddressSet)518_storage" + "value": "t_struct(AddressSet)514_storage" }, - "t_mapping(t_address,t_struct(Delegation)372_storage)": { + "t_mapping(t_address,t_struct(Delegation)368_storage)": { "encoding": "mapping", "key": "t_address", "label": "mapping(address => struct StakingStorage.Delegation)", "numberOfBytes": "32", - "value": "t_struct(Delegation)372_storage" + "value": "t_struct(Delegation)368_storage" }, - "t_mapping(t_address,t_struct(Validator)363_storage)": { + "t_mapping(t_address,t_struct(Validator)359_storage)": { "encoding": "mapping", "key": "t_address", "label": "mapping(address => struct StakingStorage.Validator)", "numberOfBytes": "32", - "value": "t_struct(Validator)363_storage" + "value": "t_struct(Validator)359_storage" }, "t_mapping(t_address,t_uint256)": { "encoding": "mapping", @@ -282,38 +276,38 @@ "numberOfBytes": "32", "value": "t_address" }, - "t_mapping(t_uint64,t_struct(RedelegationQueueEntry)405_storage)": { + "t_mapping(t_uint64,t_struct(RedelegationQueueEntry)401_storage)": { "encoding": "mapping", "key": "t_uint64", "label": "mapping(uint64 => struct StakingStorage.RedelegationQueueEntry)", "numberOfBytes": "32", - "value": "t_struct(RedelegationQueueEntry)405_storage" + "value": "t_struct(RedelegationQueueEntry)401_storage" }, - "t_mapping(t_uint64,t_struct(UnbondingQueueEntry)389_storage)": { + "t_mapping(t_uint64,t_struct(UnbondingQueueEntry)385_storage)": { "encoding": "mapping", "key": "t_uint64", "label": "mapping(uint64 => struct StakingStorage.UnbondingQueueEntry)", "numberOfBytes": "32", - "value": "t_struct(UnbondingQueueEntry)389_storage" + "value": "t_struct(UnbondingQueueEntry)385_storage" }, - "t_mapping(t_uint64,t_struct(ValidatorQueueEntry)413_storage)": { + "t_mapping(t_uint64,t_struct(ValidatorQueueEntry)409_storage)": { "encoding": "mapping", "key": "t_uint64", "label": "mapping(uint64 => struct StakingStorage.ValidatorQueueEntry)", "numberOfBytes": "32", - "value": "t_struct(ValidatorQueueEntry)413_storage" + "value": "t_struct(ValidatorQueueEntry)409_storage" }, "t_string_storage": { "encoding": "bytes", "label": "string", "numberOfBytes": "32" }, - "t_struct(AddressSet)518_storage": { + "t_struct(AddressSet)514_storage": { "encoding": "inplace", "label": "struct AddressSet", "members": [ { - "astId": 513, + "astId": 509, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "values", "offset": 0, @@ -321,7 +315,7 @@ "type": "t_array(t_address)dyn_storage" }, { - "astId": 517, + "astId": 513, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "positions", "offset": 0, @@ -385,12 +379,12 @@ ], "numberOfBytes": "96" }, - "t_struct(Delegation)372_storage": { + "t_struct(Delegation)368_storage": { "encoding": "inplace", "label": "struct StakingStorage.Delegation", "members": [ { - "astId": 371, + "astId": 367, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "shares", "offset": 0, @@ -447,12 +441,12 @@ ], "numberOfBytes": "160" }, - "t_struct(QueueBounds)419_storage": { + "t_struct(QueueBounds)415_storage": { "encoding": "inplace", "label": "struct StakingStorage.QueueBounds", "members": [ { - "astId": 416, + "astId": 412, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "head", "offset": 0, @@ -460,7 +454,7 @@ "type": "t_uint64" }, { - "astId": 418, + "astId": 414, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "tail", "offset": 8, @@ -470,12 +464,12 @@ ], "numberOfBytes": "32" }, - "t_struct(RedelegationQueueEntry)405_storage": { + "t_struct(RedelegationQueueEntry)401_storage": { "encoding": "inplace", "label": "struct StakingStorage.RedelegationQueueEntry", "members": [ { - "astId": 392, + "astId": 388, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "completionTime", "offset": 0, @@ -483,7 +477,7 @@ "type": "t_uint64" }, { - "astId": 394, + "astId": 390, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "delegator", "offset": 8, @@ -491,7 +485,7 @@ "type": "t_address" }, { - "astId": 396, + "astId": 392, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "creationHeight", "offset": 0, @@ -499,7 +493,7 @@ "type": "t_uint64" }, { - "astId": 398, + "astId": 394, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "srcValidator", "offset": 8, @@ -507,7 +501,7 @@ "type": "t_address" }, { - "astId": 400, + "astId": 396, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "dstValidator", "offset": 0, @@ -515,7 +509,7 @@ "type": "t_address" }, { - "astId": 402, + "astId": 398, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "initialBalance", "offset": 0, @@ -523,7 +517,7 @@ "type": "t_uint256" }, { - "astId": 404, + "astId": 400, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "sharesDst", "offset": 0, @@ -533,12 +527,12 @@ ], "numberOfBytes": "160" }, - "t_struct(UnbondingDelegationEntry)381_storage": { + "t_struct(UnbondingDelegationEntry)377_storage": { "encoding": "inplace", "label": "struct StakingStorage.UnbondingDelegationEntry", "members": [ { - "astId": 374, + "astId": 370, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "creationHeight", "offset": 0, @@ -546,7 +540,7 @@ "type": "t_uint64" }, { - "astId": 376, + "astId": 372, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "completionTime", "offset": 8, @@ -554,7 +548,7 @@ "type": "t_uint64" }, { - "astId": 378, + "astId": 374, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "initialBalance", "offset": 0, @@ -562,7 +556,7 @@ "type": "t_uint256" }, { - "astId": 380, + "astId": 376, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "balance", "offset": 0, @@ -572,12 +566,12 @@ ], "numberOfBytes": "96" }, - "t_struct(UnbondingQueueEntry)389_storage": { + "t_struct(UnbondingQueueEntry)385_storage": { "encoding": "inplace", "label": "struct StakingStorage.UnbondingQueueEntry", "members": [ { - "astId": 384, + "astId": 380, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "completionTime", "offset": 0, @@ -585,7 +579,7 @@ "type": "t_uint64" }, { - "astId": 386, + "astId": 382, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "delegator", "offset": 8, @@ -593,7 +587,7 @@ "type": "t_address" }, { - "astId": 388, + "astId": 384, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "validator", "offset": 0, @@ -603,7 +597,7 @@ ], "numberOfBytes": "64" }, - "t_struct(Validator)363_storage": { + "t_struct(Validator)359_storage": { "encoding": "inplace", "label": "struct StakingStorage.Validator", "members": [ @@ -686,24 +680,16 @@ "offset": 0, "slot": "14", "type": "t_uint256" - }, - { - "astId": 362, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", - "label": "__gap", - "offset": 0, - "slot": "15", - "type": "t_array(t_uint256)8_storage" } ], - "numberOfBytes": "736" + "numberOfBytes": "480" }, - "t_struct(ValidatorPower)369_storage": { + "t_struct(ValidatorPower)365_storage": { "encoding": "inplace", "label": "struct StakingStorage.ValidatorPower", "members": [ { - "astId": 366, + "astId": 362, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "operator", "offset": 0, @@ -711,7 +697,7 @@ "type": "t_address" }, { - "astId": 368, + "astId": 364, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "power", "offset": 20, @@ -721,12 +707,12 @@ ], "numberOfBytes": "32" }, - "t_struct(ValidatorQueueEntry)413_storage": { + "t_struct(ValidatorQueueEntry)409_storage": { "encoding": "inplace", "label": "struct StakingStorage.ValidatorQueueEntry", "members": [ { - "astId": 408, + "astId": 404, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "completionTime", "offset": 0, @@ -734,7 +720,7 @@ "type": "t_uint64" }, { - "astId": 410, + "astId": 406, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "unbondingHeight", "offset": 8, @@ -742,7 +728,7 @@ "type": "t_uint64" }, { - "astId": 412, + "astId": 408, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "operator", "offset": 0, From ebe97e095fd2048a1404386ae2fb8c0a518dc704 Mon Sep 17 00:00:00 2001 From: Tony Chen Date: Wed, 4 Nov 2026 17:16:14 +0800 Subject: [PATCH 13/44] feat(staking): delegate, redelegate and undelegate in a precompile - Add the staking precompile at 0x1005 over its storage: delegate (payable), redelegate and undelegate, by address and in whole usei. V2's string forms and authz methods keep their selectors and revert naming the replacement. - Port x/staking's share math, minSelfDelegation jailing, Sei's max voting power ratio, the maxEntries limits, transitive redelegation refusal, and the bonded/not-bonded escrow moves. - EndBlock applies the bonded set from the sorted power index, then completes the validator, unbonding and redelegation queues under a per-queue budget. Each step runs under a snapshot; a failure is reverted and reported as degraded. - Add Hooks at StakingHooks' points, and genesis SetParams and AddGenesisValidator. Not yet registered in evmonlyapp. Co-Authored-By: Claude Opus 5.5 --- giga/evmonly/precompiles/staking/Staking.sol | 91 +++++ giga/evmonly/precompiles/staking/abi.json | 385 ++++++++++++++++++ .../evmonly/precompiles/staking/delegation.go | 377 +++++++++++++++++ giga/evmonly/precompiles/staking/endblock.go | 253 ++++++++++++ .../precompiles/staking/endblock_test.go | 260 ++++++++++++ giga/evmonly/precompiles/staking/genesis.go | 109 +++++ .../precompiles/staking/helpers_test.go | 232 +++++++++++ giga/evmonly/precompiles/staking/hooks.go | 67 +++ giga/evmonly/precompiles/staking/staking.go | 171 ++++++++ .../precompiles/staking/staking_test.go | 344 ++++++++++++++++ giga/evmonly/precompiles/staking/validator.go | 108 +++++ giga/evmonly/staking_precompile_test.go | 146 +++++++ 12 files changed, 2543 insertions(+) create mode 100644 giga/evmonly/precompiles/staking/Staking.sol create mode 100644 giga/evmonly/precompiles/staking/abi.json create mode 100644 giga/evmonly/precompiles/staking/delegation.go create mode 100644 giga/evmonly/precompiles/staking/endblock.go create mode 100644 giga/evmonly/precompiles/staking/endblock_test.go create mode 100644 giga/evmonly/precompiles/staking/genesis.go create mode 100644 giga/evmonly/precompiles/staking/hooks.go create mode 100644 giga/evmonly/precompiles/staking/staking.go create mode 100644 giga/evmonly/precompiles/staking/staking_test.go create mode 100644 giga/evmonly/staking_precompile_test.go diff --git a/giga/evmonly/precompiles/staking/Staking.sol b/giga/evmonly/precompiles/staking/Staking.sol new file mode 100644 index 0000000000..186d170e3d --- /dev/null +++ b/giga/evmonly/precompiles/staking/Staking.sol @@ -0,0 +1,91 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.30; + +address constant STAKING_PRECOMPILE_ADDRESS = 0x0000000000000000000000000000000000001005; + +IStaking constant STAKING_CONTRACT = IStaking(STAKING_PRECOMPILE_ADDRESS); + +/// @notice The EVM-only staking precompile. Validators are named by their +/// operator's address, amounts are wei and must be a positive whole number of +/// usei, and times are Unix nanoseconds. +/// @dev An argument out of range, such as a zero amount or one that is not whole +/// usei, reverts with an Error(string) naming it; a call that fails against the +/// current state, such as undelegating more than is delegated, fails with no +/// revert data and uses its gas. A method marked "Reverts:" is kept so a caller +/// of a V2 method gets a revert whose Error(string) names the call to use +/// instead, or says the operation is not supported. The address holds no code; +/// solc 0.8.10 and later call it without checking for code because every method +/// returns data. Calldata over 20 KiB fails the call and uses its gas. +interface IStaking { + /// @notice The caller delegated amount to validator for shares, 1e18-scaled. + event Delegate(address indexed delegator, address indexed validator, uint256 amount, uint256 shares); + + /// @notice The caller moved amount from srcValidator to dstValidator. The + /// stake moved at once; completionTime is when the move stops counting toward + /// maxEntries and stops blocking a redelegation out of dstValidator, or 0 when + /// it never did, because srcValidator was unbonded. + event Redelegate( + address indexed delegator, + address indexed srcValidator, + address indexed dstValidator, + uint256 amount, + uint64 completionTime + ); + + /// @notice The caller undelegated from validator. amount is the tokens its + /// shares were worth, paid to the caller at the first block at or after + /// completionTime. + event Undelegate(address indexed delegator, address indexed validator, uint256 amount, uint64 completionTime); + + /// @notice Delegates msg.value to validator. + function delegate(address validator) external payable returns (bool success); + + /// @notice Moves amount of the caller's delegation from srcValidator to + /// dstValidator, as x/staking's MsgBeginRedelegate does. + function redelegate(address srcValidator, address dstValidator, uint256 amount) external returns (bool success); + + /// @notice Undelegates amount from validator, as x/staking's MsgUndelegate + /// does. The tokens are paid once the unbonding period ends. + function undelegate(address validator, uint256 amount) external returns (bool success); + + /// @notice Reverts: use delegate(address). + function delegate(string memory valAddress) external payable returns (bool success); + + /// @notice Reverts: use redelegate(address,address,uint256). + function redelegate(string memory srcAddress, string memory dstAddress, uint256 amount) + external + returns (bool success); + + /// @notice Reverts: use undelegate(address,uint256). + function undelegate(string memory valAddress, uint256 amount) external returns (bool success); + + /// @notice Reverts: staking authorizations are not supported. + function grantStakingAuthorization( + address grantee, + string[] memory allowedValidators, + uint256 maxTokens, + int64 expiration + ) external returns (bool success); + + /// @notice Reverts: staking authorizations are not supported. + function delegateWithAuthorization(address delegator, string memory valAddress) + external + payable + returns (bool success); + + /// @notice Reverts: staking authorizations are not supported. + function redelegateWithAuthorization( + address delegator, + string memory srcAddress, + string memory dstAddress, + uint256 amount + ) external returns (bool success); + + /// @notice Reverts: staking authorizations are not supported. + function undelegateWithAuthorization(address delegator, string memory valAddress, uint256 amount) + external + returns (bool success); + + /// @notice Reverts: staking authorizations are not supported. + function revokeStakingAuthorization(address grantee) external returns (bool success); +} diff --git a/giga/evmonly/precompiles/staking/abi.json b/giga/evmonly/precompiles/staking/abi.json new file mode 100644 index 0000000000..6907d186dd --- /dev/null +++ b/giga/evmonly/precompiles/staking/abi.json @@ -0,0 +1,385 @@ +[ + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "delegator", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "validator", + "type": "address" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "amount", + "type": "uint256" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "shares", + "type": "uint256" + } + ], + "name": "Delegate", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "delegator", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "srcValidator", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "dstValidator", + "type": "address" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "amount", + "type": "uint256" + }, + { + "indexed": false, + "internalType": "uint64", + "name": "completionTime", + "type": "uint64" + } + ], + "name": "Redelegate", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "delegator", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "validator", + "type": "address" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "amount", + "type": "uint256" + }, + { + "indexed": false, + "internalType": "uint64", + "name": "completionTime", + "type": "uint64" + } + ], + "name": "Undelegate", + "type": "event" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "validator", + "type": "address" + } + ], + "name": "delegate", + "outputs": [ + { + "internalType": "bool", + "name": "success", + "type": "bool" + } + ], + "stateMutability": "payable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "string", + "name": "valAddress", + "type": "string" + } + ], + "name": "delegate", + "outputs": [ + { + "internalType": "bool", + "name": "success", + "type": "bool" + } + ], + "stateMutability": "payable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "delegator", + "type": "address" + }, + { + "internalType": "string", + "name": "valAddress", + "type": "string" + } + ], + "name": "delegateWithAuthorization", + "outputs": [ + { + "internalType": "bool", + "name": "success", + "type": "bool" + } + ], + "stateMutability": "payable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "grantee", + "type": "address" + }, + { + "internalType": "string[]", + "name": "allowedValidators", + "type": "string[]" + }, + { + "internalType": "uint256", + "name": "maxTokens", + "type": "uint256" + }, + { + "internalType": "int64", + "name": "expiration", + "type": "int64" + } + ], + "name": "grantStakingAuthorization", + "outputs": [ + { + "internalType": "bool", + "name": "success", + "type": "bool" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "srcValidator", + "type": "address" + }, + { + "internalType": "address", + "name": "dstValidator", + "type": "address" + }, + { + "internalType": "uint256", + "name": "amount", + "type": "uint256" + } + ], + "name": "redelegate", + "outputs": [ + { + "internalType": "bool", + "name": "success", + "type": "bool" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "string", + "name": "srcAddress", + "type": "string" + }, + { + "internalType": "string", + "name": "dstAddress", + "type": "string" + }, + { + "internalType": "uint256", + "name": "amount", + "type": "uint256" + } + ], + "name": "redelegate", + "outputs": [ + { + "internalType": "bool", + "name": "success", + "type": "bool" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "delegator", + "type": "address" + }, + { + "internalType": "string", + "name": "srcAddress", + "type": "string" + }, + { + "internalType": "string", + "name": "dstAddress", + "type": "string" + }, + { + "internalType": "uint256", + "name": "amount", + "type": "uint256" + } + ], + "name": "redelegateWithAuthorization", + "outputs": [ + { + "internalType": "bool", + "name": "success", + "type": "bool" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "grantee", + "type": "address" + } + ], + "name": "revokeStakingAuthorization", + "outputs": [ + { + "internalType": "bool", + "name": "success", + "type": "bool" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "validator", + "type": "address" + }, + { + "internalType": "uint256", + "name": "amount", + "type": "uint256" + } + ], + "name": "undelegate", + "outputs": [ + { + "internalType": "bool", + "name": "success", + "type": "bool" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "string", + "name": "valAddress", + "type": "string" + }, + { + "internalType": "uint256", + "name": "amount", + "type": "uint256" + } + ], + "name": "undelegate", + "outputs": [ + { + "internalType": "bool", + "name": "success", + "type": "bool" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "delegator", + "type": "address" + }, + { + "internalType": "string", + "name": "valAddress", + "type": "string" + }, + { + "internalType": "uint256", + "name": "amount", + "type": "uint256" + } + ], + "name": "undelegateWithAuthorization", + "outputs": [ + { + "internalType": "bool", + "name": "success", + "type": "bool" + } + ], + "stateMutability": "nonpayable", + "type": "function" + } +] diff --git a/giga/evmonly/precompiles/staking/delegation.go b/giga/evmonly/precompiles/staking/delegation.go new file mode 100644 index 0000000000..b64dce39eb --- /dev/null +++ b/giga/evmonly/precompiles/staking/delegation.go @@ -0,0 +1,377 @@ +package staking + +import ( + "errors" + "fmt" + "math/big" + + "github.com/ethereum/go-ethereum/accounts/abi" + "github.com/ethereum/go-ethereum/common" + ethtypes "github.com/ethereum/go-ethereum/core/types" + + "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles" + chainparams "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles/params" +) + +var ( + errNoValidatorFound = errors.New("validator does not exist") + errNoDelegation = errors.New("no delegation for (address, validator) tuple") + errNotEnoughShares = errors.New("not enough delegation shares") + errInvalidShares = errors.New("invalid shares amount") + errExRateInvalid = errors.New("cannot delegate to validators with invalid (zero) ex-rate") + errExceedMaxVotingPower = errors.New("validator's voting power ratio would exceed the max allowed ratio") + errMaxUnbondingEntries = errors.New("too many unbonding delegation entries for (delegator, validator) tuple") + errMaxRedelegationEntries = errors.New("too many redelegation entries for (delegator, src-validator, dst-validator) tuple") + errSelfRedelegation = errors.New("cannot redelegate to the same validator") + errBadRedelegationValidator = errors.New("redelegation validator does not exist") + errTransitiveRedelegation = errors.New("redelegation to this validator already in progress; first redelegation to this validator must complete before next redelegation") + errTinyRedelegationAmount = errors.New("too few tokens to redelegate (truncates to zero tokens)") + errEscrowShort = errors.New("escrow holds less than the transfer") + errBalanceOverflow = errors.New("transfer would overflow the recipient's balance") + errInvalidTransition = errors.New("invalid validator status transition") + errInvalidStatus = errors.New("invalid validator status") +) + +func (p Precompile) delegateCall(ctx *precompiles.Context, s store, method *abi.Method, args []interface{}) ([]byte, error) { + op := args[0].(common.Address) + v, ok := s.validator(op) + if !ok { + return nil, fmt.Errorf("%w: %s", errNoValidatorFound, op) + } + amount := new(big.Int).Set(ctx.ApparentValue) + shares, err := p.delegate(ctx.Block, s, s.params(), ctx.Caller, op, &v, amount, statusUnbonded, ctx.Address) + if err != nil { + return nil, err + } + if err := emit(ctx, DelegateEvent, []common.Hash{addressTopic(ctx.Caller), addressTopic(op)}, amount, shares); err != nil { + return nil, err + } + return method.Outputs.Pack(true) +} + +func (p Precompile) undelegateCall(ctx *precompiles.Context, s store, method *abi.Method, args []interface{}) ([]byte, error) { + op, amount := args[0].(common.Address), args[1].(*big.Int) + shares, err := validateUnbondAmount(s, ctx.Caller, op, amount) + if err != nil { + return nil, err + } + returned, completionTime, err := p.undelegate(ctx.Block, s, s.params(), ctx.Caller, op, shares) + if err != nil { + return nil, err + } + if err := emit(ctx, UndelegateEvent, []common.Hash{addressTopic(ctx.Caller), addressTopic(op)}, returned, completionTime); err != nil { + return nil, err + } + return method.Outputs.Pack(true) +} + +func (p Precompile) redelegateCall(ctx *precompiles.Context, s store, method *abi.Method, args []interface{}) ([]byte, error) { + src, dst, amount := args[0].(common.Address), args[1].(common.Address), args[2].(*big.Int) + shares, err := validateUnbondAmount(s, ctx.Caller, src, amount) + if err != nil { + return nil, err + } + returned, completionTime, err := p.redelegate(ctx.Block, s, s.params(), ctx.Caller, src, dst, shares) + if err != nil { + return nil, err + } + if err := emit(ctx, RedelegateEvent, []common.Hash{addressTopic(ctx.Caller), addressTopic(src), addressTopic(dst)}, returned, completionTime); err != nil { + return nil, err + } + return method.Outputs.Pack(true) +} + +// delegate adds amount to delegator's delegation to op's validator v and +// returns the shares it issues, as x/staking's Delegate does. The tokens come +// from the balance of from, or, when from is the zero address, from the escrow +// of a validator whose status was tokenSrc. +func (p Precompile) delegate( + block precompiles.BlockContext, s store, params chainparams.Staking, + delegator, op common.Address, v *validator, amount *big.Int, tokenSrc uint8, from common.Address, +) (*big.Int, error) { + if v.invalidExRate() { + return nil, errExRateInvalid + } + if err := checkVotingPowerRatio(block, s, params, v, amount); err != nil { + return nil, err + } + shares, found := s.delegation(delegator, op) + hook := p.hooks().BeforeDelegationCreated + if found { + hook = p.hooks().BeforeDelegationSharesModified + } + if err := hook(block, s.State, delegator, op); err != nil { + return nil, err + } + + dstEscrow, err := escrowOf(v.status) + if err != nil { + return nil, err + } + if from == (common.Address{}) { + if from, err = escrowOf(tokenSrc); err != nil { + return nil, err + } + } + if err := transfer(s.State, from, dstEscrow, amount); err != nil { + return nil, err + } + + issued, err := s.addTokensFromDelegation(op, v, amount) + if err != nil { + return nil, err + } + s.setDelegation(delegator, op, new(big.Int).Add(shares, issued)) + return issued, p.hooks().AfterDelegationModified(block, s.State, delegator, op) +} + +// checkVotingPowerRatio fails when delegating amount to v would take v past the +// max voting power ratio of the bonded set's power, once that power reaches the +// enforcement threshold, as x/staking's Delegate checks. +func checkVotingPowerRatio(block precompiles.BlockContext, s store, params chainparams.Staking, v *validator, amount *big.Int) error { + newTotalPower := new(big.Int).Add(s.lastTotalPower(), consensusPower(amount)) + if block.Number == 0 || newTotalPower.Sign() == 0 || newTotalPower.Cmp(params.MaxVotingPowerEnforcementThreshold) < 0 { + return nil + } + validatorPower := consensusPower(new(big.Int).Add(v.tokens, amount)) + ratio := quoDec(intToDec(validatorPower), intToDec(newTotalPower)) + if ratio.Cmp(params.MaxVotingPowerRatio) > 0 { + return fmt.Errorf("%w: %s, max %s", errExceedMaxVotingPower, ratio, params.MaxVotingPowerRatio) + } + return nil +} + +// validateUnbondAmount returns the shares of delegator's delegation to op that +// amount of tokens is worth, as x/staking's ValidateUnbondAmount does, failing +// when they are more than the delegation holds. +func validateUnbondAmount(s store, delegator, op common.Address, amount *big.Int) (*big.Int, error) { + v, ok := s.validator(op) + if !ok { + return nil, fmt.Errorf("%w: %s", errNoValidatorFound, op) + } + delegated, ok := s.delegation(delegator, op) + if !ok { + return nil, errNoDelegation + } + shares, err := v.sharesFromTokens(amount) + if err != nil { + return nil, err + } + if shares.Cmp(delegated) > 0 { + return nil, errInvalidShares + } + return shares, nil +} + +// unbond takes shares from delegator's delegation to op and returns the tokens +// they were worth, as x/staking's Unbond does. The tokens stay in op's escrow. +// An operator whose self-delegation falls below its minimum is jailed, and an +// unbonded validator left with no shares is removed. +func (p Precompile) unbond(block precompiles.BlockContext, s store, delegator, op common.Address, shares *big.Int) (*big.Int, error) { + delegated, ok := s.delegation(delegator, op) + if !ok { + return nil, errNoDelegation + } + if err := p.hooks().BeforeDelegationSharesModified(block, s.State, delegator, op); err != nil { + return nil, err + } + if delegated.Cmp(shares) < 0 { + return nil, fmt.Errorf("%w: %s", errNotEnoughShares, delegated) + } + v, ok := s.validator(op) + if !ok { + return nil, fmt.Errorf("%w: %s", errNoValidatorFound, op) + } + + remaining := new(big.Int).Sub(delegated, shares) + if delegator == op && !v.jailed && truncateDec(v.tokensFromShares(remaining)).Cmp(v.minSelfDelegation) < 0 { + if err := s.jail(op, &v); err != nil { + return nil, err + } + } + if remaining.Sign() == 0 { + if err := p.hooks().BeforeDelegationRemoved(block, s.State, delegator, op); err != nil { + return nil, err + } + s.removeDelegation(delegator, op) + } else { + s.setDelegation(delegator, op, remaining) + if err := p.hooks().AfterDelegationModified(block, s.State, delegator, op); err != nil { + return nil, err + } + } + + amount, err := s.removeDelegationShares(op, &v, shares) + if err != nil { + return nil, err + } + if v.delegatorShares.Sign() == 0 && v.status == statusUnbonded { + if err := p.removeValidator(block, s, op, v); err != nil { + return nil, err + } + } + return amount, nil +} + +// undelegate unbonds shares of delegator's delegation to op into a new +// unbonding entry, paid one unbonding period from now, as x/staking's +// Undelegate does. It returns the entry's balance and completion time. +func (p Precompile) undelegate( + block precompiles.BlockContext, s store, params chainparams.Staking, delegator, op common.Address, shares *big.Int, +) (*big.Int, uint64, error) { + v, ok := s.validator(op) + if !ok { + return nil, 0, fmt.Errorf("%w: %s", errNoValidatorFound, op) + } + if s.unbondingEntryCount(delegator, op) >= uint64(params.MaxEntries) { + return nil, 0, errMaxUnbondingEntries + } + amount, err := p.unbond(block, s, delegator, op, shares) + if err != nil { + return nil, 0, err + } + if v.bonded() { + if err := transfer(s.State, BondedEscrow, NotBondedEscrow, amount); err != nil { + return nil, 0, err + } + } + + q := s.unbondingQueue() + completionTime := q.clamp(block.UnixNano + params.UnbondingTime) + s.appendUnbondingEntry(delegator, op, unbondingEntry{ + creationHeight: block.Number, + completionTime: completionTime, + initialBalance: amount, + balance: amount, + }) + e, err := q.push(completionTime) + if err != nil { + return nil, 0, err + } + s.SetAddressAt(at(e, unbondingQueueDelegator), unbondingQueueDelegator.offset, delegator) + s.SetAddressAt(at(e, unbondingQueueValidator), unbondingQueueValidator.offset, op) + return amount, completionTime, nil +} + +// redelegate moves shares of delegator's delegation to src into a delegation +// to dst, as x/staking's BeginRedelegation does, and queues the redelegation +// entry unless src is unbonded. It returns the tokens moved and the entry's +// completion time, or 0 for no entry. +func (p Precompile) redelegate( + block precompiles.BlockContext, s store, params chainparams.Staking, delegator, src, dst common.Address, shares *big.Int, +) (*big.Int, uint64, error) { + if src == dst { + return nil, 0, errSelfRedelegation + } + dstValidator, ok := s.validator(dst) + if !ok { + return nil, 0, fmt.Errorf("%w: %s", errBadRedelegationValidator, dst) + } + srcValidator, ok := s.validator(src) + if !ok { + return nil, 0, fmt.Errorf("%w: %s", errBadRedelegationValidator, src) + } + if s.receivingRedelegations(src, delegator).Sign() > 0 { + return nil, 0, errTransitiveRedelegation + } + entries := s.redelegationEntryCount(delegator, src, dst) + if entries.Cmp(new(big.Int).SetUint64(uint64(params.MaxEntries))) >= 0 { + return nil, 0, errMaxRedelegationEntries + } + + amount, err := p.unbond(block, s, delegator, src, shares) + if err != nil { + return nil, 0, err + } + if amount.Sign() == 0 { + return nil, 0, errTinyRedelegationAmount + } + sharesDst, err := p.delegate(block, s, params, delegator, dst, &dstValidator, amount, srcValidator.status, common.Address{}) + if err != nil { + return nil, 0, err + } + + completionTime, creationHeight, completeNow := redelegationBeginInfo(block, s, params, src) + if completeNow { + return amount, 0, nil + } + q := s.redelegationQueue() + completionTime = q.clamp(completionTime) + e, err := q.push(completionTime) + if err != nil { + return nil, 0, err + } + s.SetAddressAt(at(e, redelegationQueueDelegator), redelegationQueueDelegator.offset, delegator) + s.SetUint64(at(e, redelegationQueueCreationHeight), redelegationQueueCreationHeight.offset, creationHeight) + s.SetAddressAt(at(e, redelegationQueueSrcValidator), redelegationQueueSrcValidator.offset, src) + s.SetAddressAt(at(e, redelegationQueueDstValidator), redelegationQueueDstValidator.offset, dst) + s.SetUint256(at(e, redelegationQueueInitialBalance), amount) + s.SetUint256(at(e, redelegationQueueSharesDst), sharesDst) + s.setRedelegationEntryCount(delegator, src, dst, entries.Add(entries, big.NewInt(1))) + received := s.receivingRedelegations(dst, delegator) + s.setReceivingRedelegations(dst, delegator, received.Add(received, big.NewInt(1))) + return amount, completionTime, nil +} + +// redelegationBeginInfo returns when a redelegation out of src completes and +// the height it counts from, as x/staking's getBeginInfo does: one unbonding +// period from now when src is bonded or gone, src's own unbonding end when it +// is unbonding, and now, with completeNow, when it is unbonded. +func redelegationBeginInfo(block precompiles.BlockContext, s store, params chainparams.Staking, src common.Address) (completionTime, height uint64, completeNow bool) { + v, ok := s.validator(src) + switch { + case !ok || v.status == statusBonded: + return block.UnixNano + params.UnbondingTime, block.Number, false + case v.status == statusUnbonding: + return v.unbondingTime, v.unbondingHeight, false + default: + return 0, 0, true + } +} + +// escrowOf returns the escrow holding the tokens of a validator with status. +func escrowOf(status uint8) (common.Address, error) { + switch status { + case statusBonded: + return BondedEscrow, nil + case statusUnbonded, statusUnbonding: + return NotBondedEscrow, nil + } + return common.Address{}, fmt.Errorf("%w: %d", errInvalidStatus, status) +} + +// transfer moves amount from one balance to another, failing without moving +// anything when from holds less than amount or to would overflow. A transfer +// between the same address moves nothing. +func transfer(state precompiles.State, from, to common.Address, amount *big.Int) error { + if from == to || amount.Sign() == 0 { + return nil + } + if state.GetBalance(from).Cmp(amount) < 0 { + return fmt.Errorf("%w: %s holds less than %s", errEscrowShort, from, amount) + } + if new(big.Int).Add(state.GetBalance(to), amount).BitLen() > 256 { + return fmt.Errorf("%w: %s", errBalanceOverflow, to) + } + if err := state.SubBalance(from, amount); err != nil { + return err + } + state.AddBalance(to, amount) + return nil +} + +// emit logs event name with the indexed topics after its signature and data as +// its non-indexed fields. +func emit(ctx *precompiles.Context, name string, indexed []common.Hash, data ...interface{}) error { + event := ABI.Events[name] + bz, err := event.Inputs.NonIndexed().Pack(data...) + if err != nil { + return err + } + ctx.Logs.AddLog(ðtypes.Log{Address: ctx.Address, Topics: append([]common.Hash{event.ID}, indexed...), Data: bz}) + return nil +} + +func addressTopic(a common.Address) common.Hash { + return common.BytesToHash(a[:]) +} diff --git a/giga/evmonly/precompiles/staking/endblock.go b/giga/evmonly/precompiles/staking/endblock.go new file mode 100644 index 0000000000..5fb442d999 --- /dev/null +++ b/giga/evmonly/precompiles/staking/endblock.go @@ -0,0 +1,253 @@ +package staking + +import ( + "bytes" + "errors" + "fmt" + "maps" + "math/big" + "slices" + + "github.com/ethereum/go-ethereum/common" + + "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles" + chainparams "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles/params" +) + +var ( + errNoBondedPower = errors.New("the bonded set would have no power") + errJailedInPowerIndex = errors.New("jailed validator in the power index") + errUnknownValidator = errors.New("validator in the bonded set or power index does not exist") + errPowerOverflow = errors.New("consensus power does not fit 64 bits") + errRedelegationCounted = errors.New("redelegation entry was not counted") +) + +// endBlockBudget bounds the entries one EndBlock completes from each queue: one +// unit per entry, plus one per unbonding entry of the delegation it pays. +// Entries past the budget wait for the next EndBlock; an entry larger than the +// whole budget runs when nothing has spent it, and uses it up. Queuing an +// unbonding or redelegation entry writes at least five new slots, over 100,000 +// gas, so one EndBlock completes more entries than 300M gas of calls can queue. +const endBlockBudget = 3_000 + +// EndBlock updates the bonded set, then completes the validators, unbonding +// entries and redelegation entries whose unbonding period is over, in that +// order, as x/staking's BlockValidatorUpdates does. Before staking's params are +// written it does nothing. Its failures are a bonded set that could not be +// updated, which is kept as it was, and queue entries whose stored data does +// not add up, which are dropped. It returns no error. +func (p Precompile) EndBlock(block precompiles.BlockContext, state precompiles.State) ([]error, error) { + if !chainparams.HasStaking(state) { + return nil, nil + } + s := newStore(state) + params := s.params() + var failures []error + if err := p.updateBondedSet(block, s, params); err != nil { + failures = append(failures, fmt.Errorf("%w: bonded set kept as it was: %w", precompiles.ErrDegraded, err)) + } + drain(block, s.validatorQueue(), "validator", &failures, + func(common.Hash) uint64 { return 1 }, + func(e common.Hash) error { return p.completeValidatorUnbonding(block, s, e) }) + drain(block, s.unbondingQueue(), "unbonding", &failures, + func(e common.Hash) uint64 { + delegator, op := unbondingQueueEntry(s, e) + return 1 + s.unbondingEntryCount(delegator, op) + }, + func(e common.Hash) error { return completeUnbonding(block, s, e) }) + drain(block, s.redelegationQueue(), "redelegation", &failures, + func(common.Hash) uint64 { return 1 }, + func(e common.Hash) error { return completeRedelegation(s, e) }) + return failures, nil +} + +// updateBondedSet applies the bonded set the power index ranks, as x/staking's +// ApplyAndReturnValidatorSetUpdates does. When that fails, or would leave the +// set with no power, it writes nothing. +func (p Precompile) updateBondedSet(block precompiles.BlockContext, s store, params chainparams.Staking) error { + snap := s.State.Snapshot() + if err := p.applyBondedSet(block, s, params); err != nil { + s.State.RevertToSnapshot(snap) + return err + } + return nil +} + +// applyBondedSet bonds the first MaxValidators validators of the power index +// that have power, begins unbonding those of the last set that are no longer +// among them, in address order, moves their tokens between the escrows, and +// stores the new set and its total power when it differs from the last. +func (p Precompile) applyBondedSet(block precompiles.BlockContext, s store, params chainparams.Staking) error { + last, err := s.lastValidators() + if err != nil { + return err + } + lastPower := make(map[common.Address]uint64, len(last)) + for _, v := range last { + lastPower[v.operator] = v.power + } + + changed := false + next := make([]validatorPower, 0, params.MaxValidators) + total, toBonded, toNotBonded := new(big.Int), new(big.Int), new(big.Int) + index := s.powerIndex() + for i, n := uint64(0), index.len(); i < n && len(next) < int(params.MaxValidators); i++ { + op := index.at(i) + v, ok := s.validator(op) + switch { + case !ok: + return fmt.Errorf("%w: %s", errUnknownValidator, op) + case v.jailed: + return fmt.Errorf("%w: %s", errJailedInPowerIndex, op) + } + power := consensusPower(v.tokens) + if power.Sign() == 0 { + break + } + if !power.IsUint64() { + return fmt.Errorf("%w: %s", errPowerOverflow, op) + } + if !v.bonded() { + if err := p.bond(block, s, op, &v); err != nil { + return err + } + toBonded.Add(toBonded, v.tokens) + } + if old, ok := lastPower[op]; !ok || old != power.Uint64() { + changed = true + } + delete(lastPower, op) + next = append(next, validatorPower{operator: op, power: power.Uint64()}) + total.Add(total, power) + } + + gone := slices.SortedFunc(maps.Keys(lastPower), func(a, b common.Address) int { return bytes.Compare(a[:], b[:]) }) + for _, op := range gone { + v, ok := s.validator(op) + if !ok { + return fmt.Errorf("%w: %s", errUnknownValidator, op) + } + if err := p.beginUnbonding(block, s, op, &v, params.UnbondingTime); err != nil { + return err + } + toNotBonded.Add(toNotBonded, v.tokens) + changed = true + } + if total.Sign() == 0 && len(last) > 0 { + return errNoBondedPower + } + + switch toBonded.Cmp(toNotBonded) { + case 1: + err = transfer(s.State, NotBondedEscrow, BondedEscrow, toBonded.Sub(toBonded, toNotBonded)) + case -1: + err = transfer(s.State, BondedEscrow, NotBondedEscrow, toNotBonded.Sub(toNotBonded, toBonded)) + } + if err != nil { + return err + } + if changed { + s.setLastValidators(next) + s.setLastTotalPower(total) + } + return nil +} + +// drain completes each entry due in q, in queue order, under a budget of its +// own, until none is due or the next does not fit what is left. Each entry is +// removed from q once completed. A completion that fails is reverted and its +// entry removed all the same, so it holds up no other, and the failure is +// reported. A queue whose head is past its tail is reported and left alone. +func drain(block precompiles.BlockContext, q queue, name string, failures *[]error, cost func(e common.Hash) uint64, complete func(e common.Hash) error) { + if err := q.check(); err != nil { + *failures = append(*failures, fmt.Errorf("%w: %s queue: %w", precompiles.ErrDegraded, name, err)) + return + } + budget := uint64(endBlockBudget) + for e, ok := q.due(block.UnixNano); ok; e, ok = q.due(block.UnixNano) { + if !take(&budget, cost(e)) { + return + } + snap := q.s.State.Snapshot() + if err := complete(e); err != nil { + q.s.State.RevertToSnapshot(snap) + *failures = append(*failures, fmt.Errorf("%w: %s queue entry %d dropped: %w", precompiles.ErrDegraded, name, q.head(), err)) + } + q.pop() + } +} + +// take spends n of budget, reporting whether the work may run. Work larger than +// the whole budget runs only on a budget nothing else has spent, and uses it up. +func take(budget *uint64, n uint64) bool { + switch { + case n <= *budget: + *budget -= n + case *budget == endBlockBudget: + *budget = 0 + default: + return false + } + return true +} + +// completeValidatorUnbonding makes the validator of validator queue entry e +// unbonded, as x/staking's UnbondAllMatureValidators does, and removes it when +// it has no shares left. An entry left by a validator that bonded again since +// is skipped. +func (p Precompile) completeValidatorUnbonding(block precompiles.BlockContext, s store, e common.Hash) error { + op := s.AddressAt(at(e, validatorQueueOperator), validatorQueueOperator.offset) + v, ok := s.validator(op) + if !ok || v.status != statusUnbonding || + v.unbondingTime != s.Uint64(at(e, queueCompletionTime), queueCompletionTime.offset) || + v.unbondingHeight != s.Uint64(at(e, validatorQueueUnbondingHeight), validatorQueueUnbondingHeight.offset) { + return nil + } + v.status = statusUnbonded + s.setValidator(op, v) + if v.delegatorShares.Sign() == 0 { + return p.removeValidator(block, s, op, v) + } + return nil +} + +// completeUnbonding pays the delegator of unbonding queue entry e every +// matured entry of its unbonding from the entry's validator, out of the +// not-bonded escrow, and removes them, as x/staking's CompleteUnbonding does. +func completeUnbonding(block precompiles.BlockContext, s store, e common.Hash) error { + delegator, op := unbondingQueueEntry(s, e) + entries, err := s.unbondingEntries(delegator, op) + if err != nil { + return err + } + kept := make([]unbondingEntry, 0, len(entries)) + for _, entry := range entries { + if entry.completionTime > block.UnixNano { + kept = append(kept, entry) + continue + } + if err := transfer(s.State, NotBondedEscrow, delegator, entry.balance); err != nil { + return fmt.Errorf("paying %s from %s: %w", delegator, op, err) + } + } + if len(kept) != len(entries) { + s.setUnbondingEntries(delegator, op, kept) + } + return nil +} + +// completeRedelegation uncounts redelegation queue entry e from its delegator's +// open redelegations, as x/staking's CompleteRedelegation removes the entry. It +// moves no tokens: they moved when the redelegation began. +func completeRedelegation(s store, e common.Hash) error { + delegator := s.AddressAt(at(e, redelegationQueueDelegator), redelegationQueueDelegator.offset) + src := s.AddressAt(at(e, redelegationQueueSrcValidator), redelegationQueueSrcValidator.offset) + dst := s.AddressAt(at(e, redelegationQueueDstValidator), redelegationQueueDstValidator.offset) + entries, received := s.redelegationEntryCount(delegator, src, dst), s.receivingRedelegations(dst, delegator) + if entries.Sign() == 0 || received.Sign() == 0 { + return fmt.Errorf("%w: %s from %s to %s", errRedelegationCounted, delegator, src, dst) + } + s.setRedelegationEntryCount(delegator, src, dst, entries.Sub(entries, big.NewInt(1))) + s.setReceivingRedelegations(dst, delegator, received.Sub(received, big.NewInt(1))) + return nil +} diff --git a/giga/evmonly/precompiles/staking/endblock_test.go b/giga/evmonly/precompiles/staking/endblock_test.go new file mode 100644 index 0000000000..29bd5fc877 --- /dev/null +++ b/giga/evmonly/precompiles/staking/endblock_test.go @@ -0,0 +1,260 @@ +package staking + +import ( + "math/big" + "testing" + + "github.com/ethereum/go-ethereum/common" + "github.com/stretchr/testify/require" + + "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles" + chainparams "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles/params" + "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles/solstorage" +) + +func TestFirstEndBlockBondsTheTopValidators(t *testing.T) { + h := newHarness(t, testParams) + require.Equal(t, []validatorPower{{val1, 30}, {val2, 20}}, h.lastValidators()) + require.Equal(t, big.NewInt(50), h.store().lastTotalPower()) + require.Equal(t, statusBonded, h.validator(val1).status) + require.Equal(t, statusBonded, h.validator(val2).status) + require.Equal(t, statusUnbonded, h.validator(val3).status) + require.Equal(t, sei(50), h.state.GetBalance(BondedEscrow)) + require.Equal(t, sei(10), h.state.GetBalance(NotBondedEscrow)) + h.requireInvariants() +} + +func TestAValidatorOutrankedLeavesTheSetAndUnbonds(t *testing.T) { + h := newHarness(t, testParams) + require.NoError(t, h.delegate(alice, val3, sei(15))) + h.endBlock() + require.Empty(t, h.failures) + require.Equal(t, []validatorPower{{val1, 30}, {val3, 25}}, h.lastValidators()) + require.Equal(t, big.NewInt(55), h.store().lastTotalPower()) + require.Equal(t, statusBonded, h.validator(val3).status) + v2 := h.validator(val2) + require.Equal(t, statusUnbonding, v2.status) + require.Equal(t, h.time-second+testParams.UnbondingTime, v2.unbondingTime) + require.Equal(t, h.number-1, v2.unbondingHeight) + h.requireInvariants(alice) + + h.advance(testParams.UnbondingTime - 2*second) + require.Equal(t, statusUnbonding, h.validator(val2).status, "not before its unbonding time") + h.endBlock() + require.Empty(t, h.failures) + require.Equal(t, statusUnbonded, h.validator(val2).status) + q := h.store().validatorQueue() + require.Equal(t, q.head(), q.tail()) + h.requireInvariants(alice) +} + +func TestAValidatorThatBondsAgainSkipsItsOldQueueEntry(t *testing.T) { + h := newHarness(t, testParams) + require.NoError(t, h.delegate(alice, val3, sei(15))) + h.endBlock() + require.Equal(t, statusUnbonding, h.validator(val2).status) + require.NoError(t, h.delegate(bob, val2, sei(20))) + h.endBlock() + require.Equal(t, statusBonded, h.validator(val2).status) + + h.advance(testParams.UnbondingTime) + require.Empty(t, h.failures) + require.Equal(t, statusBonded, h.validator(val2).status, "the stale entry leaves it bonded") + require.Equal(t, statusUnbonded, h.validator(val3).status, "val3's own entry completes") + q := h.store().validatorQueue() + require.Equal(t, q.head(), q.tail()) + h.requireInvariants(alice, bob) +} + +func TestAnUnbondedValidatorWithNoSharesIsRemoved(t *testing.T) { + h := newHarness(t, testParams) + require.NoError(t, h.undelegate(val3, val3, sei(10))) + _, ok := h.store().validator(val3) + require.False(t, ok) + require.False(t, h.store().validatorSet().Contains(common.BytesToHash(val3[:]))) + require.Equal(t, common.Address{}, h.store().validatorByPubkey(common.BytesToHash(val3[:]))) + require.Equal(t, []common.Address{val1, val2}, h.powerIndex()) + for i := uint64(0); i < validatorSlots; i++ { + require.NotContains(t, h.state.storage[Address], solstorage.Offset(validatorBase(val3), i), "slot %d of the record is cleared", i) + } + h.requireInvariants() + + h.advance(testParams.UnbondingTime) + require.Empty(t, h.failures) + require.Zero(t, h.state.GetBalance(NotBondedEscrow).Sign()) + require.Equal(t, sei(10), h.state.GetBalance(val3), "the unbonding entry outlives its validator") +} + +func TestAValidatorFinishingUnbondingWithNoSharesIsRemoved(t *testing.T) { + h := newHarness(t, testParams) + require.NoError(t, h.undelegate(val2, val2, sei(20))) + h.endBlock() + require.Equal(t, statusUnbonding, h.validator(val2).status) + h.advance(testParams.UnbondingTime) + require.Empty(t, h.failures) + _, ok := h.store().validator(val2) + require.False(t, ok) + require.Equal(t, sei(20), h.state.GetBalance(val2)) + h.requireInvariants() +} + +func TestUnbondingPaysOutOnceItsTimeComes(t *testing.T) { + h := newHarness(t, testParams) + require.NoError(t, h.delegate(alice, val1, sei(5))) + require.NoError(t, h.undelegate(alice, val1, sei(2))) + h.advance(testParams.UnbondingTime - second) + require.Zero(t, h.state.GetBalance(alice).Sign(), "not before its completion time") + require.Len(t, must(h.store().unbondingEntries(alice, val1)), 1) + h.endBlock() + require.Empty(t, h.failures) + require.Equal(t, sei(2), h.state.GetBalance(alice)) + require.Empty(t, must(h.store().unbondingEntries(alice, val1))) + q := h.store().unbondingQueue() + require.Equal(t, q.head(), q.tail()) + h.requireInvariants(alice) +} + +func TestOneQueueEntryPaysEveryMaturedEntryOfItsDelegation(t *testing.T) { + h := newHarness(t, testParams) + require.NoError(t, h.delegate(alice, val1, sei(5))) + require.NoError(t, h.undelegate(alice, val1, sei(1))) + require.NoError(t, h.undelegate(alice, val1, sei(2))) + h.endBlock() + require.NoError(t, h.undelegate(alice, val1, sei(1))) + h.advance(testParams.UnbondingTime - second) + require.Equal(t, sei(3), h.state.GetBalance(alice), "both entries of the first block, from its first queue entry") + require.Len(t, must(h.store().unbondingEntries(alice, val1)), 1) + h.endBlock() + require.Empty(t, h.failures) + require.Equal(t, sei(4), h.state.GetBalance(alice)) + require.Empty(t, must(h.store().unbondingEntries(alice, val1))) + h.requireInvariants(alice) +} + +func TestRedelegationCompletesWithoutMovingTokens(t *testing.T) { + h := newHarness(t, testParams) + require.NoError(t, h.delegate(alice, val1, sei(5))) + require.NoError(t, h.redelegate(alice, val1, val2, sei(2))) + bonded := h.state.GetBalance(BondedEscrow) + h.advance(testParams.UnbondingTime) + require.Empty(t, h.failures) + require.Zero(t, h.store().redelegationEntryCount(alice, val1, val2).Sign()) + require.Zero(t, h.store().receivingRedelegations(val2, alice).Sign()) + q := h.store().redelegationQueue() + require.Equal(t, q.head(), q.tail()) + require.Equal(t, bonded, h.state.GetBalance(BondedEscrow)) + h.requireInvariants(alice) +} + +func TestARedelegationFromAnUnbondingValidatorEndsWithIt(t *testing.T) { + h := newHarness(t, testParams) + require.NoError(t, h.delegate(alice, val2, sei(5))) + require.NoError(t, h.delegate(bob, val3, sei(20))) + h.endBlock() + v2 := h.validator(val2) + require.Equal(t, statusUnbonding, v2.status) + h.advance(10 * second) + + require.NoError(t, h.redelegate(alice, val2, val1, sei(5))) + e := h.store().redelegationQueue().entry(0) + require.Equal(t, v2.unbondingTime, h.store().Uint64(at(e, queueCompletionTime), queueCompletionTime.offset)) + require.Equal(t, v2.unbondingHeight, h.store().Uint64(at(e, redelegationQueueCreationHeight), redelegationQueueCreationHeight.offset)) + h.requireInvariants(alice, bob) +} + +func TestAShorterUnbondingTimeQueuesBehindTheLongerOnes(t *testing.T) { + h := newHarness(t, testParams) + require.NoError(t, h.delegate(alice, val1, sei(5))) + require.NoError(t, h.undelegate(alice, val1, sei(1))) + first := h.time + testParams.UnbondingTime + require.NoError(t, chainparams.Apply(h.state, []chainparams.Change{{Subspace: "staking", Key: "UnbondingTime", Value: common.BigToHash(new(big.Int).SetUint64(10 * second)).Bytes()}})) + h.endBlock() + require.NoError(t, h.undelegate(alice, val1, sei(1))) + entries := must(h.store().unbondingEntries(alice, val1)) + require.Equal(t, first, entries[1].completionTime, "the new entry waits for the one ahead of it") + h.requireInvariants(alice) +} + +func TestAShortPayoutIsReportedAndItsEntryKept(t *testing.T) { + h := newHarness(t, testParams) + require.NoError(t, h.delegate(alice, val1, sei(5))) + require.NoError(t, h.undelegate(alice, val1, sei(2))) + require.NoError(t, h.delegate(bob, val1, sei(1))) + require.NoError(t, h.undelegate(bob, val1, sei(1))) + // The escrow holds val3's 10 SEI and the two entries' 3. Leave it 1 SEI: + // short of alice's entry, ahead in the queue, but enough for bob's. + require.NoError(t, h.state.SubBalance(NotBondedEscrow, sei(12))) + h.advance(testParams.UnbondingTime) + require.Len(t, h.failures, 1) + require.ErrorIs(t, h.failures[0], precompiles.ErrDegraded) + require.ErrorIs(t, h.failures[0], errEscrowShort) + require.Zero(t, h.state.GetBalance(alice).Sign()) + require.Len(t, must(h.store().unbondingEntries(alice, val1)), 1, "the unpaid entry stays on record") + require.Equal(t, sei(1), h.state.GetBalance(bob), "the next entry is paid") + q := h.store().unbondingQueue() + require.Equal(t, q.head(), q.tail(), "the failed queue entry is dropped") +} + +func TestEndBlockBudgetDefersTheRest(t *testing.T) { + h := newHarness(t, testParams) + // Each entry costs two units: one for itself, one for the entry it pays. + n := endBlockBudget/2 + 1 + delegators := make([]common.Address, n) + s := h.store() + for i := range delegators { + d := common.BigToAddress(big.NewInt(int64(0x10000 + i))) + delegators[i] = d + h.fund(d, sei(1)) + v := h.validator(val1) + _, err := h.staking.delegate(h.block(), s, testParams, d, val1, &v, sei(1), statusUnbonded, d) + require.NoError(t, err) + _, _, err = h.staking.undelegate(h.block(), s, testParams, d, val1, h.shares(d, val1)) + require.NoError(t, err) + } + h.advance(testParams.UnbondingTime - second) + h.endBlock() + require.Empty(t, h.failures) + q := h.store().unbondingQueue() + require.Equal(t, uint64(1), q.tail()-q.head(), "one entry waits for the next block") + require.Zero(t, h.state.GetBalance(delegators[n-1]).Sign()) + h.endBlock() + require.Equal(t, sei(1), h.state.GetBalance(delegators[n-1])) + require.Equal(t, q.head(), q.tail()) +} + +func TestABondedSetWithNoPowerIsKept(t *testing.T) { + params := testParams + params.MaxValidators = 1 + h := newHarness(t, params) + require.NoError(t, h.undelegate(val1, val1, sei(30))) + require.NoError(t, h.undelegate(val2, val2, sei(20))) + require.NoError(t, h.undelegate(val3, val3, sei(10))) + h.endBlock() + require.Len(t, h.failures, 1) + require.ErrorIs(t, h.failures[0], precompiles.ErrDegraded) + require.ErrorIs(t, h.failures[0], errNoBondedPower) + require.Equal(t, []validatorPower{{val1, 30}}, h.lastValidators(), "the last set stands") + require.Equal(t, statusBonded, h.validator(val1).status) +} + +func TestTake(t *testing.T) { + budget := uint64(endBlockBudget) + require.True(t, take(&budget, endBlockBudget+1), "work larger than a whole budget runs on a fresh one") + require.Zero(t, budget) + budget = 10 + require.True(t, take(&budget, 10)) + require.False(t, take(&budget, 1)) + budget = 10 + require.False(t, take(&budget, 11)) + require.Equal(t, uint64(10), budget) +} + +func TestACorruptQueueIsReported(t *testing.T) { + h := newHarness(t, testParams) + q := h.store().redelegationQueue() + h.store().SetUint64(at(q.bounds, queueHead), queueHead.offset, 5) + h.endBlock() + require.Len(t, h.failures, 1) + require.ErrorIs(t, h.failures[0], errQueueCorrupt) + require.ErrorContains(t, h.failures[0], "redelegation queue") +} diff --git a/giga/evmonly/precompiles/staking/genesis.go b/giga/evmonly/precompiles/staking/genesis.go new file mode 100644 index 0000000000..30a856deec --- /dev/null +++ b/giga/evmonly/precompiles/staking/genesis.go @@ -0,0 +1,109 @@ +package staking + +import ( + "errors" + "fmt" + "math/big" + "time" + + "github.com/ethereum/go-ethereum/common" + + "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles" + chainparams "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles/params" + "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles/solstorage" +) + +var ( + errValidatorExists = errors.New("validator already exists for this operator") + errPubkeyExists = errors.New("validator already exists for this consensus key") + errInvalidGenesis = errors.New("invalid genesis validator") + errStakingNotWritten = errors.New("staking's params must be written before its validators") +) + +// DefaultParams returns x/staking's default params as Sei sets them. +func DefaultParams() chainparams.Staking { + return chainparams.Staking{ + UnbondingTime: uint64(21 * 24 * time.Hour), + MaxValidators: 35, + MaxEntries: 7, + MaxVotingPowerRatio: big.NewInt(200_000_000_000_000_000), + MaxVotingPowerEnforcementThreshold: big.NewInt(1_000_000), + } +} + +// SetParams writes p as staking's params, for genesis. +func SetParams(state precompiles.State, p chainparams.Staking) error { + return chainparams.WriteStaking(state, p) +} + +// HasParams reports whether staking's params have been written. +func HasParams(state precompiles.State) bool { + return chainparams.HasStaking(state) +} + +// GenesisValidator is a validator staking starts with. Amounts are wei, whole +// usei. +type GenesisValidator struct { + Operator common.Address + ConsensusPubkey common.Hash // ed25519 + SelfDelegation *big.Int + MinSelfDelegation *big.Int +} + +// AddGenesisValidator creates g's validator unbonded and delegates its +// self-delegation from the operator's balance, as a genesis transaction's +// MsgCreateValidator does. The next EndBlock bonds it if it ranks among the +// first MaxValidators. It fails when staking's params are not written, or the +// operator or the consensus key already has a validator. +func (p Precompile) AddGenesisValidator(block precompiles.BlockContext, state precompiles.State, g GenesisValidator) error { + if !chainparams.HasStaking(state) { + return errStakingNotWritten + } + if err := g.check(); err != nil { + return err + } + s := newStore(state) + if _, ok := s.validator(g.Operator); ok { + return fmt.Errorf("%w: %s", errValidatorExists, g.Operator) + } + if s.validatorByPubkey(g.ConsensusPubkey) != (common.Address{}) { + return fmt.Errorf("%w: %s", errPubkeyExists, g.ConsensusPubkey) + } + + v := validator{ + consensusPubkey: g.ConsensusPubkey, + status: statusUnbonded, + tokens: new(big.Int), + delegatorShares: new(big.Int), + minSelfDelegation: g.MinSelfDelegation, + } + s.setValidator(g.Operator, v) + s.validatorSet().Add(solstorage.AddressKey(g.Operator)) + s.setValidatorByPubkey(g.ConsensusPubkey, g.Operator) + s.powerIndex().insert(g.Operator, new(big.Int)) + if err := p.hooks().AfterValidatorCreated(block, state, g.Operator); err != nil { + return err + } + _, err := p.delegate(block, s, s.params(), g.Operator, g.Operator, &v, g.SelfDelegation, statusUnbonded, g.Operator) + return err +} + +// check requires an operator, a consensus key, a positive minimum +// self-delegation, and a self-delegation of whole usei at least that minimum. +func (g GenesisValidator) check() error { + switch { + case g.Operator == (common.Address{}): + return fmt.Errorf("%w: no operator", errInvalidGenesis) + case g.ConsensusPubkey == (common.Hash{}): + return fmt.Errorf("%w: no consensus key", errInvalidGenesis) + case g.MinSelfDelegation == nil || g.MinSelfDelegation.Sign() <= 0: + return fmt.Errorf("%w: minimum self-delegation must be positive", errInvalidGenesis) + } + if err := checkAmount(g.SelfDelegation); err != nil { + return fmt.Errorf("%w: self-delegation: %w", errInvalidGenesis, err) + } + if g.SelfDelegation.Cmp(g.MinSelfDelegation) < 0 { + return fmt.Errorf("%w: self-delegation below its minimum", errInvalidGenesis) + } + return nil +} diff --git a/giga/evmonly/precompiles/staking/helpers_test.go b/giga/evmonly/precompiles/staking/helpers_test.go index d62c3134fd..6d13373db9 100644 --- a/giga/evmonly/precompiles/staking/helpers_test.go +++ b/giga/evmonly/precompiles/staking/helpers_test.go @@ -2,14 +2,21 @@ package staking import ( "errors" + "fmt" "maps" "math/big" + "testing" "time" + "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/common" ethtypes "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/core/vm" + "github.com/stretchr/testify/require" "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles" + chainparams "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles/params" + "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles/solstorage" ) // memState is a map-backed precompiles.State and LogSink. @@ -116,6 +123,231 @@ func sei(n int64) *big.Int { return new(big.Int).Mul(big.NewInt(n), powerReduction) } +// testParams bond two validators, unbond over 100 seconds, and leave the +// voting power ratio unenforced. +var testParams = chainparams.Staking{ + UnbondingTime: 100 * second, + MaxValidators: 2, + MaxEntries: 7, + MaxVotingPowerRatio: decOne, + MaxVotingPowerEnforcementThreshold: new(big.Int), +} + +type harness struct { + t *testing.T + staking Precompile + state *memState + time uint64 + number uint64 + // failures are the last EndBlock's failures. + failures []error +} + +// newHarness starts staking with params and val1, val2 and val3 self-delegating +// 30, 20 and 10 SEI, then runs the first EndBlock, which bonds val1 and val2. +func newHarness(t *testing.T, params chainparams.Staking) *harness { + h := &harness{t: t, state: newMemState(), time: startTime} + require.NoError(t, SetParams(h.state, params)) + for i, op := range []common.Address{val1, val2, val3} { + self := sei(int64(30 - 10*i)) + h.state.AddBalance(op, self) + require.NoError(t, h.staking.AddGenesisValidator(h.block(), h.state, GenesisValidator{ + Operator: op, + ConsensusPubkey: common.BytesToHash(op[:]), + SelfDelegation: self, + MinSelfDelegation: sei(1), + })) + } + h.endBlock() + require.Empty(t, h.failures) + return h +} + +func (h *harness) block() precompiles.BlockContext { + return precompiles.BlockContext{Number: h.number, UnixNano: h.time} +} + +// endBlock runs EndBlock at the current block, then starts the next block one +// second later. +func (h *harness) endBlock() { + failures, err := h.staking.EndBlock(h.block(), h.state) + require.NoError(h.t, err) + h.failures = failures + h.number++ + h.time += second +} + +// advance ends blocks until it has ended one at least d after the current +// block, keeping every block's failures. +func (h *harness) advance(d uint64) { + var failures []error + for end := h.time + d; ; { + ended := h.time + h.endBlock() + failures = append(failures, h.failures...) + if ended >= end { + break + } + } + h.failures = failures +} + +type callOpts struct { + value *big.Int + readOnly bool + delegateCall bool +} + +// call runs method as caller. Like the EVM, it credits value to the precompile +// before running it, and undoes the call's writes when it fails. +func (h *harness) call(caller common.Address, opts callOpts, method string, args ...interface{}) error { + input, err := ABI.Pack(method, args...) + require.NoError(h.t, err) + return h.run(caller, opts, input) +} + +func (h *harness) run(caller common.Address, opts callOpts, input []byte) error { + snap := h.state.Snapshot() + if opts.value != nil { + require.NoError(h.t, h.state.SubBalance(caller, opts.value)) + h.state.AddBalance(Address, opts.value) + } + out, err := h.staking.Run(&precompiles.Context{ + Caller: caller, + Address: Address, + ApparentValue: opts.value, + ReadOnly: opts.readOnly, + DelegateCall: opts.delegateCall, + Block: h.block(), + State: h.state, + Logs: h.state, + }, input) + if err != nil { + h.state.RevertToSnapshot(snap) + } + if errors.Is(err, vm.ErrExecutionReverted) { + reason, unpackErr := abi.UnpackRevert(out) + require.NoError(h.t, unpackErr) + return fmt.Errorf("%w: %s", err, reason) + } + if err != nil { + return err + } + values, err := ABI.Methods[methodName(input)].Outputs.Unpack(out) + require.NoError(h.t, err) + require.Equal(h.t, []interface{}{true}, values) + return nil +} + +func methodName(input []byte) string { + m, err := ABI.MethodById(input[:4]) + if err != nil { + panic(err) + } + return m.Name +} + +// fund gives addr amount. +func (h *harness) fund(addr common.Address, amount *big.Int) { + h.state.AddBalance(addr, amount) +} + +func (h *harness) delegate(delegator, op common.Address, amount *big.Int) error { + h.fund(delegator, amount) + return h.call(delegator, callOpts{value: amount}, DelegateMethod, op) +} + +func (h *harness) undelegate(delegator, op common.Address, amount *big.Int) error { + return h.call(delegator, callOpts{}, UndelegateMethod, op, amount) +} + +func (h *harness) redelegate(delegator, src, dst common.Address, amount *big.Int) error { + return h.call(delegator, callOpts{}, RedelegateMethod, src, dst, amount) +} + +func (h *harness) store() store { + return newStore(h.state) +} + +func (h *harness) validator(op common.Address) validator { + v, ok := h.store().validator(op) + require.True(h.t, ok, "validator %s exists", op) + return v +} + +func (h *harness) shares(delegator, op common.Address) *big.Int { + shares, _ := h.store().delegation(delegator, op) + return shares +} + +func (h *harness) lastValidators() []validatorPower { + set, err := h.store().lastValidators() + require.NoError(h.t, err) + return set +} + +func (h *harness) powerIndex() []common.Address { + p := h.store().powerIndex() + out := []common.Address{} + for i := uint64(0); i < p.len(); i++ { + out = append(out, p.at(i)) + } + return out +} + +// requireReverts checks that err is a revert whose reason carries want's message. +func requireReverts(t *testing.T, err error, want error, msgAndArgs ...interface{}) { + t.Helper() + require.ErrorIs(t, err, vm.ErrExecutionReverted, msgAndArgs...) + require.ErrorContains(t, err, want.Error(), msgAndArgs...) +} + +// requireInvariants checks that each validator's shares are its delegations' +// shares, each escrow holds the tokens and balances it should, and the power +// index holds every unjailed validator in order. delegators are every account +// that may delegate. +func (h *harness) requireInvariants(delegators ...common.Address) { + t, s := h.t, h.store() + delegators = append(delegators, val1, val2, val3) + bonded, notBonded := new(big.Int), new(big.Int) + var unjailed []common.Address + set := s.validatorSet() + for i := uint64(0); i < set.Len(); i++ { + op := solstorage.MemberAddress(set.At(i)) + v := h.validator(op) + shares := new(big.Int) + for _, d := range delegators { + shares.Add(shares, h.shares(d, op)) + } + require.Equal(t, v.delegatorShares.String(), shares.String(), "%s's shares are its delegations'", op) + if v.bonded() { + bonded.Add(bonded, v.tokens) + } else { + notBonded.Add(notBonded, v.tokens) + } + if !v.jailed { + unjailed = append(unjailed, op) + } + require.Equal(t, op, s.validatorByPubkey(v.consensusPubkey)) + } + for _, d := range delegators { + for _, op := range []common.Address{val1, val2, val3} { + for _, e := range must(s.unbondingEntries(d, op)) { + notBonded.Add(notBonded, e.balance) + } + } + } + require.Equal(t, bonded.String(), h.state.GetBalance(BondedEscrow).String(), "the bonded escrow holds the bonded validators' tokens") + require.Equal(t, notBonded.String(), h.state.GetBalance(NotBondedEscrow).String(), "the not-bonded escrow holds the other validators' tokens and every unbonding balance") + + index := h.powerIndex() + require.ElementsMatch(t, unjailed, index, "the power index holds every unjailed validator") + for i := 1; i < len(index); i++ { + a, b := index[i-1], index[i] + require.True(t, ranksBefore(s.validatorPower(a), a, s.validatorPower(b), b), "the power index is in rank order: %v", index) + } +} + // must returns v, panicking on err, for test reads that cannot fail. func must[T any](v T, err error) T { if err != nil { diff --git a/giga/evmonly/precompiles/staking/hooks.go b/giga/evmonly/precompiles/staking/hooks.go new file mode 100644 index 0000000000..ca61410157 --- /dev/null +++ b/giga/evmonly/precompiles/staking/hooks.go @@ -0,0 +1,67 @@ +package staking + +import ( + "github.com/ethereum/go-ethereum/common" + + "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles" +) + +// Hooks are the calls staking makes into the precompiles that track its +// delegations and validators, at the points x/staking's StakingHooks are +// called. Each runs under the rules of the Run or EndBlock that calls it, and +// an error fails the operation that called it. +type Hooks interface { + AfterValidatorCreated(block precompiles.BlockContext, state precompiles.State, validator common.Address) error + BeforeDelegationCreated(block precompiles.BlockContext, state precompiles.State, delegator, validator common.Address) error + BeforeDelegationSharesModified(block precompiles.BlockContext, state precompiles.State, delegator, validator common.Address) error + BeforeDelegationRemoved(block precompiles.BlockContext, state precompiles.State, delegator, validator common.Address) error + AfterDelegationModified(block precompiles.BlockContext, state precompiles.State, delegator, validator common.Address) error + AfterValidatorBonded(block precompiles.BlockContext, state precompiles.State, validator common.Address) error + AfterValidatorBeginUnbonding(block precompiles.BlockContext, state precompiles.State, validator common.Address) error + AfterValidatorRemoved(block precompiles.BlockContext, state precompiles.State, validator common.Address) error +} + +// NoHooks is Hooks that does nothing. +type NoHooks struct{} + +var _ Hooks = NoHooks{} + +func (NoHooks) AfterValidatorCreated(precompiles.BlockContext, precompiles.State, common.Address) error { + return nil +} + +func (NoHooks) BeforeDelegationCreated(precompiles.BlockContext, precompiles.State, common.Address, common.Address) error { + return nil +} + +func (NoHooks) BeforeDelegationSharesModified(precompiles.BlockContext, precompiles.State, common.Address, common.Address) error { + return nil +} + +func (NoHooks) BeforeDelegationRemoved(precompiles.BlockContext, precompiles.State, common.Address, common.Address) error { + return nil +} + +func (NoHooks) AfterDelegationModified(precompiles.BlockContext, precompiles.State, common.Address, common.Address) error { + return nil +} + +func (NoHooks) AfterValidatorBonded(precompiles.BlockContext, precompiles.State, common.Address) error { + return nil +} + +func (NoHooks) AfterValidatorBeginUnbonding(precompiles.BlockContext, precompiles.State, common.Address) error { + return nil +} + +func (NoHooks) AfterValidatorRemoved(precompiles.BlockContext, precompiles.State, common.Address) error { + return nil +} + +// hooks returns p's Hooks, or NoHooks when it has none. +func (p Precompile) hooks() Hooks { + if p.Hooks == nil { + return NoHooks{} + } + return p.Hooks +} diff --git a/giga/evmonly/precompiles/staking/staking.go b/giga/evmonly/precompiles/staking/staking.go new file mode 100644 index 0000000000..b3946e7a1a --- /dev/null +++ b/giga/evmonly/precompiles/staking/staking.go @@ -0,0 +1,171 @@ +// Package staking is the EVM-only staking precompile. Its ABI is Staking.sol +// and its state is docs/giga-storage/StakingStorage.sol, held as contract +// storage at Address. Its params are the params precompile's staking subspace. +// +// It serves delegate, redelegate and undelegate, and its EndBlock updates the +// bonded set and completes matured unbondings and redelegations. Unlike +// x/staking, its queues are first-in first-out, so an entry never completes +// before one queued ahead of it, and it does not slash unbonding or +// redelegation entries. +package staking + +import ( + "bytes" + _ "embed" + "errors" + "fmt" + "math/big" + + "github.com/ethereum/go-ethereum/accounts/abi" + "github.com/ethereum/go-ethereum/core/vm" + + "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles" + chainparams "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles/params" +) + +//go:embed abi.json +var abiJSON []byte + +// ABI is the staking precompile's ABI. +var ABI = func() abi.ABI { + parsed, err := abi.JSON(bytes.NewReader(abiJSON)) + if err != nil { + panic(err) + } + return parsed +}() + +const ( + DelegateMethod = "delegate" + RedelegateMethod = "redelegate" + UndelegateMethod = "undelegate" +) + +// Events. +const ( + DelegateEvent = "Delegate" + RedelegateEvent = "Redelegate" + UndelegateEvent = "Undelegate" +) + +const authzUnsupported = "staking authorizations are not supported" + +// retiredMethods are the V2 methods, by signature, staking keeps in its ABI +// only to revert with a reason naming the call to use instead. They are checked +// before dispatch. +var retiredMethods = map[string]string{ + "delegate(string)": "delegate(string) is not supported; use delegate(address) with the validator's operator address", + "redelegate(string,string,uint256)": "redelegate(string,string,uint256) is not supported; use redelegate(address,address,uint256) with the validators' operator addresses and an amount in wei", + "undelegate(string,uint256)": "undelegate(string,uint256) is not supported; use undelegate(address,uint256) with the validator's operator address and an amount in wei", + "grantStakingAuthorization(address,string[],uint256,int64)": authzUnsupported, + "delegateWithAuthorization(address,string)": authzUnsupported, + "redelegateWithAuthorization(address,string,string,uint256)": authzUnsupported, + "undelegateWithAuthorization(address,string,uint256)": authzUnsupported, + "revokeStakingAuthorization(address)": authzUnsupported, +} + +// Flat per-call gas, as V2's pcommon.DefaultGasCost prices it from the +// Cosmos KV gas config, charged on the arguments after the method selector. +const ( + unknownMethodGas = 3_000 + transactionGas = 2_000 + transactionByteGas = 30 +) + +var ( + errDelegateCall = errors.New("cannot delegatecall staking") + errStaticCall = fmt.Errorf("cannot call staking precompile from staticcall: %w", vm.ErrWriteProtection) + errNonPayable = errors.New("sending funds to a non-payable function") + errUnknownMethod = errors.New("unknown staking method") + errInvalidAmount = errors.New("amount must be a positive whole number of usei, in wei") + errNotStarted = errors.New("staking starts once its params are written") +) + +// Precompile is the staking precompile. Hooks are called as x/staking calls its +// StakingHooks; with none, nothing else tracks delegations. +type Precompile struct { + Hooks Hooks +} + +var ( + _ precompiles.Contract = Precompile{} + _ precompiles.EndBlocker = Precompile{} +) + +func (Precompile) RequiredGas(input []byte) uint64 { + if _, err := methodOf(input); err != nil { + return unknownMethodGas + } + return transactionGas + transactionByteGas*uint64(len(input)-4) //nolint:gosec // methodOf requires a 4-byte selector +} + +func (p Precompile) Run(ctx *precompiles.Context, input []byte) ([]byte, error) { + // CALLCODE also arrives as DelegateCall, with a value no transfer backed; + // refusing it keeps a call from delegating staking's own balance. + if ctx.DelegateCall { + return nil, errDelegateCall + } + method, err := methodOf(input) + if err != nil { + return nil, err + } + if reason, ok := retiredMethods[method.Sig]; ok { + return precompiles.Revert(reason) + } + if ctx.ReadOnly { + return nil, errStaticCall + } + args, err := method.Inputs.Unpack(input[4:]) + if err != nil { + return nil, err + } + if !method.IsPayable() && ctx.ApparentValue != nil && ctx.ApparentValue.Sign() != 0 { + return nil, errNonPayable + } + if check, ok := argChecks[method.Name]; ok { + if err := check(ctx, args); err != nil { + return precompiles.Revert(err.Error()) + } + } + if !chainparams.HasStaking(ctx.State) { + return nil, errNotStarted + } + s := newStore(ctx.State) + + switch method.Name { + case DelegateMethod: + return p.delegateCall(ctx, s, method, args) + case RedelegateMethod: + return p.redelegateCall(ctx, s, method, args) + case UndelegateMethod: + return p.undelegateCall(ctx, s, method, args) + } + return nil, errUnknownMethod +} + +func methodOf(input []byte) (*abi.Method, error) { + if len(input) < 4 { + return nil, errUnknownMethod + } + method, err := ABI.MethodById(input[:4]) + if err != nil { + return nil, errUnknownMethod + } + return method, nil +} + +// argChecks range-check each method's arguments, and delegate's value, before +// it reads state. A failure reverts the call with the error's message. +var argChecks = map[string]func(ctx *precompiles.Context, args []interface{}) error{ + DelegateMethod: func(ctx *precompiles.Context, _ []interface{}) error { return checkAmount(ctx.ApparentValue) }, + RedelegateMethod: func(_ *precompiles.Context, args []interface{}) error { return checkAmount(args[2].(*big.Int)) }, + UndelegateMethod: func(_ *precompiles.Context, args []interface{}) error { return checkAmount(args[1].(*big.Int)) }, +} + +// checkAmount requires a positive whole number of usei. +func checkAmount(amount *big.Int) error { + if amount == nil || amount.Sign() <= 0 || new(big.Int).Mod(amount, weiPerUsei).Sign() != 0 { + return fmt.Errorf("%w: %s", errInvalidAmount, amount) + } + return nil +} diff --git a/giga/evmonly/precompiles/staking/staking_test.go b/giga/evmonly/precompiles/staking/staking_test.go new file mode 100644 index 0000000000..400f77da86 --- /dev/null +++ b/giga/evmonly/precompiles/staking/staking_test.go @@ -0,0 +1,344 @@ +package staking + +import ( + "bytes" + "math/big" + "os" + "reflect" + "testing" + + "github.com/ethereum/go-ethereum/accounts/abi" + "github.com/ethereum/go-ethereum/common" + "github.com/stretchr/testify/require" + + "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles" + chainparams "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles/params" +) + +func TestDelegateIssuesSharesAndBondsTheTokens(t *testing.T) { + h := newHarness(t, testParams) + require.NoError(t, h.delegate(alice, val1, sei(5))) + + require.Equal(t, intToDec(sei(5)), h.shares(alice, val1), "a validator's first exchange rate is one share per token") + v := h.validator(val1) + require.Equal(t, sei(35), v.tokens) + require.Equal(t, intToDec(sei(35)), v.delegatorShares) + require.Equal(t, sei(55), h.state.GetBalance(BondedEscrow)) + require.Zero(t, h.state.GetBalance(Address).Sign(), "the call's value leaves the precompile") + require.True(t, h.store().delegatedValidators(alice).Contains(common.BytesToHash(val1[:]))) + + log := h.state.logs[len(h.state.logs)-1] + require.Equal(t, []common.Hash{ABI.Events[DelegateEvent].ID, addressTopic(alice), addressTopic(val1)}, log.Topics) + data, err := ABI.Events[DelegateEvent].Inputs.NonIndexed().Unpack(log.Data) + require.NoError(t, err) + require.Equal(t, []interface{}{sei(5), intToDec(sei(5))}, data) + h.requireInvariants(alice) +} + +func TestDelegateToAnUnbondedValidatorFundsTheNotBondedEscrow(t *testing.T) { + h := newHarness(t, testParams) + require.NoError(t, h.delegate(alice, val3, sei(5))) + require.Equal(t, sei(15), h.state.GetBalance(NotBondedEscrow)) + h.requireInvariants(alice) +} + +func TestDelegateRejectsBadCalls(t *testing.T) { + h := newHarness(t, testParams) + requireReverts(t, h.call(alice, callOpts{}, DelegateMethod, val1), errInvalidAmount) + h.fund(alice, sei(1)) + requireReverts(t, h.call(alice, callOpts{value: big.NewInt(1)}, DelegateMethod, val1), errInvalidAmount) + require.ErrorIs(t, h.delegate(alice, bob, sei(1)), errNoValidatorFound) + require.ErrorIs(t, h.call(alice, callOpts{value: sei(1), readOnly: true}, DelegateMethod, val1), errStaticCall) + require.ErrorIs(t, h.call(alice, callOpts{value: sei(1), delegateCall: true}, DelegateMethod, val1), errDelegateCall) + h.fund(alice, sei(1)) + require.ErrorIs(t, h.call(alice, callOpts{value: sei(1)}, UndelegateMethod, val1, sei(1)), errNonPayable) + require.ErrorIs(t, h.run(alice, callOpts{}, []byte{1, 2, 3}), errUnknownMethod) + h.requireInvariants(alice) +} + +func TestCallsWaitForParams(t *testing.T) { + h := &harness{t: t, state: newMemState(), time: startTime} + require.ErrorIs(t, h.delegate(alice, val1, sei(1)), errNotStarted) + failures, err := Precompile{}.EndBlock(h.block(), h.state) + require.NoError(t, err) + require.Empty(t, failures) + require.Empty(t, h.state.storage, "EndBlock writes nothing before staking's params") +} + +func TestUndelegateQueuesAnUnbondingEntry(t *testing.T) { + h := newHarness(t, testParams) + require.NoError(t, h.delegate(alice, val1, sei(5))) + require.NoError(t, h.undelegate(alice, val1, sei(2))) + + require.Equal(t, intToDec(sei(3)), h.shares(alice, val1)) + require.Equal(t, sei(33), h.validator(val1).tokens) + completion := h.time + testParams.UnbondingTime + require.Equal(t, []unbondingEntry{{creationHeight: h.number, completionTime: completion, initialBalance: sei(2), balance: sei(2)}}, + must(h.store().unbondingEntries(alice, val1))) + q := h.store().unbondingQueue() + require.Equal(t, uint64(1), q.tail()-q.head()) + require.Equal(t, sei(53), h.state.GetBalance(BondedEscrow)) + require.Equal(t, sei(12), h.state.GetBalance(NotBondedEscrow)) + + log := h.state.logs[len(h.state.logs)-1] + require.Equal(t, []common.Hash{ABI.Events[UndelegateEvent].ID, addressTopic(alice), addressTopic(val1)}, log.Topics) + data, err := ABI.Events[UndelegateEvent].Inputs.NonIndexed().Unpack(log.Data) + require.NoError(t, err) + require.Equal(t, []interface{}{sei(2), completion}, data) + h.requireInvariants(alice) +} + +func TestUndelegatingEverythingRemovesTheDelegation(t *testing.T) { + h := newHarness(t, testParams) + require.NoError(t, h.delegate(alice, val1, sei(5))) + require.NoError(t, h.undelegate(alice, val1, sei(5))) + _, found := h.store().delegation(alice, val1) + require.False(t, found) + require.Zero(t, h.store().delegatedValidators(alice).Len()) + h.requireInvariants(alice) +} + +func TestUndelegateRejectsBadCalls(t *testing.T) { + h := newHarness(t, testParams) + require.NoError(t, h.delegate(alice, val1, sei(5))) + requireReverts(t, h.undelegate(alice, val1, new(big.Int)), errInvalidAmount) + requireReverts(t, h.undelegate(alice, val1, big.NewInt(1)), errInvalidAmount) + require.ErrorIs(t, h.undelegate(alice, val1, sei(6)), errInvalidShares) + require.ErrorIs(t, h.undelegate(alice, bob, sei(1)), errNoValidatorFound) + require.ErrorIs(t, h.undelegate(bob, val1, sei(1)), errNoDelegation) + h.requireInvariants(alice) +} + +func TestUndelegateStopsAtMaxEntries(t *testing.T) { + params := testParams + params.MaxEntries = 2 + h := newHarness(t, params) + require.NoError(t, h.delegate(alice, val1, sei(5))) + require.NoError(t, h.undelegate(alice, val1, sei(1))) + require.NoError(t, h.undelegate(alice, val1, sei(1))) + require.ErrorIs(t, h.undelegate(alice, val1, sei(1)), errMaxUnbondingEntries) + require.NoError(t, h.delegate(alice, val2, sei(1))) + require.NoError(t, h.undelegate(alice, val2, sei(1)), "each validator has its own entries") + h.advance(params.UnbondingTime) + require.NoError(t, h.undelegate(alice, val1, sei(1)), "completed entries free their place") + h.requireInvariants(alice) +} + +func TestSelfUndelegationBelowTheMinimumJails(t *testing.T) { + h := newHarness(t, testParams) + require.NoError(t, h.undelegate(val2, val2, sei(20))) + v, ok := h.store().validator(val2) + require.True(t, ok) + require.True(t, v.jailed) + require.Zero(t, v.tokens.Sign()) + require.Equal(t, []common.Address{val1, val3}, h.powerIndex(), "a jailed validator leaves the power index") + h.requireInvariants() + + h.endBlock() + require.Empty(t, h.failures) + require.Equal(t, []validatorPower{{val1, 30}, {val3, 10}}, h.lastValidators(), "val3 takes the jailed validator's place") + require.Equal(t, statusUnbonding, h.validator(val2).status) + h.requireInvariants() +} + +func TestRedelegateMovesTheStakeAndQueuesTheEntry(t *testing.T) { + h := newHarness(t, testParams) + require.NoError(t, h.delegate(alice, val1, sei(5))) + require.NoError(t, h.redelegate(alice, val1, val2, sei(2))) + + require.Equal(t, intToDec(sei(3)), h.shares(alice, val1)) + require.Equal(t, intToDec(sei(2)), h.shares(alice, val2)) + require.Equal(t, sei(33), h.validator(val1).tokens) + require.Equal(t, sei(22), h.validator(val2).tokens) + require.Equal(t, big.NewInt(1), h.store().redelegationEntryCount(alice, val1, val2)) + require.Equal(t, big.NewInt(1), h.store().receivingRedelegations(val2, alice)) + + s, q := h.store(), h.store().redelegationQueue() + require.Equal(t, uint64(1), q.tail()-q.head()) + e := q.entry(q.head()) + completion := h.time + testParams.UnbondingTime + require.Equal(t, completion, s.Uint64(at(e, queueCompletionTime), queueCompletionTime.offset)) + require.Equal(t, alice, s.AddressAt(at(e, redelegationQueueDelegator), redelegationQueueDelegator.offset)) + require.Equal(t, h.number, s.Uint64(at(e, redelegationQueueCreationHeight), redelegationQueueCreationHeight.offset)) + require.Equal(t, val1, s.AddressAt(at(e, redelegationQueueSrcValidator), redelegationQueueSrcValidator.offset)) + require.Equal(t, val2, s.AddressAt(at(e, redelegationQueueDstValidator), redelegationQueueDstValidator.offset)) + require.Equal(t, sei(2), s.Uint256(at(e, redelegationQueueInitialBalance))) + require.Equal(t, intToDec(sei(2)), s.Uint256(at(e, redelegationQueueSharesDst))) + + log := h.state.logs[len(h.state.logs)-1] + require.Equal(t, []common.Hash{ABI.Events[RedelegateEvent].ID, addressTopic(alice), addressTopic(val1), addressTopic(val2)}, log.Topics) + data, err := ABI.Events[RedelegateEvent].Inputs.NonIndexed().Unpack(log.Data) + require.NoError(t, err) + require.Equal(t, []interface{}{sei(2), completion}, data) + h.requireInvariants(alice) +} + +func TestRedelegatingFromAnUnbondedValidatorCompletesAtOnce(t *testing.T) { + h := newHarness(t, testParams) + require.NoError(t, h.delegate(alice, val3, sei(5))) + require.NoError(t, h.redelegate(alice, val3, val1, sei(5))) + require.Zero(t, h.store().redelegationEntryCount(alice, val3, val1).Sign()) + q := h.store().redelegationQueue() + require.Equal(t, q.head(), q.tail(), "no entry is queued") + require.Equal(t, sei(55), h.state.GetBalance(BondedEscrow), "the tokens move to the bonded escrow") + data, err := ABI.Events[RedelegateEvent].Inputs.NonIndexed().Unpack(h.state.logs[len(h.state.logs)-1].Data) + require.NoError(t, err) + require.Equal(t, []interface{}{sei(5), uint64(0)}, data) + h.requireInvariants(alice) +} + +func TestRedelegatingOutOfAnOpenRedelegationWaits(t *testing.T) { + h := newHarness(t, testParams) + require.NoError(t, h.delegate(alice, val1, sei(5))) + require.NoError(t, h.redelegate(alice, val1, val2, sei(2))) + require.ErrorIs(t, h.redelegate(alice, val2, val1, sei(1)), errTransitiveRedelegation) + + h.advance(testParams.UnbondingTime) + require.Empty(t, h.failures) + require.Zero(t, h.store().receivingRedelegations(val2, alice).Sign()) + require.NoError(t, h.redelegate(alice, val2, val1, sei(1))) + h.requireInvariants(alice) +} + +func TestRedelegateRejectsBadCalls(t *testing.T) { + params := testParams + params.MaxEntries = 1 + h := newHarness(t, params) + require.NoError(t, h.delegate(alice, val1, sei(5))) + requireReverts(t, h.redelegate(alice, val1, val2, new(big.Int)), errInvalidAmount) + require.ErrorIs(t, h.redelegate(alice, val1, val1, sei(1)), errSelfRedelegation) + require.ErrorIs(t, h.redelegate(alice, val1, bob, sei(1)), errBadRedelegationValidator) + require.ErrorIs(t, h.redelegate(alice, bob, val2, sei(1)), errNoValidatorFound) + require.ErrorIs(t, h.redelegate(alice, val1, val2, sei(6)), errInvalidShares) + require.NoError(t, h.redelegate(alice, val1, val2, sei(1))) + require.ErrorIs(t, h.redelegate(alice, val1, val2, sei(1)), errMaxRedelegationEntries) + h.requireInvariants(alice) +} + +func TestDelegateKeepsTheVotingPowerRatio(t *testing.T) { + params := testParams + params.MaxVotingPowerRatio = new(big.Int).Div(decOne, big.NewInt(2)) + params.MaxVotingPowerEnforcementThreshold = big.NewInt(1) + h := newHarness(t, params) + // val1 holds 30 of 50 bonded power; any more takes it past one half. + require.ErrorIs(t, h.delegate(alice, val1, sei(1)), errExceedMaxVotingPower) + require.NoError(t, h.delegate(alice, val2, sei(1))) + h.requireInvariants(alice) +} + +func TestThePowerIndexFollowsEveryChange(t *testing.T) { + h := newHarness(t, testParams) + require.Equal(t, []common.Address{val1, val2, val3}, h.powerIndex()) + require.NoError(t, h.delegate(alice, val3, sei(25))) + require.Equal(t, []common.Address{val3, val1, val2}, h.powerIndex()) + require.NoError(t, h.undelegate(alice, val3, sei(16))) + require.Equal(t, []common.Address{val1, val2, val3}, h.powerIndex()) + require.NoError(t, h.delegate(alice, val3, sei(1))) + require.Equal(t, []common.Address{val1, val2, val3}, h.powerIndex(), "a tie goes to the lower address") + require.NoError(t, h.delegate(bob, val3, sei(11))) + require.Equal(t, []common.Address{val3, val1, val2}, h.powerIndex()) + require.NoError(t, h.redelegate(bob, val3, val2, sei(11))) + require.Equal(t, []common.Address{val2, val1, val3}, h.powerIndex(), "one call moves two validators") + h.requireInvariants(alice, bob) +} + +func TestRetiredMethodsRevertNamingTheReplacement(t *testing.T) { + h := newHarness(t, testParams) + for sig, args := range map[string][]interface{}{ + "delegate(string)": {"seivaloper1"}, + "redelegate(string,string,uint256)": {"seivaloper1", "seivaloper2", big.NewInt(1)}, + "undelegate(string,uint256)": {"seivaloper1", big.NewInt(1)}, + "grantStakingAuthorization(address,string[],uint256,int64)": {bob, []string{"seivaloper1"}, big.NewInt(1), int64(1)}, + "delegateWithAuthorization(address,string)": {bob, "seivaloper1"}, + "redelegateWithAuthorization(address,string,string,uint256)": {bob, "seivaloper1", "seivaloper2", big.NewInt(1)}, + "undelegateWithAuthorization(address,string,uint256)": {bob, "seivaloper1", big.NewInt(1)}, + "revokeStakingAuthorization(address)": {bob}, + } { + method := methodBySig(t, sig) + input, err := method.Inputs.Pack(args...) + require.NoError(t, err, sig) + err = h.run(alice, callOpts{}, append(method.ID, input...)) + requireReverts(t, err, errorString(retiredMethods[sig]), sig) + } +} + +func TestEveryMethodIsServedOrRetired(t *testing.T) { + h := newHarness(t, testParams) + for name, method := range ABI.Methods { + if _, retired := retiredMethods[method.Sig]; retired { + continue + } + args := make([]interface{}, len(method.Inputs)) + for i, in := range method.Inputs { + args[i] = reflect.New(in.Type.GetType()).Elem().Interface() + if in.Type.T == abi.UintTy && in.Type.Size == 256 { + args[i] = sei(1) + } + } + input, err := method.Inputs.Pack(args...) + require.NoError(t, err, name) + require.NotErrorIs(t, h.run(alice, callOpts{}, append(method.ID, input...)), errUnknownMethod, name) + } +} + +// TestABIKeepsV2Methods pins the methods staking shares with precompiles/staking +// to V2's signatures, so callers of those selectors get a revert naming the +// call to use instead. +func TestABIKeepsV2Methods(t *testing.T) { + bz, err := os.ReadFile("../../../../precompiles/staking/abi.json") + require.NoError(t, err) + v2, err := abi.JSON(bytes.NewReader(bz)) + require.NoError(t, err) + for sig := range retiredMethods { + var found bool + for _, m := range v2.Methods { + found = found || m.Sig == sig + } + require.True(t, found, "%s is a V2 method", sig) + require.Equal(t, sig, methodBySig(t, sig).Sig) + } +} + +func TestAddGenesisValidatorRejectsReuse(t *testing.T) { + h := newHarness(t, testParams) + h.fund(bob, sei(10)) + g := GenesisValidator{Operator: val1, ConsensusPubkey: common.HexToHash("0x01"), SelfDelegation: sei(1), MinSelfDelegation: sei(1)} + require.ErrorIs(t, h.staking.AddGenesisValidator(h.block(), h.state, g), errValidatorExists) + g.Operator, g.ConsensusPubkey = bob, common.BytesToHash(val1[:]) + require.ErrorIs(t, h.staking.AddGenesisValidator(h.block(), h.state, g), errPubkeyExists) + g.ConsensusPubkey = common.HexToHash("0x01") + g.SelfDelegation = big.NewInt(1) + require.ErrorIs(t, h.staking.AddGenesisValidator(h.block(), h.state, g), errInvalidGenesis) + require.ErrorIs(t, Precompile{}.AddGenesisValidator(h.block(), newMemState(), g), errStakingNotWritten) +} + +func TestDefaultParamsAreValid(t *testing.T) { + require.NoError(t, DefaultParams().Validate()) + state := newMemState() + require.NoError(t, SetParams(state, DefaultParams())) + require.True(t, HasParams(state)) + require.Equal(t, DefaultParams(), chainparams.ReadStaking(state)) +} + +func TestRequiredGas(t *testing.T) { + input, err := ABI.Pack(UndelegateMethod, val1, sei(1)) + require.NoError(t, err) + require.Equal(t, uint64(transactionGas+transactionByteGas*64), Precompile{}.RequiredGas(input)) + require.Equal(t, uint64(unknownMethodGas), Precompile{}.RequiredGas([]byte{1})) +} + +func methodBySig(t *testing.T, sig string) abi.Method { + for _, m := range ABI.Methods { + if m.Sig == sig { + return m + } + } + t.Fatalf("no method %s", sig) + return abi.Method{} +} + +type errorString string + +func (e errorString) Error() string { return string(e) } + +var _ precompiles.Contract = Precompile{} diff --git a/giga/evmonly/precompiles/staking/validator.go b/giga/evmonly/precompiles/staking/validator.go index aa07b9e80e..da69f4b7a2 100644 --- a/giga/evmonly/precompiles/staking/validator.go +++ b/giga/evmonly/precompiles/staking/validator.go @@ -7,6 +7,7 @@ import ( "github.com/ethereum/go-ethereum/common" + "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles" "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles/solstorage" ) @@ -130,3 +131,110 @@ func (p powerIndex) move(op common.Address, from, to *big.Int) error { } return nil } + +// setTokensAndShares stores v as op's validator with tokens and shares, +// reordering it in the power index unless it is jailed. +func (s store) setTokensAndShares(op common.Address, v *validator, tokens, shares *big.Int) error { + if !v.jailed { + if err := s.powerIndex().move(op, consensusPower(v.tokens), consensusPower(tokens)); err != nil { + return err + } + } + v.tokens, v.delegatorShares = tokens, shares + s.setValidator(op, *v) + return nil +} + +// addTokensFromDelegation adds amount to v's tokens and returns the shares it +// issues, as x/staking's AddValidatorTokensAndShares does: the first delegation +// to a validator with no shares sets the exchange rate to one. +func (s store) addTokensFromDelegation(op common.Address, v *validator, amount *big.Int) (*big.Int, error) { + issued := intToDec(amount) + if v.delegatorShares.Sign() != 0 { + var err error + if issued, err = v.sharesFromTokens(amount); err != nil { + return nil, err + } + } + tokens := new(big.Int).Add(v.tokens, amount) + shares := new(big.Int).Add(v.delegatorShares, issued) + return issued, s.setTokensAndShares(op, v, tokens, shares) +} + +// removeDelegationShares takes shares from v and returns the tokens they are +// worth, truncated, as x/staking's RemoveValidatorTokensAndShares does: the last +// shares out take every token left. +func (s store) removeDelegationShares(op common.Address, v *validator, shares *big.Int) (*big.Int, error) { + remaining := new(big.Int).Sub(v.delegatorShares, shares) + if remaining.Sign() < 0 { + return nil, fmt.Errorf("%w: removing %s of %s", errInsufficientShares, shares, v.delegatorShares) + } + issued := new(big.Int).Set(v.tokens) + if remaining.Sign() != 0 { + issued = truncateDec(v.tokensFromShares(shares)) + } + tokens := new(big.Int).Sub(v.tokens, issued) + if tokens.Sign() < 0 { + return nil, fmt.Errorf("%w: removing %s tokens of %s", errInsufficientShares, issued, v.tokens) + } + return issued, s.setTokensAndShares(op, v, tokens, remaining) +} + +// jail jails op's validator and takes it out of the power index. +func (s store) jail(op common.Address, v *validator) error { + if err := s.powerIndex().remove(op, consensusPower(v.tokens)); err != nil { + return err + } + v.jailed = true + s.setValidator(op, *v) + return nil +} + +// removeValidator deletes op's validator, which must be unbonded and hold no +// tokens, and every index naming it, then runs AfterValidatorRemoved. +func (p Precompile) removeValidator(block precompiles.BlockContext, s store, op common.Address, v validator) error { + if v.status != statusUnbonded || v.tokens.Sign() != 0 { + return fmt.Errorf("%w: removing %s with status %d and %s tokens", errInvalidTransition, op, v.status, v.tokens) + } + if !v.jailed { + if err := s.powerIndex().remove(op, consensusPower(v.tokens)); err != nil { + return err + } + } + s.setValidatorByPubkey(v.consensusPubkey, common.Address{}) + s.validatorSet().Remove(solstorage.AddressKey(op)) + if err := s.deleteValidator(op); err != nil { + return err + } + return p.hooks().AfterValidatorRemoved(block, s.State, op) +} + +// bond makes op's validator bonded, as x/staking's bondValidator does. +func (p Precompile) bond(block precompiles.BlockContext, s store, op common.Address, v *validator) error { + if v.status != statusUnbonded && v.status != statusUnbonding { + return fmt.Errorf("%w: bonding %s with status %d", errInvalidTransition, op, v.status) + } + v.status = statusBonded + s.setValidator(op, *v) + return p.hooks().AfterValidatorBonded(block, s.State, op) +} + +// beginUnbonding makes op's validator unbonding until one unbonding period from +// now, as x/staking's beginUnbondingValidator does, and queues its completion. +func (p Precompile) beginUnbonding(block precompiles.BlockContext, s store, op common.Address, v *validator, unbondingTime uint64) error { + if v.status != statusBonded { + return fmt.Errorf("%w: unbonding %s with status %d", errInvalidTransition, op, v.status) + } + q := s.validatorQueue() + v.status = statusUnbonding + v.unbondingTime = q.clamp(block.UnixNano + unbondingTime) + v.unbondingHeight = block.Number + s.setValidator(op, *v) + e, err := q.push(v.unbondingTime) + if err != nil { + return err + } + s.SetUint64(at(e, validatorQueueUnbondingHeight), validatorQueueUnbondingHeight.offset, v.unbondingHeight) + s.SetAddressAt(at(e, validatorQueueOperator), validatorQueueOperator.offset, op) + return p.hooks().AfterValidatorBeginUnbonding(block, s.State, op) +} diff --git a/giga/evmonly/staking_precompile_test.go b/giga/evmonly/staking_precompile_test.go new file mode 100644 index 0000000000..d8d77c01b4 --- /dev/null +++ b/giga/evmonly/staking_precompile_test.go @@ -0,0 +1,146 @@ +package evmonly + +// Pins the staking precompile running through the executor on real transactions. + +import ( + "crypto/ecdsa" + "math/big" + "testing" + "time" + + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/crypto" + "github.com/stretchr/testify/require" + + "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles" + "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles/staking" +) + +var ( + stakingVal1 = common.HexToAddress("0x0000000000000000000000000000000000000a01") + stakingVal2 = common.HexToAddress("0x0000000000000000000000000000000000000a02") +) + +// seiWei returns n SEI in wei. +func seiWei(n int64) *big.Int { + return new(big.Int).Mul(big.NewInt(n), big.NewInt(1_000_000_000_000_000_000)) +} + +// stakingGenesis returns a state with staking's params, unbonding over 100 +// seconds, and two genesis validators self-delegating 30 and 20 SEI. +func stakingGenesis(t *testing.T) *MemoryState { + state := NewMemoryState() + params := staking.DefaultParams() + params.UnbondingTime = uint64(100 * time.Second) + params.MaxVotingPowerRatio = big.NewInt(1_000_000_000_000_000_000) + require.NoError(t, staking.SetParams(genesisState{state}, params)) + for i, op := range []common.Address{stakingVal1, stakingVal2} { + self := seiWei(int64(30 - 10*i)) + state.SetBalance(op, self) + require.NoError(t, staking.Precompile{}.AddGenesisValidator(precompiles.BlockContext{}, genesisState{state}, staking.GenesisValidator{ + Operator: op, + ConsensusPubkey: common.BytesToHash(op[:]), + SelfDelegation: self, + MinSelfDelegation: seiWei(1), + })) + } + return state +} + +func stakingRegistry() precompiles.Registry { + return precompiles.NewStaticRegistry(map[common.Address]precompiles.Contract{staking.Address: staking.Precompile{}}, staking.Address) +} + +func TestStakingPrecompileThroughExecutor(t *testing.T) { + chainID := big.NewInt(testChainID) + key, err := crypto.HexToECDSA(behaviorAnvilKey0) + require.NoError(t, err) + sender := crypto.PubkeyToAddress(key.PublicKey) + state := stakingGenesis(t) + state.SetBalance(sender, seiWei(100)) + + delegate, err := staking.ABI.Pack(staking.DelegateMethod, stakingVal2) + require.NoError(t, err) + undelegate, err := staking.ABI.Pack(staking.UndelegateMethod, stakingVal2, seiWei(4)) + require.NoError(t, err) + redelegate, err := staking.ABI.Pack(staking.RedelegateMethod, stakingVal2, stakingVal1, seiWei(1)) + require.NoError(t, err) + to := staking.Address + txs := [][]byte{ + signLegacyTxWithGasPrice(t, key, chainID, 0, &to, seiWei(10), delegate, 2_000_000, big.NewInt(0)), + signLegacyTxWithGasPrice(t, key, chainID, 1, &to, big.NewInt(0), undelegate, 2_000_000, big.NewInt(0)), + signLegacyTxWithGasPrice(t, key, chainID, 2, &to, big.NewInt(0), redelegate, 2_000_000, big.NewInt(0)), + } + cfg := Config{MinGasPrice: big.NewInt(0), CustomPrecompiles: stakingRegistry()} + block := blockContext(chainID) + result, err := NewExecutor(cfg, withTestState(state)).ExecuteBlock(t.Context(), BlockRequest{Context: block, Txs: txs}) + require.NoError(t, err) + for i, tx := range result.Txs { + require.NoError(t, tx.Err, "tx %d", i) + require.Equal(t, uint64(1), tx.Status, "tx %d", i) + require.Len(t, result.Receipts[i].Logs, 1, "tx %d logs its event", i) + } + state.ApplyChangeSet(result.ChangeSet) + + require.Equal(t, seiWei(90), state.GetBalance(sender)) + require.Zero(t, state.GetBalance(staking.Address).Sign()) + require.Equal(t, seiWei(56), state.GetBalance(staking.BondedEscrow), "the first EndBlock bonds both validators") + require.Equal(t, seiWei(4), state.GetBalance(staking.NotBondedEscrow), "the unbonding entry waits") + + block.Number++ + block.Time += 100 + result, err = NewExecutor(cfg, withTestState(state)).ExecuteBlock(t.Context(), BlockRequest{Context: block}) + require.NoError(t, err) + state.ApplyChangeSet(result.ChangeSet) + require.Equal(t, seiWei(94), state.GetBalance(sender), "the unbonding entry is paid") + require.Zero(t, state.GetBalance(staking.NotBondedEscrow).Sign()) +} + +func TestStakingPrecompileOCCMatchesSequential(t *testing.T) { + chainID := big.NewInt(testChainID) + keys := make([]*ecdsa.PrivateKey, len(anvilKeys)) + nonces := make([]uint64, len(anvilKeys)) + for i, hex := range anvilKeys { + key, err := crypto.HexToECDSA(hex) + require.NoError(t, err) + keys[i] = key + } + to := staking.Address + var txs [][]byte + send := func(i int, value *big.Int, method string, args ...interface{}) { + data, err := staking.ABI.Pack(method, args...) + require.NoError(t, err) + txs = append(txs, signLegacyTxWithGasPrice(t, keys[i], chainID, nonces[i], &to, value, data, 2_000_000, big.NewInt(0))) + nonces[i]++ + } + for i := range keys { + send(i, seiWei(int64(5+i)), staking.DelegateMethod, []common.Address{stakingVal1, stakingVal2}[i%2]) + } + send(0, nil, staking.UndelegateMethod, stakingVal1, seiWei(2)) + send(1, nil, staking.RedelegateMethod, stakingVal2, stakingVal1, seiWei(3)) + send(2, nil, staking.RedelegateMethod, stakingVal1, stakingVal2, seiWei(7)) + send(3, nil, staking.UndelegateMethod, stakingVal2, seiWei(8)) + send(4, seiWei(1), staking.DelegateMethod, stakingVal2) + + run := func(workers int) *BlockResult { + state := stakingGenesis(t) + for _, key := range keys { + state.SetBalance(crypto.PubkeyToAddress(key.PublicKey), seiWei(100)) + } + result, err := NewExecutor(Config{MinGasPrice: big.NewInt(0), OCCWorkers: workers, CustomPrecompiles: stakingRegistry()}, withTestState(state)). + ExecuteBlock(t.Context(), BlockRequest{Context: blockContext(chainID), Txs: txs}) + require.NoError(t, err) + return result + } + sequential, occ := run(1), run(4) + require.True(t, occ.OCCStats.Attempted) + require.False(t, occ.OCCStats.Fallback, occ.OCCStats.FallbackReason) + require.Positive(t, occ.OCCStats.RerunCount, "the block's staking txs conflict") + for i, tx := range sequential.Txs { + require.Equal(t, uint64(1), tx.Status, "tx %d", i) + } + require.Equal(t, sequential.GasUsed, occ.GasUsed) + require.Equal(t, sequential.Txs, occ.Txs) + require.Equal(t, sequential.Receipts, occ.Receipts) + require.Equal(t, sequential.ChangeSet, occ.ChangeSet) +} From 310f32a5cd3d42786b46329891ff14223f444563 Mon Sep 17 00:00:00 2001 From: Tony Chen Date: Mon, 9 Nov 2026 11:51:34 +0800 Subject: [PATCH 14/44] feat(staking): never jail a validator An operator whose self-delegation falls below its minimum keeps its validator in the power index, where x/staking jails it. Co-Authored-By: Claude Opus 5.5 --- .../evmonly/precompiles/staking/delegation.go | 11 +++-------- giga/evmonly/precompiles/staking/staking.go | 5 +++-- .../precompiles/staking/staking_test.go | 19 +++++++++---------- giga/evmonly/precompiles/staking/validator.go | 10 ---------- 4 files changed, 15 insertions(+), 30 deletions(-) diff --git a/giga/evmonly/precompiles/staking/delegation.go b/giga/evmonly/precompiles/staking/delegation.go index b64dce39eb..7590b68291 100644 --- a/giga/evmonly/precompiles/staking/delegation.go +++ b/giga/evmonly/precompiles/staking/delegation.go @@ -164,9 +164,9 @@ func validateUnbondAmount(s store, delegator, op common.Address, amount *big.Int } // unbond takes shares from delegator's delegation to op and returns the tokens -// they were worth, as x/staking's Unbond does. The tokens stay in op's escrow. -// An operator whose self-delegation falls below its minimum is jailed, and an -// unbonded validator left with no shares is removed. +// they were worth, as x/staking's Unbond does, except that an operator whose +// self-delegation falls below its minimum is not jailed. The tokens stay in +// op's escrow. An unbonded validator left with no shares is removed. func (p Precompile) unbond(block precompiles.BlockContext, s store, delegator, op common.Address, shares *big.Int) (*big.Int, error) { delegated, ok := s.delegation(delegator, op) if !ok { @@ -184,11 +184,6 @@ func (p Precompile) unbond(block precompiles.BlockContext, s store, delegator, o } remaining := new(big.Int).Sub(delegated, shares) - if delegator == op && !v.jailed && truncateDec(v.tokensFromShares(remaining)).Cmp(v.minSelfDelegation) < 0 { - if err := s.jail(op, &v); err != nil { - return nil, err - } - } if remaining.Sign() == 0 { if err := p.hooks().BeforeDelegationRemoved(block, s.State, delegator, op); err != nil { return nil, err diff --git a/giga/evmonly/precompiles/staking/staking.go b/giga/evmonly/precompiles/staking/staking.go index b3946e7a1a..3e8286e13b 100644 --- a/giga/evmonly/precompiles/staking/staking.go +++ b/giga/evmonly/precompiles/staking/staking.go @@ -4,8 +4,9 @@ // // It serves delegate, redelegate and undelegate, and its EndBlock updates the // bonded set and completes matured unbondings and redelegations. Unlike -// x/staking, its queues are first-in first-out, so an entry never completes -// before one queued ahead of it, and it does not slash unbonding or +// x/staking, it never jails a validator, so an operator may hold less than its +// minimum self-delegation; its queues are first-in first-out, so an entry never +// completes before one queued ahead of it; and it does not slash unbonding or // redelegation entries. package staking diff --git a/giga/evmonly/precompiles/staking/staking_test.go b/giga/evmonly/precompiles/staking/staking_test.go index 400f77da86..f8bf27a209 100644 --- a/giga/evmonly/precompiles/staking/staking_test.go +++ b/giga/evmonly/precompiles/staking/staking_test.go @@ -124,21 +124,20 @@ func TestUndelegateStopsAtMaxEntries(t *testing.T) { h.requireInvariants(alice) } -func TestSelfUndelegationBelowTheMinimumJails(t *testing.T) { +func TestSelfUndelegationBelowTheMinimumDoesNotJail(t *testing.T) { h := newHarness(t, testParams) + require.NoError(t, h.delegate(alice, val2, sei(15))) require.NoError(t, h.undelegate(val2, val2, sei(20))) - v, ok := h.store().validator(val2) - require.True(t, ok) - require.True(t, v.jailed) - require.Zero(t, v.tokens.Sign()) - require.Equal(t, []common.Address{val1, val3}, h.powerIndex(), "a jailed validator leaves the power index") - h.requireInvariants() + v := h.validator(val2) + require.False(t, v.jailed) + require.Equal(t, sei(15).String(), v.tokens.String()) + require.Equal(t, []common.Address{val1, val2, val3}, h.powerIndex(), "val2 keeps its place on alice's stake") + h.requireInvariants(alice) h.endBlock() require.Empty(t, h.failures) - require.Equal(t, []validatorPower{{val1, 30}, {val3, 10}}, h.lastValidators(), "val3 takes the jailed validator's place") - require.Equal(t, statusUnbonding, h.validator(val2).status) - h.requireInvariants() + require.Equal(t, []validatorPower{{val1, 30}, {val2, 15}}, h.lastValidators(), "val2 stays bonded with no self-delegation") + h.requireInvariants(alice) } func TestRedelegateMovesTheStakeAndQueuesTheEntry(t *testing.T) { diff --git a/giga/evmonly/precompiles/staking/validator.go b/giga/evmonly/precompiles/staking/validator.go index da69f4b7a2..e6aa1448c6 100644 --- a/giga/evmonly/precompiles/staking/validator.go +++ b/giga/evmonly/precompiles/staking/validator.go @@ -180,16 +180,6 @@ func (s store) removeDelegationShares(op common.Address, v *validator, shares *b return issued, s.setTokensAndShares(op, v, tokens, remaining) } -// jail jails op's validator and takes it out of the power index. -func (s store) jail(op common.Address, v *validator) error { - if err := s.powerIndex().remove(op, consensusPower(v.tokens)); err != nil { - return err - } - v.jailed = true - s.setValidator(op, *v) - return nil -} - // removeValidator deletes op's validator, which must be unbonded and hold no // tokens, and every index naming it, then runs AfterValidatorRemoved. func (p Precompile) removeValidator(block precompiles.BlockContext, s store, op common.Address, v validator) error { From 2117c934d0803c5b9e08cef30861e835e888b4c9 Mon Sep 17 00:00:00 2001 From: Tony Chen Date: Wed, 4 Nov 2026 14:53:02 +0800 Subject: [PATCH 15/44] test(staking): check delegations and EndBlock against x/staking Runs each delegate, undelegate, redelegate and EndBlock on the precompile and on x/staking's keeper side by side, and requires the same outcome, the same hooks and the same state after every step. Covers the delegation rules and the validator lifecycle in scenarios, plus seeded random operations. Co-Authored-By: Claude Opus 5.5 --- .../staking/parity_helpers_test.go | 663 ++++++++++++++++++ .../precompiles/staking/parity_test.go | 346 +++++++++ 2 files changed, 1009 insertions(+) create mode 100644 giga/evmonly/precompiles/staking/parity_helpers_test.go create mode 100644 giga/evmonly/precompiles/staking/parity_test.go diff --git a/giga/evmonly/precompiles/staking/parity_helpers_test.go b/giga/evmonly/precompiles/staking/parity_helpers_test.go new file mode 100644 index 0000000000..30b9d46012 --- /dev/null +++ b/giga/evmonly/precompiles/staking/parity_helpers_test.go @@ -0,0 +1,663 @@ +package staking + +import ( + "context" + "errors" + "fmt" + "log/slog" + "math/big" + "strings" + "testing" + "time" + + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/crypto" + "github.com/sei-protocol/seilog" + "github.com/stretchr/testify/require" + dbm "github.com/tendermint/tm-db" + + "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles" + chainparams "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles/params" + "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles/solstorage" + "github.com/sei-protocol/sei-chain/sei-cosmos/codec" + codectypes "github.com/sei-protocol/sei-chain/sei-cosmos/codec/types" + "github.com/sei-protocol/sei-chain/sei-cosmos/crypto/keys/ed25519" + "github.com/sei-protocol/sei-chain/sei-cosmos/std" + sdkstore "github.com/sei-protocol/sei-chain/sei-cosmos/store" + sdk "github.com/sei-protocol/sei-chain/sei-cosmos/types" + sdkerrors "github.com/sei-protocol/sei-chain/sei-cosmos/types/errors" + authkeeper "github.com/sei-protocol/sei-chain/sei-cosmos/x/auth/keeper" + authtypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/auth/types" + bankkeeper "github.com/sei-protocol/sei-chain/sei-cosmos/x/bank/keeper" + banktypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/bank/types" + paramskeeper "github.com/sei-protocol/sei-chain/sei-cosmos/x/params/keeper" + paramstypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/params/types" + stakingkeeper "github.com/sei-protocol/sei-chain/sei-cosmos/x/staking/keeper" + stakingtypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/staking/types" + tmproto "github.com/sei-protocol/sei-chain/sei-tendermint/proto/tendermint/types" +) + +const ( + bondDenom = "usei" + minterModule = "minter" + + // seiInUsei is one SEI in usei. + seiInUsei = 1_000_000 +) + +// toWei returns usei in wei. +func toWei(usei sdk.Int) *big.Int { + return new(big.Int).Mul(usei.BigInt(), weiPerUsei) +} + +// sharesToWei returns x/staking shares, counted in usei, as the precompile +// counts them, in wei. +func sharesToWei(shares sdk.Dec) *big.Int { + return new(big.Int).Mul(shares.BigInt(), weiPerUsei) +} + +// v2Params returns x/staking's params for the precompile's p. +func v2Params(p chainparams.Staking) stakingtypes.Params { + return stakingtypes.Params{ + UnbondingTime: time.Duration(p.UnbondingTime), //nolint:gosec // params bound it below MaxPeriod + MaxValidators: p.MaxValidators, + MaxEntries: p.MaxEntries, + BondDenom: bondDenom, + MinCommissionRate: sdk.ZeroDec(), + MaxVotingPowerRatio: sdk.NewDecFromBigIntWithPrec(p.MaxVotingPowerRatio, sdk.Precision), + MaxVotingPowerEnforcementThreshold: sdk.NewIntFromBigInt(p.MaxVotingPowerEnforcementThreshold), + } +} + +// v2Chain is x/staking's keeper, with the auth and bank keepers it moves +// tokens through, over in-memory stores. +type v2Chain struct { + t *testing.T + ctx sdk.Context + keeper stakingkeeper.Keeper + msgs stakingtypes.MsgServer + bank bankkeeper.BaseKeeper + accounts authkeeper.AccountKeeper +} + +func newV2Chain(t *testing.T, params stakingtypes.Params, hooks stakingtypes.StakingHooks) *v2Chain { + // x/staking logs every delegation the voting power ratio refuses as an error. + seilog.SetLevel("cosmos/x/staking/keeper", slog.LevelError+1) + keys := sdk.NewKVStoreKeys(authtypes.StoreKey, banktypes.StoreKey, stakingtypes.StoreKey, paramstypes.StoreKey) + tkey := sdk.NewTransientStoreKey(paramstypes.TStoreKey) + db := dbm.NewMemDB() + ms := sdkstore.NewCommitMultiStore(db) + for _, key := range keys { + ms.MountStoreWithDB(key, sdk.StoreTypeIAVL, db) + } + ms.MountStoreWithDB(tkey, sdk.StoreTypeTransient, db) + require.NoError(t, ms.LoadLatestVersion()) + ctx := sdk.NewContext(ms, tmproto.Header{}, false) + + registry := codectypes.NewInterfaceRegistry() + std.RegisterInterfaces(registry) + authtypes.RegisterInterfaces(registry) + stakingtypes.RegisterInterfaces(registry) + cdc := codec.NewProtoCodec(registry) + + paramsKeeper := paramskeeper.NewKeeper(cdc, codec.NewLegacyAmino(), keys[paramstypes.StoreKey], tkey) + accounts := authkeeper.NewAccountKeeper(cdc, keys[authtypes.StoreKey], paramsKeeper.Subspace(authtypes.ModuleName), + authtypes.ProtoBaseAccount, map[string][]string{ + minterModule: {authtypes.Minter}, + stakingtypes.BondedPoolName: {authtypes.Burner, authtypes.Staking}, + stakingtypes.NotBondedPoolName: {authtypes.Burner, authtypes.Staking}, + }) + bank := bankkeeper.NewBaseKeeper(cdc, keys[banktypes.StoreKey], accounts, paramsKeeper.Subspace(banktypes.ModuleName), map[string]bool{}) + bank.SetParams(ctx, banktypes.DefaultParams()) + keeper := stakingkeeper.NewKeeper(cdc, keys[stakingtypes.StoreKey], accounts, bank, paramsKeeper.Subspace(stakingtypes.ModuleName)) + keeper.SetParams(ctx, params) + keeper.SetHooks(hooks) + return &v2Chain{t: t, ctx: ctx, keeper: keeper, msgs: stakingkeeper.NewMsgServerImpl(keeper), bank: bank, accounts: accounts} +} + +// setBlock makes the current block number, at unixNano. +func (c *v2Chain) setBlock(number, unixNano uint64) { + c.ctx = c.ctx.WithBlockHeight(int64(number)).WithBlockTime(time.Unix(0, int64(unixNano))) //nolint:gosec // test heights and times fit +} + +// fund mints amount usei to addr. +func (c *v2Chain) fund(addr common.Address, amount sdk.Int) { + coins := sdk.NewCoins(sdk.NewCoin(bondDenom, amount)) + require.NoError(c.t, c.bank.MintCoins(c.ctx, minterModule, coins)) + require.NoError(c.t, c.bank.SendCoinsFromModuleToAccount(c.ctx, minterModule, sdk.AccAddress(addr[:]), coins)) +} + +// deliver runs msg as a transaction does: it fails msg's stateless checks +// before running it, and keeps no write of a run that fails. +func (c *v2Chain) deliver(msg interface{ ValidateBasic() error }, run func(context.Context) error) error { + if err := msg.ValidateBasic(); err != nil { + return err + } + ctx, write := c.ctx.CacheContext() + if err := run(sdk.WrapSDKContext(ctx)); err != nil { + return err + } + write() + return nil +} + +func (c *v2Chain) createValidator(op common.Address, pubkey common.Hash, self, minSelf sdk.Int) error { + zero := sdk.ZeroDec() + msg, err := stakingtypes.NewMsgCreateValidator(sdk.ValAddress(op[:]), &ed25519.PubKey{Key: pubkey[:]}, sdk.NewCoin(bondDenom, self), + stakingtypes.NewDescription(op.Hex(), "", "", "", ""), stakingtypes.NewCommissionRates(zero, zero, zero), minSelf) + require.NoError(c.t, err) + return c.deliver(msg, func(ctx context.Context) error { + _, err := c.msgs.CreateValidator(ctx, msg) + return err + }) +} + +func (c *v2Chain) delegate(delegator, op common.Address, amount sdk.Int) error { + msg := stakingtypes.NewMsgDelegate(sdk.AccAddress(delegator[:]), sdk.ValAddress(op[:]), sdk.NewCoin(bondDenom, amount)) + return c.deliver(msg, func(ctx context.Context) error { + _, err := c.msgs.Delegate(ctx, msg) + return err + }) +} + +func (c *v2Chain) undelegate(delegator, op common.Address, amount sdk.Int) error { + msg := stakingtypes.NewMsgUndelegate(sdk.AccAddress(delegator[:]), sdk.ValAddress(op[:]), sdk.NewCoin(bondDenom, amount)) + return c.deliver(msg, func(ctx context.Context) error { + _, err := c.msgs.Undelegate(ctx, msg) + return err + }) +} + +func (c *v2Chain) redelegate(delegator, src, dst common.Address, amount sdk.Int) error { + msg := stakingtypes.NewMsgBeginRedelegate(sdk.AccAddress(delegator[:]), sdk.ValAddress(src[:]), sdk.ValAddress(dst[:]), sdk.NewCoin(bondDenom, amount)) + return c.deliver(msg, func(ctx context.Context) error { + _, err := c.msgs.BeginRedelegate(ctx, msg) + return err + }) +} + +// delegatedTokens returns the usei delegator's delegation to op is worth, or +// zero when it has none. +func (c *v2Chain) delegatedTokens(delegator, op common.Address) sdk.Int { + d, found := c.keeper.GetDelegation(c.ctx, sdk.AccAddress(delegator[:]), sdk.ValAddress(op[:])) + v, ok := c.keeper.GetValidator(c.ctx, sdk.ValAddress(op[:])) + if !found || !ok { + return sdk.ZeroInt() + } + return v.TokensFromShares(d.Shares).TruncateInt() +} + +func (c *v2Chain) validator(op common.Address) (stakingtypes.Validator, bool) { + return c.keeper.GetValidator(c.ctx, sdk.ValAddress(op[:])) +} + +// stakingState is what staking holds that x/staking's rules decide, in the +// precompile's units. Unbonding and redelegation entries are keyed by the +// accounts and validators they name. +type stakingState struct { + validators map[common.Address]validatorState + delegations map[delegationKey]string + unbonding map[delegationKey][]unbondingEntryState + redelegations map[redelegationKey][]redelegationEntryState + redelegationCounts map[redelegationKey]uint64 + // receiving counts the redelegation entries into each validator, keyed by + // that validator. + receiving map[delegationKey]uint64 + lastValidators map[common.Address]uint64 + lastTotalPower string + powerIndex []common.Address + balances map[common.Address]string +} + +type delegationKey struct{ delegator, validator common.Address } + +type redelegationKey struct{ delegator, src, dst common.Address } + +type validatorState struct { + pubkey common.Hash + jailed bool + status uint8 + tokens string + shares string + minSelfDelegation string + unbondingHeight uint64 + unbondingTime uint64 +} + +type unbondingEntryState struct { + creationHeight, completionTime uint64 + initialBalance, balance string +} + +type redelegationEntryState struct { + creationHeight, completionTime uint64 + initialBalance, sharesDst string +} + +func newStakingState() stakingState { + return stakingState{ + validators: map[common.Address]validatorState{}, + delegations: map[delegationKey]string{}, + unbonding: map[delegationKey][]unbondingEntryState{}, + redelegations: map[redelegationKey][]redelegationEntryState{}, + redelegationCounts: map[redelegationKey]uint64{}, + receiving: map[delegationKey]uint64{}, + lastValidators: map[common.Address]uint64{}, + powerIndex: []common.Address{}, + balances: map[common.Address]string{}, + } +} + +// state returns x/staking's state for accounts, in the precompile's units. +func (c *v2Chain) state(accounts []common.Address) stakingState { + st := newStakingState() + for _, v := range c.keeper.GetAllValidators(c.ctx) { + pk, err := v.ConsPubKey() + require.NoError(c.t, err) + st.validators[common.BytesToAddress(v.GetOperator())] = validatorState{ + pubkey: common.BytesToHash(pk.Bytes()), + jailed: v.Jailed, + status: uint8(v.Status), //nolint:gosec // a BondStatus + tokens: toWei(v.Tokens).String(), + shares: sharesToWei(v.DelegatorShares).String(), + minSelfDelegation: toWei(v.MinSelfDelegation).String(), + unbondingHeight: uint64(v.UnbondingHeight), //nolint:gosec // a block height + unbondingTime: uint64(v.UnbondingTime.UnixNano()), //nolint:gosec // a block time + } + } + for _, d := range c.keeper.GetAllDelegations(c.ctx) { + key := delegationKey{common.BytesToAddress(d.GetDelegatorAddr()), common.BytesToAddress(d.GetValidatorAddr())} + st.delegations[key] = sharesToWei(d.Shares).String() + } + for _, a := range accounts { + for _, ubd := range c.keeper.GetAllUnbondingDelegations(c.ctx, sdk.AccAddress(a[:])) { + op, err := sdk.ValAddressFromBech32(ubd.ValidatorAddress) + require.NoError(c.t, err) + key := delegationKey{a, common.BytesToAddress(op)} + for _, e := range ubd.Entries { + st.unbonding[key] = append(st.unbonding[key], unbondingEntryState{ + creationHeight: uint64(e.CreationHeight), //nolint:gosec // a block height + completionTime: uint64(e.CompletionTime.UnixNano()), //nolint:gosec // a block time + initialBalance: toWei(e.InitialBalance).String(), + balance: toWei(e.Balance).String(), + }) + } + } + for _, red := range c.keeper.GetAllRedelegations(c.ctx, sdk.AccAddress(a[:]), nil, nil) { + src, err := sdk.ValAddressFromBech32(red.ValidatorSrcAddress) + require.NoError(c.t, err) + dst, err := sdk.ValAddressFromBech32(red.ValidatorDstAddress) + require.NoError(c.t, err) + key := redelegationKey{a, common.BytesToAddress(src), common.BytesToAddress(dst)} + for _, e := range red.Entries { + st.redelegations[key] = append(st.redelegations[key], redelegationEntryState{ + creationHeight: uint64(e.CreationHeight), //nolint:gosec // a block height + completionTime: uint64(e.CompletionTime.UnixNano()), //nolint:gosec // a block time + initialBalance: toWei(e.InitialBalance).String(), + sharesDst: sharesToWei(e.SharesDst).String(), + }) + } + st.redelegationCounts[key] = uint64(len(red.Entries)) + st.receiving[delegationKey{a, key.dst}] += uint64(len(red.Entries)) + } + st.balances[a] = toWei(c.bank.GetBalance(c.ctx, sdk.AccAddress(a[:]), bondDenom).Amount).String() + } + for _, v := range c.keeper.GetLastValidators(c.ctx) { + st.lastValidators[common.BytesToAddress(v.GetOperator())] = uint64(c.keeper.GetLastValidatorPower(c.ctx, v.GetOperator())) //nolint:gosec // a consensus power + } + st.lastTotalPower = c.keeper.GetLastTotalPower(c.ctx).String() + it := c.keeper.ValidatorsPowerStoreIterator(c.ctx) + for ; it.Valid(); it.Next() { + st.powerIndex = append(st.powerIndex, common.BytesToAddress(it.Value())) + } + require.NoError(c.t, it.Close()) + for escrow, pool := range map[common.Address]string{BondedEscrow: stakingtypes.BondedPoolName, NotBondedEscrow: stakingtypes.NotBondedPoolName} { + st.balances[escrow] = toWei(c.bank.GetBalance(c.ctx, c.accounts.GetModuleAddress(pool), bondDenom).Amount).String() + } + return st +} + +// parityState returns the precompile's state for accounts and validators, in +// the form v2Chain.state returns x/staking's. +func (h *harness) parityState(validators, accounts []common.Address) stakingState { + s, st := h.store(), newStakingState() + set := s.validatorSet() + for i := uint64(0); i < set.Len(); i++ { + op := solstorage.MemberAddress(set.At(i)) + v := h.validator(op) + st.validators[op] = validatorState{ + pubkey: v.consensusPubkey, + jailed: v.jailed, + status: v.status, + tokens: v.tokens.String(), + shares: v.delegatorShares.String(), + minSelfDelegation: v.minSelfDelegation.String(), + unbondingHeight: v.unbondingHeight, + unbondingTime: v.unbondingTime, + } + } + for _, a := range accounts { + delegated := s.delegatedValidators(a) + for i := uint64(0); i < delegated.Len(); i++ { + op := solstorage.MemberAddress(delegated.At(i)) + shares, _ := s.delegation(a, op) + st.delegations[delegationKey{a, op}] = shares.String() + } + for _, op := range validators { + for _, e := range must(s.unbondingEntries(a, op)) { + key := delegationKey{a, op} + st.unbonding[key] = append(st.unbonding[key], unbondingEntryState{ + creationHeight: e.creationHeight, + completionTime: e.completionTime, + initialBalance: e.initialBalance.String(), + balance: e.balance.String(), + }) + } + if n := s.receivingRedelegations(op, a); n.Sign() != 0 { + st.receiving[delegationKey{a, op}] = n.Uint64() + } + for _, dst := range validators { + if n := s.redelegationEntryCount(a, op, dst); n.Sign() != 0 { + st.redelegationCounts[redelegationKey{a, op, dst}] = n.Uint64() + } + } + } + st.balances[a] = h.state.GetBalance(a).String() + } + q := s.redelegationQueue() + for i := q.head(); i < q.tail(); i++ { + e := q.entry(i) + key := redelegationKey{ + s.AddressAt(at(e, redelegationQueueDelegator), redelegationQueueDelegator.offset), + s.AddressAt(at(e, redelegationQueueSrcValidator), redelegationQueueSrcValidator.offset), + s.AddressAt(at(e, redelegationQueueDstValidator), redelegationQueueDstValidator.offset), + } + st.redelegations[key] = append(st.redelegations[key], redelegationEntryState{ + creationHeight: s.Uint64(at(e, redelegationQueueCreationHeight), redelegationQueueCreationHeight.offset), + completionTime: s.Uint64(at(e, queueCompletionTime), queueCompletionTime.offset), + initialBalance: s.Uint256(at(e, redelegationQueueInitialBalance)).String(), + sharesDst: s.Uint256(at(e, redelegationQueueSharesDst)).String(), + }) + } + for _, v := range h.lastValidators() { + st.lastValidators[v.operator] = v.power + } + st.lastTotalPower = s.lastTotalPower().String() + st.powerIndex = h.powerIndex() + st.balances[BondedEscrow] = h.state.GetBalance(BondedEscrow).String() + st.balances[NotBondedEscrow] = h.state.GetBalance(NotBondedEscrow).String() + return st +} + +// hookLog records each hook call as its name and the addresses it names. +type hookLog []string + +func (l *hookLog) add(name string, addrs ...common.Address) { + call := name + for _, a := range addrs { + call += " " + a.Hex() + } + *l = append(*l, call) +} + +// loggingHooks are Hooks that record each call. +type loggingHooks struct{ log *hookLog } + +var _ Hooks = loggingHooks{} + +func (h loggingHooks) AfterValidatorCreated(_ precompiles.BlockContext, _ precompiles.State, v common.Address) error { + h.log.add("AfterValidatorCreated", v) + return nil +} + +func (h loggingHooks) BeforeDelegationCreated(_ precompiles.BlockContext, _ precompiles.State, d, v common.Address) error { + h.log.add("BeforeDelegationCreated", d, v) + return nil +} + +func (h loggingHooks) BeforeDelegationSharesModified(_ precompiles.BlockContext, _ precompiles.State, d, v common.Address) error { + h.log.add("BeforeDelegationSharesModified", d, v) + return nil +} + +func (h loggingHooks) BeforeDelegationRemoved(_ precompiles.BlockContext, _ precompiles.State, d, v common.Address) error { + h.log.add("BeforeDelegationRemoved", d, v) + return nil +} + +func (h loggingHooks) AfterDelegationModified(_ precompiles.BlockContext, _ precompiles.State, d, v common.Address) error { + h.log.add("AfterDelegationModified", d, v) + return nil +} + +func (h loggingHooks) AfterValidatorBonded(_ precompiles.BlockContext, _ precompiles.State, v common.Address) error { + h.log.add("AfterValidatorBonded", v) + return nil +} + +func (h loggingHooks) AfterValidatorBeginUnbonding(_ precompiles.BlockContext, _ precompiles.State, v common.Address) error { + h.log.add("AfterValidatorBeginUnbonding", v) + return nil +} + +func (h loggingHooks) AfterValidatorRemoved(_ precompiles.BlockContext, _ precompiles.State, v common.Address) error { + h.log.add("AfterValidatorRemoved", v) + return nil +} + +// v2LoggingHooks are x/staking's StakingHooks that record each call. +type v2LoggingHooks struct{ log *hookLog } + +var _ stakingtypes.StakingHooks = v2LoggingHooks{} + +func (h v2LoggingHooks) AfterValidatorCreated(_ sdk.Context, v sdk.ValAddress) { + h.log.add("AfterValidatorCreated", common.BytesToAddress(v)) +} + +func (h v2LoggingHooks) BeforeValidatorModified(_ sdk.Context, v sdk.ValAddress) { + h.log.add("BeforeValidatorModified", common.BytesToAddress(v)) +} + +func (h v2LoggingHooks) AfterValidatorRemoved(_ sdk.Context, _ sdk.ConsAddress, v sdk.ValAddress) { + h.log.add("AfterValidatorRemoved", common.BytesToAddress(v)) +} + +func (h v2LoggingHooks) AfterValidatorBonded(_ sdk.Context, _ sdk.ConsAddress, v sdk.ValAddress) { + h.log.add("AfterValidatorBonded", common.BytesToAddress(v)) +} + +func (h v2LoggingHooks) AfterValidatorBeginUnbonding(_ sdk.Context, _ sdk.ConsAddress, v sdk.ValAddress) { + h.log.add("AfterValidatorBeginUnbonding", common.BytesToAddress(v)) +} + +func (h v2LoggingHooks) BeforeDelegationCreated(_ sdk.Context, d sdk.AccAddress, v sdk.ValAddress) { + h.log.add("BeforeDelegationCreated", common.BytesToAddress(d), common.BytesToAddress(v)) +} + +func (h v2LoggingHooks) BeforeDelegationSharesModified(_ sdk.Context, d sdk.AccAddress, v sdk.ValAddress) { + h.log.add("BeforeDelegationSharesModified", common.BytesToAddress(d), common.BytesToAddress(v)) +} + +func (h v2LoggingHooks) BeforeDelegationRemoved(_ sdk.Context, d sdk.AccAddress, v sdk.ValAddress) { + h.log.add("BeforeDelegationRemoved", common.BytesToAddress(d), common.BytesToAddress(v)) +} + +func (h v2LoggingHooks) AfterDelegationModified(_ sdk.Context, d sdk.AccAddress, v sdk.ValAddress) { + h.log.add("AfterDelegationModified", common.BytesToAddress(d), common.BytesToAddress(v)) +} + +func (h v2LoggingHooks) BeforeValidatorSlashed(_ sdk.Context, v sdk.ValAddress, _ sdk.Dec) { + h.log.add("BeforeValidatorSlashed", common.BytesToAddress(v)) +} + +// v2Errors pairs each x/staking error a delegation can fail with to the +// precompile's error for the same rule. +var v2Errors = []struct{ v2, precompile error }{ + {stakingtypes.ErrNoValidatorFound, errNoValidatorFound}, + {stakingtypes.ErrNoDelegation, errNoDelegation}, + {stakingtypes.ErrNotEnoughDelegationShares, errNotEnoughShares}, + {stakingtypes.ErrDelegatorShareExRateInvalid, errExRateInvalid}, + {stakingtypes.ErrExceedMaxVotingPowerRatio, errExceedMaxVotingPower}, + {stakingtypes.ErrMaxUnbondingDelegationEntries, errMaxUnbondingEntries}, + {stakingtypes.ErrMaxRedelegationEntries, errMaxRedelegationEntries}, + {stakingtypes.ErrSelfRedelegation, errSelfRedelegation}, + {stakingtypes.ErrBadRedelegationDst, errBadRedelegationValidator}, + {stakingtypes.ErrTransitiveRedelegation, errTransitiveRedelegation}, + {stakingtypes.ErrTinyRedelegationAmount, errTinyRedelegationAmount}, + // ValidateUnbondAmount's "invalid shares amount", for more than the delegation holds. + {sdkerrors.ErrInvalidRequest, errInvalidShares}, +} + +// pair runs every operation on the precompile and on x/staking, in wei on one +// and usei on the other, and checks that both end it the same way, call the +// same hooks, and leave the same state. +type pair struct { + t *testing.T + p *harness + v2 *v2Chain + pHooks, v2Hooks hookLog + validators []common.Address // every validator created, removed ones included + accounts []common.Address // every account that may delegate, operators included + outcomes map[string]int // how often each operation kind ended each way, and each hook was called +} + +// parityValidator is a validator a pair starts with, its amounts in usei. +type parityValidator struct { + op common.Address + self, minSelf int64 +} + +// newPair starts both sides with params, validators and the accounts that +// will delegate, then runs the first EndBlock. +func newPair(t *testing.T, params chainparams.Staking, validators []parityValidator, accounts ...common.Address) *pair { + pr := &pair{t: t, outcomes: map[string]int{}} + pr.p = &harness{t: t, state: newMemState(), time: startTime, staking: Precompile{Hooks: loggingHooks{&pr.pHooks}}} + require.NoError(t, SetParams(pr.p.state, params)) + pr.v2 = newV2Chain(t, v2Params(params), v2LoggingHooks{&pr.v2Hooks}) + pr.v2.setBlock(pr.p.number, pr.p.time) + pr.accounts = append(pr.accounts, accounts...) + for _, v := range validators { + pr.createValidator(v) + } + pr.endBlock() + return pr +} + +// apply runs an operation of kind on both sides, checks it, and returns V2's +// error. +func (pr *pair) apply(kind, detail string, onPrecompile, onV2 func() error) error { + t := pr.t + t.Helper() + step := fmt.Sprintf("%s at block %d", strings.TrimSpace(kind+" "+detail), pr.p.number) + pHooks, v2Hooks := len(pr.pHooks), len(pr.v2Hooks) + v2Err := onV2() + pErr := onPrecompile() + outcome := pr.requireSameOutcome(step, v2Err, pErr) + pr.outcomes[kind+": "+outcome]++ + if v2Err != nil { + pr.pHooks, pr.v2Hooks = pr.pHooks[:pHooks], pr.v2Hooks[:v2Hooks] + } + require.Equal(t, []string(pr.v2Hooks[v2Hooks:]), []string(pr.pHooks[pHooks:]), "%s calls the same hooks", step) + for _, call := range pr.pHooks[pHooks:] { + name, _, _ := strings.Cut(call, " ") + pr.outcomes["hook: "+name]++ + } + require.Equal(t, pr.v2.state(pr.accounts), pr.p.parityState(pr.validators, pr.accounts), "%s leaves the same state", step) + require.Zero(t, pr.p.state.GetBalance(Address).Sign(), "the precompile keeps nothing after %s", step) + return v2Err +} + +// requireSameOutcome checks that the precompile fails exactly when V2 does, +// by the same rule, and returns the outcome: "ok" or V2's error. +func (pr *pair) requireSameOutcome(step string, v2Err, pErr error) string { + t := pr.t + t.Helper() + if v2Err == nil { + require.NoError(t, pErr, "%s succeeds on V2", step) + return "ok" + } + require.Error(t, pErr, "%s fails on V2 with %v", step, v2Err) + for _, e := range v2Errors { + if errors.Is(v2Err, e.v2) { + require.ErrorIs(t, pErr, e.precompile, "%s fails on V2 with %v", step, v2Err) + return e.v2.Error() + } + } + require.Failf(t, "unmapped V2 error", "%s fails on V2 with %v", step, v2Err) + return "" +} + +func (pr *pair) createValidator(v parityValidator) { + pubkey := common.BytesToHash(crypto.Keccak256(v.op[:])) + self, minSelf := sdk.NewInt(v.self), sdk.NewInt(v.minSelf) + pr.v2.fund(v.op, self) + pr.p.fund(v.op, toWei(self)) + pr.validators = append(pr.validators, v.op) + pr.accounts = append(pr.accounts, v.op) + require.NoError(pr.t, pr.apply("create validator", v.op.Hex(), + func() error { + return pr.p.staking.AddGenesisValidator(pr.p.block(), pr.p.state, GenesisValidator{ + Operator: v.op, + ConsensusPubkey: pubkey, + SelfDelegation: toWei(self), + MinSelfDelegation: toWei(minSelf), + }) + }, + func() error { return pr.v2.createValidator(v.op, pubkey, self, minSelf) })) +} + +// delegate funds delegator with usei, then delegates it to op. +func (pr *pair) delegate(delegator, op common.Address, usei int64) error { + amount := sdk.NewInt(usei) + pr.v2.fund(delegator, amount) + pr.p.fund(delegator, toWei(amount)) + return pr.apply("delegate", fmt.Sprintf("%d usei from %s to %s", usei, delegator, op), + func() error { return pr.p.call(delegator, callOpts{value: toWei(amount)}, DelegateMethod, op) }, + func() error { return pr.v2.delegate(delegator, op, amount) }) +} + +func (pr *pair) undelegate(delegator, op common.Address, usei int64) error { + amount := sdk.NewInt(usei) + return pr.apply("undelegate", fmt.Sprintf("%d usei of %s from %s", usei, delegator, op), + func() error { return pr.p.undelegate(delegator, op, toWei(amount)) }, + func() error { return pr.v2.undelegate(delegator, op, amount) }) +} + +func (pr *pair) redelegate(delegator, src, dst common.Address, usei int64) error { + amount := sdk.NewInt(usei) + return pr.apply("redelegate", fmt.Sprintf("%d usei of %s from %s to %s", usei, delegator, src, dst), + func() error { return pr.p.redelegate(delegator, src, dst, toWei(amount)) }, + func() error { return pr.v2.redelegate(delegator, src, dst, amount) }) +} + +// endBlock runs EndBlock on both sides, then starts the next block one second +// later. +func (pr *pair) endBlock() { + _ = pr.apply("EndBlock", "", func() error { + pr.p.endBlock() + return errors.Join(pr.p.failures...) + }, func() error { + pr.v2.keeper.BlockValidatorUpdates(pr.v2.ctx) + return nil + }) + pr.v2.setBlock(pr.p.number, pr.p.time) +} + +// wait moves the current block d later. +func (pr *pair) wait(d uint64) { + pr.p.time += d + pr.v2.setBlock(pr.p.number, pr.p.time) +} + +// clampsRedelegation reports whether a redelegation out of src would queue +// behind a later entry and complete after V2's does, the precompile's +// first-in first-out queues' deviation. Only a redelegation out of an +// unbonding validator can, while the unbonding time stays the same. +func (pr *pair) clampsRedelegation(src common.Address) bool { + v, ok := pr.v2.validator(src) + if !ok || !v.IsUnbonding() { + return false + } + t := uint64(v.UnbondingTime.UnixNano()) //nolint:gosec // a block time + return pr.p.store().redelegationQueue().clamp(t) != t +} diff --git a/giga/evmonly/precompiles/staking/parity_test.go b/giga/evmonly/precompiles/staking/parity_test.go new file mode 100644 index 0000000000..b7dc5921c5 --- /dev/null +++ b/giga/evmonly/precompiles/staking/parity_test.go @@ -0,0 +1,346 @@ +package staking + +import ( + "fmt" + "math/big" + "math/rand" + "slices" + "testing" + + "github.com/ethereum/go-ethereum/common" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + chainparams "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles/params" + sdk "github.com/sei-protocol/sei-chain/sei-cosmos/types" + sdkerrors "github.com/sei-protocol/sei-chain/sei-cosmos/types/errors" + stakingtypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/staking/types" +) + +var ( + val4 = common.HexToAddress("0x0000000000000000000000000000000000000a04") + carol = common.HexToAddress("0x00000000000000000000000000000000000ca401") + unknownValidator = common.HexToAddress("0x0000000000000000000000000000000000000a0f") +) + +// parityParams bond three validators, unbond over thirty seconds, allow three +// entries, and cap a validator at half the bonded power. +var parityParams = chainparams.Staking{ + UnbondingTime: 30 * second, + MaxValidators: 3, + MaxEntries: 3, + MaxVotingPowerRatio: new(big.Int).Div(decOne, big.NewInt(2)), + MaxVotingPowerEnforcementThreshold: big.NewInt(1), +} + +// newParityPair starts val1 to val4 self-delegating 30, 25, 20 and 15 SEI, with +// alice, bob and carol to delegate, then runs the first EndBlock, which bonds +// val1, val2 and val3. +func newParityPair(t *testing.T) *pair { + return newPair(t, parityParams, []parityValidator{ + {val1, 30 * seiInUsei, seiInUsei}, + {val2, 25 * seiInUsei, seiInUsei}, + {val3, 20 * seiInUsei, seiInUsei}, + {val4, 15 * seiInUsei, seiInUsei}, + }, alice, bob, carol) +} + +func (pr *pair) v2UnbondingEntries(delegator, op common.Address) int { + ubd, _ := pr.v2.keeper.GetUnbondingDelegation(pr.v2.ctx, sdk.AccAddress(delegator[:]), sdk.ValAddress(op[:])) + return len(ubd.Entries) +} + +func (pr *pair) v2Redelegations(delegator common.Address) []stakingtypes.Redelegation { + return pr.v2.keeper.GetAllRedelegations(pr.v2.ctx, sdk.AccAddress(delegator[:]), nil, nil) +} + +func (pr *pair) v2Status(op common.Address) stakingtypes.BondStatus { + v, ok := pr.v2.validator(op) + require.True(pr.t, ok, "%s exists", op) + return v.Status +} + +// TestDelegationMatchesV2 takes delegate, undelegate and redelegate through +// each of x/staking's rules on the precompile and on x/staking, checking after +// every step that both end it alike, call the same hooks and hold the same +// state. +func TestDelegationMatchesV2(t *testing.T) { + for _, tc := range []struct { + name string + run func(t *testing.T, pr *pair) + }{ + {"undelegations from bonded and unbonded validators pay out when due", func(t *testing.T, pr *pair) { + require.NoError(t, pr.delegate(alice, val1, 5*seiInUsei)) + require.NoError(t, pr.delegate(alice, val4, 2*seiInUsei+7)) + require.NoError(t, pr.undelegate(alice, val1, 2*seiInUsei)) + require.NoError(t, pr.undelegate(alice, val4, seiInUsei+3)) + pr.endBlock() + require.NoError(t, pr.undelegate(alice, val1, seiInUsei)) + pr.wait(parityParams.UnbondingTime - second) + pr.endBlock() + require.Equal(t, 1, pr.v2UnbondingEntries(alice, val1), "the later entry waits") + require.Zero(t, pr.v2UnbondingEntries(alice, val4)) + pr.endBlock() + require.Zero(t, pr.v2UnbondingEntries(alice, val1)) + }}, + {"a full withdrawal removes the delegation", func(t *testing.T, pr *pair) { + require.NoError(t, pr.delegate(alice, val2, 3*seiInUsei)) + require.NoError(t, pr.undelegate(alice, val2, 3*seiInUsei)) + _, found := pr.v2.keeper.GetDelegation(pr.v2.ctx, sdk.AccAddress(alice[:]), sdk.ValAddress(val2[:])) + require.False(t, found) + }}, + {"unbonding and redelegation entries stop at the max entries", func(t *testing.T, pr *pair) { + require.NoError(t, pr.delegate(alice, val1, 10*seiInUsei)) + for range parityParams.MaxEntries { + require.NoError(t, pr.undelegate(alice, val1, seiInUsei)) + } + require.ErrorIs(t, pr.undelegate(alice, val1, seiInUsei), stakingtypes.ErrMaxUnbondingDelegationEntries) + for range parityParams.MaxEntries { + require.NoError(t, pr.redelegate(alice, val1, val2, seiInUsei)) + } + require.ErrorIs(t, pr.redelegate(alice, val1, val2, seiInUsei), stakingtypes.ErrMaxRedelegationEntries) + pr.wait(parityParams.UnbondingTime) + pr.endBlock() + require.NoError(t, pr.undelegate(alice, val1, seiInUsei)) + require.NoError(t, pr.redelegate(alice, val1, val2, seiInUsei)) + }}, + {"a redelegation out of a validator waits on the ones into it", func(t *testing.T, pr *pair) { + require.NoError(t, pr.delegate(alice, val1, 5*seiInUsei)) + require.NoError(t, pr.redelegate(alice, val1, val2, 2*seiInUsei)) + require.ErrorIs(t, pr.redelegate(alice, val2, val3, seiInUsei), stakingtypes.ErrTransitiveRedelegation) + require.NoError(t, pr.redelegate(alice, val1, val3, seiInUsei)) + pr.wait(parityParams.UnbondingTime) + pr.endBlock() + require.Empty(t, pr.v2Redelegations(alice)) + require.NoError(t, pr.redelegate(alice, val2, val3, seiInUsei)) + }}, + {"the voting power ratio caps delegations and redelegations", func(t *testing.T, pr *pair) { + require.ErrorIs(t, pr.delegate(alice, val1, 20*seiInUsei), stakingtypes.ErrExceedMaxVotingPowerRatio, "50 of 95") + require.NoError(t, pr.delegate(alice, val1, 10*seiInUsei), "40 of 85") + require.NoError(t, pr.delegate(bob, val2, 5*seiInUsei)) + require.ErrorIs(t, pr.redelegate(bob, val2, val1, 5*seiInUsei), stakingtypes.ErrExceedMaxVotingPowerRatio, "45 of 80") + require.NoError(t, pr.redelegate(bob, val2, val3, 5*seiInUsei), "25 of 80") + }}, + {"a delegation is refused by each of its checks", func(t *testing.T, pr *pair) { + require.ErrorIs(t, pr.delegate(alice, unknownValidator, seiInUsei), stakingtypes.ErrNoValidatorFound) + require.ErrorIs(t, pr.undelegate(alice, val1, seiInUsei), stakingtypes.ErrNoDelegation) + require.ErrorIs(t, pr.undelegate(alice, unknownValidator, seiInUsei), stakingtypes.ErrNoValidatorFound) + require.NoError(t, pr.delegate(alice, val1, seiInUsei)) + require.ErrorIs(t, pr.undelegate(alice, val1, seiInUsei+1), sdkerrors.ErrInvalidRequest) + require.ErrorIs(t, pr.redelegate(alice, val1, val1, seiInUsei), stakingtypes.ErrSelfRedelegation) + require.ErrorIs(t, pr.redelegate(alice, val1, unknownValidator, seiInUsei), stakingtypes.ErrBadRedelegationDst) + require.ErrorIs(t, pr.redelegate(alice, unknownValidator, val1, seiInUsei), stakingtypes.ErrNoValidatorFound) + require.ErrorIs(t, pr.redelegate(bob, val1, val2, seiInUsei), stakingtypes.ErrNoDelegation) + }}, + } { + t.Run(tc.name, func(t *testing.T) { + tc.run(t, newParityPair(t)) + }) + } +} + +// TestValidatorLifecycleMatchesV2 takes validators in and out of the bonded +// set, through jailing, unbonding and removal, on the precompile and on +// x/staking, checking after every step. +func TestValidatorLifecycleMatchesV2(t *testing.T) { + for _, tc := range []struct { + name string + run func(t *testing.T, pr *pair) + }{ + {"an operator below its minimum self-delegation is jailed, unbonds and is removed", func(t *testing.T, pr *pair) { + require.NoError(t, pr.delegate(alice, val3, seiInUsei)) + require.NoError(t, pr.undelegate(val3, val3, 19*seiInUsei+1)) + v, _ := pr.v2.validator(val3) + require.True(t, v.Jailed) + pr.endBlock() + require.Equal(t, stakingtypes.Unbonding, pr.v2Status(val3)) + require.Equal(t, stakingtypes.Bonded, pr.v2Status(val4)) + require.NoError(t, pr.delegate(bob, val3, seiInUsei), "a jailed validator takes delegations") + pr.wait(parityParams.UnbondingTime) + pr.endBlock() + require.Equal(t, stakingtypes.Unbonded, pr.v2Status(val3)) + require.NoError(t, pr.undelegate(val3, val3, seiInUsei-1)) + require.NoError(t, pr.undelegate(alice, val3, seiInUsei)) + require.NoError(t, pr.undelegate(bob, val3, seiInUsei)) + _, ok := pr.v2.validator(val3) + require.False(t, ok, "the last shares out remove an unbonded validator") + require.ErrorIs(t, pr.delegate(alice, val3, seiInUsei), stakingtypes.ErrNoValidatorFound) + pr.wait(parityParams.UnbondingTime) + pr.endBlock() + }}, + {"an operator at exactly its minimum self-delegation stays unjailed", func(t *testing.T, pr *pair) { + require.NoError(t, pr.undelegate(val2, val2, 24*seiInUsei)) + v, _ := pr.v2.validator(val2) + require.False(t, v.Jailed) + require.NoError(t, pr.undelegate(val2, val2, 1)) + v, _ = pr.v2.validator(val2) + require.True(t, v.Jailed) + }}, + {"validators leaving the bonded set together unbond in address order", func(t *testing.T, pr *pair) { + require.NoError(t, pr.undelegate(val3, val3, 20*seiInUsei)) + require.NoError(t, pr.undelegate(val2, val2, 25*seiInUsei)) + pr.endBlock() + require.Equal(t, stakingtypes.Unbonding, pr.v2Status(val2)) + require.Equal(t, stakingtypes.Unbonding, pr.v2Status(val3)) + pr.wait(parityParams.UnbondingTime) + pr.endBlock() + _, ok := pr.v2.validator(val2) + require.False(t, ok) + }}, + {"an unbonding validator left with no shares is removed when its unbonding ends", func(t *testing.T, pr *pair) { + require.NoError(t, pr.undelegate(val3, val3, 20*seiInUsei)) + pr.endBlock() + require.Equal(t, stakingtypes.Unbonding, pr.v2Status(val3)) + pr.wait(parityParams.UnbondingTime) + pr.endBlock() + _, ok := pr.v2.validator(val3) + require.False(t, ok) + }}, + {"redelegations out of unbonding and unbonded validators", func(t *testing.T, pr *pair) { + require.NoError(t, pr.delegate(alice, val3, 4*seiInUsei)) + require.NoError(t, pr.delegate(bob, val4, 15*seiInUsei)) + pr.endBlock() + require.Equal(t, stakingtypes.Unbonding, pr.v2Status(val3), "val4 outranks val3") + require.False(t, pr.clampsRedelegation(val3)) + require.NoError(t, pr.redelegate(alice, val3, val1, seiInUsei), "completes when val3's unbonding does") + pr.wait(parityParams.UnbondingTime) + pr.endBlock() + require.Equal(t, stakingtypes.Unbonded, pr.v2Status(val3)) + require.Empty(t, pr.v2Redelegations(alice)) + require.NoError(t, pr.redelegate(alice, val3, val2, seiInUsei), "completes at once") + require.Empty(t, pr.v2Redelegations(alice)) + require.NoError(t, pr.redelegate(alice, val1, val3, seiInUsei), "into an unbonded validator") + pr.endBlock() + }}, + {"a validator bonded again while unbonding stays bonded when that unbonding would end", func(t *testing.T, pr *pair) { + require.NoError(t, pr.delegate(alice, val4, 10*seiInUsei)) + pr.endBlock() + require.Equal(t, stakingtypes.Unbonding, pr.v2Status(val3), "val4 outranks val3") + require.NoError(t, pr.delegate(bob, val3, 10*seiInUsei)) + pr.endBlock() + require.Equal(t, stakingtypes.Bonded, pr.v2Status(val3)) + require.Equal(t, stakingtypes.Unbonding, pr.v2Status(val4), "val2 ranks before val4 at the same power") + pr.wait(parityParams.UnbondingTime) + pr.endBlock() + require.Equal(t, stakingtypes.Bonded, pr.v2Status(val3)) + require.Equal(t, stakingtypes.Unbonded, pr.v2Status(val4)) + }}, + } { + t.Run(tc.name, func(t *testing.T) { + tc.run(t, newParityPair(t)) + }) + } +} + +// TestRandomOperationsMatchV2 runs random delegations, undelegations, +// redelegations and EndBlocks on the precompile and on x/staking, checking +// after every step, and requires the runs between them to reach each rule. +// Redelegations the precompile's queue would complete later than x/staking are +// left out. +func TestRandomOperationsMatchV2(t *testing.T) { + outcomes := map[string]int{} + for seed := range int64(6) { + t.Run(fmt.Sprintf("seed %d", seed), func(t *testing.T) { + pr := newParityPair(t) + randomOperations(pr, rand.New(rand.NewSource(seed)), 300) //nolint:gosec // deterministic test data + for k, n := range pr.outcomes { + outcomes[k] += n + } + }) + } + for _, want := range []string{ + "delegate: ok", + "delegate: " + stakingtypes.ErrNoValidatorFound.Error(), + "delegate: " + stakingtypes.ErrExceedMaxVotingPowerRatio.Error(), + "undelegate: ok", + "undelegate: " + stakingtypes.ErrNoDelegation.Error(), + "undelegate: " + sdkerrors.ErrInvalidRequest.Error(), + "undelegate: " + stakingtypes.ErrMaxUnbondingDelegationEntries.Error(), + "redelegate: ok", + "redelegate: " + stakingtypes.ErrSelfRedelegation.Error(), + "redelegate: " + stakingtypes.ErrBadRedelegationDst.Error(), + "redelegate: " + stakingtypes.ErrTransitiveRedelegation.Error(), + "redelegate: " + stakingtypes.ErrMaxRedelegationEntries.Error(), + "hook: AfterValidatorBonded", + "hook: AfterValidatorBeginUnbonding", + "hook: BeforeDelegationRemoved", + } { + assert.Positive(t, outcomes[want], "the runs reach %q", want) + } +} + +// randomOperations runs steps random operations on pr. val1's operator never +// acts, so val1 keeps its power and the bonded set never has none. An actor +// often repeats its last redelegation, as reaching the max entries takes. +func randomOperations(pr *pair, rng *rand.Rand, steps int) { + actors := []common.Address{alice, bob, carol, val2, val3, val4} + targets := append(slices.Clone(pr.validators), unknownValidator) + lastRedelegation := map[common.Address][2]common.Address{} + for range steps { + d := pick(rng, actors) + switch n := rng.Intn(100); { + case n < 30: + _ = pr.delegate(d, pick(rng, targets), randomDelegation(rng)) + case n < 55: + op := pr.randomSource(rng, d, targets) + _ = pr.undelegate(d, op, randomUnbond(rng, pr.v2.delegatedTokens(d, op))) + case n < 80: + src, dst := pr.randomSource(rng, d, targets), pick(rng, targets) + if last, ok := lastRedelegation[d]; ok && rng.Intn(3) != 0 { + src, dst = last[0], last[1] + } + lastRedelegation[d] = [2]common.Address{src, dst} + if !pr.clampsRedelegation(src) { + _ = pr.redelegate(d, src, dst, randomUnbond(rng, pr.v2.delegatedTokens(d, src))) + } + case n < 95: + pr.endBlock() + default: + pr.wait(uint64(rng.Int63n(int64(parityParams.UnbondingTime)))) //nolint:gosec // a positive duration + pr.endBlock() + } + } +} + +// randomSource returns, mostly, a validator delegator delegates to. +func (pr *pair) randomSource(rng *rand.Rand, delegator common.Address, targets []common.Address) common.Address { + delegations := pr.v2.keeper.GetDelegatorDelegations(pr.v2.ctx, sdk.AccAddress(delegator[:]), 100) + if len(delegations) == 0 || rng.Intn(5) == 0 { + return pick(rng, targets) + } + return common.BytesToAddress(pick(rng, delegations).GetValidatorAddr()) +} + +// randomDelegation returns usei to delegate: mostly a few SEI, sometimes less +// than one unit of power, and sometimes enough to meet the voting power cap. +func randomDelegation(rng *rand.Rand) int64 { + switch rng.Intn(10) { + case 0: + return rng.Int63n(seiInUsei) + 1 + case 1: + return 10*seiInUsei + rng.Int63n(20*seiInUsei) + default: + return rng.Int63n(5*seiInUsei) + 1 + } +} + +// randomUnbond returns usei to unbond from a delegation worth tokens: mostly +// part of it, sometimes all of it, and sometimes more than it holds. +func randomUnbond(rng *rand.Rand, tokens sdk.Int) int64 { + if !tokens.IsPositive() { + return rng.Int63n(seiInUsei) + 1 + } + all := tokens.Int64() + switch rng.Intn(10) { + case 0: + return all + case 1: + return all + rng.Int63n(seiInUsei) + 1 + default: + return rng.Int63n(all) + 1 + } +} + +func pick[T any](rng *rand.Rand, xs []T) T { + return xs[rng.Intn(len(xs))] +} From 60ada4bb09cf74a9562ff367a56c5a6b716e9790 Mon Sep 17 00:00:00 2001 From: Tony Chen Date: Mon, 9 Nov 2026 12:04:53 +0800 Subject: [PATCH 16/44] docs(staking): state the unbonding queue's real EndBlock throughput Co-Authored-By: Claude Opus 5.5 --- giga/evmonly/precompiles/staking/endblock.go | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/giga/evmonly/precompiles/staking/endblock.go b/giga/evmonly/precompiles/staking/endblock.go index 5fb442d999..7ccd29417c 100644 --- a/giga/evmonly/precompiles/staking/endblock.go +++ b/giga/evmonly/precompiles/staking/endblock.go @@ -22,12 +22,15 @@ var ( errRedelegationCounted = errors.New("redelegation entry was not counted") ) -// endBlockBudget bounds the entries one EndBlock completes from each queue: one -// unit per entry, plus one per unbonding entry of the delegation it pays. -// Entries past the budget wait for the next EndBlock; an entry larger than the -// whole budget runs when nothing has spent it, and uses it up. Queuing an +// endBlockBudget bounds the work one EndBlock does on each queue: one unit per +// entry, plus one per unbonding entry of the delegation an unbonding queue entry +// pays. Entries past the budget wait for the next EndBlock; an entry larger than +// the whole budget runs when nothing has spent it, and uses it up. Queuing an // unbonding or redelegation entry writes at least five new slots, over 100,000 -// gas, so one EndBlock completes more entries than 300M gas of calls can queue. +// gas, so 300M gas of calls queue at most 3,000 a block. The redelegation queue +// completes that many; the unbonding queue, whose entries cost at least two +// units, completes at most 1,500, and a backlog waits for blocks with fewer +// undelegations. const endBlockBudget = 3_000 // EndBlock updates the bonded set, then completes the validators, unbonding From 4c53cb4f3b7ba40600b318a54d9bf36ee6c8c4d1 Mon Sep 17 00:00:00 2001 From: Tony Chen Date: Mon, 9 Nov 2026 11:53:06 +0800 Subject: [PATCH 17/44] test(staking): undo x/staking's jailing in the parity tests The precompile never jails, so after each undelegation and redelegation the V2 side unjails a validator x/staking jailed for its self-delegation. Co-Authored-By: Claude Opus 5.5 --- .../staking/parity_helpers_test.go | 29 ++++++++++++++++--- .../precompiles/staking/parity_test.go | 24 +++++++-------- 2 files changed, 35 insertions(+), 18 deletions(-) diff --git a/giga/evmonly/precompiles/staking/parity_helpers_test.go b/giga/evmonly/precompiles/staking/parity_helpers_test.go index 30b9d46012..c162dfbfee 100644 --- a/giga/evmonly/precompiles/staking/parity_helpers_test.go +++ b/giga/evmonly/precompiles/staking/parity_helpers_test.go @@ -162,18 +162,39 @@ func (c *v2Chain) delegate(delegator, op common.Address, amount sdk.Int) error { func (c *v2Chain) undelegate(delegator, op common.Address, amount sdk.Int) error { msg := stakingtypes.NewMsgUndelegate(sdk.AccAddress(delegator[:]), sdk.ValAddress(op[:]), sdk.NewCoin(bondDenom, amount)) - return c.deliver(msg, func(ctx context.Context) error { + if err := c.deliver(msg, func(ctx context.Context) error { _, err := c.msgs.Undelegate(ctx, msg) return err - }) + }); err != nil { + return err + } + c.unjail(op) + return nil } func (c *v2Chain) redelegate(delegator, src, dst common.Address, amount sdk.Int) error { msg := stakingtypes.NewMsgBeginRedelegate(sdk.AccAddress(delegator[:]), sdk.ValAddress(src[:]), sdk.ValAddress(dst[:]), sdk.NewCoin(bondDenom, amount)) - return c.deliver(msg, func(ctx context.Context) error { + if err := c.deliver(msg, func(ctx context.Context) error { _, err := c.msgs.BeginRedelegate(ctx, msg) return err - }) + }); err != nil { + return err + } + c.unjail(src) + return nil +} + +// unjail undoes x/staking's jailing of op's validator for a self-delegation +// below its minimum, which the precompile never does. x/staking's jail and +// unjail only take the validator out of its power index and put it back. +func (c *v2Chain) unjail(op common.Address) { + v, ok := c.validator(op) + if !ok || !v.Jailed { + return + } + consAddr, err := v.GetConsAddr() + require.NoError(c.t, err) + c.keeper.Unjail(c.ctx, consAddr) } // delegatedTokens returns the usei delegator's delegation to op is worth, or diff --git a/giga/evmonly/precompiles/staking/parity_test.go b/giga/evmonly/precompiles/staking/parity_test.go index b7dc5921c5..9563f0c02e 100644 --- a/giga/evmonly/precompiles/staking/parity_test.go +++ b/giga/evmonly/precompiles/staking/parity_test.go @@ -140,22 +140,20 @@ func TestDelegationMatchesV2(t *testing.T) { } // TestValidatorLifecycleMatchesV2 takes validators in and out of the bonded -// set, through jailing, unbonding and removal, on the precompile and on -// x/staking, checking after every step. +// set, through unbonding and removal, on the precompile and on x/staking, +// checking after every step. func TestValidatorLifecycleMatchesV2(t *testing.T) { for _, tc := range []struct { name string run func(t *testing.T, pr *pair) }{ - {"an operator below its minimum self-delegation is jailed, unbonds and is removed", func(t *testing.T, pr *pair) { + {"an operator below its minimum self-delegation is outranked, unbonds and is removed", func(t *testing.T, pr *pair) { require.NoError(t, pr.delegate(alice, val3, seiInUsei)) require.NoError(t, pr.undelegate(val3, val3, 19*seiInUsei+1)) - v, _ := pr.v2.validator(val3) - require.True(t, v.Jailed) pr.endBlock() require.Equal(t, stakingtypes.Unbonding, pr.v2Status(val3)) require.Equal(t, stakingtypes.Bonded, pr.v2Status(val4)) - require.NoError(t, pr.delegate(bob, val3, seiInUsei), "a jailed validator takes delegations") + require.NoError(t, pr.delegate(bob, val3, seiInUsei), "an unbonding validator takes delegations") pr.wait(parityParams.UnbondingTime) pr.endBlock() require.Equal(t, stakingtypes.Unbonded, pr.v2Status(val3)) @@ -168,13 +166,11 @@ func TestValidatorLifecycleMatchesV2(t *testing.T) { pr.wait(parityParams.UnbondingTime) pr.endBlock() }}, - {"an operator at exactly its minimum self-delegation stays unjailed", func(t *testing.T, pr *pair) { - require.NoError(t, pr.undelegate(val2, val2, 24*seiInUsei)) - v, _ := pr.v2.validator(val2) - require.False(t, v.Jailed) - require.NoError(t, pr.undelegate(val2, val2, 1)) - v, _ = pr.v2.validator(val2) - require.True(t, v.Jailed) + {"an operator with no self-delegation stays bonded on its delegators' stake", func(t *testing.T, pr *pair) { + require.NoError(t, pr.delegate(alice, val2, 20*seiInUsei)) + require.NoError(t, pr.undelegate(val2, val2, 25*seiInUsei)) + pr.endBlock() + require.Equal(t, stakingtypes.Bonded, pr.v2Status(val2)) }}, {"validators leaving the bonded set together unbond in address order", func(t *testing.T, pr *pair) { require.NoError(t, pr.undelegate(val3, val3, 20*seiInUsei)) @@ -236,7 +232,7 @@ func TestValidatorLifecycleMatchesV2(t *testing.T) { // redelegations and EndBlocks on the precompile and on x/staking, checking // after every step, and requires the runs between them to reach each rule. // Redelegations the precompile's queue would complete later than x/staking are -// left out. +// left out, and x/staking's jailing is undone, since the precompile never jails. func TestRandomOperationsMatchV2(t *testing.T) { outcomes := map[string]int{} for seed := range int64(6) { From 7982369c89205c447060f651d123f2709c46085f Mon Sep 17 00:00:00 2001 From: Tony Chen Date: Mon, 9 Nov 2026 12:21:33 +0800 Subject: [PATCH 18/44] fix(staking): take calls only once an EndBlock has bonded validators x/staking bonds its genesis validators before the first block, but here the first EndBlock does, so a delegation before it checked the voting power ratio against no bonded power. Run now refuses calls until the bonded set has power. Co-Authored-By: Claude Opus 5.5 --- giga/evmonly/precompiles/staking/staking.go | 9 ++++++--- giga/evmonly/precompiles/staking/staking_test.go | 14 +++++++++++++- giga/evmonly/staking_precompile_test.go | 11 +++++++++-- 3 files changed, 28 insertions(+), 6 deletions(-) diff --git a/giga/evmonly/precompiles/staking/staking.go b/giga/evmonly/precompiles/staking/staking.go index 3e8286e13b..df134ee6bf 100644 --- a/giga/evmonly/precompiles/staking/staking.go +++ b/giga/evmonly/precompiles/staking/staking.go @@ -79,7 +79,7 @@ var ( errNonPayable = errors.New("sending funds to a non-payable function") errUnknownMethod = errors.New("unknown staking method") errInvalidAmount = errors.New("amount must be a positive whole number of usei, in wei") - errNotStarted = errors.New("staking starts once its params are written") + errNotStarted = errors.New("staking starts once an EndBlock has bonded its first validators") ) // Precompile is the staking precompile. Hooks are called as x/staking calls its @@ -128,10 +128,13 @@ func (p Precompile) Run(ctx *precompiles.Context, input []byte) ([]byte, error) return precompiles.Revert(err.Error()) } } - if !chainparams.HasStaking(ctx.State) { + s := newStore(ctx.State) + // x/staking bonds its genesis validators before the first block runs, and + // here the first EndBlock does. Until then the voting power ratio would be + // checked against no bonded power. + if !chainparams.HasStaking(ctx.State) || s.lastTotalPower().Sign() == 0 { return nil, errNotStarted } - s := newStore(ctx.State) switch method.Name { case DelegateMethod: diff --git a/giga/evmonly/precompiles/staking/staking_test.go b/giga/evmonly/precompiles/staking/staking_test.go index f8bf27a209..4e04b641da 100644 --- a/giga/evmonly/precompiles/staking/staking_test.go +++ b/giga/evmonly/precompiles/staking/staking_test.go @@ -56,13 +56,25 @@ func TestDelegateRejectsBadCalls(t *testing.T) { h.requireInvariants(alice) } -func TestCallsWaitForParams(t *testing.T) { +func TestCallsWaitForTheFirstBondedSet(t *testing.T) { h := &harness{t: t, state: newMemState(), time: startTime} require.ErrorIs(t, h.delegate(alice, val1, sei(1)), errNotStarted) failures, err := Precompile{}.EndBlock(h.block(), h.state) require.NoError(t, err) require.Empty(t, failures) require.Empty(t, h.state.storage, "EndBlock writes nothing before staking's params") + + require.NoError(t, SetParams(h.state, testParams)) + h.fund(val1, sei(10)) + require.NoError(t, h.staking.AddGenesisValidator(h.block(), h.state, GenesisValidator{ + Operator: val1, + ConsensusPubkey: common.BytesToHash(val1[:]), + SelfDelegation: sei(10), + MinSelfDelegation: sei(1), + })) + require.ErrorIs(t, h.delegate(alice, val1, sei(1)), errNotStarted, "nothing is bonded before the first EndBlock") + h.endBlock() + require.NoError(t, h.delegate(alice, val1, sei(1))) } func TestUndelegateQueuesAnUnbondingEntry(t *testing.T) { diff --git a/giga/evmonly/staking_precompile_test.go b/giga/evmonly/staking_precompile_test.go index d8d77c01b4..b1a746c95f 100644 --- a/giga/evmonly/staking_precompile_test.go +++ b/giga/evmonly/staking_precompile_test.go @@ -27,7 +27,8 @@ func seiWei(n int64) *big.Int { } // stakingGenesis returns a state with staking's params, unbonding over 100 -// seconds, and two genesis validators self-delegating 30 and 20 SEI. +// seconds, and two genesis validators self-delegating 30 and 20 SEI, bonded by +// a genesis block's EndBlock as x/staking's genesis bonds them. func stakingGenesis(t *testing.T) *MemoryState { state := NewMemoryState() params := staking.DefaultParams() @@ -44,6 +45,12 @@ func stakingGenesis(t *testing.T) *MemoryState { MinSelfDelegation: seiWei(1), })) } + genesis := blockContext(big.NewInt(testChainID)) + genesis.Number, genesis.Time = 0, 0 + result, err := NewExecutor(Config{MinGasPrice: big.NewInt(0), CustomPrecompiles: stakingRegistry()}, withTestState(state)). + ExecuteBlock(t.Context(), BlockRequest{Context: genesis}) + require.NoError(t, err) + state.ApplyChangeSet(result.ChangeSet) return state } @@ -84,7 +91,7 @@ func TestStakingPrecompileThroughExecutor(t *testing.T) { require.Equal(t, seiWei(90), state.GetBalance(sender)) require.Zero(t, state.GetBalance(staking.Address).Sign()) - require.Equal(t, seiWei(56), state.GetBalance(staking.BondedEscrow), "the first EndBlock bonds both validators") + require.Equal(t, seiWei(56), state.GetBalance(staking.BondedEscrow), "both validators are bonded") require.Equal(t, seiWei(4), state.GetBalance(staking.NotBondedEscrow), "the unbonding entry waits") block.Number++ From ade0e82b96ea7447e15971042b2d3b36661137af Mon Sep 17 00:00:00 2001 From: Tony Chen Date: Mon, 9 Nov 2026 11:59:24 +0800 Subject: [PATCH 19/44] test(staking): scope the parity coverage check and the invalid-request pairing The random run checks that every rule is reached only when all its seeds ran and passed, so one seed can be run and debugged alone. ErrInvalidRequest pairs with errInvalidShares only for ValidateUnbondAmount's message, since every ValidateBasic refusal is an ErrInvalidRequest too. Co-Authored-By: Claude Opus 5.5 --- .../staking/parity_helpers_test.go | 38 +++++++++++-------- .../precompiles/staking/parity_test.go | 11 +++++- 2 files changed, 31 insertions(+), 18 deletions(-) diff --git a/giga/evmonly/precompiles/staking/parity_helpers_test.go b/giga/evmonly/precompiles/staking/parity_helpers_test.go index c162dfbfee..43ab462418 100644 --- a/giga/evmonly/precompiles/staking/parity_helpers_test.go +++ b/giga/evmonly/precompiles/staking/parity_helpers_test.go @@ -512,21 +512,27 @@ func (h v2LoggingHooks) BeforeValidatorSlashed(_ sdk.Context, v sdk.ValAddress, } // v2Errors pairs each x/staking error a delegation can fail with to the -// precompile's error for the same rule. -var v2Errors = []struct{ v2, precompile error }{ - {stakingtypes.ErrNoValidatorFound, errNoValidatorFound}, - {stakingtypes.ErrNoDelegation, errNoDelegation}, - {stakingtypes.ErrNotEnoughDelegationShares, errNotEnoughShares}, - {stakingtypes.ErrDelegatorShareExRateInvalid, errExRateInvalid}, - {stakingtypes.ErrExceedMaxVotingPowerRatio, errExceedMaxVotingPower}, - {stakingtypes.ErrMaxUnbondingDelegationEntries, errMaxUnbondingEntries}, - {stakingtypes.ErrMaxRedelegationEntries, errMaxRedelegationEntries}, - {stakingtypes.ErrSelfRedelegation, errSelfRedelegation}, - {stakingtypes.ErrBadRedelegationDst, errBadRedelegationValidator}, - {stakingtypes.ErrTransitiveRedelegation, errTransitiveRedelegation}, - {stakingtypes.ErrTinyRedelegationAmount, errTinyRedelegationAmount}, - // ValidateUnbondAmount's "invalid shares amount", for more than the delegation holds. - {sdkerrors.ErrInvalidRequest, errInvalidShares}, +// precompile's error for the same rule. msg narrows a V2 error that several +// rules share to the one whose message contains it. +var v2Errors = []struct { + v2 error + msg string + precompile error +}{ + {v2: stakingtypes.ErrNoValidatorFound, precompile: errNoValidatorFound}, + {v2: stakingtypes.ErrNoDelegation, precompile: errNoDelegation}, + {v2: stakingtypes.ErrNotEnoughDelegationShares, precompile: errNotEnoughShares}, + {v2: stakingtypes.ErrDelegatorShareExRateInvalid, precompile: errExRateInvalid}, + {v2: stakingtypes.ErrExceedMaxVotingPowerRatio, precompile: errExceedMaxVotingPower}, + {v2: stakingtypes.ErrMaxUnbondingDelegationEntries, precompile: errMaxUnbondingEntries}, + {v2: stakingtypes.ErrMaxRedelegationEntries, precompile: errMaxRedelegationEntries}, + {v2: stakingtypes.ErrSelfRedelegation, precompile: errSelfRedelegation}, + {v2: stakingtypes.ErrBadRedelegationDst, precompile: errBadRedelegationValidator}, + {v2: stakingtypes.ErrTransitiveRedelegation, precompile: errTransitiveRedelegation}, + {v2: stakingtypes.ErrTinyRedelegationAmount, precompile: errTinyRedelegationAmount}, + // ValidateUnbondAmount's, for more than the delegation holds. Every + // ValidateBasic refusal is an ErrInvalidRequest too. + {v2: sdkerrors.ErrInvalidRequest, msg: "invalid shares amount", precompile: errInvalidShares}, } // pair runs every operation on the precompile and on x/staking, in wei on one @@ -599,7 +605,7 @@ func (pr *pair) requireSameOutcome(step string, v2Err, pErr error) string { } require.Error(t, pErr, "%s fails on V2 with %v", step, v2Err) for _, e := range v2Errors { - if errors.Is(v2Err, e.v2) { + if errors.Is(v2Err, e.v2) && strings.Contains(v2Err.Error(), e.msg) { require.ErrorIs(t, pErr, e.precompile, "%s fails on V2 with %v", step, v2Err) return e.v2.Error() } diff --git a/giga/evmonly/precompiles/staking/parity_test.go b/giga/evmonly/precompiles/staking/parity_test.go index 9563f0c02e..9df64e2684 100644 --- a/giga/evmonly/precompiles/staking/parity_test.go +++ b/giga/evmonly/precompiles/staking/parity_test.go @@ -234,9 +234,11 @@ func TestValidatorLifecycleMatchesV2(t *testing.T) { // Redelegations the precompile's queue would complete later than x/staking are // left out, and x/staking's jailing is undone, since the precompile never jails. func TestRandomOperationsMatchV2(t *testing.T) { - outcomes := map[string]int{} - for seed := range int64(6) { + const seeds = 6 + outcomes, ran := map[string]int{}, 0 + for seed := range int64(seeds) { t.Run(fmt.Sprintf("seed %d", seed), func(t *testing.T) { + ran++ pr := newParityPair(t) randomOperations(pr, rand.New(rand.NewSource(seed)), 300) //nolint:gosec // deterministic test data for k, n := range pr.outcomes { @@ -244,6 +246,11 @@ func TestRandomOperationsMatchV2(t *testing.T) { } }) } + // Only all the runs together reach every rule, and a failed run's mismatch + // is the failure to read, so a failed or partial run skips this check. + if t.Failed() || ran < seeds { + return + } for _, want := range []string{ "delegate: ok", "delegate: " + stakingtypes.ErrNoValidatorFound.Error(), From 690a1744a04e9a74e4973a075fdbe4e489c9c02a Mon Sep 17 00:00:00 2001 From: Tony Chen Date: Thu, 5 Nov 2026 12:57:53 +0800 Subject: [PATCH 20/44] feat(evmonly): serve staking's bonded set as the validator set - Add staking.BondedValidators: the bonded set the last EndBlock stored, with each member's consensus key and power. - Add evmonly.ReadOnlyState: a custom precompile State over a committed store view, which rejects writes as a static call does. - GetValidators returns staking's bonded set from the committed state, and the configured validators until staking bonds one. A stored set that does not add up returns none. Staking is not yet registered in the node, so the configured validators still serve. Co-Authored-By: Claude Opus 5.5 --- giga/evmonly/custom_precompile.go | 7 ++ .../custom_precompile_execution_test.go | 16 +++ .../evmonly/precompiles/staking/bonded_set.go | 36 ++++++ .../precompiles/staking/bonded_set_test.go | 45 +++++++ giga/evmonly/precompiles/staking/storage.go | 6 + sei-tendermint/internal/evmonlyapp/app.go | 7 +- .../internal/evmonlyapp/validators.go | 58 +++++++++ .../internal/evmonlyapp/validators_test.go | 111 ++++++++++++++++++ 8 files changed, 281 insertions(+), 5 deletions(-) create mode 100644 giga/evmonly/precompiles/staking/bonded_set.go create mode 100644 giga/evmonly/precompiles/staking/bonded_set_test.go create mode 100644 sei-tendermint/internal/evmonlyapp/validators.go create mode 100644 sei-tendermint/internal/evmonlyapp/validators_test.go diff --git a/giga/evmonly/custom_precompile.go b/giga/evmonly/custom_precompile.go index 5a3ca176de..ab23348824 100644 --- a/giga/evmonly/custom_precompile.go +++ b/giga/evmonly/custom_precompile.go @@ -14,6 +14,7 @@ import ( "github.com/holiman/uint256" "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles" + gigatypes "github.com/sei-protocol/sei-chain/sei-db/state_db/giga/types" ) var ( @@ -167,6 +168,12 @@ var ( _ precompiles.LogSink = (*precompileState)(nil) ) +// ReadOnlyState returns view as a custom precompile's State under a static +// call: a write is dropped and fails the state, and nothing is charged. +func ReadOnlyState(view gigatypes.EVMStateView) precompiles.State { + return &precompileState{db: newNativeStateDB(gigaSnapshotStateReader{snapshot: view}), readOnly: true} +} + func (s *precompileState) GetBalance(addr common.Address) *big.Int { return s.db.GetBalance(addr).ToBig() } diff --git a/giga/evmonly/custom_precompile_execution_test.go b/giga/evmonly/custom_precompile_execution_test.go index 2ebee208da..5903b44e21 100644 --- a/giga/evmonly/custom_precompile_execution_test.go +++ b/giga/evmonly/custom_precompile_execution_test.go @@ -270,3 +270,19 @@ func TestPrecompileStateMetersLogs(t *testing.T) { require.ErrorIs(t, s.err, vm.ErrOutOfGas) require.Empty(t, db.logs, "the log is dropped") } + +func TestReadOnlyStateReadsTheViewAndFailsOnAWrite(t *testing.T) { + slot, value := testHash(0x01), testHash(0x02) + source := NewMemoryState() + source.SetState(registeredPrecompileAddress, slot, value) + view := NewMemoryStore(source).OpenView() + defer view.Close() + + state := ReadOnlyState(view) + require.Equal(t, value, state.GetState(registeredPrecompileAddress, slot)) + require.False(t, state.Failed()) + + state.SetState(registeredPrecompileAddress, slot, common.Hash{}) + require.True(t, state.Failed()) + require.Equal(t, value, view.GetStorage(registeredPrecompileAddress, slot), "the view is unchanged") +} diff --git a/giga/evmonly/precompiles/staking/bonded_set.go b/giga/evmonly/precompiles/staking/bonded_set.go new file mode 100644 index 0000000000..c0c90e4bca --- /dev/null +++ b/giga/evmonly/precompiles/staking/bonded_set.go @@ -0,0 +1,36 @@ +package staking + +import ( + "fmt" + + "github.com/ethereum/go-ethereum/common" + + "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles" +) + +// BondedValidator is a member of the bonded set. +type BondedValidator struct { + Operator common.Address + ConsensusPubkey common.Hash // ed25519 + Power uint64 +} + +// BondedValidators returns the bonded set the last EndBlock stored, in the +// order it ranked them, or none before staking has bonded a set. It fails when +// the stored set does not add up. +func BondedValidators(state precompiles.State) ([]BondedValidator, error) { + s := newStore(state) + last, err := s.lastValidators() + if err != nil { + return nil, err + } + bonded := make([]BondedValidator, len(last)) + for i, v := range last { + pubkey := s.consensusPubkey(v.operator) + if pubkey == (common.Hash{}) { + return nil, fmt.Errorf("%w: %s", errUnknownValidator, v.operator) + } + bonded[i] = BondedValidator{Operator: v.operator, ConsensusPubkey: pubkey, Power: v.power} + } + return bonded, nil +} diff --git a/giga/evmonly/precompiles/staking/bonded_set_test.go b/giga/evmonly/precompiles/staking/bonded_set_test.go new file mode 100644 index 0000000000..218e93ce46 --- /dev/null +++ b/giga/evmonly/precompiles/staking/bonded_set_test.go @@ -0,0 +1,45 @@ +package staking + +import ( + "testing" + + "github.com/ethereum/go-ethereum/common" + "github.com/stretchr/testify/require" + + "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles/solstorage" +) + +func TestBondedValidatorsAreTheSetTheLastEndBlockStored(t *testing.T) { + h := newHarness(t, testParams) + want := []BondedValidator{ + {Operator: val1, ConsensusPubkey: common.BytesToHash(val1[:]), Power: 30}, + {Operator: val2, ConsensusPubkey: common.BytesToHash(val2[:]), Power: 20}, + } + require.Equal(t, want, must(BondedValidators(h.state))) + + require.NoError(t, h.delegate(alice, val3, sei(15))) + require.Equal(t, want, must(BondedValidators(h.state)), "a delegation moves the set only at EndBlock") + h.endBlock() + require.Equal(t, []BondedValidator{ + {Operator: val1, ConsensusPubkey: common.BytesToHash(val1[:]), Power: 30}, + {Operator: val3, ConsensusPubkey: common.BytesToHash(val3[:]), Power: 25}, + }, must(BondedValidators(h.state))) +} + +func TestNoValidatorsAreBondedBeforeStakingBondsASet(t *testing.T) { + state := newMemState() + require.Empty(t, must(BondedValidators(state))) + require.NoError(t, SetParams(state, testParams)) + require.Empty(t, must(BondedValidators(state))) +} + +func TestBondedValidatorsFailOnAStoredSetThatDoesNotAddUp(t *testing.T) { + h := newHarness(t, testParams) + h.store().setLastValidators([]validatorPower{{val1, 30}, {alice, 20}}) + _, err := BondedValidators(h.state) + require.ErrorIs(t, err, errUnknownValidator, "a member with no validator") + + h.store().SetUint64(solstorage.Slot(slotLastValidators), 0, 101) + _, err = BondedValidators(h.state) + require.ErrorIs(t, err, errInvalidStoredSet, "a set longer than any MaxValidators allows") +} diff --git a/giga/evmonly/precompiles/staking/storage.go b/giga/evmonly/precompiles/staking/storage.go index 3cee6cbc8f..a10f270c08 100644 --- a/giga/evmonly/precompiles/staking/storage.go +++ b/giga/evmonly/precompiles/staking/storage.go @@ -144,6 +144,12 @@ func (s store) validatorPower(op common.Address) *big.Int { return consensusPower(s.Uint256(at(validatorBase(op), validatorTokens))) } +// consensusPubkey returns op's stored consensus key, zero when op has no +// validator. +func (s store) consensusPubkey(op common.Address) common.Hash { + return s.Word(at(validatorBase(op), validatorConsensusPubkey)) +} + func (s store) validatorSet() solstorage.Set { return solstorage.Set{Store: s.Store, Base: solstorage.Slot(slotValidatorSet)} } diff --git a/sei-tendermint/internal/evmonlyapp/app.go b/sei-tendermint/internal/evmonlyapp/app.go index 5aa552a201..312414ed3f 100644 --- a/sei-tendermint/internal/evmonlyapp/app.go +++ b/sei-tendermint/internal/evmonlyapp/app.go @@ -114,7 +114,8 @@ type evmOnlyApplication struct { execution gigaconfig.ExecutionConfig minGasPrice *big.Int storage *bootstrap.GigaStorageManager - validators []abci.ValidatorUpdate + // validators are the configured validators, served until staking bonds a set. + validators []abci.ValidatorUpdate // customPrecompiles are the native contracts every executor runs. customPrecompiles utils.Option[precompiles.Registry] // upgradeInfoPath is where a halt on a due upgrade plan writes @@ -379,10 +380,6 @@ func (a *evmOnlyApplication) EvmGasLimit() uint64 { panic("unreachable") } -func (a *evmOnlyApplication) GetValidators() []abci.ValidatorUpdate { - return slices.Clone(a.validators) -} - func (a *evmOnlyApplication) CheckTx(_ context.Context, req *abci.RequestCheckTxV2) *abci.ResponseCheckTxV2 { // TODO(evmonly-production): close the gap between admission and block validity // before accepting arbitrary traffic; this test app assumes executable load-test transactions. diff --git a/sei-tendermint/internal/evmonlyapp/validators.go b/sei-tendermint/internal/evmonlyapp/validators.go new file mode 100644 index 0000000000..d451c80e69 --- /dev/null +++ b/sei-tendermint/internal/evmonlyapp/validators.go @@ -0,0 +1,58 @@ +package evmonlyapp + +import ( + "fmt" + "slices" + + "github.com/sei-protocol/sei-chain/giga/evmonly" + "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles/staking" + abci "github.com/sei-protocol/sei-chain/sei-tendermint/abci/types" + "github.com/sei-protocol/sei-chain/sei-tendermint/crypto" + "github.com/sei-protocol/sei-chain/sei-tendermint/crypto/ed25519" + "github.com/sei-protocol/sei-chain/sei-tendermint/libs/utils" +) + +// GetValidators returns staking's bonded set in the committed state, and the +// configured validators until staking has bonded one. It returns none when the +// stored set does not add up, which autobahn cannot stage as a committee. +func (a *evmOnlyApplication) GetValidators() []abci.ValidatorUpdate { + bonded, err := a.bondedValidators() + if err != nil { + logger.Error("EVM-only bonded validator set does not add up", "err", err) + return nil + } + if len(bonded) == 0 { + return slices.Clone(a.validators) + } + return bonded +} + +// bondedValidators returns staking's bonded set in the committed state. +func (a *evmOnlyApplication) bondedValidators() ([]abci.ValidatorUpdate, error) { + view := a.openSettledView() + defer view.Close() + bonded, err := staking.BondedValidators(evmonly.ReadOnlyState(view)) + if err != nil { + return nil, err + } + updates := make([]abci.ValidatorUpdate, len(bonded)) + for i, v := range bonded { + if updates[i], err = validatorUpdate(v); err != nil { + return nil, err + } + } + return updates, nil +} + +// validatorUpdate returns bonded validator v as consensus reads it. +func validatorUpdate(v staking.BondedValidator) (abci.ValidatorUpdate, error) { + key, err := ed25519.PublicKeyFromBytes(v.ConsensusPubkey[:]) + if err != nil { + return abci.ValidatorUpdate{}, fmt.Errorf("validator %s: %w", v.Operator, err) + } + power, ok := utils.SafeCast[int64](v.Power) + if !ok { + return abci.ValidatorUpdate{}, fmt.Errorf("validator %s power %d does not fit int64", v.Operator, v.Power) + } + return abci.ValidatorUpdate{PubKey: crypto.PubKeyToProto(key), Power: power}, nil +} diff --git a/sei-tendermint/internal/evmonlyapp/validators_test.go b/sei-tendermint/internal/evmonlyapp/validators_test.go new file mode 100644 index 0000000000..88669e7091 --- /dev/null +++ b/sei-tendermint/internal/evmonlyapp/validators_test.go @@ -0,0 +1,111 @@ +package evmonlyapp + +import ( + "math/big" + "testing" + + "github.com/ethereum/go-ethereum/common" + + gigaconfig "github.com/sei-protocol/sei-chain/giga/config" + "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles" + "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles/staking" + seidbconfig "github.com/sei-protocol/sei-chain/sei-db/config" + abci "github.com/sei-protocol/sei-chain/sei-tendermint/abci/types" + "github.com/sei-protocol/sei-chain/sei-tendermint/crypto" + "github.com/sei-protocol/sei-chain/sei-tendermint/crypto/ed25519" + "github.com/sei-protocol/sei-chain/sei-tendermint/libs/utils" + "github.com/sei-protocol/sei-chain/sei-tendermint/libs/utils/require" +) + +// stakingGenesis is staking with the params and validators it writes at its +// first EndBlock. +type stakingGenesis struct { + staking.Precompile + validators []staking.GenesisValidator +} + +func (g stakingGenesis) EndBlock(block precompiles.BlockContext, state precompiles.State) ([]error, error) { + if !staking.HasParams(state) { + if err := staking.SetParams(state, staking.DefaultParams()); err != nil { + return nil, err + } + for _, v := range g.validators { + if err := g.AddGenesisValidator(block, state, v); err != nil { + return nil, err + } + } + } + return g.Precompile.EndBlock(block, state) +} + +// corruptBondedSet stores a bonded set longer than staking allows at every +// EndBlock. +type corruptBondedSet struct { + staking.Precompile +} + +func (corruptBondedSet) EndBlock(_ precompiles.BlockContext, state precompiles.State) ([]error, error) { + // Slot 0 of StakingStorage holds the bonded set's length. + state.SetState(staking.Address, common.Hash{}, common.BigToHash(big.NewInt(101))) + return nil, nil +} + +// newStakingEVMOnlyTestApp returns an initialized application serving the +// configured validators and running staking as contract. +func newStakingEVMOnlyTestApp(t *testing.T, configured []abci.ValidatorUpdate, contract precompiles.Contract) abci.Application { + t.Helper() + storageConfig, err := seidbconfig.AutobahnStorageConfig(t.TempDir()) + require.NoError(t, err) + storage := openEVMOnlyTestStorage(t, storageConfig) + registry := precompiles.NewStaticRegistry(map[common.Address]precompiles.Contract{staking.Address: contract}, staking.Address) + app, err := NewEVMOnlyApplication( + evmOnlyTestChainID, + configured, + storage, + gigaconfig.DefaultConfig.Execution, + utils.Some[precompiles.Registry](registry), + utils.None[string](), + ) + require.NoError(t, err) + t.Cleanup(func() { closeEVMOnlyTestApp(t, app, storage) }) + _, err = app.InitChain(evmOnlyTestInitChain()) + require.NoError(t, err) + return app +} + +// testSei returns n SEI in wei. +func testSei(n int64) *big.Int { + return new(big.Int).Mul(big.NewInt(n), big.NewInt(1_000_000_000_000_000_000)) +} + +func testGenesisValidator(operator common.Address, key ed25519.PublicKey, self int64) staking.GenesisValidator { + return staking.GenesisValidator{ + Operator: operator, + ConsensusPubkey: common.BytesToHash(key.Bytes()), + SelfDelegation: testSei(self), + MinSelfDelegation: testSei(1), + } +} + +func TestEVMOnlyApplicationServesStakingsBondedSet(t *testing.T) { + configured := []abci.ValidatorUpdate{{PubKey: crypto.PubKeyToProto(ed25519.TestSecretKey([]byte("configured")).Public()), Power: 1}} + key1 := ed25519.TestSecretKey([]byte("validator-1")).Public() + key2 := ed25519.TestSecretKey([]byte("validator-2")).Public() + app := newStakingEVMOnlyTestApp(t, configured, stakingGenesis{validators: []staking.GenesisValidator{ + testGenesisValidator(common.HexToAddress("0xa2"), key2, 20), + testGenesisValidator(common.HexToAddress("0xa1"), key1, 30), + }}) + require.Equal(t, configured, app.GetValidators(), "the configured validators serve until staking bonds a set") + + finalizeAndCommitEVMOnlyTestBlock(t, app, evmOnlyTestBlock(1)) + require.Equal(t, []abci.ValidatorUpdate{ + {PubKey: crypto.PubKeyToProto(key1), Power: 30}, + {PubKey: crypto.PubKeyToProto(key2), Power: 20}, + }, app.GetValidators()) +} + +func TestEVMOnlyApplicationServesNoValidatorsFromACorruptBondedSet(t *testing.T) { + app := newStakingEVMOnlyTestApp(t, []abci.ValidatorUpdate{{Power: 1}}, corruptBondedSet{}) + finalizeAndCommitEVMOnlyTestBlock(t, app, evmOnlyTestBlock(1)) + require.Empty(t, app.GetValidators()) +} From bf37f0456091c5dab44992d8fbadde50b41297c5 Mon Sep 17 00:00:00 2001 From: Tony Chen Date: Fri, 6 Nov 2026 03:45:05 +0800 Subject: [PATCH 21/44] refactor(evmonlyapp): stop handling an ed25519 key error that cannot happen Co-Authored-By: Claude Opus 5.5 --- sei-tendermint/internal/evmonlyapp/validators.go | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/sei-tendermint/internal/evmonlyapp/validators.go b/sei-tendermint/internal/evmonlyapp/validators.go index d451c80e69..5bd22d3e27 100644 --- a/sei-tendermint/internal/evmonlyapp/validators.go +++ b/sei-tendermint/internal/evmonlyapp/validators.go @@ -46,13 +46,11 @@ func (a *evmOnlyApplication) bondedValidators() ([]abci.ValidatorUpdate, error) // validatorUpdate returns bonded validator v as consensus reads it. func validatorUpdate(v staking.BondedValidator) (abci.ValidatorUpdate, error) { - key, err := ed25519.PublicKeyFromBytes(v.ConsensusPubkey[:]) - if err != nil { - return abci.ValidatorUpdate{}, fmt.Errorf("validator %s: %w", v.Operator, err) - } power, ok := utils.SafeCast[int64](v.Power) if !ok { return abci.ValidatorUpdate{}, fmt.Errorf("validator %s power %d does not fit int64", v.Operator, v.Power) } + // PublicKeyFromBytes checks only the length, and a common.Hash is always 32 bytes. + key := utils.OrPanic1(ed25519.PublicKeyFromBytes(v.ConsensusPubkey[:])) return abci.ValidatorUpdate{PubKey: crypto.PubKeyToProto(key), Power: power}, nil } From 1324feeb745f5fe9ea1ea149b01887f5540b31be Mon Sep 17 00:00:00 2001 From: Tony Chen Date: Mon, 9 Nov 2026 11:58:29 +0800 Subject: [PATCH 22/44] fix(evmonlyapp): serve no validators after a failed block commit GetValidators fed a committee to autobahn from the last state that committed, since openSettledView only logs a failed commit. Autobahn persists the committee it stages, so the failure now reaches GetValidators, which returns none and autobahn refuses to stage it. Co-Authored-By: Claude Opus 5.5 --- .../internal/evmonlyapp/validators.go | 17 +++++++++++----- .../internal/evmonlyapp/validators_test.go | 20 +++++++++++++++++++ 2 files changed, 32 insertions(+), 5 deletions(-) diff --git a/sei-tendermint/internal/evmonlyapp/validators.go b/sei-tendermint/internal/evmonlyapp/validators.go index 5bd22d3e27..cab115b8fb 100644 --- a/sei-tendermint/internal/evmonlyapp/validators.go +++ b/sei-tendermint/internal/evmonlyapp/validators.go @@ -13,12 +13,13 @@ import ( ) // GetValidators returns staking's bonded set in the committed state, and the -// configured validators until staking has bonded one. It returns none when the -// stored set does not add up, which autobahn cannot stage as a committee. +// configured validators until staking has bonded one. It returns none when a +// finalized block failed to commit or the stored set does not add up, and +// autobahn cannot stage an empty committee. func (a *evmOnlyApplication) GetValidators() []abci.ValidatorUpdate { bonded, err := a.bondedValidators() if err != nil { - logger.Error("EVM-only bonded validator set does not add up", "err", err) + logger.Error("EVM-only bonded validator set is unavailable", "err", err) return nil } if len(bonded) == 0 { @@ -27,9 +28,15 @@ func (a *evmOnlyApplication) GetValidators() []abci.ValidatorUpdate { return bonded } -// bondedValidators returns staking's bonded set in the committed state. +// bondedValidators returns staking's bonded set once every finalized block is +// committed. It fails when one failed to commit. func (a *evmOnlyApplication) bondedValidators() ([]abci.ValidatorUpdate, error) { - view := a.openSettledView() + // openSettledView only logs a failed commit, which would serve a set from + // before the failed block, and autobahn persists the committee it stages. + if err := a.AwaitCommits(); err != nil { + return nil, fmt.Errorf("block commit failed: %w", err) + } + view := a.storage.StateDB().OpenView() defer view.Close() bonded, err := staking.BondedValidators(evmonly.ReadOnlyState(view)) if err != nil { diff --git a/sei-tendermint/internal/evmonlyapp/validators_test.go b/sei-tendermint/internal/evmonlyapp/validators_test.go index 88669e7091..e8381471c7 100644 --- a/sei-tendermint/internal/evmonlyapp/validators_test.go +++ b/sei-tendermint/internal/evmonlyapp/validators_test.go @@ -104,6 +104,26 @@ func TestEVMOnlyApplicationServesStakingsBondedSet(t *testing.T) { }, app.GetValidators()) } +func TestEVMOnlyApplicationServesNoValidatorsAfterAFailedCommit(t *testing.T) { + storageConfig, err := seidbconfig.AutobahnStorageConfig(t.TempDir()) + require.NoError(t, err) + storage := openEVMOnlyTestStorage(t, storageConfig) + t.Cleanup(func() { require.NoError(t, storage.Close()) }) + configured := []abci.ValidatorUpdate{{PubKey: crypto.PubKeyToProto(ed25519.TestSecretKey([]byte("configured")).Public()), Power: 1}} + app, err := NewEVMOnlyApplication(evmOnlyTestChainID, configured, storage, gigaconfig.DefaultConfig.Execution, utils.None[precompiles.Registry](), utils.None[string]()) + require.NoError(t, err) + _, err = app.InitChain(evmOnlyTestInitChain()) + require.NoError(t, err) + settler, ok := app.(*evmOnlyApplication) + require.True(t, ok) + installUnwritableEVMExecutor(settler) + require.Equal(t, configured, app.GetValidators()) + + raw, _ := signedEVMOnlyTestTx(t, evmOnlyTestChainID, 0) + finalizeAndCommitEVMOnlyTestBlock(t, app, evmOnlyTestBlock(1, raw)) + require.Empty(t, app.GetValidators(), "block 1 failed to commit, so the committed state predates it") +} + func TestEVMOnlyApplicationServesNoValidatorsFromACorruptBondedSet(t *testing.T) { app := newStakingEVMOnlyTestApp(t, []abci.ValidatorUpdate{{Power: 1}}, corruptBondedSet{}) finalizeAndCommitEVMOnlyTestBlock(t, app, evmOnlyTestBlock(1)) From 4c7f65bf3a9ad9bfb6a39c828fac5f232d0c7de8 Mon Sep 17 00:00:00 2001 From: Tony Chen Date: Fri, 13 Nov 2026 01:53:30 +0800 Subject: [PATCH 23/44] test(params): build the storage harness with solc 0.8.30 The harness and ParamsStorage declare pragma solidity 0.8.30, and the committed binary came from 0.8.28. Rebuild it with 0.8.30 and name the command that reproduces it. Co-Authored-By: Claude Opus 5.5 --- giga/evmonly/precompiles/params/layout_test.go | 4 ++-- .../params/testdata/ParamsStorageHarness.bin-runtime | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/giga/evmonly/precompiles/params/layout_test.go b/giga/evmonly/precompiles/params/layout_test.go index eecc060368..24b3aec92f 100644 --- a/giga/evmonly/precompiles/params/layout_test.go +++ b/giga/evmonly/precompiles/params/layout_test.go @@ -124,8 +124,8 @@ func mustUint(t *testing.T, s string) uint64 { // TestReadsCompilerWrites runs ParamsStorageHarness, which writes // ParamsStorage with solc's codegen, and reads the result back. Rebuild -// testdata with `forge inspect ParamsStorageHarness deployedBytecode` and the -// remapping giga-storage/=docs/giga-storage/. +// testdata from the repository root with solc 0.8.30 and +// `solc --bin-runtime giga-storage/=docs/giga-storage/ giga/evmonly/precompiles/params/testdata/ParamsStorageHarness.sol`. func TestReadsCompilerWrites(t *testing.T) { code, err := os.ReadFile("testdata/ParamsStorageHarness.bin-runtime") require.NoError(t, err) diff --git a/giga/evmonly/precompiles/params/testdata/ParamsStorageHarness.bin-runtime b/giga/evmonly/precompiles/params/testdata/ParamsStorageHarness.bin-runtime index da6bd015cd..66e4e0df98 100644 --- a/giga/evmonly/precompiles/params/testdata/ParamsStorageHarness.bin-runtime +++ b/giga/evmonly/precompiles/params/testdata/ParamsStorageHarness.bin-runtime @@ -1 +1 @@ -608060405234801561000f575f5ffd5b5060043610610029575f3560e01c80637d94792a1461002d575b5f5ffd5b610035610037565b005b604051806101600160405280659d29229e000067ffffffffffffffff16815260200165ebbdb3ed000067ffffffffffffffff168152602001654e94914f000167ffffffffffffffff16815260200163d09dc30081526020016401a13b860081526020016704a29b3afafb000081526020016706f05b59d3b2000081526020016704a29b3afafb00008152602001670941a8f7512f80008152602001670941a8f7512f800081526020016040518061010001604052805f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f8152508152505f5f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506040820151815f0160106101000a81548167ffffffffffffffff021916908367ffffffffffffffff160217905550606082015181600101556080820151816002015560a0820151816003015560c0820151816004015560e082015181600501556101008201518160060155610120820151816007015561014082015181600801906008610206929190610307565b50506040805160c080820183526606722feb7b000082526023602080840191825260078486019081526702c68af0bb1400006060808701918252620f42416080808901918252895161010081018b525f808252968101879052998a0186905291890185905290880184905260a080890185905295880184905260e08801939093529385018690528451601080549451925167ffffffffffffffff9092166bffffffffffffffffffffffff19909516949094176801000000000000000063ffffffff938416021763ffffffff60601b1916600160601b92909116919091021782559151601155905160125590925090610302906013906008610307565b505050565b8260088101928215610335579160200282015b8281111561033557825182559160200191906001019061031a565b50610341929150610345565b5090565b5b80821115610341575f815560010161034656fea2646970667358221220c06f3b49d1a7d0d9ccf807b93c6b5be715e0db9f8a8857759423af51b7af943d64736f6c634300081c0033 +608060405234801561000f575f5ffd5b5060043610610029575f3560e01c80637d94792a1461002d575b5f5ffd5b610035610037565b005b604051806101600160405280659d29229e000067ffffffffffffffff16815260200165ebbdb3ed000067ffffffffffffffff168152602001654e94914f000167ffffffffffffffff16815260200163d09dc30081526020016401a13b860081526020016704a29b3afafb000081526020016706f05b59d3b2000081526020016704a29b3afafb00008152602001670941a8f7512f80008152602001670941a8f7512f800081526020016040518061010001604052805f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f8152508152505f5f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506040820151815f0160106101000a81548167ffffffffffffffff021916908367ffffffffffffffff160217905550606082015181600101556080820151816002015560a0820151816003015560c0820151816004015560e082015181600501556101008201518160060155610120820151816007015561014082015181600801906008610206929190610345565b509050506040518060c001604052806606722feb7b000067ffffffffffffffff168152602001602363ffffffff168152602001600763ffffffff1681526020016702c68af0bb1400008152602001620f424181526020016040518061010001604052805f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81525081525060105f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548163ffffffff021916908363ffffffff1602179055506040820151815f01600c6101000a81548163ffffffff021916908363ffffffff160217905550606082015181600101556080820151816002015560a08201518160030190600861033f929190610345565b50905050565b8260088101928215610374579160200282015b82811115610373578251825591602001919060010190610358565b5b5090506103819190610385565b5090565b5b8082111561039c575f815f905550600101610386565b509056fea2646970667358221220b7b3fa3dbab443014a8bed161cc1724eec13717cb015b5863a74bfefcf386dee64736f6c634300081e0033 From 9626d69a7b7ff60b41a7cac82aa4cfa87afb8af0 Mon Sep 17 00:00:00 2001 From: Tony Chen Date: Fri, 13 Nov 2026 01:54:04 +0800 Subject: [PATCH 24/44] test(staking): build the storage harness with solc 0.8.30 The harness and StakingStorage declare pragma solidity 0.8.30, and the committed binary came from 0.8.28. Rebuild it with 0.8.30 and name the command that reproduces it. Co-Authored-By: Claude Opus 5.5 --- giga/evmonly/precompiles/staking/layout_test.go | 4 ++-- .../staking/testdata/StakingStorageHarness.bin-runtime | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/giga/evmonly/precompiles/staking/layout_test.go b/giga/evmonly/precompiles/staking/layout_test.go index bd5933ba76..daa8b86d18 100644 --- a/giga/evmonly/precompiles/staking/layout_test.go +++ b/giga/evmonly/precompiles/staking/layout_test.go @@ -175,8 +175,8 @@ func mustUint(t *testing.T, s string) uint64 { // TestStoreReadsCompilerWrites runs StakingStorageHarness, which writes // StakingStorage with solc's codegen, and reads the result back through store. -// Rebuild testdata with `solc --bin-runtime` of the harness and the remapping -// giga-storage/=docs/giga-storage/. +// Rebuild testdata from the repository root with solc 0.8.30 and +// `solc --bin-runtime giga-storage/=docs/giga-storage/ giga/evmonly/precompiles/staking/testdata/StakingStorageHarness.sol`. func TestStoreReadsCompilerWrites(t *testing.T) { code, err := os.ReadFile("testdata/StakingStorageHarness.bin-runtime") require.NoError(t, err) diff --git a/giga/evmonly/precompiles/staking/testdata/StakingStorageHarness.bin-runtime b/giga/evmonly/precompiles/staking/testdata/StakingStorageHarness.bin-runtime index 8a99b869d8..2501059207 100644 --- a/giga/evmonly/precompiles/staking/testdata/StakingStorageHarness.bin-runtime +++ b/giga/evmonly/precompiles/staking/testdata/StakingStorageHarness.bin-runtime @@ -1 +1 @@ -608060405234801561000f575f5ffd5b5060043610610029575f3560e01c80633afaaf0e1461002d575b5f5ffd5b61004061003b366004610aa7565b610042565b005b6040805180820182526001600160a01b03868116808352601e60208085019182525f80546001808201835582805296517f290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563918201805495519188166001600160e01b031996871617600160a01b6001600160401b039384168102919091179091558951808b018b528d8916815260148187019081528554808c018755868052915191909401805494519190991693909616929092179416029290921790935560328455908152600280835290849020858155928301805461ffff19166102011790556801ae361fc1451c0000908301556f1812f9cf7920e2b66973e200000000006003830155825160608101909352603480845291929190610c429083013960048201906101709082610b87565b506040805180820190915260018152601960fa1b602082015260088201906101989082610b87565b506009810180546fffffffffffffffffffffffffffffffff1916682200000000000000211790556023600a820155600d81018054602467ffffffffffffffff199091161790556025600e8201556001600160a01b0384165f908152600260205260409020600101805461ff001916610300179055610217600386610a49565b610222600385610a49565b5f82815260056020908152604080832080546001600160a01b03808b166001600160a01b0319928316811790935560068054600181810183557ff652222313e28459528d920b65115c16c04f3efc82aaedc97be59f3f377c0d3f91820180548e861690871617905582549081019092550180549092168317909155871680855260078452828520918552908352818420602990558352600890915290206102c99086610a49565b60095f846001600160a01b03166001600160a01b031681526020019081526020015f205f866001600160a01b03166001600160a01b031681526020019081526020015f20604051806080016040528060336001600160401b0316815260200160346001600160401b03168152602001603581526020016036815250908060018154018082558091505060019003905f5260205f2090600302015f909190919091505f820151815f015f6101000a8154816001600160401b0302191690836001600160401b031602179055506020820151815f0160086101000a8154816001600160401b0302191690836001600160401b031602179055506040820151816001015560608201518160020155505060095f846001600160a01b03166001600160a01b031681526020019081526020015f205f866001600160a01b03166001600160a01b031681526020019081526020015f20604051806080016040528060376001600160401b0316815260200160386001600160401b0316815260200160398152602001603a815250908060018154018082558091505060019003905f5260205f2090600302015f909190919091505f820151815f015f6101000a8154816001600160401b0302191690836001600160401b031602179055506020820151815f0160086101000a8154816001600160401b0302191690836001600160401b03160217905550604082015181600101556060820151816002015550506002600a5f856001600160a01b03166001600160a01b031681526020019081526020015f205f876001600160a01b03166001600160a01b031681526020019081526020015f205f866001600160a01b03166001600160a01b031681526020019081526020015f20819055506003600b5f866001600160a01b03166001600160a01b031681526020019081526020015f205f856001600160a01b03166001600160a01b031681526020019081526020015f2081905550604051806040016040528060016001600160401b0316815260200160026001600160401b0316815250600c5f820151815f015f6101000a8154816001600160401b0302191690836001600160401b031602179055506020820151815f0160086101000a8154816001600160401b0302191690836001600160401b031602179055509050506040518060600160405280603d6001600160401b03168152602001846001600160a01b03168152602001866001600160a01b0316815250600d5f60016001600160401b031681526020019081526020015f205f820151815f015f6101000a8154816001600160401b0302191690836001600160401b031602179055506020820151815f0160086101000a8154816001600160a01b0302191690836001600160a01b031602179055506040820151816001015f6101000a8154816001600160a01b0302191690836001600160a01b0316021790555090505060405180604001604052805f6001600160401b0316815260200160016001600160401b0316815250600e5f820151815f015f6101000a8154816001600160401b0302191690836001600160401b031602179055506020820151815f0160086101000a8154816001600160401b0302191690836001600160401b031602179055509050506040518060e0016040528060476001600160401b03168152602001846001600160a01b0316815260200160486001600160401b03168152602001866001600160a01b03168152602001856001600160a01b0316815260200160498152602001604a815250600f5f5f6001600160401b031681526020019081526020015f205f820151815f015f6101000a8154816001600160401b0302191690836001600160401b031602179055506020820151815f0160086101000a8154816001600160a01b0302191690836001600160a01b031602179055506040820151816001015f6101000a8154816001600160401b0302191690836001600160401b0316021790555060608201518160010160086101000a8154816001600160a01b0302191690836001600160a01b031602179055506080820151816002015f6101000a8154816001600160a01b0302191690836001600160a01b0316021790555060a0820151816003015560c08201518160040155905050604051806040016040528060046001600160401b0316815260200160056001600160401b031681525060105f820151815f015f6101000a8154816001600160401b0302191690836001600160401b031602179055506020820151815f0160086101000a8154816001600160401b0302191690836001600160401b03160217905550905050604051806060016040528060516001600160401b0316815260200160526001600160401b03168152602001856001600160a01b031681525060115f60046001600160401b031681526020019081526020015f205f820151815f015f6101000a8154816001600160401b0302191690836001600160401b031602179055506020820151815f0160086101000a8154816001600160401b0302191690836001600160401b031602179055506040820151816001015f6101000a8154816001600160a01b0302191690836001600160a01b031602179055509050505050505050565b8154600181810184555f848152602080822090930180546001600160a01b039095166001600160a01b031990951685179055845493815293019052604090912055565b80356001600160a01b0381168114610aa2575f5ffd5b919050565b5f5f5f5f60808587031215610aba575f5ffd5b610ac385610a8c565b9350610ad160208601610a8c565b9250610adf60408601610a8c565b9396929550929360600135925050565b634e487b7160e01b5f52604160045260245ffd5b600181811c90821680610b1757607f821691505b602082108103610b3557634e487b7160e01b5f52602260045260245ffd5b50919050565b601f821115610b8257805f5260205f20601f840160051c81016020851015610b605750805b601f840160051c820191505b81811015610b7f575f8155600101610b6c565b50505b505050565b81516001600160401b03811115610ba057610ba0610aef565b610bb481610bae8454610b03565b84610b3b565b6020601f821160018114610be6575f8315610bcf5750848201515b5f19600385901b1c1916600184901b178455610b7f565b5f84815260208120601f198516915b82811015610c155787850151825560209485019460019092019101610bf5565b5084821015610c3257868401515f19600387901b60f8161c191681555b50505050600190811b0190555056fe61206d6f6e696b6572206c6f6e6720656e6f75676820746f207370696c6c2070617374206f6e652073746f7261676520776f7264a26469706673582212200bd261bbd131367b0cd28e69d1cce95e169395bac03866effa024dcaf4e3fe3f64736f6c634300081c0033 +608060405234801561000f575f5ffd5b5060043610610029575f3560e01c80633afaaf0e1461002d575b5f5ffd5b610047600480360381019061004291906110b4565b610049565b005b5f60405180604001604052808673ffffffffffffffffffffffffffffffffffffffff168152602001601e67ffffffffffffffff16815250908060018154018082558091505060019003905f5260205f20015f909190919091505f820151815f015f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506020820151815f0160146101000a81548167ffffffffffffffff021916908367ffffffffffffffff16021790555050505f60405180604001604052808573ffffffffffffffffffffffffffffffffffffffff168152602001601467ffffffffffffffff16815250908060018154018082558091505060019003905f5260205f20015f909190919091505f820151815f015f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506020820151815f0160146101000a81548167ffffffffffffffff021916908367ffffffffffffffff160217905550505060326001819055505f60025f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20905081815f01819055506001816001015f6101000a81548160ff02191690831515021790555060028160010160016101000a81548160ff021916908360ff1602179055506801ae361fc1451c000081600201819055506f1812f9cf7920e2b66973e20000000000816003018190555060405180606001604052806034815260200161142560349139816004015f0190816102c39190611355565b506040518060400160405280600181526020017f640000000000000000000000000000000000000000000000000000000000000081525081600401600401908161030d9190611355565b506021816009015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff16021790555060228160090160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff160217905550602381600a015f015f0181905550602481600a016003015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff160217905550602581600e0181905550600360025f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f2060010160016101000a81548160ff021916908360ff160217905550610410600386610f74565b61041b600385610f74565b8460055f8481526020019081526020015f205f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550600684908060018154018082558091505060019003905f5260205f20015f9091909190916101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550600685908060018154018082558091505060019003905f5260205f20015f9091909190916101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550602960075f8573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f01819055506105f060085f8573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f2086610f74565b60095f8473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f206040518060800160405280603367ffffffffffffffff168152602001603467ffffffffffffffff168152602001603581526020016036815250908060018154018082558091505060019003905f5260205f2090600302015f909190919091505f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506040820151816001015560608201518160020155505060095f8473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f206040518060800160405280603767ffffffffffffffff168152602001603867ffffffffffffffff16815260200160398152602001603a815250908060018154018082558091505060019003905f5260205f2090600302015f909190919091505f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff160217905550604082015181600101556060820151816002015550506002600a5f8573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20819055506003600b5f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20819055506040518060400160405280600167ffffffffffffffff168152602001600267ffffffffffffffff16815250600c5f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055509050506040518060600160405280603d67ffffffffffffffff1681526020018473ffffffffffffffffffffffffffffffffffffffff1681526020018673ffffffffffffffffffffffffffffffffffffffff16815250600d5f600167ffffffffffffffff1681526020019081526020015f205f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506040820151816001015f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555090505060405180604001604052805f67ffffffffffffffff168152602001600167ffffffffffffffff16815250600e5f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055509050506040518060e00160405280604767ffffffffffffffff1681526020018473ffffffffffffffffffffffffffffffffffffffff168152602001604867ffffffffffffffff1681526020018673ffffffffffffffffffffffffffffffffffffffff1681526020018573ffffffffffffffffffffffffffffffffffffffff16815260200160498152602001604a815250600f5f5f67ffffffffffffffff1681526020019081526020015f205f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506040820151816001015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff16021790555060608201518160010160086101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506080820151816002015f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555060a0820151816003015560c082015181600401559050506040518060400160405280600467ffffffffffffffff168152602001600567ffffffffffffffff1681525060105f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055509050506040518060600160405280605167ffffffffffffffff168152602001605267ffffffffffffffff1681526020018573ffffffffffffffffffffffffffffffffffffffff1681525060115f600467ffffffffffffffff1681526020019081526020015f205f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506040820151816001015f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055509050505050505050565b815f0181908060018154018082558091505060019003905f5260205f20015f9091909190916101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550815f0180549050826001015f8373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20819055505050565b5f5ffd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f61105082611027565b9050919050565b61106081611046565b811461106a575f5ffd5b50565b5f8135905061107b81611057565b92915050565b5f819050919050565b61109381611081565b811461109d575f5ffd5b50565b5f813590506110ae8161108a565b92915050565b5f5f5f5f608085870312156110cc576110cb611023565b5b5f6110d98782880161106d565b94505060206110ea8782880161106d565b93505060406110fb8782880161106d565b925050606061110c878288016110a0565b91505092959194509250565b5f81519050919050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52604160045260245ffd5b7f4e487b71000000000000000000000000000000000000000000000000000000005f52602260045260245ffd5b5f600282049050600182168061119357607f821691505b6020821081036111a6576111a561114f565b5b50919050565b5f819050815f5260205f209050919050565b5f6020601f8301049050919050565b5f82821b905092915050565b5f600883026112087fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff826111cd565b61121286836111cd565b95508019841693508086168417925050509392505050565b5f819050919050565b5f819050919050565b5f61125661125161124c8461122a565b611233565b61122a565b9050919050565b5f819050919050565b61126f8361123c565b61128361127b8261125d565b8484546111d9565b825550505050565b5f5f905090565b61129a61128b565b6112a5818484611266565b505050565b5b818110156112c8576112bd5f82611292565b6001810190506112ab565b5050565b601f82111561130d576112de816111ac565b6112e7846111be565b810160208510156112f6578190505b61130a611302856111be565b8301826112aa565b50505b505050565b5f82821c905092915050565b5f61132d5f1984600802611312565b1980831691505092915050565b5f611345838361131e565b9150826002028217905092915050565b61135e82611118565b67ffffffffffffffff81111561137757611376611122565b5b611381825461117c565b61138c8282856112cc565b5f60209050601f8311600181146113bd575f84156113ab578287015190505b6113b5858261133a565b86555061141c565b601f1984166113cb866111ac565b5f5b828110156113f2578489015182556001820191506020850194506020810190506113cd565b8683101561140f578489015161140b601f89168261131e565b8355505b6001600288020188555050505b50505050505056fe61206d6f6e696b6572206c6f6e6720656e6f75676820746f207370696c6c2070617374206f6e652073746f7261676520776f7264a26469706673582212205c15fa37db41f0049a9d40775052987863b4620fae48fddcec9e74526f520a5564736f6c634300081e0033 From 2665668e5971814e6d07938066959a418cc0b667 Mon Sep 17 00:00:00 2001 From: Tony Chen Date: Fri, 13 Nov 2026 02:12:11 +0800 Subject: [PATCH 25/44] refactor(evmonly): move 1e18 decimal math to a shared dec package Staking's share math and gov's tally both divide and round 1e18-scaled decimals as sdk.Dec does. Put staking's helpers in precompiles/dec so the precompiles share one implementation; staking keeps its token units and consensus power in units.go. Co-Authored-By: Claude Opus 5.5 --- giga/evmonly/precompiles/dec/dec.go | 48 ++++++++++++++++ giga/evmonly/precompiles/dec/dec_test.go | 21 +++++++ giga/evmonly/precompiles/staking/dec.go | 55 ------------------- giga/evmonly/precompiles/staking/dec_test.go | 55 ------------------- .../precompiles/staking/layout_test.go | 3 +- giga/evmonly/precompiles/staking/storage.go | 3 +- .../precompiles/staking/storage_test.go | 38 +++++++++++++ giga/evmonly/precompiles/staking/units.go | 19 +++++++ 8 files changed, 130 insertions(+), 112 deletions(-) create mode 100644 giga/evmonly/precompiles/dec/dec.go create mode 100644 giga/evmonly/precompiles/dec/dec_test.go delete mode 100644 giga/evmonly/precompiles/staking/dec.go delete mode 100644 giga/evmonly/precompiles/staking/dec_test.go create mode 100644 giga/evmonly/precompiles/staking/units.go diff --git a/giga/evmonly/precompiles/dec/dec.go b/giga/evmonly/precompiles/dec/dec.go new file mode 100644 index 0000000000..1db229717c --- /dev/null +++ b/giga/evmonly/precompiles/dec/dec.go @@ -0,0 +1,48 @@ +// Package dec is arithmetic on decimals held as big.Int values scaled by 1e18, +// rounding as the Cosmos SDK's sdk.Dec does. +package dec + +import ( + "math/big" +) + +// one is 1 as a decimal. +var one = big.NewInt(1_000_000_000_000_000_000) + +// One returns 1 as a decimal. +func One() *big.Int { + return new(big.Int).Set(one) +} + +// FromInt returns integer i as a decimal. +func FromInt(i *big.Int) *big.Int { + return new(big.Int).Mul(i, one) +} + +// Truncate returns non-negative decimal d with its fraction dropped. +func Truncate(d *big.Int) *big.Int { + return new(big.Int).Quo(d, one) +} + +// Quo divides decimal a by decimal b, both non-negative, as sdk.Dec's Quo +// does: truncated to 36 places, then rounded half to even to 18. +func Quo(a, b *big.Int) *big.Int { + q := new(big.Int).Mul(a, one) + q.Mul(q, one) + return round(q.Quo(q, b)) +} + +// round divides non-negative x by 1e18, rounding half to even, as sdk.Dec's +// chopPrecisionAndRound does. +func round(x *big.Int) *big.Int { + q, r := new(big.Int).QuoRem(x, one, new(big.Int)) + switch r.Lsh(r, 1).Cmp(one) { + case 1: + q.Add(q, big.NewInt(1)) + case 0: + if q.Bit(0) == 1 { + q.Add(q, big.NewInt(1)) + } + } + return q +} diff --git a/giga/evmonly/precompiles/dec/dec_test.go b/giga/evmonly/precompiles/dec/dec_test.go new file mode 100644 index 0000000000..b9d5ab8a7a --- /dev/null +++ b/giga/evmonly/precompiles/dec/dec_test.go @@ -0,0 +1,21 @@ +package dec + +import ( + "math/big" + "math/rand" + "testing" + + "github.com/stretchr/testify/require" + + sdk "github.com/sei-protocol/sei-chain/sei-cosmos/types" +) + +func TestQuoMatchesSDK(t *testing.T) { + rng := rand.New(rand.NewSource(11)) //nolint:gosec // deterministic test data + for range 2_000 { + total := big.NewInt(rng.Int63n(1<<40) + 1) + power := new(big.Int).Rand(rng, total) + want := sdk.NewIntFromBigInt(power).ToDec().Quo(sdk.NewIntFromBigInt(total).ToDec()) + require.Equal(t, want.BigInt().String(), Quo(FromInt(power), FromInt(total)).String(), "%s / %s", power, total) + } +} diff --git a/giga/evmonly/precompiles/staking/dec.go b/giga/evmonly/precompiles/staking/dec.go deleted file mode 100644 index 0e4a462b72..0000000000 --- a/giga/evmonly/precompiles/staking/dec.go +++ /dev/null @@ -1,55 +0,0 @@ -package staking - -import ( - "math/big" -) - -var ( - // decOne is 1 as a 1e18-scaled decimal, the scale of shares and ratios. - decOne = big.NewInt(1_000_000_000_000_000_000) - - // weiPerUsei is the wei in one usei, the smallest unit an amount may hold. - weiPerUsei = big.NewInt(1_000_000_000_000) - - // powerReduction is the tokens in one unit of consensus power: one SEI, as - // x/staking's DefaultPowerReduction of 1e6 usei is. - powerReduction = new(big.Int).Mul(big.NewInt(1_000_000), weiPerUsei) -) - -// consensusPower returns the consensus power tokens are worth. -func consensusPower(tokens *big.Int) *big.Int { - return new(big.Int).Quo(tokens, powerReduction) -} - -// intToDec returns integer i as a decimal. -func intToDec(i *big.Int) *big.Int { - return new(big.Int).Mul(i, decOne) -} - -// truncateDec returns non-negative decimal d with its fraction dropped. -func truncateDec(d *big.Int) *big.Int { - return new(big.Int).Quo(d, decOne) -} - -// quoDec divides decimal a by decimal b, both non-negative, as sdk.Dec's Quo -// does: truncated to 36 places, then rounded half to even to 18. -func quoDec(a, b *big.Int) *big.Int { - q := new(big.Int).Mul(a, decOne) - q.Mul(q, decOne) - return roundDec(q.Quo(q, b)) -} - -// roundDec divides non-negative x by 1e18, rounding half to even, as -// sdk.Dec's chopPrecisionAndRound does. -func roundDec(x *big.Int) *big.Int { - q, r := new(big.Int).QuoRem(x, decOne, new(big.Int)) - switch r.Lsh(r, 1).Cmp(decOne) { - case 1: - q.Add(q, big.NewInt(1)) - case 0: - if q.Bit(0) == 1 { - q.Add(q, big.NewInt(1)) - } - } - return q -} diff --git a/giga/evmonly/precompiles/staking/dec_test.go b/giga/evmonly/precompiles/staking/dec_test.go deleted file mode 100644 index 62102bebd7..0000000000 --- a/giga/evmonly/precompiles/staking/dec_test.go +++ /dev/null @@ -1,55 +0,0 @@ -package staking - -import ( - "math/big" - "math/rand" - "testing" - - "github.com/stretchr/testify/require" - - sdk "github.com/sei-protocol/sei-chain/sei-cosmos/types" - stakingtypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/staking/types" -) - -// TestShareMathMatchesSDK pins the exchange between tokens and shares to -// x/staking's Validator, rounding included. -func TestShareMathMatchesSDK(t *testing.T) { - rng := rand.New(rand.NewSource(7)) //nolint:gosec // deterministic test data - random := func(bits int) *big.Int { - v := new(big.Int).Rand(rng, new(big.Int).Lsh(big.NewInt(1), uint(rng.Intn(bits)+1))) //nolint:gosec // bounded - return v.Add(v, big.NewInt(1)) - } - for range 2_000 { - v := validator{tokens: random(100), delegatorShares: random(160)} - sv := stakingtypes.Validator{ - Tokens: sdk.NewIntFromBigInt(v.tokens), - DelegatorShares: sdk.NewDecFromBigIntWithPrec(v.delegatorShares, sdk.Precision), - } - - amount := random(100) - got, err := v.sharesFromTokens(amount) - require.NoError(t, err) - want, err := sv.SharesFromTokens(sdk.NewIntFromBigInt(amount)) - require.NoError(t, err) - require.Equal(t, want.BigInt().String(), got.String(), "shares for %s tokens", amount) - truncated, err := sv.SharesFromTokensTruncated(sdk.NewIntFromBigInt(amount)) - require.NoError(t, err) - require.Equal(t, truncated.BigInt().String(), got.String(), "x/staking's truncated shares are the same") - - shares := new(big.Int).Rand(rng, v.delegatorShares) - decTokens := v.tokensFromShares(shares) - wantTokens := sv.TokensFromShares(sdk.NewDecFromBigIntWithPrec(shares, sdk.Precision)) - require.Equal(t, wantTokens.BigInt().String(), decTokens.String(), "tokens for %s shares", shares) - require.Equal(t, wantTokens.TruncateInt().BigInt().String(), truncateDec(decTokens).String()) - } -} - -func TestVotingPowerRatioMatchesSDK(t *testing.T) { - rng := rand.New(rand.NewSource(11)) //nolint:gosec // deterministic test data - for range 2_000 { - total := big.NewInt(rng.Int63n(1<<40) + 1) - power := new(big.Int).Rand(rng, total) - want := sdk.NewIntFromBigInt(power).ToDec().Quo(sdk.NewIntFromBigInt(total).ToDec()) - require.Equal(t, want.BigInt().String(), quoDec(intToDec(power), intToDec(total)).String(), "%s / %s", power, total) - } -} diff --git a/giga/evmonly/precompiles/staking/layout_test.go b/giga/evmonly/precompiles/staking/layout_test.go index daa8b86d18..3420c40d2e 100644 --- a/giga/evmonly/precompiles/staking/layout_test.go +++ b/giga/evmonly/precompiles/staking/layout_test.go @@ -14,6 +14,7 @@ import ( "github.com/ethereum/go-ethereum/core/vm/runtime" "github.com/stretchr/testify/require" + "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles/dec" "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles/solstorage" ) @@ -204,7 +205,7 @@ func TestStoreReadsCompilerWrites(t *testing.T) { jailed: true, status: statusUnbonding, tokens: sei(31), - delegatorShares: intToDec(sei(32)), + delegatorShares: dec.FromInt(sei(32)), unbondingHeight: 33, unbondingTime: 34, minSelfDelegation: big.NewInt(37), diff --git a/giga/evmonly/precompiles/staking/storage.go b/giga/evmonly/precompiles/staking/storage.go index 3cee6cbc8f..d5898692d5 100644 --- a/giga/evmonly/precompiles/staking/storage.go +++ b/giga/evmonly/precompiles/staking/storage.go @@ -9,6 +9,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles" + "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles/dec" chainparams "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles/params" "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles/solstorage" ) @@ -68,7 +69,7 @@ func (v validator) tokensFromShares(shares *big.Int) *big.Int { if v.delegatorShares.Sign() == 0 { return new(big.Int) } - return quoDec(new(big.Int).Mul(shares, v.tokens), v.delegatorShares) + return dec.Quo(new(big.Int).Mul(shares, v.tokens), v.delegatorShares) } // store is StakingStorage at the staking precompile's address. diff --git a/giga/evmonly/precompiles/staking/storage_test.go b/giga/evmonly/precompiles/staking/storage_test.go index 855cc52c20..8cf7b77d2c 100644 --- a/giga/evmonly/precompiles/staking/storage_test.go +++ b/giga/evmonly/precompiles/staking/storage_test.go @@ -1,12 +1,17 @@ package staking import ( + "math/big" + "math/rand" "testing" "github.com/ethereum/go-ethereum/common" "github.com/stretchr/testify/require" + "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles/dec" "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles/solstorage" + sdk "github.com/sei-protocol/sei-chain/sei-cosmos/types" + stakingtypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/staking/types" ) func TestUnbondingEntriesRejectAnImpossibleLength(t *testing.T) { @@ -30,3 +35,36 @@ func TestQueueClampsToItsLastEntry(t *testing.T) { require.False(t, ok) require.Equal(t, common.Hash{}, q.s.Word(q.entry(0)), "pop zeroes the entry") } + +// TestShareMathMatchesSDK pins the exchange between tokens and shares to +// x/staking's Validator, rounding included. +func TestShareMathMatchesSDK(t *testing.T) { + rng := rand.New(rand.NewSource(7)) //nolint:gosec // deterministic test data + random := func(bits int) *big.Int { + v := new(big.Int).Rand(rng, new(big.Int).Lsh(big.NewInt(1), uint(rng.Intn(bits)+1))) //nolint:gosec // bounded + return v.Add(v, big.NewInt(1)) + } + for range 2_000 { + v := validator{tokens: random(100), delegatorShares: random(160)} + sv := stakingtypes.Validator{ + Tokens: sdk.NewIntFromBigInt(v.tokens), + DelegatorShares: sdk.NewDecFromBigIntWithPrec(v.delegatorShares, sdk.Precision), + } + + amount := random(100) + got, err := v.sharesFromTokens(amount) + require.NoError(t, err) + want, err := sv.SharesFromTokens(sdk.NewIntFromBigInt(amount)) + require.NoError(t, err) + require.Equal(t, want.BigInt().String(), got.String(), "shares for %s tokens", amount) + truncated, err := sv.SharesFromTokensTruncated(sdk.NewIntFromBigInt(amount)) + require.NoError(t, err) + require.Equal(t, truncated.BigInt().String(), got.String(), "x/staking's truncated shares are the same") + + shares := new(big.Int).Rand(rng, v.delegatorShares) + decTokens := v.tokensFromShares(shares) + wantTokens := sv.TokensFromShares(sdk.NewDecFromBigIntWithPrec(shares, sdk.Precision)) + require.Equal(t, wantTokens.BigInt().String(), decTokens.String(), "tokens for %s shares", shares) + require.Equal(t, wantTokens.TruncateInt().BigInt().String(), dec.Truncate(decTokens).String()) + } +} diff --git a/giga/evmonly/precompiles/staking/units.go b/giga/evmonly/precompiles/staking/units.go new file mode 100644 index 0000000000..e02196ac62 --- /dev/null +++ b/giga/evmonly/precompiles/staking/units.go @@ -0,0 +1,19 @@ +package staking + +import ( + "math/big" +) + +var ( + // weiPerUsei is the wei in one usei, the smallest unit an amount may hold. + weiPerUsei = big.NewInt(1_000_000_000_000) + + // powerReduction is the tokens in one unit of consensus power: one SEI, as + // x/staking's DefaultPowerReduction of 1e6 usei is. + powerReduction = new(big.Int).Mul(big.NewInt(1_000_000), weiPerUsei) +) + +// consensusPower returns the consensus power tokens are worth. +func consensusPower(tokens *big.Int) *big.Int { + return new(big.Int).Quo(tokens, powerReduction) +} From 035bb86ac8815f6fa0d542a43eedc414e7201122 Mon Sep 17 00:00:00 2001 From: Tony Chen Date: Fri, 13 Nov 2026 02:19:07 +0800 Subject: [PATCH 26/44] fix(staking): refuse genesis validators worth no consensus power Run takes calls only once an EndBlock has bonded a set with power, and genesis validators are the only way into the first one. A genesis whose validators were each below one SEI never bonded, so every call failed for good. Genesis now requires each self-delegation to be worth at least one unit of consensus power. Co-Authored-By: Claude Opus 5.5 --- giga/evmonly/precompiles/staking/genesis.go | 8 +++++++- giga/evmonly/precompiles/staking/staking_test.go | 15 +++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/giga/evmonly/precompiles/staking/genesis.go b/giga/evmonly/precompiles/staking/genesis.go index 30a856deec..9e784f75c2 100644 --- a/giga/evmonly/precompiles/staking/genesis.go +++ b/giga/evmonly/precompiles/staking/genesis.go @@ -89,7 +89,8 @@ func (p Precompile) AddGenesisValidator(block precompiles.BlockContext, state pr } // check requires an operator, a consensus key, a positive minimum -// self-delegation, and a self-delegation of whole usei at least that minimum. +// self-delegation, and a self-delegation of whole usei, at least that minimum, +// worth at least one unit of consensus power. func (g GenesisValidator) check() error { switch { case g.Operator == (common.Address{}): @@ -105,5 +106,10 @@ func (g GenesisValidator) check() error { if g.SelfDelegation.Cmp(g.MinSelfDelegation) < 0 { return fmt.Errorf("%w: self-delegation below its minimum", errInvalidGenesis) } + // Run takes calls only once an EndBlock has bonded a set with power, and + // genesis validators are the only way into the first one. + if consensusPower(g.SelfDelegation).Sign() == 0 { + return fmt.Errorf("%w: self-delegation worth no consensus power", errInvalidGenesis) + } return nil } diff --git a/giga/evmonly/precompiles/staking/staking_test.go b/giga/evmonly/precompiles/staking/staking_test.go index 980fc140c4..d2ede2d055 100644 --- a/giga/evmonly/precompiles/staking/staking_test.go +++ b/giga/evmonly/precompiles/staking/staking_test.go @@ -324,6 +324,21 @@ func TestAddGenesisValidatorRejectsReuse(t *testing.T) { require.ErrorIs(t, Precompile{}.AddGenesisValidator(h.block(), newMemState(), g), errStakingNotWritten) } +func TestGenesisValidatorsHoldConsensusPower(t *testing.T) { + h := newHarness(t, testParams) + h.fund(bob, sei(1)) + g := GenesisValidator{ + Operator: bob, + ConsensusPubkey: common.BytesToHash(bob[:]), + SelfDelegation: new(big.Int).Sub(sei(1), weiPerUsei), + MinSelfDelegation: weiPerUsei, + } + require.ErrorIs(t, h.staking.AddGenesisValidator(h.block(), h.state, g), errInvalidGenesis, + "a genesis set below one SEI each would never bond, and staking would never start") + g.SelfDelegation = sei(1) + require.NoError(t, h.staking.AddGenesisValidator(h.block(), h.state, g)) +} + func TestDefaultParamsAreValid(t *testing.T) { require.NoError(t, DefaultParams().Validate()) state := newMemState() From d830d0f7dd28a548f2134a3a57c9e5c734298466 Mon Sep 17 00:00:00 2001 From: Danno Ferrin Date: Mon, 2 Nov 2026 14:52:27 -0700 Subject: [PATCH 27/44] docs(giga-storage): propose staking, distribution and slashing storage Draft storage layouts for the EVM-only staking, distribution and slashing precompiles, and the rationale behind them, taken from ffd15bb, which is not merged on its own. - staking-design-rationale.md: the proposal, built from three principles (Solidity slot layout, V2 structures for migration, rewards undesigned) - StakingStorage, DistributionStorage, SlashingStorage: draft layouts - Sets.sol: dependency-free AddressSet/UintSet with EnumerableSet's layout --- docs/giga-storage/DistributionStorage.sol | 43 ++ docs/giga-storage/Sets.sol | 16 + docs/giga-storage/SlashingStorage.sol | 29 + docs/giga-storage/StakingStorage.sol | 128 +++++ docs/giga-storage/staking-design-rationale.md | 534 ++++++++++++++++++ 5 files changed, 750 insertions(+) create mode 100644 docs/giga-storage/DistributionStorage.sol create mode 100644 docs/giga-storage/Sets.sol create mode 100644 docs/giga-storage/SlashingStorage.sol create mode 100644 docs/giga-storage/StakingStorage.sol create mode 100644 docs/giga-storage/staking-design-rationale.md diff --git a/docs/giga-storage/DistributionStorage.sol b/docs/giga-storage/DistributionStorage.sol new file mode 100644 index 0000000000..80a272a19a --- /dev/null +++ b/docs/giga-storage/DistributionStorage.sol @@ -0,0 +1,43 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.30; + +/// @notice Storage schema of the evmonly distribution precompile (0x1007), held as +/// that address's contract storage. Each state variable is an x/distribution +/// store prefix, named in its comment. +/// @dev Params are `ParamsStorage.distribution`. Outstanding rewards and the +/// community pool sit in the balance of `DistributionEscrow`, a derived address +/// in `distribution/layout.go`. Amounts and stakes are wei; reward ratios and +/// slash fractions are 1e18-scaled. +contract DistributionStorage { + struct ValidatorHistoricalRewards { + uint256 cumulativeRewardRatio; + uint32 referenceCount; + } + + struct ValidatorCurrentRewards { + uint256 rewards; + uint64 period; + } + + struct DelegatorStartingInfo { + uint64 previousPeriod; + uint64 height; + uint256 stake; + } + + struct ValidatorSlashEvent { + uint64 height; + uint64 validatorPeriod; + uint256 fraction; + } + + uint256 internal communityPool; // 0x00: FeePool.community_pool + address internal previousProposer; // 0x01: consensus address + mapping(address => uint256) internal validatorOutstandingRewards; // 0x02: validator => + mapping(address => address) internal delegatorWithdrawAddr; // 0x03: delegator => payee; zero is the delegator + mapping(address => mapping(address => DelegatorStartingInfo)) internal delegatorStartingInfo; // 0x04: validator => delegator => + mapping(address => mapping(uint64 => ValidatorHistoricalRewards)) internal validatorHistoricalRewards; // 0x05: validator => period => + mapping(address => ValidatorCurrentRewards) internal validatorCurrentRewards; // 0x06: validator => + mapping(address => uint256) internal validatorAccumulatedCommission; // 0x07: validator => + mapping(address => ValidatorSlashEvent[]) internal validatorSlashEvents; // 0x08: validator => ascending by height +} diff --git a/docs/giga-storage/Sets.sol b/docs/giga-storage/Sets.sol new file mode 100644 index 0000000000..89dba29bea --- /dev/null +++ b/docs/giga-storage/Sets.sol @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.30; + +/// @notice A set of addresses. positions holds each member's 1-based index into +/// values, 0 when absent; removal moves the last value into the gap. Read and +/// written by solstorage.Set. +struct AddressSet { + address[] values; + mapping(address => uint256) positions; +} + +/// @notice A set of uint256 values, laid out as AddressSet. +struct UintSet { + uint256[] values; + mapping(uint256 => uint256) positions; +} diff --git a/docs/giga-storage/SlashingStorage.sol b/docs/giga-storage/SlashingStorage.sol new file mode 100644 index 0000000000..671c3a0394 --- /dev/null +++ b/docs/giga-storage/SlashingStorage.sol @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.30; + +import "./Sets.sol"; + +/// @notice Storage schema of the evmonly slashing precompile (0x1014), held as that +/// address's contract storage. Each state variable is an x/slashing store prefix, +/// named in its comment. +/// @dev Params are `ParamsStorage.slashing`. Keys are consensus addresses, +/// sha256(consensusPubkey)[:20]. Times are Unix nanoseconds. +contract SlashingStorage { + struct ValidatorSigningInfo { + uint64 startHeight; + uint64 indexOffset; + uint64 jailedUntil; + bool tombstoned; + uint64 missedBlocksCounter; + } + + struct ValidatorMissedBlockArray { + uint64 windowSize; + uint64[] missedBlocks; // bit i of the window is bit i%64 of word i/64 + } + + mapping(address => ValidatorSigningInfo) internal validatorSigningInfo; // 0x01: consensus address => + AddressSet internal signingInfoSet; // every consensus address in validatorSigningInfo + mapping(address => ValidatorMissedBlockArray) internal validatorMissedBlocks; // 0x02: consensus address => + mapping(address => bytes32) internal addrPubkeyRelation; // 0x03: consensus address => ed25519 key +} diff --git a/docs/giga-storage/StakingStorage.sol b/docs/giga-storage/StakingStorage.sol new file mode 100644 index 0000000000..c08dd14947 --- /dev/null +++ b/docs/giga-storage/StakingStorage.sol @@ -0,0 +1,128 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.30; + +import "./Sets.sol"; + +/// @notice Storage schema of the evmonly staking precompile (0x1005), held as that +/// address's contract storage. Each state variable is an x/staking store prefix, +/// named in its comment. +/// @dev Params are `ParamsStorage.staking`. Bonded tokens sit in the balance of +/// `BondedEscrow` and unbonded and unbonding tokens in `NotBondedEscrow`, derived +/// addresses in `staking/layout.go`. Tokens and balances are wei; shares and +/// rates are 1e18-scaled; times are Unix nanoseconds. Accounts and operators are EVM +/// addresses; a consensus address is sha256(consensusPubkey)[:20]. +contract StakingStorage { + struct Description { + string moniker; + string identity; + string website; + string securityContact; + string details; + } + + struct CommissionRates { + uint256 rate; + uint256 maxRate; + uint256 maxChangeRate; + } + + struct Commission { + CommissionRates commissionRates; + uint64 updateTime; + } + + struct Validator { + bytes32 consensusPubkey; // ed25519 + bool jailed; + uint8 status; // 1=Unbonded, 2=Unbonding, 3=Bonded + uint256 tokens; + uint256 delegatorShares; + Description description; + uint64 unbondingHeight; + uint64 unbondingTime; + Commission commission; + uint256 minSelfDelegation; + uint256[8] __gap; + } + + struct Delegation { + uint256 shares; + } + + struct UnbondingDelegationEntry { + uint64 creationHeight; + uint64 completionTime; + uint256 initialBalance; + uint256 balance; + } + + struct RedelegationEntry { + uint64 creationHeight; + uint64 completionTime; + uint256 initialBalance; + uint256 sharesDst; + } + + /// @dev A queue entry's completionTime is never earlier than the one before it. + struct UnbondingQueueEntry { + uint64 completionTime; + address delegator; + address validator; + } + + struct RedelegationQueueEntry { + uint64 completionTime; + address delegator; + address srcValidator; + address dstValidator; + } + + struct ValidatorQueueEntry { + uint64 completionTime; + uint64 completionHeight; + address operator; + } + + /// @dev A first-in first-out queue: entries are at indexes [head, tail). + struct QueueBounds { + uint64 head; + uint64 tail; + } + + mapping(address => uint64) internal lastValidatorPower; // 0x11: operator => power + AddressSet internal lastValidatorPowerSet; // operators with a lastValidatorPower + uint256 internal lastTotalPower; // 0x12 + + mapping(address => Validator) internal validators; // 0x21: operator => + AddressSet internal validatorSet; // every operator in validators + mapping(address => address) internal validatorsByConsAddr; // 0x22: consensus address => operator + address[] internal validatorsByPower; // 0x23: unjailed operators, descending by power, ties to the lower address + + mapping(address => mapping(address => Delegation)) internal delegations; // 0x31: delegator => validator => + mapping(address => AddressSet) internal delegationsByValidator; // 0x37: validator => delegators + mapping(address => AddressSet) internal delegationsByDelegator; // delegator => validators + + mapping(address => mapping(address => UnbondingDelegationEntry[])) internal unbondingDelegations; // 0x32: delegator => validator => entries, at most maxEntries + mapping(address => AddressSet) internal unbondingDelegationsByValidator; // 0x33: validator => delegators + mapping(address => AddressSet) internal unbondingDelegationsByDelegator; // delegator => validators + + mapping(address => mapping(address => mapping(address => RedelegationEntry[]))) internal redelegations; // 0x34: delegator => src => dst => entries, at most maxEntries + mapping(address => mapping(address => AddressSet)) internal redelegationsByValSrc; // 0x35: src => delegator => dsts + mapping(address => AddressSet) internal redelegationDelegatorsByValSrc; // src => delegators + mapping(address => mapping(address => uint256)) internal redelegationsByValDst; // 0x36: dst => delegator => open entries into dst + mapping(address => mapping(address => AddressSet)) internal redelegationsByDelegator; // delegator => src => dsts + mapping(address => AddressSet) internal redelegationSrcsByDelegator; // delegator => srcs + + QueueBounds internal unbondingQueueBounds; + mapping(uint64 => UnbondingQueueEntry) internal unbondingQueue; // 0x41: index => + QueueBounds internal redelegationQueueBounds; + mapping(uint64 => RedelegationQueueEntry) internal redelegationQueue; // 0x42: index => + QueueBounds internal validatorQueueBounds; + mapping(uint64 => ValidatorQueueEntry) internal validatorQueue; // 0x43: index => + + /// @dev V2 to giga migration. The phase runs from the cutover height until + /// migrationCursor passes the last V2 key. + bool internal migrating; + bytes internal migrationCursor; // last V2 store key copied + bytes[] internal migrationFailures; // V2 store keys that could not be copied +} diff --git a/docs/giga-storage/staking-design-rationale.md b/docs/giga-storage/staking-design-rationale.md new file mode 100644 index 0000000000..54acc305e0 --- /dev/null +++ b/docs/giga-storage/staking-design-rationale.md @@ -0,0 +1,534 @@ +# Giga staking, distribution and slashing: storage proposal + +This is a proposal for how state for the EVM-only staking (`0x1005`), +distribution (`0x1007`) and slashing (`0x1014`) precompiles could be stored. It +is not a settled design. It starts from three principles and works forward, so +each choice can be traced back to the principle behind it, and it calls out the +places where the principles pull against each other and the choice is still +open. + +The draft layouts are the `.sol` files in this directory: `StakingStorage.sol`, +`DistributionStorage.sol`, `SlashingStorage.sol`, and the shared `Sets.sol`. +`staking-design.md` is a terser working draft of the same proposal. Nothing here +is implemented. + +The three principles: + +1. **Storage follows Solidity's layout rules**, ideally declared in a `.sol` + file. +2. **Migration from V2 should be easy**, so the proposal copies V2's record + structures wherever it can, while using Ethereum-native data types. V2's + precompiles would be shut off before the migration and the giga precompiles + turned on after it. +3. **How staking rewards are applied during execution is not designed yet.** + The storage should be able to support that design without presuming it. + +--- + +## Principle 1: storage follows Solidity's layout rules + +### What it means + +Each precompile would keep its state as the contract storage of its own +address, as a deployed contract does. The slot for every value is the slot the +Solidity compiler would assign if the `.sol` file in this directory were +compiled. Go code reads and writes those slots through the `solstorage` +helpers, the same way gov and params do today. + +Solidity's rules, briefly: + +- State variables take slots in declaration order, starting at 0. +- Small fields (`bool`, `uint8`, `uint64`, `address`) are packed into one + 32-byte slot when they fit next to each other. +- A struct starts on a fresh slot and takes consecutive slots for its fields. +- A static array (`uint256[8]`) is laid out inline, like a struct. +- A dynamic array keeps its length in its own slot; its elements start at + `keccak256(slot)`. +- A mapping's own slot stays empty; the value for key `k` lives at + `keccak256(k . slot)`. Nested mappings apply this once per level. +- `string` and `bytes` are stored inline when short and spill out to + `keccak256(slot)` when long. + +For example, a delegation's shares would live at +`delegations[delegator][validator].shares`. In the draft, `delegations` sits at +slot 9 of `StakingStorage` (the two sets before it take two slots each), so the +shares are at `keccak256(validator . keccak256(delegator . 9))`, with each key +padded to 32 bytes. + +`Validator` shows the struct rules on a larger record. In the draft it takes 23 +slots: + +| Slot offset | Fields | +|---|---| +| 0 | `consensusPubkey` | +| 1 | `jailed`, `status` (packed) | +| 2 | `tokens` | +| 3 | `delegatorShares` | +| 4–8 | `description` (five strings) | +| 9 | `unbondingHeight`, `unbondingTime` (packed) | +| 10–13 | `commission` (three rates, then `updateTime`) | +| 14 | `minSelfDelegation` | +| 15–22 | `__gap` (reserved) | + +### Why + +- **The `.sol` file is the spec.** `solc --storage-layout` or `forge inspect` + on it gives the exact slot of every field, so there is no second, + hand-written description of the storage to drift out of date. +- **Standard tooling can read the state.** `eth_getStorageAt`, explorers and + debuggers already understand this layout, and a contract could be written + against the same file to read it. +- **It matches gov and params**, so all giga precompiles would share one + storage model and one set of helpers. + +### Consequences + +**Layouts only grow.** Once a public network runs a layout, a state variable or +field cannot move. New fields would take slots from a struct's `__gap`, and new +state variables would go after the last one. The draft `Validator` reserves +eight slots for this, and `layout_test.go` pins would catch an accidental +reorder. + +**No library dependencies.** The draft layouts import nothing from outside this +directory, including OpenZeppelin. The precompiles need enumerable sets, and +OpenZeppelin's `EnumerableSet` has the right shape, but importing it would tie +the storage to a third-party version. `Sets.sol` instead declares `AddressSet` +and `UintSet` as plain structs with the same slot layout: + +```solidity +struct AddressSet { + address[] values; // members, in insertion order + mapping(address => uint256) positions; // 1-based index into values; 0 = absent +} +``` + +Removing a member moves the last value into the gap, so each operation is a +constant number of writes. `solstorage.Set` already reads this layout. + +**Some things IAVL can do, slots cannot.** V2 stores state in an ordered key +value store. It can walk keys in sorted order, walk every key under a prefix, +delete every key under a prefix, and ask whether any key under a prefix exists. +Contract storage is a hash map with none of those operations. Each place this +proposal departs from V2's structures comes from that gap. The largest, the +prefix walks, may argue for relaxing Principle 1 in places; see below. + +--- + +## Principle 2: copy V2's structures + +### What it means + +The migration from V2 is likely the riskiest step in this work. It moves the +stake and pending rewards of every delegator on the chain, and it has to finish +while blocks keep coming. One way to keep it manageable is to make it close to +a transcription: each V2 record becomes one giga record with the same shape, so +the migration code is a field-by-field conversion and a test can compare V2 and +giga record for record. + +The proposal copies **structure**, not data types: + +- **Each V2 store prefix becomes one state variable**, named after the V2 + record and commented with the prefix it came from. +- **Each record keeps V2's fields, field order and names.** +- **Data types are Ethereum-native.** Amounts are wei, not usei. Shares, rates + and reward ratios are 1e18-scaled fixed point, which is also V2's `sdk.Dec` + scale. Addresses are EVM addresses, times are Unix nanoseconds. +- **The rewards accounting stays F1.** + +**Converting amounts to wei.** One usei is 10¹² wei, so the migration would +multiply token amounts by 10¹². To keep each validator's exchange rate between +tokens and shares unchanged, shares would be multiplied by the same factor, as +would delegations' starting stake. F1's reward ratios are rewards per token, so +they are unchanged when both sides scale. V2 keeps rewards as `Dec` because usei +is coarse. In wei the fractional part is far smaller; one option is to store +reward and pool amounts as whole wei and drop the sub-wei remainder (under one +wei per record) at migration, another is to keep them 1e18-scaled as V2 does. +This needs a decision. + +**Why F1.** V2 does not credit each delegator every block. It credits each +*validator* with a running "rewards per token" total, and records, for each +delegation, the period of that total it started in. When a delegator acts, their +rewards are `stake × (current total − total when they started)`. Nothing +per-delegation is written until the delegator does something. A simpler +rewards-per-share model was considered, but it would mean settling every +delegation's pending rewards at cutover, which with something on the order of a +million delegations is not a single-block operation. Keeping F1 lets pending +rewards carry over in the same shape. + +### The mapping + +Staking: + +| V2 prefix | V2 record | Proposed giga state variable | +|---|---|---| +| `0x11` | last validator power | `lastValidatorPower` (+ set) | +| `0x12` | last total power | `lastTotalPower` | +| `0x21` | validators | `validators` (+ set) | +| `0x22` | validator by consensus address | `validatorsByConsAddr` | +| `0x23` | validators by power | `validatorsByPower` (sorted array) | +| `0x31` | delegations | `delegations` (+ set per delegator) | +| `0x37` | delegations by validator | `delegationsByValidator` | +| `0x32`, `0x33` | unbonding delegations and their index | `unbondingDelegations` (+ sets) | +| `0x34`–`0x36` | redelegations and their indexes | `redelegations` (+ sets, a count) | +| `0x41`–`0x43` | unbonding, redelegation, validator queues | three queues | +| `0x50` | historical info | not carried over (see below) | + +Distribution: prefixes `0x00`–`0x08` map one to one onto the nine state +variables in `DistributionStorage.sol`, from `communityPool` to +`validatorSlashEvents`. + +Slashing: signing info (`0x01`), Sei's packed missed-block array (`0x02`) and +the address-to-pubkey relation (`0x03`) map one to one. The missed-block +`uint64[]` packs four words per slot, so the bits are V2's bits. + +### The power index + +V2 keeps validators sorted by power under `0x23`, and EndBlock walks that range +from the top to pick the active set. The proposal keeps the same structure: a +stored index, `validatorsByPower`, holding the same validators V2 indexes +(jailed validators are left out), in V2's order: descending by consensus power, +ties to the lower address. Because it is committed state, the index is the same +on every node, survives restarts and state sync without a rebuild, and can be +copied from V2's `0x23` range in order at cutover. + +Slots cannot keep keys sorted for free, so the index is an `address[]` that the +precompile keeps in order. When a validator's power changes, its old position is +found by binary search over the array (reading each probed validator's power), +and it moves up or down until it is in order again, one slot write for each +place it passes. A change that does not pass a neighbour costs reads only, since +the validator's tokens are written anyway. + +**How often that happens.** Over about 28 hours of pacific-1 (216,000 blocks, +ending at height 241,156,163), the 40 bonded validators saw 60 delegations, 29 +undelegations and 2 incoming redelegations, about one power change every 2,400 +blocks, touching 23 validators. The gaps between neighbours in the ranking are +large: the smallest gap between adjacent bonded validators is about 225k SEI, +the median 1.9M SEI, and 40th place sits 27.8M SEI above 41st. Almost every +change moves its validator zero places; a full re-sort never happens. + +**The worst case and whether it can be abused.** The most a single transaction +can cost is moving one validator from last to first: about N slot writes, where +N is the number of indexed validators (88 today). The precompile would charge +gas for each place moved, so whoever causes a reorder pays for it, and the cost +of a transaction is bounded by N. + +Flipping a validator between first and last repeatedly is not a cheap way to +load the chain: + +- Moving from 41st to 1st today needs more than the top validator's stake, + about 183M SEI on top of the 17.6M already there. Even a one-place move needs + at least the smallest gap, about 225k SEI. +- Moving the stake back is rate-limited. Undelegating locks funds for 21 days. + A redelegation's destination cannot be redelegated out of until that entry + matures, and `maxEntries` caps open entries at 7 per pair. Each tranche of + capital gets roughly two large moves per unbonding period. +- The capital is not lost; it stays staked and earns rewards. The limit on the + attacker is the capital needed and the lock-ups, and the cost is the gas, + which is no worse than a contract writing N slots. + +A cheaper variant would be to register many validators with small, nearly equal +stakes, so that small delegations cause long moves. That is bounded by a cap on +validator records (a `maxValidatorRecords` param) and a minimum self-delegation +to create a validator, together with the per-place gas charge. V2's index has +the same economics for active-set churn; the difference is that V2 pays a fixed +IAVL delete and insert, where slots pay per place moved. + +**Scaling.** At tens of thousands of validator records, gaps shrink and changes +move further, so the per-place cost grows. The cap keeps N in the range where +that cost is small. + +**Alternatives considered:** + +- **Rank in memory at EndBlock.** Read every validator, sort, take the top + `maxValidators`. Nothing extra is stored, but every validator is read every + block. +- **A node-local cache.** The same sorted list held in memory instead of slots. + The reorder is not gas-metered, and the cache must be rebuilt identically on + every node, follow tx reverts and snapshots, and be rebuilt after state sync. +- **Ordered flatkv keys**, V2's approach exactly. See *Prefix walks*. + +### Where the structures don't carry over + +Each of these is a place where slot storage, or a deliberate simplification, +forces a change from V2. The first is the hardest. + +#### Prefix walks + +Anywhere V2 walks every key under a prefix ("all delegations of this delegator", +"all delegators of this validator", "all validators"), slot storage needs an +explicit enumeration set. The draft layouts do this: V2's own index prefixes +(`0x33`, `0x35`, `0x37`) become sets of the same shape, and new sets cover walks +V2 did over the primary key (`validatorSet`, `delegationsByDelegator` and so +on). + +This may not hold up. Each set adds two or three slot writes whenever a member +joins or leaves, and the sets roughly double the writes for every delegation +created or removed. Across a million delegations the sets themselves are a large +share of the state, and of what the migration has to write. Removing a validator +or a delegator with many entries means walking and clearing large sets. + +The alternative is to store the indexes, and possibly the primary records, as +ordered flatkv keys and use flatkv's prefix reads, which is what V2 does on IAVL. +That would give back ordered and prefix iteration, prefix delete and existence +checks, and could also hold the power index. It gives up +Principle 1 for those records: they would not be described by a `.sol` file and +would not be readable through `eth_getStorageAt`. It also depends on flatkv +exposing ordered prefix iteration to the precompiles, as part of committed state. +A middle ground is to keep primary records in slots and move only the indexes +to flatkv. A further option, for indexes that only queries use, is to leave them +to an off-chain indexer. Which of these to pursue is open. + +#### Smaller changes + +**"Does any key exist under this prefix" becomes a counter.** V2 refuses to +chain redelegations by checking whether any key exists under +`0x36 ‖ dst ‖ delegator`. The draft counts open entries in +`redelegationsByValDst` instead. + +**Time-ordered queues become first-in, first-out lists.** V2 keys its maturity +queues by completion time and walks them up to the current time. The draft +makes each queue an array read from its head, with each new entry's completion +time clamped to be no earlier than the entry before it. While `unbondingTime` +stays constant this changes nothing. If governance shortens `unbondingTime`, new +unbondings would wait behind older ones rather than overtaking them. A validator +that re-bonds before its unbonding finishes would leave a stale queue entry, +which EndBlock skips. Ordered flatkv keys would avoid the clamp. + +**Slash events become an array ordered by height**, found by binary search, +where V2 uses a key range by height. + +**No prefix delete.** When a validator is removed, V2 deletes its whole +historical-rewards prefix. The draft deletes the periods that can still be +referenced (the slash events' periods and the last period); F1's reference +counts mean no others are live. + +**One denomination.** V2's rewards are `DecCoins`, a list of amounts by denom. +Multi-denom rewards are going away, so each amount is a single `uint256` of wei. +On pacific-1 the community pool and the outstanding rewards sampled are usei +only today; the pre-migration checklist would confirm it for everything. + +**Typed keys.** Bech32 strings become EVM addresses, and the consensus public key +(a protobuf `Any` in V2) becomes a `bytes32` ed25519 key. All 88 validators on +pacific-1 use ed25519. + +**Historical info is not carried over.** V2 writes the full validator set into +`0x50` every block, and its only reader is IBC, which giga does not run. + +### A consequence for gov + +V2 tallies a proposal inside one EndBlock, so it sees state at one instant. Gov +on giga counts votes under a per-block budget, so a proposal with many voters is +counted over several blocks, and a delegation that changes mid-count could be +counted on both sides. + +One way to handle this without giving staking a history is to freeze the inputs +while gov counts: + +- staking refuses delegate, undelegate and redelegate while a tally is being + counted, with a revert naming the tally; +- gov stores the bonded validator set (at most `maxValidators` records) when + counting starts, since jailing can change the set without any delegation + write. + +That would reproduce V2's single-instant tally. The lock would last a few blocks +for a typical proposal and about two minutes for one with a million voters. Both +are small changes to gov's existing tally code. + +### Principle 2.1: precompiles are off during the migration + +V2's staking, distribution and slashing precompiles would be shut down ahead of +the migration, and the giga precompiles turned on only once it finishes. In +between, no user transaction can touch this state. + +That keeps the migration simple. If nothing writes a delegation while it runs, a +V2 record has been migrated exactly when it lies behind the migration cursor. +There is no promote-on-write path, no "already migrated" marker, and no conflict +between a user's write and the copy. + +A possible sequence: + +1. **At the cutover height, copy everything per validator in one go**: + validator records, power, the validator queue, every per-validator rewards + record, slash events, the community pool, signing info and missed blocks, + params and escrow balances. This is about a hundred validators' worth of + state. +2. **Sweep the per-delegation state over the following blocks.** Staking's + EndBlock copies V2 records in V2 key order, a budgeted number per block, and + saves its position in `migrationCursor`. Delegations first, each with its F1 + starting info, the historical rewards entry it references, and the + delegator's withdraw address; then unbonding entries, redelegation entries + and the two remaining queues. A record that cannot be copied goes into + `migrationFailures` and is skipped, so one bad record does not stall the + sweep. +3. **Finish.** When the cursor passes the last V2 key, `migrating` clears, V2 + state is no longer read, and the giga precompiles turn on. + +Sei has done something similar in V2: the `0x37` delegation-by-validator index +was backfilled with a cursor key and a ready marker. + +**How long it might take.** Roughly V2 keys × writes per key ÷ the per-block +budget. V2 holds about three or four keys per delegation, and with the draft's +sets each takes about three or four slot writes. At a million delegations and +10,000 keys per block, that is about 1,500 blocks, or ten minutes at 400 ms +blocks; at 100,000 delegations, about a minute. Fewer sets (see *Prefix walks*) +would shorten it. The real delegation count is not known yet. + +**Where V2 state is read from.** The sweep would read V2 through an interface +implemented in `evmonlyapp`, which may import sei-cosmos, so `giga/evmonly` +only sees typed records. Every node needs the frozen V2 state as of the cutover +for the whole sweep, including nodes that state-sync during it. If the existing +memiavl-to-flatkv migration has moved staking and distribution into flatkv by +then, that store may serve as the source. + +**What still runs during the migration.** Turning the precompiles off stops +user writes, but some work is driven by the chain itself: + +- Unbonding and redelegation maturity could pause, with entries that come due + paid on the first block after the migration. +- Gov could defer any tally that would start during the migration. +- Whether the validator set can change during the window (jailing for downtime, + validators finishing their unbonding) is open. The per-validator records are + migrated first, so it is possible, but freezing the set is simpler. +- Whether rewards accrue during the window depends on Principle 3. + +--- + +## Principle 3: applying rewards during execution is not designed yet + +How fees and inflation are collected and credited each block is a separate +design. This proposal does not try to answer it; it aims to keep the storage +able to carry whatever that design decides, and lists the assumptions it would +need to confirm. + +**What the storage would support.** With F1, crediting rewards only touches +per-validator records: the validator's outstanding rewards, current rewards and +commission. Distribution could expose two Go entry points for that: + +- `AllocateTokensToValidator(state, from, validator, amount)`: moves funds into + the distribution escrow and splits commission as V2 does; +- `FundCommunityPool(state, from, amount)`. + +The rewards code would call these and write no distribution slots directly. + +**What it would not support cheaply.** Anything that writes to every delegation +on a schedule. With F1, a delegation is written only when its owner acts. A +design that pushes rewards to each delegator every epoch would be on the order +of a million state writes per epoch. + +**Assumptions for the rewards design to confirm or replace:** + +- Rewards are allocated in a new BeginBlock step, before slashing and before any + transaction, using the previous block's votes. The giga executor has no + BeginBlock hook today. +- The fee pot is for the rewards design to define. Giga's coinbase and base fee + are zero today. +- Minting belongs to the rewards design. pacific-1's release schedule is empty. +- Power and the bonded set are read from staking, not copied. +- `communityTax` and the proposer reward params stay in distribution's params + (all zero on pacific-1). + +--- + +## How the pieces could fit together + +**Funds in escrow addresses.** The tokens would be the balances of derived +addresses, the pattern gov uses for deposits: + +| Escrow | V2 module account | Holds | +|---|---|---| +| staking bonded escrow | `bonded_tokens_pool` | bonded validators' tokens | +| staking not-bonded escrow | `not_bonded_tokens_pool` | unbonded validators' tokens and unbonding entries | +| distribution escrow | `distribution` | outstanding rewards and the community pool | + +Escrows and records both hold wei. Each payout would check the escrow balance +before moving funds. + +**Precompiles call each other in Go.** Staking would define a hooks interface +equivalent to V2's `StakingHooks`, and `evmonlyapp` would wire distribution and +slashing into it. Gov would read staking through an adapter, so no precompile +package imports another. + +**Block order follows V2.** BeginBlock would run rewards, then slashing. +EndBlock would run gov, then staking: the migration sweep while it is running, +then the validator set update, then the three queues. Each EndBlock step would +follow gov's fail-safe rule: each item runs in its own snapshot, a failure +reverts that item and is reported, and the block does not halt. Two guards +would sit where every path passes: the validator set update never sends a set +with zero total power, and a payout that finds its escrow short leaves the +funds where they are and reports it. + +--- + +## Checklist before the migration + +Proposed steps on pacific-1 before a cutover height is chosen. + +1. **Confirm there are no CosmWasm delegators.** The proposal keys everything by + EVM address. A CosmWasm contract has a 32-byte address with no EVM + equivalent, so its delegations would have no owner on giga. Walk every + delegator in `0x31`, `0x32` and `0x34` and flag any 32-byte address. The same + walk can flag multisig and module accounts, and any account that has never + signed a transaction (no public key in x/auth, so no derivable EVM address). + Each one found needs a decision: undelegate it before cutover, or map it some + other way. +2. **Confirm every reward balance is usei.** Multi-denom rewards are going away, + and the proposal stores a single amount. Check the community pool and every + validator's outstanding rewards and accumulated commission. If another denom + is present, one fix is to force a distribution before cutover: withdraw all + delegator rewards and validator commission so non-usei amounts are paid out + in V2, leaving only usei to migrate. +3. **Get a real delegation count, then shadow-migrate.** The count sets how long + the sweep runs and how much the set overhead matters. Count `0x31` keys on a + pacific-1 snapshot, then run the migration against snapshots, more than once, + before doing it for real. Each shadow run could report how many blocks the + sweep took, any entries in `migrationFailures`, and these invariants: + - each validator's `delegatorShares` equals the sum of its delegations' + shares; + - the bonded escrow equals the total tokens of bonded validators, and the + not-bonded escrow equals unbonded validators' tokens plus every unbonding + balance; + - the distribution escrow covers every outstanding reward plus the community + pool; + - a sample of delegators' pending rewards computed on giga matches V2, ×10¹². + +--- + +## Not yet covered + +Known gaps that need an owner or a decision. + +- **Vesting accounts.** V2 tracks delegated vesting and delegated free amounts + on vesting accounts. Giga has no vesting accounts; what happens when a + vesting delegator undelegates is undecided. +- **Bank balances and escrow funding** at cutover belong to the bank migration. +- **Dynamic validator sets in autobahn.** The giga application returns the + genesis validator set today, and validator updates have nowhere to go. +- **Validator operations through authz.** Some operators run validator + operations through authz grants, which the giga precompiles would not + support. +- **Signing state at cutover.** Whether missed-block windows, jail times and + tombstones copy as they are, or liveness windows restart, is undecided. +- **Slashing stake.** Both slash fractions are zero on pacific-1. The proposal + pins them at zero and defers slashing unbonding and redelegation entries. +- **Existing callers of the V2 precompiles.** Contracts calling the V2 + selectors would get a revert naming the method to use instead. +- **Events.** Indexers and explorers would move from Cosmos events to EVM logs. +- **Parallel execution.** The escrows, `lastTotalPower` and the validator + records make staking transactions conflict with each other. Custom + precompiles run sequentially today. +- **In-flight gov proposals** at cutover belong to gov's migration. + +## Open questions + +1. Power index: what cap on validator records, and what minimum to create + one? And is gas per place moved the right charge for a reorder? +2. Prefix walks: enumeration sets in slots, ordered flatkv keys (for indexes + only, or for records too), or off-chain indexing for query-only walks? +3. Reward and pool amounts: whole wei, or 1e18-scaled wei? +4. Is the queue behaviour after a shortened `unbondingTime` acceptable, or does + the queue answer change with question 2? +5. Do the gov changes (counting lock and stored bonded set) land in the gov PR + stack or with the staking work, and is a tally lock of a couple of minutes + acceptable for very large proposals? +6. Is the validator set frozen during the migration, or can it change? +7. Who owns the V2 read side of the sweep, and can the flatkv copy serve it? From ca725900996cd348e990b3f78ff478a0d2b5253c Mon Sep 17 00:00:00 2001 From: Tony Chen Date: Tue, 3 Nov 2026 10:23:07 +0800 Subject: [PATCH 28/44] docs(giga-storage): keep only the staking structures an on-chain path reads - Drop the consensus address: validators are keyed by operator in staking, distribution and slashing. 0x22 is keyed by the ed25519 key, for the duplicate-key check and key lookups; slashing's 0x03 relation is dropped. - Drop the enumeration sets read only by queries (0x37, unbonding and redelegations by delegator) or by entry slashing (0x33, 0x35). - Keep redelegation entries in the redelegation queue, with a per-triple count for maxEntries. - Store the bonded set as one ValidatorPower array instead of a mapping and a set. - Update the rationale doc to match, including which queue entries the FIFO clamp delays. Co-Authored-By: Claude Opus 5.5 --- docs/giga-storage/DistributionStorage.sol | 2 +- docs/giga-storage/SlashingStorage.sol | 12 +- docs/giga-storage/StakingStorage.sol | 37 +++-- docs/giga-storage/staking-design-rationale.md | 140 +++++++++++------- giga/evmonly/precompiles/gov/electorate.go | 2 +- 5 files changed, 114 insertions(+), 79 deletions(-) diff --git a/docs/giga-storage/DistributionStorage.sol b/docs/giga-storage/DistributionStorage.sol index 80a272a19a..9e2404d9a7 100644 --- a/docs/giga-storage/DistributionStorage.sol +++ b/docs/giga-storage/DistributionStorage.sol @@ -32,7 +32,7 @@ contract DistributionStorage { } uint256 internal communityPool; // 0x00: FeePool.community_pool - address internal previousProposer; // 0x01: consensus address + address internal previousProposer; // 0x01: operator mapping(address => uint256) internal validatorOutstandingRewards; // 0x02: validator => mapping(address => address) internal delegatorWithdrawAddr; // 0x03: delegator => payee; zero is the delegator mapping(address => mapping(address => DelegatorStartingInfo)) internal delegatorStartingInfo; // 0x04: validator => delegator => diff --git a/docs/giga-storage/SlashingStorage.sol b/docs/giga-storage/SlashingStorage.sol index 671c3a0394..7450ac9890 100644 --- a/docs/giga-storage/SlashingStorage.sol +++ b/docs/giga-storage/SlashingStorage.sol @@ -6,8 +6,9 @@ import "./Sets.sol"; /// @notice Storage schema of the evmonly slashing precompile (0x1014), held as that /// address's contract storage. Each state variable is an x/slashing store prefix, /// named in its comment. -/// @dev Params are `ParamsStorage.slashing`. Keys are consensus addresses, -/// sha256(consensusPubkey)[:20]. Times are Unix nanoseconds. +/// @dev Params are `ParamsStorage.slashing`. Keys are validator operators. A +/// validator's ed25519 key is `StakingStorage.validators[operator].consensusPubkey`. +/// Times are Unix nanoseconds. contract SlashingStorage { struct ValidatorSigningInfo { uint64 startHeight; @@ -22,8 +23,7 @@ contract SlashingStorage { uint64[] missedBlocks; // bit i of the window is bit i%64 of word i/64 } - mapping(address => ValidatorSigningInfo) internal validatorSigningInfo; // 0x01: consensus address => - AddressSet internal signingInfoSet; // every consensus address in validatorSigningInfo - mapping(address => ValidatorMissedBlockArray) internal validatorMissedBlocks; // 0x02: consensus address => - mapping(address => bytes32) internal addrPubkeyRelation; // 0x03: consensus address => ed25519 key + mapping(address => ValidatorSigningInfo) internal validatorSigningInfo; // 0x01: operator => + AddressSet internal signingInfoSet; // every operator in validatorSigningInfo + mapping(address => ValidatorMissedBlockArray) internal validatorMissedBlocks; // 0x02: operator => } diff --git a/docs/giga-storage/StakingStorage.sol b/docs/giga-storage/StakingStorage.sol index c08dd14947..ce6b1a04d7 100644 --- a/docs/giga-storage/StakingStorage.sol +++ b/docs/giga-storage/StakingStorage.sol @@ -9,8 +9,9 @@ import "./Sets.sol"; /// @dev Params are `ParamsStorage.staking`. Bonded tokens sit in the balance of /// `BondedEscrow` and unbonded and unbonding tokens in `NotBondedEscrow`, derived /// addresses in `staking/layout.go`. Tokens and balances are wei; shares and -/// rates are 1e18-scaled; times are Unix nanoseconds. Accounts and operators are EVM -/// addresses; a consensus address is sha256(consensusPubkey)[:20]. +/// rates are 1e18-scaled; times are Unix nanoseconds. Accounts are EVM addresses, +/// and a validator is keyed by its operator's. An enumeration is kept only where an +/// on-chain path walks it. contract StakingStorage { struct Description { string moniker; @@ -45,6 +46,12 @@ contract StakingStorage { uint256[8] __gap; } + /// @dev A bonded validator and the consensus power last sent for it. + struct ValidatorPower { + address operator; + uint64 power; + } + struct Delegation { uint256 shares; } @@ -56,13 +63,6 @@ contract StakingStorage { uint256 balance; } - struct RedelegationEntry { - uint64 creationHeight; - uint64 completionTime; - uint256 initialBalance; - uint256 sharesDst; - } - /// @dev A queue entry's completionTime is never earlier than the one before it. struct UnbondingQueueEntry { uint64 completionTime; @@ -70,11 +70,16 @@ contract StakingStorage { address validator; } + /// @dev A redelegation entry's only record: V2's queue triplet and its + /// RedelegationEntry together. struct RedelegationQueueEntry { uint64 completionTime; address delegator; + uint64 creationHeight; address srcValidator; address dstValidator; + uint256 initialBalance; + uint256 sharesDst; } struct ValidatorQueueEntry { @@ -89,29 +94,21 @@ contract StakingStorage { uint64 tail; } - mapping(address => uint64) internal lastValidatorPower; // 0x11: operator => power - AddressSet internal lastValidatorPowerSet; // operators with a lastValidatorPower + ValidatorPower[] internal lastValidators; // 0x11: the bonded set, as last sent to consensus uint256 internal lastTotalPower; // 0x12 mapping(address => Validator) internal validators; // 0x21: operator => AddressSet internal validatorSet; // every operator in validators - mapping(address => address) internal validatorsByConsAddr; // 0x22: consensus address => operator + mapping(bytes32 => address) internal validatorsByConsensusPubkey; // 0x22, keyed by the key itself: consensusPubkey => operator address[] internal validatorsByPower; // 0x23: unjailed operators, descending by power, ties to the lower address mapping(address => mapping(address => Delegation)) internal delegations; // 0x31: delegator => validator => - mapping(address => AddressSet) internal delegationsByValidator; // 0x37: validator => delegators mapping(address => AddressSet) internal delegationsByDelegator; // delegator => validators mapping(address => mapping(address => UnbondingDelegationEntry[])) internal unbondingDelegations; // 0x32: delegator => validator => entries, at most maxEntries - mapping(address => AddressSet) internal unbondingDelegationsByValidator; // 0x33: validator => delegators - mapping(address => AddressSet) internal unbondingDelegationsByDelegator; // delegator => validators - mapping(address => mapping(address => mapping(address => RedelegationEntry[]))) internal redelegations; // 0x34: delegator => src => dst => entries, at most maxEntries - mapping(address => mapping(address => AddressSet)) internal redelegationsByValSrc; // 0x35: src => delegator => dsts - mapping(address => AddressSet) internal redelegationDelegatorsByValSrc; // src => delegators + mapping(address => mapping(address => mapping(address => uint256))) internal redelegationEntryCounts; // 0x34: delegator => src => dst => open entries, at most maxEntries mapping(address => mapping(address => uint256)) internal redelegationsByValDst; // 0x36: dst => delegator => open entries into dst - mapping(address => mapping(address => AddressSet)) internal redelegationsByDelegator; // delegator => src => dsts - mapping(address => AddressSet) internal redelegationSrcsByDelegator; // delegator => srcs QueueBounds internal unbondingQueueBounds; mapping(uint64 => UnbondingQueueEntry) internal unbondingQueue; // 0x41: index => diff --git a/docs/giga-storage/staking-design-rationale.md b/docs/giga-storage/staking-design-rationale.md index 54acc305e0..79554e66e1 100644 --- a/docs/giga-storage/staking-design-rationale.md +++ b/docs/giga-storage/staking-design-rationale.md @@ -51,9 +51,9 @@ Solidity's rules, briefly: For example, a delegation's shares would live at `delegations[delegator][validator].shares`. In the draft, `delegations` sits at -slot 9 of `StakingStorage` (the two sets before it take two slots each), so the -shares are at `keccak256(validator . keccak256(delegator . 9))`, with each key -padded to 32 bytes. +slot 7 of `StakingStorage` (the set before it takes two slots), so the shares +are at `keccak256(validator . keccak256(delegator . 7))`, with each key padded +to 32 bytes. `Validator` shows the struct rules on a larger record. In the draft it takes 23 slots: @@ -108,9 +108,10 @@ constant number of writes. `solstorage.Set` already reads this layout. **Some things IAVL can do, slots cannot.** V2 stores state in an ordered key value store. It can walk keys in sorted order, walk every key under a prefix, delete every key under a prefix, and ask whether any key under a prefix exists. -Contract storage is a hash map with none of those operations. Each place this -proposal departs from V2's structures comes from that gap. The largest, the -prefix walks, may argue for relaxing Principle 1 in places; see below. +Contract storage is a hash map with none of those operations. Most places this +proposal departs from V2's structures come from that gap. The largest, the +prefix walks, is answered by keeping only the walks an on-chain path needs; see +below. --- @@ -127,8 +128,10 @@ giga record for record. The proposal copies **structure**, not data types: -- **Each V2 store prefix becomes one state variable**, named after the V2 - record and commented with the prefix it came from. +- **Each V2 store prefix that an on-chain path reads becomes one state + variable**, named after the V2 record and commented with the prefix it came + from. Indexes that only queries or entry slashing read are left out; see + *Prefix walks*. - **Each record keeps V2's fields, field order and names.** - **Data types are Ethereum-native.** Amounts are wei, not usei. Shares, rates and reward ratios are 1e18-scaled fixed point, which is also V2's `sdk.Dec` @@ -161,15 +164,15 @@ Staking: | V2 prefix | V2 record | Proposed giga state variable | |---|---|---| -| `0x11` | last validator power | `lastValidatorPower` (+ set) | +| `0x11` | last validator power | `lastValidators` (array, one slot per bonded validator) | | `0x12` | last total power | `lastTotalPower` | | `0x21` | validators | `validators` (+ set) | -| `0x22` | validator by consensus address | `validatorsByConsAddr` | +| `0x22` | validator by consensus address | `validatorsByConsensusPubkey`, keyed by the key itself | | `0x23` | validators by power | `validatorsByPower` (sorted array) | | `0x31` | delegations | `delegations` (+ set per delegator) | -| `0x37` | delegations by validator | `delegationsByValidator` | -| `0x32`, `0x33` | unbonding delegations and their index | `unbondingDelegations` (+ sets) | -| `0x34`–`0x36` | redelegations and their indexes | `redelegations` (+ sets, a count) | +| `0x37` | delegations by validator | not carried over (queries only) | +| `0x32`, `0x33` | unbonding delegations and their index | `unbondingDelegations`; the index is not carried over | +| `0x34`–`0x36` | redelegations and their indexes | `redelegationEntryCounts` and `redelegationsByValDst`; entries live in the redelegation queue, and `0x35` is not carried over | | `0x41`–`0x43` | unbonding, redelegation, validator queues | three queues | | `0x50` | historical info | not carried over (see below) | @@ -177,9 +180,11 @@ Distribution: prefixes `0x00`–`0x08` map one to one onto the nine state variables in `DistributionStorage.sol`, from `communityPool` to `validatorSlashEvents`. -Slashing: signing info (`0x01`), Sei's packed missed-block array (`0x02`) and -the address-to-pubkey relation (`0x03`) map one to one. The missed-block -`uint64[]` packs four words per slot, so the bits are V2's bits. +Slashing: signing info (`0x01`) and Sei's packed missed-block array (`0x02`) +map one to one, keyed by operator rather than consensus address. The missed-block +`uint64[]` packs four words per slot, so the bits are V2's bits. The +address-to-pubkey relation (`0x03`) is not carried over, since the key is on the +staking `Validator`. ### The power index @@ -256,27 +261,35 @@ forces a change from V2. The first is the hardest. Anywhere V2 walks every key under a prefix ("all delegations of this delegator", "all delegators of this validator", "all validators"), slot storage needs an -explicit enumeration set. The draft layouts do this: V2's own index prefixes -(`0x33`, `0x35`, `0x37`) become sets of the same shape, and new sets cover walks -V2 did over the primary key (`validatorSet`, `delegationsByDelegator` and so -on). - -This may not hold up. Each set adds two or three slot writes whenever a member -joins or leaves, and the sets roughly double the writes for every delegation -created or removed. Across a million delegations the sets themselves are a large -share of the state, and of what the migration has to write. Removing a validator -or a delegator with many entries means walking and clearing large sets. - -The alternative is to store the indexes, and possibly the primary records, as -ordered flatkv keys and use flatkv's prefix reads, which is what V2 does on IAVL. -That would give back ordered and prefix iteration, prefix delete and existence -checks, and could also hold the power index. It gives up -Principle 1 for those records: they would not be described by a `.sol` file and -would not be readable through `eth_getStorageAt`. It also depends on flatkv -exposing ordered prefix iteration to the precompiles, as part of committed state. -A middle ground is to keep primary records in slots and move only the indexes -to flatkv. A further option, for indexes that only queries use, is to leave them -to an off-chain indexer. Which of these to pursue is open. +explicit enumeration set, and each set adds two or three slot writes whenever a +member joins or leaves. The draft keeps two: + +- `delegationsByDelegator`, which gov's tally walks for each voter. +- `validatorSet`, every validator record. Nothing on chain walks it while + `validatorsByPower` holds the unjailed validators, so whether it stays is + open. + +V2's other walks have no on-chain reader in giga: + +| V2 walk | Read by | +|---|---| +| `0x37`, delegations by validator | queries | +| `0x33`, unbonding delegations by validator | slashing unbonding entries | +| `0x35`, redelegations by source validator | slashing redelegation entries | +| unbonding delegations and redelegations by delegator | queries | + +Queries would be served by an off-chain indexer reading the precompile's logs. +Slashing unbonding and redelegation entries is deferred (see *Not yet covered*). +Both kinds of entry keep their creation height and amounts, so turning it on +needs only a way to find a validator's entries: these walks back, or a check +made as each entry matures. + +Ordered flatkv keys, V2's approach on IAVL, are the alternative for the walks +that remain and for the power index. They would give back ordered and prefix +iteration, prefix delete and existence checks, but give up Principle 1 for +those records: they would not be described by a `.sol` file or readable through +`eth_getStorageAt`. They also depend on flatkv exposing ordered prefix +iteration to the precompiles, as part of committed state. #### Smaller changes @@ -285,14 +298,30 @@ chain redelegations by checking whether any key exists under `0x36 ‖ dst ‖ delegator`. The draft counts open entries in `redelegationsByValDst` instead. +**Redelegation entries live in the queue.** On chain, V2 reads a redelegation +entry's fields only to slash it. Completing one moves no funds, since the stake +moved when the redelegation began. The draft keeps each entry's fields in its +`redelegationQueue` entry, and counts open entries per delegator, source and +destination in `redelegationEntryCounts` for `maxEntries`. A matured entry pops +off the queue and decrements that count and `redelegationsByValDst`. + **Time-ordered queues become first-in, first-out lists.** V2 keys its maturity queues by completion time and walks them up to the current time. The draft makes each queue an array read from its head, with each new entry's completion -time clamped to be no earlier than the entry before it. While `unbondingTime` -stays constant this changes nothing. If governance shortens `unbondingTime`, new -unbondings would wait behind older ones rather than overtaking them. A validator -that re-bonds before its unbonding finishes would leave a stale queue entry, -which EndBlock skips. Ordered flatkv keys would avoid the clamp. +time clamped to be no earlier than the entry before it. Two kinds of entry are +clamped: + +- A redelegation from an unbonding validator. V2 completes it when that + validator finishes unbonding. The clamp moves it to the completion time of the + entry queued before it, up to one unbonding period from now. The stake moves + at once either way, so the entry only holds the delegator to the chaining rule + and `maxEntries` for longer, by at most the time since the source began + unbonding. +- Every new entry after governance shortens `unbondingTime`, which waits behind + older ones rather than overtaking them. + +A validator that re-bonds before its unbonding finishes would leave a stale +queue entry, which EndBlock skips. Ordered flatkv keys would avoid the clamp. **Slash events become an array ordered by height**, found by binary search, where V2 uses a key range by height. @@ -311,6 +340,14 @@ only today; the pre-migration checklist would confirm it for everything. (a protobuf `Any` in V2) becomes a `bytes32` ed25519 key. All 88 validators on pacific-1 use ed25519. +**No consensus address.** Staking, distribution and slashing key a validator by +its operator. The one lookup by key, `validatorsByConsensusPubkey`, rejects a +key another validator already uses, as V2's `0x22` does, and resolves a key that +consensus names; autobahn names committee members by key. Keying validators by +an address derived from the key would make the duplicate check free, but nobody +could sign for that address, so a validator would still need a separate +operator, and could never change its key. + **Historical info is not carried over.** V2 writes the full validator set into `0x50` every block, and its only reader is IBC, which giga does not run. @@ -367,11 +404,11 @@ Sei has done something similar in V2: the `0x37` delegation-by-validator index was backfilled with a cursor key and a ready marker. **How long it might take.** Roughly V2 keys × writes per key ÷ the per-block -budget. V2 holds about three or four keys per delegation, and with the draft's -sets each takes about three or four slot writes. At a million delegations and -10,000 keys per block, that is about 1,500 blocks, or ten minutes at 400 ms -blocks; at 100,000 delegations, about a minute. Fewer sets (see *Prefix walks*) -would shorten it. The real delegation count is not known yet. +budget. V2 holds about three or four keys per delegation, and each takes at +most three or four slot writes; the index keys giga does not carry over +(`0x33`, `0x35`, `0x37`) take none. At a million delegations and 10,000 keys per +block, that is about 1,500 blocks, or ten minutes at 400 ms blocks; at 100,000 +delegations, about a minute. The real delegation count is not known yet. **Where V2 state is read from.** The sweep would read V2 through an interface implemented in `evmonlyapp`, which may import sei-cosmos, so `giga/evmonly` @@ -522,11 +559,12 @@ Known gaps that need an owner or a decision. 1. Power index: what cap on validator records, and what minimum to create one? And is gas per place moved the right charge for a reorder? -2. Prefix walks: enumeration sets in slots, ordered flatkv keys (for indexes - only, or for records too), or off-chain indexing for query-only walks? +2. Prefix walks: does `validatorSet` stay? And do the remaining set and the + power index stay in slots, or move to ordered flatkv keys? 3. Reward and pool amounts: whole wei, or 1e18-scaled wei? -4. Is the queue behaviour after a shortened `unbondingTime` acceptable, or does - the queue answer change with question 2? +4. Is the clamped queue behaviour acceptable: a redelegation from an unbonding + validator held to the chaining rule for longer, and new entries waiting + behind older ones after a shortened `unbondingTime`? 5. Do the gov changes (counting lock and stored bonded set) land in the gov PR stack or with the staking work, and is a tally lock of a couple of minutes acceptable for very large proposals? diff --git a/giga/evmonly/precompiles/gov/electorate.go b/giga/evmonly/precompiles/gov/electorate.go index 81c75b3c7f..0fe3307a45 100644 --- a/giga/evmonly/precompiles/gov/electorate.go +++ b/giga/evmonly/precompiles/gov/electorate.go @@ -29,7 +29,7 @@ type Delegation struct { // gives it to x/gov. Tallies are in the unit of its tokens. // // TODO(giga staking): add an Electorate reading StakingStorage at 0x1005, from -// bondedValidatorSet, validators[operator].tokens and .delegatorShares, +// lastValidators, validators[operator].tokens and .delegatorShares, // delegationsByDelegator[voter] and delegations[voter][validator].shares, with // TotalBonded the bonded escrow's balance. It replaces GenesisElectorate. type Electorate interface { From a9bf44abf898f3fa3cd1f4c21863ee66aaa309b5 Mon Sep 17 00:00:00 2001 From: Tony Chen Date: Thu, 5 Nov 2026 13:08:04 +0800 Subject: [PATCH 29/44] docs(giga-storage): say where each kind of struct can grow A mapping value grows at its end and needs no reserved slots. A struct inside another, a top-level struct with variables after it, and an array element cannot grow at their end; say what each can do instead, and add an open question on validatorSlashEvents, the one array of structs kept for good. Co-Authored-By: Claude Opus 5.5 --- docs/giga-storage/staking-design-rationale.md | 35 ++++++++++++++++--- 1 file changed, 30 insertions(+), 5 deletions(-) diff --git a/docs/giga-storage/staking-design-rationale.md b/docs/giga-storage/staking-design-rationale.md index 79554e66e1..c12c451967 100644 --- a/docs/giga-storage/staking-design-rationale.md +++ b/docs/giga-storage/staking-design-rationale.md @@ -83,11 +83,33 @@ slots: ### Consequences -**Layouts only grow.** Once a public network runs a layout, a state variable or -field cannot move. New fields would take slots from a struct's `__gap`, and new -state variables would go after the last one. The draft `Validator` reserves -eight slots for this, and `layout_test.go` pins would catch an accidental -reorder. +**Layouts only grow.** Once a public network runs a layout, no state variable +or field can move, change type or go away. A retired field keeps its slot, and +the slot is not reused for anything else, since records written before still +hold the old values. New state variables go after the last one. A new field +reads as zero in every record written before it, so zero has to mean what the +code did before, or the upgrade that adds the field writes it. Where a new field +can go depends on where its struct is stored: + +- **A mapping value** (`Validator`, `Delegation`, the queue entries, + `DelegatorStartingInfo`, `ValidatorSigningInfo`) grows at its end. Each value + starts at its own hashed slot, so the slots after it are free, and no + reserved slots are needed: `Validator`'s `__gap` is optional. +- **A struct inside another** (`Description` and `Commission` in `Validator`) + cannot grow without moving the fields after it. A new field goes at the end + of the outer struct instead. +- **A top-level struct with state variables after it** grows only into room it + already has: `ParamsStorage`'s subspaces into their `__gap`, a `QueueBounds` + into the 16 free bytes of its slot. +- **An array element** cannot grow, since a larger element moves every element + after the first. `lastValidators` holds at most 100, so the upgrade can + rewrite it. Unbonding entries complete within the unbonding time, so a new + layout can start in a new state variable while the old one drains. + `validatorSlashEvents` is kept for good, so its element has to be settled + before launch (see *Open questions*). + +`layout_test.go` pins every slot and offset, so a change that moves one fails +it. **No library dependencies.** The draft layouts import nothing from outside this directory, including OpenZeppelin. The precompiles need enumerable sets, and @@ -570,3 +592,6 @@ Known gaps that need an owner or a decision. acceptable for very large proposals? 6. Is the validator set frozen during the migration, or can it change? 7. Who owns the V2 read side of the sweep, and can the flatkv copy serve it? +8. `validatorSlashEvents` is the one array of structs kept for good, so its + element can never grow. Should it be a mapping by index with a count, whose + values can? From 23de979ef70187062d417b554c77127aaeb3d9d9 Mon Sep 17 00:00:00 2001 From: Tony Chen Date: Thu, 5 Nov 2026 13:10:19 +0800 Subject: [PATCH 30/44] docs(giga-storage): drop Validator's reserved slots Validator is a mapping value, so it grows at its end and needs no __gap. Co-Authored-By: Claude Opus 5.5 --- docs/giga-storage/StakingStorage.sol | 1 - docs/giga-storage/staking-design-rationale.md | 5 ++--- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/docs/giga-storage/StakingStorage.sol b/docs/giga-storage/StakingStorage.sol index ce6b1a04d7..c727f99c80 100644 --- a/docs/giga-storage/StakingStorage.sol +++ b/docs/giga-storage/StakingStorage.sol @@ -43,7 +43,6 @@ contract StakingStorage { uint64 unbondingTime; Commission commission; uint256 minSelfDelegation; - uint256[8] __gap; } /// @dev A bonded validator and the consensus power last sent for it. diff --git a/docs/giga-storage/staking-design-rationale.md b/docs/giga-storage/staking-design-rationale.md index c12c451967..38e720ce01 100644 --- a/docs/giga-storage/staking-design-rationale.md +++ b/docs/giga-storage/staking-design-rationale.md @@ -55,7 +55,7 @@ slot 7 of `StakingStorage` (the set before it takes two slots), so the shares are at `keccak256(validator . keccak256(delegator . 7))`, with each key padded to 32 bytes. -`Validator` shows the struct rules on a larger record. In the draft it takes 23 +`Validator` shows the struct rules on a larger record. In the draft it takes 15 slots: | Slot offset | Fields | @@ -68,7 +68,6 @@ slots: | 9 | `unbondingHeight`, `unbondingTime` (packed) | | 10–13 | `commission` (three rates, then `updateTime`) | | 14 | `minSelfDelegation` | -| 15–22 | `__gap` (reserved) | ### Why @@ -94,7 +93,7 @@ can go depends on where its struct is stored: - **A mapping value** (`Validator`, `Delegation`, the queue entries, `DelegatorStartingInfo`, `ValidatorSigningInfo`) grows at its end. Each value starts at its own hashed slot, so the slots after it are free, and no - reserved slots are needed: `Validator`'s `__gap` is optional. + reserved slots are needed. - **A struct inside another** (`Description` and `Commission` in `Validator`) cannot grow without moving the fields after it. A new field goes at the end of the outer struct instead. From a576e3e5aa001bc1fe21df4d216b5a0029c38ba8 Mon Sep 17 00:00:00 2001 From: Tony Chen Date: Thu, 5 Nov 2026 13:10:59 +0800 Subject: [PATCH 31/44] docs(giga-storage): let an array element grow into a gap of its own Co-Authored-By: Claude Opus 5.5 --- docs/giga-storage/staking-design-rationale.md | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/docs/giga-storage/staking-design-rationale.md b/docs/giga-storage/staking-design-rationale.md index 38e720ce01..8bba269a33 100644 --- a/docs/giga-storage/staking-design-rationale.md +++ b/docs/giga-storage/staking-design-rationale.md @@ -100,10 +100,13 @@ can go depends on where its struct is stored: - **A top-level struct with state variables after it** grows only into room it already has: `ParamsStorage`'s subspaces into their `__gap`, a `QueueBounds` into the 16 free bytes of its slot. -- **An array element** cannot grow, since a larger element moves every element - after the first. `lastValidators` holds at most 100, so the upgrade can - rewrite it. Unbonding entries complete within the unbonding time, so a new - layout can start in a new state variable while the old one drains. +- **An array element** grows only into a `__gap` of its own, since a larger + element moves every element after the first. A gap costs nothing to store, as + a zero slot is not stored, provided adding, moving and clearing elements + write only the fields in use: Solidity's `delete` and `pop` zero every slot. + Without a gap, `lastValidators` holds at most 100, so the upgrade can rewrite + it, and unbonding entries complete within the unbonding time, so a new layout + can start in a new state variable while the old one drains. `validatorSlashEvents` is kept for good, so its element has to be settled before launch (see *Open questions*). @@ -591,6 +594,6 @@ Known gaps that need an owner or a decision. acceptable for very large proposals? 6. Is the validator set frozen during the migration, or can it change? 7. Who owns the V2 read side of the sweep, and can the flatkv copy serve it? -8. `validatorSlashEvents` is the one array of structs kept for good, so its - element can never grow. Should it be a mapping by index with a count, whose - values can? +8. `validatorSlashEvents` is the one array of structs kept for good. Should its + element get a `__gap`, or should it be a mapping by index with a count, + whose values grow at their end? From eb2760fdee28edf7b5628c7ac7dd6a9939989d82 Mon Sep 17 00:00:00 2001 From: Tony Chen Date: Thu, 5 Nov 2026 19:51:30 +0800 Subject: [PATCH 32/44] docs(giga-storage): cover deletes, top-level values, scalar mapping values and sets in the growth rule Co-Authored-By: Claude Opus 5.5 --- docs/giga-storage/staking-design-rationale.md | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/docs/giga-storage/staking-design-rationale.md b/docs/giga-storage/staking-design-rationale.md index 8bba269a33..2d4dd15821 100644 --- a/docs/giga-storage/staking-design-rationale.md +++ b/docs/giga-storage/staking-design-rationale.md @@ -87,13 +87,21 @@ or field can move, change type or go away. A retired field keeps its slot, and the slot is not reused for anything else, since records written before still hold the old values. New state variables go after the last one. A new field reads as zero in every record written before it, so zero has to mean what the -code did before, or the upgrade that adds the field writes it. Where a new field -can go depends on where its struct is stored: - +code did before, or the upgrade that adds the field writes it. A delete has to +clear every slot the record has used, fields added since included, or a record +later created under the same key reads the old values. What can change depends +on where the state is stored: + +- **A top-level value** (`lastTotalPower`, `communityPool`, `previousProposer`) + cannot change type. A new state variable replaces it, and the upgrade copies + the value over. - **A mapping value** (`Validator`, `Delegation`, the queue entries, `DelegatorStartingInfo`, `ValidatorSigningInfo`) grows at its end. Each value starts at its own hashed slot, so the slots after it are free, and no reserved slots are needed. +- **A mapping value that is not a struct** (`validatorOutstandingRewards`, + `delegatorWithdrawAddr`, `redelegationEntryCounts`) can become a struct whose + first field is the old value, which stays in the same slot. - **A struct inside another** (`Description` and `Commission` in `Validator`) cannot grow without moving the fields after it. A new field goes at the end of the outer struct instead. @@ -109,6 +117,11 @@ can go depends on where its struct is stored: can start in a new state variable while the old one drains. `validatorSlashEvents` is kept for good, so its element has to be settled before launch (see *Open questions*). +- **An enumeration set** keeps its shape, and dropping one only stops its + writes. Adding one after launch means filling it with the existing members, + and a mapping's keys cannot be listed from its slots, so a set can be added + only where its members can be found another way. The sets a later upgrade may + need are decided before launch (see *Prefix walks*). `layout_test.go` pins every slot and offset, so a change that moves one fails it. From c2f60cdff02b0ecd177715a9de2b4e23ade506aa Mon Sep 17 00:00:00 2001 From: Tony Chen Date: Thu, 5 Nov 2026 19:51:30 +0800 Subject: [PATCH 33/44] docs(giga-storage): give ValidatorSlashEvent a __gap Co-Authored-By: Claude Opus 5.5 --- docs/giga-storage/DistributionStorage.sol | 1 + docs/giga-storage/staking-design-rationale.md | 13 +++++-------- 2 files changed, 6 insertions(+), 8 deletions(-) diff --git a/docs/giga-storage/DistributionStorage.sol b/docs/giga-storage/DistributionStorage.sol index 9e2404d9a7..23fdad6aca 100644 --- a/docs/giga-storage/DistributionStorage.sol +++ b/docs/giga-storage/DistributionStorage.sol @@ -29,6 +29,7 @@ contract DistributionStorage { uint64 height; uint64 validatorPeriod; uint256 fraction; + uint256[8] __gap; } uint256 internal communityPool; // 0x00: FeePool.community_pool diff --git a/docs/giga-storage/staking-design-rationale.md b/docs/giga-storage/staking-design-rationale.md index 2d4dd15821..11234f148b 100644 --- a/docs/giga-storage/staking-design-rationale.md +++ b/docs/giga-storage/staking-design-rationale.md @@ -112,11 +112,11 @@ on where the state is stored: element moves every element after the first. A gap costs nothing to store, as a zero slot is not stored, provided adding, moving and clearing elements write only the fields in use: Solidity's `delete` and `pop` zero every slot. - Without a gap, `lastValidators` holds at most 100, so the upgrade can rewrite - it, and unbonding entries complete within the unbonding time, so a new layout - can start in a new state variable while the old one drains. - `validatorSlashEvents` is kept for good, so its element has to be settled - before launch (see *Open questions*). + `ValidatorSlashEvent` has one, since `validatorSlashEvents` is kept for good. + The other arrays have none: `lastValidators` holds at most 100, so the + upgrade can rewrite it, and unbonding entries complete within the unbonding + time, so a new layout can start in a new state variable while the old one + drains. - **An enumeration set** keeps its shape, and dropping one only stops its writes. Adding one after launch means filling it with the existing members, and a mapping's keys cannot be listed from its slots, so a set can be added @@ -607,6 +607,3 @@ Known gaps that need an owner or a decision. acceptable for very large proposals? 6. Is the validator set frozen during the migration, or can it change? 7. Who owns the V2 read side of the sweep, and can the flatkv copy serve it? -8. `validatorSlashEvents` is the one array of structs kept for good. Should its - element get a `__gap`, or should it be a mapping by index with a count, - whose values grow at their end? From 01eba028846f84f02fceef86bda28c33692ae61b Mon Sep 17 00:00:00 2001 From: Tony Chen Date: Mon, 9 Nov 2026 12:00:17 +0800 Subject: [PATCH 34/44] docs(giga-storage): drop signingInfoSet Only queries walk signing infos, so the slashing layout keeps no enumeration of them, as the rule for enumerations says. Co-Authored-By: Claude Opus 5.5 --- docs/giga-storage/SlashingStorage.sol | 3 --- docs/giga-storage/staking-design-rationale.md | 1 + 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/docs/giga-storage/SlashingStorage.sol b/docs/giga-storage/SlashingStorage.sol index 7450ac9890..438f640efa 100644 --- a/docs/giga-storage/SlashingStorage.sol +++ b/docs/giga-storage/SlashingStorage.sol @@ -1,8 +1,6 @@ // SPDX-License-Identifier: MIT pragma solidity 0.8.30; -import "./Sets.sol"; - /// @notice Storage schema of the evmonly slashing precompile (0x1014), held as that /// address's contract storage. Each state variable is an x/slashing store prefix, /// named in its comment. @@ -24,6 +22,5 @@ contract SlashingStorage { } mapping(address => ValidatorSigningInfo) internal validatorSigningInfo; // 0x01: operator => - AddressSet internal signingInfoSet; // every operator in validatorSigningInfo mapping(address => ValidatorMissedBlockArray) internal validatorMissedBlocks; // 0x02: operator => } diff --git a/docs/giga-storage/staking-design-rationale.md b/docs/giga-storage/staking-design-rationale.md index 11234f148b..6a1b5aa0aa 100644 --- a/docs/giga-storage/staking-design-rationale.md +++ b/docs/giga-storage/staking-design-rationale.md @@ -314,6 +314,7 @@ V2's other walks have no on-chain reader in giga: | `0x33`, unbonding delegations by validator | slashing unbonding entries | | `0x35`, redelegations by source validator | slashing redelegation entries | | unbonding delegations and redelegations by delegator | queries | +| slashing `0x01`, signing infos | queries; liveness reads each voter's by key | Queries would be served by an off-chain indexer reading the precompile's logs. Slashing unbonding and redelegation entries is deferred (see *Not yet covered*). From 0ca730fa3df74ae6a38b43cbc239444957e3a9b5 Mon Sep 17 00:00:00 2001 From: Tony Chen Date: Mon, 16 Nov 2026 12:06:03 +0800 Subject: [PATCH 35/44] docs(giga-storage): keep delegations by validator V2's staking precompile serves a validator's delegations to contracts, and a set of them cannot be filled after launch, since a mapping's keys cannot be listed from its slots. Co-Authored-By: Claude Opus 5.5 --- docs/giga-storage/StakingStorage.sol | 1 + docs/giga-storage/staking-design-rationale.md | 13 ++++++++----- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/docs/giga-storage/StakingStorage.sol b/docs/giga-storage/StakingStorage.sol index c727f99c80..5dbfce4078 100644 --- a/docs/giga-storage/StakingStorage.sol +++ b/docs/giga-storage/StakingStorage.sol @@ -103,6 +103,7 @@ contract StakingStorage { mapping(address => mapping(address => Delegation)) internal delegations; // 0x31: delegator => validator => mapping(address => AddressSet) internal delegationsByDelegator; // delegator => validators + mapping(address => AddressSet) internal delegationsByValidator; // 0x37: validator => delegators mapping(address => mapping(address => UnbondingDelegationEntry[])) internal unbondingDelegations; // 0x32: delegator => validator => entries, at most maxEntries diff --git a/docs/giga-storage/staking-design-rationale.md b/docs/giga-storage/staking-design-rationale.md index 6a1b5aa0aa..9a470371d4 100644 --- a/docs/giga-storage/staking-design-rationale.md +++ b/docs/giga-storage/staking-design-rationale.md @@ -207,7 +207,7 @@ Staking: | `0x22` | validator by consensus address | `validatorsByConsensusPubkey`, keyed by the key itself | | `0x23` | validators by power | `validatorsByPower` (sorted array) | | `0x31` | delegations | `delegations` (+ set per delegator) | -| `0x37` | delegations by validator | not carried over (queries only) | +| `0x37` | delegations by validator | `delegationsByValidator` (set per validator) | | `0x32`, `0x33` | unbonding delegations and their index | `unbondingDelegations`; the index is not carried over | | `0x34`–`0x36` | redelegations and their indexes | `redelegationEntryCounts` and `redelegationsByValDst`; entries live in the redelegation queue, and `0x35` is not carried over | | `0x41`–`0x43` | unbonding, redelegation, validator queues | three queues | @@ -299,9 +299,13 @@ forces a change from V2. The first is the hardest. Anywhere V2 walks every key under a prefix ("all delegations of this delegator", "all delegators of this validator", "all validators"), slot storage needs an explicit enumeration set, and each set adds two or three slot writes whenever a -member joins or leaves. The draft keeps two: +member joins or leaves. The draft keeps three: - `delegationsByDelegator`, which gov's tally walks for each voter. +- `delegationsByValidator`, which V2's staking precompile serves to contracts + as `validatorDelegations`. Its members are found only through the delegations + themselves, so it could not be filled after launch, and it is kept from the + start for a later method to page through. - `validatorSet`, every validator record. Nothing on chain walks it while `validatorsByPower` holds the unjailed validators, so whether it stays is open. @@ -310,7 +314,6 @@ V2's other walks have no on-chain reader in giga: | V2 walk | Read by | |---|---| -| `0x37`, delegations by validator | queries | | `0x33`, unbonding delegations by validator | slashing unbonding entries | | `0x35`, redelegations by source validator | slashing redelegation entries | | unbonding delegations and redelegations by delegator | queries | @@ -444,7 +447,7 @@ was backfilled with a cursor key and a ready marker. **How long it might take.** Roughly V2 keys × writes per key ÷ the per-block budget. V2 holds about three or four keys per delegation, and each takes at most three or four slot writes; the index keys giga does not carry over -(`0x33`, `0x35`, `0x37`) take none. At a million delegations and 10,000 keys per +(`0x33`, `0x35`) take none. At a million delegations and 10,000 keys per block, that is about 1,500 blocks, or ten minutes at 400 ms blocks; at 100,000 delegations, about a minute. The real delegation count is not known yet. @@ -597,7 +600,7 @@ Known gaps that need an owner or a decision. 1. Power index: what cap on validator records, and what minimum to create one? And is gas per place moved the right charge for a reorder? -2. Prefix walks: does `validatorSet` stay? And do the remaining set and the +2. Prefix walks: does `validatorSet` stay? And do the remaining sets and the power index stay in slots, or move to ordered flatkv keys? 3. Reward and pool amounts: whole wei, or 1e18-scaled wei? 4. Is the clamped queue behaviour acceptable: a redelegation from an unbonding From c77cd417bc2facef76381cfd163c2055b284e084 Mon Sep 17 00:00:00 2001 From: Tony Chen Date: Mon, 16 Nov 2026 12:08:28 +0800 Subject: [PATCH 36/44] feat(staking): keep each validator's delegators setDelegation and removeDelegation keep delegationsByValidator in step with delegationsByDelegator, so a validator's delegations can be listed without a migration. The harness and layout testdata are rebuilt with solc 0.8.30. Co-Authored-By: Claude Opus 5.5 --- .../precompiles/staking/helpers_test.go | 10 + giga/evmonly/precompiles/staking/layout.go | 19 +- .../precompiles/staking/layout_test.go | 8 +- giga/evmonly/precompiles/staking/storage.go | 7 + .../precompiles/staking/storage_test.go | 15 + .../StakingStorageHarness.bin-runtime | 2 +- .../testdata/StakingStorageHarness.sol | 1 + .../testdata/staking_storage_layout.json | 258 +++++++++--------- 8 files changed, 182 insertions(+), 138 deletions(-) diff --git a/giga/evmonly/precompiles/staking/helpers_test.go b/giga/evmonly/precompiles/staking/helpers_test.go index d62c3134fd..5c9dae92dc 100644 --- a/giga/evmonly/precompiles/staking/helpers_test.go +++ b/giga/evmonly/precompiles/staking/helpers_test.go @@ -10,6 +10,7 @@ import ( ethtypes "github.com/ethereum/go-ethereum/core/types" "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles" + "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles/solstorage" ) // memState is a map-backed precompiles.State and LogSink. @@ -123,3 +124,12 @@ func must[T any](v T, err error) T { } return v } + +// addresses returns the members of an address set, in set order. +func addresses(set solstorage.Set) []common.Address { + out := make([]common.Address, set.Len()) + for i := range out { + out[i] = solstorage.MemberAddress(set.At(uint64(i))) + } + return out +} diff --git a/giga/evmonly/precompiles/staking/layout.go b/giga/evmonly/precompiles/staking/layout.go index a8a4bf8eb9..a8a99d168b 100644 --- a/giga/evmonly/precompiles/staking/layout.go +++ b/giga/evmonly/precompiles/staking/layout.go @@ -18,15 +18,16 @@ const ( slotValidatorsByPower = 6 slotDelegations = 7 slotDelegationsByDelegator = 8 - slotUnbondingDelegations = 9 - slotRedelegationEntryCounts = 10 - slotRedelegationsByValDst = 11 - slotUnbondingQueueBounds = 12 - slotUnbondingQueue = 13 - slotRedelegationQueueBounds = 14 - slotRedelegationQueue = 15 - slotValidatorQueueBounds = 16 - slotValidatorQueue = 17 + slotDelegationsByValidator = 9 + slotUnbondingDelegations = 10 + slotRedelegationEntryCounts = 11 + slotRedelegationsByValDst = 12 + slotUnbondingQueueBounds = 13 + slotUnbondingQueue = 14 + slotRedelegationQueueBounds = 15 + slotRedelegationQueue = 16 + slotValidatorQueueBounds = 17 + slotValidatorQueue = 18 ) // member is a struct member's position relative to the struct's base slot. diff --git a/giga/evmonly/precompiles/staking/layout_test.go b/giga/evmonly/precompiles/staking/layout_test.go index 3420c40d2e..adf4ffeb3a 100644 --- a/giga/evmonly/precompiles/staking/layout_test.go +++ b/giga/evmonly/precompiles/staking/layout_test.go @@ -58,6 +58,7 @@ func TestLayoutMatchesSolc(t *testing.T) { "validatorsByPower": slotValidatorsByPower, "delegations": slotDelegations, "delegationsByDelegator": slotDelegationsByDelegator, + "delegationsByValidator": slotDelegationsByValidator, "unbondingDelegations": slotUnbondingDelegations, "redelegationEntryCounts": slotRedelegationEntryCounts, "redelegationsByValDst": slotRedelegationsByValDst, @@ -67,9 +68,9 @@ func TestLayoutMatchesSolc(t *testing.T) { "redelegationQueue": slotRedelegationQueue, "validatorQueueBounds": slotValidatorQueueBounds, "validatorQueue": slotValidatorQueue, - "migrating": 18, - "migrationCursor": 19, - "migrationFailures": 20, + "migrating": 19, + "migrationCursor": 20, + "migrationFailures": 21, }, got) // Each struct's Go members, and how many slots it takes. Description and @@ -231,6 +232,7 @@ func TestStoreReadsCompilerWrites(t *testing.T) { require.True(t, found) require.Equal(t, big.NewInt(41), shares) require.True(t, s.delegatedValidators(delegator).Contains(solstorage.AddressKey(op))) + require.True(t, s.delegators(op).Contains(solstorage.AddressKey(delegator))) require.Equal(t, []unbondingEntry{ {creationHeight: 51, completionTime: 52, initialBalance: big.NewInt(53), balance: big.NewInt(54)}, {creationHeight: 55, completionTime: 56, initialBalance: big.NewInt(57), balance: big.NewInt(58)}, diff --git a/giga/evmonly/precompiles/staking/storage.go b/giga/evmonly/precompiles/staking/storage.go index d5898692d5..464847e411 100644 --- a/giga/evmonly/precompiles/staking/storage.go +++ b/giga/evmonly/precompiles/staking/storage.go @@ -225,6 +225,11 @@ func (s store) delegatedValidators(delegator common.Address) solstorage.Set { return solstorage.Set{Store: s.Store, Base: solstorage.MapAddress(solstorage.Slot(slotDelegationsByDelegator), delegator)} } +// delegators is the delegators of op. +func (s store) delegators(op common.Address) solstorage.Set { + return solstorage.Set{Store: s.Store, Base: solstorage.MapAddress(solstorage.Slot(slotDelegationsByValidator), op)} +} + // delegation returns delegator's shares in op and whether delegator delegates // to op; a delegation can exist with no shares, as x/staking's can. func (s store) delegation(delegator, op common.Address) (*big.Int, bool) { @@ -238,11 +243,13 @@ func (s store) delegation(delegator, op common.Address) (*big.Int, bool) { func (s store) setDelegation(delegator, op common.Address, shares *big.Int) { s.SetUint256(delegationSlot(delegator, op), shares) s.delegatedValidators(delegator).Add(solstorage.AddressKey(op)) + s.delegators(op).Add(solstorage.AddressKey(delegator)) } func (s store) removeDelegation(delegator, op common.Address) { s.SetUint256(delegationSlot(delegator, op), nil) s.delegatedValidators(delegator).Remove(solstorage.AddressKey(op)) + s.delegators(op).Remove(solstorage.AddressKey(delegator)) } // unbondingEntry is StakingStorage.UnbondingDelegationEntry. diff --git a/giga/evmonly/precompiles/staking/storage_test.go b/giga/evmonly/precompiles/staking/storage_test.go index 8cf7b77d2c..03f932aea7 100644 --- a/giga/evmonly/precompiles/staking/storage_test.go +++ b/giga/evmonly/precompiles/staking/storage_test.go @@ -36,6 +36,21 @@ func TestQueueClampsToItsLastEntry(t *testing.T) { require.Equal(t, common.Hash{}, q.s.Word(q.entry(0)), "pop zeroes the entry") } +func TestDelegationsAreIndexedByDelegatorAndValidator(t *testing.T) { + s := newStore(newMemState()) + s.setDelegation(alice, val1, big.NewInt(1)) + s.setDelegation(alice, val1, big.NewInt(2)) + s.setDelegation(bob, val1, big.NewInt(3)) + s.setDelegation(alice, val2, big.NewInt(4)) + require.Equal(t, []common.Address{alice, bob}, addresses(s.delegators(val1)), "a top-up does not list its delegator twice") + require.Equal(t, []common.Address{alice}, addresses(s.delegators(val2))) + + s.removeDelegation(alice, val1) + require.Equal(t, []common.Address{bob}, addresses(s.delegators(val1))) + require.Equal(t, []common.Address{alice}, addresses(s.delegators(val2))) + require.False(t, s.delegatedValidators(alice).Contains(solstorage.AddressKey(val1))) +} + // TestShareMathMatchesSDK pins the exchange between tokens and shares to // x/staking's Validator, rounding included. func TestShareMathMatchesSDK(t *testing.T) { diff --git a/giga/evmonly/precompiles/staking/testdata/StakingStorageHarness.bin-runtime b/giga/evmonly/precompiles/staking/testdata/StakingStorageHarness.bin-runtime index 2501059207..6747b79150 100644 --- a/giga/evmonly/precompiles/staking/testdata/StakingStorageHarness.bin-runtime +++ b/giga/evmonly/precompiles/staking/testdata/StakingStorageHarness.bin-runtime @@ -1 +1 @@ -608060405234801561000f575f5ffd5b5060043610610029575f3560e01c80633afaaf0e1461002d575b5f5ffd5b610047600480360381019061004291906110b4565b610049565b005b5f60405180604001604052808673ffffffffffffffffffffffffffffffffffffffff168152602001601e67ffffffffffffffff16815250908060018154018082558091505060019003905f5260205f20015f909190919091505f820151815f015f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506020820151815f0160146101000a81548167ffffffffffffffff021916908367ffffffffffffffff16021790555050505f60405180604001604052808573ffffffffffffffffffffffffffffffffffffffff168152602001601467ffffffffffffffff16815250908060018154018082558091505060019003905f5260205f20015f909190919091505f820151815f015f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506020820151815f0160146101000a81548167ffffffffffffffff021916908367ffffffffffffffff160217905550505060326001819055505f60025f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20905081815f01819055506001816001015f6101000a81548160ff02191690831515021790555060028160010160016101000a81548160ff021916908360ff1602179055506801ae361fc1451c000081600201819055506f1812f9cf7920e2b66973e20000000000816003018190555060405180606001604052806034815260200161142560349139816004015f0190816102c39190611355565b506040518060400160405280600181526020017f640000000000000000000000000000000000000000000000000000000000000081525081600401600401908161030d9190611355565b506021816009015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff16021790555060228160090160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff160217905550602381600a015f015f0181905550602481600a016003015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff160217905550602581600e0181905550600360025f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f2060010160016101000a81548160ff021916908360ff160217905550610410600386610f74565b61041b600385610f74565b8460055f8481526020019081526020015f205f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550600684908060018154018082558091505060019003905f5260205f20015f9091909190916101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550600685908060018154018082558091505060019003905f5260205f20015f9091909190916101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550602960075f8573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f01819055506105f060085f8573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f2086610f74565b60095f8473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f206040518060800160405280603367ffffffffffffffff168152602001603467ffffffffffffffff168152602001603581526020016036815250908060018154018082558091505060019003905f5260205f2090600302015f909190919091505f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506040820151816001015560608201518160020155505060095f8473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f206040518060800160405280603767ffffffffffffffff168152602001603867ffffffffffffffff16815260200160398152602001603a815250908060018154018082558091505060019003905f5260205f2090600302015f909190919091505f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff160217905550604082015181600101556060820151816002015550506002600a5f8573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20819055506003600b5f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20819055506040518060400160405280600167ffffffffffffffff168152602001600267ffffffffffffffff16815250600c5f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055509050506040518060600160405280603d67ffffffffffffffff1681526020018473ffffffffffffffffffffffffffffffffffffffff1681526020018673ffffffffffffffffffffffffffffffffffffffff16815250600d5f600167ffffffffffffffff1681526020019081526020015f205f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506040820151816001015f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555090505060405180604001604052805f67ffffffffffffffff168152602001600167ffffffffffffffff16815250600e5f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055509050506040518060e00160405280604767ffffffffffffffff1681526020018473ffffffffffffffffffffffffffffffffffffffff168152602001604867ffffffffffffffff1681526020018673ffffffffffffffffffffffffffffffffffffffff1681526020018573ffffffffffffffffffffffffffffffffffffffff16815260200160498152602001604a815250600f5f5f67ffffffffffffffff1681526020019081526020015f205f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506040820151816001015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff16021790555060608201518160010160086101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506080820151816002015f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555060a0820151816003015560c082015181600401559050506040518060400160405280600467ffffffffffffffff168152602001600567ffffffffffffffff1681525060105f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055509050506040518060600160405280605167ffffffffffffffff168152602001605267ffffffffffffffff1681526020018573ffffffffffffffffffffffffffffffffffffffff1681525060115f600467ffffffffffffffff1681526020019081526020015f205f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506040820151816001015f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055509050505050505050565b815f0181908060018154018082558091505060019003905f5260205f20015f9091909190916101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550815f0180549050826001015f8373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20819055505050565b5f5ffd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f61105082611027565b9050919050565b61106081611046565b811461106a575f5ffd5b50565b5f8135905061107b81611057565b92915050565b5f819050919050565b61109381611081565b811461109d575f5ffd5b50565b5f813590506110ae8161108a565b92915050565b5f5f5f5f608085870312156110cc576110cb611023565b5b5f6110d98782880161106d565b94505060206110ea8782880161106d565b93505060406110fb8782880161106d565b925050606061110c878288016110a0565b91505092959194509250565b5f81519050919050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52604160045260245ffd5b7f4e487b71000000000000000000000000000000000000000000000000000000005f52602260045260245ffd5b5f600282049050600182168061119357607f821691505b6020821081036111a6576111a561114f565b5b50919050565b5f819050815f5260205f209050919050565b5f6020601f8301049050919050565b5f82821b905092915050565b5f600883026112087fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff826111cd565b61121286836111cd565b95508019841693508086168417925050509392505050565b5f819050919050565b5f819050919050565b5f61125661125161124c8461122a565b611233565b61122a565b9050919050565b5f819050919050565b61126f8361123c565b61128361127b8261125d565b8484546111d9565b825550505050565b5f5f905090565b61129a61128b565b6112a5818484611266565b505050565b5b818110156112c8576112bd5f82611292565b6001810190506112ab565b5050565b601f82111561130d576112de816111ac565b6112e7846111be565b810160208510156112f6578190505b61130a611302856111be565b8301826112aa565b50505b505050565b5f82821c905092915050565b5f61132d5f1984600802611312565b1980831691505092915050565b5f611345838361131e565b9150826002028217905092915050565b61135e82611118565b67ffffffffffffffff81111561137757611376611122565b5b611381825461117c565b61138c8282856112cc565b5f60209050601f8311600181146113bd575f84156113ab578287015190505b6113b5858261133a565b86555061141c565b601f1984166113cb866111ac565b5f5b828110156113f2578489015182556001820191506020850194506020810190506113cd565b8683101561140f578489015161140b601f89168261131e565b8355505b6001600288020188555050505b50505050505056fe61206d6f6e696b6572206c6f6e6720656e6f75676820746f207370696c6c2070617374206f6e652073746f7261676520776f7264a26469706673582212205c15fa37db41f0049a9d40775052987863b4620fae48fddcec9e74526f520a5564736f6c634300081e0033 +608060405234801561000f575f5ffd5b5060043610610029575f3560e01c80633afaaf0e1461002d575b5f5ffd5b610047600480360381019061004291906110fa565b610049565b005b5f60405180604001604052808673ffffffffffffffffffffffffffffffffffffffff168152602001601e67ffffffffffffffff16815250908060018154018082558091505060019003905f5260205f20015f909190919091505f820151815f015f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506020820151815f0160146101000a81548167ffffffffffffffff021916908367ffffffffffffffff16021790555050505f60405180604001604052808573ffffffffffffffffffffffffffffffffffffffff168152602001601467ffffffffffffffff16815250908060018154018082558091505060019003905f5260205f20015f909190919091505f820151815f015f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506020820151815f0160146101000a81548167ffffffffffffffff021916908367ffffffffffffffff160217905550505060326001819055505f60025f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20905081815f01819055506001816001015f6101000a81548160ff02191690831515021790555060028160010160016101000a81548160ff021916908360ff1602179055506801ae361fc1451c000081600201819055506f1812f9cf7920e2b66973e20000000000816003018190555060405180606001604052806034815260200161146b60349139816004015f0190816102c3919061139b565b506040518060400160405280600181526020017f640000000000000000000000000000000000000000000000000000000000000081525081600401600401908161030d919061139b565b506021816009015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff16021790555060228160090160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff160217905550602381600a015f015f0181905550602481600a016003015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff160217905550602581600e0181905550600360025f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f2060010160016101000a81548160ff021916908360ff160217905550610410600386610fba565b61041b600385610fba565b8460055f8481526020019081526020015f205f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550600684908060018154018082558091505060019003905f5260205f20015f9091909190916101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550600685908060018154018082558091505060019003905f5260205f20015f9091909190916101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550602960075f8573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f01819055506105f060085f8573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f2086610fba565b61063660095f8773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f2084610fba565b600a5f8473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f206040518060800160405280603367ffffffffffffffff168152602001603467ffffffffffffffff168152602001603581526020016036815250908060018154018082558091505060019003905f5260205f2090600302015f909190919091505f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff16021790555060408201518160010155606082015181600201555050600a5f8473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f206040518060800160405280603767ffffffffffffffff168152602001603867ffffffffffffffff16815260200160398152602001603a815250908060018154018082558091505060019003905f5260205f2090600302015f909190919091505f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff160217905550604082015181600101556060820151816002015550506002600b5f8573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20819055506003600c5f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20819055506040518060400160405280600167ffffffffffffffff168152602001600267ffffffffffffffff16815250600d5f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055509050506040518060600160405280603d67ffffffffffffffff1681526020018473ffffffffffffffffffffffffffffffffffffffff1681526020018673ffffffffffffffffffffffffffffffffffffffff16815250600e5f600167ffffffffffffffff1681526020019081526020015f205f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506040820151816001015f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555090505060405180604001604052805f67ffffffffffffffff168152602001600167ffffffffffffffff16815250600f5f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055509050506040518060e00160405280604767ffffffffffffffff1681526020018473ffffffffffffffffffffffffffffffffffffffff168152602001604867ffffffffffffffff1681526020018673ffffffffffffffffffffffffffffffffffffffff1681526020018573ffffffffffffffffffffffffffffffffffffffff16815260200160498152602001604a81525060105f5f67ffffffffffffffff1681526020019081526020015f205f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506040820151816001015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff16021790555060608201518160010160086101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506080820151816002015f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555060a0820151816003015560c082015181600401559050506040518060400160405280600467ffffffffffffffff168152602001600567ffffffffffffffff1681525060115f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055509050506040518060600160405280605167ffffffffffffffff168152602001605267ffffffffffffffff1681526020018573ffffffffffffffffffffffffffffffffffffffff1681525060125f600467ffffffffffffffff1681526020019081526020015f205f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506040820151816001015f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055509050505050505050565b815f0181908060018154018082558091505060019003905f5260205f20015f9091909190916101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550815f0180549050826001015f8373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20819055505050565b5f5ffd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6110968261106d565b9050919050565b6110a68161108c565b81146110b0575f5ffd5b50565b5f813590506110c18161109d565b92915050565b5f819050919050565b6110d9816110c7565b81146110e3575f5ffd5b50565b5f813590506110f4816110d0565b92915050565b5f5f5f5f6080858703121561111257611111611069565b5b5f61111f878288016110b3565b9450506020611130878288016110b3565b9350506040611141878288016110b3565b9250506060611152878288016110e6565b91505092959194509250565b5f81519050919050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52604160045260245ffd5b7f4e487b71000000000000000000000000000000000000000000000000000000005f52602260045260245ffd5b5f60028204905060018216806111d957607f821691505b6020821081036111ec576111eb611195565b5b50919050565b5f819050815f5260205f209050919050565b5f6020601f8301049050919050565b5f82821b905092915050565b5f6008830261124e7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff82611213565b6112588683611213565b95508019841693508086168417925050509392505050565b5f819050919050565b5f819050919050565b5f61129c61129761129284611270565b611279565b611270565b9050919050565b5f819050919050565b6112b583611282565b6112c96112c1826112a3565b84845461121f565b825550505050565b5f5f905090565b6112e06112d1565b6112eb8184846112ac565b505050565b5b8181101561130e576113035f826112d8565b6001810190506112f1565b5050565b601f82111561135357611324816111f2565b61132d84611204565b8101602085101561133c578190505b61135061134885611204565b8301826112f0565b50505b505050565b5f82821c905092915050565b5f6113735f1984600802611358565b1980831691505092915050565b5f61138b8383611364565b9150826002028217905092915050565b6113a48261115e565b67ffffffffffffffff8111156113bd576113bc611168565b5b6113c782546111c2565b6113d2828285611312565b5f60209050601f831160018114611403575f84156113f1578287015190505b6113fb8582611380565b865550611462565b601f198416611411866111f2565b5f5b8281101561143857848901518255600182019150602085019450602081019050611413565b868310156114555784890151611451601f891682611364565b8355505b6001600288020188555050505b50505050505056fe61206d6f6e696b6572206c6f6e6720656e6f75676820746f207370696c6c2070617374206f6e652073746f7261676520776f7264a2646970667358221220ca5344d3b5f6f14544837d3f326231a5017eb67a3e45fd84e5063d42ade3370764736f6c634300081e0033 diff --git a/giga/evmonly/precompiles/staking/testdata/StakingStorageHarness.sol b/giga/evmonly/precompiles/staking/testdata/StakingStorageHarness.sol index 77cabb347a..16178f9852 100644 --- a/giga/evmonly/precompiles/staking/testdata/StakingStorageHarness.sol +++ b/giga/evmonly/precompiles/staking/testdata/StakingStorageHarness.sol @@ -33,6 +33,7 @@ contract StakingStorageHarness is StakingStorage { delegations[delegator][op].shares = 41; add(delegationsByDelegator[delegator], op); + add(delegationsByValidator[op], delegator); unbondingDelegations[delegator][op].push( UnbondingDelegationEntry({creationHeight: 51, completionTime: 52, initialBalance: 53, balance: 54}) diff --git a/giga/evmonly/precompiles/staking/testdata/staking_storage_layout.json b/giga/evmonly/precompiles/staking/testdata/staking_storage_layout.json index 31556305d8..8615ae68fe 100644 --- a/giga/evmonly/precompiles/staking/testdata/staking_storage_layout.json +++ b/giga/evmonly/precompiles/staking/testdata/staking_storage_layout.json @@ -1,15 +1,15 @@ { "storage": [ { - "astId": 419, + "astId": 426, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "lastValidators", "offset": 0, "slot": "0", - "type": "t_array(t_struct(ValidatorPower)365_storage)dyn_storage" + "type": "t_array(t_struct(ValidatorPower)372_storage)dyn_storage" }, { - "astId": 421, + "astId": 428, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "lastTotalPower", "offset": 0, @@ -17,23 +17,23 @@ "type": "t_uint256" }, { - "astId": 426, + "astId": 433, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "validators", "offset": 0, "slot": "2", - "type": "t_mapping(t_address,t_struct(Validator)359_storage)" + "type": "t_mapping(t_address,t_struct(Validator)366_storage)" }, { - "astId": 429, + "astId": 436, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "validatorSet", "offset": 0, "slot": "3", - "type": "t_struct(AddressSet)514_storage" + "type": "t_struct(AddressSet)526_storage" }, { - "astId": 433, + "astId": 440, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "validatorsByConsensusPubkey", "offset": 0, @@ -41,7 +41,7 @@ "type": "t_mapping(t_bytes32,t_address)" }, { - "astId": 436, + "astId": 443, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "validatorsByPower", "offset": 0, @@ -49,115 +49,123 @@ "type": "t_array(t_address)dyn_storage" }, { - "astId": 443, + "astId": 450, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "delegations", "offset": 0, "slot": "7", - "type": "t_mapping(t_address,t_mapping(t_address,t_struct(Delegation)368_storage))" + "type": "t_mapping(t_address,t_mapping(t_address,t_struct(Delegation)375_storage))" }, { - "astId": 448, + "astId": 455, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "delegationsByDelegator", "offset": 0, "slot": "8", - "type": "t_mapping(t_address,t_struct(AddressSet)514_storage)" + "type": "t_mapping(t_address,t_struct(AddressSet)526_storage)" }, { - "astId": 456, + "astId": 460, "contract": "giga-storage/StakingStorage.sol:StakingStorage", - "label": "unbondingDelegations", + "label": "delegationsByValidator", "offset": 0, "slot": "9", - "type": "t_mapping(t_address,t_mapping(t_address,t_array(t_struct(UnbondingDelegationEntry)377_storage)dyn_storage))" + "type": "t_mapping(t_address,t_struct(AddressSet)526_storage)" }, { - "astId": 464, + "astId": 468, "contract": "giga-storage/StakingStorage.sol:StakingStorage", - "label": "redelegationEntryCounts", + "label": "unbondingDelegations", "offset": 0, "slot": "10", + "type": "t_mapping(t_address,t_mapping(t_address,t_array(t_struct(UnbondingDelegationEntry)384_storage)dyn_storage))" + }, + { + "astId": 476, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "redelegationEntryCounts", + "offset": 0, + "slot": "11", "type": "t_mapping(t_address,t_mapping(t_address,t_mapping(t_address,t_uint256)))" }, { - "astId": 470, + "astId": 482, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "redelegationsByValDst", "offset": 0, - "slot": "11", + "slot": "12", "type": "t_mapping(t_address,t_mapping(t_address,t_uint256))" }, { - "astId": 473, + "astId": 485, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "unbondingQueueBounds", "offset": 0, - "slot": "12", - "type": "t_struct(QueueBounds)415_storage" + "slot": "13", + "type": "t_struct(QueueBounds)422_storage" }, { - "astId": 478, + "astId": 490, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "unbondingQueue", "offset": 0, - "slot": "13", - "type": "t_mapping(t_uint64,t_struct(UnbondingQueueEntry)385_storage)" + "slot": "14", + "type": "t_mapping(t_uint64,t_struct(UnbondingQueueEntry)392_storage)" }, { - "astId": 481, + "astId": 493, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "redelegationQueueBounds", "offset": 0, - "slot": "14", - "type": "t_struct(QueueBounds)415_storage" + "slot": "15", + "type": "t_struct(QueueBounds)422_storage" }, { - "astId": 486, + "astId": 498, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "redelegationQueue", "offset": 0, - "slot": "15", - "type": "t_mapping(t_uint64,t_struct(RedelegationQueueEntry)401_storage)" + "slot": "16", + "type": "t_mapping(t_uint64,t_struct(RedelegationQueueEntry)408_storage)" }, { - "astId": 489, + "astId": 501, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "validatorQueueBounds", "offset": 0, - "slot": "16", - "type": "t_struct(QueueBounds)415_storage" + "slot": "17", + "type": "t_struct(QueueBounds)422_storage" }, { - "astId": 494, + "astId": 506, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "validatorQueue", "offset": 0, - "slot": "17", - "type": "t_mapping(t_uint64,t_struct(ValidatorQueueEntry)409_storage)" + "slot": "18", + "type": "t_mapping(t_uint64,t_struct(ValidatorQueueEntry)416_storage)" }, { - "astId": 497, + "astId": 509, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "migrating", "offset": 0, - "slot": "18", + "slot": "19", "type": "t_bool" }, { - "astId": 499, + "astId": 511, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "migrationCursor", "offset": 0, - "slot": "19", + "slot": "20", "type": "t_bytes_storage" }, { - "astId": 502, + "astId": 514, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "migrationFailures", "offset": 0, - "slot": "20", + "slot": "21", "type": "t_array(t_bytes_storage)dyn_storage" } ], @@ -179,14 +187,14 @@ "label": "bytes[]", "numberOfBytes": "32" }, - "t_array(t_struct(UnbondingDelegationEntry)377_storage)dyn_storage": { - "base": "t_struct(UnbondingDelegationEntry)377_storage", + "t_array(t_struct(UnbondingDelegationEntry)384_storage)dyn_storage": { + "base": "t_struct(UnbondingDelegationEntry)384_storage", "encoding": "dynamic_array", "label": "struct StakingStorage.UnbondingDelegationEntry[]", "numberOfBytes": "32" }, - "t_array(t_struct(ValidatorPower)365_storage)dyn_storage": { - "base": "t_struct(ValidatorPower)365_storage", + "t_array(t_struct(ValidatorPower)372_storage)dyn_storage": { + "base": "t_struct(ValidatorPower)372_storage", "encoding": "dynamic_array", "label": "struct StakingStorage.ValidatorPower[]", "numberOfBytes": "32" @@ -206,19 +214,19 @@ "label": "bytes", "numberOfBytes": "32" }, - "t_mapping(t_address,t_array(t_struct(UnbondingDelegationEntry)377_storage)dyn_storage)": { + "t_mapping(t_address,t_array(t_struct(UnbondingDelegationEntry)384_storage)dyn_storage)": { "encoding": "mapping", "key": "t_address", "label": "mapping(address => struct StakingStorage.UnbondingDelegationEntry[])", "numberOfBytes": "32", - "value": "t_array(t_struct(UnbondingDelegationEntry)377_storage)dyn_storage" + "value": "t_array(t_struct(UnbondingDelegationEntry)384_storage)dyn_storage" }, - "t_mapping(t_address,t_mapping(t_address,t_array(t_struct(UnbondingDelegationEntry)377_storage)dyn_storage))": { + "t_mapping(t_address,t_mapping(t_address,t_array(t_struct(UnbondingDelegationEntry)384_storage)dyn_storage))": { "encoding": "mapping", "key": "t_address", "label": "mapping(address => mapping(address => struct StakingStorage.UnbondingDelegationEntry[]))", "numberOfBytes": "32", - "value": "t_mapping(t_address,t_array(t_struct(UnbondingDelegationEntry)377_storage)dyn_storage)" + "value": "t_mapping(t_address,t_array(t_struct(UnbondingDelegationEntry)384_storage)dyn_storage)" }, "t_mapping(t_address,t_mapping(t_address,t_mapping(t_address,t_uint256)))": { "encoding": "mapping", @@ -227,12 +235,12 @@ "numberOfBytes": "32", "value": "t_mapping(t_address,t_mapping(t_address,t_uint256))" }, - "t_mapping(t_address,t_mapping(t_address,t_struct(Delegation)368_storage))": { + "t_mapping(t_address,t_mapping(t_address,t_struct(Delegation)375_storage))": { "encoding": "mapping", "key": "t_address", "label": "mapping(address => mapping(address => struct StakingStorage.Delegation))", "numberOfBytes": "32", - "value": "t_mapping(t_address,t_struct(Delegation)368_storage)" + "value": "t_mapping(t_address,t_struct(Delegation)375_storage)" }, "t_mapping(t_address,t_mapping(t_address,t_uint256))": { "encoding": "mapping", @@ -241,26 +249,26 @@ "numberOfBytes": "32", "value": "t_mapping(t_address,t_uint256)" }, - "t_mapping(t_address,t_struct(AddressSet)514_storage)": { + "t_mapping(t_address,t_struct(AddressSet)526_storage)": { "encoding": "mapping", "key": "t_address", "label": "mapping(address => struct AddressSet)", "numberOfBytes": "32", - "value": "t_struct(AddressSet)514_storage" + "value": "t_struct(AddressSet)526_storage" }, - "t_mapping(t_address,t_struct(Delegation)368_storage)": { + "t_mapping(t_address,t_struct(Delegation)375_storage)": { "encoding": "mapping", "key": "t_address", "label": "mapping(address => struct StakingStorage.Delegation)", "numberOfBytes": "32", - "value": "t_struct(Delegation)368_storage" + "value": "t_struct(Delegation)375_storage" }, - "t_mapping(t_address,t_struct(Validator)359_storage)": { + "t_mapping(t_address,t_struct(Validator)366_storage)": { "encoding": "mapping", "key": "t_address", "label": "mapping(address => struct StakingStorage.Validator)", "numberOfBytes": "32", - "value": "t_struct(Validator)359_storage" + "value": "t_struct(Validator)366_storage" }, "t_mapping(t_address,t_uint256)": { "encoding": "mapping", @@ -276,38 +284,38 @@ "numberOfBytes": "32", "value": "t_address" }, - "t_mapping(t_uint64,t_struct(RedelegationQueueEntry)401_storage)": { + "t_mapping(t_uint64,t_struct(RedelegationQueueEntry)408_storage)": { "encoding": "mapping", "key": "t_uint64", "label": "mapping(uint64 => struct StakingStorage.RedelegationQueueEntry)", "numberOfBytes": "32", - "value": "t_struct(RedelegationQueueEntry)401_storage" + "value": "t_struct(RedelegationQueueEntry)408_storage" }, - "t_mapping(t_uint64,t_struct(UnbondingQueueEntry)385_storage)": { + "t_mapping(t_uint64,t_struct(UnbondingQueueEntry)392_storage)": { "encoding": "mapping", "key": "t_uint64", "label": "mapping(uint64 => struct StakingStorage.UnbondingQueueEntry)", "numberOfBytes": "32", - "value": "t_struct(UnbondingQueueEntry)385_storage" + "value": "t_struct(UnbondingQueueEntry)392_storage" }, - "t_mapping(t_uint64,t_struct(ValidatorQueueEntry)409_storage)": { + "t_mapping(t_uint64,t_struct(ValidatorQueueEntry)416_storage)": { "encoding": "mapping", "key": "t_uint64", "label": "mapping(uint64 => struct StakingStorage.ValidatorQueueEntry)", "numberOfBytes": "32", - "value": "t_struct(ValidatorQueueEntry)409_storage" + "value": "t_struct(ValidatorQueueEntry)416_storage" }, "t_string_storage": { "encoding": "bytes", "label": "string", "numberOfBytes": "32" }, - "t_struct(AddressSet)514_storage": { + "t_struct(AddressSet)526_storage": { "encoding": "inplace", "label": "struct AddressSet", "members": [ { - "astId": 509, + "astId": 521, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "values", "offset": 0, @@ -315,7 +323,7 @@ "type": "t_array(t_address)dyn_storage" }, { - "astId": 513, + "astId": 525, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "positions", "offset": 0, @@ -325,20 +333,20 @@ ], "numberOfBytes": "64" }, - "t_struct(Commission)336_storage": { + "t_struct(Commission)343_storage": { "encoding": "inplace", "label": "struct StakingStorage.Commission", "members": [ { - "astId": 333, + "astId": 340, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "commissionRates", "offset": 0, "slot": "0", - "type": "t_struct(CommissionRates)330_storage" + "type": "t_struct(CommissionRates)337_storage" }, { - "astId": 335, + "astId": 342, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "updateTime", "offset": 0, @@ -348,12 +356,12 @@ ], "numberOfBytes": "128" }, - "t_struct(CommissionRates)330_storage": { + "t_struct(CommissionRates)337_storage": { "encoding": "inplace", "label": "struct StakingStorage.CommissionRates", "members": [ { - "astId": 325, + "astId": 332, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "rate", "offset": 0, @@ -361,7 +369,7 @@ "type": "t_uint256" }, { - "astId": 327, + "astId": 334, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "maxRate", "offset": 0, @@ -369,7 +377,7 @@ "type": "t_uint256" }, { - "astId": 329, + "astId": 336, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "maxChangeRate", "offset": 0, @@ -379,12 +387,12 @@ ], "numberOfBytes": "96" }, - "t_struct(Delegation)368_storage": { + "t_struct(Delegation)375_storage": { "encoding": "inplace", "label": "struct StakingStorage.Delegation", "members": [ { - "astId": 367, + "astId": 374, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "shares", "offset": 0, @@ -394,12 +402,12 @@ ], "numberOfBytes": "32" }, - "t_struct(Description)323_storage": { + "t_struct(Description)330_storage": { "encoding": "inplace", "label": "struct StakingStorage.Description", "members": [ { - "astId": 314, + "astId": 321, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "moniker", "offset": 0, @@ -407,7 +415,7 @@ "type": "t_string_storage" }, { - "astId": 316, + "astId": 323, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "identity", "offset": 0, @@ -415,7 +423,7 @@ "type": "t_string_storage" }, { - "astId": 318, + "astId": 325, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "website", "offset": 0, @@ -423,7 +431,7 @@ "type": "t_string_storage" }, { - "astId": 320, + "astId": 327, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "securityContact", "offset": 0, @@ -431,7 +439,7 @@ "type": "t_string_storage" }, { - "astId": 322, + "astId": 329, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "details", "offset": 0, @@ -441,12 +449,12 @@ ], "numberOfBytes": "160" }, - "t_struct(QueueBounds)415_storage": { + "t_struct(QueueBounds)422_storage": { "encoding": "inplace", "label": "struct StakingStorage.QueueBounds", "members": [ { - "astId": 412, + "astId": 419, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "head", "offset": 0, @@ -454,7 +462,7 @@ "type": "t_uint64" }, { - "astId": 414, + "astId": 421, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "tail", "offset": 8, @@ -464,12 +472,12 @@ ], "numberOfBytes": "32" }, - "t_struct(RedelegationQueueEntry)401_storage": { + "t_struct(RedelegationQueueEntry)408_storage": { "encoding": "inplace", "label": "struct StakingStorage.RedelegationQueueEntry", "members": [ { - "astId": 388, + "astId": 395, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "completionTime", "offset": 0, @@ -477,7 +485,7 @@ "type": "t_uint64" }, { - "astId": 390, + "astId": 397, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "delegator", "offset": 8, @@ -485,7 +493,7 @@ "type": "t_address" }, { - "astId": 392, + "astId": 399, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "creationHeight", "offset": 0, @@ -493,7 +501,7 @@ "type": "t_uint64" }, { - "astId": 394, + "astId": 401, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "srcValidator", "offset": 8, @@ -501,7 +509,7 @@ "type": "t_address" }, { - "astId": 396, + "astId": 403, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "dstValidator", "offset": 0, @@ -509,7 +517,7 @@ "type": "t_address" }, { - "astId": 398, + "astId": 405, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "initialBalance", "offset": 0, @@ -517,7 +525,7 @@ "type": "t_uint256" }, { - "astId": 400, + "astId": 407, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "sharesDst", "offset": 0, @@ -527,12 +535,12 @@ ], "numberOfBytes": "160" }, - "t_struct(UnbondingDelegationEntry)377_storage": { + "t_struct(UnbondingDelegationEntry)384_storage": { "encoding": "inplace", "label": "struct StakingStorage.UnbondingDelegationEntry", "members": [ { - "astId": 370, + "astId": 377, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "creationHeight", "offset": 0, @@ -540,7 +548,7 @@ "type": "t_uint64" }, { - "astId": 372, + "astId": 379, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "completionTime", "offset": 8, @@ -548,7 +556,7 @@ "type": "t_uint64" }, { - "astId": 374, + "astId": 381, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "initialBalance", "offset": 0, @@ -556,7 +564,7 @@ "type": "t_uint256" }, { - "astId": 376, + "astId": 383, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "balance", "offset": 0, @@ -566,12 +574,12 @@ ], "numberOfBytes": "96" }, - "t_struct(UnbondingQueueEntry)385_storage": { + "t_struct(UnbondingQueueEntry)392_storage": { "encoding": "inplace", "label": "struct StakingStorage.UnbondingQueueEntry", "members": [ { - "astId": 380, + "astId": 387, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "completionTime", "offset": 0, @@ -579,7 +587,7 @@ "type": "t_uint64" }, { - "astId": 382, + "astId": 389, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "delegator", "offset": 8, @@ -587,7 +595,7 @@ "type": "t_address" }, { - "astId": 384, + "astId": 391, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "validator", "offset": 0, @@ -597,12 +605,12 @@ ], "numberOfBytes": "64" }, - "t_struct(Validator)359_storage": { + "t_struct(Validator)366_storage": { "encoding": "inplace", "label": "struct StakingStorage.Validator", "members": [ { - "astId": 338, + "astId": 345, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "consensusPubkey", "offset": 0, @@ -610,7 +618,7 @@ "type": "t_bytes32" }, { - "astId": 340, + "astId": 347, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "jailed", "offset": 0, @@ -618,7 +626,7 @@ "type": "t_bool" }, { - "astId": 342, + "astId": 349, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "status", "offset": 1, @@ -626,7 +634,7 @@ "type": "t_uint8" }, { - "astId": 344, + "astId": 351, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "tokens", "offset": 0, @@ -634,7 +642,7 @@ "type": "t_uint256" }, { - "astId": 346, + "astId": 353, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "delegatorShares", "offset": 0, @@ -642,15 +650,15 @@ "type": "t_uint256" }, { - "astId": 349, + "astId": 356, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "description", "offset": 0, "slot": "4", - "type": "t_struct(Description)323_storage" + "type": "t_struct(Description)330_storage" }, { - "astId": 351, + "astId": 358, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "unbondingHeight", "offset": 0, @@ -658,7 +666,7 @@ "type": "t_uint64" }, { - "astId": 353, + "astId": 360, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "unbondingTime", "offset": 8, @@ -666,15 +674,15 @@ "type": "t_uint64" }, { - "astId": 356, + "astId": 363, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "commission", "offset": 0, "slot": "10", - "type": "t_struct(Commission)336_storage" + "type": "t_struct(Commission)343_storage" }, { - "astId": 358, + "astId": 365, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "minSelfDelegation", "offset": 0, @@ -684,12 +692,12 @@ ], "numberOfBytes": "480" }, - "t_struct(ValidatorPower)365_storage": { + "t_struct(ValidatorPower)372_storage": { "encoding": "inplace", "label": "struct StakingStorage.ValidatorPower", "members": [ { - "astId": 362, + "astId": 369, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "operator", "offset": 0, @@ -697,7 +705,7 @@ "type": "t_address" }, { - "astId": 364, + "astId": 371, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "power", "offset": 20, @@ -707,12 +715,12 @@ ], "numberOfBytes": "32" }, - "t_struct(ValidatorQueueEntry)409_storage": { + "t_struct(ValidatorQueueEntry)416_storage": { "encoding": "inplace", "label": "struct StakingStorage.ValidatorQueueEntry", "members": [ { - "astId": 404, + "astId": 411, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "completionTime", "offset": 0, @@ -720,7 +728,7 @@ "type": "t_uint64" }, { - "astId": 406, + "astId": 413, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "unbondingHeight", "offset": 8, @@ -728,7 +736,7 @@ "type": "t_uint64" }, { - "astId": 408, + "astId": 415, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "operator", "offset": 0, From 22f564f191888b4449f9fd4d306c34d8eb79bb17 Mon Sep 17 00:00:00 2001 From: Tony Chen Date: Mon, 16 Nov 2026 12:11:05 +0800 Subject: [PATCH 37/44] test(staking): compare each validator's delegators with V2 Co-Authored-By: Claude Opus 5.5 --- .../staking/parity_helpers_test.go | 21 +++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/giga/evmonly/precompiles/staking/parity_helpers_test.go b/giga/evmonly/precompiles/staking/parity_helpers_test.go index 43ab462418..26432ed44a 100644 --- a/giga/evmonly/precompiles/staking/parity_helpers_test.go +++ b/giga/evmonly/precompiles/staking/parity_helpers_test.go @@ -6,6 +6,7 @@ import ( "fmt" "log/slog" "math/big" + "slices" "strings" "testing" "time" @@ -216,8 +217,10 @@ func (c *v2Chain) validator(op common.Address) (stakingtypes.Validator, bool) { // precompile's units. Unbonding and redelegation entries are keyed by the // accounts and validators they name. type stakingState struct { - validators map[common.Address]validatorState - delegations map[delegationKey]string + validators map[common.Address]validatorState + delegations map[delegationKey]string + // delegators lists each validator's delegators, sorted. + delegators map[common.Address][]common.Address unbonding map[delegationKey][]unbondingEntryState redelegations map[redelegationKey][]redelegationEntryState redelegationCounts map[redelegationKey]uint64 @@ -259,6 +262,7 @@ func newStakingState() stakingState { return stakingState{ validators: map[common.Address]validatorState{}, delegations: map[delegationKey]string{}, + delegators: map[common.Address][]common.Address{}, unbonding: map[delegationKey][]unbondingEntryState{}, redelegations: map[redelegationKey][]redelegationEntryState{}, redelegationCounts: map[redelegationKey]uint64{}, @@ -289,7 +293,9 @@ func (c *v2Chain) state(accounts []common.Address) stakingState { for _, d := range c.keeper.GetAllDelegations(c.ctx) { key := delegationKey{common.BytesToAddress(d.GetDelegatorAddr()), common.BytesToAddress(d.GetValidatorAddr())} st.delegations[key] = sharesToWei(d.Shares).String() + st.delegators[key.validator] = append(st.delegators[key.validator], key.delegator) } + sortDelegators(st.delegators) for _, a := range accounts { for _, ubd := range c.keeper.GetAllUnbondingDelegations(c.ctx, sdk.AccAddress(a[:])) { op, err := sdk.ValAddressFromBech32(ubd.ValidatorAddress) @@ -356,7 +362,11 @@ func (h *harness) parityState(validators, accounts []common.Address) stakingStat unbondingHeight: v.unbondingHeight, unbondingTime: v.unbondingTime, } + if delegators := addresses(s.delegators(op)); len(delegators) > 0 { + st.delegators[op] = delegators + } } + sortDelegators(st.delegators) for _, a := range accounts { delegated := s.delegatedValidators(a) for i := uint64(0); i < delegated.Len(); i++ { @@ -688,3 +698,10 @@ func (pr *pair) clampsRedelegation(src common.Address) bool { t := uint64(v.UnbondingTime.UnixNano()) //nolint:gosec // a block time return pr.p.store().redelegationQueue().clamp(t) != t } + +// sortDelegators orders each validator's delegators by address. +func sortDelegators(delegators map[common.Address][]common.Address) { + for _, list := range delegators { + slices.SortFunc(list, common.Address.Cmp) + } +} From 3eecf1428688abe2ff93c550ebbd54ddbefe57a1 Mon Sep 17 00:00:00 2001 From: Tony Chen Date: Mon, 16 Nov 2026 12:23:16 +0800 Subject: [PATCH 38/44] fix(evmonlyapp): serve validators without waiting for the commit in flight Autobahn calls GetValidators before every block, so awaiting the previous block's commit there held execution behind it. Executor.ReadLatest reads the store through the in-flight block's overlay instead, and refuses once a commit is known to have failed. Co-Authored-By: Claude Opus 5.5 --- giga/evmonly/giga_store.go | 47 +++++++++++++ giga/evmonly/pipeline_store_test.go | 70 +++++++++++++++++++ .../internal/evmonlyapp/validators.go | 39 +++++++---- .../internal/evmonlyapp/validators_test.go | 1 + 4 files changed, 142 insertions(+), 15 deletions(-) diff --git a/giga/evmonly/giga_store.go b/giga/evmonly/giga_store.go index bffa20369e..1a4fc76226 100644 --- a/giga/evmonly/giga_store.go +++ b/giga/evmonly/giga_store.go @@ -9,6 +9,7 @@ import ( "github.com/ethereum/go-ethereum/common" + "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles" gigametrics "github.com/sei-protocol/sei-chain/giga/metrics" gigatypes "github.com/sei-protocol/sei-chain/sei-db/state_db/giga/types" ) @@ -168,6 +169,52 @@ func (e *Executor) AwaitCommits() error { return e.awaitPipelineCommit() } +// ReadLatest calls read with read-only state holding every block this executor has run, without +// waiting for the commit in flight. It fails once a commit is known to have failed. +func (e *Executor) ReadLatest(read func(precompiles.State) error) error { + if e.stateStore == nil { + return errMissingStateStore + } + // Held so that no block starts its commit between taking the overlay and opening the view, + // which would pair the view with an overlay older than it. + e.storeMu.Lock() + defer e.storeMu.Unlock() + // Taken before the view, never after, as in executePreparedBlockWithStore. + pending := e.pipelinePending() + snapshot := e.stateStore.OpenView() + if snapshot == nil { + return errors.New("giga store returned a nil snapshot") + } + defer snapshot.Close() + source := pending.overlay(gigaSnapshotStateReader{snapshot: snapshot, missingState: e.missingState}) + if err := read(&precompileState{db: newNativeStateDB(source), readOnly: true}); err != nil { + return err + } + // Checked after the read: a failed commit retired before the overlay was taken leaves the view + // short of that block and nothing to supply it. + return e.commitFailure() +} + +// commitFailure reports a commit known to have failed, without waiting for the one in flight. +func (e *Executor) commitFailure() error { + e.pipelineMu.Lock() + defer e.pipelineMu.Unlock() + if e.pipelineFailure != nil { + return e.pipelineFailure + } + if e.pipelineDone == nil { + return nil + } + select { + case <-e.pipelineDone: + if e.pipelineErr != nil { + return fmt.Errorf("commit state changes: %w", e.pipelineErr) + } + default: + } + return nil +} + // pipelinePending returns the indexed changes of a block whose commit has not been waited on yet, or // nil when the store is caught up. func (e *Executor) pipelinePending() *pendingIndex { diff --git a/giga/evmonly/pipeline_store_test.go b/giga/evmonly/pipeline_store_test.go index 0def74e9cd..cf697cf37e 100644 --- a/giga/evmonly/pipeline_store_test.go +++ b/giga/evmonly/pipeline_store_test.go @@ -3,6 +3,7 @@ package evmonly import ( "errors" "math/big" + "sync" "testing" "time" @@ -10,6 +11,7 @@ import ( "github.com/holiman/uint256" "github.com/stretchr/testify/require" + "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles" gigatypes "github.com/sei-protocol/sei-chain/sei-db/state_db/giga/types" ) @@ -307,3 +309,71 @@ func executePipelinedBlock(t *testing.T, executor *Executor, chainID *big.Int, n require.NoError(t, err) return result } + +// heldCommitStore holds every commit until release is closed. +type heldCommitStore struct { + *recordingGigaStore + release chan struct{} +} + +func (s *heldCommitStore) CommitStateChanges(blockNum int64, changes *gigatypes.StateChangeSet) error { + <-s.release + return s.recordingGigaStore.CommitStateChanges(blockNum, changes) +} + +// ReadLatest serves the state a block produced while that block's commit is still running. +func TestReadLatestServesTheBlockStillCommitting(t *testing.T) { + chainID := big.NewInt(testChainID) + key, err := crypto.GenerateKey() + require.NoError(t, err) + sender := crypto.PubkeyToAddress(key.PublicKey) + recipient := testAddress(0xa9) + + snapshot := newMemoryGigaSnapshot(40) + snapshot.setBalance(sender, big.NewInt(testFundedBalanceWei)) + store := &heldCommitStore{recordingGigaStore: &recordingGigaStore{snapshot: snapshot}, release: make(chan struct{})} + executor := NewExecutor(Config{}, withTestStores(store, NewMemoryReceiptStore())) + defer executor.Close() + var released sync.Once + release := func() { released.Do(func() { close(store.release) }) } + defer release() + + executePipelinedBlock(t, executor, chainID, 41, + signLegacyTx(t, key, chainID, 0, &recipient, big.NewInt(7), nil)) + + var balance *big.Int + require.NoError(t, executor.ReadLatest(func(state precompiles.State) error { + balance = state.GetBalance(recipient) + return nil + })) + require.Equal(t, big.NewInt(7), balance, "block 41's payment is served while its commit is held") + + release() + require.NoError(t, executor.AwaitCommits()) + require.Equal(t, []int64{41}, store.commitBlock) +} + +// ReadLatest refuses once a commit has failed, whether or not anything has waited on it, since the +// store then predates that block. +func TestReadLatestFailsOnceACommitHasFailed(t *testing.T) { + chainID := big.NewInt(testChainID) + key, err := crypto.GenerateKey() + require.NoError(t, err) + sender := crypto.PubkeyToAddress(key.PublicKey) + recipient := testAddress(0xa9) + + snapshot := newMemoryGigaSnapshot(40) + snapshot.setBalance(sender, big.NewInt(testFundedBalanceWei)) + store := &recordingGigaStore{snapshot: snapshot, commitErr: errTestCommitFailed} + executor := NewExecutor(Config{}, withTestStores(store, NewMemoryReceiptStore())) + defer executor.Close() + + executePipelinedBlock(t, executor, chainID, 41, + signLegacyTx(t, key, chainID, 0, &recipient, big.NewInt(7), nil)) + + read := func(precompiles.State) error { return nil } + require.Eventually(t, func() bool { return errors.Is(executor.ReadLatest(read), errTestCommitFailed) }, + 5*time.Second, time.Millisecond, "a failed commit is reported before anything waits on it") + require.ErrorIs(t, executor.AwaitCommits(), errTestCommitFailed) + require.ErrorIs(t, executor.ReadLatest(read), errTestCommitFailed, "and still once it has been waited on") +} diff --git a/sei-tendermint/internal/evmonlyapp/validators.go b/sei-tendermint/internal/evmonlyapp/validators.go index 8de4ed3d4a..52eda7b097 100644 --- a/sei-tendermint/internal/evmonlyapp/validators.go +++ b/sei-tendermint/internal/evmonlyapp/validators.go @@ -5,16 +5,17 @@ import ( "slices" "github.com/sei-protocol/sei-chain/giga/evmonly" + "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles" "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles/staking" "github.com/sei-protocol/sei-chain/sei-tendermint/autobahn/types" "github.com/sei-protocol/sei-chain/sei-tendermint/internal/proxy" "github.com/sei-protocol/sei-chain/sei-tendermint/libs/utils" ) -// GetValidators returns staking's bonded set in the committed state, and the -// configured validators until staking has bonded one. It returns none when a -// finalized block failed to commit or the stored set does not add up, and -// autobahn cannot stage an empty committee. +// GetValidators returns staking's bonded set after the latest finalized block, +// and the configured validators until staking has bonded one. It returns none +// once a block is known to have failed to commit or the stored set does not add +// up, and autobahn cannot stage an empty committee. func (a *evmOnlyApplication) GetValidators() []proxy.ValidatorUpdate { bonded, err := a.bondedValidators() if err != nil { @@ -27,22 +28,30 @@ func (a *evmOnlyApplication) GetValidators() []proxy.ValidatorUpdate { return bonded } -// bondedValidators returns staking's bonded set once every finalized block is -// committed. It fails when one failed to commit. +// bondedValidators returns staking's bonded set after the latest finalized +// block, without waiting for that block's commit. func (a *evmOnlyApplication) bondedValidators() ([]proxy.ValidatorUpdate, error) { - // openSettledView only logs a failed commit, which would serve a set from - // before the failed block, and autobahn persists the committee it stages. - if err := a.AwaitCommits(); err != nil { - return nil, fmt.Errorf("block commit failed: %w", err) + var bonded []staking.BondedValidator + read := func(state precompiles.State) (err error) { + bonded, err = staking.BondedValidators(state) + return err } - view := a.storage.StateDB().OpenView() - defer view.Close() - bonded, err := staking.BondedValidators(evmonly.ReadOnlyState(view)) - if err != nil { - return nil, err + // Autobahn calls this before every block, so it must not hold execution + // behind the previous block's commit. + if executor, ok := a.settler.Load().Get(); ok { + if err := executor.ReadLatest(read); err != nil { + return nil, err + } + } else { + view := a.storage.StateDB().OpenView() + defer view.Close() + if err := read(evmonly.ReadOnlyState(view)); err != nil { + return nil, err + } } updates := make([]proxy.ValidatorUpdate, len(bonded)) for i, v := range bonded { + var err error if updates[i], err = validatorUpdate(v); err != nil { return nil, err } diff --git a/sei-tendermint/internal/evmonlyapp/validators_test.go b/sei-tendermint/internal/evmonlyapp/validators_test.go index 4c8ed03172..76ae5f81ee 100644 --- a/sei-tendermint/internal/evmonlyapp/validators_test.go +++ b/sei-tendermint/internal/evmonlyapp/validators_test.go @@ -122,6 +122,7 @@ func TestEVMOnlyApplicationServesNoValidatorsAfterAFailedCommit(t *testing.T) { raw, _ := signedEVMOnlyTestTx(t, evmOnlyTestChainID, 0) finalizeAndCommitEVMOnlyTestBlock(t, app, evmOnlyTestBlock(1, raw)) + require.Error(t, settler.AwaitCommits()) require.Empty(t, app.GetValidators(), "block 1 failed to commit, so the committed state predates it") } From 2c4672066e46877b3aa7bebe1279dc000b03ce83 Mon Sep 17 00:00:00 2001 From: Tony Chen Date: Mon, 16 Nov 2026 12:48:39 +0800 Subject: [PATCH 39/44] feat(autobahn): tell the app which block closes an epoch The executor sets Header.ClosingEpoch on each epoch's last block, from the epoch package's arithmetic over the genesis initial height, and the EVM-only app carries it to the end blockers' BlockContext. Co-Authored-By: Claude Opus 5.5 --- giga/evmonly/end_block.go | 15 ++++++++------- giga/evmonly/precompiles/context.go | 5 +++++ giga/evmonly/types.go | 3 +++ .../internal/autobahn/epoch/registry.go | 14 ++++++++------ .../internal/autobahn/epoch/registry_test.go | 10 ++++++++++ .../internal/autobahn/execution/execution.go | 3 +++ sei-tendermint/internal/evmonlyapp/app.go | 6 +++++- sei-tendermint/internal/proxy/evm_types.go | 2 ++ 8 files changed, 44 insertions(+), 14 deletions(-) diff --git a/giga/evmonly/end_block.go b/giga/evmonly/end_block.go index 3a3576a751..b7828bfa1a 100644 --- a/giga/evmonly/end_block.go +++ b/giga/evmonly/end_block.go @@ -114,13 +114,14 @@ func truncateUTF8(s string, n int) string { func endBlockContext(block BlockContext, chainID *big.Int) precompiles.BlockContext { return precompiles.BlockContext{ - Number: block.Number, - UnixNano: unixNano(block.Time), - ChainID: cloneOptionalBig(chainID), - BaseFee: cloneOptionalBig(block.BaseFee), - BlobBaseFee: cloneOptionalBig(block.BlobBaseFee), - Coinbase: block.Coinbase, - PrevRandao: block.PrevRandao, + Number: block.Number, + UnixNano: unixNano(block.Time), + ChainID: cloneOptionalBig(chainID), + BaseFee: cloneOptionalBig(block.BaseFee), + BlobBaseFee: cloneOptionalBig(block.BlobBaseFee), + Coinbase: block.Coinbase, + PrevRandao: block.PrevRandao, + ClosingEpoch: block.ClosingEpoch, } } diff --git a/giga/evmonly/precompiles/context.go b/giga/evmonly/precompiles/context.go index 7dc62bef47..b99cd76c76 100644 --- a/giga/evmonly/precompiles/context.go +++ b/giga/evmonly/precompiles/context.go @@ -6,6 +6,8 @@ import ( "github.com/ethereum/go-ethereum/common" ethtypes "github.com/ethereum/go-ethereum/core/types" + + "github.com/sei-protocol/sei-chain/sei-tendermint/libs/utils" ) var ErrCustomPrecompilesOpen = errors.New("evm-only custom precompiles are not implemented") @@ -82,6 +84,9 @@ type BlockContext struct { // Replay is set when the block runs only to rebuild its state, as for a // trace, rather than to execute it. Replay bool + // ClosingEpoch is the consensus epoch this block is the last block of, if + // it is one. + ClosingEpoch utils.Option[uint64] } // State is the precompile-facing state API. Implementations must make these diff --git a/giga/evmonly/types.go b/giga/evmonly/types.go index bc9b14080f..481ce1ea5c 100644 --- a/giga/evmonly/types.go +++ b/giga/evmonly/types.go @@ -87,6 +87,9 @@ type BlockContext struct { ParentHash common.Hash BlockHash common.Hash PrevRandao common.Hash + // ClosingEpoch is the consensus epoch this block is the last block of, if + // it is one. + ClosingEpoch utils.Option[uint64] } // BlockResult is the executor output consumed by the new runtime boundary. diff --git a/sei-tendermint/internal/autobahn/epoch/registry.go b/sei-tendermint/internal/autobahn/epoch/registry.go index e349f43738..a4bdfa449f 100644 --- a/sei-tendermint/internal/autobahn/epoch/registry.go +++ b/sei-tendermint/internal/autobahn/epoch/registry.go @@ -88,14 +88,16 @@ func (r *Registry) IndexForRoad(road types.RoadIndex) types.EpochIndex { // ClosingEpoch returns the epoch that road ends, if road is that epoch's last // road. Otherwise None. func (r *Registry) ClosingEpoch(road types.RoadIndex) utils.Option[types.EpochIndex] { - if road < r.firstRoad { - return utils.None[types.EpochIndex]() - } - idx := r.IndexForRoad(road) - if road != r.LastRoad(idx) { + return ClosingEpoch(r.firstRoad, road) +} + +// ClosingEpoch returns the epoch that road ends, for epochs counted from +// firstRoad, if road is that epoch's last road. Otherwise None. +func ClosingEpoch(firstRoad, road types.RoadIndex) utils.Option[types.EpochIndex] { + if road < firstRoad || (road-firstRoad+1)%epochLength != 0 { return utils.None[types.EpochIndex]() } - return utils.Some(idx) + return utils.Some(types.EpochIndex((road - firstRoad) / epochLength)) } // GenesisTimestamp returns the genesis epoch timestamp. diff --git a/sei-tendermint/internal/autobahn/epoch/registry_test.go b/sei-tendermint/internal/autobahn/epoch/registry_test.go index 3b7b169850..fa88e0e944 100644 --- a/sei-tendermint/internal/autobahn/epoch/registry_test.go +++ b/sei-tendermint/internal/autobahn/epoch/registry_test.go @@ -15,6 +15,16 @@ import ( "github.com/sei-protocol/sei-chain/sei-tendermint/libs/utils/scope" ) +func TestClosingEpochIsTheLastRoadOfEachEpoch(t *testing.T) { + for _, first := range []types.RoadIndex{0, 1, 2*epochLength + 7} { + require.Equal(t, utils.None[types.EpochIndex](), ClosingEpoch(first, first)) + require.Equal(t, utils.Some(types.EpochIndex(0)), ClosingEpoch(first, first+epochLength-1)) + require.Equal(t, utils.None[types.EpochIndex](), ClosingEpoch(first, first+epochLength)) + require.Equal(t, utils.Some(types.EpochIndex(2)), ClosingEpoch(first, first+3*epochLength-1)) + } + require.Equal(t, utils.None[types.EpochIndex](), ClosingEpoch(epochLength, epochLength-1), "a road before the first") +} + func TestRegistryGenesisAndLookups(t *testing.T) { for _, first := range []types.RoadIndex{0, 2*epochLength + 7} { t.Run(fmt.Sprint(first), func(t *testing.T) { diff --git a/sei-tendermint/internal/autobahn/execution/execution.go b/sei-tendermint/internal/autobahn/execution/execution.go index 1175a2e7de..8489a028d8 100644 --- a/sei-tendermint/internal/autobahn/execution/execution.go +++ b/sei-tendermint/internal/autobahn/execution/execution.go @@ -11,6 +11,7 @@ import ( gigametrics "github.com/sei-protocol/sei-chain/giga/metrics" "github.com/sei-protocol/sei-chain/sei-tendermint/autobahn/blockstore" atypes "github.com/sei-protocol/sei-chain/sei-tendermint/autobahn/types" + "github.com/sei-protocol/sei-chain/sei-tendermint/internal/autobahn/epoch" "github.com/sei-protocol/sei-chain/sei-tendermint/internal/autobahn/execution/metrics" "github.com/sei-protocol/sei-chain/sei-tendermint/internal/proxy" "github.com/sei-protocol/sei-chain/sei-tendermint/libs/utils" @@ -154,6 +155,8 @@ func (e *Executor) executeBlock(ctx context.Context, b *atypes.SuperBlock) error // WARNING: the reward distribution has corner cases where it forgets the proposer, // because reward is distributed with a delay. This is not our problem here though. ProposerAddress: proposerAddress, + // Epochs count from the genesis initial height, as the epoch registry's do. + ClosingEpoch: epoch.ClosingEpoch(atypes.RoadIndex(e.cfg.GenDoc.InitialHeight), b.Height), // nolint:gosec // verified to be positive. }, }) if err != nil { diff --git a/sei-tendermint/internal/evmonlyapp/app.go b/sei-tendermint/internal/evmonlyapp/app.go index ed22379656..2166beeb38 100644 --- a/sei-tendermint/internal/evmonlyapp/app.go +++ b/sei-tendermint/internal/evmonlyapp/app.go @@ -969,8 +969,12 @@ func (a *evmOnlyApplication) finalizeBlock(ctx context.Context, req *proxy.Reque defer a.finalizePhases.Reset() a.finalizePhases.SetPhase(finalizePhaseTakeSenders) senders := a.takeSenders(req.Txs) + block := a.blockContext(number, timestamp, parent.gasLimit, parent.blockHash, blockHash) + if epoch, ok := req.Header.ClosingEpoch.Get(); ok { + block.ClosingEpoch = utils.Some(uint64(epoch)) + } result, err := a.executeBlockPipelined(ctx, executor, evmonly.BlockRequest{ - Context: a.blockContext(number, timestamp, parent.gasLimit, parent.blockHash, blockHash), + Context: block, Txs: req.Txs, Senders: senders, }) diff --git a/sei-tendermint/internal/proxy/evm_types.go b/sei-tendermint/internal/proxy/evm_types.go index a88054a7ab..fff04f6374 100644 --- a/sei-tendermint/internal/proxy/evm_types.go +++ b/sei-tendermint/internal/proxy/evm_types.go @@ -47,6 +47,8 @@ type Header struct { Height int64 Time time.Time ProposerAddress []byte + // ClosingEpoch is the epoch this block is the last block of, if it is one. + ClosingEpoch utils.Option[types.EpochIndex] } // RequestCheckTxV2 is a transaction submitted for admission. From 6285f3532197317aff95074eceb601637e54387b Mon Sep 17 00:00:00 2001 From: Tony Chen Date: Mon, 16 Nov 2026 12:48:39 +0800 Subject: [PATCH 40/44] feat(staking): snapshot the bonded set when an epoch closes EndBlock copies lastValidators into epochValidators on an epoch's last block and keeps the latest three, and GetValidators serves the latest snapshot, so every node hands consensus the same set for an epoch's committee. Co-Authored-By: Claude Opus 5.5 --- docs/giga-storage/StakingStorage.sol | 5 + docs/giga-storage/staking-design-rationale.md | 23 +- .../evmonly/precompiles/staking/bonded_set.go | 18 +- .../precompiles/staking/bonded_set_test.go | 41 ++- giga/evmonly/precompiles/staking/endblock.go | 37 ++- .../precompiles/staking/helpers_test.go | 14 +- giga/evmonly/precompiles/staking/layout.go | 34 +- .../precompiles/staking/layout_test.go | 12 +- giga/evmonly/precompiles/staking/storage.go | 40 ++- .../StakingStorageHarness.bin-runtime | 2 +- .../testdata/StakingStorageHarness.sol | 2 + .../testdata/staking_storage_layout.json | 291 ++++++++++-------- .../internal/evmonlyapp/validators.go | 21 +- .../internal/evmonlyapp/validators_test.go | 33 +- .../internal/p2p/giga_router_common.go | 11 +- 15 files changed, 374 insertions(+), 210 deletions(-) diff --git a/docs/giga-storage/StakingStorage.sol b/docs/giga-storage/StakingStorage.sol index dda9dc012e..edcbd47b66 100644 --- a/docs/giga-storage/StakingStorage.sol +++ b/docs/giga-storage/StakingStorage.sol @@ -97,6 +97,11 @@ contract StakingStorage { ValidatorPower[] internal lastValidators; // 0x11: the bonded set, as last sent to consensus uint256 internal lastTotalPower; // 0x12 + /// @dev lastValidators at the end of each epoch's last block. Consensus + /// derives an epoch's committee from the set two epochs before it, so the + /// latest three are kept. + mapping(uint64 => ValidatorPower[]) internal epochValidators; // epoch => + uint64 internal nextSnapshotEpoch; // the epoch after the latest in epochValidators, 0 before any mapping(address => Validator) internal validators; // 0x21: operator => AddressSet internal validatorSet; // every operator in validators diff --git a/docs/giga-storage/staking-design-rationale.md b/docs/giga-storage/staking-design-rationale.md index 9a470371d4..76e5410fa8 100644 --- a/docs/giga-storage/staking-design-rationale.md +++ b/docs/giga-storage/staking-design-rationale.md @@ -203,6 +203,7 @@ Staking: |---|---|---| | `0x11` | last validator power | `lastValidators` (array, one slot per bonded validator) | | `0x12` | last total power | `lastTotalPower` | +| none | the bonded set at each epoch end | `epochValidators` (see *The epoch snapshot*) | | `0x21` | validators | `validators` (+ set) | | `0x22` | validator by consensus address | `validatorsByConsensusPubkey`, keyed by the key itself | | `0x23` | validators by power | `validatorsByPower` (sorted array) | @@ -289,6 +290,25 @@ that cost is small. every node, follow tx reverts and snapshots, and be rebuilt after state sync. - **Ordered flatkv keys**, V2's approach exactly. See *Prefix walks*. +### The epoch snapshot + +V2 hands CometBFT a new validator set every block. Autobahn changes its +committee once per epoch, and derives epoch E+2's committee from the set it +reads at the end of epoch E's last block. The node reads the set outside block +execution, at whatever height the app has reached by then, so the set it gets +could differ from node to node. + +So at the end of an epoch's last block, EndBlock copies `lastValidators` into +`epochValidators[epoch]`, and the app serves consensus the latest snapshot. The +snapshot is committed state, so every node serves the same one for an epoch, +and a node that state-syncs gets it too. Consensus marks the block that closes +an epoch, so the app never repeats the epoch length. + +The snapshot is also what rewards read: the committee that served a block in +epoch E is the snapshot of epoch E−2. Three are kept, E−2 to E, and EndBlock +deletes the one before them when it takes a new one: about 100 slot writes once +an epoch. + ### Where the structures don't carry over Each of these is a place where slot storage, or a deliberate simplification, @@ -501,7 +521,8 @@ of a million state writes per epoch. - The fee pot is for the rewards design to define. Giga's coinbase and base fee are zero today. - Minting belongs to the rewards design. pacific-1's release schedule is empty. -- Power and the bonded set are read from staking, not copied. +- Power and the bonded set are read from staking, not copied: the committee + that served a block from staking's epoch snapshot. - `communityTax` and the proposer reward params stay in distribution's params (all zero on pacific-1). diff --git a/giga/evmonly/precompiles/staking/bonded_set.go b/giga/evmonly/precompiles/staking/bonded_set.go index c0c90e4bca..bea3be0b68 100644 --- a/giga/evmonly/precompiles/staking/bonded_set.go +++ b/giga/evmonly/precompiles/staking/bonded_set.go @@ -15,17 +15,21 @@ type BondedValidator struct { Power uint64 } -// BondedValidators returns the bonded set the last EndBlock stored, in the -// order it ranked them, or none before staking has bonded a set. It fails when -// the stored set does not add up. -func BondedValidators(state precompiles.State) ([]BondedValidator, error) { +// EpochValidators returns the bonded set snapshotted at the end of the latest +// epoch, in the order it ranked them, or none before the first snapshot. It +// fails when the stored set does not add up. +func EpochValidators(state precompiles.State) ([]BondedValidator, error) { s := newStore(state) - last, err := s.lastValidators() + epoch, ok := s.latestSnapshotEpoch() + if !ok { + return nil, nil + } + set, err := s.epochValidators(epoch) if err != nil { return nil, err } - bonded := make([]BondedValidator, len(last)) - for i, v := range last { + bonded := make([]BondedValidator, len(set)) + for i, v := range set { pubkey := s.consensusPubkey(v.operator) if pubkey == (common.Hash{}) { return nil, fmt.Errorf("%w: %s", errUnknownValidator, v.operator) diff --git a/giga/evmonly/precompiles/staking/bonded_set_test.go b/giga/evmonly/precompiles/staking/bonded_set_test.go index 218e93ce46..c81da92e75 100644 --- a/giga/evmonly/precompiles/staking/bonded_set_test.go +++ b/giga/evmonly/precompiles/staking/bonded_set_test.go @@ -9,37 +9,56 @@ import ( "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles/solstorage" ) -func TestBondedValidatorsAreTheSetTheLastEndBlockStored(t *testing.T) { +func TestEpochValidatorsAreTheSetAtTheLatestEpochEnd(t *testing.T) { h := newHarness(t, testParams) + require.Empty(t, must(EpochValidators(h.state)), "no epoch has ended") + + h.endEpoch(0) want := []BondedValidator{ {Operator: val1, ConsensusPubkey: common.BytesToHash(val1[:]), Power: 30}, {Operator: val2, ConsensusPubkey: common.BytesToHash(val2[:]), Power: 20}, } - require.Equal(t, want, must(BondedValidators(h.state))) + require.Equal(t, want, must(EpochValidators(h.state))) require.NoError(t, h.delegate(alice, val3, sei(15))) - require.Equal(t, want, must(BondedValidators(h.state)), "a delegation moves the set only at EndBlock") h.endBlock() + require.Equal(t, want, must(EpochValidators(h.state)), "the bonded set moves within an epoch, its snapshot only at the epoch's end") + h.endEpoch(1) require.Equal(t, []BondedValidator{ {Operator: val1, ConsensusPubkey: common.BytesToHash(val1[:]), Power: 30}, {Operator: val3, ConsensusPubkey: common.BytesToHash(val3[:]), Power: 25}, - }, must(BondedValidators(h.state))) + }, must(EpochValidators(h.state))) +} + +func TestEpochSnapshotsKeepTheLatestThree(t *testing.T) { + h := newHarness(t, testParams) + for epoch := range uint64(5) { + h.endEpoch(epoch) + } + s := h.store() + for epoch, kept := range []bool{false, false, true, true, true} { + require.Equal(t, kept, len(must(s.epochValidators(uint64(epoch)))) > 0, "epoch %d", epoch) + } + latest, ok := s.latestSnapshotEpoch() + require.True(t, ok) + require.Equal(t, uint64(4), latest) } -func TestNoValidatorsAreBondedBeforeStakingBondsASet(t *testing.T) { +func TestNoEpochValidatorsBeforeStakingStarts(t *testing.T) { state := newMemState() - require.Empty(t, must(BondedValidators(state))) + require.Empty(t, must(EpochValidators(state))) require.NoError(t, SetParams(state, testParams)) - require.Empty(t, must(BondedValidators(state))) + require.Empty(t, must(EpochValidators(state))) } -func TestBondedValidatorsFailOnAStoredSetThatDoesNotAddUp(t *testing.T) { +func TestEpochValidatorsFailOnAStoredSetThatDoesNotAddUp(t *testing.T) { h := newHarness(t, testParams) h.store().setLastValidators([]validatorPower{{val1, 30}, {alice, 20}}) - _, err := BondedValidators(h.state) + h.endEpoch(0) + _, err := EpochValidators(h.state) require.ErrorIs(t, err, errUnknownValidator, "a member with no validator") - h.store().SetUint64(solstorage.Slot(slotLastValidators), 0, 101) - _, err = BondedValidators(h.state) + h.store().SetUint64(solstorage.MapUint64(solstorage.Slot(slotEpochValidators), 0), 0, 101) + _, err = EpochValidators(h.state) require.ErrorIs(t, err, errInvalidStoredSet, "a set longer than any MaxValidators allows") } diff --git a/giga/evmonly/precompiles/staking/endblock.go b/giga/evmonly/precompiles/staking/endblock.go index 7ccd29417c..6f80e0e294 100644 --- a/giga/evmonly/precompiles/staking/endblock.go +++ b/giga/evmonly/precompiles/staking/endblock.go @@ -33,12 +33,13 @@ var ( // undelegations. const endBlockBudget = 3_000 -// EndBlock updates the bonded set, then completes the validators, unbonding -// entries and redelegation entries whose unbonding period is over, in that -// order, as x/staking's BlockValidatorUpdates does. Before staking's params are -// written it does nothing. Its failures are a bonded set that could not be -// updated, which is kept as it was, and queue entries whose stored data does -// not add up, which are dropped. It returns no error. +// EndBlock updates the bonded set, snapshots it when the block closes an epoch, +// then completes the validators, unbonding entries and redelegation entries +// whose unbonding period is over, in that order, as x/staking's +// BlockValidatorUpdates does. Before staking's params are written it does +// nothing. Its failures are a bonded set that could not be updated, which is +// kept as it was, a snapshot that could not be taken, and queue entries whose +// stored data does not add up, which are dropped. It returns no error. func (p Precompile) EndBlock(block precompiles.BlockContext, state precompiles.State) ([]error, error) { if !chainparams.HasStaking(state) { return nil, nil @@ -49,6 +50,11 @@ func (p Precompile) EndBlock(block precompiles.BlockContext, state precompiles.S if err := p.updateBondedSet(block, s, params); err != nil { failures = append(failures, fmt.Errorf("%w: bonded set kept as it was: %w", precompiles.ErrDegraded, err)) } + if epoch, ok := block.ClosingEpoch.Get(); ok { + if err := snapshotEpoch(s, epoch); err != nil { + failures = append(failures, fmt.Errorf("%w: epoch %d's bonded set not snapshotted: %w", precompiles.ErrDegraded, epoch, err)) + } + } drain(block, s.validatorQueue(), "validator", &failures, func(common.Hash) uint64 { return 1 }, func(e common.Hash) error { return p.completeValidatorUnbonding(block, s, e) }) @@ -156,6 +162,25 @@ func (p Precompile) applyBondedSet(block precompiles.BlockContext, s store, para return nil } +// epochSnapshotsKept is how many epoch snapshots are kept, as an epoch's +// committee is derived from the snapshot two epochs before it. +const epochSnapshotsKept = 3 + +// snapshotEpoch copies the bonded set into epoch's snapshot and deletes the one +// that no longer falls among the latest epochSnapshotsKept. +func snapshotEpoch(s store, epoch uint64) error { + last, err := s.lastValidators() + if err != nil { + return err + } + s.setEpochValidators(epoch, last) + if epoch >= epochSnapshotsKept { + s.setEpochValidators(epoch-epochSnapshotsKept, nil) + } + s.setLatestSnapshotEpoch(epoch) + return nil +} + // drain completes each entry due in q, in queue order, under a budget of its // own, until none is due or the next does not fit what is left. Each entry is // removed from q once completed. A completion that fails is reverted and its diff --git a/giga/evmonly/precompiles/staking/helpers_test.go b/giga/evmonly/precompiles/staking/helpers_test.go index bbfdc1411c..c612658b77 100644 --- a/giga/evmonly/precompiles/staking/helpers_test.go +++ b/giga/evmonly/precompiles/staking/helpers_test.go @@ -18,6 +18,7 @@ import ( "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles/dec" chainparams "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles/params" "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles/solstorage" + "github.com/sei-protocol/sei-chain/sei-tendermint/libs/utils" ) // memState is a map-backed precompiles.State and LogSink. @@ -171,7 +172,18 @@ func (h *harness) block() precompiles.BlockContext { // endBlock runs EndBlock at the current block, then starts the next block one // second later. func (h *harness) endBlock() { - failures, err := h.staking.EndBlock(h.block(), h.state) + h.endBlockWith(h.block()) +} + +// endEpoch ends the current block as the last block of epoch. +func (h *harness) endEpoch(epoch uint64) { + block := h.block() + block.ClosingEpoch = utils.Some(epoch) + h.endBlockWith(block) +} + +func (h *harness) endBlockWith(block precompiles.BlockContext) { + failures, err := h.staking.EndBlock(block, h.state) require.NoError(h.t, err) h.failures = failures h.number++ diff --git a/giga/evmonly/precompiles/staking/layout.go b/giga/evmonly/precompiles/staking/layout.go index a8a99d168b..0c3973b48c 100644 --- a/giga/evmonly/precompiles/staking/layout.go +++ b/giga/evmonly/precompiles/staking/layout.go @@ -12,22 +12,24 @@ var Address = common.HexToAddress("0x0000000000000000000000000000000000001005") const ( slotLastValidators = 0 slotLastTotalPower = 1 - slotValidators = 2 - slotValidatorSet = 3 - slotValidatorsByConsensusPubkey = 5 - slotValidatorsByPower = 6 - slotDelegations = 7 - slotDelegationsByDelegator = 8 - slotDelegationsByValidator = 9 - slotUnbondingDelegations = 10 - slotRedelegationEntryCounts = 11 - slotRedelegationsByValDst = 12 - slotUnbondingQueueBounds = 13 - slotUnbondingQueue = 14 - slotRedelegationQueueBounds = 15 - slotRedelegationQueue = 16 - slotValidatorQueueBounds = 17 - slotValidatorQueue = 18 + slotEpochValidators = 2 + slotNextSnapshotEpoch = 3 + slotValidators = 4 + slotValidatorSet = 5 + slotValidatorsByConsensusPubkey = 7 + slotValidatorsByPower = 8 + slotDelegations = 9 + slotDelegationsByDelegator = 10 + slotDelegationsByValidator = 11 + slotUnbondingDelegations = 12 + slotRedelegationEntryCounts = 13 + slotRedelegationsByValDst = 14 + slotUnbondingQueueBounds = 15 + slotUnbondingQueue = 16 + slotRedelegationQueueBounds = 17 + slotRedelegationQueue = 18 + slotValidatorQueueBounds = 19 + slotValidatorQueue = 20 ) // member is a struct member's position relative to the struct's base slot. diff --git a/giga/evmonly/precompiles/staking/layout_test.go b/giga/evmonly/precompiles/staking/layout_test.go index adf4ffeb3a..89e3a9dff9 100644 --- a/giga/evmonly/precompiles/staking/layout_test.go +++ b/giga/evmonly/precompiles/staking/layout_test.go @@ -52,6 +52,8 @@ func TestLayoutMatchesSolc(t *testing.T) { require.Equal(t, map[string]uint64{ "lastValidators": slotLastValidators, "lastTotalPower": slotLastTotalPower, + "epochValidators": slotEpochValidators, + "nextSnapshotEpoch": slotNextSnapshotEpoch, "validators": slotValidators, "validatorSet": slotValidatorSet, "validatorsByConsensusPubkey": slotValidatorsByConsensusPubkey, @@ -68,9 +70,9 @@ func TestLayoutMatchesSolc(t *testing.T) { "redelegationQueue": slotRedelegationQueue, "validatorQueueBounds": slotValidatorQueueBounds, "validatorQueue": slotValidatorQueue, - "migrating": 19, - "migrationCursor": 20, - "migrationFailures": 21, + "migrating": 21, + "migrationCursor": 22, + "migrationFailures": 23, }, got) // Each struct's Go members, and how many slots it takes. Description and @@ -198,6 +200,10 @@ func TestStoreReadsCompilerWrites(t *testing.T) { require.NoError(t, err) require.Equal(t, []validatorPower{{op, 30}, {other, 20}}, set) require.Equal(t, big.NewInt(50), s.lastTotalPower()) + require.Equal(t, []validatorPower{{other, 21}}, must(s.epochValidators(7))) + latest, ok := s.latestSnapshotEpoch() + require.True(t, ok) + require.Equal(t, uint64(7), latest) v, ok := s.validator(op) require.True(t, ok) diff --git a/giga/evmonly/precompiles/staking/storage.go b/giga/evmonly/precompiles/staking/storage.go index 2b7f176cf2..ba46b8aa7b 100644 --- a/giga/evmonly/precompiles/staking/storage.go +++ b/giga/evmonly/precompiles/staking/storage.go @@ -178,7 +178,38 @@ type validatorPower struct { // lastValidators returns the bonded set as last stored, failing on a set longer // than any MaxValidators allows. func (s store) lastValidators() ([]validatorPower, error) { - base := solstorage.Slot(slotLastValidators) + return s.validatorPowers(solstorage.Slot(slotLastValidators)) +} + +// setLastValidators replaces the bonded set. +func (s store) setLastValidators(set []validatorPower) { + s.setValidatorPowers(solstorage.Slot(slotLastValidators), set) +} + +// epochValidators returns the bonded set snapshotted at the end of epoch, or +// none when that epoch has no snapshot. +func (s store) epochValidators(epoch uint64) ([]validatorPower, error) { + return s.validatorPowers(solstorage.MapUint64(solstorage.Slot(slotEpochValidators), epoch)) +} + +func (s store) setEpochValidators(epoch uint64, set []validatorPower) { + s.setValidatorPowers(solstorage.MapUint64(solstorage.Slot(slotEpochValidators), epoch), set) +} + +// latestSnapshotEpoch returns the latest epoch with a snapshot, and false +// before any. +func (s store) latestSnapshotEpoch() (uint64, bool) { + next := s.Uint64(solstorage.Slot(slotNextSnapshotEpoch), 0) + return next - 1, next > 0 +} + +func (s store) setLatestSnapshotEpoch(epoch uint64) { + s.SetUint64(solstorage.Slot(slotNextSnapshotEpoch), 0, epoch+1) +} + +// validatorPowers returns the ValidatorPower[] at base, failing on one longer +// than any MaxValidators allows. +func (s store) validatorPowers(base common.Hash) ([]validatorPower, error) { n := s.Uint64(base, 0) if n > uint64(chainparams.MaxBondedValidators) { return nil, fmt.Errorf("%w: %d validators", errInvalidStoredSet, n) @@ -195,10 +226,9 @@ func (s store) lastValidators() ([]validatorPower, error) { return out, nil } -// setLastValidators replaces the bonded set, zeroing elements the new set no -// longer covers. -func (s store) setLastValidators(set []validatorPower) { - base := solstorage.Slot(slotLastValidators) +// setValidatorPowers replaces the ValidatorPower[] at base, zeroing elements +// the new one no longer covers. +func (s store) setValidatorPowers(base common.Hash, set []validatorPower) { old := min(s.Uint64(base, 0), uint64(chainparams.MaxBondedValidators)) data := solstorage.ArrayData(base) for i, v := range set { diff --git a/giga/evmonly/precompiles/staking/testdata/StakingStorageHarness.bin-runtime b/giga/evmonly/precompiles/staking/testdata/StakingStorageHarness.bin-runtime index 6747b79150..10bc635e43 100644 --- a/giga/evmonly/precompiles/staking/testdata/StakingStorageHarness.bin-runtime +++ b/giga/evmonly/precompiles/staking/testdata/StakingStorageHarness.bin-runtime @@ -1 +1 @@ -608060405234801561000f575f5ffd5b5060043610610029575f3560e01c80633afaaf0e1461002d575b5f5ffd5b610047600480360381019061004291906110fa565b610049565b005b5f60405180604001604052808673ffffffffffffffffffffffffffffffffffffffff168152602001601e67ffffffffffffffff16815250908060018154018082558091505060019003905f5260205f20015f909190919091505f820151815f015f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506020820151815f0160146101000a81548167ffffffffffffffff021916908367ffffffffffffffff16021790555050505f60405180604001604052808573ffffffffffffffffffffffffffffffffffffffff168152602001601467ffffffffffffffff16815250908060018154018082558091505060019003905f5260205f20015f909190919091505f820151815f015f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506020820151815f0160146101000a81548167ffffffffffffffff021916908367ffffffffffffffff160217905550505060326001819055505f60025f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20905081815f01819055506001816001015f6101000a81548160ff02191690831515021790555060028160010160016101000a81548160ff021916908360ff1602179055506801ae361fc1451c000081600201819055506f1812f9cf7920e2b66973e20000000000816003018190555060405180606001604052806034815260200161146b60349139816004015f0190816102c3919061139b565b506040518060400160405280600181526020017f640000000000000000000000000000000000000000000000000000000000000081525081600401600401908161030d919061139b565b506021816009015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff16021790555060228160090160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff160217905550602381600a015f015f0181905550602481600a016003015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff160217905550602581600e0181905550600360025f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f2060010160016101000a81548160ff021916908360ff160217905550610410600386610fba565b61041b600385610fba565b8460055f8481526020019081526020015f205f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550600684908060018154018082558091505060019003905f5260205f20015f9091909190916101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550600685908060018154018082558091505060019003905f5260205f20015f9091909190916101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550602960075f8573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f01819055506105f060085f8573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f2086610fba565b61063660095f8773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f2084610fba565b600a5f8473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f206040518060800160405280603367ffffffffffffffff168152602001603467ffffffffffffffff168152602001603581526020016036815250908060018154018082558091505060019003905f5260205f2090600302015f909190919091505f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff16021790555060408201518160010155606082015181600201555050600a5f8473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f206040518060800160405280603767ffffffffffffffff168152602001603867ffffffffffffffff16815260200160398152602001603a815250908060018154018082558091505060019003905f5260205f2090600302015f909190919091505f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff160217905550604082015181600101556060820151816002015550506002600b5f8573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20819055506003600c5f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20819055506040518060400160405280600167ffffffffffffffff168152602001600267ffffffffffffffff16815250600d5f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055509050506040518060600160405280603d67ffffffffffffffff1681526020018473ffffffffffffffffffffffffffffffffffffffff1681526020018673ffffffffffffffffffffffffffffffffffffffff16815250600e5f600167ffffffffffffffff1681526020019081526020015f205f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506040820151816001015f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555090505060405180604001604052805f67ffffffffffffffff168152602001600167ffffffffffffffff16815250600f5f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055509050506040518060e00160405280604767ffffffffffffffff1681526020018473ffffffffffffffffffffffffffffffffffffffff168152602001604867ffffffffffffffff1681526020018673ffffffffffffffffffffffffffffffffffffffff1681526020018573ffffffffffffffffffffffffffffffffffffffff16815260200160498152602001604a81525060105f5f67ffffffffffffffff1681526020019081526020015f205f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506040820151816001015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff16021790555060608201518160010160086101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506080820151816002015f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555060a0820151816003015560c082015181600401559050506040518060400160405280600467ffffffffffffffff168152602001600567ffffffffffffffff1681525060115f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055509050506040518060600160405280605167ffffffffffffffff168152602001605267ffffffffffffffff1681526020018573ffffffffffffffffffffffffffffffffffffffff1681525060125f600467ffffffffffffffff1681526020019081526020015f205f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506040820151816001015f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055509050505050505050565b815f0181908060018154018082558091505060019003905f5260205f20015f9091909190916101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550815f0180549050826001015f8373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20819055505050565b5f5ffd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6110968261106d565b9050919050565b6110a68161108c565b81146110b0575f5ffd5b50565b5f813590506110c18161109d565b92915050565b5f819050919050565b6110d9816110c7565b81146110e3575f5ffd5b50565b5f813590506110f4816110d0565b92915050565b5f5f5f5f6080858703121561111257611111611069565b5b5f61111f878288016110b3565b9450506020611130878288016110b3565b9350506040611141878288016110b3565b9250506060611152878288016110e6565b91505092959194509250565b5f81519050919050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52604160045260245ffd5b7f4e487b71000000000000000000000000000000000000000000000000000000005f52602260045260245ffd5b5f60028204905060018216806111d957607f821691505b6020821081036111ec576111eb611195565b5b50919050565b5f819050815f5260205f209050919050565b5f6020601f8301049050919050565b5f82821b905092915050565b5f6008830261124e7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff82611213565b6112588683611213565b95508019841693508086168417925050509392505050565b5f819050919050565b5f819050919050565b5f61129c61129761129284611270565b611279565b611270565b9050919050565b5f819050919050565b6112b583611282565b6112c96112c1826112a3565b84845461121f565b825550505050565b5f5f905090565b6112e06112d1565b6112eb8184846112ac565b505050565b5b8181101561130e576113035f826112d8565b6001810190506112f1565b5050565b601f82111561135357611324816111f2565b61132d84611204565b8101602085101561133c578190505b61135061134885611204565b8301826112f0565b50505b505050565b5f82821c905092915050565b5f6113735f1984600802611358565b1980831691505092915050565b5f61138b8383611364565b9150826002028217905092915050565b6113a48261115e565b67ffffffffffffffff8111156113bd576113bc611168565b5b6113c782546111c2565b6113d2828285611312565b5f60209050601f831160018114611403575f84156113f1578287015190505b6113fb8582611380565b865550611462565b601f198416611411866111f2565b5f5b8281101561143857848901518255600182019150602085019450602081019050611413565b868310156114555784890151611451601f891682611364565b8355505b6001600288020188555050505b50505050505056fe61206d6f6e696b6572206c6f6e6720656e6f75676820746f207370696c6c2070617374206f6e652073746f7261676520776f7264a2646970667358221220ca5344d3b5f6f14544837d3f326231a5017eb67a3e45fd84e5063d42ade3370764736f6c634300081e0033 +608060405234801561000f575f5ffd5b5060043610610029575f3560e01c80633afaaf0e1461002d575b5f5ffd5b6100476004803603810190610042919061120b565b610049565b005b5f60405180604001604052808673ffffffffffffffffffffffffffffffffffffffff168152602001601e67ffffffffffffffff16815250908060018154018082558091505060019003905f5260205f20015f909190919091505f820151815f015f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506020820151815f0160146101000a81548167ffffffffffffffff021916908367ffffffffffffffff16021790555050505f60405180604001604052808573ffffffffffffffffffffffffffffffffffffffff168152602001601467ffffffffffffffff16815250908060018154018082558091505060019003905f5260205f20015f909190919091505f820151815f015f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506020820151815f0160146101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055505050603260018190555060025f600767ffffffffffffffff1681526020019081526020015f2060405180604001604052808573ffffffffffffffffffffffffffffffffffffffff168152602001601567ffffffffffffffff16815250908060018154018082558091505060019003905f5260205f20015f909190919091505f820151815f015f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506020820151815f0160146101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055505050600860035f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055505f60045f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20905081815f01819055506001816001015f6101000a81548160ff02191690831515021790555060028160010160016101000a81548160ff021916908360ff1602179055506801ae361fc1451c000081600201819055506f1812f9cf7920e2b66973e20000000000816003018190555060405180606001604052806034815260200161157c60349139816004015f0190816103d491906114ac565b506040518060400160405280600181526020017f640000000000000000000000000000000000000000000000000000000000000081525081600401600401908161041e91906114ac565b506021816009015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff16021790555060228160090160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff160217905550602381600a015f015f0181905550602481600a016003015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff160217905550602581600e0181905550600360045f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f2060010160016101000a81548160ff021916908360ff1602179055506105216005866110cb565b61052c6005856110cb565b8460075f8481526020019081526020015f205f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550600884908060018154018082558091505060019003905f5260205f20015f9091909190916101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550600885908060018154018082558091505060019003905f5260205f20015f9091909190916101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550602960095f8573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f0181905550610701600a5f8573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20866110cb565b610747600b5f8773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20846110cb565b600c5f8473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f206040518060800160405280603367ffffffffffffffff168152602001603467ffffffffffffffff168152602001603581526020016036815250908060018154018082558091505060019003905f5260205f2090600302015f909190919091505f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff16021790555060408201518160010155606082015181600201555050600c5f8473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f206040518060800160405280603767ffffffffffffffff168152602001603867ffffffffffffffff16815260200160398152602001603a815250908060018154018082558091505060019003905f5260205f2090600302015f909190919091505f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff160217905550604082015181600101556060820151816002015550506002600d5f8573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20819055506003600e5f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20819055506040518060400160405280600167ffffffffffffffff168152602001600267ffffffffffffffff16815250600f5f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055509050506040518060600160405280603d67ffffffffffffffff1681526020018473ffffffffffffffffffffffffffffffffffffffff1681526020018673ffffffffffffffffffffffffffffffffffffffff1681525060105f600167ffffffffffffffff1681526020019081526020015f205f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506040820151816001015f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555090505060405180604001604052805f67ffffffffffffffff168152602001600167ffffffffffffffff1681525060115f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055509050506040518060e00160405280604767ffffffffffffffff1681526020018473ffffffffffffffffffffffffffffffffffffffff168152602001604867ffffffffffffffff1681526020018673ffffffffffffffffffffffffffffffffffffffff1681526020018573ffffffffffffffffffffffffffffffffffffffff16815260200160498152602001604a81525060125f5f67ffffffffffffffff1681526020019081526020015f205f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506040820151816001015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff16021790555060608201518160010160086101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506080820151816002015f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555060a0820151816003015560c082015181600401559050506040518060400160405280600467ffffffffffffffff168152602001600567ffffffffffffffff1681525060135f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055509050506040518060600160405280605167ffffffffffffffff168152602001605267ffffffffffffffff1681526020018573ffffffffffffffffffffffffffffffffffffffff1681525060145f600467ffffffffffffffff1681526020019081526020015f205f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506040820151816001015f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055509050505050505050565b815f0181908060018154018082558091505060019003905f5260205f20015f9091909190916101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550815f0180549050826001015f8373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20819055505050565b5f5ffd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6111a78261117e565b9050919050565b6111b78161119d565b81146111c1575f5ffd5b50565b5f813590506111d2816111ae565b92915050565b5f819050919050565b6111ea816111d8565b81146111f4575f5ffd5b50565b5f81359050611205816111e1565b92915050565b5f5f5f5f608085870312156112235761122261117a565b5b5f611230878288016111c4565b9450506020611241878288016111c4565b9350506040611252878288016111c4565b9250506060611263878288016111f7565b91505092959194509250565b5f81519050919050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52604160045260245ffd5b7f4e487b71000000000000000000000000000000000000000000000000000000005f52602260045260245ffd5b5f60028204905060018216806112ea57607f821691505b6020821081036112fd576112fc6112a6565b5b50919050565b5f819050815f5260205f209050919050565b5f6020601f8301049050919050565b5f82821b905092915050565b5f6008830261135f7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff82611324565b6113698683611324565b95508019841693508086168417925050509392505050565b5f819050919050565b5f819050919050565b5f6113ad6113a86113a384611381565b61138a565b611381565b9050919050565b5f819050919050565b6113c683611393565b6113da6113d2826113b4565b848454611330565b825550505050565b5f5f905090565b6113f16113e2565b6113fc8184846113bd565b505050565b5b8181101561141f576114145f826113e9565b600181019050611402565b5050565b601f8211156114645761143581611303565b61143e84611315565b8101602085101561144d578190505b61146161145985611315565b830182611401565b50505b505050565b5f82821c905092915050565b5f6114845f1984600802611469565b1980831691505092915050565b5f61149c8383611475565b9150826002028217905092915050565b6114b58261126f565b67ffffffffffffffff8111156114ce576114cd611279565b5b6114d882546112d3565b6114e3828285611423565b5f60209050601f831160018114611514575f8415611502578287015190505b61150c8582611491565b865550611573565b601f19841661152286611303565b5f5b8281101561154957848901518255600182019150602085019450602081019050611524565b868310156115665784890151611562601f891682611475565b8355505b6001600288020188555050505b50505050505056fe61206d6f6e696b6572206c6f6e6720656e6f75676820746f207370696c6c2070617374206f6e652073746f7261676520776f7264a2646970667358221220dc3b466112c8b58d9f8dabe6750c7a816eb8343b23ff50a598771f216d089b6764736f6c634300081e0033 diff --git a/giga/evmonly/precompiles/staking/testdata/StakingStorageHarness.sol b/giga/evmonly/precompiles/staking/testdata/StakingStorageHarness.sol index 16178f9852..ca418d5740 100644 --- a/giga/evmonly/precompiles/staking/testdata/StakingStorageHarness.sol +++ b/giga/evmonly/precompiles/staking/testdata/StakingStorageHarness.sol @@ -10,6 +10,8 @@ contract StakingStorageHarness is StakingStorage { lastValidators.push(ValidatorPower({operator: op, power: 30})); lastValidators.push(ValidatorPower({operator: other, power: 20})); lastTotalPower = 50; + epochValidators[7].push(ValidatorPower({operator: other, power: 21})); + nextSnapshotEpoch = 8; Validator storage v = validators[op]; v.consensusPubkey = pubkey; diff --git a/giga/evmonly/precompiles/staking/testdata/staking_storage_layout.json b/giga/evmonly/precompiles/staking/testdata/staking_storage_layout.json index 8615ae68fe..1d7ae6c423 100644 --- a/giga/evmonly/precompiles/staking/testdata/staking_storage_layout.json +++ b/giga/evmonly/precompiles/staking/testdata/staking_storage_layout.json @@ -1,15 +1,15 @@ { "storage": [ { - "astId": 426, + "astId": 440, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "lastValidators", "offset": 0, "slot": "0", - "type": "t_array(t_struct(ValidatorPower)372_storage)dyn_storage" + "type": "t_array(t_struct(ValidatorPower)386_storage)dyn_storage" }, { - "astId": 428, + "astId": 442, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "lastTotalPower", "offset": 0, @@ -17,155 +17,171 @@ "type": "t_uint256" }, { - "astId": 433, + "astId": 449, "contract": "giga-storage/StakingStorage.sol:StakingStorage", - "label": "validators", + "label": "epochValidators", "offset": 0, "slot": "2", - "type": "t_mapping(t_address,t_struct(Validator)366_storage)" + "type": "t_mapping(t_uint64,t_array(t_struct(ValidatorPower)386_storage)dyn_storage)" }, { - "astId": 436, + "astId": 451, "contract": "giga-storage/StakingStorage.sol:StakingStorage", - "label": "validatorSet", + "label": "nextSnapshotEpoch", "offset": 0, "slot": "3", - "type": "t_struct(AddressSet)526_storage" + "type": "t_uint64" }, { - "astId": 440, + "astId": 456, "contract": "giga-storage/StakingStorage.sol:StakingStorage", - "label": "validatorsByConsensusPubkey", + "label": "validators", + "offset": 0, + "slot": "4", + "type": "t_mapping(t_address,t_struct(Validator)380_storage)" + }, + { + "astId": 459, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "validatorSet", "offset": 0, "slot": "5", + "type": "t_struct(AddressSet)549_storage" + }, + { + "astId": 463, + "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "label": "validatorsByConsensusPubkey", + "offset": 0, + "slot": "7", "type": "t_mapping(t_bytes32,t_address)" }, { - "astId": 443, + "astId": 466, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "validatorsByPower", "offset": 0, - "slot": "6", + "slot": "8", "type": "t_array(t_address)dyn_storage" }, { - "astId": 450, + "astId": 473, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "delegations", "offset": 0, - "slot": "7", - "type": "t_mapping(t_address,t_mapping(t_address,t_struct(Delegation)375_storage))" + "slot": "9", + "type": "t_mapping(t_address,t_mapping(t_address,t_struct(Delegation)389_storage))" }, { - "astId": 455, + "astId": 478, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "delegationsByDelegator", "offset": 0, - "slot": "8", - "type": "t_mapping(t_address,t_struct(AddressSet)526_storage)" + "slot": "10", + "type": "t_mapping(t_address,t_struct(AddressSet)549_storage)" }, { - "astId": 460, + "astId": 483, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "delegationsByValidator", "offset": 0, - "slot": "9", - "type": "t_mapping(t_address,t_struct(AddressSet)526_storage)" + "slot": "11", + "type": "t_mapping(t_address,t_struct(AddressSet)549_storage)" }, { - "astId": 468, + "astId": 491, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "unbondingDelegations", "offset": 0, - "slot": "10", - "type": "t_mapping(t_address,t_mapping(t_address,t_array(t_struct(UnbondingDelegationEntry)384_storage)dyn_storage))" + "slot": "12", + "type": "t_mapping(t_address,t_mapping(t_address,t_array(t_struct(UnbondingDelegationEntry)398_storage)dyn_storage))" }, { - "astId": 476, + "astId": 499, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "redelegationEntryCounts", "offset": 0, - "slot": "11", + "slot": "13", "type": "t_mapping(t_address,t_mapping(t_address,t_mapping(t_address,t_uint256)))" }, { - "astId": 482, + "astId": 505, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "redelegationsByValDst", "offset": 0, - "slot": "12", + "slot": "14", "type": "t_mapping(t_address,t_mapping(t_address,t_uint256))" }, { - "astId": 485, + "astId": 508, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "unbondingQueueBounds", "offset": 0, - "slot": "13", - "type": "t_struct(QueueBounds)422_storage" + "slot": "15", + "type": "t_struct(QueueBounds)436_storage" }, { - "astId": 490, + "astId": 513, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "unbondingQueue", "offset": 0, - "slot": "14", - "type": "t_mapping(t_uint64,t_struct(UnbondingQueueEntry)392_storage)" + "slot": "16", + "type": "t_mapping(t_uint64,t_struct(UnbondingQueueEntry)406_storage)" }, { - "astId": 493, + "astId": 516, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "redelegationQueueBounds", "offset": 0, - "slot": "15", - "type": "t_struct(QueueBounds)422_storage" + "slot": "17", + "type": "t_struct(QueueBounds)436_storage" }, { - "astId": 498, + "astId": 521, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "redelegationQueue", "offset": 0, - "slot": "16", - "type": "t_mapping(t_uint64,t_struct(RedelegationQueueEntry)408_storage)" + "slot": "18", + "type": "t_mapping(t_uint64,t_struct(RedelegationQueueEntry)422_storage)" }, { - "astId": 501, + "astId": 524, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "validatorQueueBounds", "offset": 0, - "slot": "17", - "type": "t_struct(QueueBounds)422_storage" + "slot": "19", + "type": "t_struct(QueueBounds)436_storage" }, { - "astId": 506, + "astId": 529, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "validatorQueue", "offset": 0, - "slot": "18", - "type": "t_mapping(t_uint64,t_struct(ValidatorQueueEntry)416_storage)" + "slot": "20", + "type": "t_mapping(t_uint64,t_struct(ValidatorQueueEntry)430_storage)" }, { - "astId": 509, + "astId": 532, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "migrating", "offset": 0, - "slot": "19", + "slot": "21", "type": "t_bool" }, { - "astId": 511, + "astId": 534, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "migrationCursor", "offset": 0, - "slot": "20", + "slot": "22", "type": "t_bytes_storage" }, { - "astId": 514, + "astId": 537, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "migrationFailures", "offset": 0, - "slot": "21", + "slot": "23", "type": "t_array(t_bytes_storage)dyn_storage" } ], @@ -187,14 +203,14 @@ "label": "bytes[]", "numberOfBytes": "32" }, - "t_array(t_struct(UnbondingDelegationEntry)384_storage)dyn_storage": { - "base": "t_struct(UnbondingDelegationEntry)384_storage", + "t_array(t_struct(UnbondingDelegationEntry)398_storage)dyn_storage": { + "base": "t_struct(UnbondingDelegationEntry)398_storage", "encoding": "dynamic_array", "label": "struct StakingStorage.UnbondingDelegationEntry[]", "numberOfBytes": "32" }, - "t_array(t_struct(ValidatorPower)372_storage)dyn_storage": { - "base": "t_struct(ValidatorPower)372_storage", + "t_array(t_struct(ValidatorPower)386_storage)dyn_storage": { + "base": "t_struct(ValidatorPower)386_storage", "encoding": "dynamic_array", "label": "struct StakingStorage.ValidatorPower[]", "numberOfBytes": "32" @@ -214,19 +230,19 @@ "label": "bytes", "numberOfBytes": "32" }, - "t_mapping(t_address,t_array(t_struct(UnbondingDelegationEntry)384_storage)dyn_storage)": { + "t_mapping(t_address,t_array(t_struct(UnbondingDelegationEntry)398_storage)dyn_storage)": { "encoding": "mapping", "key": "t_address", "label": "mapping(address => struct StakingStorage.UnbondingDelegationEntry[])", "numberOfBytes": "32", - "value": "t_array(t_struct(UnbondingDelegationEntry)384_storage)dyn_storage" + "value": "t_array(t_struct(UnbondingDelegationEntry)398_storage)dyn_storage" }, - "t_mapping(t_address,t_mapping(t_address,t_array(t_struct(UnbondingDelegationEntry)384_storage)dyn_storage))": { + "t_mapping(t_address,t_mapping(t_address,t_array(t_struct(UnbondingDelegationEntry)398_storage)dyn_storage))": { "encoding": "mapping", "key": "t_address", "label": "mapping(address => mapping(address => struct StakingStorage.UnbondingDelegationEntry[]))", "numberOfBytes": "32", - "value": "t_mapping(t_address,t_array(t_struct(UnbondingDelegationEntry)384_storage)dyn_storage)" + "value": "t_mapping(t_address,t_array(t_struct(UnbondingDelegationEntry)398_storage)dyn_storage)" }, "t_mapping(t_address,t_mapping(t_address,t_mapping(t_address,t_uint256)))": { "encoding": "mapping", @@ -235,12 +251,12 @@ "numberOfBytes": "32", "value": "t_mapping(t_address,t_mapping(t_address,t_uint256))" }, - "t_mapping(t_address,t_mapping(t_address,t_struct(Delegation)375_storage))": { + "t_mapping(t_address,t_mapping(t_address,t_struct(Delegation)389_storage))": { "encoding": "mapping", "key": "t_address", "label": "mapping(address => mapping(address => struct StakingStorage.Delegation))", "numberOfBytes": "32", - "value": "t_mapping(t_address,t_struct(Delegation)375_storage)" + "value": "t_mapping(t_address,t_struct(Delegation)389_storage)" }, "t_mapping(t_address,t_mapping(t_address,t_uint256))": { "encoding": "mapping", @@ -249,26 +265,26 @@ "numberOfBytes": "32", "value": "t_mapping(t_address,t_uint256)" }, - "t_mapping(t_address,t_struct(AddressSet)526_storage)": { + "t_mapping(t_address,t_struct(AddressSet)549_storage)": { "encoding": "mapping", "key": "t_address", "label": "mapping(address => struct AddressSet)", "numberOfBytes": "32", - "value": "t_struct(AddressSet)526_storage" + "value": "t_struct(AddressSet)549_storage" }, - "t_mapping(t_address,t_struct(Delegation)375_storage)": { + "t_mapping(t_address,t_struct(Delegation)389_storage)": { "encoding": "mapping", "key": "t_address", "label": "mapping(address => struct StakingStorage.Delegation)", "numberOfBytes": "32", - "value": "t_struct(Delegation)375_storage" + "value": "t_struct(Delegation)389_storage" }, - "t_mapping(t_address,t_struct(Validator)366_storage)": { + "t_mapping(t_address,t_struct(Validator)380_storage)": { "encoding": "mapping", "key": "t_address", "label": "mapping(address => struct StakingStorage.Validator)", "numberOfBytes": "32", - "value": "t_struct(Validator)366_storage" + "value": "t_struct(Validator)380_storage" }, "t_mapping(t_address,t_uint256)": { "encoding": "mapping", @@ -284,38 +300,45 @@ "numberOfBytes": "32", "value": "t_address" }, - "t_mapping(t_uint64,t_struct(RedelegationQueueEntry)408_storage)": { + "t_mapping(t_uint64,t_array(t_struct(ValidatorPower)386_storage)dyn_storage)": { + "encoding": "mapping", + "key": "t_uint64", + "label": "mapping(uint64 => struct StakingStorage.ValidatorPower[])", + "numberOfBytes": "32", + "value": "t_array(t_struct(ValidatorPower)386_storage)dyn_storage" + }, + "t_mapping(t_uint64,t_struct(RedelegationQueueEntry)422_storage)": { "encoding": "mapping", "key": "t_uint64", "label": "mapping(uint64 => struct StakingStorage.RedelegationQueueEntry)", "numberOfBytes": "32", - "value": "t_struct(RedelegationQueueEntry)408_storage" + "value": "t_struct(RedelegationQueueEntry)422_storage" }, - "t_mapping(t_uint64,t_struct(UnbondingQueueEntry)392_storage)": { + "t_mapping(t_uint64,t_struct(UnbondingQueueEntry)406_storage)": { "encoding": "mapping", "key": "t_uint64", "label": "mapping(uint64 => struct StakingStorage.UnbondingQueueEntry)", "numberOfBytes": "32", - "value": "t_struct(UnbondingQueueEntry)392_storage" + "value": "t_struct(UnbondingQueueEntry)406_storage" }, - "t_mapping(t_uint64,t_struct(ValidatorQueueEntry)416_storage)": { + "t_mapping(t_uint64,t_struct(ValidatorQueueEntry)430_storage)": { "encoding": "mapping", "key": "t_uint64", "label": "mapping(uint64 => struct StakingStorage.ValidatorQueueEntry)", "numberOfBytes": "32", - "value": "t_struct(ValidatorQueueEntry)416_storage" + "value": "t_struct(ValidatorQueueEntry)430_storage" }, "t_string_storage": { "encoding": "bytes", "label": "string", "numberOfBytes": "32" }, - "t_struct(AddressSet)526_storage": { + "t_struct(AddressSet)549_storage": { "encoding": "inplace", "label": "struct AddressSet", "members": [ { - "astId": 521, + "astId": 544, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "values", "offset": 0, @@ -323,7 +346,7 @@ "type": "t_array(t_address)dyn_storage" }, { - "astId": 525, + "astId": 548, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "positions", "offset": 0, @@ -333,20 +356,20 @@ ], "numberOfBytes": "64" }, - "t_struct(Commission)343_storage": { + "t_struct(Commission)357_storage": { "encoding": "inplace", "label": "struct StakingStorage.Commission", "members": [ { - "astId": 340, + "astId": 354, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "commissionRates", "offset": 0, "slot": "0", - "type": "t_struct(CommissionRates)337_storage" + "type": "t_struct(CommissionRates)351_storage" }, { - "astId": 342, + "astId": 356, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "updateTime", "offset": 0, @@ -356,12 +379,12 @@ ], "numberOfBytes": "128" }, - "t_struct(CommissionRates)337_storage": { + "t_struct(CommissionRates)351_storage": { "encoding": "inplace", "label": "struct StakingStorage.CommissionRates", "members": [ { - "astId": 332, + "astId": 346, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "rate", "offset": 0, @@ -369,7 +392,7 @@ "type": "t_uint256" }, { - "astId": 334, + "astId": 348, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "maxRate", "offset": 0, @@ -377,7 +400,7 @@ "type": "t_uint256" }, { - "astId": 336, + "astId": 350, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "maxChangeRate", "offset": 0, @@ -387,12 +410,12 @@ ], "numberOfBytes": "96" }, - "t_struct(Delegation)375_storage": { + "t_struct(Delegation)389_storage": { "encoding": "inplace", "label": "struct StakingStorage.Delegation", "members": [ { - "astId": 374, + "astId": 388, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "shares", "offset": 0, @@ -402,12 +425,12 @@ ], "numberOfBytes": "32" }, - "t_struct(Description)330_storage": { + "t_struct(Description)344_storage": { "encoding": "inplace", "label": "struct StakingStorage.Description", "members": [ { - "astId": 321, + "astId": 335, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "moniker", "offset": 0, @@ -415,7 +438,7 @@ "type": "t_string_storage" }, { - "astId": 323, + "astId": 337, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "identity", "offset": 0, @@ -423,7 +446,7 @@ "type": "t_string_storage" }, { - "astId": 325, + "astId": 339, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "website", "offset": 0, @@ -431,7 +454,7 @@ "type": "t_string_storage" }, { - "astId": 327, + "astId": 341, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "securityContact", "offset": 0, @@ -439,7 +462,7 @@ "type": "t_string_storage" }, { - "astId": 329, + "astId": 343, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "details", "offset": 0, @@ -449,12 +472,12 @@ ], "numberOfBytes": "160" }, - "t_struct(QueueBounds)422_storage": { + "t_struct(QueueBounds)436_storage": { "encoding": "inplace", "label": "struct StakingStorage.QueueBounds", "members": [ { - "astId": 419, + "astId": 433, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "head", "offset": 0, @@ -462,7 +485,7 @@ "type": "t_uint64" }, { - "astId": 421, + "astId": 435, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "tail", "offset": 8, @@ -472,12 +495,12 @@ ], "numberOfBytes": "32" }, - "t_struct(RedelegationQueueEntry)408_storage": { + "t_struct(RedelegationQueueEntry)422_storage": { "encoding": "inplace", "label": "struct StakingStorage.RedelegationQueueEntry", "members": [ { - "astId": 395, + "astId": 409, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "completionTime", "offset": 0, @@ -485,7 +508,7 @@ "type": "t_uint64" }, { - "astId": 397, + "astId": 411, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "delegator", "offset": 8, @@ -493,7 +516,7 @@ "type": "t_address" }, { - "astId": 399, + "astId": 413, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "creationHeight", "offset": 0, @@ -501,7 +524,7 @@ "type": "t_uint64" }, { - "astId": 401, + "astId": 415, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "srcValidator", "offset": 8, @@ -509,7 +532,7 @@ "type": "t_address" }, { - "astId": 403, + "astId": 417, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "dstValidator", "offset": 0, @@ -517,7 +540,7 @@ "type": "t_address" }, { - "astId": 405, + "astId": 419, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "initialBalance", "offset": 0, @@ -525,7 +548,7 @@ "type": "t_uint256" }, { - "astId": 407, + "astId": 421, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "sharesDst", "offset": 0, @@ -535,12 +558,12 @@ ], "numberOfBytes": "160" }, - "t_struct(UnbondingDelegationEntry)384_storage": { + "t_struct(UnbondingDelegationEntry)398_storage": { "encoding": "inplace", "label": "struct StakingStorage.UnbondingDelegationEntry", "members": [ { - "astId": 377, + "astId": 391, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "creationHeight", "offset": 0, @@ -548,7 +571,7 @@ "type": "t_uint64" }, { - "astId": 379, + "astId": 393, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "completionTime", "offset": 8, @@ -556,7 +579,7 @@ "type": "t_uint64" }, { - "astId": 381, + "astId": 395, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "initialBalance", "offset": 0, @@ -564,7 +587,7 @@ "type": "t_uint256" }, { - "astId": 383, + "astId": 397, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "balance", "offset": 0, @@ -574,12 +597,12 @@ ], "numberOfBytes": "96" }, - "t_struct(UnbondingQueueEntry)392_storage": { + "t_struct(UnbondingQueueEntry)406_storage": { "encoding": "inplace", "label": "struct StakingStorage.UnbondingQueueEntry", "members": [ { - "astId": 387, + "astId": 401, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "completionTime", "offset": 0, @@ -587,7 +610,7 @@ "type": "t_uint64" }, { - "astId": 389, + "astId": 403, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "delegator", "offset": 8, @@ -595,7 +618,7 @@ "type": "t_address" }, { - "astId": 391, + "astId": 405, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "validator", "offset": 0, @@ -605,12 +628,12 @@ ], "numberOfBytes": "64" }, - "t_struct(Validator)366_storage": { + "t_struct(Validator)380_storage": { "encoding": "inplace", "label": "struct StakingStorage.Validator", "members": [ { - "astId": 345, + "astId": 359, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "consensusPubkey", "offset": 0, @@ -618,7 +641,7 @@ "type": "t_bytes32" }, { - "astId": 347, + "astId": 361, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "jailed", "offset": 0, @@ -626,7 +649,7 @@ "type": "t_bool" }, { - "astId": 349, + "astId": 363, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "status", "offset": 1, @@ -634,7 +657,7 @@ "type": "t_uint8" }, { - "astId": 351, + "astId": 365, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "tokens", "offset": 0, @@ -642,7 +665,7 @@ "type": "t_uint256" }, { - "astId": 353, + "astId": 367, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "delegatorShares", "offset": 0, @@ -650,15 +673,15 @@ "type": "t_uint256" }, { - "astId": 356, + "astId": 370, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "description", "offset": 0, "slot": "4", - "type": "t_struct(Description)330_storage" + "type": "t_struct(Description)344_storage" }, { - "astId": 358, + "astId": 372, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "unbondingHeight", "offset": 0, @@ -666,7 +689,7 @@ "type": "t_uint64" }, { - "astId": 360, + "astId": 374, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "unbondingTime", "offset": 8, @@ -674,15 +697,15 @@ "type": "t_uint64" }, { - "astId": 363, + "astId": 377, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "commission", "offset": 0, "slot": "10", - "type": "t_struct(Commission)343_storage" + "type": "t_struct(Commission)357_storage" }, { - "astId": 365, + "astId": 379, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "minSelfDelegation", "offset": 0, @@ -692,12 +715,12 @@ ], "numberOfBytes": "480" }, - "t_struct(ValidatorPower)372_storage": { + "t_struct(ValidatorPower)386_storage": { "encoding": "inplace", "label": "struct StakingStorage.ValidatorPower", "members": [ { - "astId": 369, + "astId": 383, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "operator", "offset": 0, @@ -705,7 +728,7 @@ "type": "t_address" }, { - "astId": 371, + "astId": 385, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "power", "offset": 20, @@ -715,12 +738,12 @@ ], "numberOfBytes": "32" }, - "t_struct(ValidatorQueueEntry)416_storage": { + "t_struct(ValidatorQueueEntry)430_storage": { "encoding": "inplace", "label": "struct StakingStorage.ValidatorQueueEntry", "members": [ { - "astId": 411, + "astId": 425, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "completionTime", "offset": 0, @@ -728,7 +751,7 @@ "type": "t_uint64" }, { - "astId": 413, + "astId": 427, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "unbondingHeight", "offset": 8, @@ -736,7 +759,7 @@ "type": "t_uint64" }, { - "astId": 415, + "astId": 429, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "operator", "offset": 0, diff --git a/sei-tendermint/internal/evmonlyapp/validators.go b/sei-tendermint/internal/evmonlyapp/validators.go index 52eda7b097..e231c25327 100644 --- a/sei-tendermint/internal/evmonlyapp/validators.go +++ b/sei-tendermint/internal/evmonlyapp/validators.go @@ -12,14 +12,14 @@ import ( "github.com/sei-protocol/sei-chain/sei-tendermint/libs/utils" ) -// GetValidators returns staking's bonded set after the latest finalized block, -// and the configured validators until staking has bonded one. It returns none -// once a block is known to have failed to commit or the stored set does not add -// up, and autobahn cannot stage an empty committee. +// GetValidators returns the bonded set staking snapshotted at the end of the +// latest epoch, and the configured validators until it has snapshotted one. It +// returns none once a block is known to have failed to commit or the stored set +// does not add up, and autobahn cannot stage an empty committee. func (a *evmOnlyApplication) GetValidators() []proxy.ValidatorUpdate { - bonded, err := a.bondedValidators() + bonded, err := a.epochValidators() if err != nil { - logger.Error("EVM-only bonded validator set is unavailable", "err", err) + logger.Error("EVM-only epoch validator set is unavailable", "err", err) return nil } if len(bonded) == 0 { @@ -28,12 +28,13 @@ func (a *evmOnlyApplication) GetValidators() []proxy.ValidatorUpdate { return bonded } -// bondedValidators returns staking's bonded set after the latest finalized -// block, without waiting for that block's commit. -func (a *evmOnlyApplication) bondedValidators() ([]proxy.ValidatorUpdate, error) { +// epochValidators returns the bonded set staking snapshotted at the end of the +// latest epoch, after the latest finalized block, without waiting for that +// block's commit. +func (a *evmOnlyApplication) epochValidators() ([]proxy.ValidatorUpdate, error) { var bonded []staking.BondedValidator read := func(state precompiles.State) (err error) { - bonded, err = staking.BondedValidators(state) + bonded, err = staking.EpochValidators(state) return err } // Autobahn calls this before every block, so it must not hold execution diff --git a/sei-tendermint/internal/evmonlyapp/validators_test.go b/sei-tendermint/internal/evmonlyapp/validators_test.go index 76ae5f81ee..e6f0d08529 100644 --- a/sei-tendermint/internal/evmonlyapp/validators_test.go +++ b/sei-tendermint/internal/evmonlyapp/validators_test.go @@ -8,6 +8,7 @@ import ( gigaconfig "github.com/sei-protocol/sei-chain/giga/config" "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles" + "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles/solstorage" "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles/staking" seidbconfig "github.com/sei-protocol/sei-chain/sei-db/config" "github.com/sei-protocol/sei-chain/sei-tendermint/autobahn/types" @@ -38,18 +39,27 @@ func (g stakingGenesis) EndBlock(block precompiles.BlockContext, state precompil return g.Precompile.EndBlock(block, state) } -// corruptBondedSet stores a bonded set longer than staking allows at every -// EndBlock. -type corruptBondedSet struct { +// corruptEpochSnapshot stores an epoch snapshot longer than staking allows at +// every EndBlock. +type corruptEpochSnapshot struct { staking.Precompile } -func (corruptBondedSet) EndBlock(_ precompiles.BlockContext, state precompiles.State) ([]error, error) { - // Slot 0 of StakingStorage holds the bonded set's length. - state.SetState(staking.Address, common.Hash{}, common.BigToHash(big.NewInt(101))) +func (corruptEpochSnapshot) EndBlock(_ precompiles.BlockContext, state precompiles.State) ([]error, error) { + // Slot 2 of StakingStorage maps each epoch to its snapshot, and slot 3 holds + // the epoch after the latest. + state.SetState(staking.Address, solstorage.MapUint64(solstorage.Slot(2), 0), common.BigToHash(big.NewInt(101))) + state.SetState(staking.Address, solstorage.Slot(3), common.BigToHash(big.NewInt(1))) return nil, nil } +// evmOnlyTestClosingBlock returns an empty block at height that closes epoch. +func evmOnlyTestClosingBlock(height int64, epoch types.EpochIndex) *proxy.RequestFinalizeBlock { + req := evmOnlyTestBlock(height) + req.Header.ClosingEpoch = utils.Some(epoch) + return req +} + // newStakingEVMOnlyTestApp returns an initialized application serving the // configured validators and running staking as contract. func newStakingEVMOnlyTestApp(t *testing.T, configured []proxy.ValidatorUpdate, contract precompiles.Contract) proxy.EVMApplication { @@ -88,7 +98,7 @@ func testGenesisValidator(operator common.Address, key ed25519.PublicKey, self i } } -func TestEVMOnlyApplicationServesStakingsBondedSet(t *testing.T) { +func TestEVMOnlyApplicationServesStakingsSetAtEachEpochEnd(t *testing.T) { configured := []proxy.ValidatorUpdate{{PubKey: autobahnKey(ed25519.TestSecretKey([]byte("configured")).Public()), Power: 1}} key1 := ed25519.TestSecretKey([]byte("validator-1")).Public() key2 := ed25519.TestSecretKey([]byte("validator-2")).Public() @@ -96,9 +106,12 @@ func TestEVMOnlyApplicationServesStakingsBondedSet(t *testing.T) { testGenesisValidator(common.HexToAddress("0xa2"), key2, 20), testGenesisValidator(common.HexToAddress("0xa1"), key1, 30), }}) - require.Equal(t, configured, app.GetValidators(), "the configured validators serve until staking bonds a set") + require.Equal(t, configured, app.GetValidators(), "the configured validators serve until staking snapshots a set") finalizeAndCommitEVMOnlyTestBlock(t, app, evmOnlyTestBlock(1)) + require.Equal(t, configured, app.GetValidators(), "staking bonded a set, but no epoch has ended") + + finalizeAndCommitEVMOnlyTestBlock(t, app, evmOnlyTestClosingBlock(2, 0)) require.Equal(t, []proxy.ValidatorUpdate{ {PubKey: autobahnKey(key1), Power: 30}, {PubKey: autobahnKey(key2), Power: 20}, @@ -126,8 +139,8 @@ func TestEVMOnlyApplicationServesNoValidatorsAfterAFailedCommit(t *testing.T) { require.Empty(t, app.GetValidators(), "block 1 failed to commit, so the committed state predates it") } -func TestEVMOnlyApplicationServesNoValidatorsFromACorruptBondedSet(t *testing.T) { - app := newStakingEVMOnlyTestApp(t, []proxy.ValidatorUpdate{{Power: 1}}, corruptBondedSet{}) +func TestEVMOnlyApplicationServesNoValidatorsFromACorruptEpochSnapshot(t *testing.T) { + app := newStakingEVMOnlyTestApp(t, []proxy.ValidatorUpdate{{Power: 1}}, corruptEpochSnapshot{}) finalizeAndCommitEVMOnlyTestBlock(t, app, evmOnlyTestBlock(1)) require.Empty(t, app.GetValidators()) } diff --git a/sei-tendermint/internal/p2p/giga_router_common.go b/sei-tendermint/internal/p2p/giga_router_common.go index f2350566a1..ed4d29ff57 100644 --- a/sei-tendermint/internal/p2p/giga_router_common.go +++ b/sei-tendermint/internal/p2p/giga_router_common.go @@ -192,11 +192,12 @@ func (r *gigaRouterCommon) runPushAppHashes(ctx context.Context) error { if err != nil { return fmt.Errorf("AppHashBuilder.GetAppHash(%v): %w", n, err) } - // TODO: PushAppHash needs the validator set from right after block n. - // GetValidators() is the app tip, which can be past n. This is exact only - // while the app's validator set never changes, as for the EVM-only and mock - // apps Autobahn runs. Read the next epoch's validator set from app state - // once it keeps one. + // PushAppHash needs the validator set from right after block n, and uses it + // only when n closes an epoch. GetValidators() reads the app tip, which can + // be past n. The EVM-only app serves the set it snapshotted when the latest + // epoch closed, which is block n's until the tip closes the next one, and + // the mock app's set never changes. + // TODO: ask the app for the set as of block n, to drop that bound. weights, err := committeeWeights(r.app.GetValidators()) if err != nil { return err From ce583aae2cf4eae233f384211fac3296d07fd4e5 Mon Sep 17 00:00:00 2001 From: Tony Chen Date: Mon, 16 Nov 2026 22:54:38 +0800 Subject: [PATCH 41/44] docs(staking): say a redelegation that empties an unbonded source waits Taking the last shares out of an unbonded validator removes it before the redelegation's completion is decided, so the move waits a full unbonding period, as x/staking's BeginRedelegation does. The Redelegate event and redelegate's doc now say so, and a test pins it. Co-Authored-By: Claude Opus 5.5 --- giga/evmonly/precompiles/staking/Staking.sol | 6 ++++-- giga/evmonly/precompiles/staking/delegation.go | 6 ++++-- giga/evmonly/precompiles/staking/staking_test.go | 16 ++++++++++++++++ 3 files changed, 24 insertions(+), 4 deletions(-) diff --git a/giga/evmonly/precompiles/staking/Staking.sol b/giga/evmonly/precompiles/staking/Staking.sol index 186d170e3d..88615f10c2 100644 --- a/giga/evmonly/precompiles/staking/Staking.sol +++ b/giga/evmonly/precompiles/staking/Staking.sol @@ -22,8 +22,10 @@ interface IStaking { /// @notice The caller moved amount from srcValidator to dstValidator. The /// stake moved at once; completionTime is when the move stops counting toward - /// maxEntries and stops blocking a redelegation out of dstValidator, or 0 when - /// it never did, because srcValidator was unbonded. + /// maxEntries and stops blocking a redelegation out of dstValidator. It is 0 + /// when srcValidator was unbonded, unless the move took its last shares: that + /// removes srcValidator, and the move then counts for a full unbonding period, + /// as in x/staking. event Redelegate( address indexed delegator, address indexed srcValidator, diff --git a/giga/evmonly/precompiles/staking/delegation.go b/giga/evmonly/precompiles/staking/delegation.go index 5234c43263..e3da6af0d7 100644 --- a/giga/evmonly/precompiles/staking/delegation.go +++ b/giga/evmonly/precompiles/staking/delegation.go @@ -251,8 +251,8 @@ func (p Precompile) undelegate( // redelegate moves shares of delegator's delegation to src into a delegation // to dst, as x/staking's BeginRedelegation does, and queues the redelegation -// entry unless src is unbonded. It returns the tokens moved and the entry's -// completion time, or 0 for no entry. +// entry unless src is unbonded and still exists once the shares leave it. It +// returns the tokens moved and the entry's completion time, or 0 for no entry. func (p Precompile) redelegate( block precompiles.BlockContext, s store, params chainparams.Staking, delegator, src, dst common.Address, shares *big.Int, ) (*big.Int, uint64, error) { @@ -287,6 +287,8 @@ func (p Precompile) redelegate( return nil, 0, err } + // Read after unbond, as x/staking does: taking the last shares out of an + // unbonded src removes it, and a missing src waits a full unbonding period. completionTime, creationHeight, completeNow := redelegationBeginInfo(block, s, params, src) if completeNow { return amount, 0, nil diff --git a/giga/evmonly/precompiles/staking/staking_test.go b/giga/evmonly/precompiles/staking/staking_test.go index d2ede2d055..f0eaae9586 100644 --- a/giga/evmonly/precompiles/staking/staking_test.go +++ b/giga/evmonly/precompiles/staking/staking_test.go @@ -199,6 +199,22 @@ func TestRedelegatingFromAnUnbondedValidatorCompletesAtOnce(t *testing.T) { h.requireInvariants(alice) } +func TestRedelegatingTheLastSharesOutOfAnUnbondedValidatorWaits(t *testing.T) { + h := newHarness(t, testParams) + require.NoError(t, h.redelegate(val3, val3, val1, sei(10))) + _, ok := h.store().validator(val3) + require.False(t, ok, "the last shares out remove an unbonded validator") + require.Equal(t, int64(1), h.store().redelegationEntryCount(val3, val3, val1).Int64(), "a missing source waits as a bonded one does") + data, err := ABI.Events[RedelegateEvent].Inputs.NonIndexed().Unpack(h.state.logs[len(h.state.logs)-1].Data) + require.NoError(t, err) + require.Equal(t, []interface{}{sei(10), h.time + testParams.UnbondingTime}, data) + + h.advance(testParams.UnbondingTime) + require.Empty(t, h.failures) + require.Zero(t, h.store().redelegationEntryCount(val3, val3, val1).Sign()) + h.requireInvariants() +} + func TestRedelegatingOutOfAnOpenRedelegationWaits(t *testing.T) { h := newHarness(t, testParams) require.NoError(t, h.delegate(alice, val1, sei(5))) From 3790e4ba1933959cd2266ef5f84a8dee6c3945c4 Mon Sep 17 00:00:00 2001 From: Tony Chen Date: Mon, 16 Nov 2026 22:56:34 +0800 Subject: [PATCH 42/44] test(staking): compare redelegating an unbonded validator's last shares with V2 Co-Authored-By: Claude Opus 5.5 --- giga/evmonly/precompiles/staking/parity_test.go | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/giga/evmonly/precompiles/staking/parity_test.go b/giga/evmonly/precompiles/staking/parity_test.go index ab57e9b5b2..9b876a8b00 100644 --- a/giga/evmonly/precompiles/staking/parity_test.go +++ b/giga/evmonly/precompiles/staking/parity_test.go @@ -209,6 +209,16 @@ func TestValidatorLifecycleMatchesV2(t *testing.T) { require.NoError(t, pr.redelegate(alice, val1, val3, seiInUsei), "into an unbonded validator") pr.endBlock() }}, + {"the last shares out of an unbonded validator remove it and redelegate as from a bonded one", func(t *testing.T, pr *pair) { + require.Equal(t, stakingtypes.Unbonded, pr.v2Status(val4)) + require.NoError(t, pr.redelegate(val4, val4, val3, 15*seiInUsei)) + _, ok := pr.v2.validator(val4) + require.False(t, ok) + require.Len(t, pr.v2Redelegations(val4), 1, "x/staking finds no source and waits a full unbonding period") + pr.wait(parityParams.UnbondingTime) + pr.endBlock() + require.Empty(t, pr.v2Redelegations(val4)) + }}, {"a validator bonded again while unbonding stays bonded when that unbonding would end", func(t *testing.T, pr *pair) { require.NoError(t, pr.delegate(alice, val4, 10*seiInUsei)) pr.endBlock() From 8a6aa880941cded9f31a8d5a87fab6632e9b85f1 Mon Sep 17 00:00:00 2001 From: Tony Chen Date: Mon, 16 Nov 2026 23:11:45 +0800 Subject: [PATCH 43/44] fix(staking): keep each member's consensus key in the epoch snapshot A snapshotted validator can leave the bonded set, finish unbonding with no shares and be removed before its snapshot is retired, so reading its key from the live record left GetValidators with no committee. The snapshot now copies each member's key when it is taken, while every member is bonded, and is read on its own. Co-Authored-By: Claude Opus 5.5 --- docs/giga-storage/StakingStorage.sol | 15 +- docs/giga-storage/staking-design-rationale.md | 17 +- .../evmonly/precompiles/staking/bonded_set.go | 16 +- .../precompiles/staking/bonded_set_test.go | 32 +- giga/evmonly/precompiles/staking/endblock.go | 17 +- giga/evmonly/precompiles/staking/layout.go | 10 + .../precompiles/staking/layout_test.go | 7 +- giga/evmonly/precompiles/staking/storage.go | 96 +++-- .../StakingStorageHarness.bin-runtime | 2 +- .../testdata/StakingStorageHarness.sol | 2 +- .../testdata/staking_storage_layout.json | 367 ++++++++++-------- 11 files changed, 344 insertions(+), 237 deletions(-) diff --git a/docs/giga-storage/StakingStorage.sol b/docs/giga-storage/StakingStorage.sol index edcbd47b66..a7c83a84d4 100644 --- a/docs/giga-storage/StakingStorage.sol +++ b/docs/giga-storage/StakingStorage.sol @@ -51,6 +51,13 @@ contract StakingStorage { uint64 power; } + /// @dev A member of an epoch snapshot. + struct EpochValidator { + address operator; + uint64 power; + bytes32 consensusPubkey; // ed25519 + } + struct Delegation { uint256 shares; } @@ -97,10 +104,10 @@ contract StakingStorage { ValidatorPower[] internal lastValidators; // 0x11: the bonded set, as last sent to consensus uint256 internal lastTotalPower; // 0x12 - /// @dev lastValidators at the end of each epoch's last block. Consensus - /// derives an epoch's committee from the set two epochs before it, so the - /// latest three are kept. - mapping(uint64 => ValidatorPower[]) internal epochValidators; // epoch => + /// @dev The bonded set at the end of each epoch's last block, with each + /// member's consensus key. Consensus derives an epoch's committee from the + /// set two epochs before it, so the latest three are kept. + mapping(uint64 => EpochValidator[]) internal epochValidators; // epoch => uint64 internal nextSnapshotEpoch; // the epoch after the latest in epochValidators, 0 before any mapping(address => Validator) internal validators; // 0x21: operator => diff --git a/docs/giga-storage/staking-design-rationale.md b/docs/giga-storage/staking-design-rationale.md index 76e5410fa8..77cb048446 100644 --- a/docs/giga-storage/staking-design-rationale.md +++ b/docs/giga-storage/staking-design-rationale.md @@ -298,16 +298,19 @@ reads at the end of epoch E's last block. The node reads the set outside block execution, at whatever height the app has reached by then, so the set it gets could differ from node to node. -So at the end of an epoch's last block, EndBlock copies `lastValidators` into -`epochValidators[epoch]`, and the app serves consensus the latest snapshot. The -snapshot is committed state, so every node serves the same one for an epoch, -and a node that state-syncs gets it too. Consensus marks the block that closes -an epoch, so the app never repeats the epoch length. +So at the end of an epoch's last block, EndBlock copies `lastValidators`, with +each member's consensus key, into `epochValidators[epoch]`, and the app serves +consensus the latest snapshot. The snapshot is committed state, so every node +serves the same one for an epoch, and a node that state-syncs gets it too. +Consensus marks the block that closes an epoch, so the app never repeats the +epoch length. The keys are copied because a member can leave the bonded set, +finish unbonding with no shares and be removed while its snapshot is still +served. The snapshot is also what rewards read: the committee that served a block in epoch E is the snapshot of epoch E−2. Three are kept, E−2 to E, and EndBlock -deletes the one before them when it takes a new one: about 100 slot writes once -an epoch. +deletes the one before them when it takes a new one: about 150 slot writes once +an epoch at 35 validators. ### Where the structures don't carry over diff --git a/giga/evmonly/precompiles/staking/bonded_set.go b/giga/evmonly/precompiles/staking/bonded_set.go index bea3be0b68..dfc541b82d 100644 --- a/giga/evmonly/precompiles/staking/bonded_set.go +++ b/giga/evmonly/precompiles/staking/bonded_set.go @@ -1,8 +1,6 @@ package staking import ( - "fmt" - "github.com/ethereum/go-ethereum/common" "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles" @@ -24,17 +22,5 @@ func EpochValidators(state precompiles.State) ([]BondedValidator, error) { if !ok { return nil, nil } - set, err := s.epochValidators(epoch) - if err != nil { - return nil, err - } - bonded := make([]BondedValidator, len(set)) - for i, v := range set { - pubkey := s.consensusPubkey(v.operator) - if pubkey == (common.Hash{}) { - return nil, fmt.Errorf("%w: %s", errUnknownValidator, v.operator) - } - bonded[i] = BondedValidator{Operator: v.operator, ConsensusPubkey: pubkey, Power: v.power} - } - return bonded, nil + return s.epochValidators(epoch) } diff --git a/giga/evmonly/precompiles/staking/bonded_set_test.go b/giga/evmonly/precompiles/staking/bonded_set_test.go index c81da92e75..53930692c0 100644 --- a/giga/evmonly/precompiles/staking/bonded_set_test.go +++ b/giga/evmonly/precompiles/staking/bonded_set_test.go @@ -1,6 +1,7 @@ package staking import ( + "errors" "testing" "github.com/ethereum/go-ethereum/common" @@ -51,14 +52,35 @@ func TestNoEpochValidatorsBeforeStakingStarts(t *testing.T) { require.Empty(t, must(EpochValidators(state))) } -func TestEpochValidatorsFailOnAStoredSetThatDoesNotAddUp(t *testing.T) { +func TestEpochValidatorsOutliveTheirValidators(t *testing.T) { h := newHarness(t, testParams) - h.store().setLastValidators([]validatorPower{{val1, 30}, {alice, 20}}) h.endEpoch(0) - _, err := EpochValidators(h.state) - require.ErrorIs(t, err, errUnknownValidator, "a member with no validator") + want := must(EpochValidators(h.state)) + + require.NoError(t, h.delegate(alice, val3, sei(15))) + h.endBlock() + require.NoError(t, h.undelegate(val2, val2, sei(20))) + h.advance(testParams.UnbondingTime) + require.Empty(t, h.failures) + _, ok := h.store().validator(val2) + require.False(t, ok, "val2 left the bonded set and was removed once it unbonded with no shares") + require.Equal(t, want, must(EpochValidators(h.state))) +} + +func TestAnEpochWhoseSetDoesNotAddUpIsNotSnapshotted(t *testing.T) { + h := newHarness(t, testParams) + h.endEpoch(0) + want := must(EpochValidators(h.state)) + h.store().setLastValidators([]validatorPower{{val1, 30}, {alice, 20}}) + h.endEpoch(1) + require.ErrorIs(t, errors.Join(h.failures...), errUnknownValidator, "a member with no validator") + require.Equal(t, want, must(EpochValidators(h.state)), "epoch 0's snapshot stays the latest") +} +func TestEpochValidatorsFailOnAStoredSetThatDoesNotAddUp(t *testing.T) { + h := newHarness(t, testParams) + h.endEpoch(0) h.store().SetUint64(solstorage.MapUint64(solstorage.Slot(slotEpochValidators), 0), 0, 101) - _, err = EpochValidators(h.state) + _, err := EpochValidators(h.state) require.ErrorIs(t, err, errInvalidStoredSet, "a set longer than any MaxValidators allows") } diff --git a/giga/evmonly/precompiles/staking/endblock.go b/giga/evmonly/precompiles/staking/endblock.go index 6f80e0e294..9215fa23e6 100644 --- a/giga/evmonly/precompiles/staking/endblock.go +++ b/giga/evmonly/precompiles/staking/endblock.go @@ -166,14 +166,25 @@ func (p Precompile) applyBondedSet(block precompiles.BlockContext, s store, para // committee is derived from the snapshot two epochs before it. const epochSnapshotsKept = 3 -// snapshotEpoch copies the bonded set into epoch's snapshot and deletes the one -// that no longer falls among the latest epochSnapshotsKept. +// snapshotEpoch copies the bonded set, with each member's consensus key, into +// epoch's snapshot and deletes the one that no longer falls among the latest +// epochSnapshotsKept. func snapshotEpoch(s store, epoch uint64) error { last, err := s.lastValidators() if err != nil { return err } - s.setEpochValidators(epoch, last) + set := make([]BondedValidator, len(last)) + for i, v := range last { + // The key is copied rather than looked up when the snapshot is read, + // because a member can be removed before its snapshot is retired. + pubkey := s.consensusPubkey(v.operator) + if pubkey == (common.Hash{}) { + return fmt.Errorf("%w: %s", errUnknownValidator, v.operator) + } + set[i] = BondedValidator{Operator: v.operator, ConsensusPubkey: pubkey, Power: v.power} + } + s.setEpochValidators(epoch, set) if epoch >= epochSnapshotsKept { s.setEpochValidators(epoch-epochSnapshotsKept, nil) } diff --git a/giga/evmonly/precompiles/staking/layout.go b/giga/evmonly/precompiles/staking/layout.go index 0c3973b48c..b55844b4d3 100644 --- a/giga/evmonly/precompiles/staking/layout.go +++ b/giga/evmonly/precompiles/staking/layout.go @@ -68,6 +68,16 @@ var ( validatorPowerPower = member{0, 20} ) +// StakingStorage.EpochValidator members. +var ( + epochValidatorOperator = member{0, 0} + epochValidatorPower = member{0, 20} + epochValidatorConsensusPubkey = member{1, 0} +) + +// epochValidatorSlots is how many slots a StakingStorage.EpochValidator takes. +const epochValidatorSlots = 2 + // StakingStorage.UnbondingDelegationEntry members. var ( unbondingEntryCreationHeight = member{0, 0} diff --git a/giga/evmonly/precompiles/staking/layout_test.go b/giga/evmonly/precompiles/staking/layout_test.go index 89e3a9dff9..e257115db0 100644 --- a/giga/evmonly/precompiles/staking/layout_test.go +++ b/giga/evmonly/precompiles/staking/layout_test.go @@ -113,6 +113,11 @@ func TestLayoutMatchesSolc(t *testing.T) { "operator": validatorPowerOperator, "power": validatorPowerPower, }, 1}, + "struct StakingStorage.EpochValidator": {map[string]member{ + "operator": epochValidatorOperator, + "power": epochValidatorPower, + "consensusPubkey": epochValidatorConsensusPubkey, + }, epochValidatorSlots}, "struct StakingStorage.Delegation": {map[string]member{"shares": {0, 0}}, 1}, "struct StakingStorage.UnbondingDelegationEntry": {map[string]member{ "creationHeight": unbondingEntryCreationHeight, @@ -200,7 +205,7 @@ func TestStoreReadsCompilerWrites(t *testing.T) { require.NoError(t, err) require.Equal(t, []validatorPower{{op, 30}, {other, 20}}, set) require.Equal(t, big.NewInt(50), s.lastTotalPower()) - require.Equal(t, []validatorPower{{other, 21}}, must(s.epochValidators(7))) + require.Equal(t, []BondedValidator{{Operator: other, ConsensusPubkey: pubkey, Power: 21}}, must(s.epochValidators(7))) latest, ok := s.latestSnapshotEpoch() require.True(t, ok) require.Equal(t, uint64(7), latest) diff --git a/giga/evmonly/precompiles/staking/storage.go b/giga/evmonly/precompiles/staking/storage.go index ba46b8aa7b..92d38c9ce3 100644 --- a/giga/evmonly/precompiles/staking/storage.go +++ b/giga/evmonly/precompiles/staking/storage.go @@ -178,38 +178,7 @@ type validatorPower struct { // lastValidators returns the bonded set as last stored, failing on a set longer // than any MaxValidators allows. func (s store) lastValidators() ([]validatorPower, error) { - return s.validatorPowers(solstorage.Slot(slotLastValidators)) -} - -// setLastValidators replaces the bonded set. -func (s store) setLastValidators(set []validatorPower) { - s.setValidatorPowers(solstorage.Slot(slotLastValidators), set) -} - -// epochValidators returns the bonded set snapshotted at the end of epoch, or -// none when that epoch has no snapshot. -func (s store) epochValidators(epoch uint64) ([]validatorPower, error) { - return s.validatorPowers(solstorage.MapUint64(solstorage.Slot(slotEpochValidators), epoch)) -} - -func (s store) setEpochValidators(epoch uint64, set []validatorPower) { - s.setValidatorPowers(solstorage.MapUint64(solstorage.Slot(slotEpochValidators), epoch), set) -} - -// latestSnapshotEpoch returns the latest epoch with a snapshot, and false -// before any. -func (s store) latestSnapshotEpoch() (uint64, bool) { - next := s.Uint64(solstorage.Slot(slotNextSnapshotEpoch), 0) - return next - 1, next > 0 -} - -func (s store) setLatestSnapshotEpoch(epoch uint64) { - s.SetUint64(solstorage.Slot(slotNextSnapshotEpoch), 0, epoch+1) -} - -// validatorPowers returns the ValidatorPower[] at base, failing on one longer -// than any MaxValidators allows. -func (s store) validatorPowers(base common.Hash) ([]validatorPower, error) { + base := solstorage.Slot(slotLastValidators) n := s.Uint64(base, 0) if n > uint64(chainparams.MaxBondedValidators) { return nil, fmt.Errorf("%w: %d validators", errInvalidStoredSet, n) @@ -226,9 +195,10 @@ func (s store) validatorPowers(base common.Hash) ([]validatorPower, error) { return out, nil } -// setValidatorPowers replaces the ValidatorPower[] at base, zeroing elements -// the new one no longer covers. -func (s store) setValidatorPowers(base common.Hash, set []validatorPower) { +// setLastValidators replaces the bonded set, zeroing elements the new set no +// longer covers. +func (s store) setLastValidators(set []validatorPower) { + base := solstorage.Slot(slotLastValidators) old := min(s.Uint64(base, 0), uint64(chainparams.MaxBondedValidators)) data := solstorage.ArrayData(base) for i, v := range set { @@ -243,6 +213,62 @@ func (s store) setValidatorPowers(base common.Hash, set []validatorPower) { s.SetWord(base, solstorage.Slot(uint64(len(set)))) } +func epochValidatorsBase(epoch uint64) common.Hash { + return solstorage.MapUint64(solstorage.Slot(slotEpochValidators), epoch) +} + +// epochValidators returns the bonded set snapshotted at the end of epoch, or +// none when that epoch has no snapshot. It fails on a set longer than any +// MaxValidators allows. +func (s store) epochValidators(epoch uint64) ([]BondedValidator, error) { + base := epochValidatorsBase(epoch) + n := s.Uint64(base, 0) + if n > uint64(chainparams.MaxBondedValidators) { + return nil, fmt.Errorf("%w: %d validators", errInvalidStoredSet, n) + } + data := solstorage.ArrayData(base) + out := make([]BondedValidator, n) + for i := range out { + e := solstorage.Offset(data, uint64(i)*epochValidatorSlots) //nolint:gosec // i is below n + out[i] = BondedValidator{ + Operator: s.AddressAt(at(e, epochValidatorOperator), epochValidatorOperator.offset), + ConsensusPubkey: s.Word(at(e, epochValidatorConsensusPubkey)), + Power: s.Uint64(at(e, epochValidatorPower), epochValidatorPower.offset), + } + } + return out, nil +} + +// setEpochValidators replaces epoch's snapshot, zeroing elements the new one no +// longer covers. +func (s store) setEpochValidators(epoch uint64, set []BondedValidator) { + base := epochValidatorsBase(epoch) + old := min(s.Uint64(base, 0), uint64(chainparams.MaxBondedValidators)) + data := solstorage.ArrayData(base) + for i, v := range set { + e := solstorage.Offset(data, uint64(i)*epochValidatorSlots) //nolint:gosec // i is non-negative + s.SetWord(at(e, epochValidatorOperator), common.Hash{}) + s.SetAddressAt(at(e, epochValidatorOperator), epochValidatorOperator.offset, v.Operator) + s.SetUint64(at(e, epochValidatorPower), epochValidatorPower.offset, v.Power) + s.SetWord(at(e, epochValidatorConsensusPubkey), v.ConsensusPubkey) + } + for i := uint64(len(set)) * epochValidatorSlots; i < old*epochValidatorSlots; i++ { + s.SetWord(solstorage.Offset(data, i), common.Hash{}) + } + s.SetWord(base, solstorage.Slot(uint64(len(set)))) +} + +// latestSnapshotEpoch returns the latest epoch with a snapshot, and false +// before any. +func (s store) latestSnapshotEpoch() (uint64, bool) { + next := s.Uint64(solstorage.Slot(slotNextSnapshotEpoch), 0) + return next - 1, next > 0 +} + +func (s store) setLatestSnapshotEpoch(epoch uint64) { + s.SetUint64(solstorage.Slot(slotNextSnapshotEpoch), 0, epoch+1) +} + // lastTotalPower returns the consensus power of the bonded set as last stored. func (s store) lastTotalPower() *big.Int { return s.Uint256(solstorage.Slot(slotLastTotalPower)) diff --git a/giga/evmonly/precompiles/staking/testdata/StakingStorageHarness.bin-runtime b/giga/evmonly/precompiles/staking/testdata/StakingStorageHarness.bin-runtime index 10bc635e43..5f84c63551 100644 --- a/giga/evmonly/precompiles/staking/testdata/StakingStorageHarness.bin-runtime +++ b/giga/evmonly/precompiles/staking/testdata/StakingStorageHarness.bin-runtime @@ -1 +1 @@ -608060405234801561000f575f5ffd5b5060043610610029575f3560e01c80633afaaf0e1461002d575b5f5ffd5b6100476004803603810190610042919061120b565b610049565b005b5f60405180604001604052808673ffffffffffffffffffffffffffffffffffffffff168152602001601e67ffffffffffffffff16815250908060018154018082558091505060019003905f5260205f20015f909190919091505f820151815f015f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506020820151815f0160146101000a81548167ffffffffffffffff021916908367ffffffffffffffff16021790555050505f60405180604001604052808573ffffffffffffffffffffffffffffffffffffffff168152602001601467ffffffffffffffff16815250908060018154018082558091505060019003905f5260205f20015f909190919091505f820151815f015f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506020820151815f0160146101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055505050603260018190555060025f600767ffffffffffffffff1681526020019081526020015f2060405180604001604052808573ffffffffffffffffffffffffffffffffffffffff168152602001601567ffffffffffffffff16815250908060018154018082558091505060019003905f5260205f20015f909190919091505f820151815f015f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506020820151815f0160146101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055505050600860035f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055505f60045f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20905081815f01819055506001816001015f6101000a81548160ff02191690831515021790555060028160010160016101000a81548160ff021916908360ff1602179055506801ae361fc1451c000081600201819055506f1812f9cf7920e2b66973e20000000000816003018190555060405180606001604052806034815260200161157c60349139816004015f0190816103d491906114ac565b506040518060400160405280600181526020017f640000000000000000000000000000000000000000000000000000000000000081525081600401600401908161041e91906114ac565b506021816009015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff16021790555060228160090160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff160217905550602381600a015f015f0181905550602481600a016003015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff160217905550602581600e0181905550600360045f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f2060010160016101000a81548160ff021916908360ff1602179055506105216005866110cb565b61052c6005856110cb565b8460075f8481526020019081526020015f205f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550600884908060018154018082558091505060019003905f5260205f20015f9091909190916101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550600885908060018154018082558091505060019003905f5260205f20015f9091909190916101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550602960095f8573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f0181905550610701600a5f8573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20866110cb565b610747600b5f8773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20846110cb565b600c5f8473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f206040518060800160405280603367ffffffffffffffff168152602001603467ffffffffffffffff168152602001603581526020016036815250908060018154018082558091505060019003905f5260205f2090600302015f909190919091505f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff16021790555060408201518160010155606082015181600201555050600c5f8473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f206040518060800160405280603767ffffffffffffffff168152602001603867ffffffffffffffff16815260200160398152602001603a815250908060018154018082558091505060019003905f5260205f2090600302015f909190919091505f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff160217905550604082015181600101556060820151816002015550506002600d5f8573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20819055506003600e5f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20819055506040518060400160405280600167ffffffffffffffff168152602001600267ffffffffffffffff16815250600f5f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055509050506040518060600160405280603d67ffffffffffffffff1681526020018473ffffffffffffffffffffffffffffffffffffffff1681526020018673ffffffffffffffffffffffffffffffffffffffff1681525060105f600167ffffffffffffffff1681526020019081526020015f205f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506040820151816001015f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555090505060405180604001604052805f67ffffffffffffffff168152602001600167ffffffffffffffff1681525060115f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055509050506040518060e00160405280604767ffffffffffffffff1681526020018473ffffffffffffffffffffffffffffffffffffffff168152602001604867ffffffffffffffff1681526020018673ffffffffffffffffffffffffffffffffffffffff1681526020018573ffffffffffffffffffffffffffffffffffffffff16815260200160498152602001604a81525060125f5f67ffffffffffffffff1681526020019081526020015f205f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506040820151816001015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff16021790555060608201518160010160086101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506080820151816002015f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555060a0820151816003015560c082015181600401559050506040518060400160405280600467ffffffffffffffff168152602001600567ffffffffffffffff1681525060135f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055509050506040518060600160405280605167ffffffffffffffff168152602001605267ffffffffffffffff1681526020018573ffffffffffffffffffffffffffffffffffffffff1681525060145f600467ffffffffffffffff1681526020019081526020015f205f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506040820151816001015f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055509050505050505050565b815f0181908060018154018082558091505060019003905f5260205f20015f9091909190916101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550815f0180549050826001015f8373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20819055505050565b5f5ffd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6111a78261117e565b9050919050565b6111b78161119d565b81146111c1575f5ffd5b50565b5f813590506111d2816111ae565b92915050565b5f819050919050565b6111ea816111d8565b81146111f4575f5ffd5b50565b5f81359050611205816111e1565b92915050565b5f5f5f5f608085870312156112235761122261117a565b5b5f611230878288016111c4565b9450506020611241878288016111c4565b9350506040611252878288016111c4565b9250506060611263878288016111f7565b91505092959194509250565b5f81519050919050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52604160045260245ffd5b7f4e487b71000000000000000000000000000000000000000000000000000000005f52602260045260245ffd5b5f60028204905060018216806112ea57607f821691505b6020821081036112fd576112fc6112a6565b5b50919050565b5f819050815f5260205f209050919050565b5f6020601f8301049050919050565b5f82821b905092915050565b5f6008830261135f7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff82611324565b6113698683611324565b95508019841693508086168417925050509392505050565b5f819050919050565b5f819050919050565b5f6113ad6113a86113a384611381565b61138a565b611381565b9050919050565b5f819050919050565b6113c683611393565b6113da6113d2826113b4565b848454611330565b825550505050565b5f5f905090565b6113f16113e2565b6113fc8184846113bd565b505050565b5b8181101561141f576114145f826113e9565b600181019050611402565b5050565b601f8211156114645761143581611303565b61143e84611315565b8101602085101561144d578190505b61146161145985611315565b830182611401565b50505b505050565b5f82821c905092915050565b5f6114845f1984600802611469565b1980831691505092915050565b5f61149c8383611475565b9150826002028217905092915050565b6114b58261126f565b67ffffffffffffffff8111156114ce576114cd611279565b5b6114d882546112d3565b6114e3828285611423565b5f60209050601f831160018114611514575f8415611502578287015190505b61150c8582611491565b865550611573565b601f19841661152286611303565b5f5b8281101561154957848901518255600182019150602085019450602081019050611524565b868310156115665784890151611562601f891682611475565b8355505b6001600288020188555050505b50505050505056fe61206d6f6e696b6572206c6f6e6720656e6f75676820746f207370696c6c2070617374206f6e652073746f7261676520776f7264a2646970667358221220dc3b466112c8b58d9f8dabe6750c7a816eb8343b23ff50a598771f216d089b6764736f6c634300081e0033 +608060405234801561000f575f5ffd5b5060043610610029575f3560e01c80633afaaf0e1461002d575b5f5ffd5b6100476004803603810190610042919061121f565b610049565b005b5f60405180604001604052808673ffffffffffffffffffffffffffffffffffffffff168152602001601e67ffffffffffffffff16815250908060018154018082558091505060019003905f5260205f20015f909190919091505f820151815f015f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506020820151815f0160146101000a81548167ffffffffffffffff021916908367ffffffffffffffff16021790555050505f60405180604001604052808573ffffffffffffffffffffffffffffffffffffffff168152602001601467ffffffffffffffff16815250908060018154018082558091505060019003905f5260205f20015f909190919091505f820151815f015f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506020820151815f0160146101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055505050603260018190555060025f600767ffffffffffffffff1681526020019081526020015f2060405180606001604052808573ffffffffffffffffffffffffffffffffffffffff168152602001601567ffffffffffffffff16815260200183815250908060018154018082558091505060019003905f5260205f2090600202015f909190919091505f820151815f015f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506020820151815f0160146101000a81548167ffffffffffffffff021916908367ffffffffffffffff160217905550604082015181600101555050600860035f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055505f60045f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20905081815f01819055506001816001015f6101000a81548160ff02191690831515021790555060028160010160016101000a81548160ff021916908360ff1602179055506801ae361fc1451c000081600201819055506f1812f9cf7920e2b66973e20000000000816003018190555060405180606001604052806034815260200161159060349139816004015f0190816103e891906114c0565b506040518060400160405280600181526020017f640000000000000000000000000000000000000000000000000000000000000081525081600401600401908161043291906114c0565b506021816009015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff16021790555060228160090160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff160217905550602381600a015f015f0181905550602481600a016003015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff160217905550602581600e0181905550600360045f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f2060010160016101000a81548160ff021916908360ff1602179055506105356005866110df565b6105406005856110df565b8460075f8481526020019081526020015f205f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550600884908060018154018082558091505060019003905f5260205f20015f9091909190916101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550600885908060018154018082558091505060019003905f5260205f20015f9091909190916101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550602960095f8573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f0181905550610715600a5f8573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20866110df565b61075b600b5f8773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20846110df565b600c5f8473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f206040518060800160405280603367ffffffffffffffff168152602001603467ffffffffffffffff168152602001603581526020016036815250908060018154018082558091505060019003905f5260205f2090600302015f909190919091505f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff16021790555060408201518160010155606082015181600201555050600c5f8473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f206040518060800160405280603767ffffffffffffffff168152602001603867ffffffffffffffff16815260200160398152602001603a815250908060018154018082558091505060019003905f5260205f2090600302015f909190919091505f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff160217905550604082015181600101556060820151816002015550506002600d5f8573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20819055506003600e5f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20819055506040518060400160405280600167ffffffffffffffff168152602001600267ffffffffffffffff16815250600f5f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055509050506040518060600160405280603d67ffffffffffffffff1681526020018473ffffffffffffffffffffffffffffffffffffffff1681526020018673ffffffffffffffffffffffffffffffffffffffff1681525060105f600167ffffffffffffffff1681526020019081526020015f205f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506040820151816001015f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555090505060405180604001604052805f67ffffffffffffffff168152602001600167ffffffffffffffff1681525060115f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055509050506040518060e00160405280604767ffffffffffffffff1681526020018473ffffffffffffffffffffffffffffffffffffffff168152602001604867ffffffffffffffff1681526020018673ffffffffffffffffffffffffffffffffffffffff1681526020018573ffffffffffffffffffffffffffffffffffffffff16815260200160498152602001604a81525060125f5f67ffffffffffffffff1681526020019081526020015f205f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506040820151816001015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff16021790555060608201518160010160086101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506080820151816002015f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555060a0820151816003015560c082015181600401559050506040518060400160405280600467ffffffffffffffff168152602001600567ffffffffffffffff1681525060135f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055509050506040518060600160405280605167ffffffffffffffff168152602001605267ffffffffffffffff1681526020018573ffffffffffffffffffffffffffffffffffffffff1681525060145f600467ffffffffffffffff1681526020019081526020015f205f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506040820151816001015f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055509050505050505050565b815f0181908060018154018082558091505060019003905f5260205f20015f9091909190916101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550815f0180549050826001015f8373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20819055505050565b5f5ffd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6111bb82611192565b9050919050565b6111cb816111b1565b81146111d5575f5ffd5b50565b5f813590506111e6816111c2565b92915050565b5f819050919050565b6111fe816111ec565b8114611208575f5ffd5b50565b5f81359050611219816111f5565b92915050565b5f5f5f5f608085870312156112375761123661118e565b5b5f611244878288016111d8565b9450506020611255878288016111d8565b9350506040611266878288016111d8565b92505060606112778782880161120b565b91505092959194509250565b5f81519050919050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52604160045260245ffd5b7f4e487b71000000000000000000000000000000000000000000000000000000005f52602260045260245ffd5b5f60028204905060018216806112fe57607f821691505b602082108103611311576113106112ba565b5b50919050565b5f819050815f5260205f209050919050565b5f6020601f8301049050919050565b5f82821b905092915050565b5f600883026113737fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff82611338565b61137d8683611338565b95508019841693508086168417925050509392505050565b5f819050919050565b5f819050919050565b5f6113c16113bc6113b784611395565b61139e565b611395565b9050919050565b5f819050919050565b6113da836113a7565b6113ee6113e6826113c8565b848454611344565b825550505050565b5f5f905090565b6114056113f6565b6114108184846113d1565b505050565b5b81811015611433576114285f826113fd565b600181019050611416565b5050565b601f8211156114785761144981611317565b61145284611329565b81016020851015611461578190505b61147561146d85611329565b830182611415565b50505b505050565b5f82821c905092915050565b5f6114985f198460080261147d565b1980831691505092915050565b5f6114b08383611489565b9150826002028217905092915050565b6114c982611283565b67ffffffffffffffff8111156114e2576114e161128d565b5b6114ec82546112e7565b6114f7828285611437565b5f60209050601f831160018114611528575f8415611516578287015190505b61152085826114a5565b865550611587565b601f19841661153686611317565b5f5b8281101561155d57848901518255600182019150602085019450602081019050611538565b8683101561157a5784890151611576601f891682611489565b8355505b6001600288020188555050505b50505050505056fe61206d6f6e696b6572206c6f6e6720656e6f75676820746f207370696c6c2070617374206f6e652073746f7261676520776f7264a2646970667358221220be5dd9b21d97abe0f8e1b526f2bcc050b141fa92e35ab20b3b11b5b3a3756d4264736f6c634300081e0033 diff --git a/giga/evmonly/precompiles/staking/testdata/StakingStorageHarness.sol b/giga/evmonly/precompiles/staking/testdata/StakingStorageHarness.sol index ca418d5740..0340f0a02b 100644 --- a/giga/evmonly/precompiles/staking/testdata/StakingStorageHarness.sol +++ b/giga/evmonly/precompiles/staking/testdata/StakingStorageHarness.sol @@ -10,7 +10,7 @@ contract StakingStorageHarness is StakingStorage { lastValidators.push(ValidatorPower({operator: op, power: 30})); lastValidators.push(ValidatorPower({operator: other, power: 20})); lastTotalPower = 50; - epochValidators[7].push(ValidatorPower({operator: other, power: 21})); + epochValidators[7].push(EpochValidator({operator: other, power: 21, consensusPubkey: pubkey})); nextSnapshotEpoch = 8; Validator storage v = validators[op]; diff --git a/giga/evmonly/precompiles/staking/testdata/staking_storage_layout.json b/giga/evmonly/precompiles/staking/testdata/staking_storage_layout.json index 1d7ae6c423..e73adb0f33 100644 --- a/giga/evmonly/precompiles/staking/testdata/staking_storage_layout.json +++ b/giga/evmonly/precompiles/staking/testdata/staking_storage_layout.json @@ -1,15 +1,15 @@ { "storage": [ { - "astId": 440, + "astId": 449, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "lastValidators", "offset": 0, "slot": "0", - "type": "t_array(t_struct(ValidatorPower)386_storage)dyn_storage" + "type": "t_array(t_struct(ValidatorPower)387_storage)dyn_storage" }, { - "astId": 442, + "astId": 451, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "lastTotalPower", "offset": 0, @@ -17,15 +17,15 @@ "type": "t_uint256" }, { - "astId": 449, + "astId": 458, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "epochValidators", "offset": 0, "slot": "2", - "type": "t_mapping(t_uint64,t_array(t_struct(ValidatorPower)386_storage)dyn_storage)" + "type": "t_mapping(t_uint64,t_array(t_struct(EpochValidator)395_storage)dyn_storage)" }, { - "astId": 451, + "astId": 460, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "nextSnapshotEpoch", "offset": 0, @@ -33,23 +33,23 @@ "type": "t_uint64" }, { - "astId": 456, + "astId": 465, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "validators", "offset": 0, "slot": "4", - "type": "t_mapping(t_address,t_struct(Validator)380_storage)" + "type": "t_mapping(t_address,t_struct(Validator)381_storage)" }, { - "astId": 459, + "astId": 468, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "validatorSet", "offset": 0, "slot": "5", - "type": "t_struct(AddressSet)549_storage" + "type": "t_struct(AddressSet)558_storage" }, { - "astId": 463, + "astId": 472, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "validatorsByConsensusPubkey", "offset": 0, @@ -57,7 +57,7 @@ "type": "t_mapping(t_bytes32,t_address)" }, { - "astId": 466, + "astId": 475, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "validatorsByPower", "offset": 0, @@ -65,39 +65,39 @@ "type": "t_array(t_address)dyn_storage" }, { - "astId": 473, + "astId": 482, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "delegations", "offset": 0, "slot": "9", - "type": "t_mapping(t_address,t_mapping(t_address,t_struct(Delegation)389_storage))" + "type": "t_mapping(t_address,t_mapping(t_address,t_struct(Delegation)398_storage))" }, { - "astId": 478, + "astId": 487, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "delegationsByDelegator", "offset": 0, "slot": "10", - "type": "t_mapping(t_address,t_struct(AddressSet)549_storage)" + "type": "t_mapping(t_address,t_struct(AddressSet)558_storage)" }, { - "astId": 483, + "astId": 492, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "delegationsByValidator", "offset": 0, "slot": "11", - "type": "t_mapping(t_address,t_struct(AddressSet)549_storage)" + "type": "t_mapping(t_address,t_struct(AddressSet)558_storage)" }, { - "astId": 491, + "astId": 500, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "unbondingDelegations", "offset": 0, "slot": "12", - "type": "t_mapping(t_address,t_mapping(t_address,t_array(t_struct(UnbondingDelegationEntry)398_storage)dyn_storage))" + "type": "t_mapping(t_address,t_mapping(t_address,t_array(t_struct(UnbondingDelegationEntry)407_storage)dyn_storage))" }, { - "astId": 499, + "astId": 508, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "redelegationEntryCounts", "offset": 0, @@ -105,7 +105,7 @@ "type": "t_mapping(t_address,t_mapping(t_address,t_mapping(t_address,t_uint256)))" }, { - "astId": 505, + "astId": 514, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "redelegationsByValDst", "offset": 0, @@ -113,55 +113,55 @@ "type": "t_mapping(t_address,t_mapping(t_address,t_uint256))" }, { - "astId": 508, + "astId": 517, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "unbondingQueueBounds", "offset": 0, "slot": "15", - "type": "t_struct(QueueBounds)436_storage" + "type": "t_struct(QueueBounds)445_storage" }, { - "astId": 513, + "astId": 522, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "unbondingQueue", "offset": 0, "slot": "16", - "type": "t_mapping(t_uint64,t_struct(UnbondingQueueEntry)406_storage)" + "type": "t_mapping(t_uint64,t_struct(UnbondingQueueEntry)415_storage)" }, { - "astId": 516, + "astId": 525, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "redelegationQueueBounds", "offset": 0, "slot": "17", - "type": "t_struct(QueueBounds)436_storage" + "type": "t_struct(QueueBounds)445_storage" }, { - "astId": 521, + "astId": 530, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "redelegationQueue", "offset": 0, "slot": "18", - "type": "t_mapping(t_uint64,t_struct(RedelegationQueueEntry)422_storage)" + "type": "t_mapping(t_uint64,t_struct(RedelegationQueueEntry)431_storage)" }, { - "astId": 524, + "astId": 533, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "validatorQueueBounds", "offset": 0, "slot": "19", - "type": "t_struct(QueueBounds)436_storage" + "type": "t_struct(QueueBounds)445_storage" }, { - "astId": 529, + "astId": 538, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "validatorQueue", "offset": 0, "slot": "20", - "type": "t_mapping(t_uint64,t_struct(ValidatorQueueEntry)430_storage)" + "type": "t_mapping(t_uint64,t_struct(ValidatorQueueEntry)439_storage)" }, { - "astId": 532, + "astId": 541, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "migrating", "offset": 0, @@ -169,7 +169,7 @@ "type": "t_bool" }, { - "astId": 534, + "astId": 543, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "migrationCursor", "offset": 0, @@ -177,7 +177,7 @@ "type": "t_bytes_storage" }, { - "astId": 537, + "astId": 546, "contract": "giga-storage/StakingStorage.sol:StakingStorage", "label": "migrationFailures", "offset": 0, @@ -203,14 +203,20 @@ "label": "bytes[]", "numberOfBytes": "32" }, - "t_array(t_struct(UnbondingDelegationEntry)398_storage)dyn_storage": { - "base": "t_struct(UnbondingDelegationEntry)398_storage", + "t_array(t_struct(EpochValidator)395_storage)dyn_storage": { + "base": "t_struct(EpochValidator)395_storage", + "encoding": "dynamic_array", + "label": "struct StakingStorage.EpochValidator[]", + "numberOfBytes": "32" + }, + "t_array(t_struct(UnbondingDelegationEntry)407_storage)dyn_storage": { + "base": "t_struct(UnbondingDelegationEntry)407_storage", "encoding": "dynamic_array", "label": "struct StakingStorage.UnbondingDelegationEntry[]", "numberOfBytes": "32" }, - "t_array(t_struct(ValidatorPower)386_storage)dyn_storage": { - "base": "t_struct(ValidatorPower)386_storage", + "t_array(t_struct(ValidatorPower)387_storage)dyn_storage": { + "base": "t_struct(ValidatorPower)387_storage", "encoding": "dynamic_array", "label": "struct StakingStorage.ValidatorPower[]", "numberOfBytes": "32" @@ -230,19 +236,19 @@ "label": "bytes", "numberOfBytes": "32" }, - "t_mapping(t_address,t_array(t_struct(UnbondingDelegationEntry)398_storage)dyn_storage)": { + "t_mapping(t_address,t_array(t_struct(UnbondingDelegationEntry)407_storage)dyn_storage)": { "encoding": "mapping", "key": "t_address", "label": "mapping(address => struct StakingStorage.UnbondingDelegationEntry[])", "numberOfBytes": "32", - "value": "t_array(t_struct(UnbondingDelegationEntry)398_storage)dyn_storage" + "value": "t_array(t_struct(UnbondingDelegationEntry)407_storage)dyn_storage" }, - "t_mapping(t_address,t_mapping(t_address,t_array(t_struct(UnbondingDelegationEntry)398_storage)dyn_storage))": { + "t_mapping(t_address,t_mapping(t_address,t_array(t_struct(UnbondingDelegationEntry)407_storage)dyn_storage))": { "encoding": "mapping", "key": "t_address", "label": "mapping(address => mapping(address => struct StakingStorage.UnbondingDelegationEntry[]))", "numberOfBytes": "32", - "value": "t_mapping(t_address,t_array(t_struct(UnbondingDelegationEntry)398_storage)dyn_storage)" + "value": "t_mapping(t_address,t_array(t_struct(UnbondingDelegationEntry)407_storage)dyn_storage)" }, "t_mapping(t_address,t_mapping(t_address,t_mapping(t_address,t_uint256)))": { "encoding": "mapping", @@ -251,12 +257,12 @@ "numberOfBytes": "32", "value": "t_mapping(t_address,t_mapping(t_address,t_uint256))" }, - "t_mapping(t_address,t_mapping(t_address,t_struct(Delegation)389_storage))": { + "t_mapping(t_address,t_mapping(t_address,t_struct(Delegation)398_storage))": { "encoding": "mapping", "key": "t_address", "label": "mapping(address => mapping(address => struct StakingStorage.Delegation))", "numberOfBytes": "32", - "value": "t_mapping(t_address,t_struct(Delegation)389_storage)" + "value": "t_mapping(t_address,t_struct(Delegation)398_storage)" }, "t_mapping(t_address,t_mapping(t_address,t_uint256))": { "encoding": "mapping", @@ -265,26 +271,26 @@ "numberOfBytes": "32", "value": "t_mapping(t_address,t_uint256)" }, - "t_mapping(t_address,t_struct(AddressSet)549_storage)": { + "t_mapping(t_address,t_struct(AddressSet)558_storage)": { "encoding": "mapping", "key": "t_address", "label": "mapping(address => struct AddressSet)", "numberOfBytes": "32", - "value": "t_struct(AddressSet)549_storage" + "value": "t_struct(AddressSet)558_storage" }, - "t_mapping(t_address,t_struct(Delegation)389_storage)": { + "t_mapping(t_address,t_struct(Delegation)398_storage)": { "encoding": "mapping", "key": "t_address", "label": "mapping(address => struct StakingStorage.Delegation)", "numberOfBytes": "32", - "value": "t_struct(Delegation)389_storage" + "value": "t_struct(Delegation)398_storage" }, - "t_mapping(t_address,t_struct(Validator)380_storage)": { + "t_mapping(t_address,t_struct(Validator)381_storage)": { "encoding": "mapping", "key": "t_address", "label": "mapping(address => struct StakingStorage.Validator)", "numberOfBytes": "32", - "value": "t_struct(Validator)380_storage" + "value": "t_struct(Validator)381_storage" }, "t_mapping(t_address,t_uint256)": { "encoding": "mapping", @@ -300,54 +306,54 @@ "numberOfBytes": "32", "value": "t_address" }, - "t_mapping(t_uint64,t_array(t_struct(ValidatorPower)386_storage)dyn_storage)": { + "t_mapping(t_uint64,t_array(t_struct(EpochValidator)395_storage)dyn_storage)": { "encoding": "mapping", "key": "t_uint64", - "label": "mapping(uint64 => struct StakingStorage.ValidatorPower[])", + "label": "mapping(uint64 => struct StakingStorage.EpochValidator[])", "numberOfBytes": "32", - "value": "t_array(t_struct(ValidatorPower)386_storage)dyn_storage" + "value": "t_array(t_struct(EpochValidator)395_storage)dyn_storage" }, - "t_mapping(t_uint64,t_struct(RedelegationQueueEntry)422_storage)": { + "t_mapping(t_uint64,t_struct(RedelegationQueueEntry)431_storage)": { "encoding": "mapping", "key": "t_uint64", "label": "mapping(uint64 => struct StakingStorage.RedelegationQueueEntry)", "numberOfBytes": "32", - "value": "t_struct(RedelegationQueueEntry)422_storage" + "value": "t_struct(RedelegationQueueEntry)431_storage" }, - "t_mapping(t_uint64,t_struct(UnbondingQueueEntry)406_storage)": { + "t_mapping(t_uint64,t_struct(UnbondingQueueEntry)415_storage)": { "encoding": "mapping", "key": "t_uint64", "label": "mapping(uint64 => struct StakingStorage.UnbondingQueueEntry)", "numberOfBytes": "32", - "value": "t_struct(UnbondingQueueEntry)406_storage" + "value": "t_struct(UnbondingQueueEntry)415_storage" }, - "t_mapping(t_uint64,t_struct(ValidatorQueueEntry)430_storage)": { + "t_mapping(t_uint64,t_struct(ValidatorQueueEntry)439_storage)": { "encoding": "mapping", "key": "t_uint64", "label": "mapping(uint64 => struct StakingStorage.ValidatorQueueEntry)", "numberOfBytes": "32", - "value": "t_struct(ValidatorQueueEntry)430_storage" + "value": "t_struct(ValidatorQueueEntry)439_storage" }, "t_string_storage": { "encoding": "bytes", "label": "string", "numberOfBytes": "32" }, - "t_struct(AddressSet)549_storage": { + "t_struct(AddressSet)558_storage": { "encoding": "inplace", "label": "struct AddressSet", "members": [ { - "astId": 544, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 553, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "values", "offset": 0, "slot": "0", "type": "t_array(t_address)dyn_storage" }, { - "astId": 548, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 557, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "positions", "offset": 0, "slot": "1", @@ -356,21 +362,21 @@ ], "numberOfBytes": "64" }, - "t_struct(Commission)357_storage": { + "t_struct(Commission)358_storage": { "encoding": "inplace", "label": "struct StakingStorage.Commission", "members": [ { - "astId": 354, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 355, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "commissionRates", "offset": 0, "slot": "0", - "type": "t_struct(CommissionRates)351_storage" + "type": "t_struct(CommissionRates)352_storage" }, { - "astId": 356, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 357, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "updateTime", "offset": 0, "slot": "3", @@ -379,29 +385,29 @@ ], "numberOfBytes": "128" }, - "t_struct(CommissionRates)351_storage": { + "t_struct(CommissionRates)352_storage": { "encoding": "inplace", "label": "struct StakingStorage.CommissionRates", "members": [ { - "astId": 346, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 347, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "rate", "offset": 0, "slot": "0", "type": "t_uint256" }, { - "astId": 348, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 349, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "maxRate", "offset": 0, "slot": "1", "type": "t_uint256" }, { - "astId": 350, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 351, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "maxChangeRate", "offset": 0, "slot": "2", @@ -410,13 +416,13 @@ ], "numberOfBytes": "96" }, - "t_struct(Delegation)389_storage": { + "t_struct(Delegation)398_storage": { "encoding": "inplace", "label": "struct StakingStorage.Delegation", "members": [ { - "astId": 388, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 397, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "shares", "offset": 0, "slot": "0", @@ -425,45 +431,45 @@ ], "numberOfBytes": "32" }, - "t_struct(Description)344_storage": { + "t_struct(Description)345_storage": { "encoding": "inplace", "label": "struct StakingStorage.Description", "members": [ { - "astId": 335, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 336, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "moniker", "offset": 0, "slot": "0", "type": "t_string_storage" }, { - "astId": 337, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 338, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "identity", "offset": 0, "slot": "1", "type": "t_string_storage" }, { - "astId": 339, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 340, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "website", "offset": 0, "slot": "2", "type": "t_string_storage" }, { - "astId": 341, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 342, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "securityContact", "offset": 0, "slot": "3", "type": "t_string_storage" }, { - "astId": 343, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 344, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "details", "offset": 0, "slot": "4", @@ -472,21 +478,52 @@ ], "numberOfBytes": "160" }, - "t_struct(QueueBounds)436_storage": { + "t_struct(EpochValidator)395_storage": { + "encoding": "inplace", + "label": "struct StakingStorage.EpochValidator", + "members": [ + { + "astId": 390, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", + "label": "operator", + "offset": 0, + "slot": "0", + "type": "t_address" + }, + { + "astId": 392, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", + "label": "power", + "offset": 20, + "slot": "0", + "type": "t_uint64" + }, + { + "astId": 394, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", + "label": "consensusPubkey", + "offset": 0, + "slot": "1", + "type": "t_bytes32" + } + ], + "numberOfBytes": "64" + }, + "t_struct(QueueBounds)445_storage": { "encoding": "inplace", "label": "struct StakingStorage.QueueBounds", "members": [ { - "astId": 433, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 442, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "head", "offset": 0, "slot": "0", "type": "t_uint64" }, { - "astId": 435, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 444, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "tail", "offset": 8, "slot": "0", @@ -495,61 +532,61 @@ ], "numberOfBytes": "32" }, - "t_struct(RedelegationQueueEntry)422_storage": { + "t_struct(RedelegationQueueEntry)431_storage": { "encoding": "inplace", "label": "struct StakingStorage.RedelegationQueueEntry", "members": [ { - "astId": 409, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 418, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "completionTime", "offset": 0, "slot": "0", "type": "t_uint64" }, { - "astId": 411, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 420, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "delegator", "offset": 8, "slot": "0", "type": "t_address" }, { - "astId": 413, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 422, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "creationHeight", "offset": 0, "slot": "1", "type": "t_uint64" }, { - "astId": 415, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 424, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "srcValidator", "offset": 8, "slot": "1", "type": "t_address" }, { - "astId": 417, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 426, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "dstValidator", "offset": 0, "slot": "2", "type": "t_address" }, { - "astId": 419, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 428, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "initialBalance", "offset": 0, "slot": "3", "type": "t_uint256" }, { - "astId": 421, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 430, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "sharesDst", "offset": 0, "slot": "4", @@ -558,37 +595,37 @@ ], "numberOfBytes": "160" }, - "t_struct(UnbondingDelegationEntry)398_storage": { + "t_struct(UnbondingDelegationEntry)407_storage": { "encoding": "inplace", "label": "struct StakingStorage.UnbondingDelegationEntry", "members": [ { - "astId": 391, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 400, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "creationHeight", "offset": 0, "slot": "0", "type": "t_uint64" }, { - "astId": 393, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 402, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "completionTime", "offset": 8, "slot": "0", "type": "t_uint64" }, { - "astId": 395, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 404, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "initialBalance", "offset": 0, "slot": "1", "type": "t_uint256" }, { - "astId": 397, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 406, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "balance", "offset": 0, "slot": "2", @@ -597,29 +634,29 @@ ], "numberOfBytes": "96" }, - "t_struct(UnbondingQueueEntry)406_storage": { + "t_struct(UnbondingQueueEntry)415_storage": { "encoding": "inplace", "label": "struct StakingStorage.UnbondingQueueEntry", "members": [ { - "astId": 401, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 410, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "completionTime", "offset": 0, "slot": "0", "type": "t_uint64" }, { - "astId": 403, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 412, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "delegator", "offset": 8, "slot": "0", "type": "t_address" }, { - "astId": 405, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 414, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "validator", "offset": 0, "slot": "1", @@ -628,85 +665,85 @@ ], "numberOfBytes": "64" }, - "t_struct(Validator)380_storage": { + "t_struct(Validator)381_storage": { "encoding": "inplace", "label": "struct StakingStorage.Validator", "members": [ { - "astId": 359, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 360, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "consensusPubkey", "offset": 0, "slot": "0", "type": "t_bytes32" }, { - "astId": 361, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 362, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "jailed", "offset": 0, "slot": "1", "type": "t_bool" }, { - "astId": 363, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 364, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "status", "offset": 1, "slot": "1", "type": "t_uint8" }, { - "astId": 365, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 366, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "tokens", "offset": 0, "slot": "2", "type": "t_uint256" }, { - "astId": 367, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 368, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "delegatorShares", "offset": 0, "slot": "3", "type": "t_uint256" }, { - "astId": 370, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 371, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "description", "offset": 0, "slot": "4", - "type": "t_struct(Description)344_storage" + "type": "t_struct(Description)345_storage" }, { - "astId": 372, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 373, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "unbondingHeight", "offset": 0, "slot": "9", "type": "t_uint64" }, { - "astId": 374, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 375, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "unbondingTime", "offset": 8, "slot": "9", "type": "t_uint64" }, { - "astId": 377, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 378, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "commission", "offset": 0, "slot": "10", - "type": "t_struct(Commission)357_storage" + "type": "t_struct(Commission)358_storage" }, { - "astId": 379, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 380, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "minSelfDelegation", "offset": 0, "slot": "14", @@ -715,21 +752,21 @@ ], "numberOfBytes": "480" }, - "t_struct(ValidatorPower)386_storage": { + "t_struct(ValidatorPower)387_storage": { "encoding": "inplace", "label": "struct StakingStorage.ValidatorPower", "members": [ { - "astId": 383, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 384, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "operator", "offset": 0, "slot": "0", "type": "t_address" }, { - "astId": 385, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 386, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "power", "offset": 20, "slot": "0", @@ -738,29 +775,29 @@ ], "numberOfBytes": "32" }, - "t_struct(ValidatorQueueEntry)430_storage": { + "t_struct(ValidatorQueueEntry)439_storage": { "encoding": "inplace", "label": "struct StakingStorage.ValidatorQueueEntry", "members": [ { - "astId": 425, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 434, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "completionTime", "offset": 0, "slot": "0", "type": "t_uint64" }, { - "astId": 427, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 436, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "unbondingHeight", "offset": 8, "slot": "0", "type": "t_uint64" }, { - "astId": 429, - "contract": "giga-storage/StakingStorage.sol:StakingStorage", + "astId": 438, + "contract": "docs/giga-storage/StakingStorage.sol:StakingStorage", "label": "operator", "offset": 0, "slot": "1", From 24acfa7b68e3f97f9f306f3faf1d9dd6e4756b12 Mon Sep 17 00:00:00 2001 From: Tony Chen Date: Tue, 17 Nov 2026 13:19:29 +0800 Subject: [PATCH 44/44] feat(evmonly): serve staking's current bonded set as the validator set Autobahn keeps the committee it derives in its own epoch state, so what it needs from the app is the bonded set as it stands. GetValidators reads staking's lastValidators through BondedValidators again, and the epoch snapshot stays for rewards, built from the same read. Co-Authored-By: Claude Opus 5.5 --- docs/giga-storage/staking-design-rationale.md | 30 ++++++++-------- .../evmonly/precompiles/staking/bonded_set.go | 27 ++++++++++++++ .../precompiles/staking/bonded_set_test.go | 35 +++++++++++++++++++ giga/evmonly/precompiles/staking/endblock.go | 18 +++------- .../internal/evmonlyapp/app_test.go | 29 +++++++++++++++ .../internal/evmonlyapp/validators.go | 21 ++++++----- .../internal/evmonlyapp/validators_test.go | 33 ++++++----------- .../internal/p2p/giga_router_common.go | 6 ++-- 8 files changed, 133 insertions(+), 66 deletions(-) diff --git a/docs/giga-storage/staking-design-rationale.md b/docs/giga-storage/staking-design-rationale.md index 77cb048446..ee475c4b83 100644 --- a/docs/giga-storage/staking-design-rationale.md +++ b/docs/giga-storage/staking-design-rationale.md @@ -293,24 +293,22 @@ that cost is small. ### The epoch snapshot V2 hands CometBFT a new validator set every block. Autobahn changes its -committee once per epoch, and derives epoch E+2's committee from the set it -reads at the end of epoch E's last block. The node reads the set outside block -execution, at whatever height the app has reached by then, so the set it gets -could differ from node to node. +committee once per epoch: it reads the bonded set after an epoch's last block, +derives the committee two epochs ahead from it, and keeps that committee in +consensus-owned state the precompiles do not read. Rewards need the committee +that served a block. So at the end of an epoch's last block, EndBlock copies `lastValidators`, with -each member's consensus key, into `epochValidators[epoch]`, and the app serves -consensus the latest snapshot. The snapshot is committed state, so every node -serves the same one for an epoch, and a node that state-syncs gets it too. -Consensus marks the block that closes an epoch, so the app never repeats the -epoch length. The keys are copied because a member can leave the bonded set, -finish unbonding with no shares and be removed while its snapshot is still -served. - -The snapshot is also what rewards read: the committee that served a block in -epoch E is the snapshot of epoch E−2. Three are kept, E−2 to E, and EndBlock -deletes the one before them when it takes a new one: about 150 slot writes once -an epoch at 35 validators. +each member's consensus key, into `epochValidators[epoch]`, and the committee +that served a block in epoch E is the snapshot of epoch E−2. The snapshot is +committed state, so every node reads the same one, and a node that state-syncs +gets it too. Consensus marks the block that closes an epoch, so the app never +repeats the epoch length. The keys are copied because a member can leave the +bonded set, finish unbonding with no shares and be removed while its snapshot +is still read. + +Three are kept, E−2 to E, and EndBlock deletes the one before them when it +takes a new one: about 150 slot writes once an epoch at 35 validators. ### Where the structures don't carry over diff --git a/giga/evmonly/precompiles/staking/bonded_set.go b/giga/evmonly/precompiles/staking/bonded_set.go index dfc541b82d..ec9801a899 100644 --- a/giga/evmonly/precompiles/staking/bonded_set.go +++ b/giga/evmonly/precompiles/staking/bonded_set.go @@ -1,6 +1,8 @@ package staking import ( + "fmt" + "github.com/ethereum/go-ethereum/common" "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles" @@ -13,6 +15,13 @@ type BondedValidator struct { Power uint64 } +// BondedValidators returns the bonded set the last EndBlock stored, in the +// order it ranked them, or none before staking has bonded a set. It fails when +// the stored set does not add up. +func BondedValidators(state precompiles.State) ([]BondedValidator, error) { + return bondedValidators(newStore(state)) +} + // EpochValidators returns the bonded set snapshotted at the end of the latest // epoch, in the order it ranked them, or none before the first snapshot. It // fails when the stored set does not add up. @@ -24,3 +33,21 @@ func EpochValidators(state precompiles.State) ([]BondedValidator, error) { } return s.epochValidators(epoch) } + +// bondedValidators returns the bonded set the last EndBlock stored, with each +// member's consensus key. +func bondedValidators(s store) ([]BondedValidator, error) { + last, err := s.lastValidators() + if err != nil { + return nil, err + } + bonded := make([]BondedValidator, len(last)) + for i, v := range last { + pubkey := s.consensusPubkey(v.operator) + if pubkey == (common.Hash{}) { + return nil, fmt.Errorf("%w: %s", errUnknownValidator, v.operator) + } + bonded[i] = BondedValidator{Operator: v.operator, ConsensusPubkey: pubkey, Power: v.power} + } + return bonded, nil +} diff --git a/giga/evmonly/precompiles/staking/bonded_set_test.go b/giga/evmonly/precompiles/staking/bonded_set_test.go index 53930692c0..25b52365c2 100644 --- a/giga/evmonly/precompiles/staking/bonded_set_test.go +++ b/giga/evmonly/precompiles/staking/bonded_set_test.go @@ -10,6 +10,41 @@ import ( "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles/solstorage" ) +func TestBondedValidatorsAreTheSetTheLastEndBlockStored(t *testing.T) { + h := newHarness(t, testParams) + want := []BondedValidator{ + {Operator: val1, ConsensusPubkey: common.BytesToHash(val1[:]), Power: 30}, + {Operator: val2, ConsensusPubkey: common.BytesToHash(val2[:]), Power: 20}, + } + require.Equal(t, want, must(BondedValidators(h.state))) + + require.NoError(t, h.delegate(alice, val3, sei(15))) + require.Equal(t, want, must(BondedValidators(h.state)), "a delegation moves the set only at EndBlock") + h.endBlock() + require.Equal(t, []BondedValidator{ + {Operator: val1, ConsensusPubkey: common.BytesToHash(val1[:]), Power: 30}, + {Operator: val3, ConsensusPubkey: common.BytesToHash(val3[:]), Power: 25}, + }, must(BondedValidators(h.state)), "the set moves at any EndBlock, not only an epoch's last") +} + +func TestNoValidatorsAreBondedBeforeStakingBondsASet(t *testing.T) { + state := newMemState() + require.Empty(t, must(BondedValidators(state))) + require.NoError(t, SetParams(state, testParams)) + require.Empty(t, must(BondedValidators(state))) +} + +func TestBondedValidatorsFailOnAStoredSetThatDoesNotAddUp(t *testing.T) { + h := newHarness(t, testParams) + h.store().setLastValidators([]validatorPower{{val1, 30}, {alice, 20}}) + _, err := BondedValidators(h.state) + require.ErrorIs(t, err, errUnknownValidator, "a member with no validator") + + h.store().SetUint64(solstorage.Slot(slotLastValidators), 0, 101) + _, err = BondedValidators(h.state) + require.ErrorIs(t, err, errInvalidStoredSet, "a set longer than any MaxValidators allows") +} + func TestEpochValidatorsAreTheSetAtTheLatestEpochEnd(t *testing.T) { h := newHarness(t, testParams) require.Empty(t, must(EpochValidators(h.state)), "no epoch has ended") diff --git a/giga/evmonly/precompiles/staking/endblock.go b/giga/evmonly/precompiles/staking/endblock.go index 9215fa23e6..de8ba9985f 100644 --- a/giga/evmonly/precompiles/staking/endblock.go +++ b/giga/evmonly/precompiles/staking/endblock.go @@ -162,28 +162,20 @@ func (p Precompile) applyBondedSet(block precompiles.BlockContext, s store, para return nil } -// epochSnapshotsKept is how many epoch snapshots are kept, as an epoch's -// committee is derived from the snapshot two epochs before it. +// epochSnapshotsKept is how many epoch snapshots are kept, as the committee +// serving an epoch is the bonded set at the end of the epoch two before it. const epochSnapshotsKept = 3 // snapshotEpoch copies the bonded set, with each member's consensus key, into // epoch's snapshot and deletes the one that no longer falls among the latest // epochSnapshotsKept. func snapshotEpoch(s store, epoch uint64) error { - last, err := s.lastValidators() + set, err := bondedValidators(s) if err != nil { return err } - set := make([]BondedValidator, len(last)) - for i, v := range last { - // The key is copied rather than looked up when the snapshot is read, - // because a member can be removed before its snapshot is retired. - pubkey := s.consensusPubkey(v.operator) - if pubkey == (common.Hash{}) { - return fmt.Errorf("%w: %s", errUnknownValidator, v.operator) - } - set[i] = BondedValidator{Operator: v.operator, ConsensusPubkey: pubkey, Power: v.power} - } + // The keys are copied rather than looked up when the snapshot is read, + // because a member can be removed before its snapshot is retired. s.setEpochValidators(epoch, set) if epoch >= epochSnapshotsKept { s.setEpochValidators(epoch-epochSnapshotsKept, nil) diff --git a/sei-tendermint/internal/evmonlyapp/app_test.go b/sei-tendermint/internal/evmonlyapp/app_test.go index fc79fca4ec..63adb4ba3c 100644 --- a/sei-tendermint/internal/evmonlyapp/app_test.go +++ b/sei-tendermint/internal/evmonlyapp/app_test.go @@ -23,6 +23,7 @@ import ( gigaconfig "github.com/sei-protocol/sei-chain/giga/config" "github.com/sei-protocol/sei-chain/giga/evmonly" "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles" + "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles/staking" sdk "github.com/sei-protocol/sei-chain/sei-cosmos/types" "github.com/sei-protocol/sei-chain/sei-db/bootstrap" "github.com/sei-protocol/sei-chain/sei-db/common/keys" @@ -30,6 +31,7 @@ import ( seidbconfig "github.com/sei-protocol/sei-chain/sei-db/config" "github.com/sei-protocol/sei-chain/sei-db/ledger_db/receipt" gigatypes "github.com/sei-protocol/sei-chain/sei-db/state_db/giga/types" + "github.com/sei-protocol/sei-chain/sei-tendermint/autobahn/types" "github.com/sei-protocol/sei-chain/sei-tendermint/internal/proxy" "github.com/sei-protocol/sei-chain/sei-tendermint/libs/utils" "github.com/sei-protocol/sei-chain/sei-tendermint/libs/utils/require" @@ -91,6 +93,33 @@ func evmOnlyTestEpochBlock(height int64, state proxy.EpochState) *proxy.RequestF return req } +// evmOnlyTestClosingBlock returns an empty block at height that closes epoch. +func evmOnlyTestClosingBlock(height int64, epoch types.EpochIndex) *proxy.RequestFinalizeBlock { + req := evmOnlyTestBlock(height) + req.Header.ClosingEpoch = utils.Some(epoch) + return req +} + +// closingEpochRecorder is staking, with each EndBlock only recording the epoch +// its block closes. +type closingEpochRecorder struct { + staking.Precompile + closed *[]utils.Option[uint64] +} + +func (r closingEpochRecorder) EndBlock(block precompiles.BlockContext, _ precompiles.State) ([]error, error) { + *r.closed = append(*r.closed, block.ClosingEpoch) + return nil, nil +} + +func TestEVMOnlyApplicationTellsEndBlockersWhichEpochABlockCloses(t *testing.T) { + var closed []utils.Option[uint64] + app := newStakingEVMOnlyTestApp(t, []proxy.ValidatorUpdate{{Power: 1}}, closingEpochRecorder{closed: &closed}) + finalizeAndCommitEVMOnlyTestBlock(t, app, evmOnlyTestBlock(1)) + finalizeAndCommitEVMOnlyTestBlock(t, app, evmOnlyTestClosingBlock(2, 7)) + require.Equal(t, []utils.Option[uint64]{utils.None[uint64](), utils.Some[uint64](7)}, closed) +} + func finalizeAndCommitEVMOnlyTestBlock(t *testing.T, app proxy.EVMApplication, req *proxy.RequestFinalizeBlock) []byte { t.Helper() response, err := app.FinalizeBlock(t.Context(), req) diff --git a/sei-tendermint/internal/evmonlyapp/validators.go b/sei-tendermint/internal/evmonlyapp/validators.go index e231c25327..52eda7b097 100644 --- a/sei-tendermint/internal/evmonlyapp/validators.go +++ b/sei-tendermint/internal/evmonlyapp/validators.go @@ -12,14 +12,14 @@ import ( "github.com/sei-protocol/sei-chain/sei-tendermint/libs/utils" ) -// GetValidators returns the bonded set staking snapshotted at the end of the -// latest epoch, and the configured validators until it has snapshotted one. It -// returns none once a block is known to have failed to commit or the stored set -// does not add up, and autobahn cannot stage an empty committee. +// GetValidators returns staking's bonded set after the latest finalized block, +// and the configured validators until staking has bonded one. It returns none +// once a block is known to have failed to commit or the stored set does not add +// up, and autobahn cannot stage an empty committee. func (a *evmOnlyApplication) GetValidators() []proxy.ValidatorUpdate { - bonded, err := a.epochValidators() + bonded, err := a.bondedValidators() if err != nil { - logger.Error("EVM-only epoch validator set is unavailable", "err", err) + logger.Error("EVM-only bonded validator set is unavailable", "err", err) return nil } if len(bonded) == 0 { @@ -28,13 +28,12 @@ func (a *evmOnlyApplication) GetValidators() []proxy.ValidatorUpdate { return bonded } -// epochValidators returns the bonded set staking snapshotted at the end of the -// latest epoch, after the latest finalized block, without waiting for that -// block's commit. -func (a *evmOnlyApplication) epochValidators() ([]proxy.ValidatorUpdate, error) { +// bondedValidators returns staking's bonded set after the latest finalized +// block, without waiting for that block's commit. +func (a *evmOnlyApplication) bondedValidators() ([]proxy.ValidatorUpdate, error) { var bonded []staking.BondedValidator read := func(state precompiles.State) (err error) { - bonded, err = staking.EpochValidators(state) + bonded, err = staking.BondedValidators(state) return err } // Autobahn calls this before every block, so it must not hold execution diff --git a/sei-tendermint/internal/evmonlyapp/validators_test.go b/sei-tendermint/internal/evmonlyapp/validators_test.go index e6f0d08529..76ae5f81ee 100644 --- a/sei-tendermint/internal/evmonlyapp/validators_test.go +++ b/sei-tendermint/internal/evmonlyapp/validators_test.go @@ -8,7 +8,6 @@ import ( gigaconfig "github.com/sei-protocol/sei-chain/giga/config" "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles" - "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles/solstorage" "github.com/sei-protocol/sei-chain/giga/evmonly/precompiles/staking" seidbconfig "github.com/sei-protocol/sei-chain/sei-db/config" "github.com/sei-protocol/sei-chain/sei-tendermint/autobahn/types" @@ -39,27 +38,18 @@ func (g stakingGenesis) EndBlock(block precompiles.BlockContext, state precompil return g.Precompile.EndBlock(block, state) } -// corruptEpochSnapshot stores an epoch snapshot longer than staking allows at -// every EndBlock. -type corruptEpochSnapshot struct { +// corruptBondedSet stores a bonded set longer than staking allows at every +// EndBlock. +type corruptBondedSet struct { staking.Precompile } -func (corruptEpochSnapshot) EndBlock(_ precompiles.BlockContext, state precompiles.State) ([]error, error) { - // Slot 2 of StakingStorage maps each epoch to its snapshot, and slot 3 holds - // the epoch after the latest. - state.SetState(staking.Address, solstorage.MapUint64(solstorage.Slot(2), 0), common.BigToHash(big.NewInt(101))) - state.SetState(staking.Address, solstorage.Slot(3), common.BigToHash(big.NewInt(1))) +func (corruptBondedSet) EndBlock(_ precompiles.BlockContext, state precompiles.State) ([]error, error) { + // Slot 0 of StakingStorage holds the bonded set's length. + state.SetState(staking.Address, common.Hash{}, common.BigToHash(big.NewInt(101))) return nil, nil } -// evmOnlyTestClosingBlock returns an empty block at height that closes epoch. -func evmOnlyTestClosingBlock(height int64, epoch types.EpochIndex) *proxy.RequestFinalizeBlock { - req := evmOnlyTestBlock(height) - req.Header.ClosingEpoch = utils.Some(epoch) - return req -} - // newStakingEVMOnlyTestApp returns an initialized application serving the // configured validators and running staking as contract. func newStakingEVMOnlyTestApp(t *testing.T, configured []proxy.ValidatorUpdate, contract precompiles.Contract) proxy.EVMApplication { @@ -98,7 +88,7 @@ func testGenesisValidator(operator common.Address, key ed25519.PublicKey, self i } } -func TestEVMOnlyApplicationServesStakingsSetAtEachEpochEnd(t *testing.T) { +func TestEVMOnlyApplicationServesStakingsBondedSet(t *testing.T) { configured := []proxy.ValidatorUpdate{{PubKey: autobahnKey(ed25519.TestSecretKey([]byte("configured")).Public()), Power: 1}} key1 := ed25519.TestSecretKey([]byte("validator-1")).Public() key2 := ed25519.TestSecretKey([]byte("validator-2")).Public() @@ -106,12 +96,9 @@ func TestEVMOnlyApplicationServesStakingsSetAtEachEpochEnd(t *testing.T) { testGenesisValidator(common.HexToAddress("0xa2"), key2, 20), testGenesisValidator(common.HexToAddress("0xa1"), key1, 30), }}) - require.Equal(t, configured, app.GetValidators(), "the configured validators serve until staking snapshots a set") + require.Equal(t, configured, app.GetValidators(), "the configured validators serve until staking bonds a set") finalizeAndCommitEVMOnlyTestBlock(t, app, evmOnlyTestBlock(1)) - require.Equal(t, configured, app.GetValidators(), "staking bonded a set, but no epoch has ended") - - finalizeAndCommitEVMOnlyTestBlock(t, app, evmOnlyTestClosingBlock(2, 0)) require.Equal(t, []proxy.ValidatorUpdate{ {PubKey: autobahnKey(key1), Power: 30}, {PubKey: autobahnKey(key2), Power: 20}, @@ -139,8 +126,8 @@ func TestEVMOnlyApplicationServesNoValidatorsAfterAFailedCommit(t *testing.T) { require.Empty(t, app.GetValidators(), "block 1 failed to commit, so the committed state predates it") } -func TestEVMOnlyApplicationServesNoValidatorsFromACorruptEpochSnapshot(t *testing.T) { - app := newStakingEVMOnlyTestApp(t, []proxy.ValidatorUpdate{{Power: 1}}, corruptEpochSnapshot{}) +func TestEVMOnlyApplicationServesNoValidatorsFromACorruptBondedSet(t *testing.T) { + app := newStakingEVMOnlyTestApp(t, []proxy.ValidatorUpdate{{Power: 1}}, corruptBondedSet{}) finalizeAndCommitEVMOnlyTestBlock(t, app, evmOnlyTestBlock(1)) require.Empty(t, app.GetValidators()) } diff --git a/sei-tendermint/internal/p2p/giga_router_common.go b/sei-tendermint/internal/p2p/giga_router_common.go index ed4d29ff57..dadbee133f 100644 --- a/sei-tendermint/internal/p2p/giga_router_common.go +++ b/sei-tendermint/internal/p2p/giga_router_common.go @@ -194,9 +194,9 @@ func (r *gigaRouterCommon) runPushAppHashes(ctx context.Context) error { } // PushAppHash needs the validator set from right after block n, and uses it // only when n closes an epoch. GetValidators() reads the app tip, which can - // be past n. The EVM-only app serves the set it snapshotted when the latest - // epoch closed, which is block n's until the tip closes the next one, and - // the mock app's set never changes. + // be past n, so the set is block n's only while no later block has changed + // it. The mock app's set never changes; the EVM-only app's can change at + // any block. // TODO: ask the app for the set as of block n, to drop that bound. weights, err := committeeWeights(r.app.GetValidators()) if err != nil {