0g-chain/x/community/keeper/proposal_handler_test.go
drklee3 f757d7ab15
feat: upgrade to Cosmos v0.46 (#1477)
* Update cosmos-sdk to v0.45.10-kava

* Add RegisterNodeService to app

* Update cosmos proto files

* Update cosmos proto files

* Use tagged v0.45.10-kava-v0.19-0.21 cosmos version

* update x/auth/legacy to x/auth/migrations

* Delete rest packages and registration

* Remove rest from proposal handlers

* Remove legacy types referencing removed sdk types

* Remove legacy tx broadcast handler

* Update incentive staking hooks to return error

* Remove grpc replace directive, use new grpc version

* Fix storetypes import

* Update tally_handler with updated gov types

* Delete legacy types

* Use new gov default config

* Update RegisterTendermintService params

Signed-off-by: drklee3 <derrick@dlee.dev>

* Replace sdk.StoreKey with storetypes.StoreKey

* Replace sdk.Int#ToDec with sdk.NewDecFromInt

* Replace sdk.NewUintFromBigInt with sdkmath.NewUintFromBigInt

Signed-off-by: drklee3 <derrick@dlee.dev>

* Update most intances of govtypes to govv1beta1

* Unpack coin slice for Coins#Sub and Coins#SafeSub

Signed-off-by: drklee3 <derrick@dlee.dev>

* Update committee gov codec registration

Signed-off-by: drklee3 <derrick@dlee.dev>

* Update migrate utils period_vesting Coins#Sub

Signed-off-by: drklee3 <derrick@dlee.dev>

* Update Coin#Sub in community proposal handler

Signed-off-by: drklee3 <derrick@dlee.dev>

* Update Coin#Sub, FundModuleAccount/FundAccount in banktestutil

Signed-off-by: drklee3 <derrick@dlee.dev>

* Update community, earn, kavadist proposal gov registration

* Update evm cli client EthSecp256k1Type check

* AccAddressFromHex to AccAddressFromHexUnsafe

* Add mint DefaultInflationCalculationFn to earn test

* Update use of removed staking.NewHandler

* Rename FlagIAVLFastNode -> FlagDisableIAVLFastNode

* cmd: Update new snapshot app option

Signed-off-by: drklee3 <derrick@dlee.dev>

* cmd: Add tendermint default config, use cosmos rpc status command

Signed-off-by: drklee3 <derrick@dlee.dev>

* Update ethermint import path

github.com/tharsis/ethermint -> github.com/evmos/ethermint

* Upgrade ibc-go to v6

* Update proto dependencies

Signed-off-by: drklee3 <derrick@dlee.dev>

* Update Tally handler test with new gov types

* Update helpers.GenTx -> helpers.GenSignedMockTx

* Update evmkeeper.NewKeeper params

Signed-off-by: drklee3 <derrick@dlee.dev>

* Update ante authz, tests

* Add feemarket transient key, pass subspaces to evm/feemarket keepers

* Update new ante decorators

* Add new addModuleInitFlags to server commands

* Pass codec to keyring.New in genaccounts

* Pass codec to client keys add

* Add SendCoins to evmutil bank_keeper

* Use github.com/cosmos/iavl@v0.19.5

* Add ante HandlerOptions

* Add unimplemented SendCoins to evmutil bank keeper

Ethermint x/evm does not use this method

* Update init-new-chain script to disable post-london blocks

* Modify test genesis states to append 1 validator

* Update tally handler test to use string values

* Prevent querying balance for empty sdk.AccAddress in auction bidding test

* Set default bond denom to ukava

* Remove overwritten bank genesis total supply in committee proposal test

Signed-off-by: drklee3 <derrick@dlee.dev>

* Use ukava for testing staked balance

* Disable minting in community proposal handler test

Previously stake denom is used, which resulted in 0 minted coins

* Update hard APYToSPY test expected value

Increased iterations in sdk.ApproxRoot, updated closer to real value

* Fix NewDecCoinsFromCoins bug in incentive collectDerivativeStakingRewards

* Allow bkava earn incentive test values to match within small margin for rounding

Signed-off-by: drklee3 <derrick@dlee.dev>

* Update invalid denom in issuance message coin validation

Colons are now valid in denoms

Signed-off-by: drklee3 <derrick@dlee.dev>

* Remove genesis validator in incentive delegation tests

* Update pricefeed market test for invalid denom

Signed-off-by: drklee3 <derrick@dlee.dev>

* Update incentive delegator rewards test without genesis validator

Signed-off-by: drklee3 <derrick@dlee.dev>

* Add validator to export test

* Clear bank state in minting tests

Signed-off-by: drklee3 <derrick@dlee.dev>

* Remove validator for no stake tally test

Signed-off-by: drklee3 <derrick@dlee.dev>

* Clear incentive state before InitGenesis in incentive genesis export test

* Update swagger

Signed-off-by: drklee3 <derrick@dlee.dev>

* Update ethermint version to match replaced version

* Remove legacy swagger

* Add NewEthEmitEventDecorator

* Remove redundant func for AddModuleInitFlags

* Remove unused addBankBalanceForAddress func

* Add SetIAVLLazyLoading option to app cmd

* Use legacy.RegisterAminoMsg for committee msg concrete registration

* Remove unnecessary Amino field

* Add evm_util bankkeeper SendCoins comment

* Update test method ResetBankState to DeleteGenesisValidatorCoins to be more clear

* Validate incentive params.RewardsPerSecond to be non-zero

* Validate swap pools to disallow colons in token denoms

* Register all legacy amino types on gov modulecdc

* Remove redundant Comittee interface registration

* Pin goleveldb to v1.0.1-0.20210819022825-2ae1ddf74ef7

Causes failed to load state at height errors

* Update ethermint to new pinned version with minGasPrices parse error fix

* Update cosmos fork dependcy commit to include reverted account constructor patch

* Update Cosmos v0.46.11 and cometbft v0.34.27

* Bump minimum go version to 1.19

* Update tendermint proto

* Update internal testnet genesis

* Move NewCanTransferDecorator before NewEthGasConsumeDecorator

* Add hard borrow store tests (#1514)

* add store tests for Borrow type

* refactor Deposit tests to match

* Fix old bep3 tests (#1515)

* Update Ethermint to 1b17445 to fix duplicate proto registration

* Add custom status command to use snake_case and stdout

* Add SetInflation helper

* Reduce ambiguity with evm CanSignEthTx error

* Remove init genesis validator claim in test

* Add disabled evmante.NewMinGasPriceDecorator with x/feemarket note

* chore: use tagged versions for Cosmos and Ethermint forks

* update kvtool & increase wait for ibc transfer test

---------

Signed-off-by: drklee3 <derrick@dlee.dev>
Co-authored-by: Ruaridh <rhuairahrighairidh@users.noreply.github.com>
Co-authored-by: Robert Pirtle <astropirtle@gmail.com>
2023-04-03 20:08:45 -04:00

335 lines
10 KiB
Go

package keeper_test
import (
"fmt"
"testing"
"time"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/stretchr/testify/suite"
abcitypes "github.com/tendermint/tendermint/abci/types"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
tmtime "github.com/tendermint/tendermint/types/time"
"github.com/kava-labs/kava/app"
"github.com/kava-labs/kava/x/community/keeper"
"github.com/kava-labs/kava/x/community/testutil"
"github.com/kava-labs/kava/x/community/types"
hardkeeper "github.com/kava-labs/kava/x/hard/keeper"
hardtypes "github.com/kava-labs/kava/x/hard/types"
pricefeedtypes "github.com/kava-labs/kava/x/pricefeed/types"
)
const chainID = "kavatest_2221-1"
func ukava(amt int64) sdk.Coins {
return sdk.NewCoins(sdk.NewInt64Coin("ukava", amt))
}
func usdx(amt int64) sdk.Coins {
return sdk.NewCoins(sdk.NewInt64Coin("usdx", amt))
}
func otherdenom(amt int64) sdk.Coins {
return sdk.NewCoins(sdk.NewInt64Coin("other-denom", amt))
}
type proposalTestSuite struct {
suite.Suite
App app.TestApp
Ctx sdk.Context
Keeper keeper.Keeper
MaccAddress sdk.AccAddress
hardKeeper hardkeeper.Keeper
}
func TestProposalTestSuite(t *testing.T) {
suite.Run(t, new(proposalTestSuite))
}
func (suite *proposalTestSuite) SetupTest() {
app.SetSDKConfig()
genTime := tmtime.Now()
hardGS, pricefeedGS := testutil.NewLendGenesisBuilder().
WithMarket("ukava", "kava:usd", sdk.OneDec()).
WithMarket("usdx", "usdx:usd", sdk.OneDec()).
Build()
tApp := app.NewTestApp()
ctx := tApp.NewContext(true, tmproto.Header{
Height: 1,
Time: genTime,
ChainID: chainID,
})
tApp.InitializeFromGenesisStatesWithTimeAndChainID(
genTime, chainID,
app.GenesisState{hardtypes.ModuleName: tApp.AppCodec().MustMarshalJSON(&hardGS)},
app.GenesisState{pricefeedtypes.ModuleName: tApp.AppCodec().MustMarshalJSON(&pricefeedGS)},
)
suite.App = tApp
suite.Ctx = ctx
suite.Keeper = tApp.GetCommunityKeeper()
suite.MaccAddress = tApp.GetAccountKeeper().GetModuleAddress(types.ModuleAccountName)
suite.hardKeeper = suite.App.GetHardKeeper()
// give the community pool some funds
// ukava
suite.FundCommunityPool(ukava(1e10))
// usdx
suite.FundCommunityPool(usdx(1e10))
// other-denom
suite.FundCommunityPool(otherdenom(1e10))
}
func (suite *proposalTestSuite) NextBlock() {
newTime := suite.Ctx.BlockTime().Add(6 * time.Second)
newHeight := suite.Ctx.BlockHeight() + 1
suite.App.EndBlocker(suite.Ctx, abcitypes.RequestEndBlock{})
suite.Ctx = suite.Ctx.WithBlockTime(newTime).WithBlockHeight(newHeight).WithChainID(chainID)
suite.App.BeginBlocker(suite.Ctx, abcitypes.RequestBeginBlock{})
}
func (suite *proposalTestSuite) FundCommunityPool(coins sdk.Coins) {
// mint to ephemeral account
ephemeralAcc := app.RandomAddress()
suite.NoError(suite.App.FundAccount(suite.Ctx, ephemeralAcc, coins))
// fund community pool with newly minted coins
suite.NoError(suite.App.GetDistrKeeper().FundCommunityPool(suite.Ctx, coins, ephemeralAcc))
}
func (suite *proposalTestSuite) GetCommunityPoolBalance() sdk.Coins {
balance, change := suite.App.GetDistrKeeper().GetFeePoolCommunityCoins(suite.Ctx).TruncateDecimal()
// expect no decimal dust
suite.True(sdk.NewDecCoins().IsEqual(change), "expected no decimal dust in community pool")
return balance
}
func (suite *proposalTestSuite) CheckCommunityPoolBalance(expected sdk.Coins) {
actual := suite.GetCommunityPoolBalance()
// check that balance is expected
suite.True(expected.IsEqual(actual), fmt.Sprintf("unexpected balance in community pool\nexpected: %s\nactual: %s", expected, actual))
}
func (suite *proposalTestSuite) TestCommunityLendDepositProposal() {
testCases := []struct {
name string
proposals []*types.CommunityPoolLendDepositProposal
expectedErr string
expectedDeposits []sdk.Coins
}{
{
name: "valid - one proposal, one denom",
proposals: []*types.CommunityPoolLendDepositProposal{
{Amount: ukava(1e8)},
},
expectedErr: "",
expectedDeposits: []sdk.Coins{ukava(1e8)},
},
{
name: "valid - one proposal, multiple denoms",
proposals: []*types.CommunityPoolLendDepositProposal{
{Amount: ukava(1e8).Add(usdx(1e8)...)},
},
expectedErr: "",
expectedDeposits: []sdk.Coins{ukava(1e8).Add(usdx(1e8)...)},
},
{
name: "valid - multiple proposals, same denom",
proposals: []*types.CommunityPoolLendDepositProposal{
{Amount: ukava(1e8)},
{Amount: ukava(1e9)},
},
expectedErr: "",
expectedDeposits: []sdk.Coins{ukava(1e8 + 1e9)},
},
{
name: "valid - multiple proposals, different denoms",
proposals: []*types.CommunityPoolLendDepositProposal{
{Amount: ukava(1e8)},
{Amount: usdx(1e8)},
},
expectedErr: "",
expectedDeposits: []sdk.Coins{ukava(1e8).Add(usdx(1e8)...)},
},
{
name: "invalid - insufficient balance",
proposals: []*types.CommunityPoolLendDepositProposal{
{
Description: "more coins than i have!",
Amount: ukava(1e11),
},
},
expectedErr: "community pool does not have sufficient coins to distribute",
expectedDeposits: []sdk.Coins{},
},
{
name: "invalid - invalid lend deposit (unsupported denom)",
proposals: []*types.CommunityPoolLendDepositProposal{
{Amount: otherdenom(1e9)},
},
expectedErr: "invalid deposit denom",
expectedDeposits: []sdk.Coins{},
},
}
for _, tc := range testCases {
suite.Run(tc.name, func() {
suite.SetupTest()
for _, proposal := range tc.proposals {
err := keeper.HandleCommunityPoolLendDepositProposal(suite.Ctx, suite.Keeper, proposal)
if tc.expectedErr == "" {
suite.NoError(err)
} else {
suite.ErrorContains(err, tc.expectedErr)
}
}
deposits := suite.hardKeeper.GetDepositsByUser(suite.Ctx, suite.MaccAddress)
suite.Len(deposits, len(tc.expectedDeposits), "expected a deposit to lend")
for _, amt := range tc.expectedDeposits {
suite.Equal(amt, deposits[0].Amount, "expected amount to match")
}
})
}
}
func (suite *proposalTestSuite) TestCommunityLendWithdrawProposal() {
testCases := []struct {
name string
initialDeposit sdk.Coins
proposals []*types.CommunityPoolLendWithdrawProposal
expectedErr string
expectedWithdrawal sdk.Coins
}{
{
// in the week it would take a proposal to pass, the position would have grown
// to withdraw the entire position, it'd be safest to set a very high withdraw
name: "valid - requesting withdrawal of more than total will withdraw all",
initialDeposit: ukava(1e9),
proposals: []*types.CommunityPoolLendWithdrawProposal{
{Amount: ukava(1e12)},
},
expectedErr: "",
expectedWithdrawal: ukava(1e9),
},
{
name: "valid - single proposal, single denom, full withdrawal",
initialDeposit: ukava(1e9),
proposals: []*types.CommunityPoolLendWithdrawProposal{
{Amount: ukava(1e9)},
},
expectedErr: "",
expectedWithdrawal: ukava(1e9),
},
{
name: "valid - single proposal, multiple denoms, full withdrawal",
initialDeposit: ukava(1e9).Add(usdx(1e9)...),
proposals: []*types.CommunityPoolLendWithdrawProposal{
{Amount: ukava(1e9).Add(usdx(1e9)...)},
},
expectedErr: "",
expectedWithdrawal: ukava(1e9).Add(usdx(1e9)...),
},
{
name: "valid - single proposal, partial withdrawal",
initialDeposit: ukava(1e9).Add(usdx(1e9)...),
proposals: []*types.CommunityPoolLendWithdrawProposal{
{Amount: ukava(1e8).Add(usdx(1e9)...)},
},
expectedErr: "",
expectedWithdrawal: ukava(1e8).Add(usdx(1e9)...),
},
{
name: "valid - multiple proposals, full withdrawal",
initialDeposit: ukava(1e9).Add(usdx(1e9)...),
proposals: []*types.CommunityPoolLendWithdrawProposal{
{Amount: ukava(1e9)},
{Amount: usdx(1e9)},
},
expectedErr: "",
expectedWithdrawal: ukava(1e9).Add(usdx(1e9)...),
},
{
name: "valid - multiple proposals, partial withdrawal",
initialDeposit: ukava(1e9).Add(usdx(1e9)...),
proposals: []*types.CommunityPoolLendWithdrawProposal{
{Amount: ukava(1e8)},
{Amount: usdx(1e8)},
},
expectedErr: "",
expectedWithdrawal: ukava(1e8).Add(usdx(1e8)...),
},
{
name: "invalid - nonexistent position, has no deposits",
initialDeposit: sdk.NewCoins(),
proposals: []*types.CommunityPoolLendWithdrawProposal{
{Amount: ukava(1e8)},
},
expectedErr: "deposit not found",
expectedWithdrawal: sdk.NewCoins(),
},
{
name: "invalid - nonexistent position, has deposits of different denom",
initialDeposit: ukava(1e8),
proposals: []*types.CommunityPoolLendWithdrawProposal{
{Amount: usdx(1e8)},
},
expectedErr: "no coins of this type deposited",
expectedWithdrawal: sdk.NewCoins(),
},
}
for _, tc := range testCases {
suite.Run(tc.name, func() {
suite.SetupTest()
// Disable minting, so that the community pool balance doesn't change
// during the test - this is because staking denom is "ukava" and no
// longer "stake" which has an initial and changing balance instead
// of just 0
suite.App.SetInflation(suite.Ctx, sdk.ZeroDec())
// setup initial deposit
if !tc.initialDeposit.IsZero() {
deposit := types.NewCommunityPoolLendDepositProposal("initial deposit", "has coins", tc.initialDeposit)
err := keeper.HandleCommunityPoolLendDepositProposal(suite.Ctx, suite.Keeper, deposit)
suite.NoError(err, "unexpected error while seeding lend deposit")
}
beforeBalance := suite.GetCommunityPoolBalance()
// run the proposals
for i, proposal := range tc.proposals {
fmt.Println("submitting proposal ", i, " ", suite.Ctx.ChainID())
err := keeper.HandleCommunityPoolLendWithdrawProposal(suite.Ctx, suite.Keeper, proposal)
if tc.expectedErr == "" {
suite.NoError(err)
} else {
suite.ErrorContains(err, tc.expectedErr)
}
suite.NextBlock()
}
// expect funds to be removed from hard deposit
expectedRemaining := tc.initialDeposit.Sub(tc.expectedWithdrawal...)
deposits := suite.hardKeeper.GetDepositsByUser(suite.Ctx, suite.MaccAddress)
if expectedRemaining.IsZero() {
suite.Len(deposits, 0, "expected all deposits to be withdrawn")
} else {
suite.Len(deposits, 1, "expected user to have remaining deposit")
suite.Equal(expectedRemaining, deposits[0].Amount)
}
// expect funds to be distributed back to community pool
suite.CheckCommunityPoolBalance(beforeBalance.Add(tc.expectedWithdrawal...))
})
}
}