Skip to content

Commit

Permalink
feat: token factory tests
Browse files Browse the repository at this point in the history
  • Loading branch information
emidev98 committed Aug 28, 2023
1 parent c5eb4db commit b826d41
Show file tree
Hide file tree
Showing 10 changed files with 517 additions and 130 deletions.
6 changes: 3 additions & 3 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,7 @@ proto-gen:
@echo "Generating Protobuf files"
@$(protoImage) sh ./scripts/protocgen.sh

gen-swagger-docs:
gen-swagger:
bash scripts/protoc-swagger-gen.sh

update-swagger-docs: statik
Expand All @@ -271,9 +271,9 @@ update-swagger-docs: statik
echo "Swagger docs are in sync!";\
fi

apply-swagger: gen-swagger-docs update-swagger-docs
apply-swagger: gen-swagger update-swagger-docs

.PHONY: proto-all proto-gen gen-swagger-docs update-swagger-docs apply-swagger
.PHONY: proto-all proto-gen gen-swagger update-swagger-docs apply-swagger

########################################
### Tools & dependencies
Expand Down
12 changes: 12 additions & 0 deletions app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -351,6 +351,18 @@ type TerraApp struct {
configurator module.Configurator
}

func (app TerraApp) GetAppCodec() codec.Codec {
return app.appCodec
}

func (app TerraApp) GetConfigurator() module.Configurator {
return app.configurator
}

func (app TerraApp) GetModuleManager() *module.Manager {
return app.mm
}

