-
Notifications
You must be signed in to change notification settings - Fork 2
/
action.go
1230 lines (1108 loc) · 31 KB
/
action.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
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (C) 2024, AllianceBlock. All rights reserved.
// See the file LICENSE for licensing terms.
package cmd
import (
"bytes"
"context"
"errors"
"fmt"
"math"
"regexp"
"strconv"
"time"
"github.com/spf13/cobra"
"github.com/ava-labs/avalanchego/ids"
"github.com/ava-labs/avalanchego/utils/set"
"github.com/ava-labs/avalanchego/vms/platformvm/warp"
"github.com/ava-labs/hypersdk/chain"
hyperCli "github.com/ava-labs/hypersdk/cli"
"github.com/ava-labs/hypersdk/codec"
hconsts "github.com/ava-labs/hypersdk/consts"
"github.com/ava-labs/hypersdk/crypto/bls"
"github.com/ava-labs/hypersdk/pubsub"
hrpc "github.com/ava-labs/hypersdk/rpc"
hutils "github.com/ava-labs/hypersdk/utils"
"github.com/nuklai/nuklaivm/actions"
"github.com/nuklai/nuklaivm/auth"
nconsts "github.com/nuklai/nuklaivm/consts"
nrpc "github.com/nuklai/nuklaivm/rpc"
)
var actionCmd = &cobra.Command{
Use: "action",
RunE: func(*cobra.Command, []string) error {
return ErrMissingSubcommand
},
}
var transferCmd = &cobra.Command{
Use: "transfer",
RunE: func(cmd *cobra.Command, args []string) error {
var (
assetID ids.ID
recipient codec.Address
amount uint64
err error
)
ctx := context.Background()
_, priv, factory, hcli, hws, ncli, err := handler.DefaultActor()
if err != nil {
return err
}
// Get assetID
assetIDStr, _ := cmd.Flags().GetString("assetID")
if assetIDStr == "" {
assetID, err = handler.Root().PromptAsset("assetID", true)
if err != nil {
return err
}
} else {
if assetIDStr == nconsts.Symbol {
assetID = ids.Empty
} else {
assetID, err = ids.FromString(assetIDStr)
if err != nil {
return err
}
}
}
_, decimals, balance, _, err := handler.GetAssetInfo(ctx, ncli, priv.Address, assetID, true)
if balance == 0 || err != nil {
return err
}
// Get recipient
recipientStr, _ := cmd.Flags().GetString("recipient")
if recipientStr == "" {
recipient, err = handler.Root().PromptAddress("recipient")
if err != nil {
return err
}
} else {
recipient, err = codec.ParseAddressBech32(nconsts.HRP, recipientStr)
if err != nil {
return err
}
}
// Get amount
amountStr, _ := cmd.Flags().GetString("amount")
if amountStr == "" {
amount, err = handler.Root().PromptAmount("amount", decimals, balance, nil)
if err != nil {
return err
}
} else {
amount, err = hutils.ParseBalance(amountStr, nconsts.Decimals)
if err != nil {
return err
}
}
// Confirm action
if assetIDStr == "" || recipientStr == "" || amountStr == "" {
confirm, err := handler.Root().PromptContinue()
if !confirm || err != nil {
return errors.New("transfer not confirmed")
}
} else {
// Auto-confirm if all arguments are provided
hutils.Outf("All arguments provided, auto-confirming the transfer\n")
}
// Generate transaction
_, _, err = sendAndWait(ctx, nil, &actions.Transfer{
To: recipient,
Asset: assetID,
Value: amount,
}, hcli, hws, ncli, factory, true)
return err
},
}
var createAssetCmd = &cobra.Command{
Use: "create-asset",
RunE: func(*cobra.Command, []string) error {
ctx := context.Background()
_, _, factory, hcli, hws, ncli, err := handler.DefaultActor()
if err != nil {
return err
}
// Add symbol to token
symbol, err := handler.Root().PromptString("symbol", 1, actions.MaxSymbolSize)
if err != nil {
return err
}
// Add decimal to token
decimals, err := handler.Root().PromptInt("decimals", actions.MaxDecimals)
if err != nil {
return err
}
// Add metadata to token
metadata, err := handler.Root().PromptString("metadata", 1, actions.MaxMetadataSize)
if err != nil {
return err
}
// Confirm action
cont, err := handler.Root().PromptContinue()
if !cont || err != nil {
return err
}
// Generate transaction
_, _, err = sendAndWait(ctx, nil, &actions.CreateAsset{
Symbol: []byte(symbol),
Decimals: uint8(decimals), // already constrain above to prevent overflow
Metadata: []byte(metadata),
}, hcli, hws, ncli, factory, true)
return err
},
}
var mintAssetCmd = &cobra.Command{
Use: "mint-asset",
RunE: func(*cobra.Command, []string) error {
ctx := context.Background()
_, priv, factory, hcli, hws, ncli, err := handler.DefaultActor()
if err != nil {
return err
}
// Select token to mint
assetID, err := handler.Root().PromptAsset("assetID", false)
if err != nil {
return err
}
exists, symbol, decimals, metadata, supply, owner, warp, err := ncli.Asset(ctx, assetID, false)
if err != nil {
return err
}
if !exists {
hutils.Outf("{{red}}%s does not exist{{/}}\n", assetID)
hutils.Outf("{{red}}exiting...{{/}}\n")
return nil
}
if warp {
hutils.Outf("{{red}}cannot mint a warped asset{{/}}\n", assetID)
hutils.Outf("{{red}}exiting...{{/}}\n")
return nil
}
if owner != codec.MustAddressBech32(nconsts.HRP, priv.Address) {
hutils.Outf("{{red}}%s is the owner of %s, you are not{{/}}\n", owner, assetID)
hutils.Outf("{{red}}exiting...{{/}}\n")
return nil
}
hutils.Outf(
"{{yellow}}symbol:{{/}} %s {{yellow}}decimals:{{/}} %d {{yellow}}metadata:{{/}} %s {{yellow}}supply:{{/}} %d\n",
string(symbol),
decimals,
string(metadata),
supply,
)
// Select recipient
recipient, err := handler.Root().PromptAddress("recipient")
if err != nil {
return err
}
// Select amount
amount, err := handler.Root().PromptAmount("amount", decimals, hconsts.MaxUint64-supply, nil)
if err != nil {
return err
}
// Confirm action
cont, err := handler.Root().PromptContinue()
if !cont || err != nil {
return err
}
// Generate transaction
_, _, err = sendAndWait(ctx, nil, &actions.MintAsset{
Asset: assetID,
To: recipient,
Value: amount,
}, hcli, hws, ncli, factory, true)
return err
},
}
func performImport(
ctx context.Context,
hscli *hrpc.JSONRPCClient,
hdcli *hrpc.JSONRPCClient,
hws *hrpc.WebSocketClient,
ncli *nrpc.JSONRPCClient,
exportTxID ids.ID,
factory chain.AuthFactory,
) error {
// Select TxID (if not provided)
var err error
if exportTxID == ids.Empty {
exportTxID, err = handler.Root().PromptID("export txID")
if err != nil {
return err
}
}
// Generate warp signature (as long as >= 80% stake)
var (
msg *warp.Message
subnetWeight, sigWeight uint64
)
for ctx.Err() == nil {
msg, subnetWeight, sigWeight, err = hscli.GenerateAggregateWarpSignature(ctx, exportTxID)
if sigWeight >= (subnetWeight*4)/5 && err == nil {
break
}
if err == nil {
hutils.Outf(
"{{yellow}}waiting for signature weight:{{/}} %d {{yellow}}observed:{{/}} %d\n",
subnetWeight,
sigWeight,
)
} else {
hutils.Outf("{{red}}encountered error:{{/}} %v\n", err)
}
cont, err := handler.Root().PromptBool("try again")
if err != nil {
return err
}
if !cont {
hutils.Outf("{{red}}exiting...{{/}}\n")
return nil
}
}
if ctx.Err() != nil {
return ctx.Err()
}
wt, err := actions.UnmarshalWarpTransfer(msg.UnsignedMessage.Payload)
if err != nil {
return err
}
outputAssetID := wt.Asset
if !wt.Return {
outputAssetID = actions.ImportedAssetID(wt.Asset, msg.SourceChainID)
}
hutils.Outf(
"%s {{yellow}}to:{{/}} %s {{yellow}}source assetID:{{/}} %s {{yellow}}source symbol:{{/}} %s {{yellow}}output assetID:{{/}} %s {{yellow}}value:{{/}} %s {{yellow}}reward:{{/}} %s {{yellow}}return:{{/}} %t\n",
hutils.ToID(
msg.UnsignedMessage.Payload,
),
codec.MustAddressBech32(nconsts.HRP, wt.To),
wt.Asset,
wt.Symbol,
outputAssetID,
hutils.FormatBalance(wt.Value, wt.Decimals),
hutils.FormatBalance(wt.Reward, wt.Decimals),
wt.Return,
)
if wt.SwapIn > 0 {
_, outSymbol, outDecimals, _, _, _, _, err := ncli.Asset(ctx, wt.AssetOut, false)
if err != nil {
return err
}
hutils.Outf(
"{{yellow}}asset in:{{/}} %s {{yellow}}swap in:{{/}} %s {{yellow}}asset out:{{/}} %s {{yellow}}symbol out:{{/}} %s {{yellow}}swap out:{{/}} %s {{yellow}}swap expiry:{{/}} %d\n",
outputAssetID,
hutils.FormatBalance(wt.SwapIn, wt.Decimals),
wt.AssetOut,
outSymbol,
hutils.FormatBalance(wt.SwapOut, outDecimals),
wt.SwapExpiry,
)
}
// Select fill
var fill bool
if wt.SwapIn > 0 {
fill, err = handler.Root().PromptBool("fill")
if err != nil {
return err
}
}
if !fill && wt.SwapExpiry > time.Now().UnixMilli() {
return ErrMustFill
}
// Generate transaction
_, _, err = sendAndWait(ctx, msg, &actions.ImportAsset{
Fill: fill,
}, hdcli, hws, ncli, factory, true)
return err
}
var importAssetCmd = &cobra.Command{
Use: "import-asset",
RunE: func(*cobra.Command, []string) error {
ctx := context.Background()
currentChainID, _, factory, hdcli, hws, ncli, err := handler.DefaultActor()
if err != nil {
return err
}
// Select source
_, uris, err := handler.Root().PromptChain("sourceChainID", set.Of(currentChainID))
if err != nil {
return err
}
hscli := hrpc.NewJSONRPCClient(uris[0])
// Perform import
return performImport(ctx, hscli, hdcli, hws, ncli, ids.Empty, factory)
},
}
var exportAssetCmd = &cobra.Command{
Use: "export-asset",
RunE: func(*cobra.Command, []string) error {
ctx := context.Background()
currentChainID, priv, factory, hcli, hws, ncli, err := handler.DefaultActor()
if err != nil {
return err
}
// Select token to send
assetID, err := handler.Root().PromptAsset("assetID", true)
if err != nil {
return err
}
_, decimals, balance, sourceChainID, err := handler.GetAssetInfo(ctx, ncli, priv.Address, assetID, true)
if balance == 0 || err != nil {
return err
}
// Select recipient
recipient, err := handler.Root().PromptAddress("recipient")
if err != nil {
return err
}
// Select amount
amount, err := handler.Root().PromptAmount("amount", decimals, balance, nil)
if err != nil {
return err
}
// Determine return
var ret bool
if sourceChainID != ids.Empty {
ret = true
}
// Select reward
reward, err := handler.Root().PromptAmount("reward", decimals, balance-amount, nil)
if err != nil {
return err
}
// Determine destination
destination := sourceChainID
if !ret {
destination, _, err = handler.Root().PromptChain("destination", set.Of(currentChainID))
if err != nil {
return err
}
}
// Determine if swap in
swap, err := handler.Root().PromptBool("swap on import")
if err != nil {
return err
}
var (
swapIn uint64
assetOut ids.ID
swapOut uint64
swapExpiry int64
)
if swap {
swapIn, err = handler.Root().PromptAmount("swap in", decimals, amount, nil)
if err != nil {
return err
}
assetOut, err = handler.Root().PromptAsset("asset out (on destination)", true)
if err != nil {
return err
}
uris, err := handler.Root().GetChain(destination)
if err != nil {
return err
}
networkID, _, _, err := hcli.Network(ctx)
if err != nil {
return err
}
dcli := nrpc.NewJSONRPCClient(uris[0], networkID, destination)
_, decimals, _, _, err := handler.GetAssetInfo(ctx, dcli, priv.Address, assetOut, false)
if err != nil {
return err
}
swapOut, err = handler.Root().PromptAmount(
"swap out (on destination, no decimals)",
decimals,
hconsts.MaxUint64,
nil,
)
if err != nil {
return err
}
swapExpiry, err = handler.Root().PromptTime("swap expiry")
if err != nil {
return err
}
}
// Confirm action
cont, err := handler.Root().PromptContinue()
if !cont || err != nil {
return err
}
// Generate transaction
success, txID, err := sendAndWait(ctx, nil, &actions.ExportAsset{
To: recipient,
Asset: assetID,
Value: amount,
Return: ret,
Reward: reward,
SwapIn: swapIn,
AssetOut: assetOut,
SwapOut: swapOut,
SwapExpiry: swapExpiry,
Destination: destination,
}, hcli, hws, ncli, factory, true)
if err != nil {
return err
}
if !success {
return errors.New("not successful")
}
// Perform import
imp, err := handler.Root().PromptBool("perform import on destination")
if err != nil {
return err
}
if imp {
uris, err := handler.Root().GetChain(destination)
if err != nil {
return err
}
networkID, _, _, err := hcli.Network(ctx)
if err != nil {
return err
}
hdcli, err := hrpc.NewWebSocketClient(uris[0], hrpc.DefaultHandshakeTimeout, pubsub.MaxPendingMessages, pubsub.MaxReadMessageSize)
if err != nil {
return err
}
if err := performImport(ctx, hcli, hrpc.NewJSONRPCClient(uris[0]), hdcli, nrpc.NewJSONRPCClient(uris[0], networkID, destination), txID, factory); err != nil {
return err
}
}
// Ask if user would like to switch to destination chain
sw, err := handler.Root().PromptBool("switch default chain to destination")
if err != nil {
return err
}
if !sw {
return nil
}
return handler.Root().StoreDefaultChain(destination)
},
}
// Define the layout that matches the provided date string
// Note: the reference time is "Mon Jan 2 15:04:05 MST 2006" in Go
const (
TimeLayout = "2006-01-02 15:04:05"
Auto = "auto"
Manual = "manual"
)
var registerValidatorStakeCmd = &cobra.Command{
Use: "register-validator-stake [manual | auto <node#>]",
PreRunE: func(cmd *cobra.Command, args []string) error {
if len(args) == 0 || (args[0] != Manual && args[0] != Auto) {
return ErrInvalidArgs
}
return nil
},
RunE: func(_ *cobra.Command, args []string) error {
autoRegister := args[0] == Auto
nodeNumber := "node1"
if len(args) == 2 {
isValid := regexp.MustCompile(`^node([1-9]|10)$`).MatchString(nodeNumber)
if !isValid {
return fmt.Errorf("invalid node number")
}
nodeNumber = args[1]
}
ctx := context.Background()
_, priv, factory, hcli, hws, ncli, err := handler.DefaultActor()
if err != nil {
return err
}
if autoRegister {
hutils.Outf("{{yellow}}Loading private key for %s{{/}}\n", nodeNumber)
validatorSignerKey, err := loadPrivateKey("bls", fmt.Sprintf("/tmp/nuklaivm/nodes/%s-bls/signer.key", nodeNumber))
if err != nil {
return err
}
validatorSignerAddress := codec.MustAddressBech32(nconsts.HRP, validatorSignerKey.Address)
nclients, err := handler.DefaultNuklaiVMJSONRPCClient(checkAllChains)
if err != nil {
return err
}
_, _, balance, _, err := handler.GetAssetInfo(ctx, nclients[0], validatorSignerKey.Address, ids.Empty, true)
if err != nil {
return err
}
hutils.Outf("{{yellow}}Balance of validator signer:{{/}} %s\n", hutils.FormatBalance(balance, nconsts.Decimals))
if balance < uint64(100*math.Pow10(int(nconsts.Decimals))) {
hutils.Outf("{{yellow}} You need a minimum of 100 NAI to register a validator{{/}}\n")
return nil
}
// Set the default key to the validator signer key
hutils.Outf("{{yellow}}Loading validator signer key :{{/}} %s\n", validatorSignerAddress)
if err := handler.h.StoreKey(validatorSignerKey); err != nil && !errors.Is(err, hyperCli.ErrDuplicate) {
return err
}
if err := handler.h.StoreDefaultKey(validatorSignerKey.Address); err != nil {
return err
}
_, priv, factory, hcli, hws, ncli, err = handler.DefaultActor()
if err != nil {
return err
}
}
keyType, _ := getKeyType(priv.Address)
if keyType != blsKey {
return fmt.Errorf("actor must be a BLS key")
}
secretKey, err := bls.PrivateKeyFromBytes(priv.Bytes)
if err != nil {
return err
}
publicKey := bls.PublicKeyToBytes(bls.PublicFromPrivateKey(secretKey))
hutils.Outf("{{yellow}}Validator Signer Address: %s\n", codec.MustAddressBech32(nconsts.HRP, priv.Address))
// Get the validator for which the actor is a signer
// Get current list of validators
validators, err := ncli.AllValidators(ctx)
if err != nil {
return err
}
if len(validators) == 0 {
hutils.Outf("{{red}}no validators{{/}}\n")
return nil
}
var nodeID ids.NodeID
for i := 0; i < len(validators); i++ {
if bytes.Equal(publicKey, validators[i].PublicKey) {
nodeID = validators[i].NodeID
break
}
}
hutils.Outf("{{yellow}}Validator NodeID:{{/}} %s\n", nodeID.String())
if nodeID.Compare(ids.EmptyNodeID) == 0 {
hutils.Outf("{{red}}actor is not a signer for any of the validators{{/}}\n")
return nil
}
// Get balance info
_, _, balance, _, err := handler.GetAssetInfo(ctx, ncli, priv.Address, ids.Empty, true)
if balance == 0 || err != nil {
return err
}
if balance < uint64(100*math.Pow10(int(nconsts.Decimals))) {
hutils.Outf("{{yellow}} You need a minimum of 100 NAI to register a validator{{/}}\n")
return nil
}
// Select staked amount
stakedAmount, err := handler.Root().PromptAmount("Staked amount", nconsts.Decimals, balance, nil)
if err != nil {
return err
}
// Get current block
currentBlockHeight, _, _, _, _, _, _, err := ncli.EmissionInfo(ctx)
if err != nil {
return err
}
stakeStartBlock := currentBlockHeight + 20 // roughly 1 minute from now
stakeEndBlock := stakeStartBlock + 20*2 // roughly 10 minutes from stakeStartBlock
delegationFeeRate := 50
rewardAddress := priv.Address
if !autoRegister {
// Select stakeStartBlock
stakeStartBlockString, err := handler.Root().PromptString(
fmt.Sprintf("Staking Start Block(must be after %d)", currentBlockHeight),
1,
32,
)
if err != nil {
return err
}
stakeStartBlock, err = strconv.ParseUint(stakeStartBlockString, 10, 64)
if err != nil {
return err
}
// Select stakeEndBlock
stakeEndBlockString, err := handler.Root().PromptString(
fmt.Sprintf("Staking End Block(must be after %s)", stakeStartBlockString),
1,
32,
)
if err != nil {
return err
}
stakeEndBlock, err = strconv.ParseUint(stakeEndBlockString, 10, 64)
if err != nil {
return err
}
// Select delegationFeeRate
delegationFeeRate, err = handler.Root().PromptInt("Delegation Fee Rate(must be over 2)", 100)
if err != nil {
return err
}
// Select rewardAddress
rewardAddress, err = handler.Root().PromptAddress("Reward Address")
if err != nil {
return err
}
}
if stakeStartBlock < currentBlockHeight {
return fmt.Errorf("staking start block must be after the current block height (%d)", currentBlockHeight)
}
if stakeEndBlock < stakeStartBlock {
return fmt.Errorf("staking end block must be after the staking start block height (%d)", stakeStartBlock)
}
if delegationFeeRate < 2 || delegationFeeRate > 100 {
return fmt.Errorf("delegation fee rate must be over 2 and under 100")
}
// Confirm action
cont, err := handler.Root().PromptContinue()
if !cont || err != nil {
return err
}
hutils.Outf("{{yellow}}Register Validator Stake Info - stakeStartBlock: %d stakeEndBlock: %d delegationFeeRate: %d rewardAddress: %s\n", stakeStartBlock, stakeEndBlock, delegationFeeRate, codec.MustAddressBech32(nconsts.HRP, rewardAddress))
stakeInfo := &actions.ValidatorStakeInfo{
NodeID: nodeID.Bytes(),
StakeStartBlock: stakeStartBlock,
StakeEndBlock: stakeEndBlock,
StakedAmount: stakedAmount,
DelegationFeeRate: uint64(delegationFeeRate),
RewardAddress: rewardAddress,
}
stakeInfoBytes, err := stakeInfo.Marshal()
if err != nil {
return err
}
authFactory := auth.NewBLSFactory(secretKey)
signature, err := authFactory.Sign(stakeInfoBytes)
if err != nil {
return err
}
signaturePacker := codec.NewWriter(signature.Size(), signature.Size())
signature.Marshal(signaturePacker)
authSignature := signaturePacker.Bytes()
// Generate transaction
_, _, err = sendAndWait(ctx, nil, &actions.RegisterValidatorStake{
StakeInfo: stakeInfoBytes,
AuthSignature: authSignature,
}, hcli, hws, ncli, factory, true)
return err
},
}
var getValidatorStakeCmd = &cobra.Command{
Use: "get-validator-stake",
RunE: func(_ *cobra.Command, args []string) error {
ctx := context.Background()
// Get clients
nclients, err := handler.DefaultNuklaiVMJSONRPCClient(checkAllChains)
if err != nil {
return err
}
ncli := nclients[0]
// Get current list of validators
validators, err := ncli.StakedValidators(ctx)
if err != nil {
return err
}
if len(validators) == 0 {
hutils.Outf("{{red}}no validators{{/}}\n")
return nil
}
hutils.Outf("{{cyan}}validators:{{/}} %d\n", len(validators))
for i := 0; i < len(validators); i++ {
hutils.Outf(
"{{yellow}}%d:{{/}} NodeID=%s\n",
i,
validators[i].NodeID,
)
}
// Select validator
keyIndex, err := handler.Root().PromptChoice("validator to get staking info for", len(validators))
if err != nil {
return err
}
validatorChosen := validators[keyIndex]
nodeID := validatorChosen.NodeID
// Get validator stake
_, _, _, _, _, _, err = handler.GetValidatorStake(ctx, ncli, nodeID)
if err != nil {
return err
}
return nil
},
}
var claimValidatorStakeRewardCmd = &cobra.Command{
Use: "claim-validator-stake-reward",
RunE: func(*cobra.Command, []string) error {
ctx := context.Background()
_, _, factory, hcli, hws, ncli, err := handler.DefaultActor()
if err != nil {
return err
}
// Get current list of validators
validators, err := ncli.StakedValidators(ctx)
if err != nil {
return err
}
if len(validators) == 0 {
hutils.Outf("{{red}}no validators{{/}}\n")
return nil
}
// Show validators to the user
hutils.Outf("{{cyan}}validators:{{/}} %d\n", len(validators))
for i := 0; i < len(validators); i++ {
hutils.Outf(
"{{yellow}}%d:{{/}} NodeID=%s\n",
i,
validators[i].NodeID,
)
}
// Select validator
keyIndex, err := handler.Root().PromptChoice("validator to claim staking rewards for", len(validators))
if err != nil {
return err
}
validatorChosen := validators[keyIndex]
nodeID := validatorChosen.NodeID
// Get stake info
_, _, stakedAmount, _, _, _, err := ncli.ValidatorStake(ctx, nodeID)
if err != nil {
return err
}
if stakedAmount == 0 {
hutils.Outf("{{red}}validator has not yet staked{{/}}\n")
return nil
}
// Confirm action
cont, err := handler.Root().PromptContinue()
if !cont || err != nil {
return err
}
// Generate transaction
_, _, err = sendAndWait(ctx, nil, &actions.ClaimValidatorStakeRewards{
NodeID: nodeID.Bytes(),
}, hcli, hws, ncli, factory, true)
return err
},
}
var withdrawValidatorStakeCmd = &cobra.Command{
Use: "withdraw-validator-stake",
RunE: func(*cobra.Command, []string) error {
ctx := context.Background()
_, priv, factory, hcli, hws, ncli, err := handler.DefaultActor()
if err != nil {
return err
}
// Get current list of validators
validators, err := ncli.StakedValidators(ctx)
if err != nil {
return err
}
if len(validators) == 0 {
hutils.Outf("{{red}}no validators{{/}}\n")
return nil
}
// Show validators to the user
hutils.Outf("{{cyan}}validators:{{/}} %d\n", len(validators))
for i := 0; i < len(validators); i++ {
hutils.Outf(
"{{yellow}}%d:{{/}} NodeID=%s\n",
i,
validators[i].NodeID,
)
}
// Select validator
keyIndex, err := handler.Root().PromptChoice("validator to withdraw from staking", len(validators))
if err != nil {
return err
}
validatorChosen := validators[keyIndex]
nodeID := validatorChosen.NodeID
// Get stake info
_, _, stakedAmount, _, _, _, err := ncli.ValidatorStake(ctx, nodeID)
if err != nil {
return err
}
if stakedAmount == 0 {
hutils.Outf("{{red}}validator has not yet been staked{{/}}\n")
return nil
}
// Confirm action
cont, err := handler.Root().PromptContinue()
if !cont || err != nil {
return err
}
// Generate transaction
_, _, err = sendAndWait(ctx, nil, &actions.WithdrawValidatorStake{
NodeID: nodeID.Bytes(),
RewardAddress: priv.Address,
}, hcli, hws, ncli, factory, true)
return err
},
}
var delegateUserStakeCmd = &cobra.Command{
Use: "delegate-user-stake [manual | auto]",
PreRunE: func(cmd *cobra.Command, args []string) error {
if len(args) == 0 || (args[0] != Manual && args[0] != Auto) {
return ErrInvalidArgs
}
return nil
},
RunE: func(_ *cobra.Command, args []string) error {
autoRegister := args[0] == Auto
ctx := context.Background()
_, priv, factory, hcli, hws, ncli, err := handler.DefaultActor()
if err != nil {
return err
}
// Get current list of validators
validators, err := ncli.StakedValidators(ctx)
if err != nil {
return err
}
if len(validators) == 0 {
hutils.Outf("{{red}}no validators{{/}}\n")
return nil
}
hutils.Outf("{{cyan}}validators:{{/}} %d\n", len(validators))
for i := 0; i < len(validators); i++ {
hutils.Outf(
"{{yellow}}%d:{{/}} NodeID=%s\n",
i,
validators[i].NodeID,
)
}
// Select validator
keyIndex, err := handler.Root().PromptChoice("validator to delegate to", len(validators))
if err != nil {
return err
}
validatorChosen := validators[keyIndex]
nodeID := validatorChosen.NodeID
// Get balance info
_, _, balance, _, err := handler.GetAssetInfo(ctx, ncli, priv.Address, ids.Empty, true)
if balance == 0 || err != nil {
return err
}
// Select staked amount
stakedAmount, err := handler.Root().PromptAmount("Staked amount", nconsts.Decimals, balance, nil)
if err != nil {
return err
}
// Get current block
currentBlockHeight, _, _, _, _, _, _, err := ncli.EmissionInfo(ctx)
if err != nil {
return err
}
stakeStartBlock := currentBlockHeight + 20 // roughly 1 minute from now
stakeEndBlock := stakeStartBlock + 20*2 // roughly 10 minutes from stakeStartBlock
rewardAddress := priv.Address
if !autoRegister {
// Select stakeStartBlock
stakeStartBlockString, err := handler.Root().PromptString(
fmt.Sprintf("Staking Start Block(must be after %d)", currentBlockHeight),
1,
32,
)
if err != nil {
return err
}
stakeStartBlock, err = strconv.ParseUint(stakeStartBlockString, 10, 64)
if err != nil {
return err
}