Skip to content

Commit

Permalink
feat(evmstaking): revert epoch staking (#192)
Browse files Browse the repository at this point in the history
  • Loading branch information
0xHansLee authored Oct 14, 2024
1 parent a9e7026 commit ca8cc46
Show file tree
Hide file tree
Showing 39 changed files with 257 additions and 1,958 deletions.
28 changes: 28 additions & 0 deletions client/x/evmengine/testutil/expected_keepers_mocks.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions client/x/evmengine/types/expected_keepers.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ type AccountKeeper interface {
}

type EvmStakingKeeper interface {
ProcessDeposit(ctx context.Context, ev *bindings.IPTokenStakingDeposit) error
ProcessWithdraw(ctx context.Context, ev *bindings.IPTokenStakingWithdraw) error
DequeueEligibleWithdrawals(ctx context.Context) (ethtypes.Withdrawals, error)
ParseDepositLog(ethlog ethtypes.Log) (*bindings.IPTokenStakingDeposit, error)
ParseWithdrawLog(ethlog ethtypes.Log) (*bindings.IPTokenStakingWithdraw, error)
Expand Down
170 changes: 72 additions & 98 deletions client/x/evmstaking/keeper/abci.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,125 +28,99 @@ func (k *Keeper) EndBlock(ctx context.Context) (abci.ValidatorUpdates, error) {
log.Debug(ctx, "EndBlock.evmstaking")
defer telemetry.ModuleMeasureSince(types.ModuleName, time.Now(), telemetry.MetricKeyEndBlocker)

var valUpdates []abci.ValidatorUpdate
sdkCtx := sdk.UnwrapSDKContext(ctx)
ctxTime := sdkCtx.BlockHeader().Time
blockHeight := sdkCtx.BlockHeader().Height

isNextEpoch, err := k.IsNextEpoch(ctx)
matureUnbonds, err := k.GetMatureUnbondedDelegations(ctx)
log.Debug(ctx, "Processing mature unbonding delegations", "count", len(matureUnbonds))
if err != nil {
return nil, errors.Wrap(err, "check if the next epoch starts")
return nil, err
}

if isNextEpoch { //nolint:nestif // readability
sdkCtx := sdk.UnwrapSDKContext(ctx)
ctxTime := sdkCtx.BlockHeader().Time
blockHeight := sdkCtx.BlockHeader().Height
// make an array with each entry being the validator address, delegator address, and the amount
var unbondedEntries []UnbondedEntry

matureUnbonds, err := k.GetMatureUnbondedDelegations(ctx)
log.Debug(ctx, "Processing mature unbonding delegations", "count", len(matureUnbonds))
for _, dvPair := range matureUnbonds {
validatorAddr, err := k.validatorAddressCodec.StringToBytes(dvPair.ValidatorAddress)
if err != nil {
return nil, err
return nil, errors.Wrap(err, "validator address from bech32")
}

// 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")
}
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
}
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,
})
}
// 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,
})
}
}
}
}

// Update validator set
// process all queued messages
if err := k.ProcessAllMsgs(ctx); err != nil {
return nil, errors.Wrap(err, "get current epoch queued messages")
}
valUpdates, err := k.stakingKeeper.EndBlocker(ctx)
if err != nil {
return nil, err
}

// if it is epoch based, increase epoch number
if err := k.IncCurEpochNumber(ctx); err != nil {
return nil, errors.Wrap(err, "increase current epoch number")
}
for _, entry := range unbondedEntries {
log.Debug(ctx, "Adding undelegation to withdrawal queue",
"delegator", entry.delegatorAddress,
"validator", entry.validatorAddress,
"amount", entry.amount.String())

// update val set
valUpdates, err = k.stakingKeeper.EndBlocker(ctx)
delegatorAddr, err := k.authKeeper.AddressCodec().StringToBytes(entry.delegatorAddress)
if err != nil {
return nil, errors.Wrap(err, "update validator set")
return nil, errors.Wrap(err, "delegator address from bech32")
}

// init message queue
if err := k.MessageQueue.Initialize(ctx); err != nil {
return nil, errors.Wrap(err, "initialize message queue")
// Burn tokens from the delegator
_, 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")
}
err = k.bankKeeper.BurnCoins(ctx, types.ModuleName, coins)
if err != nil {
return nil, errors.Wrap(err, "burn coins")
}

for _, entry := range unbondedEntries {
log.Debug(ctx, "Adding undelegation to withdrawal queue",
"delegator", entry.delegatorAddress,
"validator", entry.validatorAddress,
"amount", entry.amount.String())

delegatorAddr, err := k.authKeeper.AddressCodec().StringToBytes(entry.delegatorAddress)
if err != nil {
return nil, errors.Wrap(err, "delegator address from bech32")
}
// Burn tokens from the delegator
_, 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")
}
err = k.bankKeeper.BurnCoins(ctx, types.ModuleName, coins)
if err != nil {
return nil, errors.Wrap(err, "burn coins")
}

// 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)
if err != nil {
return nil, errors.Wrap(err, "map delegator pubkey to evm address")
}
// 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)
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,
delEvmAddr,
entry.amount.Uint64(),
))
if err != nil {
return nil, err
}
// push the undelegation to the withdrawal queue
err = k.AddWithdrawalToQueue(ctx, types.NewWithdrawal(
uint64(blockHeight),
entry.delegatorAddress,
entry.validatorAddress,
delEvmAddr,
entry.amount.Uint64(),
))
if err != nil {
return nil, err
}
}

