-
Notifications
You must be signed in to change notification settings - Fork 84
Expand file tree
/
Copy pathdependencyinstaller.go
More file actions
973 lines (811 loc) · 31.5 KB
/
dependencyinstaller.go
File metadata and controls
973 lines (811 loc) · 31.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
/*
* 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 dependencymanager
import (
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"os"
"path/filepath"
"github.com/psiemens/sconfig"
"github.com/onflow/flow-cli/common/branding"
"github.com/onflow/flow-cli/internal/prompt"
"github.com/onflow/flow-cli/internal/util"
"github.com/spf13/cobra"
"github.com/onflow/flow-go/fvm/systemcontracts"
flowGo "github.com/onflow/flow-go/model/flow"
"github.com/onflow/flowkit/v2/gateway"
"github.com/onflow/flowkit/v2/project"
flowsdk "github.com/onflow/flow-go-sdk"
"github.com/onflow/flowkit/v2/config"
"github.com/onflow/flowkit/v2"
"github.com/onflow/flowkit/v2/output"
)
type categorizedLogs struct {
fileSystemActions []string
stateUpdates []string
issues []string
}
// pendingPrompt represents a dependency that needs interactive prompts after tree display
type pendingPrompt struct {
contractName string
networkName string
needsDeployment bool
needsAlias bool
needsUpdate bool
updateHash string
}
func (cl *categorizedLogs) LogAll(logger output.Logger) {
logger.Info(util.MessageWithEmojiPrefix("📝", "Dependency Manager Actions Summary"))
logger.Info("") // Add a line break after the section
if len(cl.fileSystemActions) > 0 {
logger.Info(util.MessageWithEmojiPrefix("🗃️", "File System Actions:"))
for _, msg := range cl.fileSystemActions {
logger.Info(msg)
}
logger.Info("") // Add a line break after the section
}
if len(cl.stateUpdates) > 0 {
logger.Info(util.MessageWithEmojiPrefix("💾", "State Updates:"))
for _, msg := range cl.stateUpdates {
logger.Info(msg)
}
logger.Info("") // Add a line break after the section
}
if len(cl.issues) > 0 {
logger.Info(util.MessageWithEmojiPrefix("⚠️", "Issues:"))
for _, msg := range cl.issues {
logger.Info(msg)
}
logger.Info("")
}
if len(cl.fileSystemActions) == 0 && len(cl.stateUpdates) == 0 {
logger.Info(util.MessageWithEmojiPrefix("👍", "Zero changes were made. Everything looks good."))
}
}
type DependencyFlags struct {
skipDeployments bool `default:"false" flag:"skip-deployments" info:"Skip adding the dependency to deployments"`
skipAlias bool `default:"false" flag:"skip-alias" info:"Skip prompting for an alias"`
skipUpdatePrompts bool `default:"false" flag:"skip-update-prompts" info:"Skip prompting to update existing dependencies"`
deploymentAccount string `default:"" flag:"deployment-account,d" info:"Account name to use for deployments (skips deployment account prompt)"`
name string `default:"" flag:"name" info:"Import alias name for the dependency (sets canonical field for Cadence import aliasing)"`
}
func (f *DependencyFlags) AddToCommand(cmd *cobra.Command) {
err := sconfig.New(f).
FromEnvironment(util.EnvPrefix).
BindFlags(cmd.Flags()).
Parse()
if err != nil {
panic(err)
}
}
type DependencyInstaller struct {
Gateways map[string]gateway.Gateway
Logger output.Logger
State *flowkit.State
SaveState bool
TargetDir string
SkipDeployments bool
SkipAlias bool
DeploymentAccount string
Name string
logs categorizedLogs
dependencies map[string]config.Dependency
accountAliases map[string]map[string]flowsdk.Address // network -> account -> alias
installCount int // Track number of dependencies installed
pendingPrompts []pendingPrompt // Dependencies that need prompts after tree display
}
// NewDependencyInstaller creates a new instance of DependencyInstaller
func NewDependencyInstaller(logger output.Logger, state *flowkit.State, saveState bool, targetDir string, flags DependencyFlags) (*DependencyInstaller, error) {
emulatorGateway, err := gateway.NewGrpcGateway(config.EmulatorNetwork)
if err != nil {
return nil, fmt.Errorf("error creating emulator gateway: %v", err)
}
testnetGateway, err := gateway.NewGrpcGateway(config.TestnetNetwork)
if err != nil {
return nil, fmt.Errorf("error creating testnet gateway: %v", err)
}
mainnetGateway, err := gateway.NewGrpcGateway(config.MainnetNetwork)
if err != nil {
return nil, fmt.Errorf("error creating mainnet gateway: %v", err)
}
gateways := map[string]gateway.Gateway{
config.EmulatorNetwork.Name: emulatorGateway,
config.TestnetNetwork.Name: testnetGateway,
config.MainnetNetwork.Name: mainnetGateway,
}
return &DependencyInstaller{
Gateways: gateways,
Logger: logger,
State: state,
SaveState: saveState,
TargetDir: targetDir,
SkipDeployments: flags.skipDeployments,
SkipAlias: flags.skipAlias,
DeploymentAccount: flags.deploymentAccount,
Name: flags.name,
dependencies: make(map[string]config.Dependency),
logs: categorizedLogs{},
accountAliases: make(map[string]map[string]flowsdk.Address),
pendingPrompts: make([]pendingPrompt, 0),
}, nil
}
// saveState checks the SaveState flag and saves the state if set to true.
func (di *DependencyInstaller) saveState() error {
if di.SaveState {
statePath := filepath.Join(di.TargetDir, "flow.json")
if err := di.State.Save(statePath); err != nil {
return fmt.Errorf("error saving state: %w", err)
}
}
return nil
}
// Install processes all the dependencies in the state and installs them and any dependencies they have
func (di *DependencyInstaller) Install() error {
// Phase 1: Process all dependencies and display tree (no prompts)
for _, dependency := range *di.State.Dependencies() {
if err := di.processDependency(dependency); err != nil {
di.Logger.Error(fmt.Sprintf("Error processing dependency: %v", err))
return err
}
}
// Phase 2: Handle all collected prompts after tree is complete
if err := di.processPendingPrompts(); err != nil {
return err
}
di.checkForConflictingContracts()
if err := di.saveState(); err != nil {
return fmt.Errorf("error saving state: %w", err)
}
return nil
}
// AddBySourceString processes a single dependency and installs it and any dependencies it has, as well as adding it to the state
func (di *DependencyInstaller) AddBySourceString(depSource string) error {
depNetwork, depAddress, depContractName, err := config.ParseSourceString(depSource)
if err != nil {
return fmt.Errorf("error parsing source: %w", err)
}
dep := config.Dependency{
Name: depContractName,
Source: config.Source{
NetworkName: depNetwork,
Address: flowsdk.HexToAddress(depAddress),
ContractName: depContractName,
},
}
// If a name is provided, use it as the import alias and set canonical for Cadence import aliasing
// This enables "import OriginalContract as AliasName from address" syntax
if di.Name != "" {
dep.Name = di.Name
dep.Canonical = depContractName
}
return di.Add(dep)
}
func (di *DependencyInstaller) AddByCoreContractName(coreContractName string) error {
var depNetwork, depAddress, depContractName string
sc := systemcontracts.SystemContractsForChain(flowGo.Mainnet)
for _, coreContract := range sc.All() {
if coreContract.Name == coreContractName {
depAddress = coreContract.Address.String()
depNetwork = config.MainnetNetwork.Name
depContractName = coreContractName
break
}
}
if depAddress == "" {
return fmt.Errorf("contract %s not found in core contracts", coreContractName)
}
// Log installation with detailed information and branding colors
contractNameStyled := branding.PurpleStyle.Render(coreContractName)
shortAddress := "0x..." + depAddress[len(depAddress)-4:]
addressStyled := branding.GreenStyle.Render(shortAddress)
networkStyled := branding.GrayStyle.Render(depNetwork)
di.Logger.Info(fmt.Sprintf("%s @ %s (%s)", contractNameStyled, addressStyled, networkStyled))
dep := config.Dependency{
Name: depContractName,
Source: config.Source{
NetworkName: depNetwork,
Address: flowsdk.HexToAddress(depAddress),
ContractName: depContractName,
},
}
// If a name is provided, use it as the import alias and set canonical for Cadence import aliasing
// This enables "import OriginalContract as AliasName from address" syntax
if di.Name != "" {
dep.Name = di.Name
dep.Canonical = depContractName
}
return di.Add(dep)
}
func (di *DependencyInstaller) AddByDefiContractName(defiContractName string) error {
defiActionsSection := getDefiActionsSection()
var targetDep *config.Dependency
for _, dep := range defiActionsSection.Dependencies {
if dep.Name == defiContractName && dep.Source.NetworkName == config.MainnetNetwork.Name {
targetDep = &dep
break
}
}
if targetDep == nil {
return fmt.Errorf("contract %s not found in DeFi actions contracts", defiContractName)
}
// If a custom name is provided, use it as the dependency name and set canonical
if di.Name != "" {
targetDep.Name = di.Name
targetDep.Canonical = defiContractName
}
return di.Add(*targetDep)
}
func isDefiActionsContract(contractName string) bool {
defiActionsSection := getDefiActionsSection()
for _, dep := range defiActionsSection.Dependencies {
if dep.Name == contractName {
return true
}
}
return false
}
// Add processes a single dependency and installs it and any dependencies it has, as well as adding it to the state
func (di *DependencyInstaller) Add(dep config.Dependency) error {
// Phase 1: Process dependency and display tree (no prompts)
if err := di.processDependency(dep); err != nil {
return fmt.Errorf("error processing dependency: %w", err)
}
// Phase 2: Handle all collected prompts after tree is complete
if err := di.processPendingPrompts(); err != nil {
return err
}
di.checkForConflictingContracts()
if err := di.saveState(); err != nil {
return err
}
return nil
}
// AddMany processes multiple dependencies and installs them as well as adding them to the state
func (di *DependencyInstaller) AddMany(dependencies []config.Dependency) error {
// Phase 1: Process all dependencies and display tree (no prompts)
for _, dep := range dependencies {
if err := di.processDependency(dep); err != nil {
return fmt.Errorf("error processing dependency: %w", err)
}
}
// Phase 2: Handle all collected prompts after tree is complete
if err := di.processPendingPrompts(); err != nil {
return err
}
di.checkForConflictingContracts()
if err := di.saveState(); err != nil {
return err
}
return nil
}
func (di *DependencyInstaller) AddAllByNetworkAddress(sourceStr string) error {
// Check if name flag is set - not supported when installing all contracts at an address
if di.Name != "" {
return fmt.Errorf("--name flag is not supported when installing all contracts at an address (network://address). Please specify a specific contract using network://address.ContractName format")
}
network, address := ParseNetworkAddressString(sourceStr)
accountContracts, err := di.getContracts(network, flowsdk.HexToAddress(address))
if err != nil {
return fmt.Errorf("failed to fetch account contracts: %w", err)
}
var dependencies []config.Dependency
for _, contract := range accountContracts {
program, err := project.NewProgram(contract, nil, "")
if err != nil {
return fmt.Errorf("failed to parse program: %w", err)
}
contractName, err := program.Name()
if err != nil {
return fmt.Errorf("failed to parse contract name: %w", err)
}
dep := config.Dependency{
Name: contractName,
Source: config.Source{
NetworkName: network,
Address: flowsdk.HexToAddress(address),
ContractName: contractName,
},
}
dependencies = append(dependencies, dep)
}
if err := di.AddMany(dependencies); err != nil {
return err
}
return nil
}
func (di *DependencyInstaller) addDependency(dep config.Dependency) error {
sourceString := fmt.Sprintf("%s://%s.%s", dep.Source.NetworkName, dep.Source.Address.String(), dep.Source.ContractName)
if _, exists := di.dependencies[sourceString]; exists {
return nil
}
di.dependencies[sourceString] = dep
return nil
}
// checkForConflictingContracts checks if any of the dependencies conflict with contracts already in the state
func (di *DependencyInstaller) checkForConflictingContracts() {
for _, dependency := range di.dependencies {
foundContract, _ := di.State.Contracts().ByName(dependency.Name)
if foundContract != nil && !foundContract.IsDependency {
msg := util.MessageWithEmojiPrefix("❌", fmt.Sprintf("Contract named %s already exists in flow.json", dependency.Name))
di.logs.issues = append(di.logs.issues, msg)
}
}
}
func (di *DependencyInstaller) processDependency(dependency config.Dependency) error {
return di.processDependencies(dependency)
}
func (di *DependencyInstaller) getContracts(network string, address flowsdk.Address) (map[string][]byte, error) {
gw, ok := di.Gateways[network]
if !ok {
return nil, fmt.Errorf("gateway for network %s not found", network)
}
ctx := context.Background()
acct, err := gw.GetAccount(ctx, address)
if err != nil {
return nil, fmt.Errorf("failed to get account at %s on %s: %w", address, network, err)
}
if acct == nil {
return nil, fmt.Errorf("no account found at address %s on network %s", address, network)
}
if len(acct.Contracts) == 0 {
return nil, fmt.Errorf("no contracts found at address %s on network %s", address, network)
}
return acct.Contracts, nil
}
func (di *DependencyInstaller) processDependencies(dependency config.Dependency) error {
return di.fetchDependenciesWithDepth(dependency, 0)
}
func (di *DependencyInstaller) fetchDependenciesWithDepth(dependency config.Dependency, depth int) error {
networkName := dependency.Source.NetworkName
address := dependency.Source.Address
contractName := dependency.Source.ContractName
// Safety limit to prevent excessive recursion
const maxDepth = 10
if depth > maxDepth {
di.Logger.Info(fmt.Sprintf("⚠️ Skipping dependency %s: maximum depth (%d) exceeded", contractName, maxDepth))
return nil
}
sourceString := fmt.Sprintf("%s://%s.%s", networkName, address.String(), contractName)
if _, exists := di.dependencies[sourceString]; exists {
return nil // Skip already processed dependencies
}
// Log installation with visual hierarchy and branding colors
indent := ""
prefix := ""
if depth > 0 {
// Create indentation with proper tree characters
for i := 0; i < depth; i++ {
indent += " "
}
prefix = "├─ "
// Add depth limit warning for very deep chains
if depth >= 5 {
di.Logger.Info(fmt.Sprintf("%s⚠️ Deep dependency chain (depth %d)", indent, depth))
}
}
contractNameStyled := branding.PurpleStyle.Render(contractName)
fullAddress := address.String()
shortAddress := "0x..." + fullAddress[len(fullAddress)-4:]
addressStyled := branding.GreenStyle.Render(shortAddress)
networkStyled := branding.GrayStyle.Render(networkName)
di.Logger.Info(fmt.Sprintf("%s%s%s @ %s (%s)", indent, prefix, contractNameStyled, addressStyled, networkStyled))
di.installCount++
err := di.addDependency(dependency)
if err != nil {
return fmt.Errorf("error adding dependency: %w", err)
}
accountContracts, err := di.getContracts(networkName, address)
if err != nil {
return fmt.Errorf("error fetching contracts: %w", err)
}
contract, ok := accountContracts[contractName]
if !ok {
return fmt.Errorf("contract %s not found at address %s", contractName, address.String())
}
program, err := project.NewProgram(contract, nil, "")
if err != nil {
return fmt.Errorf("failed to parse program: %w", err)
}
if err := di.handleFoundContract(dependency, program); err != nil {
return fmt.Errorf("failed to handle found contract: %w", err)
}
if program.HasAddressImports() {
imports := program.AddressImportDeclarations()
for _, imp := range imports {
actualContractName := imp.Imports[0].Identifier.Identifier
importAddress := flowsdk.HexToAddress(imp.Location.String())
// Check if this import has an alias (e.g., "import FUSD as FUSD1 from 0xaddress")
// If aliased, use the alias as the dependency name so "import FUSD1" resolves correctly
dependencyName := actualContractName
if imp.Imports[0].Alias.Identifier != "" {
dependencyName = imp.Imports[0].Alias.Identifier
}
// Create a dependency for the import
// Name is the alias (or actual name if not aliased) - this is what gets resolved in imports
// ContractName is the actual contract name on chain - this is what gets fetched
importDependency := config.Dependency{
Name: dependencyName,
Source: config.Source{
NetworkName: networkName,
Address: importAddress,
ContractName: actualContractName,
},
}
err := di.fetchDependenciesWithDepth(importDependency, depth+1)
if err != nil {
return err
}
}
}
return nil
}
func (di *DependencyInstaller) contractFileExists(address, contractName string) bool {
fileName := fmt.Sprintf("%s.cdc", contractName)
path := filepath.Join("imports", address, fileName)
_, err := di.State.ReaderWriter().Stat(path)
return err == nil
}
func (di *DependencyInstaller) createContractFile(address, contractName, data string) error {
fileName := fmt.Sprintf("%s.cdc", contractName)
path := filepath.Join(di.TargetDir, "imports", address, fileName)
dir := filepath.Dir(path)
if err := di.State.ReaderWriter().MkdirAll(dir, 0755); err != nil {
return fmt.Errorf("error creating directories: %w", err)
}
if err := di.State.ReaderWriter().WriteFile(path, []byte(data), 0644); err != nil {
return fmt.Errorf("error writing file: %w", err)
}
return nil
}
func (di *DependencyInstaller) handleFileSystem(contractAddr, contractName, contractData, networkName string) error {
if !di.contractFileExists(contractAddr, contractName) {
if err := di.createContractFile(contractAddr, contractName, contractData); err != nil {
return fmt.Errorf("failed to create contract file: %w", err)
}
msg := util.MessageWithEmojiPrefix("✅️", fmt.Sprintf("Contract %s from %s on %s installed", contractName, contractAddr, networkName))
di.logs.fileSystemActions = append(di.logs.fileSystemActions, msg)
}
return nil
}
func (di *DependencyInstaller) handleFoundContract(dependency config.Dependency, program *project.Program) error {
networkName := dependency.Source.NetworkName
contractAddr := dependency.Source.Address.String()
contractName := dependency.Source.ContractName
hash := sha256.New()
hash.Write(program.CodeWithUnprocessedImports())
originalContractDataHash := hex.EncodeToString(hash.Sum(nil))
program.ConvertAddressImports()
contractData := string(program.CodeWithUnprocessedImports())
existingDependency := di.State.Dependencies().ByName(dependency.Name)
// If a dependency by this name already exists and its remote source network or address does not match,
// allow it only if an existing alias matches the incoming network+address; otherwise terminate.
if existingDependency != nil && (existingDependency.Source.NetworkName != networkName || existingDependency.Source.Address.String() != contractAddr) {
if !di.existingAliasMatches(dependency.Name, networkName, contractAddr) {
di.Logger.Info(fmt.Sprintf("%s A dependency named %s already exists with a different remote source. Please fix the conflict and retry.", util.PrintEmoji("🚫"), dependency.Name))
os.Exit(0)
return nil
}
// Alias matched - contract already stored, encountered via different network. Skip state update.
return nil
}
// Check if remote source version is different from local version
// If it is, defer the prompt until after the tree is displayed
// If no hash, ignore
if existingDependency != nil && existingDependency.Hash != "" && existingDependency.Hash != originalContractDataHash {
// Find existing pending prompt for this contract or create new one
found := false
for i := range di.pendingPrompts {
if di.pendingPrompts[i].contractName == dependency.Name {
di.pendingPrompts[i].needsUpdate = true
di.pendingPrompts[i].updateHash = originalContractDataHash
found = true
break
}
}
if !found {
di.pendingPrompts = append(di.pendingPrompts, pendingPrompt{
contractName: dependency.Name,
networkName: networkName,
needsUpdate: true,
updateHash: originalContractDataHash,
})
}
return nil
}
// Check if this is a new dependency before updating state
isNewDep := di.State.Dependencies().ByName(dependency.Name) == nil
err := di.updateDependencyState(dependency, originalContractDataHash)
if err != nil {
di.Logger.Error(fmt.Sprintf("Error updating state: %v", err))
return err
}
// Handle additional tasks for new dependencies or when contract file doesn't exist
// This makes sure prompts are collected for new dependencies regardless of whether contract file exists
if isNewDep || !di.contractFileExists(contractAddr, contractName) {
err := di.handleAdditionalDependencyTasks(networkName, dependency.Name)
if err != nil {
di.Logger.Error(fmt.Sprintf("Error handling additional dependency tasks: %v", err))
return err
}
}
err = di.handleFileSystem(contractAddr, contractName, contractData, networkName)
if err != nil {
return fmt.Errorf("error handling file system: %w", err)
}
return nil
}
// existingAliasMatches returns true if an existing contract with the given name has an alias
// for the provided network that matches the specified address.
func (di *DependencyInstaller) existingAliasMatches(contractName, networkName, contractAddr string) bool {
if di.State == nil || di.State.Contracts() == nil {
return false
}
contract, err := di.State.Contracts().ByName(contractName)
if err != nil || contract == nil {
return false
}
alias := contract.Aliases.ByNetwork(networkName)
if alias == nil {
return false
}
return alias.Address.String() == contractAddr
}
func (di *DependencyInstaller) handleAdditionalDependencyTasks(networkName, contractName string) error {
// If the contract is not a core contract and the user does not want to skip deployments, then collect for prompting later
needsDeployment := !di.SkipDeployments && !util.IsCoreContract(contractName)
// For DeFi Actions contracts, only allow deployment on emulator (handle immediately since no prompt needed)
if needsDeployment && isDefiActionsContract(contractName) {
err := di.updateDependencyDeployment(contractName, "emulator")
if err != nil {
di.Logger.Error(fmt.Sprintf("Error updating deployment: %v", err))
return err
}
msg := util.MessageWithEmojiPrefix("✅", fmt.Sprintf("%s added to emulator deployments (DeFi Actions contracts only supported on emulator)", contractName))
di.logs.stateUpdates = append(di.logs.stateUpdates, msg)
needsDeployment = false // Already handled
}
// If the contract is not a core contract and the user does not want to skip aliasing, then collect for prompting later
needsAlias := !di.SkipAlias && !util.IsCoreContract(contractName) && !isDefiActionsContract(contractName)
// Only add to pending prompts if we need to prompt for something
if needsDeployment || needsAlias {
di.pendingPrompts = append(di.pendingPrompts, pendingPrompt{
contractName: contractName,
networkName: networkName,
needsDeployment: needsDeployment,
needsAlias: needsAlias,
})
}
return nil
}
func (di *DependencyInstaller) updateDependencyDeployment(contractName string, forceNetwork ...string) error {
var raw *prompt.DeploymentData
network := "emulator"
// If a forced network is specified, use it
if len(forceNetwork) > 0 {
network = forceNetwork[0]
}
// If deployment account is specified via flag, use it; otherwise prompt
if di.DeploymentAccount != "" {
account, err := di.State.Accounts().ByName(di.DeploymentAccount)
if err != nil || account == nil {
return fmt.Errorf("deployment account '%s' not found in flow.json accounts", di.DeploymentAccount)
}
raw = &prompt.DeploymentData{
Network: network,
Account: di.DeploymentAccount,
Contracts: []string{contractName},
}
} else {
raw = prompt.AddContractToDeploymentPrompt(network, *di.State.Accounts(), contractName)
}
if raw != nil {
deployment := di.State.Deployments().ByAccountAndNetwork(raw.Account, raw.Network)
if deployment == nil {
di.State.Deployments().AddOrUpdate(config.Deployment{
Network: raw.Network,
Account: raw.Account,
})
deployment = di.State.Deployments().ByAccountAndNetwork(raw.Account, raw.Network)
}
for _, c := range raw.Contracts {
deployment.AddContract(config.ContractDeployment{Name: c})
}
}
return nil
}
func (di *DependencyInstaller) updateDependencyAlias(contractName, aliasNetwork string) error {
var missingNetworks []string
switch aliasNetwork {
case config.MainnetNetwork.Name:
missingNetworks = []string{config.TestnetNetwork.Name}
case config.TestnetNetwork.Name:
missingNetworks = []string{config.MainnetNetwork.Name}
}
for _, missingNetwork := range missingNetworks {
// Check if we already have an alias for this account on this network
accountAddress := di.getCurrentContractAccountAddress(contractName, aliasNetwork)
if accountAddress != "" {
if existingAlias, exists := di.getAccountAlias(accountAddress, missingNetwork); exists {
// Automatically apply the existing alias
contract, err := di.State.Contracts().ByName(contractName)
if err != nil {
return err
}
contract.Aliases.Add(missingNetwork, existingAlias)
di.Logger.Info(fmt.Sprintf("%s Automatically applied alias %s for %s on %s (from same account)",
util.PrintEmoji("🔄"), existingAlias.String(), contractName, missingNetwork))
continue
}
}
label := fmt.Sprintf("Enter an alias address for %s on %s if you have one, otherwise leave blank", contractName, missingNetwork)
raw := prompt.AddressPromptOrEmpty(label, "Invalid alias address")
if raw != "" {
aliasAddress := flowsdk.HexToAddress(raw)
if accountAddress != "" {
di.setAccountAlias(accountAddress, missingNetwork, aliasAddress)
}
contract, err := di.State.Contracts().ByName(contractName)
if err != nil {
return err
}
contract.Aliases.Add(missingNetwork, aliasAddress)
}
}
return nil
}
func (di *DependencyInstaller) updateDependencyState(originalDependency config.Dependency, contractHash string) error {
// Create the dependency to save, preserving aliases and canonical from the original
dep := config.Dependency{
Name: originalDependency.Name,
Source: originalDependency.Source,
Hash: contractHash,
Aliases: originalDependency.Aliases,
Canonical: originalDependency.Canonical,
}
isNewDep := di.State.Dependencies().ByName(dep.Name) == nil
di.State.Dependencies().AddOrUpdate(dep)
di.State.Contracts().AddDependencyAsContract(dep, originalDependency.Source.NetworkName)
// If this is an aliased import (Name differs from ContractName), set the Canonical field on the contract
// This enables flowkit to generate the correct "import X as Y from address" syntax
if dep.Name != dep.Source.ContractName {
contract, err := di.State.Contracts().ByName(dep.Name)
if err == nil && contract != nil {
contract.Canonical = dep.Source.ContractName
}
}
if isNewDep {
msg := util.MessageWithEmojiPrefix("✅", fmt.Sprintf("%s added to flow.json", dep.Name))
di.logs.stateUpdates = append(di.logs.stateUpdates, msg)
}
return nil
}
// getCurrentContractAccountAddress returns the account address for the current contract being processed
func (di *DependencyInstaller) getCurrentContractAccountAddress(contractName, networkName string) string {
for _, dep := range di.dependencies {
if dep.Name == contractName && dep.Source.NetworkName == networkName {
return dep.Source.Address.String()
}
}
return ""
}
// getAccountAlias returns the stored alias for an account on a specific network
func (di *DependencyInstaller) getAccountAlias(accountAddress, networkName string) (flowsdk.Address, bool) {
if networkAliases, exists := di.accountAliases[networkName]; exists {
if alias, exists := networkAliases[accountAddress]; exists {
return alias, true
}
}
return flowsdk.Address{}, false
}
// setAccountAlias stores an alias for an account on a specific network
func (di *DependencyInstaller) setAccountAlias(accountAddress, networkName string, alias flowsdk.Address) {
if di.accountAliases[networkName] == nil {
di.accountAliases[networkName] = make(map[string]flowsdk.Address)
}
di.accountAliases[networkName][accountAddress] = alias
}
// processPendingPrompts handles all collected prompts after the dependency tree is displayed
func (di *DependencyInstaller) processPendingPrompts() error {
if len(di.pendingPrompts) == 0 {
return nil
}
di.Logger.Info("") // Add spacing after tree display
// Check if we have any dependencies that need deployments
hasDeployments := false
for _, pending := range di.pendingPrompts {
if pending.needsDeployment {
hasDeployments = true
break
}
}
// Check if we have any dependencies that need aliases
hasAliases := false
for _, pending := range di.pendingPrompts {
if pending.needsAlias {
hasAliases = true
break
}
}
setupDeployments := false
if hasDeployments {
result, err := prompt.GenericBoolPrompt("Do you want to set up deployments for these dependencies?")
if err != nil {
return err
}
setupDeployments = result
}
setupAliases := false
if hasAliases {
result, err := prompt.GenericBoolPrompt("Do you want to set up aliases for these dependencies?")
if err != nil {
return err
}
setupAliases = result
}
// Process prompts based on user choices
for _, pending := range di.pendingPrompts {
if pending.needsUpdate {
msg := fmt.Sprintf("The latest version of %s is different from the one you have locally. Do you want to update it?", pending.contractName)
shouldUpdate, err := prompt.GenericBoolPrompt(msg)
if err != nil {
return err
}
if shouldUpdate {
dependency := di.State.Dependencies().ByName(pending.contractName)
if dependency != nil {
err := di.updateDependencyState(*dependency, pending.updateHash)
if err != nil {
di.Logger.Error(fmt.Sprintf("Error updating dependency: %v", err))
return err
}
msg := util.MessageWithEmojiPrefix("✅", fmt.Sprintf("%s updated to latest version", pending.contractName))
di.logs.stateUpdates = append(di.logs.stateUpdates, msg)
}
}
}
}
for _, pending := range di.pendingPrompts {
if pending.needsDeployment && setupDeployments {
err := di.updateDependencyDeployment(pending.contractName)
if err != nil {
di.Logger.Error(fmt.Sprintf("Error updating deployment: %v", err))
return err
}
msg := util.MessageWithEmojiPrefix("✅", fmt.Sprintf("%s added to emulator deployments", pending.contractName))
di.logs.stateUpdates = append(di.logs.stateUpdates, msg)
}
if pending.needsAlias && setupAliases {
err := di.updateDependencyAlias(pending.contractName, pending.networkName)
if err != nil {
di.Logger.Error(fmt.Sprintf("Error updating alias: %v", err))
return err
}
msg := util.MessageWithEmojiPrefix("✅", fmt.Sprintf("Alias added for %s on %s", pending.contractName, pending.networkName))
di.logs.stateUpdates = append(di.logs.stateUpdates, msg)
}
}
// Clear pending prompts after processing
di.pendingPrompts = make([]pendingPrompt, 0)
return nil
}
// GetInstallCount returns the number of dependencies installed
func (di *DependencyInstaller) GetInstallCount() int {
return di.installCount
}