Skip to content

Commit

Permalink
add fixes and token factory changes
Browse files Browse the repository at this point in the history
  • Loading branch information
Faulty Tolly committed Nov 29, 2024
1 parent 8ed1efc commit efbfcc3
Show file tree
Hide file tree
Showing 10 changed files with 337 additions and 66 deletions.
14 changes: 7 additions & 7 deletions app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -450,7 +450,7 @@ func NewRollapp(
)
app.MintKeeper.SetHooks(
minttypes.NewMultiMintHooks(
// insert mint hooks receivers here
// insert mint hooks receivers here
),
)

Expand Down Expand Up @@ -511,6 +511,11 @@ func NewRollapp(
AddRoute(upgradetypes.RouterKey, upgrade.NewSoftwareUpgradeProposalHandler(app.UpgradeKeeper)).
AddRoute(ibcclienttypes.RouterKey, ibcclient.NewClientProposalHandler(app.IBCKeeper.ClientKeeper))

// The gov proposal types can be individually enabled
if len(enabledProposals) != 0 {
govRouter.AddRoute(wasm.RouterKey, wasm.NewWasmProposalHandler(app.WasmKeeper, enabledProposals))
}

govConfig := govtypes.DefaultConfig()
/*
Example of setting gov params:
Expand All @@ -523,7 +528,7 @@ func NewRollapp(

app.GovKeeper = *govKeeper.SetHooks(
govtypes.NewMultiGovHooks(
// register the governance hooks
// register the governance hooks
),
)

Expand Down Expand Up @@ -621,11 +626,6 @@ func NewRollapp(
panic(fmt.Sprintf("error while reading wasm config: %s", err))
}

// The gov proposal types can be individually enabled
if len(enabledProposals) != 0 {
govRouter.AddRoute(wasm.RouterKey, wasm.NewWasmProposalHandler(app.WasmKeeper, enabledProposals))
}

// Include the x/cwerrors query to stargate queries
wasmOpts = append(wasmOpts, wasmkeeper.WithQueryPlugins(&wasmkeeper.QueryPlugins{
Stargate: wasmkeeper.AcceptListStargateQuerier(getAcceptedStargateQueries(), app.GRPCQueryRouter(), appCodec),
Expand Down
239 changes: 239 additions & 0 deletions app/apptesting/apptesting.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,239 @@
package apptesting

import (
"fmt"
"time"

"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/store/rootmulti"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/tx/signing"
authsigning "github.com/cosmos/cosmos-sdk/x/auth/signing"
"github.com/cosmos/cosmos-sdk/x/bank/testutil"
distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
"github.com/stretchr/testify/suite"
abci "github.com/tendermint/tendermint/abci/types"
"github.com/tendermint/tendermint/crypto/ed25519"
"github.com/tendermint/tendermint/libs/log"
tmtypes "github.com/tendermint/tendermint/proto/tendermint/types"
dbm "github.com/tendermint/tm-db"

minttypes "github.com/cosmos/cosmos-sdk/x/mint/types"
"github.com/dymensionxyz/rollapp-wasm/app"
)

type KeeperTestHelper struct {
suite.Suite

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

// Setup sets up basic environment for suite (App, Ctx, and test accounts)
func (s *KeeperTestHelper) Setup() {
s.App = app.Setup(false)
s.Ctx = s.App.BaseApp.NewContext(false, tmtypes.Header{Height: 1, ChainID: "osmosis-1", Time: time.Now().UTC()})
s.QueryHelper = &baseapp.QueryServiceTestHelper{
GRPCQueryRouter: s.App.GRPCQueryRouter(),
Ctx: s.Ctx,
}
s.TestAccs = CreateRandomAccounts(3)
}

func (s *KeeperTestHelper) SetupTestForInitGenesis() {
// Setting to True, leads to init genesis not running
s.App = app.Setup(true)
s.Ctx = s.App.BaseApp.NewContext(true, tmtypes.Header{})
}

// CreateTestContext creates a test context.
func (s *KeeperTestHelper) CreateTestContext() sdk.Context {
ctx, _ := s.CreateTestContextWithMultiStore()
return ctx
}

// CreateTestContextWithMultiStore creates a test context and returns it together with multi store.
func (s *KeeperTestHelper) CreateTestContextWithMultiStore() (sdk.Context, sdk.CommitMultiStore) {
db := dbm.NewMemDB()
logger := log.NewNopLogger()

ms := rootmulti.NewStore(db, logger)

return sdk.NewContext(ms, tmtypes.Header{}, false, logger), ms
}

// CreateTestContext creates a test context.
func (s *KeeperTestHelper) Commit() {
oldHeight := s.Ctx.BlockHeight()
oldHeader := s.Ctx.BlockHeader()
s.App.Commit()
newHeader := tmtypes.Header{Height: oldHeight + 1, ChainID: oldHeader.ChainID, Time: oldHeader.Time.Add(time.Second)}
s.App.BeginBlock(abci.RequestBeginBlock{Header: newHeader})
s.Ctx = s.App.NewContext(false, newHeader)
}

// FundAcc funds target address with specified amount.
func (s *KeeperTestHelper) FundAcc(acc sdk.AccAddress, amounts sdk.Coins) {
err := testutil.FundAccount(s.App.BankKeeper, s.Ctx, acc, amounts)
s.Require().NoError(err)
}

// FundModuleAcc funds target modules with specified amount.
func (s *KeeperTestHelper) FundModuleAcc(moduleName string, amounts sdk.Coins) {
err := testutil.FundModuleAccount(s.App.BankKeeper, s.Ctx, moduleName, amounts)
s.Require().NoError(err)
}

func (s *KeeperTestHelper) MintCoins(coins sdk.Coins) {
err := s.App.BankKeeper.MintCoins(s.Ctx, minttypes.ModuleName, coins)
s.Require().NoError(err)
}

// SetupValidator sets up a validator and returns the ValAddress.
func (s *KeeperTestHelper) SetupValidator(bondStatus stakingtypes.BondStatus) sdk.ValAddress {
/*
valPub := secp256k1.GenPrivKey().PubKey()
valAddr := sdk.ValAddress(valPub.Address())
bondDenom := s.App.StakingKeeper.GetParams(s.Ctx).BondDenom
selfBond := sdk.NewCoins(sdk.Coin{Amount: sdk.NewInt(100), Denom: bondDenom})
s.FundAcc(sdk.AccAddress(valAddr), selfBond)
stakingHandler := staking.NewHandler(s.App.StakingKeeper)
stakingCoin := sdk.NewCoin(sdk.DefaultBondDenom, selfBond[0].Amount)
ZeroCommission := stakingtypes.NewCommissionRates(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec())
msg, err := stakingtypes.NewMsgCreateValidator(valAddr, valPub, stakingCoin, stakingtypes.Description{}, ZeroCommission, sdk.OneInt())
s.Require().NoError(err)
res, err := stakingHandler(s.Ctx, msg)
s.Require().NoError(err)
s.Require().NotNil(res)
val, found := s.App.StakingKeeper.GetValidator(s.Ctx, valAddr)
s.Require().True(found)
val = val.UpdateStatus(bondStatus)
s.App.StakingKeeper.SetValidator(s.Ctx, val)
return valAddr
*/

return sdk.ValAddress("cookies")
}

