@@ -18,6 +18,7 @@ package main
18
18
19
19
import (
20
20
"bufio"
21
+ "encoding/json"
21
22
"fmt"
22
23
"io"
23
24
"os"
@@ -37,8 +38,16 @@ const (
37
38
flagRecover = "recover"
38
39
flagMnemonicSrc = "source"
39
40
flagBech32Prefix = "bech32"
41
+ flagOutput = "output"
40
42
)
41
43
44
+ type keyJsonOutput map [string ]keyJsonOutputElem
45
+
46
+ type keyJsonOutputElem struct {
47
+ Address string `json:"address"`
48
+ Mnemonic string `json:"mnemonic"`
49
+ }
50
+
42
51
// keysCmd represents the keys command
43
52
func keysCmd (ctx * cmdContext ) * cobra.Command {
44
53
cmd := & cobra.Command {
@@ -69,7 +78,8 @@ func keysAddCmd(ctx *cmdContext) *cobra.Command {
69
78
$ keys add localnet key1
70
79
$ keys add l2 key2 --bech32 celestia
71
80
$ keys add l2 key2 --recover
72
- $ keys add l2 key2 --recover --source mnemonic.txt` ),
81
+ $ keys add l2 key2 --recover --source mnemonic.txt
82
+ $ keys add l2 key2 --output json` ),
73
83
RunE : func (cmd * cobra.Command , args []string ) error {
74
84
chainId := args [0 ]
75
85
keyName := args [1 ]
@@ -138,13 +148,32 @@ $ keys add l2 key2 --recover --source mnemonic.txt`),
138
148
return err
139
149
}
140
150
141
- fmt .Fprintf (cmd .OutOrStdout (), "%s: %s\n %s\n " , account .Name , addrString , mnemonic )
151
+ outputFormat , _ := cmd .Flags ().GetString (flagOutput )
152
+ var output string
153
+ switch outputFormat {
154
+ case "json" :
155
+ jsonOutput := make (keyJsonOutput )
156
+ jsonOutput [account .Name ] = keyJsonOutputElem {
157
+ Address : addrString ,
158
+ Mnemonic : mnemonic ,
159
+ }
160
+ outputBytes , err := json .Marshal (& jsonOutput )
161
+ if err != nil {
162
+ return err
163
+ }
164
+ output = string (outputBytes )
165
+ default :
166
+ output = fmt .Sprintf ("%s: %s\n %s" , account .Name , addrString , mnemonic )
167
+ }
168
+
169
+ fmt .Fprintln (cmd .OutOrStdout (), output )
142
170
return nil
143
171
},
144
172
}
145
173
cmd .Flags ().Bool (flagRecover , false , "Provide seed phrase to recover existing key instead of creating" )
146
174
cmd .Flags ().String (flagMnemonicSrc , "" , "Import mnemonic from a file" )
147
175
cmd .Flags ().String (flagBech32Prefix , "init" , "Bech32 prefix" )
176
+ cmd .Flags ().String (flagOutput , "plain" , "Output format (plain|json)" )
148
177
return cmd
149
178
}
150
179
0 commit comments