Expand Down
6 changes: 4 additions & 2 deletions client/x/evmstaking/keeper/abci_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -242,8 +242,9 @@ func (s *TestSuite) TestEndBlock() {
pastHeader.Time = pastHeader.Time.Add(-ubdTime).Add(-time.Minute)
s.setupUnbonding(sdkCtx.WithBlockHeader(pastHeader), delAddr, valAddr1, "10")

// Mock evmstaking.EndBlocker
// Mock staking.EndBlocker
s.BankKeeper.EXPECT().UndelegateCoinsFromModuleToAccount(gomock.Any(), stypes.NotBondedPoolName, delAddr, gomock.Any()).Return(nil)
// Mock evmstaking.EndBlocker
s.BankKeeper.EXPECT().SendCoinsFromAccountToModule(gomock.Any(), delAddr, types.ModuleName, gomock.Any()).Return(errors.New("failed to send coins to module"))

return nil, []abcitypes.ValidatorUpdate{
Expand All @@ -267,8 +268,9 @@ func (s *TestSuite) TestEndBlock() {
pastHeader.Time = pastHeader.Time.Add(-ubdTime).Add(-time.Minute)
s.setupUnbonding(sdkCtx.WithBlockHeader(pastHeader), delAddr, valAddr1, "10")

// Mock evmstaking.EndBlocker
// Mock staking.EndBlocker
s.BankKeeper.EXPECT().UndelegateCoinsFromModuleToAccount(gomock.Any(), stypes.NotBondedPoolName, delAddr, gomock.Any()).Return(nil)
// Mock evmstaking.EndBlocker
s.BankKeeper.EXPECT().SendCoinsFromAccountToModule(gomock.Any(), delAddr, types.ModuleName, gomock.Any()).Return(nil)
s.BankKeeper.EXPECT().BurnCoins(gomock.Any(), types.ModuleName, gomock.Any()).Return(errors.New("failed to burn coins"))

Expand Down
74 changes: 25 additions & 49 deletions client/x/evmstaking/keeper/deposit.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package keeper
import (
"context"

"github.com/cometbft/cometbft/crypto/tmhash"
sdk "github.com/cosmos/cosmos-sdk/types"
skeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper"
stypes "github.com/cosmos/cosmos-sdk/x/staking/types"
Expand All @@ -16,8 +15,7 @@ import (
"github.com/piplabs/story/lib/log"
)

// HandleDepositEvent handles Deposit event. It converts the event to sdk.Msg and enqueues for epoched staking.
func (k Keeper) HandleDepositEvent(ctx context.Context, ev *bindings.IPTokenStakingDeposit) error {
func (k Keeper) ProcessDeposit(ctx context.Context, ev *bindings.IPTokenStakingDeposit) error {
depositorPubkey, err := k1util.PubKeyBytesToCosmos(ev.DelegatorCmpPubkey)
if err != nil {
return errors.Wrap(err, "depositor pubkey to cosmos")
Expand All @@ -40,65 +38,41 @@ func (k Keeper) HandleDepositEvent(ctx context.Context, ev *bindings.IPTokenStak
return errors.Wrap(err, "delegator pubkey to evm address")
}

amountCoin, _ := IPTokenToBondCoin(ev.Amount)

// Note that, after minting, we save the mapping between delegator bech32 address and evm address, which will be used in the withdrawal queue.
// The saving is done regardless of any error below, as the money is already minted and sent to the delegator, who can withdraw the minted amount.
// TODO: Confirm that bech32 address and evm address can be used interchangeably. Must be one-to-one or many-bech32-to-one-evm.
if err := k.DelegatorMap.Set(ctx, depositorAddr.String(), delEvmAddr.String()); err != nil {
return errors.Wrap(err, "set delegator map")
}

log.Debug(ctx, "EVM staking deposit detected, delegating to validator",
"del_story", depositorAddr.String(),
"val_story", validatorAddr.String(),
"del_evm_addr", delEvmAddr.String(),
"val_evm_addr", valEvmAddr.String(),
"amount_coin", amountCoin.String(),
)

sdkCtx := sdk.UnwrapSDKContext(ctx)
header := sdkCtx.BlockHeader()
txID := tmhash.Sum(sdkCtx.TxBytes())

msg := stypes.NewMsgDelegate(depositorAddr.String(), validatorAddr.String(), amountCoin)
qMsg, err := types.NewQueuedMessage(uint64(header.Height), header.Time, txID, msg)
if err != nil {
return errors.Wrap(err, "new queued message for Delegate event")
}

if err := k.EnqueueMsg(ctx, qMsg); err != nil {
return errors.Wrap(err, "enqueue Delegate message")
}

return nil
}

// ProcessDepositMsg processes the Delegate message. It makes delegation.
func (k Keeper) ProcessDepositMsg(ctx context.Context, msg *stypes.MsgDelegate) error {
amountCoins := sdk.Coins{msg.Amount}
delegatorAddr, err := sdk.AccAddressFromBech32(msg.DelegatorAddress)
if err != nil {
return errors.Wrap(err, "acc address from bech32", "delegator_addr", msg.DelegatorAddress)
}
amountCoin, amountCoins := IPTokenToBondCoin(ev.Amount)

// Create account if not exists
if !k.authKeeper.HasAccount(ctx, delegatorAddr) {
acc := k.authKeeper.NewAccountWithAddress(ctx, delegatorAddr)
if !k.authKeeper.HasAccount(ctx, depositorAddr) {
acc := k.authKeeper.NewAccountWithAddress(ctx, depositorAddr)
k.authKeeper.SetAccount(ctx, acc)
log.Debug(ctx, "Created account for depositor",
"address", delegatorAddr.String(),
"address", depositorAddr.String(),
"evm_address", delEvmAddr.String(),
)
}

if err := k.bankKeeper.MintCoins(ctx, types.ModuleName, amountCoins); err != nil {
return errors.Wrap(err, "create stake coin for depositor: mint coins")
}

if err := k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, delegatorAddr, amountCoins); err != nil {
if err := k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, depositorAddr, amountCoins); err != nil {
return errors.Wrap(err, "create stake coin for depositor: send coins")
}

log.Info(ctx, "EVM staking deposit detected, delegating to validator",
"del_story", depositorAddr.String(),
"val_story", validatorAddr.String(),
"del_evm_addr", delEvmAddr.String(),
"val_evm_addr", valEvmAddr.String(),
"amount_coin", amountCoin.String(),
)

// Note that, after minting, we save the mapping between delegator bech32 address and evm address, which will be used in the withdrawal queue.
// The saving is done regardless of any error below, as the money is already minted and sent to the delegator, who can withdraw the minted amount.
// TODO: Confirm that bech32 address and evm address can be used interchangeably. Must be one-to-one or many-bech32-to-one-evm.
if err := k.DelegatorMap.Set(ctx, depositorAddr.String(), delEvmAddr.String()); err != nil {
return errors.Wrap(err, "set delegator map")
}

// TODO: Check if we can instantiate the msgServer without type assertion
evmstakingSKeeper, ok := k.stakingKeeper.(*skeeper.Keeper)
if !ok {
Expand All @@ -107,7 +81,9 @@ func (k Keeper) ProcessDepositMsg(ctx context.Context, msg *stypes.MsgDelegate)
skeeperMsgServer := skeeper.NewMsgServerImpl(evmstakingSKeeper)

// Delegation by the depositor on the validator (validator existence is checked in msgServer.Delegate)
if _, err = skeeperMsgServer.Delegate(ctx, msg); err != nil {
msg := stypes.NewMsgDelegate(depositorAddr.String(), validatorAddr.String(), amountCoin)
_, err = skeeperMsgServer.Delegate(ctx, msg)
if err != nil {
return errors.Wrap(err, "delegate")
}

Expand Down
6 changes: 1 addition & 5 deletions client/x/evmstaking/keeper/deposit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -207,11 +207,7 @@ func (s *TestSuite) TestProcessDeposit() {
tc.settingMock()
}
cachedCtx, _ := ctx.CacheContext()
var err error
err = keeper.HandleDepositEvent(cachedCtx, tc.deposit)
if !keeper.MessageQueue.IsEmpty(cachedCtx) {
err = s.processQueuedMessage(cachedCtx)
}
err := keeper.ProcessDeposit(cachedCtx, tc.deposit)
if tc.expectedErr != "" {
require.ErrorContains(err, tc.expectedErr)
} else {
Expand Down
Loading

0 comments on commit ca8cc46

Please sign in to comment.