github.com/vantum/vantum@v0.0.0-20180815184342-fe37d5f7a990/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/vantum/vantum/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/vantum/vantum/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; events; and sort them alphabetically
    67  		var (
    68  			calls     = make(map[string]*tmplMethod)
    69  			transacts = make(map[string]*tmplMethod)
    70  			events    = make(map[string]*tmplEvent)
    71  		)
    72  		for _, original := range evmABI.Methods {
    73  			// Normalize the method for capital cases and non-anonymous inputs/outputs
    74  			normalized := original
    75  			normalized.Name = methodNormalizer[lang](original.Name)
    76  
    77  			normalized.Inputs = make([]abi.Argument, len(original.Inputs))
    78  			copy(normalized.Inputs, original.Inputs)
    79  			for j, input := range normalized.Inputs {
    80  				if input.Name == "" {
    81  					normalized.Inputs[j].Name = fmt.Sprintf("arg%d", j)
    82  				}
    83  			}
    84  			normalized.Outputs = make([]abi.Argument, len(original.Outputs))
    85  			copy(normalized.Outputs, original.Outputs)
    86  			for j, output := range normalized.Outputs {
    87  				if output.Name != "" {
    88  					normalized.Outputs[j].Name = capitalise(output.Name)
    89  				}
    90  			}
    91  			// Append the methods to the call or transact lists
    92  			if original.Const {
    93  				calls[original.Name] = &tmplMethod{Original: original, Normalized: normalized, Structured: structured(original.Outputs)}
    94  			} else {
    95  				transacts[original.Name] = &tmplMethod{Original: original, Normalized: normalized, Structured: structured(original.Outputs)}
    96  			}
    97  		}
    98  		for _, original := range evmABI.Events {
    99  			// Skip anonymous events as they don't support explicit filtering
   100  			if original.Anonymous {
   101  				continue
   102  			}
   103  			// Normalize the event for capital cases and non-anonymous outputs
   104  			normalized := original
   105  			normalized.Name = methodNormalizer[lang](original.Name)
   106  
   107  			normalized.Inputs = make([]abi.Argument, len(original.Inputs))
   108  			copy(normalized.Inputs, original.Inputs)
   109  			for j, input := range normalized.Inputs {
   110  				// Indexed fields are input, non-indexed ones are outputs
   111  				if input.Indexed {
   112  					if input.Name == "" {
   113  						normalized.Inputs[j].Name = fmt.Sprintf("arg%d", j)
   114  					}
   115  				}
   116  			}
   117  			// Append the event to the accumulator list
   118  			events[original.Name] = &tmplEvent{Original: original, Normalized: normalized}
   119  		}
   120  		contracts[types[i]] = &tmplContract{
   121  			Type:        capitalise(types[i]),
   122  			InputABI:    strings.Replace(strippedABI, "\"", "\\\"", -1),
   123  			InputBin:    strings.TrimSpace(bytecodes[i]),
   124  			Constructor: evmABI.Constructor,
   125  			Calls:       calls,
   126  			Transacts:   transacts,
   127  			Events:      events,
   128  		}
   129  	}
   130  	// Generate the contract template data content and render it
   131  	data := &tmplData{
   132  		Package:   pkg,
   133  		Contracts: contracts,
   134  	}
   135  	buffer := new(bytes.Buffer)
   136  
   137  	funcs := map[string]interface{}{
   138  		"bindtype":      bindType[lang],
   139  		"bindtopictype": bindTopicType[lang],
   140  		"namedtype":     namedType[lang],
   141  		"capitalise":    capitalise,
   142  		"decapitalise":  decapitalise,
   143  	}
   144  	tmpl := template.Must(template.New("").Funcs(funcs).Parse(tmplSource[lang]))
   145  	if err := tmpl.Execute(buffer, data); err != nil {
   146  		return "", err
   147  	}
   148  	// For Go bindings pass the code through goimports to clean it up and double check
   149  	if lang == LangGo {
   150  		code, err := imports.Process(".", buffer.Bytes(), nil)
   151  		if err != nil {
   152  			return "", fmt.Errorf("%v\n%s", err, buffer)
   153  		}
   154  		return string(code), nil
   155  	}
   156  	// For all others just return as is for now
   157  	return buffer.String(), nil
   158  }
   159  
   160  // bindType is a set of type binders that convert Solidity types to some supported
   161  // programming language types.
   162  var bindType = map[Lang]func(kind abi.Type) string{
   163  	LangGo:   bindTypeGo,
   164  	LangJava: bindTypeJava,
   165  }
   166  
   167  // bindTypeGo converts a Solidity type to a Go one. Since there is no clear mapping
   168  // from all Solidity types to Go ones (e.g. uint17), those that cannot be exactly
   169  // mapped will use an upscaled type (e.g. *big.Int).
   170  func bindTypeGo(kind abi.Type) string {
   171  	stringKind := kind.String()
   172  
   173  	switch {
   174  	case strings.HasPrefix(stringKind, "address"):
   175  		parts := regexp.MustCompile(`address(\[[0-9]*\])?`).FindStringSubmatch(stringKind)
   176  		if len(parts) != 2 {
   177  			return stringKind
   178  		}
   179  		return fmt.Sprintf("%scommon.Address", parts[1])
   180  
   181  	case strings.HasPrefix(stringKind, "bytes"):
   182  		parts := regexp.MustCompile(`bytes([0-9]*)(\[[0-9]*\])?`).FindStringSubmatch(stringKind)
   183  		if len(parts) != 3 {
   184  			return stringKind
   185  		}
   186  		return fmt.Sprintf("%s[%s]byte", parts[2], parts[1])
   187  
   188  	case strings.HasPrefix(stringKind, "int") || strings.HasPrefix(stringKind, "uint"):
   189  		parts := regexp.MustCompile(`(u)?int([0-9]*)(\[[0-9]*\])?`).FindStringSubmatch(stringKind)
   190  		if len(parts) != 4 {
   191  			return stringKind
   192  		}
   193  		switch parts[2] {
   194  		case "8", "16", "32", "64":
   195  			return fmt.Sprintf("%s%sint%s", parts[3], parts[1], parts[2])
   196  		}
   197  		return fmt.Sprintf("%s*big.Int", parts[3])
   198  
   199  	case strings.HasPrefix(stringKind, "bool") || strings.HasPrefix(stringKind, "string"):
   200  		parts := regexp.MustCompile(`([a-z]+)(\[[0-9]*\])?`).FindStringSubmatch(stringKind)
   201  		if len(parts) != 3 {
   202  			return stringKind
   203  		}
   204  		return fmt.Sprintf("%s%s", parts[2], parts[1])
   205  
   206  	default:
   207  		return stringKind
   208  	}
   209  }
   210  
   211  // bindTypeJava converts a Solidity type to a Java one. Since there is no clear mapping
   212  // from all Solidity types to Java ones (e.g. uint17), those that cannot be exactly
   213  // mapped will use an upscaled type (e.g. BigDecimal).
   214  func bindTypeJava(kind abi.Type) string {
   215  	stringKind := kind.String()
   216  
   217  	switch {
   218  	case strings.HasPrefix(stringKind, "address"):
   219  		parts := regexp.MustCompile(`address(\[[0-9]*\])?`).FindStringSubmatch(stringKind)
   220  		if len(parts) != 2 {
   221  			return stringKind
   222  		}
   223  		if parts[1] == "" {
   224  			return fmt.Sprintf("Address")
   225  		}
   226  		return fmt.Sprintf("Addresses")
   227  
   228  	case strings.HasPrefix(stringKind, "bytes"):
   229  		parts := regexp.MustCompile(`bytes([0-9]*)(\[[0-9]*\])?`).FindStringSubmatch(stringKind)
   230  		if len(parts) != 3 {
   231  			return stringKind
   232  		}
   233  		if parts[2] != "" {
   234  			return "byte[][]"
   235  		}
   236  		return "byte[]"
   237  
   238  	case strings.HasPrefix(stringKind, "int") || strings.HasPrefix(stringKind, "uint"):
   239  		parts := regexp.MustCompile(`(u)?int([0-9]*)(\[[0-9]*\])?`).FindStringSubmatch(stringKind)
   240  		if len(parts) != 4 {
   241  			return stringKind
   242  		}
   243  		switch parts[2] {
   244  		case "8", "16", "32", "64":
   245  			if parts[1] == "" {
   246  				if parts[3] == "" {
   247  					return fmt.Sprintf("int%s", parts[2])
   248  				}
   249  				return fmt.Sprintf("int%s[]", parts[2])
   250  			}
   251  		}
   252  		if parts[3] == "" {
   253  			return fmt.Sprintf("BigInt")
   254  		}
   255  		return fmt.Sprintf("BigInts")
   256  
   257  	case strings.HasPrefix(stringKind, "bool"):
   258  		parts := regexp.MustCompile(`bool(\[[0-9]*\])?`).FindStringSubmatch(stringKind)
   259  		if len(parts) != 2 {
   260  			return stringKind
   261  		}
   262  		if parts[1] == "" {
   263  			return fmt.Sprintf("bool")
   264  		}
   265  		return fmt.Sprintf("bool[]")
   266  
   267  	case strings.HasPrefix(stringKind, "string"):
   268  		parts := regexp.MustCompile(`string(\[[0-9]*\])?`).FindStringSubmatch(stringKind)
   269  		if len(parts) != 2 {
   270  			return stringKind
   271  		}
   272  		if parts[1] == "" {
   273  			return fmt.Sprintf("String")
   274  		}
   275  		return fmt.Sprintf("String[]")
   276  
   277  	default:
   278  		return stringKind
   279  	}
   280  }
   281  
   282  // bindTopicType is a set of type binders that convert Solidity types to some
   283  // supported programming language topic types.
   284  var bindTopicType = map[Lang]func(kind abi.Type) string{
   285  	LangGo:   bindTopicTypeGo,
   286  	LangJava: bindTopicTypeJava,
   287  }
   288  
   289  // bindTypeGo converts a Solidity topic type to a Go one. It is almost the same
   290  // funcionality as for simple types, but dynamic types get converted to hashes.
   291  func bindTopicTypeGo(kind abi.Type) string {
   292  	bound := bindTypeGo(kind)
   293  	if bound == "string" || bound == "[]byte" {
   294  		bound = "common.Hash"
   295  	}
   296  	return bound
   297  }
   298  
   299  // bindTypeGo converts a Solidity topic type to a Java one. It is almost the same
   300  // funcionality as for simple types, but dynamic types get converted to hashes.
   301  func bindTopicTypeJava(kind abi.Type) string {
   302  	bound := bindTypeJava(kind)
   303  	if bound == "String" || bound == "Bytes" {
   304  		bound = "Hash"
   305  	}
   306  	return bound
   307  }
   308  
   309  // namedType is a set of functions that transform language specific types to
   310  // named versions that my be used inside method names.
   311  var namedType = map[Lang]func(string, abi.Type) string{
   312  	LangGo:   func(string, abi.Type) string { panic("this shouldn't be needed") },
   313  	LangJava: namedTypeJava,
   314  }
   315  
   316  // namedTypeJava converts some primitive data types to named variants that can
   317  // be used as parts of method names.
   318  func namedTypeJava(javaKind string, solKind abi.Type) string {
   319  	switch javaKind {
   320  	case "byte[]":
   321  		return "Binary"
   322  	case "byte[][]":
   323  		return "Binaries"
   324  	case "string":
   325  		return "String"
   326  	case "string[]":
   327  		return "Strings"
   328  	case "bool":
   329  		return "Bool"
   330  	case "bool[]":
   331  		return "Bools"
   332  	case "BigInt":
   333  		parts := regexp.MustCompile(`(u)?int([0-9]*)(\[[0-9]*\])?`).FindStringSubmatch(solKind.String())
   334  		if len(parts) != 4 {
   335  			return javaKind
   336  		}
   337  		switch parts[2] {
   338  		case "8", "16", "32", "64":
   339  			if parts[3] == "" {
   340  				return capitalise(fmt.Sprintf("%sint%s", parts[1], parts[2]))
   341  			}
   342  			return capitalise(fmt.Sprintf("%sint%ss", parts[1], parts[2]))
   343  
   344  		default:
   345  			return javaKind
   346  		}
   347  	default:
   348  		return javaKind
   349  	}
   350  }
   351  
   352  // methodNormalizer is a name transformer that modifies Solidity method names to
   353  // conform to target language naming concentions.
   354  var methodNormalizer = map[Lang]func(string) string{
   355  	LangGo:   capitalise,
   356  	LangJava: decapitalise,
   357  }
   358  
   359  // capitalise makes the first character of a string upper case, also removing any
   360  // prefixing underscores from the variable names.
   361  func capitalise(input string) string {
   362  	for len(input) > 0 && input[0] == '_' {
   363  		input = input[1:]
   364  	}
   365  	if len(input) == 0 {
   366  		return ""
   367  	}
   368  	return strings.ToUpper(input[:1]) + input[1:]
   369  }
   370  
   371  // decapitalise makes the first character of a string lower case.
   372  func decapitalise(input string) string {
   373  	return strings.ToLower(input[:1]) + input[1:]
   374  }
   375  
   376  // structured checks whether a list of ABI data types has enough information to
   377  // operate through a proper Go struct or if flat returns are needed.
   378  func structured(args abi.Arguments) bool {
   379  	if len(args) < 2 {
   380  		return false
   381  	}
   382  	exists := make(map[string]bool)
   383  	for _, out := range args {
   384  		// If the name is anonymous, we can't organize into a struct
   385  		if out.Name == "" {
   386  			return false
   387  		}
   388  		// If the field name is empty when normalized or collides (var, Var, _var, _Var),
   389  		// we can't organize into a struct
   390  		field := capitalise(out.Name)
   391  		if field == "" || exists[field] {
   392  			return false
   393  		}
   394  		exists[field] = true
   395  	}
   396  	return true
   397  }