github.com/fibonacci-chain/fbc@v0.0.0-20231124064014-c7636198c1e9/libs/cosmos-sdk/simapp/test_helpers.go (about)

     1  package simapp
     2  
     3  import (
     4  	"os"
     5  	"testing"
     6  
     7  	abci "github.com/fibonacci-chain/fbc/libs/tendermint/abci/types"
     8  	"github.com/fibonacci-chain/fbc/libs/tendermint/crypto"
     9  	"github.com/fibonacci-chain/fbc/libs/tendermint/crypto/ed25519"
    10  	"github.com/fibonacci-chain/fbc/libs/tendermint/libs/log"
    11  	dbm "github.com/fibonacci-chain/fbc/libs/tm-db"
    12  	"github.com/stretchr/testify/require"
    13  
    14  	bam "github.com/fibonacci-chain/fbc/libs/cosmos-sdk/baseapp"
    15  	"github.com/fibonacci-chain/fbc/libs/cosmos-sdk/codec"
    16  	"github.com/fibonacci-chain/fbc/libs/cosmos-sdk/simapp/helpers"
    17  	sdk "github.com/fibonacci-chain/fbc/libs/cosmos-sdk/types"
    18  	"github.com/fibonacci-chain/fbc/libs/cosmos-sdk/x/auth"
    19  	authexported "github.com/fibonacci-chain/fbc/libs/cosmos-sdk/x/auth/exported"
    20  	"github.com/fibonacci-chain/fbc/libs/cosmos-sdk/x/supply"
    21  )
    22  
    23  // Setup initializes a new SimApp. A Nop logger is set in SimApp.
    24  func Setup(isCheckTx bool) *SimApp {
    25  	db := dbm.NewMemDB()
    26  	app := NewSimApp(log.NewNopLogger(), db, nil, true, map[int64]bool{}, 0)
    27  	if !isCheckTx {
    28  		// init chain must be called to stop deliverState from being nil
    29  		genesisState := NewDefaultGenesisState()
    30  		stateBytes, err := codec.MarshalJSONIndent(app.Codec(), genesisState)
    31  		if err != nil {
    32  			panic(err)
    33  		}
    34  
    35  		// Initialize the chain
    36  		app.InitChain(
    37  			abci.RequestInitChain{
    38  				Validators:    []abci.ValidatorUpdate{},
    39  				AppStateBytes: stateBytes,
    40  			},
    41  		)
    42  	}
    43  
    44  	return app
    45  }
    46  
    47  // SetupWithGenesisAccounts initializes a new SimApp with the passed in
    48  // genesis accounts.
    49  func SetupWithGenesisAccounts(genAccs []authexported.GenesisAccount) *SimApp {
    50  	db := dbm.NewMemDB()
    51  	app := NewSimApp(log.NewTMLogger(log.NewSyncWriter(os.Stdout)), db, nil, true, map[int64]bool{}, 0)
    52  
    53  	// initialize the chain with the passed in genesis accounts
    54  	genesisState := NewDefaultGenesisState()
    55  
    56  	authGenesis := auth.NewGenesisState(auth.DefaultParams(), genAccs)
    57  	genesisStateBz := app.Codec().MustMarshalJSON(authGenesis)
    58  	genesisState[auth.ModuleName] = genesisStateBz
    59  
    60  	stateBytes, err := codec.MarshalJSONIndent(app.Codec(), genesisState)
    61  	if err != nil {
    62  		panic(err)
    63  	}
    64  
    65  	// Initialize the chain
    66  	app.InitChain(
    67  		abci.RequestInitChain{
    68  			Validators:    []abci.ValidatorUpdate{},
    69  			AppStateBytes: stateBytes,
    70  		},
    71  	)
    72  
    73  	app.Commit(abci.RequestCommit{})
    74  	app.BeginBlock(abci.RequestBeginBlock{Header: abci.Header{Height: app.LastBlockHeight() + 1}})
    75  
    76  	return app
    77  }
    78  
    79  // AddTestAddrs constructs and returns accNum amount of accounts with an
    80  // initial balance of accAmt
    81  func AddTestAddrs(app *SimApp, ctx sdk.Context, accNum int, accAmt sdk.Int) []sdk.AccAddress {
    82  	testAddrs := make([]sdk.AccAddress, accNum)
    83  	for i := 0; i < accNum; i++ {
    84  		pk := ed25519.GenPrivKey().PubKey()
    85  		testAddrs[i] = sdk.AccAddress(pk.Address())
    86  	}
    87  
    88  	initCoins := sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), accAmt))
    89  	totalSupply := sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), accAmt.MulRaw(int64(len(testAddrs)))))
    90  	prevSupply := app.SupplyKeeper.GetSupply(ctx)
    91  	app.SupplyKeeper.SetSupply(ctx, supply.NewSupply(prevSupply.GetTotal().Add(totalSupply...)))
    92  
    93  	// fill all the addresses with some coins, set the loose pool tokens simultaneously
    94  	for _, addr := range testAddrs {
    95  		_, err := app.BankKeeper.AddCoins(ctx, addr, initCoins)
    96  		if err != nil {
    97  			panic(err)
    98  		}
    99  	}
   100  	return testAddrs
   101  }
   102  
   103  // CheckBalance checks the balance of an account.
   104  func CheckBalance(t *testing.T, app *SimApp, addr sdk.AccAddress, exp sdk.Coins) {
   105  	ctxCheck := app.BaseApp.NewContext(true, abci.Header{})
   106  	res := app.AccountKeeper.GetAccount(ctxCheck, addr)
   107  
   108  	require.True(t, exp.IsEqual(res.GetCoins()))
   109  }
   110  
   111  // SignCheckDeliver checks a generated signed transaction and simulates a
   112  // block commitment with the given transaction. A test assertion is made using
   113  // the parameter 'expPass' against the result. A corresponding result is
   114  // returned.
   115  func SignCheckDeliver(
   116  	t *testing.T, cdc *codec.Codec, app *bam.BaseApp, header abci.Header, msgs []sdk.Msg,
   117  	accNums, seq []uint64, expSimPass, expPass bool, priv ...crypto.PrivKey,
   118  ) (sdk.GasInfo, *sdk.Result, error) {
   119  
   120  	tx := helpers.GenTx(
   121  		msgs,
   122  		sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 0)},
   123  		helpers.DefaultGenTxGas,
   124  		"",
   125  		accNums,
   126  		seq,
   127  		priv...,
   128  	)
   129  
   130  	txBytes, err := cdc.MarshalBinaryLengthPrefixed(tx)
   131  	require.Nil(t, err)
   132  
   133  	// Must simulate now as CheckTx doesn't run Msgs anymore
   134  	_, res, err := app.Simulate(txBytes, tx, 0, nil)
   135  
   136  	if expSimPass {
   137  		require.NoError(t, err)
   138  		require.NotNil(t, res)
   139  	} else {
   140  		require.Error(t, err)
   141  		require.Nil(t, res)
   142  	}
   143  
   144  	// Simulate a sending a transaction and committing a block
   145  	app.BeginBlock(abci.RequestBeginBlock{Header: header})
   146  	gInfo, res, err := app.Deliver(tx)
   147  
   148  	if expPass {
   149  		require.NoError(t, err)
   150  		require.NotNil(t, res)
   151  	} else {
   152  		require.Error(t, err)
   153  		require.Nil(t, res)
   154  	}
   155  
   156  	app.EndBlock(abci.RequestEndBlock{})
   157  	app.Commit(abci.RequestCommit{})
   158  
   159  	return gInfo, res, err
   160  }
   161  
   162  // GenSequenceOfTxs generates a set of signed transactions of messages, such
   163  // that they differ only by having the sequence numbers incremented between
   164  // every transaction.
   165  func GenSequenceOfTxs(msgs []sdk.Msg, accNums []uint64, initSeqNums []uint64, numToGenerate int, priv ...crypto.PrivKey) []*auth.StdTx {
   166  	txs := make([]*auth.StdTx, numToGenerate)
   167  	for i := 0; i < numToGenerate; i++ {
   168  		txs[i] = helpers.GenTx(
   169  			msgs,
   170  			sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 0)},
   171  			helpers.DefaultGenTxGas,
   172  			"",
   173  			accNums,
   174  			initSeqNums,
   175  			priv...,
   176  		)
   177  		incrementAllSequenceNumbers(initSeqNums)
   178  	}
   179  
   180  	return txs
   181  }
   182  
   183  func incrementAllSequenceNumbers(initSeqNums []uint64) {
   184  	for i := 0; i < len(initSeqNums); i++ {
   185  		initSeqNums[i]++
   186  	}
   187  }