// BeginNewBlock starts a new block.
func (s *KeeperTestHelper) BeginNewBlock() {
var valAddr []byte

validators := s.App.StakingKeeper.GetAllValidators(s.Ctx)
if len(validators) >= 1 {
valAddrFancy, err := validators[0].GetConsAddr()
s.Require().NoError(err)
valAddr = valAddrFancy.Bytes()
} else {
valAddrFancy := s.SetupValidator(stakingtypes.Bonded)
validator, _ := s.App.StakingKeeper.GetValidator(s.Ctx, valAddrFancy)
valAddr2, _ := validator.GetConsAddr()
valAddr = valAddr2.Bytes()
}

s.BeginNewBlockWithProposer(valAddr)
}

// BeginNewBlockWithProposer begins a new block with a proposer.
func (s *KeeperTestHelper) BeginNewBlockWithProposer(proposer sdk.ValAddress) {
validator, found := s.App.StakingKeeper.GetValidator(s.Ctx, proposer)
s.Assert().True(found)

valConsAddr, err := validator.GetConsAddr()
s.Require().NoError(err)

valAddr := valConsAddr.Bytes()

newBlockTime := s.Ctx.BlockTime().Add(5 * time.Second)

header := tmtypes.Header{Height: s.Ctx.BlockHeight() + 1, Time: newBlockTime}
newCtx := s.Ctx.WithBlockTime(newBlockTime).WithBlockHeight(s.Ctx.BlockHeight() + 1)
s.Ctx = newCtx
lastCommitInfo := abci.LastCommitInfo{
Votes: []abci.VoteInfo{{
Validator: abci.Validator{Address: valAddr, Power: 1000},
SignedLastBlock: true,
}},
}
reqBeginBlock := abci.RequestBeginBlock{Header: header, LastCommitInfo: lastCommitInfo}

fmt.Println("beginning block ", s.Ctx.BlockHeight())
s.App.BeginBlocker(s.Ctx, reqBeginBlock)
}

// EndBlock ends the block.
func (s *KeeperTestHelper) EndBlock() {
reqEndBlock := abci.RequestEndBlock{Height: s.Ctx.BlockHeight()}
s.App.EndBlocker(s.Ctx, reqEndBlock)
}

// AllocateRewardsToValidator allocates reward tokens to a distribution module then allocates rewards to the validator address.
func (s *KeeperTestHelper) AllocateRewardsToValidator(valAddr sdk.ValAddress, rewardAmt sdk.Int) {
validator, found := s.App.StakingKeeper.GetValidator(s.Ctx, valAddr)
s.Require().True(found)

// allocate reward tokens to distribution module
coins := sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, rewardAmt)}
err := testutil.FundModuleAccount(s.App.BankKeeper, s.Ctx, distrtypes.ModuleName, coins)
s.Require().NoError(err)

