cosmos-sdk/client/context/viper.go

75 lines
2.0 KiB
Go
Raw Normal View History

package context
import (
2018-04-09 08:59:01 -07:00
"fmt"
2018-04-18 12:39:32 -07:00
"github.com/spf13/viper"
tcmd "github.com/tendermint/tendermint/cmd/tendermint/commands"
rpcclient "github.com/tendermint/tendermint/rpc/client"
tmtypes "github.com/tendermint/tendermint/types"
"github.com/cosmos/cosmos-sdk/client"
)
2018-04-10 02:15:34 -07:00
// NewCoreContextFromViper - return a new context with parameters from the command line
2018-04-18 12:39:32 -07:00
func NewCoreContextFromViper() CoreContext {
nodeURI := viper.GetString(client.FlagNode)
var rpc rpcclient.Client
if nodeURI != "" {
rpc = rpcclient.NewHTTP(nodeURI, "/websocket")
}
chainID := viper.GetString(client.FlagChainID)
2018-04-10 02:15:34 -07:00
// if chain ID is not specified manually, read default chain ID
if chainID == "" {
2018-04-10 02:15:34 -07:00
def, err := defaultChainID()
if err != nil {
chainID = def
}
}
2018-04-18 12:39:32 -07:00
return CoreContext{
ChainID: chainID,
Height: viper.GetInt64(client.FlagHeight),
Gas: viper.GetInt64(client.FlagGas),
TrustNode: viper.GetBool(client.FlagTrustNode),
FromAddressName: viper.GetString(client.FlagName),
NodeURI: nodeURI,
Sequence: viper.GetInt64(client.FlagSequence),
Client: rpc,
Decoder: nil,
2018-05-03 09:35:12 -07:00
AccountStore: "acc",
}
}
2018-04-09 08:59:01 -07:00
2018-04-10 02:15:34 -07:00
// read chain ID from genesis file, if present
func defaultChainID() (string, error) {
cfg, err := tcmd.ParseConfig()
if err != nil {
return "", err
}
2018-04-11 08:47:56 -07:00
doc, err := tmtypes.GenesisDocFromFile(cfg.GenesisFile())
2018-04-10 02:15:34 -07:00
if err != nil {
return "", err
}
return doc.ChainID, nil
}
// EnsureSequence - automatically set sequence number if none provided
2018-04-18 12:39:32 -07:00
func EnsureSequence(ctx CoreContext) (CoreContext, error) {
2018-05-03 09:35:12 -07:00
// Should be viper.IsSet, but this does not work - https://github.com/spf13/viper/pull/331
if viper.GetInt64(client.FlagSequence) != 0 {
2018-04-10 02:15:34 -07:00
return ctx, nil
}
from, err := ctx.GetFromAddress()
if err != nil {
return ctx, err
}
seq, err := ctx.NextSequence(from)
if err != nil {
return ctx, err
2018-04-09 08:59:01 -07:00
}
2018-04-10 02:15:34 -07:00
fmt.Printf("Defaulting to next sequence number: %d\n", seq)
ctx = ctx.WithSequence(seq)
2018-04-09 08:59:01 -07:00
return ctx, nil
}