hardhat.go 7.31 KB
Newer Older
1 2 3 4
package hardhat

import (
	"encoding/json"
5
	"errors"
6 7 8 9 10 11
	"fmt"
	"io/fs"
	"os"
	"path/filepath"
	"strings"
	"sync"
12

13
	"github.com/ethereum-optimism/optimism/op-bindings/solc"
14 15
)

16 17 18 19 20
var (
	ErrCannotFindDeployment = errors.New("cannot find deployment")
	ErrCannotFindArtifact   = errors.New("cannot find artifact")
)

21 22 23 24 25 26 27 28 29 30 31 32 33 34
// `Hardhat` encapsulates all of the functionality required to interact
// with hardhat style artifacts.
type Hardhat struct {
	ArtifactPaths   []string
	DeploymentPaths []string

	network string

	amu sync.Mutex
	dmu sync.Mutex
	bmu sync.Mutex

	artifacts   []*Artifact
	deployments []*Deployment
35
	buildInfos  []*BuildInfo //nolint:unused
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
}

// New creates a new `Hardhat` struct and reads all of the files from
// disk so that they are cached for the end user. A network is passed
// that corresponds to the network that they deployments are associated
// with. A slice of artifact paths and deployment paths are passed
// so that a single `Hardhat` instance can operate on multiple sets
// of artifacts and deployments. The deployments paths should be
// the root of the deployments directory that contains additional
// directories for each particular network.
func New(network string, artifacts, deployments []string) (*Hardhat, error) {
	hh := &Hardhat{
		network:         network,
		ArtifactPaths:   artifacts,
		DeploymentPaths: deployments,
	}

	if err := hh.init(); err != nil {
		return nil, err
	}

	return hh, nil
}

// init is called in the constructor and will cache required files to disk.
func (h *Hardhat) init() error {
62 63 64 65 66
	h.amu.Lock()
	defer h.amu.Unlock()
	h.dmu.Lock()
	defer h.dmu.Unlock()

67 68 69 70 71 72 73 74 75 76 77 78
	if err := h.initArtifacts(); err != nil {
		return err
	}
	if err := h.initDeployments(); err != nil {
		return err
	}
	return nil
}

// initDeployments reads all of the deployment json files from disk and then
// caches the deserialized `Deployment` structs.
func (h *Hardhat) initDeployments() error {
79
	knownDeployments := make(map[string]string)
80 81
	for _, deploymentPath := range h.DeploymentPaths {
		fileSystem := os.DirFS(filepath.Join(deploymentPath, h.network))
82
		err := fs.WalkDir(fileSystem, ".", func(path string, d fs.DirEntry, err error) error {
83 84 85 86 87 88 89 90 91
			if err != nil {
				return err
			}
			if d.IsDir() {
				return nil
			}
			if strings.Contains(path, "solcInputs") {
				return nil
			}
92
			if !strings.HasSuffix(path, ".json") {
93 94
				return nil
			}
95 96

			name := filepath.Join(deploymentPath, h.network, path)
97 98 99 100 101 102 103 104 105
			file, err := os.ReadFile(name)
			if err != nil {
				return err
			}
			var deployment Deployment
			if err := json.Unmarshal(file, &deployment); err != nil {
				return err
			}

106
			deployment.Name = filepath.Base(name[:len(name)-5])
107 108 109 110 111 112 113 114
			if knownDeployments[deployment.Name] != "" {
				return fmt.Errorf(
					"discovered duplicate deployment %s. old: %s, new: %s",
					deployment.Name,
					knownDeployments[deployment.Name],
					name,
				)
			}
115
			h.deployments = append(h.deployments, &deployment)
116
			knownDeployments[deployment.Name] = name
117 118
			return nil
		})
119 120 121
		if err != nil {
			return err
		}
122 123 124 125 126 127 128 129 130
	}
	return nil
}

// initArtifacts reads all of the artifact json files from disk and then caches
// the deserialized `Artifact` structs.
func (h *Hardhat) initArtifacts() error {
	for _, artifactPath := range h.ArtifactPaths {
		fileSystem := os.DirFS(artifactPath)
131
		err := fs.WalkDir(fileSystem, ".", func(path string, d fs.DirEntry, err error) error {
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
			if err != nil {
				return err
			}
			if d.IsDir() {
				return nil
			}
			name := filepath.Join(artifactPath, path)

			if strings.Contains(name, "build-info") {
				return nil
			}
			if strings.HasSuffix(name, ".dbg.json") {
				return nil
			}
			file, err := os.ReadFile(name)
			if err != nil {
				return err
			}
			var artifact Artifact
			if err := json.Unmarshal(file, &artifact); err != nil {
				return err
			}
154

155 156 157
			h.artifacts = append(h.artifacts, &artifact)
			return nil
		})
158 159 160
		if err != nil {
			return err
		}
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
	}
	return nil
}

