Skip to content

Commit

Permalink
Revert CLIContext to immutability
Browse files Browse the repository at this point in the history
  • Loading branch information
jackzampolin committed Jan 24, 2019
1 parent 57511bc commit 756d38b
Show file tree
Hide file tree
Showing 34 changed files with 148 additions and 145 deletions.
63 changes: 33 additions & 30 deletions client/context/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ type CLIContext struct {

// NewCLIContext returns a new initialized CLIContext with parameters from the
// command line using Viper.
func NewCLIContext(cdc *codec.Codec) *CLIContext {
func NewCLIContext(cdc *codec.Codec) CLIContext {
var rpc rpcclient.Client

nodeURI := viper.GetString(client.FlagNode)
Expand All @@ -65,7 +65,7 @@ func NewCLIContext(cdc *codec.Codec) *CLIContext {
verifier = createVerifier()
}

return &CLIContext{
return CLIContext{
Client: rpc,
Codec: cdc,
Output: os.Stdout,
Expand All @@ -88,81 +88,84 @@ func NewCLIContext(cdc *codec.Codec) *CLIContext {
}
}

func NewCLIContextTx(cdc *codec.Codec) *CLIContext {
ctx := NewCLIContext(cdc).SetAccountDecoder()
ctx.PrepareTxBldrOffline()
func NewCLIContextTx(cdc *codec.Codec) CLIContext {
ctx := NewCLIContext(cdc).WithAccountDecoder().WithTxBldrOffline()
return ctx
}

// PrepareTxBldrOffline sets the transaction builder for the context w/o
// WithTxBldrAddressOffline sets the transaction builder for the context w/o
// setting the sequence or account numbers
func (ctx *CLIContext) PrepareTxBldrOffline() {
func (ctx CLIContext) WithTxBldrOffline() CLIContext {
ctx.TxBldr = authtxb.NewTxBuilderFromCLI().WithTxEncoder(GetTxEncoder(ctx.Codec))
return ctx
}

// PrepareTxBldrWithAddress looks up the acc and seq numbs for an addr, also
// WithTxBldrAddress looks up the acc and seq numbs for an addr, also
// ensuring it exists
func (ctx *CLIContext) PrepareTxBldrWithAddress(addr sdk.AccAddress) error {
func (ctx CLIContext) WithTxBldrAddress(addr sdk.AccAddress) (CLIContext, error) {
if err := ctx.EnsureAccountExists(addr); err != nil {
return err
return ctx, err
}

if ctx.TxBldr.GetAccountNumber() == 0 || ctx.TxBldr.GetSequence() == 0 {
accNum, seq, err := ctx.FetchAccAndSeqNums(addr)
if err != nil {
return err
return ctx, err
}
ctx.TxBldr = ctx.TxBldr.WithAccountNumber(accNum).WithSequence(seq)
}
return nil
return ctx, nil
}

// SetAccountDecoder returns a copy of the context with an updated account
// WithMemo adds a memo to the TxBldr on the CLIContext
func (ctx CLIContext) WithMemo(s string) CLIContext {
ctx.TxBldr = ctx.TxBldr.WithMemo(s)
return ctx
}

// WithAccountDecoder returns a copy of the context with an updated account
// decoder.
func (ctx *CLIContext) SetAccountDecoder() *CLIContext {
func (ctx CLIContext) WithAccountDecoder() CLIContext {
ctx.AccDecoder = ctx.GetAccountDecoder()
return ctx
}

// GetAccountDecoder gets the account decoder for auth.DefaultAccount.
func (ctx *CLIContext) GetAccountDecoder() auth.AccountDecoder {
func (ctx CLIContext) GetAccountDecoder() auth.AccountDecoder {
return func(accBytes []byte) (acct auth.Account, err error) {
err = ctx.Codec.UnmarshalBinaryBare(accBytes, &acct)
if err != nil {
// TODO: remove this, and return the error,
// but first figure out where this is used
panic(err)
if err = ctx.Codec.UnmarshalBinaryBare(accBytes, &acct); err != nil {
return
}
return acct, err
return
}
}

// GetFromAddress returns the from address from the context's name.
func (ctx *CLIContext) FromAddr() sdk.AccAddress {
func (ctx CLIContext) FromAddr() sdk.AccAddress {
return ctx.fromAddress
}

// GetFromAddress returns the from address from the context's name
// in validator format
func (ctx *CLIContext) FromValAddr() sdk.ValAddress {
func (ctx CLIContext) FromValAddr() sdk.ValAddress {
return sdk.ValAddress(ctx.fromAddress.Bytes())
}

// GetFromName returns the key name for the current context.
func (ctx *CLIContext) FromName() string {
func (ctx CLIContext) FromName() string {
return ctx.fromName
}

// SetNode returns a copy of the context with an updated node URI.
func (ctx *CLIContext) SetNode(nodeURI string) *CLIContext {
// WithNode returns a copy of the context with an updated node URI.
func (ctx CLIContext) WithNode(nodeURI string) CLIContext {
ctx.NodeURI = nodeURI
ctx.Client = rpcclient.NewHTTP(nodeURI, "/websocket")
return ctx
}

// GetNode returns an RPC client. If the context's client is not defined, an
// error is returned.
func (ctx *CLIContext) GetNode() (rpcclient.Client, error) {
func (ctx CLIContext) GetNode() (rpcclient.Client, error) {
if ctx.Client == nil {
return nil, errors.New("no RPC client defined")
}
Expand All @@ -171,7 +174,7 @@ func (ctx *CLIContext) GetNode() (rpcclient.Client, error) {
}

// PrintOutput prints output while respecting output and indent flags
func (ctx *CLIContext) PrintOutput(toPrint fmt.Stringer) (err error) {
func (ctx CLIContext) PrintOutput(toPrint fmt.Stringer) (err error) {
var out []byte

switch ctx.OutputFormat {
Expand All @@ -195,7 +198,7 @@ func (ctx *CLIContext) PrintOutput(toPrint fmt.Stringer) (err error) {

// MessagesOutput respects flags while either generating a transaction
// for later signing, or signing and broadcasting those messages in a transaction
func (ctx *CLIContext) MessagesOutput(msgs []sdk.Msg) error {
func (ctx CLIContext) MessagesOutput(msgs []sdk.Msg) error {
for _, msg := range msgs {
if err := msg.ValidateBasic(); err != nil {
return err
Expand All @@ -211,7 +214,7 @@ func (ctx *CLIContext) MessagesOutput(msgs []sdk.Msg) error {

// MessageOutput respects flags while either generating a transaction
// for later signing, or signing and broadcasting those messages in a transaction
func (ctx *CLIContext) MessageOutput(msg sdk.Msg) error {
func (ctx CLIContext) MessageOutput(msg sdk.Msg) error {
return ctx.MessagesOutput([]sdk.Msg{msg})
}

Expand Down
2 changes: 1 addition & 1 deletion client/context/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ func (ctx CLIContext) QuerySubspace(subspace []byte, storeName string) (res []sd
// error is returned if the query or decoding fails.
func (ctx CLIContext) FetchAccount(address []byte) (auth.Account, error) {
if ctx.AccDecoder == nil {
ctx.SetAccountDecoder()
ctx.WithAccountDecoder()
}

res, err := ctx.QueryStore(auth.AddressStoreKey(address), ctx.AccountStore)
Expand Down
32 changes: 16 additions & 16 deletions client/context/tx.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,14 @@ import (
// supplied messages. Finally, it broadcasts the signed transaction to a node.
//
// NOTE: Also see CompleteAndBroadcastTxREST.
func (ctx *CLIContext) CompleteAndBroadcastTxCli(msgs []sdk.Msg) error {
err := ctx.PrepareTxBldrWithAddress(ctx.FromAddr())
func (ctx CLIContext) CompleteAndBroadcastTxCli(msgs []sdk.Msg) error {
ctx, err := ctx.WithTxBldrAddress(ctx.FromAddr())
if err != nil {
return err
}

if ctx.TxBldr.GetSimulateAndExecute() || ctx.Simulate {
err = ctx.EnrichCtxWithGas(ctx.FromName(), msgs)
ctx, err = ctx.EnrichCtxWithGas(ctx.FromName(), msgs)
if err != nil {
return err
}
Expand Down Expand Up @@ -57,13 +57,13 @@ func (ctx *CLIContext) CompleteAndBroadcastTxCli(msgs []sdk.Msg) error {

// EnrichCtxWithGas calculates the gas estimate that would be consumed by the
// transaction and set the transaction's respective value accordingly.
func (ctx *CLIContext) EnrichCtxWithGas(name string, msgs []sdk.Msg) error {
func (ctx CLIContext) EnrichCtxWithGas(name string, msgs []sdk.Msg) (CLIContext, error) {
_, adjusted, err := ctx.simulateMsgs(name, msgs)
if err != nil {
return err
return ctx, err
}
ctx.TxBldr = ctx.TxBldr.WithGas(adjusted)
return nil
return ctx, nil
}

// CalculateGas simulates the execution of a transaction and returns
Expand All @@ -88,7 +88,7 @@ func CalculateGas(queryFunc func(string, common.HexBytes) ([]byte, error), cdc *

// PrintUnsignedStdTx builds an unsigned StdTx and prints it to ctx.Ouput.
// Don't perform online validation or lookups if offline is true.
func (ctx *CLIContext) PrintUnsignedStdTx(w io.Writer, msgs []sdk.Msg, offline bool) (err error) {
func (ctx CLIContext) PrintUnsignedStdTx(w io.Writer, msgs []sdk.Msg, offline bool) (err error) {

var stdTx auth.StdTx

Expand All @@ -112,7 +112,7 @@ func (ctx *CLIContext) PrintUnsignedStdTx(w io.Writer, msgs []sdk.Msg, offline b
// SignStdTx appends a signature to a StdTx and returns a copy of a it. If appendSig
// is false, it replaces the signatures already attached with the new signature.
// Don't perform online validation or lookups if offline is true.
func (ctx *CLIContext) SignStdTx(name string, stdTx auth.StdTx, appendSig bool, offline bool) (auth.StdTx, error) {
func (ctx CLIContext) SignStdTx(name string, stdTx auth.StdTx, appendSig bool, offline bool) (auth.StdTx, error) {
var signedStdTx auth.StdTx

keybase, err := keys.GetKeyBase()
Expand All @@ -133,7 +133,7 @@ func (ctx *CLIContext) SignStdTx(name string, stdTx auth.StdTx, appendSig bool,
}

if !offline {
err = ctx.PrepareTxBldrWithAddress(addr)
ctx, err = ctx.WithTxBldrAddress(addr)
if err != nil {
return signedStdTx, err
}
Expand All @@ -150,7 +150,7 @@ func (ctx *CLIContext) SignStdTx(name string, stdTx auth.StdTx, appendSig bool,
// SignStdTxWithSignerAddress attaches a signature to a StdTx and returns a copy of a it.
// Don't perform online validation or lookups if offline is true, else
// populate account and sequence numbers from a foreign account.
func (ctx *CLIContext) SignStdTxWithSignerAddress(addr sdk.AccAddress,
func (ctx CLIContext) SignStdTxWithSignerAddress(addr sdk.AccAddress,
name string, stdTx auth.StdTx, offline bool) (signedStdTx auth.StdTx, err error) {

// check whether the address is a signer
Expand All @@ -159,7 +159,7 @@ func (ctx *CLIContext) SignStdTxWithSignerAddress(addr sdk.AccAddress,
}

if !offline {
err = ctx.PrepareTxBldrWithAddress(addr)
ctx, err = ctx.WithTxBldrAddress(addr)
if err != nil {
return signedStdTx, err
}
Expand All @@ -185,7 +185,7 @@ func GetTxEncoder(cdc *codec.Codec) (encoder sdk.TxEncoder) {

// nolint
// SimulateMsgs simulates the transaction and returns the gas estimate and the adjusted value.
func (ctx *CLIContext) simulateMsgs(name string, msgs []sdk.Msg) (uint64, uint64, error) {
func (ctx CLIContext) simulateMsgs(name string, msgs []sdk.Msg) (uint64, uint64, error) {
txBytes, err := ctx.TxBldr.BuildWithPubKey(name, msgs)
if err != nil {
return 0, 0, err
Expand All @@ -196,19 +196,19 @@ func (ctx *CLIContext) simulateMsgs(name string, msgs []sdk.Msg) (uint64, uint64

// buildUnsignedStdTx builds a StdTx as per the parameters passed in the
// contexts. Gas is automatically estimated if gas wanted is set to 0.
func (ctx *CLIContext) buildUnsignedStdTx(msgs []sdk.Msg) (stdTx auth.StdTx, err error) {
err = ctx.PrepareTxBldrWithAddress(ctx.FromAddr())
func (ctx CLIContext) buildUnsignedStdTx(msgs []sdk.Msg) (stdTx auth.StdTx, err error) {
ctx, err = ctx.WithTxBldrAddress(ctx.FromAddr())
if err != nil {
return
}
return ctx.buildUnsignedStdTxOffline(msgs)
}

func (ctx *CLIContext) buildUnsignedStdTxOffline(msgs []sdk.Msg) (stdTx auth.StdTx, err error) {
func (ctx CLIContext) buildUnsignedStdTxOffline(msgs []sdk.Msg) (stdTx auth.StdTx, err error) {
if ctx.TxBldr.GetSimulateAndExecute() {
var name = ctx.FromName()

err = ctx.EnrichCtxWithGas(name, msgs)
ctx, err = ctx.EnrichCtxWithGas(name, msgs)
if err != nil {
return
}
Expand Down
4 changes: 2 additions & 2 deletions client/lcd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ import (
// RestServer represents the Light Client Rest server
type RestServer struct {
Mux *mux.Router
CliCtx *context.CLIContext
CliCtx context.CLIContext
KeyBase keybase.Keybase
Cdc *codec.Codec

Expand All @@ -40,7 +40,7 @@ type RestServer struct {
// NewRestServer creates a new rest server instance
func NewRestServer(cdc *codec.Codec) *RestServer {
r := mux.NewRouter()
cliCtx := context.NewCLIContext(cdc).SetAccountDecoder()
cliCtx := context.NewCLIContext(cdc).WithAccountDecoder()
logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout)).With("module", "rest-server")

return &RestServer{
Expand Down
8 changes: 4 additions & 4 deletions client/rpc/block.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ func BlockCommand(cdc *codec.Codec) *cobra.Command {
return cmd
}

func getBlock(cliCtx *context.CLIContext, height *int64) ([]byte, error) {
func getBlock(cliCtx context.CLIContext, height *int64) ([]byte, error) {
// get the node
node, err := cliCtx.GetNode()
if err != nil {
Expand Down Expand Up @@ -91,7 +91,7 @@ func getBlock(cliCtx *context.CLIContext, height *int64) ([]byte, error) {
}

// get the current blockchain height
func GetChainHeight(cliCtx *context.CLIContext) (int64, error) {
func GetChainHeight(cliCtx context.CLIContext) (int64, error) {
node, err := cliCtx.GetNode()
if err != nil {
return -1, err
Expand All @@ -107,7 +107,7 @@ func GetChainHeight(cliCtx *context.CLIContext) (int64, error) {
// REST

// REST handler to get a block
func BlockRequestHandlerFn(cliCtx *context.CLIContext) http.HandlerFunc {
func BlockRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
height, err := strconv.ParseInt(vars["height"], 10, 64)
Expand All @@ -133,7 +133,7 @@ func BlockRequestHandlerFn(cliCtx *context.CLIContext) http.HandlerFunc {
}

// REST handler to get the latest block
func LatestBlockRequestHandlerFn(cliCtx *context.CLIContext) http.HandlerFunc {
func LatestBlockRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
height, err := GetChainHeight(cliCtx)
if err != nil {
Expand Down
4 changes: 2 additions & 2 deletions client/rpc/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import (
)

// Register REST endpoints
func RegisterRoutes(cliCtx *context.CLIContext, r *mux.Router) {
func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router) {
r.HandleFunc("/version", CLIVersionRequestHandler).Methods("GET")
r.HandleFunc("/node_version", NodeVersionRequestHandler(cliCtx)).Methods("GET")
r.HandleFunc("/node_info", NodeInfoRequestHandlerFn(cliCtx)).Methods("GET")
Expand All @@ -30,7 +30,7 @@ func CLIVersionRequestHandler(w http.ResponseWriter, r *http.Request) {
}

// connected node version REST handler endpoint
func NodeVersionRequestHandler(cliCtx *context.CLIContext) http.HandlerFunc {
func NodeVersionRequestHandler(cliCtx context.CLIContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
version, err := cliCtx.Query("/app/version", nil)
if err != nil {
Expand Down
6 changes: 3 additions & 3 deletions client/rpc/status.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ func StatusCommand(cdc *codec.Codec) *cobra.Command {
return cmd
}

func getNodeStatus(cliCtx *context.CLIContext) (*ctypes.ResultStatus, error) {
func getNodeStatus(cliCtx context.CLIContext) (*ctypes.ResultStatus, error) {
// get the node
node, err := cliCtx.GetNode()
if err != nil {
Expand All @@ -62,7 +62,7 @@ func getNodeStatus(cliCtx *context.CLIContext) (*ctypes.ResultStatus, error) {
// REST

// REST handler for node info
func NodeInfoRequestHandlerFn(cliCtx *context.CLIContext) http.HandlerFunc {
func NodeInfoRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
status, err := getNodeStatus(cliCtx)
if err != nil {
Expand All @@ -77,7 +77,7 @@ func NodeInfoRequestHandlerFn(cliCtx *context.CLIContext) http.HandlerFunc {
}

// REST handler for node syncing
func NodeSyncingRequestHandlerFn(cliCtx *context.CLIContext) http.HandlerFunc {
func NodeSyncingRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
status, err := getNodeStatus(cliCtx)
if err != nil {
Expand Down
Loading

0 comments on commit 756d38b

Please sign in to comment.