-
Notifications
You must be signed in to change notification settings - Fork 65
/
Copy pathprompt.go
749 lines (614 loc) · 17.4 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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
/*
* Flow CLI
*
* Copyright Flow Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package prompt
import (
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/onflow/flow-cli/internal/util"
"github.com/onflow/flowkit/v2/accounts"
"github.com/gosuri/uilive"
"github.com/manifoldco/promptui"
"github.com/onflow/flow-go-sdk"
"github.com/onflow/flow-go-sdk/crypto"
"github.com/sergi/go-diff/diffmatchpatch"
"golang.org/x/exp/maps"
"golang.org/x/exp/slices"
"github.com/onflow/flowkit/v2/config"
"github.com/onflow/flowkit/v2/output"
)
func ApproveTransactionForSigningPrompt(transaction *flow.Transaction) bool {
return ApproveTransactionPrompt(transaction, "⚠️ Do you want to SIGN this transaction?")
}
func ApproveTransactionForBuildingPrompt(transaction *flow.Transaction) bool {
return ApproveTransactionPrompt(transaction, "⚠️ Do you want to BUILD this transaction?")
}
func ApproveTransactionForSendingPrompt(transaction *flow.Transaction) bool {
return ApproveTransactionPrompt(transaction, "⚠️ Do you want to SEND this transaction?")
}
func ApproveTransactionPrompt(tx *flow.Transaction, promptMsg string) bool {
writer := uilive.New()
_, _ = fmt.Fprintf(writer, "\n")
_, _ = fmt.Fprintf(writer, "ID\t%s\n", tx.ID())
_, _ = fmt.Fprintf(writer, "Payer\t%s\n", tx.Payer.Hex())
_, _ = fmt.Fprintf(writer, "Authorizers\t%s\n", tx.Authorizers)
_, _ = fmt.Fprintf(writer,
"\nProposal Key:\t\n Address\t%s\n Index\t%v\n Sequence\t%v\n",
tx.ProposalKey.Address, tx.ProposalKey.KeyIndex, tx.ProposalKey.SequenceNumber,
)
if len(tx.PayloadSignatures) == 0 {
_, _ = fmt.Fprintf(writer, "\nNo Payload Signatures\n")
}
if len(tx.EnvelopeSignatures) == 0 {
_, _ = fmt.Fprintf(writer, "\nNo Envelope Signatures\n")
}
for i, e := range tx.PayloadSignatures {
_, _ = fmt.Fprintf(writer, "\nPayload Signature %v:\n", i)
_, _ = fmt.Fprintf(writer, " Address\t%s\n", e.Address)
_, _ = fmt.Fprintf(writer, " Signature\t%x\n", e.Signature)
_, _ = fmt.Fprintf(writer, " Key Index\t%d\n", e.KeyIndex)
}
for i, e := range tx.EnvelopeSignatures {
_, _ = fmt.Fprintf(writer, "\nEnvelope Signature %v:\n", i)
_, _ = fmt.Fprintf(writer, " Address\t%s\n", e.Address)
_, _ = fmt.Fprintf(writer, " Signature\t%x\n", e.Signature)
_, _ = fmt.Fprintf(writer, " Key Index\t%d\n", e.KeyIndex)
}
if tx.Script != nil {
if len(tx.Arguments) == 0 {
_, _ = fmt.Fprintf(writer, "\n\nArguments\tNo arguments\n")
} else {
_, _ = fmt.Fprintf(writer, "\n\nArguments (%d):\n", len(tx.Arguments))
for i, argument := range tx.Arguments {
_, _ = fmt.Fprintf(writer, " - Argument %d: %s\n", i, argument)
}
}
_, _ = fmt.Fprintf(writer, "\nCode\n\n%s\n", tx.Script)
}
_, _ = fmt.Fprintf(writer, "\n\n")
_ = writer.Flush()
prompt := promptui.Select{
Label: promptMsg,
Items: []string{"No", "Yes"},
}
_, result, _ := prompt.Run()
_, _ = fmt.Fprintf(writer, "\r\r")
_ = writer.Flush()
return result == "Yes"
}
func AutocompletionPrompt() (string, string) {
prompt := promptui.Select{
Label: "❓ Select your shell (you can run 'echo $SHELL' to find out)",
Items: []string{"bash", "zsh", "powershell"},
}
_, shell, _ := prompt.Run()
curOs := ""
switch shell {
case "bash":
prompt := promptui.Select{
Label: "❓ Select operation system",
Items: []string{"MacOS", "Linux"},
}
_, curOs, _ = prompt.Run()
case "powershell":
fmt.Printf(`PowerShell Installation Guide:
PS> flow config setup-completions powershell | Out-String | Invoke-Expression
# To load completions for every new session, run:
PS> flow config setup-completions powershell > flow.ps1
# and source this file from your PowerShell profile.
`)
}
return shell, curOs
}
func NamePrompt() string {
namePrompt := promptui.Prompt{
Label: "Enter name",
Validate: func(s string) error {
if len(s) < 1 {
return fmt.Errorf("invalid name")
}
return nil
},
}
name, err := namePrompt.Run()
if err == promptui.ErrInterrupt {
os.Exit(-1)
}
return name
}
func AccountNamePrompt(accountNames []string) string {
namePrompt := promptui.Prompt{
Label: "Enter an account name",
Validate: func(s string) error {
if slices.Contains(accountNames, s) {
return fmt.Errorf("name already exists")
}
if len(s) < 1 {
return fmt.Errorf("invalid name")
}
return nil
},
}
name, err := namePrompt.Run()
if err == promptui.ErrInterrupt {
os.Exit(-1)
}
return name
}
func secureNetworkKeyPrompt() string {
networkKeyPrompt := promptui.Prompt{
Label: "Enter a valid host network key or leave blank",
Validate: func(s string) error {
if s == "" {
return nil
}
return util.ValidateECDSAP256Pub(s)
},
}
networkKey, err := networkKeyPrompt.Run()
if err == promptui.ErrInterrupt {
os.Exit(-1)
}
return networkKey
}
func addressPrompt(label, errorMessage string) string {
addressPrompt := promptui.Prompt{
Label: label,
Validate: func(s string) error {
if flow.HexToAddress(s) == flow.EmptyAddress {
return fmt.Errorf(errorMessage)
}
return nil
},
}
address, err := addressPrompt.Run()
if err == promptui.ErrInterrupt {
os.Exit(-1)
}
return address
}
func AddressPromptOrEmpty(label, errorMessage string) string {
addressPrompt := promptui.Prompt{
Label: label,
Validate: func(s string) error {
if s == "" {
return nil
}
if flow.HexToAddress(s) == flow.EmptyAddress {
return fmt.Errorf(errorMessage)
}
return nil
},
}
address, err := addressPrompt.Run()
if err == promptui.ErrInterrupt {
os.Exit(-1)
}
return address
}
func contractPrompt(contractNames []string) string {
contractPrompt := promptui.Select{
Label: "Choose contract you wish to deploy",
Items: contractNames,
}
_, contractName, err := contractPrompt.Run()
if err == promptui.ErrInterrupt {
os.Exit(-1)
}
return contractName
}
func addAnotherContractToDeploymentPrompt() bool {
addContractPrompt := promptui.Select{
Label: "Do you wish to add another contract for deployment?",
Items: []string{"No", "Yes"},
}
_, addMore, err := addContractPrompt.Run()
if err == promptui.ErrInterrupt {
os.Exit(-1)
}
return addMore == "Yes"
}
// ShowContractDiffPrompt shows a diff between the new contract and the existing contract
// and asks the user if they wish to continue with the deployment
// returns true if the user wishes to continue with the deployment and false otherwise
func ShowContractDiffPrompt(logger output.Logger) func([]byte, []byte) bool {
return func(newContract []byte, existingContract []byte) bool {
dmp := diffmatchpatch.New()
diffs := dmp.DiffMain(string(newContract), string(existingContract), false)
diffString := dmp.DiffPrettyText(diffs)
logger.Info(diffString)
deployPrompt := promptui.Prompt{
Label: "Do you wish to deploy this contract?",
IsConfirm: true,
}
deploy, err := deployPrompt.Run()
if err == promptui.ErrInterrupt {
os.Exit(-1)
}
return strings.ToLower(deploy) == "y"
}
}
type AccountData struct {
Name string
Address string
SigAlgo string
HashAlgo string
Key string
KeyIndex string
}
func NewAccountPrompt() *AccountData {
var err error
account := &AccountData{
Name: NamePrompt(),
Address: addressPrompt("Enter address", "invalid address"),
}
sigAlgoPrompt := promptui.Select{
Label: "Choose signature algorithm",
Items: []string{"ECDSA_P256", "ECDSA_secp256k1"},
}
_, account.SigAlgo, err = sigAlgoPrompt.Run()
if err == promptui.ErrInterrupt {
os.Exit(-1)
}
hashAlgoPrompt := promptui.Select{
Label: "Choose hashing algorithm",
Items: []string{"SHA3_256", "SHA2_256"},
}
_, account.HashAlgo, err = hashAlgoPrompt.Run()
if err == promptui.ErrInterrupt {
os.Exit(-1)
}
keyPrompt := promptui.Prompt{
Label: "Enter private key",
Validate: func(s string) error {
_, err := crypto.DecodePrivateKeyHex(crypto.StringToSignatureAlgorithm(account.SigAlgo), s)
return err
},
}
account.Key, err = keyPrompt.Run()
if err == promptui.ErrInterrupt {
os.Exit(-1)
}
keyIndexPrompt := promptui.Prompt{
Label: "Enter key index (Default: 0)",
Default: "0",
Validate: func(s string) error {
v, err := strconv.Atoi(s)
if err != nil {
return fmt.Errorf("invalid index, must be a number")
}
if v < 0 {
return fmt.Errorf("invalid index, must be positive")
}
return nil
},
}
account.KeyIndex, err = keyIndexPrompt.Run()
if err == promptui.ErrInterrupt {
os.Exit(-1)
}
return account
}
type ContractData struct {
Name string
Source string
Emulator string
Testnet string
Mainnet string
}
func NewContractPrompt() *ContractData {
contract := &ContractData{
Name: NamePrompt(),
}
var err error
sourcePrompt := promptui.Prompt{
Label: "Enter contract file location",
Validate: func(s string) error {
if !config.Exists(s) {
return fmt.Errorf("contract file doesn't exist: %s", s)
}
return nil
},
}
contract.Source, err = sourcePrompt.Run()
if err == promptui.ErrInterrupt {
os.Exit(-1)
}
contract.Emulator = addressPrompt("Enter emulator alias, if exists", "invalid alias address")
contract.Testnet = addressPrompt("Enter testnet alias, if exists", "invalid testnet address")
contract.Mainnet = addressPrompt("Enter mainnet alias, if exists", "invalid mainnet address")
return contract
}
func NewNetworkPrompt() map[string]string {
networkData := make(map[string]string)
var err error
networkData["name"] = NamePrompt()
hostPrompt := promptui.Prompt{
Label: "Enter host location",
Validate: func(s string) error {
return nil
},
}
networkData["host"], err = hostPrompt.Run()
if err == promptui.ErrInterrupt {
os.Exit(-1)
}
networkData["key"] = secureNetworkKeyPrompt()
return networkData
}
type DeploymentData struct {
Network string
Account string
Contracts []string
}
func NewDeploymentPrompt(
networks config.Networks,
accounts config.Accounts,
contracts config.Contracts,
) *DeploymentData {
deploymentData := &DeploymentData{}
var err error
networkNames := make([]string, 0)
for _, network := range networks {
networkNames = append(networkNames, network.Name)
}
networkPrompt := promptui.Select{
Label: "Choose network for deployment",
Items: networkNames,
}
_, deploymentData.Network, err = networkPrompt.Run()
if err == promptui.ErrInterrupt {
os.Exit(-1)
}
accountNames := make([]string, 0)
for _, account := range accounts {
accountNames = append(accountNames, account.Name)
}
accountPrompt := promptui.Select{
Label: "Choose an account to deploy to",
Items: accountNames,
}
_, deploymentData.Account, err = accountPrompt.Run()
if err == promptui.ErrInterrupt {
os.Exit(-1)
}
contractNames := make([]string, 0)
for _, contract := range contracts {
contractNames = append(contractNames, contract.Name)
}
deploymentData.Contracts = make([]string, 0)
contractName := contractPrompt(contractNames)
deploymentData.Contracts = append(deploymentData.Contracts, contractName)
contractNames = removeFromStringArray(contractNames, contractName)
for addAnotherContractToDeploymentPrompt() {
contractName := contractPrompt(contractNames)
deploymentData.Contracts = append(deploymentData.Contracts, contractName)
contractNames = removeFromStringArray(contractNames, contractName)
if len(contractNames) == 0 {
break
}
}
return deploymentData
}
func removeFromStringArray(s []string, el string) []string {
for i, v := range s {
if v == el {
s = append(s[:i], s[i+1:]...)
break
}
}
return s
}
// AddContractToDeploymentPrompt prompts a user to select an account to deploy a given contract on a given network
func AddContractToDeploymentPrompt(networkName string, accounts accounts.Accounts, contractName string) *DeploymentData {
deploymentData := &DeploymentData{
Network: networkName,
Contracts: []string{contractName},
}
var err error
accountNames := make([]string, 0)
for _, account := range accounts {
accountNames = append(accountNames, account.Name)
}
// Add a "none" option to the list of accounts
accountNames = append(accountNames, "none")
accountPrompt := promptui.Select{
Label: fmt.Sprintf("Choose an account to deploy %s to on %s (or 'none' to skip)", contractName, networkName),
Items: accountNames,
}
selectedIndex, _, err := accountPrompt.Run()
if err == promptui.ErrInterrupt {
os.Exit(-1)
}
// Handle the "none" selection based on its last position
if selectedIndex == len(accountNames)-1 {
return nil
}
deploymentData.Account = accounts[selectedIndex].Name
return deploymentData
}
func RemoveAccountPrompt(accounts config.Accounts) string {
accountNames := make([]string, 0)
for _, account := range accounts {
accountNames = append(accountNames, account.Name)
}
namePrompt := promptui.Select{
Label: "Choose an account name you wish to remove",
Items: accountNames,
}
_, name, err := namePrompt.Run()
if err == promptui.ErrInterrupt {
os.Exit(-1)
}
return name
}
func RemoveDeploymentPrompt(deployments config.Deployments) (account string, network string) {
deploymentNames := make([]string, 0)
for _, deployment := range deployments {
contractNames := make([]string, 0)
for _, c := range deployment.Contracts {
contractNames = append(contractNames, c.Name)
}
deploymentNames = append(
deploymentNames,
fmt.Sprintf(
"Account: %s, Network: %s, Contracts: %s",
deployment.Account,
deployment.Network,
contractNames,
),
)
}
deployPrompt := promptui.Select{
Label: "Choose deployment you wish to remove",
Items: deploymentNames,
}
index, _, err := deployPrompt.Run()
if err == promptui.ErrInterrupt {
os.Exit(-1)
}
return deployments[index].Account, deployments[index].Network
}
func RemoveContractPrompt(contracts config.Contracts) string {
contractNames := make([]string, 0)
for _, contract := range contracts {
contractNames = append(contractNames, contract.Name)
}
contractPrompt := promptui.Select{
Label: "Choose contract you wish to remove",
Items: contractNames,
}
_, name, err := contractPrompt.Run()
if err == promptui.ErrInterrupt {
os.Exit(-1)
}
return name
}
func RemoveContractFromFlowJSONPrompt(contractName string) bool {
prompt := promptui.Select{
Label: fmt.Sprintf("Do you want to remove %s from your flow.json deployments?", contractName),
Items: []string{"Yes", "No"},
}
chosen, _, _ := prompt.Run()
return chosen == 0
}
func RemoveNetworkPrompt(networks config.Networks) string {
networkNames := make([]string, 0)
for _, network := range networks {
networkNames = append(networkNames, network.Name)
}
networkPrompt := promptui.Select{
Label: "Choose network you wish to remove",
Items: networkNames,
}
_, name, err := networkPrompt.Run()
if err == promptui.ErrInterrupt {
os.Exit(-1)
}
return name
}
func ReportCrash() bool {
prompt := promptui.Select{
Label: "🙏 Please report the crash so we can improve the CLI. Do you want to report it?",
Items: []string{"Yes, report the crash", "No"},
}
chosen, _, _ := prompt.Run()
return chosen == 0
}
func CreateAccountNetworkPrompt() (string, config.Network) {
networkMap := map[string]config.Network{
"Emulator": config.EmulatorNetwork,
"Testnet": config.TestnetNetwork,
"Mainnet": config.MainnetNetwork,
}
networkPrompt := promptui.Select{
Label: "Choose a network",
Items: maps.Keys(networkMap),
}
_, selectedNetwork, err := networkPrompt.Run()
if err == promptui.ErrInterrupt {
os.Exit(-1)
}
fmt.Println("")
return selectedNetwork, networkMap[selectedNetwork]
}
func WantToUseMainnetVersionPrompt() bool {
useMainnetVersionPrompt := promptui.Select{
Label: "Do you wish to use Mainnet version instead? (y/n)",
Items: []string{"Yes", "No"},
}
_, useMainnetVersion, err := useMainnetVersionPrompt.Run()
if err == promptui.ErrInterrupt {
os.Exit(-1)
}
return useMainnetVersion == "Yes"
}
const CancelInstall = 1
const AlreadyInstalled = 2
func InstallPrompt() int {
prompt := promptui.Select{
Label: "Do you wish to install it",
Items: []string{"Yes", "No", "I've already installed it"},
}
index, _, err := prompt.Run()
if err == promptui.ErrInterrupt {
os.Exit(-1)
}
return index
}
func InstallPathPrompt(defaultPath string) string {
prompt := promptui.Prompt{
Label: "Install path",
Default: defaultPath,
Validate: func(s string) error {
if _, err := os.Stat(s); err == nil {
return nil
}
// Attempt to create it
var d []byte
if err := os.WriteFile(s, d, 0644); err == nil {
os.Remove(s) // And delete it
return nil
}
return fmt.Errorf("path is invalid")
},
}
install, err := prompt.Run()
if err == promptui.ErrInterrupt {
os.Exit(-1)
}
return filepath.Clean(install)
}
func GenericBoolPrompt(msg string) bool {
prompt := promptui.Select{
Label: msg,
Items: []string{"Yes", "No"},
}
_, result, _ := prompt.Run()
return result == "Yes"
}
func GenericSelect(items []string, message string) string {
prompt := promptui.Select{
Label: message,
Items: items,
}
_, result, _ := prompt.Run()
return result
}