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

     1  package flags
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"strconv"
     7  
     8  	"github.com/spf13/cobra"
     9  	"github.com/spf13/viper"
    10  
    11  	tmcli "github.com/fibonacci-chain/fbc/libs/tendermint/libs/cli"
    12  
    13  	"github.com/fibonacci-chain/fbc/libs/cosmos-sdk/crypto/keys"
    14  )
    15  
    16  // nolint
    17  const (
    18  	// DefaultGasAdjustment is applied to gas estimates to avoid tx execution
    19  	// failures due to state changes that might occur between the tx simulation
    20  	// and the actual run.
    21  	DefaultGasAdjustment = 1.0
    22  	DefaultGasLimit      = 200000
    23  	GasFlagAuto          = "auto"
    24  
    25  	// DefaultKeyringBackend
    26  	DefaultKeyringBackend = keys.BackendTest
    27  )
    28  
    29  const (
    30  	// BroadcastBlock defines a tx broadcasting mode where the client waits for
    31  	// the tx to be committed in a block.
    32  	BroadcastBlock = "block"
    33  	// BroadcastSync defines a tx broadcasting mode where the client waits for
    34  	// a CheckTx execution response only.
    35  	BroadcastSync = "sync"
    36  	// BroadcastAsync defines a tx broadcasting mode where the client returns
    37  	// immediately.
    38  	BroadcastAsync = "async"
    39  )
    40  
    41  // List of CLI flags
    42  const (
    43  	FlagHome               = tmcli.HomeFlag
    44  	FlagUseLedger          = "ledger"
    45  	FlagChainID            = "chain-id"
    46  	FlagNode               = "node"
    47  	FlagHeight             = "height"
    48  	FlagGasAdjustment      = "gas-adjustment"
    49  	FlagTrustNode          = "trust-node"
    50  	FlagFrom               = "from"
    51  	FlagName               = "name"
    52  	FlagAccountNumber      = "account-number"
    53  	FlagSequence           = "sequence"
    54  	FlagMemo               = "memo"
    55  	FlagFees               = "fees"
    56  	FlagGasPrices          = "gas-prices"
    57  	FlagBroadcastMode      = "broadcast-mode"
    58  	FlagDryRun             = "dry-run"
    59  	FlagGenerateOnly       = "generate-only"
    60  	FlagIndentResponse     = "indent"
    61  	FlagListenAddr         = "laddr"
    62  	FlagMaxOpenConnections = "max-open"
    63  	FlagRPCReadTimeout     = "read-timeout"
    64  	FlagRPCWriteTimeout    = "write-timeout"
    65  	FlagOutputDocument     = "output-document" // inspired by wget -O
    66  	FlagSkipConfirmation   = "yes"
    67  	FlagProve              = "prove"
    68  	FlagKeyringBackend     = "keyring-backend"
    69  	FlagPage               = "page"
    70  	FlagLimit              = "limit"
    71  	FlagUnsafeCORS         = "unsafe-cors"
    72  	FlagNodeIndex          = "node-index"
    73  
    74  	TrustNodeUsage = `Using true doesn't verify results, quickly(300~400ms). True is recommended to connect familiar or self-built nodes. 
    75  Using false verifies the proof of results, safely but slowly(2~3s). False is recommended to connect to unfamiliar nodes.`
    76  )
    77  
    78  const (
    79  	FlagPageKey       = "page-key"
    80  	FlagOffset        = "offset"
    81  	FlagTimeoutHeight = "timeout-height"
    82  	FlagCountTotal    = "count-total"
    83  )
    84  
    85  // LineBreak can be included in a command list to provide a blank line
    86  // to help with readability
    87  var (
    88  	LineBreak  = &cobra.Command{Run: func(*cobra.Command, []string) {}}
    89  	GasFlagVar = GasSetting{Gas: DefaultGasLimit}
    90  )
    91  
    92  // GetCommands adds common flags to query commands
    93  func GetCommands(cmds ...*cobra.Command) []*cobra.Command {
    94  	for _, c := range cmds {
    95  		c.Flags().Bool(FlagIndentResponse, false, "Add indent to JSON response")
    96  		c.Flags().Bool(FlagTrustNode, false, TrustNodeUsage)
    97  		c.Flags().Bool(FlagUseLedger, false, "Use a connected Ledger device")
    98  		c.Flags().String(FlagNode, "tcp://localhost:26657", "<host>:<port> to Tendermint RPC interface for this chain")
    99  		c.Flags().Int64(FlagHeight, 0, "Use a specific height to query state at (this can error if the node is pruning state)")
   100  
   101  		viper.BindPFlag(FlagTrustNode, c.Flags().Lookup(FlagTrustNode))
   102  		viper.BindPFlag(FlagUseLedger, c.Flags().Lookup(FlagUseLedger))
   103  		viper.BindPFlag(FlagNode, c.Flags().Lookup(FlagNode))
   104  
   105  		c.MarkFlagRequired(FlagChainID)
   106  
   107  		c.SetErr(c.ErrOrStderr())
   108  	}
   109  	return cmds
   110  }
   111  
   112  // PostCommands adds common flags for commands to post tx
   113  func PostCommands(cmds ...*cobra.Command) []*cobra.Command {
   114  	for _, c := range cmds {
   115  		c.Flags().Bool(FlagIndentResponse, false, "Add indent to JSON response")
   116  		c.Flags().String(FlagFrom, "", "Name or address of private key with which to sign")
   117  		c.Flags().Uint64P(FlagAccountNumber, "a", 0, "The account number of the signing account (offline mode only)")
   118  		c.Flags().Uint64(FlagSequence, 0, "The sequence number of the signing account (offline mode only)")
   119  		c.Flags().String(FlagMemo, "", "Memo to send along with transaction")
   120  		c.Flags().String(FlagFees, "", "Fees to pay along with transaction; eg: 10uatom")
   121  		c.Flags().String(FlagGasPrices, "", "Gas prices to determine the transaction fee (e.g. 10uatom)")
   122  		c.Flags().String(FlagNode, "tcp://localhost:26657", "<host>:<port> to tendermint rpc interface for this chain")
   123  		c.Flags().Bool(FlagUseLedger, false, "Use a connected Ledger device")
   124  		c.Flags().Float64(FlagGasAdjustment, DefaultGasAdjustment, "adjustment factor to be multiplied against the estimate returned by the tx simulation; if the gas limit is set manually this flag is ignored ")
   125  		c.Flags().StringP(FlagBroadcastMode, "b", BroadcastSync, "Transaction broadcasting mode (sync|async|block)")
   126  		c.Flags().Bool(FlagTrustNode, true, TrustNodeUsage)
   127  		c.Flags().Bool(FlagDryRun, false, "ignore the --gas flag and perform a simulation of a transaction, but don't broadcast it")
   128  		c.Flags().Bool(FlagGenerateOnly, false, "Build an unsigned transaction and write it to STDOUT (when enabled, the local Keybase is not accessible and the node operates offline)")
   129  		c.Flags().BoolP(FlagSkipConfirmation, "y", false, "Skip tx broadcasting prompt confirmation")
   130  		c.Flags().String(FlagKeyringBackend, DefaultKeyringBackend, "Select keyring's backend (os|file|test)")
   131  
   132  		// --gas can accept integers and "simulate"
   133  		c.Flags().Var(&GasFlagVar, "gas", fmt.Sprintf(
   134  			"gas limit to set per-transaction; set to %q to calculate required gas automatically (default %d)",
   135  			GasFlagAuto, DefaultGasLimit,
   136  		))
   137  		viper.BindPFlag(FlagTrustNode, c.Flags().Lookup(FlagTrustNode))
   138  		viper.BindPFlag(FlagUseLedger, c.Flags().Lookup(FlagUseLedger))
   139  		viper.BindPFlag(FlagNode, c.Flags().Lookup(FlagNode))
   140  		viper.BindPFlag(FlagKeyringBackend, c.Flags().Lookup(FlagKeyringBackend))
   141  
   142  		c.MarkFlagRequired(FlagChainID)
   143  
   144  		c.SetErr(c.ErrOrStderr())
   145  	}
   146  	return cmds
   147  }
   148  
   149  // RegisterRestServerFlags registers the flags required for rest server
   150  func RegisterRestServerFlags(cmd *cobra.Command) *cobra.Command {
   151  	cmd = GetCommands(cmd)[0]
   152  	cmd.Flags().String(FlagListenAddr, "tcp://localhost:1317", "The address for the server to listen on")
   153  	cmd.Flags().Uint(FlagMaxOpenConnections, 1000, "The number of maximum open connections")
   154  	cmd.Flags().Uint(FlagRPCReadTimeout, 10, "The RPC read timeout (in seconds)")
   155  	cmd.Flags().Uint(FlagRPCWriteTimeout, 10, "The RPC write timeout (in seconds)")
   156  	cmd.Flags().Bool(FlagUnsafeCORS, false, "Allows CORS requests from all domains. For development purposes only, use it at your own risk.")
   157  
   158  	return cmd
   159  }
   160  
   161  // Gas flag parsing functions
   162  
   163  // GasSetting encapsulates the possible values passed through the --gas flag.
   164  type GasSetting struct {
   165  	Simulate bool
   166  	Gas      uint64
   167  }
   168  
   169  // Type returns the flag's value type.
   170  func (v *GasSetting) Type() string { return "string" }
   171  
   172  // Set parses and sets the value of the --gas flag.
   173  func (v *GasSetting) Set(s string) (err error) {
   174  	v.Simulate, v.Gas, err = ParseGas(s)
   175  	return
   176  }
   177  
   178  func (v *GasSetting) String() string {
   179  	if v.Simulate {
   180  		return GasFlagAuto
   181  	}
   182  	return strconv.FormatUint(v.Gas, 10)
   183  }
   184  
   185  // ParseGas parses the value of the gas option.
   186  func ParseGas(gasStr string) (simulateAndExecute bool, gas uint64, err error) {
   187  	switch gasStr {
   188  	case "":
   189  		gas = DefaultGasLimit
   190  	case GasFlagAuto:
   191  		simulateAndExecute = true
   192  	default:
   193  		gas, err = strconv.ParseUint(gasStr, 10, 64)
   194  		if err != nil {
   195  			err = fmt.Errorf("gas must be either integer or %q", GasFlagAuto)
   196  			return
   197  		}
   198  	}
   199  	return
   200  }
   201  
   202  // NewCompletionCmd builds a cobra.Command that generate bash completion
   203  // scripts for the given root command. If hidden is true, the command
   204  // will not show up in the root command's list of available commands.
   205  func NewCompletionCmd(rootCmd *cobra.Command, hidden bool) *cobra.Command {
   206  	flagZsh := "zsh"
   207  	cmd := &cobra.Command{
   208  		Use:   "completion",
   209  		Short: "Generate Bash/Zsh completion script to STDOUT",
   210  		Long: `To load completion script run
   211  
   212  . <(completion_script)
   213  
   214  To configure your bash shell to load completions for each session add to your bashrc
   215  
   216  # ~/.bashrc or ~/.profile
   217  . <(completion_script)
   218  `,
   219  		RunE: func(_ *cobra.Command, _ []string) error {
   220  			if viper.GetBool(flagZsh) {
   221  				return rootCmd.GenZshCompletion(os.Stdout)
   222  			}
   223  			return rootCmd.GenBashCompletion(os.Stdout)
   224  		},
   225  		Hidden: hidden,
   226  		Args:   cobra.NoArgs,
   227  	}
   228  
   229  	cmd.Flags().Bool(flagZsh, false, "Generate Zsh completion script")
   230  
   231  	return cmd
   232  }
   233  
   234  // AddQueryFlagsToCmd adds common flags to a module query command.
   235  func AddQueryFlagsToCmd(cmd *cobra.Command) {
   236  	cmd.Flags().String(FlagNode, "tcp://localhost:26657", "<host>:<port> to Tendermint RPC interface for this chain")
   237  	cmd.Flags().Int64(FlagHeight, 0, "Use a specific height to query state at (this can error if the node is pruning state)")
   238  	cmd.Flags().StringP(tmcli.OutputFlag, "o", "text", "Output format (text|json)")
   239  
   240  	cmd.MarkFlagRequired(FlagChainID)
   241  
   242  	cmd.SetErr(cmd.ErrOrStderr())
   243  	cmd.SetOut(cmd.OutOrStdout())
   244  }
   245  
   246  // AddTxFlagsToCmd adds common flags to a module tx command.
   247  func AddTxFlagsToCmd(cmd *cobra.Command) {
   248  	cmd.Flags().String(FlagFrom, "", "Name or address of private key with which to sign")
   249  	cmd.Flags().Uint64P(FlagAccountNumber, "a", 0, "The account number of the signing account (offline mode only)")
   250  	cmd.Flags().Uint64P(FlagSequence, "s", 0, "The sequence number of the signing account (offline mode only)")
   251  	cmd.Flags().String(FlagMemo, "", "Memo to send along with transaction")
   252  	cmd.Flags().String(FlagFees, "", "Fees to pay along with transaction; eg: 10uatom")
   253  	cmd.Flags().String(FlagGasPrices, "", "Gas prices in decimal format to determine the transaction fee (e.g. 0.1uatom)")
   254  	cmd.Flags().String(FlagNode, "tcp://localhost:26657", "<host>:<port> to tendermint rpc interface for this chain")
   255  	cmd.Flags().Bool(FlagUseLedger, false, "Use a connected Ledger device")
   256  	cmd.Flags().Float64(FlagGasAdjustment, DefaultGasAdjustment, "adjustment factor to be multiplied against the estimate returned by the tx simulation; if the gas limit is set manually this flag is ignored ")
   257  	cmd.Flags().StringP(FlagBroadcastMode, "b", BroadcastSync, "Transaction broadcasting mode (sync|async|block)")
   258  	cmd.Flags().Bool(FlagDryRun, false, "ignore the --gas flag and perform a simulation of a transaction, but don't broadcast it")
   259  	cmd.Flags().Bool(FlagGenerateOnly, false, "Build an unsigned transaction and write it to STDOUT (when enabled, the local Keybase is not accessible)")
   260  	cmd.Flags().BoolP(FlagSkipConfirmation, "y", false, "Skip tx broadcasting prompt confirmation")
   261  	cmd.Flags().String(FlagKeyringBackend, DefaultKeyringBackend, "Select keyring's backend (os|file|kwallet|pass|test|memory)")
   262  	cmd.Flags().Uint64(FlagTimeoutHeight, 0, "Set a block timeout height to prevent the tx from being committed past a certain height")
   263  
   264  	// --gas can accept integers and "auto"
   265  
   266  	cmd.MarkFlagRequired(FlagChainID)
   267  	cmd.Flags().Uint64Var(&GasFlagVar.Gas, "gas", DefaultGasLimit, fmt.Sprintf(
   268  		"gas limit to set per-transaction; set to %q to calculate required gas automatically (default %d)",
   269  		GasFlagAuto, DefaultGasLimit,
   270  	))
   271  
   272  	cmd.SetErr(cmd.ErrOrStderr())
   273  	cmd.SetOut(cmd.OutOrStdout())
   274  }
   275  
   276  // AddPaginationFlagsToCmd adds common pagination flags to cmd
   277  func AddPaginationFlagsToCmd(cmd *cobra.Command, query string) {
   278  	cmd.Flags().Uint64(FlagPage, 1, fmt.Sprintf("pagination page of %s to query for. This sets offset to a multiple of limit", query))
   279  	cmd.Flags().String(FlagPageKey, "", fmt.Sprintf("pagination page-key of %s to query for", query))
   280  	cmd.Flags().Uint64(FlagOffset, 0, fmt.Sprintf("pagination offset of %s to query for", query))
   281  	cmd.Flags().Uint64(FlagLimit, 100, fmt.Sprintf("pagination limit of %s to query for", query))
   282  	cmd.Flags().Bool(FlagCountTotal, false, fmt.Sprintf("count total number of records in %s to query for", query))
   283  }