Skip to content

Commit 178da7c

Browse files
committed
mobile: initial wrappers for mobile support
1 parent d89ea3e commit 178da7c

33 files changed

Lines changed: 2594 additions & 33 deletions

‎.travis.yml‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,21 @@ matrix:
6262
- go run build/ci.go install
6363
- go run build/ci.go archive -type tar -signer OSX_SIGNING_KEY -upload gethstore/builds
6464

65+
# This builder does the mobile builds (and nothing else)
66+
- os: osx
67+
go: 1.7
68+
script:
69+
- brew update
70+
- brew install android-sdk
71+
- export ANDROID_HOME=/usr/local/opt/android-sdk
72+
- echo "y" | android update sdk --no-ui --filter platform
73+
- go get github.com/tools/godep
74+
- godep restore
75+
- go get golang.org/x/mobile/cmd/gomobile
76+
- gomobile init
77+
- gomobile bind --target=android --javapkg=org.ethereum -v github.com/ethereum/go-ethereum/mobile
78+
- gomobile bind --target=ios --tags=ios -v github.com/ethereum/go-ethereum/mobile
79+
6580
install:
6681
- go get golang.org/x/tools/cmd/cover
6782
script:

‎accounts/abi/bind/bind.go‎

Lines changed: 153 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -32,11 +32,20 @@ import (
3232
"golang.org/x/tools/imports"
3333
)
3434

