Skip to content

Commit

Permalink
Estaking simplify and handle errors (#1012)
Browse files Browse the repository at this point in the history
* simplify

* handle error properly

* remove
  • Loading branch information
amityadav0 authored Dec 3, 2024
1 parent 7b89d6a commit fece87e
Show file tree
Hide file tree
Showing 6 changed files with 48 additions and 79 deletions.
1 change: 1 addition & 0 deletions x/commitment/keeper/msg_server_cancel_vest.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package keeper

import (
"context"

sdkmath "cosmossdk.io/math"

errorsmod "cosmossdk.io/errors"
Expand Down
30 changes: 19 additions & 11 deletions x/estaking/keeper/abci.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,18 @@ import (
)

// EndBlocker of incentive module
func (k Keeper) EndBlocker(ctx sdk.Context) {
func (k Keeper) EndBlocker(ctx sdk.Context) error {
// Rewards distribution
k.ProcessRewardsDistribution(ctx)
err := k.ProcessRewardsDistribution(ctx)
if err != nil {
return err
}
// Burn EdenB tokens if staking changed
k.BurnEdenBIfElysStakingReduced(ctx)
err = k.BurnEdenBIfElysStakingReduced(ctx)
if err != nil {
return err
}
return nil
}

func (k Keeper) TakeDelegationSnapshot(ctx sdk.Context, addr sdk.AccAddress) {
Expand All @@ -32,27 +39,28 @@ func (k Keeper) TakeDelegationSnapshot(ctx sdk.Context, addr sdk.AccAddress) {
k.SetElysStaked(ctx, elysStaked)
}

func (k Keeper) BurnEdenBIfElysStakingReduced(ctx sdk.Context) {
func (k Keeper) BurnEdenBIfElysStakingReduced(ctx sdk.Context) error {
addrs := k.GetAllElysStakeChange(ctx)

// Handle addresses recorded on AfterDelegationModified
// This hook is exposed for genesis delegations as well
for _, delAddr := range addrs {
k.BurnEdenBFromElysUnstaking(ctx, delAddr)
err := k.BurnEdenBFromElysUnstaking(ctx, delAddr)
if err != nil {
return err
}
k.TakeDelegationSnapshot(ctx, delAddr)
k.RemoveElysStakeChange(ctx, delAddr)
}
return nil
}

// Rewards distribution
func (k Keeper) ProcessRewardsDistribution(ctx sdk.Context) {
func (k Keeper) ProcessRewardsDistribution(ctx sdk.Context) error {
// Read tokenomics time based inflation params and update incentive module params.
k.ProcessUpdateIncentiveParams(ctx)

err := k.UpdateStakersRewards(ctx)
if err != nil {
ctx.Logger().Error("Failed to update staker rewards unclaimed", "error", err)
}
return k.UpdateStakersRewards(ctx)
}

func (k Keeper) ProcessUpdateIncentiveParams(ctx sdk.Context) {
Expand Down Expand Up @@ -117,7 +125,6 @@ func (k Keeper) UpdateStakersRewards(ctx sdk.Context) error {
}
stakersEdenAmount := edenAmountPerYear.Quo(math.NewInt(totalBlocksPerYear))

// Maximum eden APR - 30% by default
totalElysEdenEdenBStake, err := k.TotalBondedTokens(ctx)
if err != nil {
return err
Expand All @@ -128,6 +135,7 @@ func (k Keeper) UpdateStakersRewards(ctx sdk.Context) error {
return err
}

// Maximum eden APR - 30% by default
stakersMaxEdenAmount := params.MaxEdenRewardAprStakers.
MulInt(totalElysEdenStake).
QuoInt64(totalBlocksPerYear)
Expand Down
31 changes: 18 additions & 13 deletions x/estaking/keeper/keeper_burn_edenB.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,19 @@ package keeper
import (
"cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/elys-network/elys/x/estaking/types"
ptypes "github.com/elys-network/elys/x/parameter/types"
)

// Burn EdenBoost from Elys unstaked
func (k Keeper) BurnEdenBFromElysUnstaking(ctx sdk.Context, delegator sdk.AccAddress) {
func (k Keeper) BurnEdenBFromElysUnstaking(ctx sdk.Context, delegator sdk.AccAddress) error {
// Get commitments
commitments := k.commKeeper.GetCommitments(ctx, delegator)

// Get previous amount
prevElysStaked := k.GetElysStaked(ctx, delegator)
if prevElysStaked.Amount.IsZero() {
return
return nil
}

// Calculate current delegated amount of delegator
Expand All @@ -23,10 +24,13 @@ func (k Keeper) BurnEdenBFromElysUnstaking(ctx sdk.Context, delegator sdk.AccAdd
// If not unstaked,
// should return nil otherwise it will break staking module
if delAmount.GTE(prevElysStaked.Amount) {
return
return nil
}

// TODO: Claim all delegation rewards
_, err := k.WithdrawAllRewards(ctx, &types.MsgWithdrawAllRewards{DelegatorAddress: delegator.String()})
if err != nil {
return err
}

edenCommitted := commitments.GetCommittedAmountForDenom(ptypes.Eden)

Expand All @@ -45,22 +49,23 @@ func (k Keeper) BurnEdenBFromElysUnstaking(ctx sdk.Context, delegator sdk.AccAdd
edenBToBurn = unstakedElysDec.Quo(edenCommittedAndElysStakedDec).MulInt(totalEdenB)
}
if edenBToBurn.IsZero() {
return
return nil
}

// Burn EdenB in commitment module
cacheCtx, write := ctx.CacheContext()
err := k.commKeeper.BurnEdenBoost(cacheCtx, delegator, ptypes.EdenB, edenBToBurn.TruncateInt())
err = k.commKeeper.BurnEdenBoost(ctx, delegator, ptypes.EdenB, edenBToBurn.TruncateInt())
if err != nil {
k.Logger(ctx).Error("EdenB burn failure", err)
} else {
write()
return err
}
return nil
}

// Burn EdenBoost from Eden unclaimed
func (k Keeper) BurnEdenBFromEdenUncommitted(ctx sdk.Context, delegator sdk.AccAddress, uncommitAmt math.Int) error {
// TODO: Claim all delegation rewards
_, err := k.WithdrawAllRewards(ctx, &types.MsgWithdrawAllRewards{DelegatorAddress: delegator.String()})
if err != nil {
return err
}

// Get elys staked amount
elysStaked := k.GetElysStaked(ctx, delegator)
Expand All @@ -73,7 +78,7 @@ func (k Keeper) BurnEdenBFromEdenUncommitted(ctx sdk.Context, delegator sdk.AccA
totalEdenB := edenBCommitted.Add(edenBClaimed)

unclaimedAmtDec := math.LegacyNewDecFromInt(uncommitAmt)
// This formula shud be applied before eden uncommitted or elys staked is removed from eden committed amount and elys staked amount respectively
// This formula should be applied before eden uncommitted or elys staked is removed from eden committed amount and elys staked amount respectively
// So add uncommitted amount to committed eden bucket in calculation.
edenCommittedAndElysStakedDec := math.LegacyNewDecFromInt(edenCommitted.Add(elysStaked.Amount).Add(uncommitAmt))
if edenCommittedAndElysStakedDec.IsZero() {
Expand All @@ -89,6 +94,6 @@ func (k Keeper) BurnEdenBFromEdenUncommitted(ctx sdk.Context, delegator sdk.AccA
}

// Burn EdenB in commitment module
err := k.commKeeper.BurnEdenBoost(ctx, delegator, ptypes.EdenB, edenBToBurn.TruncateInt())
err = k.commKeeper.BurnEdenBoost(ctx, delegator, ptypes.EdenB, edenBToBurn.TruncateInt())
return err
}
28 changes: 0 additions & 28 deletions x/estaking/keeper/keeper_shares.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,31 +32,3 @@ func (k Keeper) CalcDelegationAmount(ctx sdk.Context, delegator sdk.AccAddress)

return delAmount.TruncateInt()
}

// Calculate delegation to bonded validators
func (k Keeper) CalcBondedDelegationAmount(ctx sdk.Context, delAddr sdk.AccAddress) math.Int {
// Get elys delegation for creator address
delAmount := math.LegacyZeroDec()
delegations, err := k.Keeper.GetDelegatorDelegations(ctx, delAddr, gomath.MaxUint16)
if err != nil {
panic(err)
}
for _, del := range delegations {
valAddr, err := sdk.ValAddressFromBech32(del.GetValidatorAddr())
if err != nil {
panic(err)
}
val, err := k.Keeper.Validator(ctx, valAddr)
if err != nil {
panic(err)
}
if !val.IsBonded() {
continue
}
shares := del.GetShares()
tokens := val.TokensFromSharesTruncated(shares)
delAmount = delAmount.Add(tokens)
}

return delAmount.TruncateInt()
}
19 changes: 0 additions & 19 deletions x/estaking/keeper/keeper_shares_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,25 +30,6 @@ func (suite *EstakingKeeperTestSuite) TestKeeperShares() {
suite.Require().Equal(delegatedAmount, sdk.DefaultPowerReduction)
},
},
{
"calc bonded delegation amount",
func() (addr sdk.AccAddress) {
suite.ResetSuite()

addr = suite.AddAccounts(1, nil)[0]

return addr
},
func(addr sdk.AccAddress) {
// Check with non-delegator
delegatedAmount := suite.app.EstakingKeeper.CalcBondedDelegationAmount(suite.ctx, addr)
suite.Require().Equal(delegatedAmount, math.ZeroInt())

// Check with genesis account (delegator)
delegatedAmount = suite.app.EstakingKeeper.CalcBondedDelegationAmount(suite.ctx, suite.genAccount)
suite.Require().Equal(delegatedAmount, sdk.DefaultPowerReduction)
},
},
}

for _, tc := range testCases {
Expand Down
18 changes: 10 additions & 8 deletions x/estaking/modules/distribution/module.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@ import (
distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
assetprofilekeeper "github.com/elys-network/elys/x/assetprofile/keeper"
commitmentkeeper "github.com/elys-network/elys/x/commitment/keeper"
estakingkeeper "github.com/elys-network/elys/x/estaking/keeper"

ptypes "github.com/elys-network/elys/x/parameter/types"
)

Expand All @@ -43,7 +45,7 @@ type AppModule struct {

keeper keeper.Keeper
accountKeeper distrtypes.AccountKeeper
bankKeeper distrtypes.BankKeeper
commitmentKeeper *commitmentkeeper.Keeper
estakingKeeper *estakingkeeper.Keeper
assetprofileKeeper *assetprofilekeeper.Keeper

Expand All @@ -54,17 +56,17 @@ type AppModule struct {
// AppModule constructor.
func NewAppModule(
cdc codec.Codec, keeper keeper.Keeper, ak distrtypes.AccountKeeper,
bk distrtypes.BankKeeper,
ck *commitmentkeeper.Keeper,
sk *estakingkeeper.Keeper,
assetprofileKeeper *assetprofilekeeper.Keeper,
feeCollectorName string, subspace exported.Subspace,
) AppModule {
distrAppMod := distr.NewAppModule(cdc, keeper, ak, bk, sk, subspace)
distrAppMod := distr.NewAppModule(cdc, keeper, ak, ck, sk, subspace)
return AppModule{
AppModule: distrAppMod,
keeper: keeper,
accountKeeper: ak,
bankKeeper: bk,
commitmentKeeper: ck,
estakingKeeper: sk,
assetprofileKeeper: assetprofileKeeper,
feeCollectorName: feeCollectorName,
Expand Down Expand Up @@ -110,15 +112,15 @@ func (am AppModule) AllocateEdenUsdcTokens(ctx sdk.Context) {
// called in BeginBlock, collected fees will be from the previous block
// (and distributed to the current representatives)
feeCollector := am.accountKeeper.GetModuleAccount(ctx, am.feeCollectorName)
feesCollectedInt := am.bankKeeper.GetAllBalances(ctx, feeCollector.GetAddress())
feesCollectedInt := am.commitmentKeeper.GetAllBalances(ctx, feeCollector.GetAddress())

usdcDenom, _ := am.assetprofileKeeper.GetUsdcDenom(ctx)
filteredCoins := FilterDenoms(feesCollectedInt, usdcDenom, ptypes.Eden)
feesCollected := sdk.NewDecCoinsFromCoins(filteredCoins...)

// transfer collected fees to the distribution module account
if filteredCoins.IsAllPositive() {
err := am.bankKeeper.SendCoinsFromModuleToModule(ctx, am.feeCollectorName, distrtypes.ModuleName, filteredCoins)
err := am.commitmentKeeper.SendCoinsFromModuleToModule(ctx, am.feeCollectorName, distrtypes.ModuleName, filteredCoins)
if err != nil {
panic(err)
}
Expand Down Expand Up @@ -190,14 +192,14 @@ func (am AppModule) AllocateEdenBTokens(ctx sdk.Context) {
// called in BeginBlock, collected fees will be from the previous block
// (and distributed to the current representatives)
feeCollector := am.accountKeeper.GetModuleAccount(ctx, am.feeCollectorName)
feesCollectedInt := am.bankKeeper.GetAllBalances(ctx, feeCollector.GetAddress())
feesCollectedInt := am.commitmentKeeper.GetAllBalances(ctx, feeCollector.GetAddress())

filteredCoins := FilterDenoms(feesCollectedInt, ptypes.EdenB)
feesCollected := sdk.NewDecCoinsFromCoins(filteredCoins...)

// transfer collected fees to the distribution module account
if filteredCoins.IsAllPositive() {
err := am.bankKeeper.SendCoinsFromModuleToModule(ctx, am.feeCollectorName, distrtypes.ModuleName, filteredCoins)
err := am.commitmentKeeper.SendCoinsFromModuleToModule(ctx, am.feeCollectorName, distrtypes.ModuleName, filteredCoins)
if err != nil {
panic(err)
}
Expand Down

0 comments on commit fece87e

Please sign in to comment.