// allocate rewards to validator
s.Ctx = s.Ctx.WithBlockHeight(s.Ctx.BlockHeight() + 1)
decTokens := sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(20000)}}
s.App.DistrKeeper.AllocateTokensToValidator(s.Ctx, validator, decTokens)
}

// BuildTx builds a transaction.
func (s *KeeperTestHelper) BuildTx(
txBuilder client.TxBuilder,
msgs []sdk.Msg,
sigV2 signing.SignatureV2,
memo string, txFee sdk.Coins,
gasLimit uint64,
) authsigning.Tx {
err := txBuilder.SetMsgs(msgs[0])
s.Require().NoError(err)

err = txBuilder.SetSignatures(sigV2)
s.Require().NoError(err)

txBuilder.SetMemo(memo)
txBuilder.SetFeeAmount(txFee)
txBuilder.SetGasLimit(gasLimit)

return txBuilder.GetTx()
}

// 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
}

// AssertEventEmitted asserts that ctx's event manager has emitted the given number of events
// of the given type.
func (s *KeeperTestHelper) AssertEventEmitted(ctx sdk.Context, eventTypeExpected string, numEventsExpected int) {
allEvents := ctx.EventManager().Events()
// filter out other events
actualEvents := make([]sdk.Event, 0)
for _, event := range allEvents {
if event.Type == eventTypeExpected {
actualEvents = append(actualEvents, event)
}
}
s.Equal(numEventsExpected, len(actualEvents))
}
66 changes: 66 additions & 0 deletions app/test_helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"testing"
"time"

"github.com/CosmWasm/wasmd/x/wasm"
appcodec "github.com/cosmos/cosmos-sdk/codec"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/crypto/codec"
Expand All @@ -20,6 +21,7 @@ import (
rollappparamstypes "github.com/dymensionxyz/dymension-rdk/x/rollappparams/types"
"github.com/tendermint/tendermint/crypto/encoding"
"github.com/tendermint/tendermint/libs/log"
"github.com/tendermint/tendermint/proto/tendermint/crypto"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
types2 "github.com/tendermint/tendermint/types"
dbm "github.com/tendermint/tm-db"
Expand Down Expand Up @@ -238,3 +240,67 @@ func addDenomToBankModule(appCodec appcodec.Codec, genesisState GenesisState, de

return genesisState
}

func Setup(isCheckTx bool, opts ...wasm.Option) *App {
db := dbm.NewMemDB()
app := NewRollapp(log.NewNopLogger(), db, nil, true, map[int64]bool{}, DefaultNodeHome, 5, MakeEncodingConfig(), wasm.EnableAllProposals, EmptyBaseAppOptions{}, opts)

if !isCheckTx {
genesisState := NewDefaultGenesisState(app.appCodec)

// make hub genesis happy by adding denom meta
bankGenesis := new(banktypes.GenesisState)
app.appCodec.MustUnmarshalJSON(genesisState[banktypes.ModuleName], bankGenesis)
bankGenesis.DenomMetadata = append(bankGenesis.DenomMetadata, banktypes.Metadata{
Description: "stake",
DenomUnits: []*banktypes.DenomUnit{
{
Denom: "stake",
Exponent: 6,
Aliases: nil,
},
},
Base: "stake",
Display: "stake",
Name: "stake",
Symbol: "stake",
URI: "",
URIHash: "",
})
genesisState[banktypes.ModuleName] = app.AppCodec().MustMarshalJSON(bankGenesis)

app.InitChain(
abci.RequestInitChain{
Time: time.Now(),
ChainId: "cookies",
ConsensusParams: DefaultConsensusParams,
Validators: []abci.ValidatorUpdate{
{
PubKey: crypto.PublicKey{},
Power: 50,
},
},
AppStateBytes: marshalGenesis(genesisState),
InitialHeight: 0,
GenesisChecksum: "cookies",
},
)
}
return app
}

// EmptyBaseAppOptions is a stub implementing AppOptions
type EmptyBaseAppOptions struct{}

// Get implements AppOptions
func (ao EmptyBaseAppOptions) Get(o string) interface{} {
return nil
}

func marshalGenesis(genesisState GenesisState) json.RawMessage {
stateBytes, err := json.MarshalIndent(genesisState, "", " ")
if err != nil {
panic(err)
}
return stateBytes
}
3 changes: 1 addition & 2 deletions x/tokenfactory/keeper/admins_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package keeper_test

/*import (
import (
"fmt"

sdk "github.com/cosmos/cosmos-sdk/types"
Expand Down Expand Up @@ -401,4 +401,3 @@ func (suite *KeeperTestSuite) TestSetDenomMetaData() {
})
}
}
*/
Loading

0 comments on commit efbfcc3

Please sign in to comment.