devnet.go 1.36 KB
Newer Older
1 2 3 4
package config

import (
	"encoding/json"
Will Cory's avatar
Will Cory committed
5
	"errors"
Hamdi Allam's avatar
Hamdi Allam committed
6
	"fmt"
Will Cory's avatar
Will Cory committed
7
	"io/fs"
8
	"os"
Hamdi Allam's avatar
Hamdi Allam committed
9
	"path/filepath"
10 11
)

Hamdi Allam's avatar
Hamdi Allam committed
12
var DevnetPresetId = 901
13

Hamdi Allam's avatar
Hamdi Allam committed
14 15 16
func DevnetPreset() (*Preset, error) {
	cwd, err := os.Getwd()
	if err != nil {
17 18 19
		return nil, err
	}

Hamdi Allam's avatar
Hamdi Allam committed
20
	root, err := findMonorepoRoot(cwd)
21 22 23 24
	if err != nil {
		return nil, err
	}

Hamdi Allam's avatar
Hamdi Allam committed
25 26
	devnetFilepath := filepath.Join(root, ".devnet", "addresses.json")
	if _, err := os.Stat(devnetFilepath); errors.Is(err, fs.ErrNotExist) {
27 28 29
		return nil, err
	}

Hamdi Allam's avatar
Hamdi Allam committed
30
	content, err := os.ReadFile(devnetFilepath)
31 32 33
	if err != nil {
		return nil, err
	}
Hamdi Allam's avatar
Hamdi Allam committed
34 35 36 37 38 39

	var l1Contracts L1Contracts
	if err := json.Unmarshal(content, &l1Contracts); err != nil {
		return nil, err
	}

40
	return &Preset{
Hamdi Allam's avatar
Hamdi Allam committed
41 42
		Name:        "Local Devnet",
		ChainConfig: ChainConfig{Preset: DevnetPresetId, L1Contracts: l1Contracts},
43 44
	}, nil
}
Hamdi Allam's avatar
Hamdi Allam committed
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66

// findMonorepoRoot will recursively search upwards for a go.mod file.
// This depends on the structure of the monorepo having a go.mod file at the root.
func findMonorepoRoot(startDir string) (string, error) {
	dir, err := filepath.Abs(startDir)
	if err != nil {
		return "", err
	}
	for {
		modulePath := filepath.Join(dir, "go.mod")
		if _, err := os.Stat(modulePath); err == nil {
			return dir, nil
		}
		parentDir := filepath.Dir(dir)
		// Check if we reached the filesystem root
		if parentDir == dir {
			break
		}
		dir = parentDir
	}
	return "", fmt.Errorf("monorepo root not found")
}