// NewTerraApp returns a reference to an initialized Terra.
func NewTerraApp(
logger log.Logger,
Expand Down
64 changes: 30 additions & 34 deletions app/app_test.go → app/app_testing/app_testing.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package app
package app_testing

import (
"encoding/json"
Expand Down Expand Up @@ -46,6 +46,7 @@ import (
"github.com/strangelove-ventures/packet-forward-middleware/v7/router"

"github.com/CosmWasm/wasmd/x/wasm"
terra_app "github.com/terra-money/core/v2/app"
)

var (
Expand All @@ -64,11 +65,11 @@ var (
)

func TestSimAppExportAndBlockedAddrs(t *testing.T) {
encCfg := MakeEncodingConfig()
encCfg := terra_app.MakeEncodingConfig()
db := dbm.NewMemDB()
app := NewTerraApp(
app := terra_app.NewTerraApp(
log.NewTMLogger(log.NewSyncWriter(os.Stdout)),
db, nil, true, map[int64]bool{}, DefaultNodeHome, 0, encCfg,
db, nil, true, map[int64]bool{}, terra_app.DefaultNodeHome, 0, encCfg,
simtestutil.EmptyAppOptions{}, wasmconfig.DefaultConfig())

// generate validator private/public key
Expand Down Expand Up @@ -102,26 +103,21 @@ func TestSimAppExportAndBlockedAddrs(t *testing.T) {
app.Commit()

// Making a new app object with the db, so that initchain hasn't been called
app2 := NewTerraApp(
app2 := terra_app.NewTerraApp(
log.NewTMLogger(log.NewSyncWriter(os.Stdout)),
db, nil, true, map[int64]bool{}, DefaultNodeHome, 0,
db, nil, true, map[int64]bool{}, terra_app.DefaultNodeHome, 0,
encCfg, simtestutil.EmptyAppOptions{}, wasmconfig.DefaultConfig())
_, err = app2.ExportAppStateAndValidators(false, []string{}, []string{})
require.NoError(t, err, "ExportAppStateAndValidators should not have an error")
}

func TestGetMaccPerms(t *testing.T) {
dup := GetMaccPerms()
require.Equal(t, maccPerms, dup, "duplicated module account permissions differed from actual module account permissions")
}

func TestInitGenesisOnMigration(t *testing.T) {
db := dbm.NewMemDB()
encCfg := MakeEncodingConfig()
encCfg := terra_app.MakeEncodingConfig()
logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout))
app := NewTerraApp(
app := terra_app.NewTerraApp(
logger, db, nil, true, map[int64]bool{},
DefaultNodeHome, 0, encCfg, simtestutil.EmptyAppOptions{}, wasmconfig.DefaultConfig())
terra_app.DefaultNodeHome, 0, encCfg, simtestutil.EmptyAppOptions{}, wasmconfig.DefaultConfig())

ctx := app.NewContext(true, tmproto.Header{Height: app.LastBlockHeight()})

Expand All @@ -131,15 +127,15 @@ func TestInitGenesisOnMigration(t *testing.T) {
t.Cleanup(mockCtrl.Finish)
mockModule := mocktestutils.NewMockAppModuleWithAllExtensions(mockCtrl)
mockDefaultGenesis := json.RawMessage(`{"key": "value"}`)
mockModule.EXPECT().DefaultGenesis(gomock.Eq(app.appCodec)).Times(1).Return(mockDefaultGenesis)
mockModule.EXPECT().InitGenesis(gomock.Eq(ctx), gomock.Eq(app.appCodec), gomock.Eq(mockDefaultGenesis)).Times(1).Return(nil)
mockModule.EXPECT().DefaultGenesis(gomock.Eq(app.AppCodec)).Times(1).Return(mockDefaultGenesis)
mockModule.EXPECT().InitGenesis(gomock.Eq(ctx), gomock.Eq(app.AppCodec), gomock.Eq(mockDefaultGenesis)).Times(1).Return(nil)
mockModule.EXPECT().ConsensusVersion().Times(1).Return(uint64(0))

app.mm.Modules["mock"] = mockModule
app.GetModuleManager().Modules["mock"] = mockModule

// Run migrations only for "mock" module. We exclude it from
// the VersionMap to simulate upgrading with a new module.
_, err := app.mm.RunMigrations(ctx, app.configurator,
_, err := app.GetModuleManager().RunMigrations(ctx, app.GetConfigurator(),
module.VersionMap{
"bank": bank.AppModule{}.ConsensusVersion(),
"auth": auth.AppModule{}.ConsensusVersion(),
Expand Down Expand Up @@ -168,44 +164,44 @@ func TestInitGenesisOnMigration(t *testing.T) {
}

func TestLegacyAmino(t *testing.T) {
encCfg := MakeEncodingConfig()
encCfg := terra_app.MakeEncodingConfig()
db := dbm.NewMemDB()
app := NewTerraApp(
app := terra_app.NewTerraApp(
log.NewTMLogger(log.NewSyncWriter(os.Stdout)),
db, nil, true, map[int64]bool{}, DefaultNodeHome, 0,
db, nil, true, map[int64]bool{}, terra_app.DefaultNodeHome, 0,
encCfg, simtestutil.EmptyAppOptions{}, wasmconfig.DefaultConfig())

require.Equal(t, encCfg.Amino, app.LegacyAmino())
}

func TestAppCodec(t *testing.T) {
encCfg := MakeEncodingConfig()
encCfg := terra_app.MakeEncodingConfig()
db := dbm.NewMemDB()
app := NewTerraApp(
app := terra_app.NewTerraApp(
log.NewTMLogger(log.NewSyncWriter(os.Stdout)),
db, nil, true, map[int64]bool{}, DefaultNodeHome, 0,
db, nil, true, map[int64]bool{}, terra_app.DefaultNodeHome, 0,
encCfg, simtestutil.EmptyAppOptions{}, wasmconfig.DefaultConfig())

require.Equal(t, encCfg.Marshaler, app.AppCodec())
}

func TestInterfaceRegistry(t *testing.T) {
encCfg := MakeEncodingConfig()
encCfg := terra_app.MakeEncodingConfig()
db := dbm.NewMemDB()
app := NewTerraApp(
app := terra_app.NewTerraApp(
log.NewTMLogger(log.NewSyncWriter(os.Stdout)),
db, nil, true, map[int64]bool{}, DefaultNodeHome, 0,
db, nil, true, map[int64]bool{}, terra_app.DefaultNodeHome, 0,
encCfg, simtestutil.EmptyAppOptions{}, wasmconfig.DefaultConfig())

require.Equal(t, encCfg.InterfaceRegistry, app.InterfaceRegistry())
}

func TestGetKey(t *testing.T) {
encCfg := MakeEncodingConfig()
encCfg := terra_app.MakeEncodingConfig()
db := dbm.NewMemDB()
app := NewTerraApp(
app := terra_app.NewTerraApp(
log.NewTMLogger(log.NewSyncWriter(os.Stdout)),
db, nil, true, map[int64]bool{}, DefaultNodeHome, 0,
db, nil, true, map[int64]bool{}, terra_app.DefaultNodeHome, 0,
encCfg, simtestutil.EmptyAppOptions{}, wasmconfig.DefaultConfig())

require.NotEmpty(t, app.GetKey(banktypes.StoreKey))
Expand All @@ -214,11 +210,11 @@ func TestGetKey(t *testing.T) {
}

func TestSimAppEnforceStakingForVestingTokens(t *testing.T) {
encCfg := MakeEncodingConfig()
encCfg := terra_app.MakeEncodingConfig()
db := dbm.NewMemDB()
app := NewTerraApp(
app := terra_app.NewTerraApp(
log.NewTMLogger(log.NewSyncWriter(os.Stdout)),
db, nil, true, map[int64]bool{}, DefaultNodeHome, 0, encCfg,
db, nil, true, map[int64]bool{}, terra_app.DefaultNodeHome, 0, encCfg,
simtestutil.EmptyAppOptions{}, wasmconfig.DefaultConfig(),
)
genAccounts := authtypes.GenesisAccounts{
Expand Down Expand Up @@ -266,7 +262,7 @@ func TestSimAppEnforceStakingForVestingTokens(t *testing.T) {
genesisState := SetupGenesisValSet(valSet, genAccounts, nil, app, encCfg, balances...)
ctx := app.NewContext(true, tmproto.Header{Height: app.LastBlockHeight()})

genesisState[authtypes.ModuleName] = app.appCodec.MustMarshalJSON(authtypes.NewGenesisState(authtypes.DefaultParams(), genAccounts))
genesisState[authtypes.ModuleName] = app.GetAppCodec().MustMarshalJSON(authtypes.NewGenesisState(authtypes.DefaultParams(), genAccounts))
delegations := app.StakingKeeper.GetAllDelegations(ctx)
sharePerValidators := make(map[string]sdk.Dec)

Expand Down
162 changes: 162 additions & 0 deletions app/app_testing/test_helpers.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
package app_testing

// DONTCOVER

import (
"os"
"time"

"github.com/CosmWasm/wasmd/x/wasm"
wasmtypes "github.com/CosmWasm/wasmd/x/wasm/types"
dbm "github.com/cometbft/cometbft-db"
"github.com/cometbft/cometbft/crypto/ed25519"
"github.com/cometbft/cometbft/libs/log"
tmproto "github.com/cometbft/cometbft/proto/tendermint/types"
tmtypes "github.com/cometbft/cometbft/types"
"github.com/cosmos/cosmos-sdk/baseapp"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types"
minttypes "github.com/cosmos/cosmos-sdk/x/mint/types"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
"github.com/stretchr/testify/suite"
"github.com/terra-money/core/v2/app"
terra_app "github.com/terra-money/core/v2/app"
terrraParams "github.com/terra-money/core/v2/app/params"
"github.com/terra-money/core/v2/app/wasmconfig"
tokenfactorytypes "github.com/terra-money/core/v2/x/tokenfactory/types"
)

type AppTestSuite struct {
suite.Suite

App *app.TerraApp
Ctx sdk.Context
QueryHelper *baseapp.QueryServiceTestHelper
TestAccs []sdk.AccAddress
}

// Setup sets up basic environment for suite (App, Ctx, and test accounts)
func (s *AppTestSuite) Setup() {
baseTestAccts := CreateRandomAccounts(3)
encCfg := terra_app.MakeEncodingConfig()

db := dbm.NewMemDB()
s.App = terra_app.NewTerraApp(
log.NewTMLogger(log.NewSyncWriter(os.Stdout)),
db,
nil,
true,
map[int64]bool{},
terra_app.DefaultNodeHome,
0,
encCfg,
simtestutil.EmptyAppOptions{},
wasmconfig.DefaultConfig(),
)

s.TestAccs = []sdk.AccAddress{}
s.TestAccs = append(s.TestAccs, baseTestAccts...)
s.Ctx = s.App.NewContext(true, tmproto.Header{Height: 1, Time: time.Now()})
s.QueryHelper = &baseapp.QueryServiceTestHelper{
GRPCQueryRouter: s.App.GRPCQueryRouter(),
Ctx: s.Ctx,
}
s.App.BankKeeper.SetParams(s.Ctx, banktypes.NewParams(true))
s.App.WasmKeeper.SetParams(s.Ctx, wasmtypes.DefaultParams())
s.App.TokenFactoryKeeper.SetParams(s.Ctx, tokenfactorytypes.DefaultParams())
s.App.DistrKeeper.SetFeePool(s.Ctx, distrtypes.InitialFeePool())
}

// CreateRandomAccounts is a function return a list of randomly generated AccAddresses
func CreateRandomAccounts(numAccts int) []sdk.AccAddress {
testAddrs := make([]sdk.AccAddress, numAccts)
for i := 0; i < numAccts; i++ {
pk := ed25519.GenPrivKey().PubKey()
testAddrs[i] = sdk.AccAddress(pk.Address())
}

return testAddrs
}

// FundAcc funds target address with specified amount.
func (s *AppTestSuite) FundAcc(acc sdk.AccAddress, amounts sdk.Coins) (err error) {
s.Require().NoError(err)
if err := s.App.BankKeeper.MintCoins(s.Ctx, minttypes.ModuleName, amounts); err != nil {
return err
}

return s.App.BankKeeper.SendCoinsFromModuleToAccount(s.Ctx, minttypes.ModuleName, acc, amounts)
}

func SetupGenesisValSet(
valSet *tmtypes.ValidatorSet,
genAccs []authtypes.GenesisAccount,
opts []wasm.Option,
app *terra_app.TerraApp,
encCfg terrraParams.EncodingConfig,
balances ...banktypes.Balance,
) terra_app.GenesisState {
genesisState := terra_app.NewDefaultGenesisState(encCfg.Marshaler)
// set genesis accounts
authGenesis := authtypes.NewGenesisState(authtypes.DefaultParams(), genAccs)
genesisState[authtypes.ModuleName] = app.AppCodec().MustMarshalJSON(authGenesis)

validators := make([]stakingtypes.Validator, 0, len(valSet.Validators))
delegations := make([]stakingtypes.Delegation, 0, len(valSet.Validators))

bondAmt := sdk.NewInt(1000000)
totalSupply := sdk.NewCoins()

for _, val := range valSet.Validators {
pk, err := cryptocodec.FromTmPubKeyInterface(val.PubKey)
if err != nil {
panic(err)
}

pkAny, err := codectypes.NewAnyWithValue(pk)
if err != nil {
panic(err)
}
validator := stakingtypes.Validator{
OperatorAddress: sdk.ValAddress(val.Address).String(),
ConsensusPubkey: pkAny,
Jailed: false,
Status: stakingtypes.Bonded,
Tokens: bondAmt,
DelegatorShares: sdk.OneDec(),
Description: stakingtypes.Description{},
UnbondingHeight: int64(0),
UnbondingTime: time.Unix(0, 0).UTC(),
Commission: stakingtypes.NewCommission(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()),
MinSelfDelegation: sdk.ZeroInt(),
}
validators = append(validators, validator)
delegations = append(delegations, stakingtypes.NewDelegation(genAccs[0].GetAddress(), val.Address.Bytes(), sdk.OneDec()))

}

// set validators and delegations
stakingGenesis := stakingtypes.NewGenesisState(stakingtypes.DefaultParams(), validators, delegations)
genesisState[stakingtypes.ModuleName] = app.AppCodec().MustMarshalJSON(stakingGenesis)

// add bonded amount to bonded pool module account
balances = append(balances, banktypes.Balance{
Address: authtypes.NewModuleAddress(stakingtypes.BondedPoolName).String(),
Coins: sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, bondAmt)},
})

for _, b := range balances {
// add genesis acc tokens and delegated tokens to total supply
totalSupply = totalSupply.Add(b.Coins...)
}
// update total supply
bankGenesis := banktypes.NewGenesisState(banktypes.DefaultGenesisState().Params, balances, totalSupply, []banktypes.Metadata{}, []banktypes.SendEnabled{})
genesisState[banktypes.ModuleName] = app.AppCodec().MustMarshalJSON(bankGenesis)

return genesisState
}
Loading

0 comments on commit b826d41

Please sign in to comment.