fix(x/protocolpool)!: do not incur into extra writes if there are no continuous funds (#21356)

This commit is contained in:
Facundo Medica 2024-08-19 18:02:01 +02:00 committed by GitHub
parent 6f30de3a41
commit c286e6ef7d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 48 additions and 0 deletions

View File

@ -177,6 +177,31 @@ func (k Keeper) SetToDistribute(ctx context.Context) error {
// Calculate the amount to be distributed
amountToDistribute := distributionBalance.Sub(lastBalance)
// Check if there are any recipients to distribute to, if not, send straight to the community pool and avoid
// setting the distributions
hasContinuousFunds := false
err = k.ContinuousFund.Walk(ctx, nil, func(_ sdk.AccAddress, _ types.ContinuousFund) (bool, error) {
hasContinuousFunds = true
return true, nil
})
if err != nil {
return err
}
// if there are no continuous funds, send all the funds to the community pool and reset the last balance
if !hasContinuousFunds {
poolCoins := sdk.NewCoins(sdk.NewCoin(denom, amountToDistribute))
if err := k.bankKeeper.SendCoinsFromModuleToModule(ctx, types.ProtocolPoolDistrAccount, types.ModuleName, poolCoins); err != nil {
return err
}
if !lastBalance.IsZero() { // only reset if the last balance is not zero (so we leave it at zero/nil)
return k.LastBalance.Set(ctx, math.ZeroInt())
}
return nil
}
if err = k.Distributions.Set(ctx, k.HeaderService.HeaderInfo(ctx).Time, amountToDistribute); err != nil {
return fmt.Errorf("error while setting Distributions: %w", err)
}

View File

@ -186,9 +186,32 @@ func (suite *KeeperTestSuite) TestSetToDistribute() {
distrBal := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(1000000)))
suite.bankKeeper.EXPECT().GetAllBalances(suite.ctx, poolDistrAcc.GetAddress()).Return(distrBal).AnyTimes()
// because there are no continuous funds, all are going to the community pool
suite.bankKeeper.EXPECT().SendCoinsFromModuleToModule(suite.ctx, poolDistrAcc.GetName(), poolAcc.GetName(), distrBal)
err := suite.poolKeeper.SetToDistribute(suite.ctx)
suite.Require().NoError(err)
// Verify that LastBalance was not set (zero balance)
_, err = suite.poolKeeper.LastBalance.Get(suite.ctx)
suite.Require().ErrorContains(err, "not found")
// create new continuous fund and distribute again
addrCdc := address.NewBech32Codec("cosmos")
addrStr := "cosmos1qypq2q2l8z4wz2z2l8z4wz2z2l8z4wz2srklj6"
addrBz, err := addrCdc.StringToBytes(addrStr)
suite.Require().NoError(err)
err = suite.poolKeeper.ContinuousFund.Set(suite.ctx, addrBz, types.ContinuousFund{
Recipient: addrStr,
Percentage: math.LegacyMustNewDecFromStr("0.3"),
Expiry: nil,
})
suite.Require().NoError(err)
err = suite.poolKeeper.SetToDistribute(suite.ctx)
suite.Require().NoError(err)
// Verify that LastBalance was set correctly
lastBalance, err := suite.poolKeeper.LastBalance.Get(suite.ctx)
suite.Require().NoError(err)