github.com/digdeepmining/go-atheios@v1.5.13-0.20180902133602-d5687a2e6f43/accounts/abi/bind/bind.go (about) 1 // Copyright 2016 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 bind generates Ethereum contract Go bindings. 18 // 19 // Detailed usage document and tutorial available on the go-ethereum Wiki page: 20 // https://github.com/atheioschain/go-atheios/wiki/Native-DApps:-Go-bindings-to-Ethereum-contracts 21 package bind 22 23 import ( 24 "bytes" 25 "fmt" 26 "regexp" 27 "strings" 28 "text/template" 29 "unicode" 30 31 "github.com/atheioschain/go-atheios/accounts/abi" 32 "golang.org/x/tools/imports" 33 ) 34 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 44 // Bind generates a Go wrapper around a contract ABI. This wrapper isn't meant 45 // to be used as is in client code, but rather as an intermediate struct which 46 // enforces compile time type safety and naming convention opposed to having to 47 // manually maintain hard coded strings that break on runtime. 48 func Bind(types []string, abis []string, bytecodes []string, pkg string, lang Lang) (string, error) { 49 // Process each individual contract requested binding 50 contracts := make(map[string]*tmplContract) 51 52 for i := 0; i < len(types); i++ { 53 // Parse the actual ABI to generate the binding for 54 evmABI, err := abi.JSON(strings.NewReader(abis[i])) 55 if err != nil { 56 return "", err 57 } 58 // Strip any whitespace from the JSON ABI 59 strippedABI := strings.Map(func(r rune) rune { 60 if unicode.IsSpace(r) { 61 return -1 62 } 63 return r 64 }, abis[i]) 65 66 // Extract the call and transact methods, and sort them alphabetically 67 var ( 68 calls = make(map[string]*tmplMethod) 69 transacts = make(map[string]*tmplMethod) 70 ) 71 for _, original := range evmABI.Methods { 72 // Normalize the method for capital cases and non-anonymous inputs/outputs 73 normalized := original 74 normalized.Name = methodNormalizer[lang](original.Name) 75 76 normalized.Inputs = make([]abi.Argument, len(original.Inputs)) 77 copy(normalized.Inputs, original.Inputs) 78 for j, input := range normalized.Inputs { 79 if input.Name == "" { 80 normalized.Inputs[j].Name = fmt.Sprintf("arg%d", j) 81 } 82 } 83 normalized.Outputs = make([]abi.Argument, len(original.Outputs)) 84 copy(normalized.Outputs, original.Outputs) 85 for j, output := range normalized.Outputs { 86 if output.Name != "" { 87 normalized.Outputs[j].Name = capitalise(output.Name) 88 } 89 } 90 // Append the methods to the call or transact lists 91 if original.Const { 92 calls[original.Name] = &tmplMethod{Original: original, Normalized: normalized, Structured: structured(original)} 93 } else { 94 transacts[original.Name] = &tmplMethod{Original: original, Normalized: normalized, Structured: structured(original)} 95 } 96 } 97 contracts[types[i]] = &tmplContract{ 98 Type: capitalise(types[i]), 99 InputABI: strings.Replace(strippedABI, "\"", "\\\"", -1), 100 InputBin: strings.TrimSpace(bytecodes[i]), 101 Constructor: evmABI.Constructor, 102 Calls: calls, 103 Transacts: transacts, 104 } 105 } 106 // Generate the contract template data content and render it 107 data := &tmplData{ 108 Package: pkg, 109 Contracts: contracts, 110 } 111 buffer := new(bytes.Buffer) 112 113 funcs := map[string]interface{}{ 114 "bindtype": bindType[lang], 115 "namedtype": namedType[lang], 116 "capitalise": capitalise, 117 "decapitalise": decapitalise, 118 } 119 tmpl := template.Must(template.New("").Funcs(funcs).Parse(tmplSource[lang])) 120 if err := tmpl.Execute(buffer, data); err != nil { 121 return "", err 122 } 123 // For Go bindings pass the code through goimports to clean it up and double check 124 if lang == LangGo { 125 code, err := imports.Process("", buffer.Bytes(), nil) 126 if err != nil { 127 return "", fmt.Errorf("%v\n%s", err, buffer) 128 } 129 return string(code), nil 130 } 131 // For all others just return as is for now 132 return string(buffer.Bytes()), nil 133 } 134 135 // bindType is a set of type binders that convert Solidity types to some supported 136 // programming language. 137 var bindType = map[Lang]func(kind abi.Type) string{ 138 LangGo: bindTypeGo, 139 LangJava: bindTypeJava, 140 } 141 142 // bindTypeGo converts a Solidity type to a Go one. Since there is no clear mapping 143 // from all Solidity types to Go ones (e.g. uint17), those that cannot be exactly 144 // mapped will use an upscaled type (e.g. *big.Int). 145 func bindTypeGo(kind abi.Type) string { 146 stringKind := kind.String() 147 148 switch { 149 case strings.HasPrefix(stringKind, "address"): 150 parts := regexp.MustCompile(`address(\[[0-9]*\])?`).FindStringSubmatch(stringKind) 151 if len(parts) != 2 { 152 return stringKind 153 } 154 return fmt.Sprintf("%scommon.Address", parts[1]) 155 156 case strings.HasPrefix(stringKind, "bytes"): 157 parts := regexp.MustCompile(`bytes([0-9]*)(\[[0-9]*\])?`).FindStringSubmatch(stringKind) 158 if len(parts) != 3 { 159 return stringKind 160 } 161 return fmt.Sprintf("%s[%s]byte", parts[2], parts[1]) 162 163 case strings.HasPrefix(stringKind, "int") || strings.HasPrefix(stringKind, "uint"): 164 parts := regexp.MustCompile(`(u)?int([0-9]*)(\[[0-9]*\])?`).FindStringSubmatch(stringKind) 165 if len(parts) != 4 { 166 return stringKind 167 } 168 switch parts[2] { 169 case "8", "16", "32", "64": 170 return fmt.Sprintf("%s%sint%s", parts[3], parts[1], parts[2]) 171 } 172 return fmt.Sprintf("%s*big.Int", parts[3]) 173 174 case strings.HasPrefix(stringKind, "bool") || strings.HasPrefix(stringKind, "string"): 175 parts := regexp.MustCompile(`([a-z]+)(\[[0-9]*\])?`).FindStringSubmatch(stringKind) 176 if len(parts) != 3 { 177 return stringKind 178 } 179 return fmt.Sprintf("%s%s", parts[2], parts[1]) 180 181 default: 182 return stringKind 183 } 184 } 185 186 // bindTypeJava converts a Solidity type to a Java one. Since there is no clear mapping 187 // from all Solidity types to Java ones (e.g. uint17), those that cannot be exactly 188 // mapped will use an upscaled type (e.g. BigDecimal). 189 func bindTypeJava(kind abi.Type) string { 190 stringKind := kind.String() 191 192 switch { 193 case strings.HasPrefix(stringKind, "address"): 194 parts := regexp.MustCompile(`address(\[[0-9]*\])?`).FindStringSubmatch(stringKind) 195 if len(parts) != 2 { 196 return stringKind 197 } 198 if parts[1] == "" { 199 return fmt.Sprintf("Address") 200 } 201 return fmt.Sprintf("Addresses") 202 203 case strings.HasPrefix(stringKind, "bytes"): 204 parts := regexp.MustCompile(`bytes([0-9]*)(\[[0-9]*\])?`).FindStringSubmatch(stringKind) 205 if len(parts) != 3 { 206 return stringKind 207 } 208 if parts[2] != "" { 209 return "byte[][]" 210 } 211 return "byte[]" 212 213 case strings.HasPrefix(stringKind, "int") || strings.HasPrefix(stringKind, "uint"): 214 parts := regexp.MustCompile(`(u)?int([0-9]*)(\[[0-9]*\])?`).FindStringSubmatch(stringKind) 215 if len(parts) != 4 { 216 return stringKind 217 } 218 switch parts[2] { 219 case "8", "16", "32", "64": 220 if parts[1] == "" { 221 if parts[3] == "" { 222 return fmt.Sprintf("int%s", parts[2]) 223 } 224 return fmt.Sprintf("int%s[]", parts[2]) 225 } 226 } 227 if parts[3] == "" { 228 return fmt.Sprintf("BigInt") 229 } 230 return fmt.Sprintf("BigInts") 231 232 case strings.HasPrefix(stringKind, "bool"): 233 parts := regexp.MustCompile(`bool(\[[0-9]*\])?`).FindStringSubmatch(stringKind) 234 if len(parts) != 2 { 235 return stringKind 236 } 237 if parts[1] == "" { 238 return fmt.Sprintf("bool") 239 } 240 return fmt.Sprintf("bool[]") 241 242 case strings.HasPrefix(stringKind, "string"): 243 parts := regexp.MustCompile(`string(\[[0-9]*\])?`).FindStringSubmatch(stringKind) 244 if len(parts) != 2 { 245 return stringKind 246 } 247 if parts[1] == "" { 248 return fmt.Sprintf("String") 249 } 250 return fmt.Sprintf("String[]") 251 252 default: 253 return stringKind 254 } 255 } 256 257 // namedType is a set of functions that transform language specific types to 258 // named versions that my be used inside method names. 259 var namedType = map[Lang]func(string, abi.Type) string{ 260 LangGo: func(string, abi.Type) string { panic("this shouldn't be needed") }, 261 LangJava: namedTypeJava, 262 } 263 264 // namedTypeJava converts some primitive data types to named variants that can 265 // be used as parts of method names. 266 func namedTypeJava(javaKind string, solKind abi.Type) string { 267 switch javaKind { 268 case "byte[]": 269 return "Binary" 270 case "byte[][]": 271 return "Binaries" 272 case "string": 273 return "String" 274 case "string[]": 275 return "Strings" 276 case "bool": 277 return "Bool" 278 case "bool[]": 279 return "Bools" 280 case "BigInt": 281 parts := regexp.MustCompile(`(u)?int([0-9]*)(\[[0-9]*\])?`).FindStringSubmatch(solKind.String()) 282 if len(parts) != 4 { 283 return javaKind 284 } 285 switch parts[2] { 286 case "8", "16", "32", "64": 287 if parts[3] == "" { 288 return capitalise(fmt.Sprintf("%sint%s", parts[1], parts[2])) 289 } 290 return capitalise(fmt.Sprintf("%sint%ss", parts[1], parts[2])) 291 292 default: 293 return javaKind 294 } 295 default: 296 return javaKind 297 } 298 } 299 300 // methodNormalizer is a name transformer that modifies Solidity method names to 301 // conform to target language naming concentions. 302 var methodNormalizer = map[Lang]func(string) string{ 303 LangGo: capitalise, 304 LangJava: decapitalise, 305 } 306 307 // capitalise makes the first character of a string upper case. 308 func capitalise(input string) string { 309 return strings.ToUpper(input[:1]) + input[1:] 310 } 311 312 // decapitalise makes the first character of a string lower case. 313 func decapitalise(input string) string { 314 return strings.ToLower(input[:1]) + input[1:] 315 } 316 317 // structured checks whether a method has enough information to return a proper 318 // Go struct ot if flat returns are needed. 319 func structured(method abi.Method) bool { 320 if len(method.Outputs) < 2 { 321 return false 322 } 323 for _, out := range method.Outputs { 324 if out.Name == "" { 325 return false 326 } 327 } 328 return true 329 }