-
Notifications
You must be signed in to change notification settings - Fork 1
/
compiler.go
96 lines (84 loc) · 2.14 KB
/
compiler.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
package huffc
import (
"bufio"
"bytes"
"encoding/hex"
"errors"
"fmt"
"os"
"os/exec"
"strings"
)
var (
ErrCompilationFailed = errors.New("compilation failed")
codePrefix = []byte("runtime: ")
deployCodePrefix = []byte("bytecode: ")
)
// Compiler represents a compiler for Huff contracts.
type Compiler struct {
cmd string
}
// New returns a new instance of the compiler.
func New() *Compiler {
c := &Compiler{
cmd: "huffc",
}
return c
}
// Compile the given huff-file with the given options and return the compiled
// contract.
func (c *Compiler) Compile(filename string, opts *Options) (*Contract, error) {
// check if file exists
stat, err := os.Stat(filename)
if err != nil {
return nil, err
}
if stat.IsDir() {
return nil, fmt.Errorf("file %q is a directory", filename)
}
// check options
if opts == nil {
opts = new(Options)
}
opts.setDefaults()
ex := exec.Command(c.cmd,
"--bin-runtime",
"--bytecode",
"--evm-version", string(opts.EVMVersion),
filename,
)
outBuf := new(bytes.Buffer)
errBuf := new(bytes.Buffer)
ex.Stdout = outBuf
ex.Stderr = errBuf
if err := ex.Run(); err != nil {
return nil, fmt.Errorf("%w: %s", ErrCompilationFailed, strings.TrimSpace(errBuf.String()))
}
contract := new(Contract)
s := bufio.NewScanner(outBuf)
for s.Scan() {
if code, ok := bytes.CutPrefix(s.Bytes(), codePrefix); ok {
contract.Runtime = make([]byte, hex.DecodedLen(len(code)))
if _, err := hex.Decode(contract.Runtime, code); err != nil {
return nil, err
}
} else if code, ok := bytes.CutPrefix(s.Bytes(), deployCodePrefix); ok {
contract.Constructor = make([]byte, hex.DecodedLen(len(code)))
if _, err := hex.Decode(contract.Constructor, code); err != nil {
return nil, err
}
}
}
if err := s.Err(); err != nil {
return nil, err
}
if contract.Runtime == nil || contract.Constructor == nil {
return nil, fmt.Errorf("%w: unexpected error", ErrCompilationFailed)
}
return contract, nil
}
// Contract represents a compiled contract.
type Contract struct {
Runtime []byte // The runtime bytecode of the contract.
Constructor []byte // The constructor bytecode of the contract.
}