Skip to content

Commit fb45828

Browse files
kushagrasharmagballet
authored andcommitted
Modified Abigen to Support Vyper (#19120)
1 parent 47c03c0 commit fb45828

8 files changed

Lines changed: 317 additions & 56 deletions

File tree

‎cmd/abigen/main.go‎

Lines changed: 27 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// Copyright 2016 The go-ethereum Authors
1+
// Copyright 2019 The go-ethereum Authors
22
// This file is part of go-ethereum.
33
//
44
// go-ethereum is free software: you can redistribute it and/or modify
@@ -37,6 +37,9 @@ var (
3737
solcFlag = flag.String("solc", "solc", "Solidity compiler to use if source builds are requested")
3838
excFlag = flag.String("exc", "", "Comma separated types to exclude from binding")
3939

40+
vyFlag = flag.String("vy", "", "Path to the Ethereum contract Vyper source to build and bind")
41+
vyperFlag = flag.String("vyper", "vyper", "Vyper compiler to use if source builds are requested")
42+
4043
pkgFlag = flag.String("pkg", "", "Package name to generate the binding into")
4144
outFlag = flag.String("out", "", "Output file for the generated binding (default = stdout)")
4245
langFlag = flag.String("lang", "go", "Destination language for the bindings (go, java, objc)")
@@ -46,11 +49,14 @@ func main() {
4649
// Parse and ensure all needed inputs are specified
4750
flag.Parse()
4851

49-
if *abiFlag == "" && *solFlag == "" {
50-
fmt.Printf("No contract ABI (--abi) or Solidity source (--sol) specified\n")
52+
if *abiFlag == "" && *solFlag == "" && *vyFlag == "" {
53+
fmt.Printf("No contract ABI (--abi), Solidity source (--sol), or Vyper source (--vy) specified\n")
54+
os.Exit(-1)
55+
} else if (*abiFlag != "" || *binFlag != "" || *typFlag != "") && (*solFlag != "" || *vyFlag != "") {
56+
fmt.Printf("Contract ABI (--abi), bytecode (--bin) and type (--type) flags are mutually exclusive with the Solidity (--sol) and Vyper (--vy) flags\n")
5157
os.Exit(-1)
52-
} else if (*abiFlag != "" || *binFlag != "" || *typFlag != "") && *solFlag != "" {
53-
fmt.Printf("Contract ABI (--abi), bytecode (--bin) and type (--type) flags are mutually exclusive with the Solidity source (--sol) flag\n")
58+
} else if *solFlag != "" && *vyFlag != "" {
59+
fmt.Printf("Solidity (--sol) and Vyper (--vy) flags are mutually exclusive\n")
5460
os.Exit(-1)
5561
}
5662
if *pkgFlag == "" {
@@ -75,7 +81,7 @@ func main() {
7581
bins []string
7682
types []string
7783
)
78-
if *solFlag != "" || (*abiFlag == "-" && *pkgFlag == "") {
84+
if *solFlag != "" || *vyFlag != "" || (*abiFlag == "-" && *pkgFlag == "") {
7985
// Generate the list of types to exclude from binding
8086
exclude := make(map[string]bool)
8187
for _, kind := range strings.Split(*excFlag, ",") {
@@ -84,13 +90,21 @@ func main() {
8490

8591
var contracts map[string]*compiler.Contract
8692
var err error
87-
if *solFlag != "" {
93+
94+
switch {
95+
case *solFlag != "":
8896
contracts, err = compiler.CompileSolidity(*solcFlag, *solFlag)
8997
if err != nil {
9098
fmt.Printf("Failed to build Solidity contract: %v\n", err)
9199
os.Exit(-1)
92100
}
93-
} else {
101+
case *vyFlag != "":
102+
contracts, err = compiler.CompileVyper(*vyperFlag, *vyFlag)
103+
if err != nil {
104+
fmt.Printf("Failed to build Vyper contract: %v\n", err)
105+
os.Exit(-1)
106+
}
107+
default:
94108
contracts, err = contractsFromStdin()
95109
if err != nil {
96110
fmt.Printf("Failed to read input ABIs from STDIN: %v\n", err)
@@ -102,7 +116,11 @@ func main() {
102116
if exclude[strings.ToLower(name)] {
103117
continue
104118
}
105-
abi, _ := json.Marshal(contract.Info.AbiDefinition) // Flatten the compiler parse
119+
abi, err := json.Marshal(contract.Info.AbiDefinition) // Flatten the compiler parse
120+
if err != nil {
121+
fmt.Printf("Failed to parse ABIs from compiler output: %v\n", err)
122+
os.Exit(-1)
123+
}
106124
abis = append(abis, string(abi))
107125
bins = append(bins, contract.Code)
108126

‎common/compiler/helpers.go‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
// Copyright 2019 The go-ethereum Authors
2+
// This file is part of the go-ethereum library.
3+
//
4+
// The go-ethereum library is free software: you can redistribute it and/or modify
5+
// it under the terms of the GNU Lesser General Public License as published by
6+
// the Free Software Foundation, either version 3 of the License, or
7+
// (at your option) any later version.
8+
//
9+
// The go-ethereum library is distributed in the hope that it will be useful,
10+
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11+
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12+
// GNU Lesser General Public License for more details.
13+
//
14+
// You should have received a copy of the GNU Lesser General Public License
15+
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
16+
17+
// Package compiler wraps the Solidity and Vyper compiler executables (solc; vyper).
18+
package compiler
19+
20+
import (
21+
"bytes"
22+
"io/ioutil"
23+
"regexp"
24+
)
25+
26+
var versionRegexp = regexp.MustCompile(`([0-9]+)\.([0-9]+)\.([0-9]+)`)
27+
28+
// Contract contains information about a compiled contract, alongside its code and runtime code.
29+
type Contract struct {
30+
Code string `json:"code"`
31+
RuntimeCode string `json:"runtime-code"`
32+
Info ContractInfo `json:"info"`
33+
}
34+
35+
// ContractInfo contains information about a compiled contract, including access
36+
// to the ABI definition, source mapping, user and developer docs, and metadata.
37+
//
38+
// Depending on the source, language version, compiler version, and compiler
39+
// options will provide information about how the contract was compiled.
40+
type ContractInfo struct {
41+
Source string `json:"source"`
42+
Language string `json:"language"`
43+
LanguageVersion string `json:"languageVersion"`
44+
CompilerVersion string `json:"compilerVersion"`
45+
CompilerOptions string `json:"compilerOptions"`
46+
SrcMap interface{} `json:"srcMap"`
47+
SrcMapRuntime string `json:"srcMapRuntime"`
48+
AbiDefinition interface{} `json:"abiDefinition"`
49+
UserDoc interface{} `json:"userDoc"`
50+
DeveloperDoc interface{} `json:"developerDoc"`
51+
Metadata string `json:"metadata"`
52+
}
53+
54+
func slurpFiles(files []string) (string, error) {
55+
var concat bytes.Buffer
56+
for _, file := range files {
57+
content, err := ioutil.ReadFile(file)
58+
if err != nil {
59+
return "", err
60+
}
61+
concat.Write(content)
62+
}
63+
return concat.String(), nil
64+
}

‎common/compiler/solidity.go‎

Lines changed: 2 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// Copyright 2015 The go-ethereum Authors
1+
// Copyright 2019 The go-ethereum Authors
22
// This file is part of the go-ethereum library.
33
//
44
// The go-ethereum library is free software: you can redistribute it and/or modify
@@ -14,49 +14,19 @@
1414
// You should have received a copy of the GNU Lesser General Public License
1515
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
1616

17-
// Package compiler wraps the Solidity compiler executable (solc).
17+
// Package compiler wraps the Solidity and Vyper compiler executables (solc; vyper).
1818
package compiler
1919

2020
import (
2121
"bytes"
2222
"encoding/json"
2323
"errors"
2424
"fmt"
25-
"io/ioutil"
2625
"os/exec"
27-
"regexp"
2826
"strconv"
2927
"strings"
3028
)
3129

32-
var versionRegexp = regexp.MustCompile(`([0-9]+)\.([0-9]+)\.([0-9]+)`)
33-
34-
// Contract contains information about a compiled contract, alongside its code and runtime code.
35-
type Contract struct {
36-
Code string `json:"code"`
37-
RuntimeCode string `json:"runtime-code"`
38-
Info ContractInfo `json:"info"`
39-
}
40-
41-
// ContractInfo contains information about a compiled contract, including access
42-
// to the ABI definition, source mapping, user and developer docs, and metadata.
43-
//
44-
// Depending on the source, language version, compiler version, and compiler
45-
// options will provide information about how the contract was compiled.
46-
type ContractInfo struct {
47-
Source string `json:"source"`
48-
Language string `json:"language"`
49-
LanguageVersion string `json:"languageVersion"`
50-
CompilerVersion string `json:"compilerVersion"`
51-
CompilerOptions string `json:"compilerOptions"`
52-
SrcMap string `json:"srcMap"`
53-
SrcMapRuntime string `json:"srcMapRuntime"`
54-
AbiDefinition interface{} `json:"abiDefinition"`
55-
UserDoc interface{} `json:"userDoc"`
56-
DeveloperDoc interface{} `json:"developerDoc"`
57-
Metadata string `json:"metadata"`
58-
}
59-
6030
// Solidity contains information about the solidity compiler.
6131
type Solidity struct {
6232
Path, Version, FullVersion string
@@ -208,15 +178,3 @@ func ParseCombinedJSON(combinedJSON []byte, source string, languageVersion strin
208178
}
209179
return contracts, nil
210180
}
211-
212-
func slurpFiles(files []string) (string, error) {
213-
var concat bytes.Buffer
214-
for _, file := range files {
215-
content, err := ioutil.ReadFile(file)
216-
if err != nil {
217-
return "", err
218-
}
219-
concat.Write(content)
220-
}
221-
return concat.String(), nil
222-
}

‎common/compiler/solidity_test.go‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// Copyright 2015 The go-ethereum Authors
1+
// Copyright 2019 The go-ethereum Authors
22
// This file is part of the go-ethereum library.
33
//
44
// The go-ethereum library is free software: you can redistribute it and/or modify
@@ -39,7 +39,7 @@ func skipWithoutSolc(t *testing.T) {
3939
}
4040
}
4141

42-
func TestCompiler(t *testing.T) {
42+
func TestSolidityCompiler(t *testing.T) {
4343
skipWithoutSolc(t)
4444

4545
contracts, err := CompileSolidityString("", testSource)
@@ -67,7 +67,7 @@ func TestCompiler(t *testing.T) {
6767
}
6868
}
6969

70-
func TestCompileError(t *testing.T) {
70+
func TestSolidityCompileError(t *testing.T) {
7171
skipWithoutSolc(t)
7272

7373
contracts, err := CompileSolidityString("", testSource[4:])

‎common/compiler/test.v.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
@public
2+
def test():
3+
hello: int128

‎common/compiler/test_bad.v.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
lic
2+
def test():
3+
hello: int128

‎common/compiler/vyper.go‎

Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,144 @@
1+
// Copyright 2019 The go-ethereum Authors
2+
// This file is part of the go-ethereum library.
3+
//
4+
// The go-ethereum library is free software: you can redistribute it and/or modify
5+
// it under the terms of the GNU Lesser General Public License as published by
6+
// the Free Software Foundation, either version 3 of the License, or
7+
// (at your option) any later version.
8+
//
9+
// The go-ethereum library is distributed in the hope that it will be useful,
10+
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11+
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12+
// GNU Lesser General Public License for more details.
13+
//
14+
// You should have received a copy of the GNU Lesser General Public License
15+
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
16+
17+
// Package compiler wraps the Solidity and Vyper compiler executables (solc; vyper).
18+
package compiler
19+
20+
import (
21+
"bytes"
22+
"encoding/json"
23+
"errors"
24+
"fmt"
25+
"os/exec"
26+
"strconv"
27+
"strings"
28+
)
29+
30+
// Vyper contains information about the vyper compiler.
31+
type Vyper struct {
32+
Path, Version, FullVersion string
33+
Major, Minor, Patch int
34+
}
35+
36+
func (s *Vyper) makeArgs() []string {
37+
p := []string{
38+
"-f", "combined_json",
39+
}
40+
return p
41+
}
42+
43+
// VyperVersion runs vyper and parses its version output.
44+
func VyperVersion(vyper string) (*Vyper, error) {
45+
if vyper == "" {
46+
vyper = "vyper"
47+
}
48+
var out bytes.Buffer
49+
cmd := exec.Command(vyper, "--version")
50+
cmd.Stdout = &out
51+
err := cmd.Run()
52+
if err != nil {
53+
return nil, err
54+
}
55+
matches := versionRegexp.FindStringSubmatch(out.String())
56+
if len(matches) != 4 {
57+
return nil, fmt.Errorf("can't parse vyper version %q", out.String())
58+
}
59+
s := &Vyper{Path: cmd.Path, FullVersion: out.String(), Version: matches[0]}
60+
if s.Major, err = strconv.Atoi(matches[1]); err != nil {
61+
return nil, err
62+
}
63+
if s.Minor, err = strconv.Atoi(matches[2]); err != nil {
64+
return nil, err
65+
}
66+
if s.Patch, err = strconv.Atoi(matches[3]); err != nil {
67+
return nil, err
68+
}
69+
return s, nil
70+
}
71+
72+
// CompileVyper compiles all given Vyper source files.
73+
func CompileVyper(vyper string, sourcefiles ...string) (map[string]*Contract, error) {
74+
if len(sourcefiles) == 0 {
75+
return nil, errors.New("vyper: no source files")
76+
}
77+
source, err := slurpFiles(sourcefiles)
78+
if err != nil {
79+
return nil, err
80+
}
81+
s, err := VyperVersion(vyper)
82+
if err != nil {
83+
return nil, err
84+
}
85+
args := s.makeArgs()
86+
cmd := exec.Command(s.Path, append(args, sourcefiles...)...)
87+
return s.run(cmd, source)
88+
}
89+
90+
func (s *Vyper) run(cmd *exec.Cmd, source string) (map[string]*Contract, error) {
91+
var stderr, stdout bytes.Buffer
92+
cmd.Stderr = &stderr
93+
cmd.Stdout = &stdout
94+
if err := cmd.Run(); err != nil {
95+
return nil, fmt.Errorf("vyper: %v\n%s", err, stderr.Bytes())
96+
}
97+
98+
return ParseVyperJSON(stdout.Bytes(), source, s.Version, s.Version, strings.Join(s.makeArgs(), " "))
99+
}
100+
101+
// ParseVyperJSON takes the direct output of a vyper --f combined_json run and
102+
// parses it into a map of string contract name to Contract structs. The
103+
// provided source, language and compiler version, and compiler options are all
104+
// passed through into the Contract structs.
105+
//
106+
// The vyper output is expected to contain ABI and source mapping.
107+
//
108+
// Returns an error if the JSON is malformed or missing data, or if the JSON
109+
// embedded within the JSON is malformed.
110+
func ParseVyperJSON(combinedJSON []byte, source string, languageVersion string, compilerVersion string, compilerOptions string) (map[string]*Contract, error) {
111+
var output map[string]interface{}
112+
if err := json.Unmarshal(combinedJSON, &output); err != nil {
113+
return nil, err
114+
}
115+
116+
// Compilation succeeded, assemble and return the contracts.
117+
contracts := make(map[string]*Contract)
118+
for name, info := range output {
119+
// Parse the individual compilation results.
120+
if name == "version" {
121+
continue
122+
}
123+
c := info.(map[string]interface{})
124+
125+
contracts[name] = &Contract{
126+
Code: c["bytecode"].(string),
127+
RuntimeCode: c["bytecode_runtime"].(string),
128+
Info: ContractInfo{
129+
Source: source,
130+
Language: "Vyper",
131+
LanguageVersion: languageVersion,
132+
CompilerVersion: compilerVersion,
133+
CompilerOptions: compilerOptions,
134+
SrcMap: c["source_map"],
135+
SrcMapRuntime: "",
136+
AbiDefinition: c["abi"],
137+
UserDoc: "",
138+
DeveloperDoc: "",
139+
Metadata: "",
140+
},
141+
}
142+
}
143+
return contracts, nil
144+
}

0 commit comments

Comments
 (0)