// GetArtifact returns the artifact that corresponds to the contract.
// This method supports just the contract name and the fully qualified
// contract name.
func (h *Hardhat) GetArtifact(name string) (*Artifact, error) {
	h.amu.Lock()
	defer h.amu.Unlock()

	if IsFullyQualifiedName(name) {
		fqn := ParseFullyQualifiedName(name)
		for _, artifact := range h.artifacts {
			contractNameMatches := artifact.ContractName == fqn.ContractName
			sourceNameMatches := artifact.SourceName == fqn.SourceName

			if contractNameMatches && sourceNameMatches {
				return artifact, nil
			}
		}
182
		return nil, fmt.Errorf("%w: %s", ErrCannotFindArtifact, name)
183 184 185 186 187 188 189 190
	}

	for _, artifact := range h.artifacts {
		if name == artifact.ContractName {
			return artifact, nil
		}
	}

191
	return nil, fmt.Errorf("%w: %s", ErrCannotFindArtifact, name)
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
}

// GetDeployment returns the deployment that corresponds to the contract.
// It does not support fully qualified contract names.
func (h *Hardhat) GetDeployment(name string) (*Deployment, error) {
	h.dmu.Lock()
	defer h.dmu.Unlock()

	fqn := ParseFullyQualifiedName(name)
	for _, deployment := range h.deployments {
		if deployment.Name == fqn.ContractName {
			return deployment, nil
		}
	}

207
	return nil, fmt.Errorf("%w: %s", ErrCannotFindDeployment, name)
208 209 210 211 212 213 214 215 216 217 218 219 220
}

// GetBuildInfo returns the build info that corresponds to the contract.
// It does not support fully qualified contract names.
func (h *Hardhat) GetBuildInfo(name string) (*BuildInfo, error) {
	h.bmu.Lock()
	defer h.bmu.Unlock()

	fqn := ParseFullyQualifiedName(name)
	buildInfos := make([]*BuildInfo, 0)

	for _, artifactPath := range h.ArtifactPaths {
		fileSystem := os.DirFS(artifactPath)
221
		err := fs.WalkDir(fileSystem, ".", func(path string, d fs.DirEntry, err error) error {
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
			if err != nil {
				return err
			}
			if d.IsDir() {
				return nil
			}
			name := filepath.Join(artifactPath, path)

			if !strings.HasSuffix(name, ".dbg.json") {
				return nil
			}

			// Remove ".dbg.json"
			target := filepath.Base(name[:len(name)-9])
			if fqn.ContractName != target {
				return nil
			}

			file, err := os.ReadFile(name)
			if err != nil {
				return err
			}
			var debugFile DebugFile
			if err := json.Unmarshal(file, &debugFile); err != nil {
				return err
			}
			relPath := filepath.Join(filepath.Dir(name), debugFile.BuildInfo)
			if err != nil {
				return err
			}
			debugPath, _ := filepath.Abs(relPath)

			buildInfoFile, err := os.ReadFile(debugPath)
			if err != nil {
				return err
			}

			var buildInfo BuildInfo
			if err := json.Unmarshal(buildInfoFile, &buildInfo); err != nil {
				return err
			}

			buildInfos = append(buildInfos, &buildInfo)

			return nil
		})
268 269 270
		if err != nil {
			return nil, err
		}
271 272 273 274 275 276 277 278 279 280 281 282
	}

	// TODO(tynes): handle multiple contracts with same name when required
	if len(buildInfos) > 1 {
		return nil, fmt.Errorf("Multiple contracts with name %s", name)
	}
	if len(buildInfos) == 0 {
		return nil, fmt.Errorf("Cannot find BuildInfo for %s", name)
	}

	return buildInfos[0], nil
}
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302

// TODO(tynes): handle fully qualified names properly
func (h *Hardhat) GetStorageLayout(name string) (*solc.StorageLayout, error) {
	fqn := ParseFullyQualifiedName(name)

	buildInfo, err := h.GetBuildInfo(name)
	if err != nil {
		return nil, err
	}

	for _, source := range buildInfo.Output.Contracts {
		for name, contract := range source {
			if name == fqn.ContractName {
				return &contract.StorageLayout, nil
			}
		}
	}

	return nil, fmt.Errorf("contract not found for %s", fqn.ContractName)
}