github.com/loomnetwork/gamechain@v0.0.0-20200406110549-36c47eb97a92/cli/cmd/root.go (about) 1 package cmd 2 3 import ( 4 "encoding/base64" 5 "fmt" 6 "github.com/pkg/errors" 7 "io/ioutil" 8 9 "github.com/loomnetwork/go-loom/client" 10 "github.com/spf13/cobra" 11 ) 12 13 var rootCmdArgs struct { 14 privateKeyFilePath string 15 readURI string 16 writeURI string 17 chainID string 18 outputFormat string 19 } 20 21 var commonTxObjs struct { 22 privateKey []byte 23 contract *client.Contract 24 rpcClient *client.DAppChainRPCClient 25 } 26 27 func readKeyFile(path string) ([]byte, error) { 28 fileContents, err := ioutil.ReadFile(path) 29 if err != nil { 30 return nil, errors.Wrapf(err, "unable to read private key from file: %s", path) 31 } 32 33 decodeBuffer := make([]byte, len(fileContents)) 34 bytesDecoded, err := base64.StdEncoding.Decode(decodeBuffer, fileContents) 35 if err != nil { 36 return nil, errors.Wrapf(err, "invalid base64 content in private key file: %s", path) 37 } 38 39 return decodeBuffer[:bytesDecoded], nil 40 } 41 42 func connectToRPC(chainID, readURI, writeURI string) error { 43 rpcClient := client.NewDAppChainRPCClient(chainID, writeURI, readURI) 44 45 loomAddress, err := rpcClient.Resolve("ZombieBattleground") 46 if err != nil { 47 return fmt.Errorf("unable to resolve RPC connection. RPC Error:%s", err.Error()) 48 } 49 50 commonTxObjs.contract = client.NewContract(rpcClient, loomAddress.Local) 51 commonTxObjs.rpcClient = rpcClient 52 53 return nil 54 } 55 56 var rootCmd = &cobra.Command{ 57 Use: "zb-cli", 58 Short: "ZombieBattleGround cli tool", 59 PersistentPreRunE: func(command *cobra.Command, args []string) error { 60 if command.Use == "merge_json_to_init" { 61 return nil 62 } 63 64 var err error 65 66 commonTxObjs.privateKey, err = readKeyFile(rootCmdArgs.privateKeyFilePath) 67 if err != nil { 68 return fmt.Errorf("error while reading private key file: %s", err.Error()) 69 } 70 71 err = connectToRPC(rootCmdArgs.chainID, rootCmdArgs.readURI, rootCmdArgs.writeURI) 72 if err != nil { 73 return fmt.Errorf("error while establishing RPC connection: %s", err.Error()) 74 } 75 76 return nil 77 }, 78 } 79 80 func Execute() error { 81 rootCmd.PersistentFlags().StringVarP(&rootCmdArgs.privateKeyFilePath, "key", "k", "priv.key", "Private key file path") 82 rootCmd.PersistentFlags().StringVarP(&rootCmdArgs.readURI, "readURI", "r", "http://localhost:46658/query", "Read URI for rpc") 83 rootCmd.PersistentFlags().StringVarP(&rootCmdArgs.writeURI, "writeURI", "w", "http://localhost:46658/rpc", "Write URI for rpc") 84 rootCmd.PersistentFlags().StringVarP(&rootCmdArgs.chainID, "chainID", "c", "default", "Chain ID") 85 rootCmd.PersistentFlags().StringVarP(&rootCmdArgs.outputFormat, "output", "O", "plaintext", "format of the output (json, plaintext)") 86 87 return rootCmd.Execute() 88 }