35+
// Lang is a target programming language selector to generate bindings for.
36+
type Lang int
37+
38+
const (
39+
LangGo Lang = iota
40+
LangJava
41+
LangObjC
42+
)
43+
3544
// Bind generates a Go wrapper around a contract ABI. This wrapper isn't meant
3645
// to be used as is in client code, but rather as an intermediate struct which
3746
// enforces compile time type safety and naming convention opposed to having to
3847
// manually maintain hard coded strings that break on runtime.
39-
func Bind(types []string, abis []string, bytecodes []string, pkg string) (string, error) {
48+
func Bind(types []string, abis []string, bytecodes []string, pkg string, lang Lang) (string, error) {
4049
// Process each individual contract requested binding
4150
contracts := make(map[string]*tmplContract)
4251

@@ -62,7 +71,7 @@ func Bind(types []string, abis []string, bytecodes []string, pkg string) (string
6271
for _, original := range evmABI.Methods {
6372
// Normalize the method for capital cases and non-anonymous inputs/outputs
6473
normalized := original
65-
normalized.Name = capitalise(original.Name)
74+
normalized.Name = methodNormalizer[lang](original.Name)
6675

6776
normalized.Inputs = make([]abi.Argument, len(original.Inputs))
6877
copy(normalized.Inputs, original.Inputs)
@@ -78,7 +87,7 @@ func Bind(types []string, abis []string, bytecodes []string, pkg string) (string
7887
normalized.Outputs[j].Name = capitalise(output.Name)
7988
}
8089
}
81-
// Append the methos to the call or transact lists
90+
// Append the methods to the call or transact lists
8291
if original.Const {
8392
calls[original.Name] = &tmplMethod{Original: original, Normalized: normalized, Structured: structured(original)}
8493
} else {
@@ -87,7 +96,7 @@ func Bind(types []string, abis []string, bytecodes []string, pkg string) (string
8796
}
8897
contracts[types[i]] = &tmplContract{
8998
Type: capitalise(types[i]),
90-
InputABI: strippedABI,
99+
InputABI: strings.Replace(strippedABI, "\"", "\\\"", -1),
91100
InputBin: strings.TrimSpace(bytecodes[i]),
92101
Constructor: evmABI.Constructor,
93102
Calls: calls,
@@ -102,9 +111,12 @@ func Bind(types []string, abis []string, bytecodes []string, pkg string) (string
102111
buffer := new(bytes.Buffer)
103112

104113
funcs := map[string]interface{}{
105-
"bindtype": bindType,
114+
"bindtype": bindType[lang],
115+
"namedtype": namedType[lang],
116+
"capitalise": capitalise,
117+
"decapitalise": decapitalise,
106118
}
107-
tmpl := template.Must(template.New("").Funcs(funcs).Parse(tmplSource))
119+
tmpl := template.Must(template.New("").Funcs(funcs).Parse(tmplSource[lang]))
108120
if err := tmpl.Execute(buffer, data); err != nil {
109121
return "", err
110122
}
@@ -116,10 +128,17 @@ func Bind(types []string, abis []string, bytecodes []string, pkg string) (string
116128
return string(code), nil
117129
}
118130

119-
// bindType converts a Solidity type to a Go one. Since there is no clear mapping
131+
// bindType is a set of type binders that convert Solidity types to some supported
132+
// programming language.
133+
var bindType = map[Lang]func(kind abi.Type) string{
134+
LangGo: bindTypeGo,
135+
LangJava: bindTypeJava,
136+
}
137+
138+
// bindTypeGo converts a Solidity type to a Go one. Since there is no clear mapping
120139
// from all Solidity types to Go ones (e.g. uint17), those that cannot be exactly
121140
// mapped will use an upscaled type (e.g. *big.Int).
122-
func bindType(kind abi.Type) string {
141+
func bindTypeGo(kind abi.Type) string {
123142
stringKind := kind.String()
124143

125144
switch {
@@ -160,11 +179,137 @@ func bindType(kind abi.Type) string {
160179
}
161180
}
162181

182+
// bindTypeJava converts a Solidity type to a Java one. Since there is no clear mapping
183+
// from all Solidity types to Java ones (e.g. uint17), those that cannot be exactly
184+
// mapped will use an upscaled type (e.g. BigDecimal).
185+
func bindTypeJava(kind abi.Type) string {
186+
stringKind := kind.String()
187+
188+
switch {
189+
case strings.HasPrefix(stringKind, "address"):
190+
parts := regexp.MustCompile("address(\\[[0-9]*\\])?").FindStringSubmatch(stringKind)
191+
if len(parts) != 2 {
192+
return stringKind
193+
}
194+
if parts[1] == "" {
195+
return fmt.Sprintf("Address")
196+
}
197+
return fmt.Sprintf("Addresses")
198+
199+
case strings.HasPrefix(stringKind, "bytes"):
200+
parts := regexp.MustCompile("bytes([0-9]*)(\\[[0-9]*\\])?").FindStringSubmatch(stringKind)
201+
if len(parts) != 3 {
202+
return stringKind
203+
}
204+
if parts[2] != "" {
205+
return "byte[][]"
206+
}
207+
return "byte[]"
208+
209+
case strings.HasPrefix(stringKind, "int") || strings.HasPrefix(stringKind, "uint"):
210+
parts := regexp.MustCompile("(u)?int([0-9]*)(\\[[0-9]*\\])?").FindStringSubmatch(stringKind)
211+
if len(parts) != 4 {
212+
return stringKind
213+
}
214+
switch parts[2] {
215+
case "8", "16", "32", "64":
216+
if parts[1] == "" {
217+
if parts[3] == "" {
218+
return fmt.Sprintf("int%s", parts[2])
219+
}
220+
return fmt.Sprintf("int%s[]", parts[2])
221+
}
222+
}
223+
if parts[3] == "" {
224+
return fmt.Sprintf("BigInt")
225+
}
226+
return fmt.Sprintf("BigInts")
227+
228+
case strings.HasPrefix(stringKind, "bool"):
229+
parts := regexp.MustCompile("bool(\\[[0-9]*\\])?").FindStringSubmatch(stringKind)
230+
if len(parts) != 2 {
231+
return stringKind
232+
}
233+
if parts[1] == "" {
234+
return fmt.Sprintf("bool")
235+
}
236+
return fmt.Sprintf("bool[]")
237+
238+
case strings.HasPrefix(stringKind, "string"):
239+
parts := regexp.MustCompile("string(\\[[0-9]*\\])?").FindStringSubmatch(stringKind)
240+
if len(parts) != 2 {
241+
return stringKind
242+
}
243+
if parts[1] == "" {
244+
return fmt.Sprintf("String")
245+
}
246+
return fmt.Sprintf("String[]")
247+
248+
default:
249+
return stringKind
250+
}
251+
}
252+
253+
// namedType is a set of functions that transform language specific types to
254+
// named versions that my be used inside method names.
255+
var namedType = map[Lang]func(string, abi.Type) string{
256+
LangGo: func(string, abi.Type) string { panic("this shouldn't be needed") },
257+
LangJava: namedTypeJava,
258+
}
259+
260+
// namedTypeJava converts some primitive data types to named variants that can
261+
// be used as parts of method names.
262+
func namedTypeJava(javaKind string, solKind abi.Type) string {
263+
switch javaKind {
264+
case "byte[]":
265+
return "Binary"
266+
case "byte[][]":
267+
return "Binaries"
268+
case "string":
269+
return "String"
270+
case "string[]":
271+
return "Strings"
272+
case "bool":
273+
return "Bool"
274+
case "bool[]":
275+
return "Bools"
276+
case "BigInt":
277+
parts := regexp.MustCompile("(u)?int([0-9]*)(\\[[0-9]*\\])?").FindStringSubmatch(solKind.String())
278+
if len(parts) != 4 {
279+
return javaKind
280+
}
281+
switch parts[2] {
282+
case "8", "16", "32", "64":
283+
if parts[3] == "" {
284+
return capitalise(fmt.Sprintf("%sint%s", parts[1], parts[2]))
285+
}
286+
return capitalise(fmt.Sprintf("%sint%ss", parts[1], parts[2]))
287+
288+
default:
289+
return javaKind
290+
}
291+
default:
292+
return javaKind
293+
}
294+
}
295+
296+
// methodNormalizer is a name transformer that modifies Solidity method names to
297+
// conform to target language naming concentions.
298+
var methodNormalizer = map[Lang]func(string) string{
299+
LangGo: capitalise,
300+
LangJava: decapitalise,
301+
}
302+
163303
// capitalise makes the first character of a string upper case.
164304
func capitalise(input string) string {
165305
return strings.ToUpper(input[:1]) + input[1:]
166306
}
167307

308+
// decapitalise makes the first character of a string lower case.
309+
func decapitalise(input string) string {
310+
return strings.ToLower(input[:1]) + input[1:]
311+
}
312+
168313
// structured checks whether a method has enough information to return a proper
169314
// Go struct ot if flat returns are needed.
170315
func structured(method abi.Method) bool {

‎accounts/abi/bind/bind_test.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -398,7 +398,7 @@ func TestBindings(t *testing.T) {
398398
// Generate the test suite for all the contracts
399399
for i, tt := range bindTests {
400400
// Generate the binding and create a Go source file in the workspace
401-
bind, err := Bind([]string{tt.name}, []string{tt.abi}, []string{tt.bytecode}, "bindtest")
401+
bind, err := Bind([]string{tt.name}, []string{tt.abi}, []string{tt.bytecode}, "bindtest", LangGo)
402402
if err != nil {
403403
t.Fatalf("test %d: failed to generate binding: %v", i, err)
404404
}

‎accounts/abi/bind/template.go‎

Lines changed: 112 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,17 +42,24 @@ type tmplMethod struct {
4242
Structured bool // Whether the returns should be accumulated into a contract
4343
}
4444

45-
// tmplSource is the Go source template use to generate the contract binding
45+
// tmplSource is language to template mapping containing all the supported
46+
// programming languages the package can generate to.
47+
var tmplSource = map[Lang]string{
48+
LangGo: tmplSourceGo,
49+
LangJava: tmplSourceJava,
50+
}
51+
52+
// tmplSourceGo is the Go source template use to generate the contract binding
4653
// based on.
47-
const tmplSource = `
54+
const tmplSourceGo = `
4855
// This file is an automatically generated Go binding. Do not modify as any
4956
// change will likely be lost upon the next re-generation!
5057
5158
package {{.Package}}
5259
5360
{{range $contract := .Contracts}}
5461
// {{.Type}}ABI is the input ABI used to generate the binding from.
55-
const {{.Type}}ABI = ` + "`" + `{{.InputABI}}` + "`" + `
62+
const {{.Type}}ABI = "{{.InputABI}}"
5663
5764
{{if .InputBin}}
5865
// {{.Type}}Bin is the compiled bytecode used for deploying new contracts.
@@ -258,3 +265,105 @@ package {{.Package}}
258265
{{end}}
259266
{{end}}
260267
`
268+
269+
// tmplSourceJava is the Java source template use to generate the contract binding
270+
// based on.
271+
const tmplSourceJava = `
272+
// This file is an automatically generated Java binding. Do not modify as any
273+
// change will likely be lost upon the next re-generation!
274+
275+
package {{.Package}};
276+
277+
import org.ethereum.geth.*;
278+
import org.ethereum.geth.internal.*;
279+
280+
{{range $contract := .Contracts}}
281+
public class {{.Type}} {
282+
// ABI is the input ABI used to generate the binding from.
283+
public final static String ABI = "{{.InputABI}}";
284+
285+
{{if .InputBin}}
286+
// Bytecode is the compiled bytecode used for deploying new contracts.
287+
public final static byte[] Bytecode = "{{.InputBin}}".getBytes();
288+
289+
// deploy deploys a new Ethereum contract, binding an instance of {{.Type}} to it.
290+
public static {{.Type}} deploy(TransactOpts auth, EthereumClient client{{range .Constructor.Inputs}}, {{bindtype .Type}} {{.Name}}{{end}}) throws Exception {
291+
Interfaces args = Geth.newInterfaces({{(len .Constructor.Inputs)}});
292+
{{range $index, $element := .Constructor.Inputs}}
293+
args.set({{$index}}, Geth.newInterface()); args.get({{$index}}).set{{namedtype (bindtype .Type) .Type}}({{.Name}});
294+
{{end}}
295+
return new {{.Type}}(Geth.deployContract(auth, ABI, Bytecode, client, args));
296+
}
297+
298+
// Internal constructor used by contract deployment.
299+
private {{.Type}}(BoundContract deployment) {
300+
this.Address = deployment.getAddress();
301+
this.Deployer = deployment.getDeployer();
302+
this.Contract = deployment;
303+
}
304+
{{end}}
305+
306+
// Ethereum address where this contract is located at.
307+
public final Address Address;
308+
309+
// Ethereum transaction in which this contract was deployed (if known!).
310+
public final Transaction Deployer;
311+
312+
// Contract instance bound to a blockchain address.
313+
private final BoundContract Contract;
314+
315+
// Creates a new instance of {{.Type}}, bound to a specific deployed contract.
316+
public {{.Type}}(Address address, EthereumClient client) throws Exception {
317+
this(Geth.bindContract(address, ABI, client));
318+
}
319+
320+
{{range .Calls}}
321+
{{if gt (len .Normalized.Outputs) 1}}
322+
// {{capitalise .Normalized.Name}}Results is the output of a call to {{.Normalized.Name}}.
323+
public class {{capitalise .Normalized.Name}}Results {
324+
{{range $index, $item := .Normalized.Outputs}}public {{bindtype .Type}} {{if ne .Name ""}}{{.Name}}{{else}}Return{{$index}}{{end}};
325+
{{end}}
326+
}
327+
{{end}}
328+
329+
// {{.Normalized.Name}} is a free data retrieval call binding the contract method 0x{{printf "%x" .Original.Id}}.
330+
//
331+
// Solidity: {{.Original.String}}
332+
public {{if gt (len .Normalized.Outputs) 1}}{{capitalise .Normalized.Name}}Results{{else}}{{range .Normalized.Outputs}}{{bindtype .Type}}{{end}}{{end}} {{.Normalized.Name}}(CallOpts opts{{range .Normalized.Inputs}}, {{bindtype .Type}} {{.Name}}{{end}}) throws Exception {
333+
Interfaces args = Geth.newInterfaces({{(len .Normalized.Inputs)}});
334+
{{range $index, $item := .Normalized.Inputs}}args.set({{$index}}, Geth.newInterface()); args.get({{$index}}).set{{namedtype (bindtype .Type) .Type}}({{.Name}});
335+
{{end}}
336+
337+
Interfaces results = Geth.newInterfaces({{(len .Normalized.Outputs)}});
338+
{{range $index, $item := .Normalized.Outputs}}Interface result{{$index}} = Geth.newInterface(); result{{$index}}.setDefault{{namedtype (bindtype .Type) .Type}}(); results.set({{$index}}, result{{$index}});
339+
{{end}}
340+
341+
if (opts == null) {
342+
opts = Geth.newCallOpts();
343+
}
344+
this.Contract.call(opts, results, "{{.Original.Name}}", args);
345+
{{if gt (len .Normalized.Outputs) 1}}
346+
{{capitalise .Normalized.Name}}Results result = new {{capitalise .Normalized.Name}}Results();
347+
{{range $index, $item := .Normalized.Outputs}}result.{{if ne .Name ""}}{{.Name}}{{else}}Return{{$index}}{{end}} = results.get({{$index}}).get{{namedtype (bindtype .Type) .Type}}();
348+
{{end}}
349+
return result;
350+
{{else}}{{range .Normalized.Outputs}}return results.get(0).get{{namedtype (bindtype .Type) .Type}}();{{end}}
351+
{{end}}
352+
}
353+
{{end}}
354+
355+
{{range .Transacts}}
356+
// {{.Normalized.Name}} is a paid mutator transaction binding the contract method 0x{{printf "%x" .Original.Id}}.
357+
//
358+
// Solidity: {{.Original.String}}
359+
public Transaction {{.Normalized.Name}}(TransactOpts opts{{range .Normalized.Inputs}}, {{bindtype .Type}} {{.Name}}{{end}}) throws Exception {
360+
Interfaces args = Geth.newInterfaces({{(len .Normalized.Inputs)}});
361+
{{range $index, $item := .Normalized.Inputs}}args.set({{$index}}, Geth.newInterface()); args.get({{$index}}).set{{namedtype (bindtype .Type) .Type}}({{.Name}});
362+
{{end}}
363+
364+
return this.Contract.transact(opts, "{{.Original.Name}}" , args);
365+
}
366+
{{end}}
367+
}
368+
{{end}}
369+
`

0 commit comments

Comments
 (0)