0g-chain/x/incentive/keeper/rewards_earn_staking_integration_test.go

194 lines
5.8 KiB
Go
Raw Normal View History

package keeper_test
import (
"testing"
"time"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/kava-labs/kava/app"
earntypes "github.com/kava-labs/kava/x/earn/types"
"github.com/kava-labs/kava/x/incentive/testutil"
"github.com/kava-labs/kava/x/incentive/types"
"github.com/stretchr/testify/suite"
abci "github.com/tendermint/tendermint/abci/types"
)
type EarnStakingRewardsIntegrationTestSuite struct {
testutil.IntegrationTester
keeper TestKeeper
userAddrs []sdk.AccAddress
valAddrs []sdk.ValAddress
}
func TestEarnStakingRewardsIntegrationTestSuite(t *testing.T) {
suite.Run(t, new(EarnStakingRewardsIntegrationTestSuite))
}
func (suite *EarnStakingRewardsIntegrationTestSuite) SetupTest() {
suite.IntegrationTester.SetupTest()
suite.keeper = TestKeeper{
Keeper: suite.App.GetIncentiveKeeper(),
}
_, addrs := app.GeneratePrivKeyAddressPairs(5)
suite.userAddrs = addrs[0:2]
suite.valAddrs = []sdk.ValAddress{
sdk.ValAddress(addrs[2]),
sdk.ValAddress(addrs[3]),
}
// Setup app with test state
authBuilder := app.NewAuthBankGenesisBuilder().
WithSimpleAccount(addrs[0], cs(c("ukava", 1e12))).
WithSimpleAccount(addrs[1], cs(c("ukava", 1e12))).
WithSimpleAccount(addrs[2], cs(c("ukava", 1e12))).
WithSimpleAccount(addrs[3], cs(c("ukava", 1e12)))
incentiveBuilder := testutil.NewIncentiveGenesisBuilder().
WithGenesisTime(suite.GenesisTime).
WithSimpleEarnRewardPeriod("bkava", cs())
savingsBuilder := testutil.NewSavingsGenesisBuilder().
WithSupportedDenoms("bkava")
earnBuilder := testutil.NewEarnGenesisBuilder().
WithAllowedVaults(earntypes.AllowedVault{
Denom: "bkava",
Strategies: earntypes.StrategyTypes{earntypes.STRATEGY_TYPE_SAVINGS},
IsPrivateVault: false,
AllowedDepositors: nil,
})
stakingBuilder := testutil.NewStakingGenesisBuilder()
mintBuilder := testutil.NewMintGenesisBuilder().
WithInflationMax(sdk.OneDec()).
WithInflationMin(sdk.OneDec()).
WithMinter(sdk.OneDec(), sdk.ZeroDec()).
WithMintDenom("ukava")
add x/kavamint & x/community modules (#1400) * add `x/kavamint` module (#1376) * stub out the x/kavamint module * mint staking rewards in x/kavamint BeginBlocker * calculate cumulative inflation from x/kavamint * cleanup, abstract bond denom, grpc query tests * store & use previous block time to calculate mints * move test suite to testutil * add test of x/kavamint BeginBlocker * cleanup & comments from @DracoLi review * fix x/incentive integration test * remove rest client grpc test * add x/kavamint module spec * track previous block time in genesis * suggested cleanup from PR review * bugfix incorrect module account check * add x/community module (#1388) * add x/community module * refactor and setup fund-community-pool tx * remove unused features (params, genesis state) * test x/community query and message * update with master branch deps * updates from review * indicate deprecated methods on module (still needed to fulfill interface) * remove legacy querier * derive msg Route() and Type() from sdk.MsgTypeURL(&msg) * use module name for message Route() * mint community pool inflation in x/kavamint (#1389) * mint community pool inflation in x/kavamint * refactor x/kavamint abci inflation test * test inflation from x/kavamint * default kavamint rates to 0% * rename kavamint account name variables * panic if genesis kavamint previous block time not set * emit event on kavamint begin blocker * add kavamint year of inflation sanity check test * update fund_community_pool message event * add x/community spec * refactor inflation accumulation into single func * use new comm pool in kavadist multispend proposal (#1403) the x/community module houses the new community pool. this commit points the CommunityPoolMultiSpendProposal at the new community pool so that multispend proposals can continue to be processed once original fee pool funds are move to x/community * updates from proto lint changes * update earn proposals to use new community pool originally the CommunityPoolDepositProposal & CommunityPoolWithdrawProposal used the vanilla community pool fee pool. this commit updates them both to use the new x/community module account. * spec formatting update * add x/community & x/kavamint to internal testnet genesis * increase test coverage of x/kavamint * increase test coverage of x/community * use string type for sdk.Dec proto fields; disable generation of getters for genesis and params (and other store objects) * follow sdk conventions for params endpoint naming * add kavamint to swagger; update swagger & proto docs * remove legacy querier; touch up module to match others * reduce max minting rate; refactor genesis to allow nil/zero block time; repace proto stringers and remove getters; keep sdk.Dec values strings in protos; increase validation of sdk.Dec values in params; increase coverage; add module account permission checks; ensure import and export of genesis does not change state * fix scaling of rate values -- should be yearly rates * revert key change * fix typo in test name * fix regression in running tests -- rename method Co-authored-by: Nick DeLuca <nickdeluca08@gmail.com>
2022-12-09 21:24:35 +00:00
suite.StartChainWithBuilders(
authBuilder,
incentiveBuilder,
savingsBuilder,
earnBuilder,
stakingBuilder,
mintBuilder,
)
}
func (suite *EarnStakingRewardsIntegrationTestSuite) TestStakingRewardsDistributed() {
// derivative 1: 8 total staked, 7 to earn, 1 not in earn
// derivative 2: 2 total staked, 1 to earn, 1 not in earn
userMintAmount0 := c("ukava", 8e9)
userMintAmount1 := c("ukava", 2e9)
userDepositAmount0 := i(7e9)
userDepositAmount1 := i(1e9)
// Create two validators
derivative0, err := suite.MintLiquidAnyValAddr(suite.userAddrs[0], suite.valAddrs[0], userMintAmount0)
suite.Require().NoError(err)
derivative1, err := suite.MintLiquidAnyValAddr(suite.userAddrs[0], suite.valAddrs[1], userMintAmount1)
suite.Require().NoError(err)
err = suite.DeliverEarnMsgDeposit(suite.userAddrs[0], sdk.NewCoin(derivative0.Denom, userDepositAmount0), earntypes.STRATEGY_TYPE_SAVINGS)
suite.NoError(err)
err = suite.DeliverEarnMsgDeposit(suite.userAddrs[0], sdk.NewCoin(derivative1.Denom, userDepositAmount1), earntypes.STRATEGY_TYPE_SAVINGS)
suite.NoError(err)
// Get derivative denoms
lq := suite.App.GetLiquidKeeper()
vaultDenom1 := lq.GetLiquidStakingTokenDenom(suite.valAddrs[0])
vaultDenom2 := lq.GetLiquidStakingTokenDenom(suite.valAddrs[1])
previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC)
suite.Ctx = suite.Ctx.WithBlockTime(previousAccrualTime)
initialVault1RewardFactor := d("0.04")
initialVault2RewardFactor := d("0.04")
globalIndexes := types.MultiRewardIndexes{
{
CollateralType: vaultDenom1,
RewardIndexes: types.RewardIndexes{
{
CollateralType: "ukava",
RewardFactor: initialVault1RewardFactor,
},
},
},
{
CollateralType: vaultDenom2,
RewardIndexes: types.RewardIndexes{
{
CollateralType: "ukava",
RewardFactor: initialVault2RewardFactor,
},
},
},
}
suite.keeper.storeGlobalEarnIndexes(suite.Ctx, globalIndexes)
suite.keeper.SetEarnRewardAccrualTime(suite.Ctx, vaultDenom1, suite.Ctx.BlockTime())
suite.keeper.SetEarnRewardAccrualTime(suite.Ctx, vaultDenom2, suite.Ctx.BlockTime())
val := suite.GetAbciValidator(suite.valAddrs[0])
// Mint tokens, distribute to validators, claim staking rewards
// 1 hour later
_, resBeginBlock := suite.NextBlockAfterWithReq(
1*time.Hour,
abci.RequestEndBlock{},
abci.RequestBeginBlock{
LastCommitInfo: abci.LastCommitInfo{
Votes: []abci.VoteInfo{{
Validator: val,
SignedLastBlock: true,
}},
},
},
)
// check time and factors
suite.StoredEarnTimeEquals(vaultDenom1, suite.Ctx.BlockTime())
suite.StoredEarnTimeEquals(vaultDenom2, suite.Ctx.BlockTime())
validatorRewards, _ := suite.GetBeginBlockClaimedStakingRewards(resBeginBlock)
suite.Require().Contains(validatorRewards, suite.valAddrs[0].String(), "there should be claim events for validator 1")
suite.Require().Contains(validatorRewards, suite.valAddrs[1].String(), "there should be claim events for validator 2")
// Total staking rewards / total source shares (**deposited in earn** not total minted)
// types.RewardIndexes.Quo() uses Dec.Quo() which uses bankers rounding.
// So we need to use Dec.Quo() to also round vs Dec.QuoInt() which truncates
expectedIndexes1 := validatorRewards[suite.valAddrs[0].String()].
AmountOf("ukava").
ToDec().
Quo(userDepositAmount0.ToDec())
expectedIndexes2 := validatorRewards[suite.valAddrs[1].String()].
AmountOf("ukava").
ToDec().
Quo(userDepositAmount1.ToDec())
// Only contains staking rewards
suite.StoredEarnIndexesEqual(vaultDenom1, types.RewardIndexes{
{
CollateralType: "ukava",
RewardFactor: initialVault1RewardFactor.Add(expectedIndexes1),
},
})
suite.StoredEarnIndexesEqual(vaultDenom2, types.RewardIndexes{
{
CollateralType: "ukava",
RewardFactor: initialVault2RewardFactor.Add(expectedIndexes2),
},
})
}