Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add fees and estimation of tx's gas #1553

Merged
merged 11 commits into from
Jan 13, 2020
2 changes: 1 addition & 1 deletion cmd/mesg-cosmos-daemon/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ func main() {
if err != nil {
panic(err)
}
appFactory := cosmos.NewAppFactory(logger.TendermintLogger(), db)
appFactory := cosmos.NewAppFactory(logger.TendermintLogger(), db, cfg.Cosmos.MinGasPrices)
enginesdk.NewBackend(appFactory)
app, err = cosmos.NewApp(appFactory)
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion cmd/mesg-cosmos/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ func main() {
if err != nil {
panic(err)
}
appFactory := cosmos.NewAppFactory(logger.TendermintLogger(), db)
appFactory := cosmos.NewAppFactory(logger.TendermintLogger(), db, cfg.Cosmos.MinGasPrices)
enginesdk.NewBackend(appFactory)
app, err = cosmos.NewApp(appFactory)
if err != nil {
Expand Down
20 changes: 15 additions & 5 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"path/filepath"
"time"

sdkcosmos "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/go-bip39"
homedir "github.com/mitchellh/go-homedir"
"github.com/sirupsen/logrus"
Expand Down Expand Up @@ -45,10 +46,12 @@ type Config struct {

Cosmos struct {
RelativePath string `validate:"required"`
MinGasPrices string `validate:"required"`
}

DevGenesis struct {
ChainID string `validate:"required"`
ChainID string `validate:"required"`
InitialBalances string `validate:"required"`
}

Account struct {
Expand Down Expand Up @@ -87,8 +90,10 @@ func defaultConfig() (*Config, error) {
c.Tendermint.Config.Instrumentation.PrometheusListenAddr = "0.0.0.0:26660"

c.Cosmos.RelativePath = "cosmos"
c.Cosmos.MinGasPrices = "1.0amesg"

c.DevGenesis.ChainID = "mesg-dev-chain"
c.DevGenesis.InitialBalances = "1000000000000000000000000amesg" // 1 000 000 * 10^18

c.Account.Name = "engine"
c.Account.Password = "pass"
Expand Down Expand Up @@ -156,14 +161,19 @@ func (c *Config) prepare() error {
// validate checks values and return an error if any validation failed.
func (c *Config) validate() error {
if _, err := logrus.ParseLevel(c.Log.Level); err != nil {
return fmt.Errorf("config.Log.Level error: %w", err)
return fmt.Errorf("config log.level error: %w", err)
}
if c.Account.Mnemonic != "" && !bip39.IsMnemonicValid(c.Account.Mnemonic) {
return fmt.Errorf("config.Account.Mnemonic error: mnemonic is not valid")
return fmt.Errorf("config account.mnemonic error: mnemonic is not valid")
}
if err := c.Tendermint.Config.ValidateBasic(); err != nil {
return fmt.Errorf("config.Tendermint error: %w", err)
return fmt.Errorf("config tendermint error: %w", err)
}
if _, err := sdkcosmos.ParseDecCoins(c.Cosmos.MinGasPrices); err != nil {
return fmt.Errorf("config cosmos.mingasprices error: %w", err)
}
if _, err := sdkcosmos.ParseCoins(c.DevGenesis.InitialBalances); err != nil {
return fmt.Errorf("config devgenesis.initialbalances error: %w", err)
}

return validator.New().Struct(c)
}
3 changes: 3 additions & 0 deletions config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ log:
forcecolors: true
account:
mnemonic: glimpse upon body vast economy give taxi yellow rabbit come click ranch chronic hammer sport near rotate charge lumber chicken cloud base thing forum
cosmos:
mingasprices: 2.0019294mesg
tendermint:
config:
consensus:
Expand All @@ -74,5 +76,6 @@ tendermint:
require.Equal(t, "tcp://0.0.0.0:26657", c.Tendermint.Config.RPC.ListenAddress)
require.Equal(t, tempPath, c.Path)
require.Equal(t, "engine", c.Name)
require.Equal(t, "2.0019294mesg", c.Cosmos.MinGasPrices)
})
}
6 changes: 3 additions & 3 deletions core/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ func loadOrGenDevGenesis(app *cosmos.App, kb *cosmos.Keybase, cfg *config.Config
"nodeID": validator.NodeID,
"peer": fmt.Sprintf("%s@%s:26656", validator.NodeID, validator.Name),
}).Warnln("Validator")
return cosmos.GenGenesis(kb, app.DefaultGenesis(), cfg.DevGenesis.ChainID, cfg.Tendermint.Config.GenesisFile(), []cosmos.GenesisValidator{validator})
return cosmos.GenGenesis(kb, app.DefaultGenesis(), cfg.DevGenesis.ChainID, cfg.DevGenesis.InitialBalances, cfg.Tendermint.Config.GenesisFile(), []cosmos.GenesisValidator{validator})
}

func main() {
Expand Down Expand Up @@ -136,7 +136,7 @@ func main() {
cosmos.CustomizeConfig()

// TODO: rename NewAppFactory to something else
appFactory := cosmos.NewAppFactory(logger.TendermintLogger(), db)
appFactory := cosmos.NewAppFactory(logger.TendermintLogger(), db, cfg.Cosmos.MinGasPrices)

// register the backend modules to the app factory.
// TODO: this is a mandatory call so it should return a new types required by cosmos.NewApp
Expand Down Expand Up @@ -174,7 +174,7 @@ func main() {
}

// create cosmos client
client := cosmos.NewClient(node, kb, genesis.ChainID, cfg.Account.Name, cfg.Account.Password)
client := cosmos.NewClient(node, kb, genesis.ChainID, cfg.Account.Name, cfg.Account.Password, cfg.Cosmos.MinGasPrices)

// init sdk
sdk := enginesdk.New(client, kb, container, cfg.Name, strconv.Itoa(port), cfg.IpfsEndpoint)
Expand Down
4 changes: 2 additions & 2 deletions cosmos/appfactory.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,12 @@ type AppFactory struct {
}

// NewAppFactory returns a new AppFactory.
func NewAppFactory(logger log.Logger, db dbm.DB) *AppFactory {
func NewAppFactory(logger log.Logger, db dbm.DB, minGasPrices string) *AppFactory {
sdk.RegisterCodec(codec.Codec)
cosmoscodec.RegisterCrypto(codec.Codec)

return &AppFactory{
baseApp: bam.NewBaseApp("engine", logger, db, auth.DefaultTxDecoder(codec.Codec)),
baseApp: bam.NewBaseApp("engine", logger, db, auth.DefaultTxDecoder(codec.Codec), baseapp.SetMinGasPrices(minGasPrices)),
modules: []module.AppModule{},
storeKeys: map[string]*sdk.KVStoreKey{
bam.MainStoreKey: sdk.NewKVStoreKey(bam.MainStoreKey),
Expand Down
44 changes: 33 additions & 11 deletions cosmos/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"github.com/cosmos/cosmos-sdk/crypto/keys"
sdktypes "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/auth"
authutils "github.com/cosmos/cosmos-sdk/x/auth/client/utils"
"github.com/mesg-foundation/engine/codec"
"github.com/mesg-foundation/engine/hash"
"github.com/mesg-foundation/engine/x/xreflect"
Expand All @@ -24,10 +25,11 @@ import (
// Client is a tendermint client with helper functions.
type Client struct {
*rpcclient.Local
kb keys.Keybase
chainID string
accName string
accPassword string
kb keys.Keybase
chainID string
accName string
accPassword string
minGasPrices string

// Local state
acc auth.Account
Expand All @@ -36,13 +38,14 @@ type Client struct {
}

// NewClient returns a rpc tendermint client.
func NewClient(node *node.Node, kb keys.Keybase, chainID, accName, accPassword string) *Client {
func NewClient(node *node.Node, kb keys.Keybase, chainID, accName, accPassword, minGasPrices string) *Client {
return &Client{
Local: rpcclient.NewLocal(node),
kb: kb,
chainID: chainID,
accName: accName,
accPassword: accPassword,
Local: rpcclient.NewLocal(node),
kb: kb,
chainID: chainID,
accName: accName,
accPassword: accPassword,
minGasPrices: minGasPrices,
}
}

Expand Down Expand Up @@ -204,7 +207,26 @@ func (c *Client) sign(msg sdktypes.Msg) (tenderminttypes.Tx, error) {
sequence := acc.GetSequence()
acc.SetSequence(acc.GetSequence() + 1)

txBuilder := NewTxBuilder(sequence, c.kb, c.chainID)
minGasPrices, err := sdktypes.ParseDecCoins(c.minGasPrices)
if err != nil {
return nil, err
}

txBuilder := NewTxBuilder(sequence, c.kb, c.chainID, minGasPrices)

// simulate tx to estimate the gas
if txBuilder.SimulateAndExecute() {
txBytes, err := txBuilder.BuildTxForSim([]sdktypes.Msg{msg})
if err != nil {
return nil, err
}
_, adjusted, err := authutils.CalculateGas(c.QueryWithData, codec.Codec, txBytes, txBuilder.GasAdjustment())
if err != nil {
return nil, err
}
txBuilder = txBuilder.WithGas(adjusted)
}

signedTx, err := txBuilder.BuildAndSignStdTx(msg, c.accName, c.accPassword)
if err != nil {
return nil, err
Expand Down
14 changes: 9 additions & 5 deletions cosmos/genesis.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ func LoadGenesis(genesisFile string) (*tmtypes.GenesisDoc, error) {
}

// GenGenesis generates a new genesis and save it.
func GenGenesis(kb *Keybase, defaultGenesisŚtate map[string]json.RawMessage, chainID string, genesisFile string, validators []GenesisValidator) (*tmtypes.GenesisDoc, error) {
func GenGenesis(kb *Keybase, defaultGenesisŚtate map[string]json.RawMessage, chainID, initialBalances, genesisFile string, validators []GenesisValidator) (*tmtypes.GenesisDoc, error) {
msgs := []sdktypes.Msg{}
for _, validator := range validators {
// get account
Expand All @@ -66,7 +66,7 @@ func GenGenesis(kb *Keybase, defaultGenesisŚtate map[string]json.RawMessage, ch
}
// generate genesis transaction
sequence := uint64(0)
b := NewTxBuilder(sequence, kb, chainID)
b := NewTxBuilder(sequence, kb, chainID, sdktypes.DecCoins{})
signedMsg, err := b.BuildSignMsg(msgs)
if err != nil {
return nil, err
Expand All @@ -79,7 +79,7 @@ func GenGenesis(kb *Keybase, defaultGenesisŚtate map[string]json.RawMessage, ch
}
}
// generate genesis
appState, err := genGenesisAppState(defaultGenesisŚtate, validatorTx)
appState, err := genGenesisAppState(defaultGenesisŚtate, validatorTx, initialBalances)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -108,11 +108,15 @@ func genGenesisDoc(appState map[string]json.RawMessage, chainID string, genesisT
return genesis, genesis.ValidateAndComplete()
}

func genGenesisAppState(defaultGenesisŚtate map[string]json.RawMessage, signedStdTx authtypes.StdTx) (map[string]json.RawMessage, error) {
func genGenesisAppState(defaultGenesisŚtate map[string]json.RawMessage, signedStdTx authtypes.StdTx, initialBalances string) (map[string]json.RawMessage, error) {
genAccs := []genaccounts.GenesisAccount{}
for _, signer := range signedStdTx.GetSigners() {
stakes := sdktypes.NewCoin(sdktypes.DefaultBondDenom, sdktypes.NewInt(100000000))
genAcc := genaccounts.NewGenesisAccountRaw(signer, sdktypes.NewCoins(stakes), sdktypes.NewCoins(), 0, 0, "", "")
initialB, err := sdktypes.ParseCoin(initialBalances)
if err != nil {
return nil, err
}
genAcc := genaccounts.NewGenesisAccountRaw(signer, sdktypes.NewCoins(stakes, initialB), sdktypes.NewCoins(), 0, 0, "", "")
if err := genAcc.Validate(); err != nil {
return nil, err
}
Expand Down
3 changes: 2 additions & 1 deletion cosmos/genesis_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ func TestGenesis(t *testing.T) {
// variables
var (
chainID = "test-chainID"
initialBalances = "100amesg"
name = "name"
password = "pass"
privValidatorKeyFile = filepath.Join(path, "privValidatorKeyFile.json")
Expand Down Expand Up @@ -57,7 +58,7 @@ func TestGenesis(t *testing.T) {
require.False(t, GenesisExist(genesisPath))
})
t.Run("generate genesis", func(t *testing.T) {
genesis, err := GenGenesis(kb, defaultGenesisState, chainID, genesisPath, validators)
genesis, err := GenGenesis(kb, defaultGenesisState, chainID, initialBalances, genesisPath, validators)
require.NoError(t, err)
require.NotEmpty(t, genesis)
})
Expand Down
12 changes: 9 additions & 3 deletions cosmos/txbuilder.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,23 +16,29 @@ type TxBuilder struct {
}

// NewTxBuilder returns a new initialized TxBuilder.
func NewTxBuilder(accSeq uint64, kb keys.Keybase, chainID string) TxBuilder {
func NewTxBuilder(accSeq uint64, kb keys.Keybase, chainID string, minGasPrices sdktypes.DecCoins) TxBuilder {
return TxBuilder{
authtypes.NewTxBuilder(
authutils.GetTxEncoder(codec.Codec),
AccNumber,
accSeq,
1000000,
flags.DefaultGasLimit,
flags.DefaultGasAdjustment,
true,
chainID,
"",
sdktypes.NewCoins(),
sdktypes.DecCoins{},
minGasPrices,
).WithKeybase(kb),
}
}

// WithGas returns a copy of the context with an updated gas.
func (b TxBuilder) WithGas(gas uint64) TxBuilder {
b.TxBuilder = b.TxBuilder.WithGas(gas)
return b
}

// BuildAndSignStdTx a signed transaction from a message.
func (b TxBuilder) BuildAndSignStdTx(msg sdktypes.Msg, accountName, accountPassword string) (authtypes.StdTx, error) {
signedMsg, err := b.BuildSignMsg([]sdktypes.Msg{msg})
Expand Down
2 changes: 1 addition & 1 deletion scripts/dev.sh
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ case $cmd in
start_engine
if ! $quiet; then
trap onexit EXIT
docker service logs --tail 10000 --follow --raw $MESG_NAME
docker service logs --tail 1000 --follow --raw $MESG_NAME
fi
;;
stop)
Expand Down