Skip to content

Commit

Permalink
feat(evmstaking): replace staking keeper endblocker (#209)
Browse files Browse the repository at this point in the history
  • Loading branch information
0xHansLee authored and leeren committed Oct 16, 2024
1 parent 441265b commit 0216074
Show file tree
Hide file tree
Showing 4 changed files with 15 additions and 90 deletions.
98 changes: 11 additions & 87 deletions client/x/evmstaking/keeper/abci.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@ import (
"context"
"time"

"cosmossdk.io/math"

abci "github.com/cometbft/cometbft/abci/types"
"github.com/cosmos/cosmos-sdk/telemetry"
sdk "github.com/cosmos/cosmos-sdk/types"
Expand All @@ -15,12 +13,6 @@ import (
"github.com/piplabs/story/lib/log"
)

type UnbondedEntry struct {
validatorAddress string
delegatorAddress string
amount math.Int
}

// Query staking module's UnbondingDelegation (UBD Queue) to get the matured unbonding delegations. Then,
// insert the matured unbonding delegations into the withdrawal queue.
// TODO: check if unbonded delegations in staking module must be distinguished based on source of generation, CL or EL.
Expand All @@ -29,96 +21,28 @@ func (k *Keeper) EndBlock(ctx context.Context) (abci.ValidatorUpdates, error) {
defer telemetry.ModuleMeasureSince(types.ModuleName, time.Now(), telemetry.MetricKeyEndBlocker)

sdkCtx := sdk.UnwrapSDKContext(ctx)
ctxTime := sdkCtx.BlockHeader().Time
blockHeight := sdkCtx.BlockHeader().Height

matureUnbonds, err := k.GetMatureUnbondedDelegations(ctx)
log.Debug(ctx, "Processing mature unbonding delegations", "count", len(matureUnbonds))
valUpdates, unbondedEntries, err := k.stakingKeeper.EndBlockerWithUnbondedEntries(ctx)
if err != nil {
return nil, err
}

// make an array with each entry being the validator address, delegator address, and the amount
var unbondedEntries []UnbondedEntry

for _, dvPair := range matureUnbonds {
validatorAddr, err := k.validatorAddressCodec.StringToBytes(dvPair.ValidatorAddress)
if err != nil {
return nil, errors.Wrap(err, "validator address from bech32")
}

delegatorAddr, err := k.authKeeper.AddressCodec().StringToBytes(dvPair.DelegatorAddress)
if err != nil {
return nil, errors.Wrap(err, "delegator address from bech32")
}

ubd, err := (k.stakingKeeper).GetUnbondingDelegation(ctx, delegatorAddr, validatorAddr)
if err != nil {
return nil, err
}

// TODO: parameterized bondDenom
bondDenom := sdk.DefaultBondDenom

// loop through all the entries and process unbonding mature entries
for i := range len(ubd.Entries) {
entry := ubd.Entries[i]
if entry.IsMature(ctxTime) && !entry.OnHold() {
// track undelegation only when remaining or truncated shares are non-zero
if !entry.Balance.IsZero() {
amt := sdk.NewCoin(bondDenom, entry.Balance)
// TODO: check if it's possible to add a double entry in the unbondedEntries array
unbondedEntries = append(unbondedEntries, UnbondedEntry{
validatorAddress: dvPair.ValidatorAddress,
delegatorAddress: dvPair.DelegatorAddress,
amount: amt.Amount,
})
}
}
}
}

valUpdates, err := k.stakingKeeper.EndBlocker(ctx)
if err != nil {
return nil, err
}
log.Debug(ctx, "Processing mature unbonding delegations", "count", len(unbondedEntries))

for _, entry := range unbondedEntries {
delegatorAddr, err := k.authKeeper.AddressCodec().StringToBytes(entry.delegatorAddress)
delegatorAddr, err := k.authKeeper.AddressCodec().StringToBytes(entry.DelegatorAddress)
if err != nil {
return nil, errors.Wrap(err, "delegator address from bech32")
}

spendableAmount := k.bankKeeper.SpendableCoin(ctx, delegatorAddr, sdk.DefaultBondDenom).Amount
if spendableAmount.IsZero() {
log.Warn(ctx, "No spendable coins for undelegation",
errors.New("no spendable coins for undelegation"),
"delegator", entry.delegatorAddress,
"validator", entry.validatorAddress,
"original_amount", entry.amount.String())

continue
}

// If the requested undelegation amount is greater than the spendable amount, set the real undelegation amount to
// the total spendable amount.
if entry.amount.GT(spendableAmount) {
entry.amount = spendableAmount
log.Warn(ctx, "Spendable amount is less than the requested undelegation amount",
errors.New("spendable amount is less than the requested undelegation amount"),
"delegator", entry.delegatorAddress,
"validator", entry.validatorAddress,
"requested_amount", entry.amount.String(),
"spendable_amount", spendableAmount.String())
}

log.Debug(ctx, "Adding undelegation to withdrawal queue",
"delegator", entry.delegatorAddress,
"validator", entry.validatorAddress,
"amount", entry.amount.String())
"delegator", entry.DelegatorAddress,
"validator", entry.ValidatorAddress,
"amount", entry.Amount.String())

// Burn tokens from the delegator
_, coins := IPTokenToBondCoin(entry.amount.BigInt())
_, coins := IPTokenToBondCoin(entry.Amount.BigInt())
err = k.bankKeeper.SendCoinsFromAccountToModule(ctx, delegatorAddr, types.ModuleName, coins)
if err != nil {
return nil, errors.Wrap(err, "send coins from account to module")
Expand All @@ -130,18 +54,18 @@ func (k *Keeper) EndBlock(ctx context.Context) (abci.ValidatorUpdates, error) {

// This should not produce error, as all delegations are done via the evmstaking module via EL.
// However, we should gracefully handle in case Get fails.
delEvmAddr, err := k.DelegatorMap.Get(ctx, entry.delegatorAddress)
delEvmAddr, err := k.DelegatorMap.Get(ctx, entry.DelegatorAddress)
if err != nil {
return nil, errors.Wrap(err, "map delegator pubkey to evm address")
}

// push the undelegation to the withdrawal queue
err = k.AddWithdrawalToQueue(ctx, types.NewWithdrawal(
uint64(blockHeight),
entry.delegatorAddress,
entry.validatorAddress,
entry.DelegatorAddress,
entry.ValidatorAddress,
delEvmAddr,
entry.amount.Uint64(),
entry.Amount.Uint64(),
))
if err != nil {
return nil, err
Expand Down
1 change: 1 addition & 0 deletions client/x/evmstaking/types/expected_keepers.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ type StakingKeeper interface {
GetUnbondingDelegationsFromValidator(ctx context.Context, valAddr sdk.ValAddress) (ubds []stakingtypes.UnbondingDelegation, err error)

EndBlocker(ctx context.Context) ([]abci.ValidatorUpdate, error)
EndBlockerWithUnbondedEntries(ctx context.Context) ([]abci.ValidatorUpdate, []stakingtypes.UnbondedEntry, error)
}

// SlashingKeeper defines the expected interface for the slashing module.
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,7 @@ replace (
cosmossdk.io/core v0.12.0 => cosmossdk.io/core v0.11.0

// Direct cosmos-sdk branch link: https://github.com/piplabs/cosmos-sdk/tree/story/v0.50.7, current branch: story/v0.50.7
github.com/cosmos/cosmos-sdk => github.com/piplabs/cosmos-sdk v0.50.7-piplabs-v0.3
github.com/cosmos/cosmos-sdk => github.com/piplabs/cosmos-sdk v0.50.7-piplabs-v0.4

// See https://github.com/cosmos/cosmos-sdk/pull/14952
// Also https://github.com/cosmos/cosmos-db/blob/main/go.mod#L11-L12
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -1032,8 +1032,8 @@ github.com/pierrec/lz4 v1.0.2-0.20190131084431-473cd7ce01a1/go.mod h1:3/3N9NVKO0
github.com/pierrec/lz4 v2.0.5+incompatible/go.mod h1:pdkljMzZIN41W+lC3N2tnIh5sFi+IEE17M5jbnwPHcY=
github.com/pingcap/errors v0.11.4 h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4=
github.com/pingcap/errors v0.11.4/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTwv5KuLY8=
github.com/piplabs/cosmos-sdk v0.50.7-piplabs-v0.3 h1:psxK/SkuqErPFobiYxuqSgW3gPw/xhDlTWQ36X5dhaU=
github.com/piplabs/cosmos-sdk v0.50.7-piplabs-v0.3/go.mod h1:84xDDJEHttRT7NDGwBaUOLVOMN0JNE9x7NbsYIxXs1s=
github.com/piplabs/cosmos-sdk v0.50.7-piplabs-v0.4 h1:EyX4nVJm08vx0/srAuA2kfSVrTfnhNAhF0uB/gT66yE=
github.com/piplabs/cosmos-sdk v0.50.7-piplabs-v0.4/go.mod h1:84xDDJEHttRT7NDGwBaUOLVOMN0JNE9x7NbsYIxXs1s=
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ=
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU=
github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=
Expand Down

0 comments on commit 0216074

Please sign in to comment.