Skip to content

Commit

Permalink
imp(inflation): remove dup store calls and improve perf (#1258)
Browse files Browse the repository at this point in the history
* imp(inflation): remove dup store calls and improve perf

* changelog

* add logger

* tests
  • Loading branch information
fedekunze committed Jan 20, 2023
1 parent a57148e commit 76dcaf8
Show file tree
Hide file tree
Showing 7 changed files with 88 additions and 67 deletions.
9 changes: 5 additions & 4 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,11 +58,12 @@ Ref: https://keepachangelog.com/en/1.0.0/

### Improvements

- (fix)[#1248](https://github.com/evmos/evmos/pull/1248) Use the Informal Systems Tendermint fork
- (revenue)[#1153](https://github.com/evmos/evmos/pull/1153) Migrate revenue module event emitting to TypedEvent
- (erc20) [#1152](https://github.com/evmos/evmos/pull/1152) Migrate event emitting to TypedEvent
- (inflation) [#1258](https://github.com/evmos/evmos/pull/1258) Remove unnecessary `Coin` validation and store calls for `Params`
- (deps)[#1248](https://github.com/evmos/evmos/pull/1248) Use the Informal Systems Tendermint Core fork
- (revenue)[#1153](https://github.com/evmos/evmos/pull/1153) Migrate revenue module event emitting to `TypedEvent`
- (erc20) [#1152](https://github.com/evmos/evmos/pull/1152) Migrate event emitting to `TypedEvent`
- (claims) [#1126](https://github.com/evmos/evmos/pull/1126) Remove old x/params migration logic
- (vesting) [#1155](https://github.com/evmos/evmos/pull/1155) Migrate deprecated event emitting to new TypedEvent
- (vesting) [#1155](https://github.com/evmos/evmos/pull/1155) Migrate deprecated event emitting to new `TypedEvent`

### Bug Fixes

Expand Down
38 changes: 22 additions & 16 deletions x/inflation/client/cli/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,11 +56,12 @@ func GetPeriod() *cobra.Command {
Use: "period",
Short: "Query the current inflation period",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
RunE: func(cmd *cobra.Command, _ []string) error {
clientCtx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}

queryClient := types.NewQueryClient(clientCtx)

params := &types.QueryPeriodRequest{}
Expand All @@ -85,15 +86,16 @@ func GetEpochMintProvision() *cobra.Command {
Use: "epoch-mint-provision",
Short: "Query the current inflation epoch provisions value",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
RunE: func(cmd *cobra.Command, _ []string) error {
clientCtx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}

queryClient := types.NewQueryClient(clientCtx)

params := &types.QueryEpochMintProvisionRequest{}
res, err := queryClient.EpochMintProvision(context.Background(), params)
req := &types.QueryEpochMintProvisionRequest{}
res, err := queryClient.EpochMintProvision(context.Background(), req)
if err != nil {
return err
}
Expand All @@ -114,15 +116,16 @@ func GetSkippedEpochs() *cobra.Command {
Use: "skipped-epochs",
Short: "Query the current number of skipped epochs",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
RunE: func(cmd *cobra.Command, _ []string) error {
clientCtx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}

queryClient := types.NewQueryClient(clientCtx)

params := &types.QuerySkippedEpochsRequest{}
res, err := queryClient.SkippedEpochs(context.Background(), params)
req := &types.QuerySkippedEpochsRequest{}
res, err := queryClient.SkippedEpochs(context.Background(), req)
if err != nil {
return err
}
Expand All @@ -142,15 +145,16 @@ func GetCirculatingSupply() *cobra.Command {
Use: "circulating-supply",
Short: "Query the current supply of tokens in circulation",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
RunE: func(cmd *cobra.Command, _ []string) error {
clientCtx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}

queryClient := types.NewQueryClient(clientCtx)

params := &types.QueryCirculatingSupplyRequest{}
res, err := queryClient.CirculatingSupply(context.Background(), params)
req := &types.QueryCirculatingSupplyRequest{}
res, err := queryClient.CirculatingSupply(context.Background(), req)
if err != nil {
return err
}
Expand All @@ -170,15 +174,16 @@ func GetInflationRate() *cobra.Command {
Use: "inflation-rate",
Short: "Query the inflation rate of the current period",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
RunE: func(cmd *cobra.Command, _ []string) error {
clientCtx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}

queryClient := types.NewQueryClient(clientCtx)

params := &types.QueryInflationRateRequest{}
res, err := queryClient.InflationRate(context.Background(), params)
req := &types.QueryInflationRateRequest{}
res, err := queryClient.InflationRate(context.Background(), req)
if err != nil {
return err
}
Expand All @@ -199,15 +204,16 @@ func GetParams() *cobra.Command {
Use: "params",
Short: "Query the current inflation parameters",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
RunE: func(cmd *cobra.Command, _ []string) error {
clientCtx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}

queryClient := types.NewQueryClient(clientCtx)

params := &types.QueryParamsRequest{}
res, err := queryClient.Params(context.Background(), params)
req := &types.QueryParamsRequest{}
res, err := queryClient.Params(context.Background(), req)
if err != nil {
return err
}
Expand Down
7 changes: 4 additions & 3 deletions x/inflation/keeper/grpc_query.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,8 @@ func (k Keeper) InflationRate(
_ *types.QueryInflationRateRequest,
) (*types.QueryInflationRateResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
inflationRate := k.GetInflationRate(ctx)
mintDenom := k.GetParams(ctx).MintDenom
inflationRate := k.GetInflationRate(ctx, mintDenom)

return &types.QueryInflationRateResponse{InflationRate: inflationRate}, nil
}
Expand All @@ -77,9 +78,9 @@ func (k Keeper) CirculatingSupply(
_ *types.QueryCirculatingSupplyRequest,
) (*types.QueryCirculatingSupplyResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
circulatingSupply := k.GetCirculatingSupply(ctx)

mintDenom := k.GetParams(ctx).MintDenom

circulatingSupply := k.GetCirculatingSupply(ctx, mintDenom)
coin := sdk.NewDecCoinFromDec(mintDenom, circulatingSupply)

return &types.QueryCirculatingSupplyResponse{CirculatingSupply: coin}, nil
Expand Down
32 changes: 24 additions & 8 deletions x/inflation/keeper/hooks.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,20 @@ func (k Keeper) AfterEpochEnd(ctx sdk.Context, epochIdentifier string, epochNumb
bondedRatio,
)

mintedCoin := sdk.NewCoin(params.MintDenom, epochMintProvision.TruncateInt())
staking, incentives, communityPool, err := k.MintAndAllocateInflation(ctx, mintedCoin)
if !epochMintProvision.IsPositive() {
k.Logger(ctx).Error(
"SKIPPING INFLATION: negative epoch mint provision",
"value", epochMintProvision.String(),
)
return
}

mintedCoin := sdk.Coin{
Denom: params.MintDenom,
Amount: epochMintProvision.TruncateInt(),
}

staking, incentives, communityPool, err := k.MintAndAllocateInflation(ctx, mintedCoin, params)
if err != nil {
panic(err)
}
Expand All @@ -93,31 +105,35 @@ func (k Keeper) AfterEpochEnd(ctx sdk.Context, epochIdentifier string, epochNumb
}

defer func() {
stakingAmt := staking.AmountOfNoDenomValidation(mintedCoin.Denom)
incentivesAmt := incentives.AmountOfNoDenomValidation(mintedCoin.Denom)
cpAmt := communityPool.AmountOfNoDenomValidation(mintedCoin.Denom)

if mintedCoin.Amount.IsInt64() {
telemetry.IncrCounterWithLabels(
[]string{types.ModuleName, "allocate", "total"},
float32(mintedCoin.Amount.Int64()),
[]metrics.Label{telemetry.NewLabel("denom", mintedCoin.Denom)},
)
}
if staking.AmountOf(mintedCoin.Denom).IsInt64() {
if stakingAmt.IsInt64() {
telemetry.IncrCounterWithLabels(
[]string{types.ModuleName, "allocate", "staking", "total"},
float32(staking.AmountOf(mintedCoin.Denom).Int64()),
float32(stakingAmt.Int64()),
[]metrics.Label{telemetry.NewLabel("denom", mintedCoin.Denom)},
)
}
if incentives.AmountOf(mintedCoin.Denom).IsInt64() {
if incentivesAmt.IsInt64() {
telemetry.IncrCounterWithLabels(
[]string{types.ModuleName, "allocate", "incentives", "total"},
float32(incentives.AmountOf(mintedCoin.Denom).Int64()),
float32(incentivesAmt.Int64()),
[]metrics.Label{telemetry.NewLabel("denom", mintedCoin.Denom)},
)
}
if communityPool.AmountOf(mintedCoin.Denom).IsInt64() {
if cpAmt.IsInt64() {
telemetry.IncrCounterWithLabels(
[]string{types.ModuleName, "allocate", "community_pool", "total"},
float32(communityPool.AmountOf(mintedCoin.Denom).Int64()),
float32(cpAmt.Int64()),
[]metrics.Label{telemetry.NewLabel("denom", mintedCoin.Denom)},
)
}
Expand Down
59 changes: 29 additions & 30 deletions x/inflation/keeper/inflation.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,30 +33,30 @@ var teamAlloc = sdk.NewInt(200_000_000).Mul(ethermint.PowerReduction)
func (k Keeper) MintAndAllocateInflation(
ctx sdk.Context,
coin sdk.Coin,
params types.Params,
) (
staking, incentives, communityPool sdk.Coins,
err error,
) {
// skip as no coins need to be minted
if coin.Amount.IsNil() || !coin.Amount.IsPositive() {
return nil, nil, nil, nil
}

// Mint coins for distribution
if err := k.MintCoins(ctx, coin); err != nil {
return nil, nil, nil, err
}

// Allocate minted coins according to allocation proportions (staking, usage
// incentives, community pool)
return k.AllocateExponentialInflation(ctx, coin)
return k.AllocateExponentialInflation(ctx, coin, params)
}

// MintCoins implements an alias call to the underlying supply keeper's
// MintCoins to be used in BeginBlocker.
func (k Keeper) MintCoins(ctx sdk.Context, coin sdk.Coin) error {
coins := sdk.NewCoins(coin)

// skip as no coins need to be minted
if coins.Empty() {
return nil
}

coins := sdk.Coins{coin}
return k.bankKeeper.MintCoins(ctx, types.ModuleName, coins)
}

Expand All @@ -68,44 +68,45 @@ func (k Keeper) MintCoins(ctx sdk.Context, coin sdk.Coin) error {
func (k Keeper) AllocateExponentialInflation(
ctx sdk.Context,
mintedCoin sdk.Coin,
params types.Params,
) (
staking, incentives, communityPool sdk.Coins,
err error,
) {
params := k.GetParams(ctx)
proportions := params.InflationDistribution
distribution := params.InflationDistribution

// Allocate staking rewards into fee collector account
staking = sdk.NewCoins(k.GetProportions(ctx, mintedCoin, proportions.StakingRewards))
err = k.bankKeeper.SendCoinsFromModuleToModule(
staking = sdk.Coins{k.GetProportions(ctx, mintedCoin, distribution.StakingRewards)}

if err := k.bankKeeper.SendCoinsFromModuleToModule(
ctx,
types.ModuleName,
k.feeCollectorName,
staking,
)
if err != nil {
); err != nil {
return nil, nil, nil, err
}

// Allocate usage incentives to incentives module account
incentives = sdk.NewCoins(k.GetProportions(ctx, mintedCoin, proportions.UsageIncentives))
err = k.bankKeeper.SendCoinsFromModuleToModule(
incentives = sdk.Coins{k.GetProportions(ctx, mintedCoin, distribution.UsageIncentives)}

if err = k.bankKeeper.SendCoinsFromModuleToModule(
ctx,
types.ModuleName,
incentivestypes.ModuleName,
incentives,
)
if err != nil {
); err != nil {
return nil, nil, nil, err
}

// Allocate community pool amount (remaining module balance) to community
// pool address
moduleAddr := k.accountKeeper.GetModuleAddress(types.ModuleName)
communityPool = k.bankKeeper.GetAllBalances(ctx, moduleAddr)
inflationBalance := k.bankKeeper.GetAllBalances(ctx, moduleAddr)

err = k.distrKeeper.FundCommunityPool(
ctx,
communityPool,
inflationBalance,
moduleAddr,
)
if err != nil {
Expand All @@ -122,10 +123,10 @@ func (k Keeper) GetProportions(
coin sdk.Coin,
distribution sdk.Dec,
) sdk.Coin {
return sdk.NewCoin(
coin.Denom,
sdk.NewDecFromInt(coin.Amount).Mul(distribution).TruncateInt(),
)
return sdk.Coin{
Denom: coin.Denom,
Amount: sdk.NewDecFromInt(coin.Amount).Mul(distribution).TruncateInt(),
}
}

// BondedRatio the fraction of the staking tokens which are currently bonded
Expand All @@ -149,9 +150,7 @@ func (k Keeper) BondedRatio(ctx sdk.Context) sdk.Dec {

// GetCirculatingSupply returns the bank supply of the mintDenom excluding the
// team allocation in the first year
func (k Keeper) GetCirculatingSupply(ctx sdk.Context) sdk.Dec {
mintDenom := k.GetParams(ctx).MintDenom

func (k Keeper) GetCirculatingSupply(ctx sdk.Context, mintDenom string) sdk.Dec {
circulatingSupply := sdk.NewDecFromInt(k.bankKeeper.GetSupply(ctx, mintDenom).Amount)
teamAllocation := sdk.NewDecFromInt(teamAlloc)

Expand All @@ -164,7 +163,7 @@ func (k Keeper) GetCirculatingSupply(ctx sdk.Context) sdk.Dec {
}

// GetInflationRate returns the inflation rate for the current period.
func (k Keeper) GetInflationRate(ctx sdk.Context) sdk.Dec {
func (k Keeper) GetInflationRate(ctx sdk.Context, mintDenom string) sdk.Dec {
epp := k.GetEpochsPerPeriod(ctx)
if epp == 0 {
return sdk.ZeroDec()
Expand All @@ -177,7 +176,7 @@ func (k Keeper) GetInflationRate(ctx sdk.Context) sdk.Dec {

epochsPerPeriod := sdk.NewDec(epp)

circulatingSupply := k.GetCirculatingSupply(ctx)
circulatingSupply := k.GetCirculatingSupply(ctx, mintDenom)
if circulatingSupply.IsZero() {
return sdk.ZeroDec()
}
Expand All @@ -186,7 +185,7 @@ func (k Keeper) GetInflationRate(ctx sdk.Context) sdk.Dec {
return epochMintProvision.Mul(epochsPerPeriod).Quo(circulatingSupply).Mul(sdk.NewDec(100))
}

// GetEpochMintProvision retireves necessary params KV storage
// GetEpochMintProvision retrieves necessary params KV storage
// and calculate EpochMintProvision
func (k Keeper) GetEpochMintProvision(ctx sdk.Context) sdk.Dec {
return types.CalculateEpochMintProvision(
Expand Down
6 changes: 3 additions & 3 deletions x/inflation/keeper/inflation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ func (suite *KeeperTestSuite) TestMintAndAllocateInflation() {

tc.malleate()

_, _, _, err := suite.app.InflationKeeper.MintAndAllocateInflation(suite.ctx, tc.mintCoin)
_, _, _, err := suite.app.InflationKeeper.MintAndAllocateInflation(suite.ctx, tc.mintCoin, types.DefaultParams())

// Get balances
balanceModule := suite.app.BankKeeper.GetBalance(
Expand Down Expand Up @@ -138,11 +138,11 @@ func (suite *KeeperTestSuite) TestGetCirculatingSupplyAndInflationRate() {
types.DefaultInflationDenom,
sdk.TokensFromConsensusPower(int64(200_000_000), ethermint.PowerReduction),
)
circulatingSupply := s.app.InflationKeeper.GetCirculatingSupply(suite.ctx)
circulatingSupply := s.app.InflationKeeper.GetCirculatingSupply(suite.ctx, types.DefaultInflationDenom)

suite.Require().Equal(decCoin.Sub(teamAlloc).Amount, circulatingSupply)

inflationRate := s.app.InflationKeeper.GetInflationRate(suite.ctx)
inflationRate := s.app.InflationKeeper.GetInflationRate(suite.ctx, types.DefaultInflationDenom)
suite.Require().Equal(tc.expInflationRate, inflationRate)
})
}
Expand Down
4 changes: 1 addition & 3 deletions x/inflation/migrations/v3/migrate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,5 @@ func TestMigrate(t *testing.T) {
require.Equal(t, epochMintProvision, []byte{0x01})

require.NoError(t, v3.MigrateStore(store))

epochMintProvision = store.Get(v3.KeyPrefixEpochMintProvision)
require.Equal(t, len(epochMintProvision), 0)
require.False(t, store.Has(v3.KeyPrefixEpochMintProvision))
}

0 comments on commit 76dcaf8

Please sign in to comment.