-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathdevnet_actions.go
More file actions
1502 lines (1286 loc) · 49.5 KB
/
devnet_actions.go
File metadata and controls
1502 lines (1286 loc) · 49.5 KB
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
package commands
import (
"context"
"crypto/rand"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"log"
"math/big"
"os"
"os/exec"
"os/signal"
"path/filepath"
"strconv"
"strings"
"sync"
"syscall"
"time"
"github.com/Layr-Labs/devkit-cli/config/configs"
"github.com/Layr-Labs/devkit-cli/config/contexts"
"github.com/Layr-Labs/devkit-cli/pkg/common"
"github.com/Layr-Labs/devkit-cli/pkg/common/devnet"
"github.com/Layr-Labs/devkit-cli/pkg/common/iface"
ethkeystore "github.com/ethereum/go-ethereum/accounts/keystore"
ethcommon "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/urfave/cli/v2"
)
func StartDevnetAction(cCtx *cli.Context) error {
// Check if docker is running, else try to start it
if err := common.EnsureDockerIsRunning(cCtx); err != nil {
if errors.Is(err, context.Canceled) {
return err // propagate the cancellation directly
}
return cli.Exit(err.Error(), 1)
}
// Get logger
logger := common.LoggerFromContext(cCtx)
// Extract vars
contextName := cCtx.String("context")
skipAvsRun := cCtx.Bool("skip-avs-run")
skipDeployContracts := cCtx.Bool("skip-deploy-contracts")
skipTransporter := cCtx.Bool("skip-transporter")
useZeus := cCtx.Bool("use-zeus")
persist := cCtx.Bool("persist")
// Migrate config
configsMigratedCount, err := configs.MigrateConfig(logger)
if err != nil {
logger.Error("config migration failed: %w", err)
}
if configsMigratedCount > 0 {
logger.Info("configs migrated: %d", configsMigratedCount)
}
// Migrate contexts
contextsMigratedCount, err := contexts.MigrateContexts(logger)
if err != nil {
logger.Error("context migrations failed: %w", err)
}
if contextsMigratedCount > 0 {
logger.Info("contexts migrated: %d", contextsMigratedCount)
}
// Load config for selected context
var config *common.ConfigWithContextConfig
if contextName == "" {
config, contextName, err = common.LoadDefaultConfigWithContextConfig()
} else {
config, contextName, err = common.LoadConfigWithContextConfig(contextName)
}
if err != nil {
return fmt.Errorf("loading config and context failed: %w", err)
}
// Prevent runs when context is not devnet
if contextName != devnet.DEVNET_CONTEXT {
return fmt.Errorf("devnet start failed: `devkit avs devnet start` only available on devnet - please run `devkit avs devnet start --context devnet`")
}
// Load the context nodes
yamlPath, rootNode, contextNode, contextName, err := common.LoadContext(contextName)
if err != nil {
return fmt.Errorf("loading context nodes failed: %w", err)
}
// Extract context details
envCtx, ok := config.Context[contextName]
if !ok {
return fmt.Errorf("context '%s' not found in configuration", contextName)
}
// Fetch EigenLayer addresses using Zeus if requested
if useZeus {
err = common.UpdateContextWithZeusAddresses(cCtx.Context, logger, contextNode, contextName)
if err != nil {
logger.Warn("Failed to fetch addresses from Zeus: %v", err)
logger.Info("Continuing with addresses from config...")
} else {
logger.Info("Successfully updated context with addresses from Zeus")
// Write yaml back to project directory
if err := common.WriteYAML(yamlPath, rootNode); err != nil {
return fmt.Errorf("failed to save updated context: %v", err)
}
}
}
l1Port := cCtx.Int("l1-port")
l2Port := cCtx.Int("l2-port")
if !devnet.IsPortAvailable(l2Port) {
return fmt.Errorf("❌ Port %d is already in use. Please choose a different port using --l2-port", l2Port)
}
if !devnet.IsPortAvailable(l1Port) {
return fmt.Errorf("❌ Port %d is already in use. Please choose a different port using --l1-port", l1Port)
}
if !devnet.IsPortAvailable(l2Port) {
return fmt.Errorf("❌ L2 port %d is already in use. Please choose a different port using --port", l2Port)
}
chainImage := devnet.GetDevnetChainImageOrDefault(config)
l1ChainArgs := devnet.GetL1DevnetChainArgsOrDefault(config)
l2ChainArgs := devnet.GetL2DevnetChainArgsOrDefault(config)
// Start timer
startTime := time.Now()
logger.Info("Starting L1 and L2 devnets...\n")
// Docker-compose for anvil devnet
composePath := devnet.WriteEmbeddedArtifacts()
l1ForkUrl, err := common.GetForkUrlDefault(contextName, config, common.L1)
if err != nil {
return fmt.Errorf("L1 fork URL error %w", err)
}
l2ForkUrl, err := common.GetForkUrlDefault(contextName, config, common.L2)
if err != nil {
return fmt.Errorf("L2 fork URL error: %w", err)
}
// Error if the l1ForkUrl has not been modified
if l1ForkUrl == "" {
return fmt.Errorf("l1 fork-url not set; set l1 fork-url in ./config/context/devnet.yaml or .env and consult README for guidance")
}
// Error if the l2ForkUrl has not been modified
if l2ForkUrl == "" {
return fmt.Errorf("l2 fork-url not set; set l2 fork-url in ./config/context/devnet.yaml or .env and consult README for guidance")
}
// Ensure fork URL uses appropriate Docker host for container environments
l1DockerForkUrl := devnet.EnsureDockerHost(l1ForkUrl)
l2DockerForkUrl := devnet.EnsureDockerHost(l2ForkUrl)
// Get the l1 block_time from env/config
l1BlockTime, err := devnet.GetDevnetBlockTimeOrDefault(config, common.L1)
if err != nil {
l1BlockTime = 12
}
// Get the l2 block_time from env/config
l2BlockTime, err := devnet.GetDevnetBlockTimeOrDefault(config, common.L2)
if err != nil {
l2BlockTime = 12
}
// Get the l1 chain_id from env/config
l1ChainId, err := devnet.GetDevnetChainIdOrDefault(config, common.L1, logger)
if err != nil {
l1ChainId = devnet.DEFAULT_L1_ANVIL_CHAINID
}
// Get the l2 chain_id from env/config
l2ChainId, err := devnet.GetDevnetChainIdOrDefault(config, common.L2, logger)
if err != nil {
l2ChainId = devnet.DEFAULT_L2_ANVIL_CHAINID
}
// Append config defined details to chainArgs for l1
l1ChainArgs = fmt.Sprintf("%s --chain-id %d", l1ChainArgs, l1ChainId)
l1ChainArgs = fmt.Sprintf("%s --block-time %d", l1ChainArgs, l1BlockTime)
// Append config defined details to chainArgs for l2
l2ChainArgs = fmt.Sprintf("%s --chain-id %d", l2ChainArgs, l2ChainId)
l2ChainArgs = fmt.Sprintf("%s --block-time %d", l2ChainArgs, l2BlockTime)
// Run docker compose up for anvil devnet
cmd := exec.CommandContext(cCtx.Context, "docker", "compose", "-p", config.Config.Project.Name, "-f", composePath, "up", "-d")
l1ContainerName := fmt.Sprintf("devkit-devnet-l1-%s", config.Config.Project.Name)
l2ContainerName := fmt.Sprintf("devkit-devnet-l2-%s", config.Config.Project.Name)
l1ChainConfig, found := envCtx.Chains[common.L1]
if !found {
return fmt.Errorf("failed to find a chain with name: l1 in devnet.yaml")
}
l2ChainConfig, found := envCtx.Chains[common.L2]
if !found {
return fmt.Errorf("failed to find a chain with name: l2 in devnet.yaml")
}
cmd.Env = append(os.Environ(),
"FOUNDRY_IMAGE="+chainImage,
"L1_ANVIL_ARGS="+l1ChainArgs,
"L2_ANVIL_ARGS="+l2ChainArgs,
fmt.Sprintf("L1_DEVNET_PORT=%d", l1Port),
fmt.Sprintf("L2_DEVNET_PORT=%d", l2Port),
"L1_FORK_RPC_URL="+l1DockerForkUrl,
"L2_FORK_RPC_URL="+l2DockerForkUrl,
fmt.Sprintf("L1_FORK_BLOCK_NUMBER=%d", l1ChainConfig.Fork.Block),
fmt.Sprintf("L2_FORK_BLOCK_NUMBER=%d", l2ChainConfig.Fork.Block),
"L1_AVS_CONTAINER_NAME="+l1ContainerName,
"L2_AVS_CONTAINER_NAME="+l2ContainerName,
)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return fmt.Errorf("❌ Failed to start devnet: %w", err)
}
// On cancel, stop the containers if we're not skipping deployContracts/avsRun and we're not persisting
if !skipDeployContracts && !skipAvsRun && !persist {
defer func() {
logger.Info("Stopping containers")
// Use background context to avoid cancellation issues during cleanup
bgCtx := context.Background()
l1Container := fmt.Sprintf("devkit-devnet-l1-%s", config.Config.Project.Name)
l2Container := fmt.Sprintf("devkit-devnet-l2-%s", config.Config.Project.Name)
logger.Info("Stopping individual containers: %s, %s", l1Container, l2Container)
devnet.StopAndRemoveContainer(&cli.Context{Context: bgCtx}, l1Container)
devnet.StopAndRemoveContainer(&cli.Context{Context: bgCtx}, l2Container)
}()
}
// Construct RPC url to pass to scripts for l1 and l2
l1RpcUrl := devnet.GetRPCURL(l1Port)
l2RpcUrl := devnet.GetRPCURL(l2Port)
logger.Info("Waiting for devnet to be ready...")
// Get chains node
chainsNode := common.GetChildByKey(contextNode, "chains")
if chainsNode == nil {
return fmt.Errorf("missing 'chains' key in context")
}
// Update RPC URLs for L1 chain
l1ChainNode := common.GetChildByKey(chainsNode, common.L1)
if l1ChainNode != nil {
l1RpcUrlNode := common.GetChildByKey(l1ChainNode, "rpc_url")
if l1RpcUrlNode != nil {
l1RpcUrlNode.Value = l1RpcUrl
}
}
// Update RPC URLs for L2 chain
l2ChainNode := common.GetChildByKey(chainsNode, common.L2)
if l2ChainNode != nil {
l2RpcUrlNode := common.GetChildByKey(l2ChainNode, "rpc_url")
if l2RpcUrlNode != nil {
l2RpcUrlNode.Value = l2RpcUrl
}
}
// Write yaml back to project directory
if err := common.WriteYAML(yamlPath, rootNode); err != nil {
return err
}
// Sleep for 4 second to ensure the devnet is fully started
time.Sleep(4 * time.Second)
// Fund the wallets defined in config on L1
logger.Info("Funding wallets on L1...")
err = devnet.FundWalletsDevnet(config, l1RpcUrl)
if err != nil {
return fmt.Errorf("funding L1 devnet wallets failed - please restart devnet and try again: %w", err)
}
// Fund the wallets defined in config on L2
logger.Info("Funding wallets on L2...")
err = devnet.FundWalletsDevnet(config, l2RpcUrl)
if err != nil {
return fmt.Errorf("failed L2 devnet wallets failed - please restart devnet and try again: %w", err)
}
// Fund stakers with strategy tokens
if contextName == devnet.DEVNET_CONTEXT {
logger.Info("Funding stakers with strategy tokens...")
var tokenAddresses []string
var tokenErr error
tokenAddresses, tokenErr = devnet.GetUnderlyingTokenAddressesFromStrategies(config, l1RpcUrl, logger)
if tokenErr != nil {
logger.Warn("Failed to get underlying token addresses from strategies: %v", tokenErr)
logger.Info("Continuing with devnet startup...")
}
if len(tokenAddresses) > 0 {
err = devnet.FundStakersWithStrategyTokens(config, l1RpcUrl, tokenAddresses)
if err != nil {
logger.Warn("Failed to fund stakers with strategy tokens: %v", err)
logger.Info("Continuing with devnet startup...")
}
} else {
logger.Info("No tokens to fund stakers with, skipping token funding")
}
} else {
logger.Info("Skipping token funding for non-devnet context")
}
elapsed := time.Since(startTime).Round(time.Second)
// Sleep for 1 second to make sure wallets are funded
time.Sleep(1 * time.Second)
logger.Info("\nL1 devnet started successfully on port %d", l1Port)
logger.Info("L2 devnet started successfully on port %d", l2Port)
logger.Info("Total startup time: %s", elapsed)
if err := WhitelistChainIdInCrossRegistryAction(cCtx, logger); err != nil {
return fmt.Errorf("whitelisting chain id in cross registry failed - please restart devnet and try again: %w", err)
}
// Deploy the contracts after starting devnet unless skipped
if !skipDeployContracts {
// Check if docker is running, else try to start it
err := common.EnsureDockerIsRunning(cCtx)
if err != nil {
return cli.Exit(err.Error(), 1)
}
// Call deploy L1 action within devnet context
if err := DeployL1ContractsAction(cCtx); err != nil {
return fmt.Errorf("deploy-contracts failed - please restart devnet and try again: %w", err)
}
// Sleep for 1 second to make sure new context values have been written
time.Sleep(1 * time.Second)
logger.Title("Registering AVS with EigenLayer...")
if !cCtx.Bool("skip-setup") {
if err := UpdateAVSMetadataAction(cCtx, logger); err != nil {
return fmt.Errorf("updating AVS metadata failed - please restart devnet and try again: %w", err)
}
if err := SetAVSRegistrarAction(cCtx, logger); err != nil {
return fmt.Errorf("setting AVS registrar failed - please restart devnet and try again: %w", err)
}
if err := CreateAVSOperatorSetsAction(cCtx, logger); err != nil {
return fmt.Errorf("creating AVS operator sets failed - please restart devnet and try again: %w", err)
}
if err := ConfigureOpSetCurveTypeAction(cCtx, logger); err != nil {
return fmt.Errorf("failed to configure OpSet in KeyRegistrar - please restart devnet and try again: %w", err)
}
if err := CreateGenerationReservationAction(cCtx, logger); err != nil {
return fmt.Errorf("failed to request op set generation reservation - please restart devnet and try again: %w", err)
}
if err := RegisterOperatorsToEigenLayerFromConfigAction(cCtx, logger); err != nil {
return fmt.Errorf("registering operators failed - please restart devnet and try again: %w", err)
}
if err := RegisterKeyInKeyRegistrarAction(cCtx, logger); err != nil {
return fmt.Errorf("registering key in key registrar failed - please restart devnet and try again: %w", err)
}
if err := DepositIntoStrategiesAction(cCtx, logger); err != nil {
return fmt.Errorf("depositing into strategies failed - please restart devnet and try again: %w", err)
}
if err := DelegateToOperatorsAction(cCtx, logger); err != nil {
return fmt.Errorf("delegating to operators failed - please restart devnet and try again: %w", err)
}
if err := SetAllocationDelayAction(cCtx, logger); err != nil {
return fmt.Errorf("setting allocation delay failed - please restart devnet and try again: %w", err)
}
if err := ModifyAllocationsAction(cCtx, logger); err != nil {
return fmt.Errorf("modifying allocations failed - please restart devnet and try again: %w", err)
}
if err := RegisterOperatorsToAvsFromConfigAction(cCtx, logger); err != nil {
return fmt.Errorf("registering operators to AVS failed - please restart devnet and try again: %w", err)
}
} else {
logger.Info("Skipping AVS setup steps...")
}
}
// Create a context that cancels on Ctrl-C (SIGINT) or docker/systemd stop (SIGTERM)
ctx, stop := signal.NotifyContext(cCtx.Context, os.Interrupt, syscall.SIGTERM)
defer stop()
// Set up waitGroup to handle bg scheduler
var wg sync.WaitGroup
wg.Add(1)
// Run Transport against schedule - exit when AVSRun exits
if !skipTransporter {
// Post initial stake roots to L1
if err := Transport(cCtx, true); err != nil && !errors.Is(err, context.Canceled) {
return fmt.Errorf("transport run failed - please restart devnet and try again: %w", err)
}
// Shallow-copy cli.Context so that ScheduleTransport sees the new ctx
childCtx := *cCtx
childCtx.Context = ctx
// Run scheduler in the background
go func() {
if err := ScheduleTransport(&childCtx, envCtx.Transporter.Schedule); err != nil && !errors.Is(err, context.Canceled) {
logger.Error("ScheduleTransport failed: %v", err)
stop()
}
}()
}
// Sleep for 2 seconds
time.Sleep(2 * time.Second)
// Deploy L2 contracts only if L1 contracts were also deployed
if !skipDeployContracts {
if err := StartDeployL2Action(cCtx); err != nil && !errors.Is(err, context.Canceled) {
return fmt.Errorf("start-l2-deploy failed - please restart devnet and try again: %w", err)
}
}
// Start offchain AVS components after starting devnet and deploying contracts unless skipped
if !skipDeployContracts && !skipAvsRun {
if err := AVSRun(cCtx); err != nil && !errors.Is(err, context.Canceled) {
return fmt.Errorf("avs run failed - please restart devnet and try again: %w", err)
}
}
// Wait for the scheduler and close on interrupt
done := make(chan struct{})
go func() { wg.Wait(); close(done) }()
select {
case <-ctx.Done(): // user interrupt -> stop scheduler, exit
case <-done: // scheduler ended on its own -> exit
}
return ctx.Err()
}
func StopDevnetAction(cCtx *cli.Context) error {
// Get logger
log := common.LoggerFromContext(cCtx)
// Read flags
stopAllContainers := cCtx.Bool("all")
// Should we stop all?
if stopAllContainers {
// Get all running containers
cmd := exec.CommandContext(cCtx.Context, "docker", devnet.GetDockerPsDevnetArgs()...)
output, err := cmd.Output()
if err != nil {
return fmt.Errorf("failed to list devnet containers: %w", err)
}
containerNames := strings.Split(strings.TrimSpace(string(output)), "\n")
lines := strings.Split(strings.TrimSpace(string(output)), "\n")
if len(lines) == 0 || (len(lines) == 1 && lines[0] == "") {
fmt.Printf("%s🚫 No devnet containers running.%s\n", devnet.Yellow, devnet.Reset)
return nil
}
if cCtx.Bool("verbose") {
log.Info("Attempting to stop devnet containers...")
}
for _, name := range containerNames {
name = strings.TrimSpace(name)
if name == "" {
continue
}
containerName := strings.Split(name, ": ")[0]
devnet.StopAndRemoveContainer(cCtx, containerName)
}
return nil
}
// Extract vars
contextName := cCtx.String("context")
projectName := cCtx.String("project.name")
projectPort := cCtx.Int("port")
l1Port := cCtx.Int("l1-port")
l2Port := cCtx.Int("l2-port")
// Check if any of the args are provided
if !(projectName == "") || !(projectPort == 0) || !(l1Port == 0) || !(l2Port == 0) {
if projectName != "" {
// Stop both L1 and L2 containers
l1Container := fmt.Sprintf("devkit-devnet-l1-%s", projectName)
l2Container := fmt.Sprintf("devkit-devnet-l2-%s", projectName)
devnet.StopAndRemoveContainer(cCtx, l1Container)
devnet.StopAndRemoveContainer(cCtx, l2Container)
} else if l1Port != 0 {
// Stop only L1 container matching the port
stopContainerByPort(cCtx, log, l1Port, "l1")
} else if l2Port != 0 {
// Stop only L2 container matching the port
stopContainerByPort(cCtx, log, l2Port, "l2")
} else if projectPort != 0 {
// Stop both L1 and L2 containers for the project found on this port
stopBothContainersByPort(cCtx, log, projectPort)
}
return nil
}
if devnet.FileExistsInRoot(filepath.Join(common.DefaultConfigWithContextConfigPath, common.BaseConfig)) {
// Load config
var err error
var config *common.ConfigWithContextConfig
if contextName == "" {
config, _, err = common.LoadDefaultConfigWithContextConfig()
} else {
config, _, err = common.LoadConfigWithContextConfig(contextName)
}
if err != nil {
return fmt.Errorf("loading config and context failed: %w", err)
}
// Stop both L1 and L2 containers
l1Container := fmt.Sprintf("devkit-devnet-l1-%s", config.Config.Project.Name)
l2Container := fmt.Sprintf("devkit-devnet-l2-%s", config.Config.Project.Name)
devnet.StopAndRemoveContainer(cCtx, l1Container)
devnet.StopAndRemoveContainer(cCtx, l2Container)
} else {
log.Info("Run this command from the avs directory or run %sdevkit avs devnet stop --help%s for available commands", devnet.Cyan, devnet.Reset)
}
return nil
}
func ListDevnetContainersAction(cCtx *cli.Context) error {
cmd := exec.CommandContext(cCtx.Context, "docker", devnet.GetDockerPsDevnetArgs()...)
output, err := cmd.Output()
if err != nil {
return fmt.Errorf("failed to list devnet containers: %w", err)
}
lines := strings.Split(strings.TrimSpace(string(output)), "\n")
if len(lines) == 0 || (len(lines) == 1 && lines[0] == "") {
fmt.Printf("%s🚫 No devnet containers running.%s\n", devnet.Yellow, devnet.Reset)
return nil
}
fmt.Printf("%s📦 Running Devnet Containers:%s\n\n", devnet.Blue, devnet.Reset)
for _, line := range lines {
parts := strings.Split(line, ": ")
if len(parts) != 2 {
continue
}
name := parts[0]
port := extractHostPort(parts[1])
fmt.Printf("%s - %s%-25s%s %s→%s %shttp://localhost:%s%s\n",
devnet.Cyan, devnet.Reset,
name,
devnet.Reset,
devnet.Green, devnet.Reset,
devnet.Yellow, port, devnet.Reset,
)
}
return nil
}
func DepositIntoStrategiesAction(cCtx *cli.Context, logger iface.Logger) error {
// Extract vars
contextName := cCtx.String("context")
// Load config for selected context
var cfg *common.ConfigWithContextConfig
var err error
if contextName == "" {
cfg, contextName, err = common.LoadDefaultConfigWithContextConfig()
} else {
cfg, contextName, err = common.LoadConfigWithContextConfig(contextName)
}
if err != nil {
return fmt.Errorf("failed to load configurations for deposit into strategies: %w", err)
}
// Extract context details
envCtx, ok := cfg.Context[contextName]
if !ok {
return fmt.Errorf("context '%s' not found in configuration", contextName)
}
logger.Info("Depositing into strategies...")
for _, stakerSpec := range envCtx.Stakers {
logger.Info("Depositing into strategies for staker %s", stakerSpec.StakerAddress)
if err := depositIntoStrategy(cCtx, stakerSpec, logger); err != nil {
logger.Error("Failed to deposit into strategies for staker %s: %v. Continuing...", stakerSpec.StakerAddress, err)
continue
}
}
logger.Info("Depositing into strategies completed.")
return nil
}
func DelegateToOperatorsAction(cCtx *cli.Context, logger iface.Logger) error {
// Extract vars
contextName := cCtx.String("context")
// Load config according to provided contextName
var err error
var cfg *common.ConfigWithContextConfig
if contextName == "" {
cfg, contextName, err = common.LoadDefaultConfigWithContextConfig()
} else {
cfg, contextName, err = common.LoadConfigWithContextConfig(contextName)
}
if err != nil {
return fmt.Errorf("failed to load configurations for delegate to operators: %w", err)
}
// Extract context details
envCtx, ok := cfg.Context[contextName]
if !ok {
return fmt.Errorf("context '%s' not found in configuration", contextName)
}
logger.Info("Delegating to operators...")
for _, stakerSpec := range envCtx.Stakers {
logger.Info("Delegating to operators for staker %s", stakerSpec.StakerAddress)
if err := delegateToOperator(cCtx, stakerSpec, ethcommon.HexToAddress(stakerSpec.OperatorAddress), logger); err != nil {
logger.Error("Failed to delegate to operators for staker %s: %v. Continuing...", stakerSpec.StakerAddress, err)
continue
}
}
logger.Info("Delegating to operators completed.")
return nil
}
func extractHostPort(portStr string) string {
if strings.Contains(portStr, "->") {
beforeArrow := strings.Split(portStr, "->")[0]
hostPort := strings.Split(beforeArrow, ":")
return hostPort[len(hostPort)-1]
}
return portStr
}
func registerOperatorEL(cCtx *cli.Context, operatorAddress string, logger iface.Logger) error {
// Extract vars
contextName := cCtx.String("context")
if operatorAddress == "" {
return fmt.Errorf("operatorAddress parameter is required and cannot be empty")
}
// Load config according to provided contextName
var err error
var cfg *common.ConfigWithContextConfig
if contextName == "" {
cfg, contextName, err = common.LoadDefaultConfigWithContextConfig()
} else {
cfg, contextName, err = common.LoadConfigWithContextConfig(contextName)
}
if err != nil {
return fmt.Errorf("failed to load configurations: %w", err)
}
// Extract context details
envCtx, ok := cfg.Context[contextName]
if !ok {
return fmt.Errorf("context '%s' not found in configuration", contextName)
}
l1Cfg, ok := envCtx.Chains[common.L1]
if !ok {
return fmt.Errorf("failed to get l1 chain config for context '%s'", contextName)
}
client, err := ethclient.Dial(l1Cfg.RPCURL)
if err != nil {
return fmt.Errorf("failed to connect to L1 RPC: %w", err)
}
defer client.Close()
var operatorPrivateKey string
var foundOperator bool
for _, op := range envCtx.Operators {
// Try to load the ECDSA key
keyHex, err := loadOperatorECDSAKey(op)
if err != nil {
continue
}
key, keyErr := crypto.HexToECDSA(keyHex)
if keyErr != nil {
continue
}
if strings.EqualFold(crypto.PubkeyToAddress(key.PublicKey).Hex(), operatorAddress) {
operatorPrivateKey = keyHex
foundOperator = true
break
}
}
if !foundOperator {
return fmt.Errorf("operator with address %s not found in config", operatorAddress)
}
allocationManagerAddr, delegationManagerAddr, strategyManagerAddr, _, _, _, _, _ := common.GetEigenLayerAddresses(contextName, cfg)
contractCaller, err := common.NewContractCaller(
operatorPrivateKey,
big.NewInt(int64(l1Cfg.ChainID)),
client,
ethcommon.HexToAddress(allocationManagerAddr),
ethcommon.HexToAddress(delegationManagerAddr),
ethcommon.HexToAddress(strategyManagerAddr),
ethcommon.HexToAddress(""),
ethcommon.HexToAddress(""),
ethcommon.HexToAddress(""),
ethcommon.HexToAddress(""),
logger,
)
if err != nil {
return fmt.Errorf("failed to create contract caller: %w", err)
}
return contractCaller.RegisterAsOperator(cCtx.Context, ethcommon.HexToAddress(operatorAddress), 0, "test")
}
func registerOperatorAVS(cCtx *cli.Context, logger iface.Logger, operatorAddress string, operatorSetID uint32, payloadHex string) error {
// Extract vars
contextName := cCtx.String("context")
if operatorAddress == "" {
return fmt.Errorf("operatorAddress parameter is required and cannot be empty")
}
if payloadHex == "" {
return fmt.Errorf("payloadHex parameter is required and cannot be empty")
}
// Load config according to provided contextName
var err error
var cfg *common.ConfigWithContextConfig
if contextName == "" {
cfg, contextName, err = common.LoadDefaultConfigWithContextConfig()
} else {
cfg, contextName, err = common.LoadConfigWithContextConfig(contextName)
}
if err != nil {
return fmt.Errorf("failed to load configurations: %w", err)
}
// Extract context details
envCtx, ok := cfg.Context[contextName]
if !ok {
return fmt.Errorf("context '%s' not found in configuration", contextName)
}
l1Cfg, ok := envCtx.Chains[common.L1]
if !ok {
return fmt.Errorf("failed to get l1 chain config for context '%s'", contextName)
}
client, err := ethclient.Dial(l1Cfg.RPCURL)
if err != nil {
return fmt.Errorf("failed to connect to L1 RPC: %w", err)
}
defer client.Close()
var operatorPrivateKey string
var foundOperator bool
for _, op := range envCtx.Operators {
// Try to load the ECDSA key
keyHex, err := loadOperatorECDSAKey(op)
if err != nil {
continue
}
key, keyErr := crypto.HexToECDSA(keyHex)
if keyErr != nil {
continue
}
if strings.EqualFold(crypto.PubkeyToAddress(key.PublicKey).Hex(), operatorAddress) {
operatorPrivateKey = keyHex
foundOperator = true
break
}
}
if !foundOperator {
return fmt.Errorf("operator with address %s not found in config", operatorAddress)
}
allocationManagerAddr, delegationManagerAddr, strategyManagerAddr, _, _, _, _, _ := common.GetEigenLayerAddresses(contextName, cfg)
contractCaller, err := common.NewContractCaller(
operatorPrivateKey,
big.NewInt(int64(l1Cfg.ChainID)),
client,
ethcommon.HexToAddress(allocationManagerAddr),
ethcommon.HexToAddress(delegationManagerAddr),
ethcommon.HexToAddress(strategyManagerAddr),
ethcommon.HexToAddress(""),
ethcommon.HexToAddress(""),
ethcommon.HexToAddress(""),
ethcommon.HexToAddress(""),
logger,
)
if err != nil {
return fmt.Errorf("failed to create contract caller: %w", err)
}
payloadBytes, err := hex.DecodeString(payloadHex)
if err != nil {
return fmt.Errorf("failed to decode payload hex '%s': %w", payloadHex, err)
}
return contractCaller.RegisterForOperatorSets(
cCtx.Context,
ethcommon.HexToAddress(operatorAddress),
ethcommon.HexToAddress(envCtx.Avs.Address),
[]uint32{operatorSetID},
payloadBytes,
)
}
func depositIntoStrategy(cCtx *cli.Context, stakerSpec common.StakerSpec, logger iface.Logger) error {
// Extract vars
contextName := cCtx.String("context")
if stakerSpec.StakerAddress == "" {
return fmt.Errorf("staker address parameter is required and cannot be empty")
}
// Load config according to provided contextName
var err error
var cfg *common.ConfigWithContextConfig
if contextName == "" {
cfg, contextName, err = common.LoadDefaultConfigWithContextConfig()
} else {
cfg, contextName, err = common.LoadConfigWithContextConfig(contextName)
}
if err != nil {
return fmt.Errorf("failed to load configurations: %w", err)
}
// Extract context details
envCtx, ok := cfg.Context[contextName]
if !ok {
return fmt.Errorf("context '%s' not found in configuration", contextName)
}
l1Cfg, ok := envCtx.Chains[common.L1]
if !ok {
return fmt.Errorf("failed to get l1 chain config for context '%s'", contextName)
}
client, err := ethclient.Dial(l1Cfg.RPCURL)
if err != nil {
return fmt.Errorf("failed to connect to L1 RPC: %w", err)
}
defer client.Close()
allocationManagerAddr, delegationManagerAddr, strategyManagerAddr, _, _, _, _, _ := common.GetEigenLayerAddresses(contextName, cfg)
stakerPrivateKey := strings.TrimPrefix(stakerSpec.StakerECDSAKey, "0x")
contractCaller, err := common.NewContractCaller(
stakerPrivateKey,
big.NewInt(int64(l1Cfg.ChainID)),
client,
ethcommon.HexToAddress(allocationManagerAddr),
ethcommon.HexToAddress(delegationManagerAddr),
ethcommon.HexToAddress(strategyManagerAddr),
ethcommon.HexToAddress(""),
ethcommon.HexToAddress(""),
ethcommon.HexToAddress(""),
ethcommon.HexToAddress(""),
logger,
)
if err != nil {
return fmt.Errorf("failed to create contract caller: %w", err)
}
for _, deposit := range stakerSpec.Deposits {
strategyAddress := deposit.StrategyAddress
depositAmount := deposit.DepositAmount
amount, err := common.ParseETHAmount(depositAmount)
if err != nil {
return fmt.Errorf("failed to parse deposit amount '%s': %w", depositAmount, err)
}
if err := contractCaller.DepositIntoStrategy(cCtx.Context, ethcommon.HexToAddress(strategyAddress), amount); err != nil {
return fmt.Errorf("failed to deposit into strategy: %w", err)
}
}
return nil
}
func delegateToOperator(cCtx *cli.Context, stakerSpec common.StakerSpec, operator ethcommon.Address, logger iface.Logger) error {
// Extract vars
contextName := cCtx.String("context")
// Load config according to provided contextName
var err error
var cfg *common.ConfigWithContextConfig
if contextName == "" {
cfg, contextName, err = common.LoadDefaultConfigWithContextConfig()
} else {
cfg, contextName, err = common.LoadConfigWithContextConfig(contextName)
}
if err != nil {
return fmt.Errorf("failed to load configurations: %w", err)
}
// Extract context details
envCtx, ok := cfg.Context[contextName]
if !ok {
return fmt.Errorf("context '%s' not found in configuration", contextName)
}
l1Cfg, ok := envCtx.Chains[common.L1]
if !ok {
return fmt.Errorf("failed to get l1 chain config for context '%s'", contextName)
}
client, err := ethclient.Dial(l1Cfg.RPCURL)
if err != nil {
return fmt.Errorf("failed to connect to L1 RPC: %w", err)
}
defer client.Close()
allocationManagerAddr, delegationManagerAddr, strategyManagerAddr, _, _, _, _, _ := common.GetEigenLayerAddresses(contextName, cfg)
stakerPrivateKey := strings.TrimPrefix(stakerSpec.StakerECDSAKey, "0x")
contractCaller, err := common.NewContractCaller(
stakerPrivateKey,
big.NewInt(int64(l1Cfg.ChainID)),
client,
ethcommon.HexToAddress(allocationManagerAddr),
ethcommon.HexToAddress(delegationManagerAddr),
ethcommon.HexToAddress(strategyManagerAddr),
ethcommon.HexToAddress(""),
ethcommon.HexToAddress(""),
ethcommon.HexToAddress(""),
ethcommon.HexToAddress(""),
logger,
)
if err != nil {
return fmt.Errorf("failed to create contract caller: %w", err)
}
// After depositing, delegate to the operator
// Extract the private key of the operator we are delegating to in order to create an approval signature
var operatorPrivateKey string
var foundOperator bool
for _, op := range envCtx.Operators {
if strings.EqualFold(op.Address, operator.Hex()) {
keyHex, err := loadOperatorECDSAKey(op)
if err != nil {
return fmt.Errorf("failed to load ECDSA key for operator %s: %w", operator, err)
}
operatorPrivateKey = keyHex
foundOperator = true
break
}
}
if !foundOperator {
return fmt.Errorf("ECDSA key not found for operator %s in operators in config. This means we cannot create an approval signature for this delegation", operator)
}
// expiry is 10 minutes from now
expiry := big.NewInt(time.Now().Add(10 * time.Minute).Unix())
// generate a random salt
salt := [32]byte{}
_, err = rand.Read(salt[:])
if err != nil {
return fmt.Errorf("failed to generate random salt: %w", err)
}
// Create the approval signature
signature, err := contractCaller.CreateApprovalSignature(cCtx.Context, ethcommon.HexToAddress(stakerSpec.StakerAddress), operator, operator, operatorPrivateKey, salt, expiry)
if err != nil {
return fmt.Errorf("failed to create approval signature: %w", err)
}
if err := contractCaller.DelegateToOperator(cCtx.Context, operator, signature, salt); err != nil {
return fmt.Errorf("failed to delegate to operator: %w", err)
}
return nil
}