-
Notifications
You must be signed in to change notification settings - Fork 0
/
prompt.go
274 lines (234 loc) · 7.14 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
package cli
import (
"encoding/json"
"fmt"
"os"
"reflect"
"sort"
"strconv"
"strings"
"github.com/manifoldco/promptui"
"github.com/spf13/cobra"
"github.com/blockgenx/blockgen-sdk/client"
"github.com/blockgenx/blockgen-sdk/client/flags"
"github.com/blockgenx/blockgen-sdk/codec"
sdk "github.com/blockgenx/blockgen-sdk/types"
authtypes "github.com/blockgenx/blockgen-sdk/x/auth/types"
"github.com/blockgenx/blockgen-sdk/x/gov/types"
)
const (
proposalText = "text"
proposalOther = "other"
draftProposalFileName = "draft_proposal.json"
draftMetadataFileName = "draft_metadata.json"
)
// Prompt prompts the user for all values of the given type.
// data is the struct to be filled
// namePrefix is the name to be display 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 v.Field(i).Kind() == reflect.Struct || v.Field(i).Kind() == reflect.Slice {
// if the field is a struct skip
// in a future we can add a recursive call to Prompt
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)
// validation per field name
if strings.Contains(fieldName, "url") {
prompt.Validate = client.ValidatePromptURL
}
if strings.EqualFold(fieldName, "authority") {
// pre-fill with gov address
prompt.Default = authtypes.NewModuleAddress(types.ModuleName).String()
prompt.Validate = client.ValidatePromptAddress
}
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)
default:
// skip other types
// possibly in the future we can add more types (like slices)
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) (*proposal, types.ProposalMetadata, error) {
proposal := &proposal{}
// set metadata
metadata, err := Prompt(types.ProposalMetadata{}, "proposal")
if err != nil {
return nil, metadata, fmt.Errorf("failed to set proposal metadata: %w", err)
}
// the metadata must be saved on IPFS, set placeholder
proposal.Metadata = "ipfs://CID"
// 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
}
var suggestedProposalTypes = []proposalType{
{
Name: proposalText,
MsgType: "", // no message for text proposal
},
{
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
},
}
func getProposalSuggestions() []string {
types := make([]string, len(suggestedProposalTypes))
for i, p := range suggestedProposalTypes {
types[i] = p.Name
}
return types
}
// NewCmdDraftProposal let a user generate a draft proposal.
func NewCmdDraftProposal() *cobra.Command {
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)
}
}
result, metadata, err := proposal.Prompt(clientCtx.Codec)
if err != nil {
return err
}
if err := writeFile(draftProposalFileName, result); err != nil {
return err
}
if err := writeFile(draftMetadataFileName, metadata); err != nil {
return err
}
fmt.Printf("Your 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.\n")
return nil
},
}
flags.AddTxFlagsToCmd(cmd)
return cmd
}
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
}