-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
prompt.go
337 lines (286 loc) · 8.99 KB
/
prompt.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
package cli
import (
"encoding/json"
"fmt"
"os"
"reflect" // #nosec
"sort"
"strconv"
"strings"
"github.com/manifoldco/promptui"
"github.com/spf13/cobra"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
"github.com/cosmos/cosmos-sdk/x/gov/types"
)
const (
proposalText = "text"
proposalOther = "other"
draftProposalFileName = "draft_proposal.json"
draftMetadataFileName = "draft_metadata.json"
)
var suggestedProposalTypes = []proposalType{
{
Name: proposalText,
MsgType: "", // no message for text proposal
},
{
Name: "community-pool-spend",
MsgType: "/cosmos.distribution.v1beta1.MsgCommunityPoolSpend",
},
{
Name: "software-upgrade",
MsgType: "/cosmos.upgrade.v1beta1.MsgSoftwareUpgrade",
},
{
Name: "cancel-software-upgrade",
MsgType: "/cosmos.upgrade.v1beta1.MsgCancelUpgrade",
},
{
Name: proposalOther,
MsgType: "", // user will input the message type
},
}
// Prompt prompts the user for all values of the given type.
// data is the struct to be filled
// namePrefix is the name to be displayed as "Enter <namePrefix> <field>"
func Prompt[T any](data T, namePrefix string) (T, error) {
v := reflect.ValueOf(&data).Elem()
if v.Kind() == reflect.Interface {
v = reflect.ValueOf(data)
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
}
for i := 0; i < v.NumField(); i++ {
// if the field is a struct skip or not slice of string or int then skip
switch v.Field(i).Kind() {
case reflect.Struct:
// TODO(@julienrbrt) in the future we can add a recursive call to Prompt
continue
case reflect.Slice:
if v.Field(i).Type().Elem().Kind() != reflect.String && v.Field(i).Type().Elem().Kind() != reflect.Int {
continue
}
}
// create prompts
prompt := promptui.Prompt{
Label: fmt.Sprintf("Enter %s %s", namePrefix, strings.ToLower(client.CamelCaseToString(v.Type().Field(i).Name))),
Validate: client.ValidatePromptNotEmpty,
}
fieldName := strings.ToLower(v.Type().Field(i).Name)
if strings.EqualFold(fieldName, "authority") {
// pre-fill with gov address
prompt.Default = authtypes.NewModuleAddress(types.ModuleName).String()
prompt.Validate = client.ValidatePromptAddress
}
// TODO(@julienrbrt) use scalar annotation instead of dumb string name matching
if strings.Contains(fieldName, "addr") ||
strings.Contains(fieldName, "sender") ||
strings.Contains(fieldName, "voter") ||
strings.Contains(fieldName, "depositor") ||
strings.Contains(fieldName, "granter") ||
strings.Contains(fieldName, "grantee") ||
strings.Contains(fieldName, "recipient") {
prompt.Validate = client.ValidatePromptAddress
}
result, err := prompt.Run()
if err != nil {
return data, fmt.Errorf("failed to prompt for %s: %w", fieldName, err)
}
switch v.Field(i).Kind() {
case reflect.String:
v.Field(i).SetString(result)
case reflect.Int:
resultInt, err := strconv.ParseInt(result, 10, 0)
if err != nil {
return data, fmt.Errorf("invalid value for int: %w", err)
}
// If a value was successfully parsed the ranges of:
// [minInt, maxInt]
// are within the ranges of:
// [minInt64, maxInt64]
// of which on 64-bit machines, which are most common,
// int==int64
v.Field(i).SetInt(resultInt)
case reflect.Slice:
switch v.Field(i).Type().Elem().Kind() {
case reflect.String:
v.Field(i).Set(reflect.ValueOf([]string{result}))
case reflect.Int:
resultInt, err := strconv.ParseInt(result, 10, 0)
if err != nil {
return data, fmt.Errorf("invalid value for int: %w", err)
}
v.Field(i).Set(reflect.ValueOf([]int{int(resultInt)}))
}
default:
// skip any other types
continue
}
}
return data, nil
}
type proposalType struct {
Name string
MsgType string
Msg sdk.Msg
}
// Prompt the proposal type values and return the proposal and its metadata
func (p *proposalType) Prompt(cdc codec.Codec, skipMetadata bool) (*proposal, types.ProposalMetadata, error) {
metadata, err := PromptMetadata(skipMetadata)
if err != nil {
return nil, metadata, fmt.Errorf("failed to set proposal metadata: %w", err)
}
proposal := &proposal{
Metadata: "ipfs://CID", // the metadata must be saved on IPFS, set placeholder
Title: metadata.Title,
Summary: metadata.Summary,
}
// set deposit
depositPrompt := promptui.Prompt{
Label: "Enter proposal deposit",
Validate: client.ValidatePromptCoins,
}
proposal.Deposit, err = depositPrompt.Run()
if err != nil {
return nil, metadata, fmt.Errorf("failed to set proposal deposit: %w", err)
}
if p.Msg == nil {
return proposal, metadata, nil
}
// set messages field
result, err := Prompt(p.Msg, "msg")
if err != nil {
return nil, metadata, fmt.Errorf("failed to set proposal message: %w", err)
}
message, err := cdc.MarshalInterfaceJSON(result)
if err != nil {
return nil, metadata, fmt.Errorf("failed to marshal proposal message: %w", err)
}
proposal.Messages = append(proposal.Messages, message)
return proposal, metadata, nil
}
// getProposalSuggestions suggests a list of proposal types
func getProposalSuggestions() []string {
types := make([]string, len(suggestedProposalTypes))
for i, p := range suggestedProposalTypes {
types[i] = p.Name
}
return types
}
// PromptMetadata prompts for proposal metadata or only title and summary if skip is true
func PromptMetadata(skip bool) (types.ProposalMetadata, error) {
if !skip {
metadata, err := Prompt(types.ProposalMetadata{}, "proposal")
if err != nil {
return metadata, fmt.Errorf("failed to set proposal metadata: %w", err)
}
return metadata, nil
}
// prompt for title and summary
titlePrompt := promptui.Prompt{
Label: "Enter proposal title",
Validate: client.ValidatePromptNotEmpty,
}
title, err := titlePrompt.Run()
if err != nil {
return types.ProposalMetadata{}, fmt.Errorf("failed to set proposal title: %w", err)
}
summaryPrompt := promptui.Prompt{
Label: "Enter proposal summary",
Validate: client.ValidatePromptNotEmpty,
}
summary, err := summaryPrompt.Run()
if err != nil {
return types.ProposalMetadata{}, fmt.Errorf("failed to set proposal summary: %w", err)
}
return types.ProposalMetadata{Title: title, Summary: summary}, nil
}
// NewCmdDraftProposal let a user generate a draft proposal.
func NewCmdDraftProposal() *cobra.Command {
flagSkipMetadata := "skip-metadata"
cmd := &cobra.Command{
Use: "draft-proposal",
Short: "Generate a draft proposal json file. The generated proposal json contains only one message (skeleton).",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, _ []string) error {
clientCtx, err := client.GetClientTxContext(cmd)
if err != nil {
return err
}
// prompt proposal type
proposalTypesPrompt := promptui.Select{
Label: "Select proposal type",
Items: getProposalSuggestions(),
}
_, selectedProposalType, err := proposalTypesPrompt.Run()
if err != nil {
return fmt.Errorf("failed to prompt proposal types: %w", err)
}
var proposal proposalType
for _, p := range suggestedProposalTypes {
if strings.EqualFold(p.Name, selectedProposalType) {
proposal = p
break
}
}
// create any proposal type
if proposal.Name == proposalOther {
// prompt proposal type
msgPrompt := promptui.Select{
Label: "Select proposal message type:",
Items: func() []string {
msgs := clientCtx.InterfaceRegistry.ListImplementations(sdk.MsgInterfaceProtoName)
sort.Strings(msgs)
return msgs
}(),
}
_, result, err := msgPrompt.Run()
if err != nil {
return fmt.Errorf("failed to prompt proposal types: %w", err)
}
proposal.MsgType = result
}
if proposal.MsgType != "" {
proposal.Msg, err = sdk.GetMsgFromTypeURL(clientCtx.Codec, proposal.MsgType)
if err != nil {
// should never happen
panic(err)
}
}
skipMetadataPrompt, _ := cmd.Flags().GetBool(flagSkipMetadata)
result, metadata, err := proposal.Prompt(clientCtx.Codec, skipMetadataPrompt)
if err != nil {
return err
}
if err := writeFile(draftProposalFileName, result); err != nil {
return err
}
if !skipMetadataPrompt {
if err := writeFile(draftMetadataFileName, metadata); err != nil {
return err
}
}
cmd.Println("The draft proposal has successfully been generated.\nProposals should contain off-chain metadata, please upload the metadata JSON to IPFS.\nThen, replace the generated metadata field with the IPFS CID.")
return nil
},
}
flags.AddTxFlagsToCmd(cmd)
cmd.Flags().Bool(flagSkipMetadata, false, "skip metadata prompt")
return cmd
}
// writeFile writes the input to the file
func writeFile(fileName string, input any) error {
raw, err := json.MarshalIndent(input, "", " ")
if err != nil {
return fmt.Errorf("failed to marshal proposal: %w", err)
}
if err := os.WriteFile(fileName, raw, 0o600); err != nil {
return err
}
return nil
}