github.com/theQRL/go-zond@v0.1.1/cmd/abigen/main.go (about)

     1  // Copyright 2016 The go-ethereum Authors
     2  // This file is part of go-ethereum.
     3  //
     4  // go-ethereum is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU 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  // go-ethereum 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 General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU General Public License
    15  // along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package main
    18  
    19  import (
    20  	"encoding/json"
    21  	"fmt"
    22  	"io"
    23  	"os"
    24  	"regexp"
    25  	"strings"
    26  
    27  	"github.com/theQRL/go-zond/accounts/abi/bind"
    28  	"github.com/theQRL/go-zond/cmd/utils"
    29  	"github.com/theQRL/go-zond/common/compiler"
    30  	"github.com/theQRL/go-zond/crypto"
    31  	"github.com/theQRL/go-zond/internal/flags"
    32  	"github.com/theQRL/go-zond/log"
    33  	"github.com/urfave/cli/v2"
    34  )
    35  
    36  var (
    37  	// Flags needed by abigen
    38  	abiFlag = &cli.StringFlag{
    39  		Name:  "abi",
    40  		Usage: "Path to the Ethereum contract ABI json to bind, - for STDIN",
    41  	}
    42  	binFlag = &cli.StringFlag{
    43  		Name:  "bin",
    44  		Usage: "Path to the Ethereum contract bytecode (generate deploy method)",
    45  	}
    46  	typeFlag = &cli.StringFlag{
    47  		Name:  "type",
    48  		Usage: "Struct name for the binding (default = package name)",
    49  	}
    50  	jsonFlag = &cli.StringFlag{
    51  		Name:  "combined-json",
    52  		Usage: "Path to the combined-json file generated by compiler, - for STDIN",
    53  	}
    54  	excFlag = &cli.StringFlag{
    55  		Name:  "exc",
    56  		Usage: "Comma separated types to exclude from binding",
    57  	}
    58  	pkgFlag = &cli.StringFlag{
    59  		Name:  "pkg",
    60  		Usage: "Package name to generate the binding into",
    61  	}
    62  	outFlag = &cli.StringFlag{
    63  		Name:  "out",
    64  		Usage: "Output file for the generated binding (default = stdout)",
    65  	}
    66  	langFlag = &cli.StringFlag{
    67  		Name:  "lang",
    68  		Usage: "Destination language for the bindings (go)",
    69  		Value: "go",
    70  	}
    71  	aliasFlag = &cli.StringFlag{
    72  		Name:  "alias",
    73  		Usage: "Comma separated aliases for function and event renaming, e.g. original1=alias1, original2=alias2",
    74  	}
    75  )
    76  
    77  var app = flags.NewApp("Ethereum ABI wrapper code generator")
    78  
    79  func init() {
    80  	app.Name = "abigen"
    81  	app.Flags = []cli.Flag{
    82  		abiFlag,
    83  		binFlag,
    84  		typeFlag,
    85  		jsonFlag,
    86  		excFlag,
    87  		pkgFlag,
    88  		outFlag,
    89  		langFlag,
    90  		aliasFlag,
    91  	}
    92  	app.Action = abigen
    93  }
    94  
    95  func abigen(c *cli.Context) error {
    96  	utils.CheckExclusive(c, abiFlag, jsonFlag) // Only one source can be selected.
    97  
    98  	if c.String(pkgFlag.Name) == "" {
    99  		utils.Fatalf("No destination package specified (--pkg)")
   100  	}
   101  	var lang bind.Lang
   102  	switch c.String(langFlag.Name) {
   103  	case "go":
   104  		lang = bind.LangGo
   105  	default:
   106  		utils.Fatalf("Unsupported destination language \"%s\" (--lang)", c.String(langFlag.Name))
   107  	}
   108  	// If the entire solidity code was specified, build and bind based on that
   109  	var (
   110  		abis    []string
   111  		bins    []string
   112  		types   []string
   113  		sigs    []map[string]string
   114  		libs    = make(map[string]string)
   115  		aliases = make(map[string]string)
   116  	)
   117  	if c.String(abiFlag.Name) != "" {
   118  		// Load up the ABI, optional bytecode and type name from the parameters
   119  		var (
   120  			abi []byte
   121  			err error
   122  		)
   123  		input := c.String(abiFlag.Name)
   124  		if input == "-" {
   125  			abi, err = io.ReadAll(os.Stdin)
   126  		} else {
   127  			abi, err = os.ReadFile(input)
   128  		}
   129  		if err != nil {
   130  			utils.Fatalf("Failed to read input ABI: %v", err)
   131  		}
   132  		abis = append(abis, string(abi))
   133  
   134  		var bin []byte
   135  		if binFile := c.String(binFlag.Name); binFile != "" {
   136  			if bin, err = os.ReadFile(binFile); err != nil {
   137  				utils.Fatalf("Failed to read input bytecode: %v", err)
   138  			}
   139  			if strings.Contains(string(bin), "//") {
   140  				utils.Fatalf("Contract has additional library references, please use other mode(e.g. --combined-json) to catch library infos")
   141  			}
   142  		}
   143  		bins = append(bins, string(bin))
   144  
   145  		kind := c.String(typeFlag.Name)
   146  		if kind == "" {
   147  			kind = c.String(pkgFlag.Name)
   148  		}
   149  		types = append(types, kind)
   150  	} else {
   151  		// Generate the list of types to exclude from binding
   152  		var exclude *nameFilter
   153  		if c.IsSet(excFlag.Name) {
   154  			var err error
   155  			if exclude, err = newNameFilter(strings.Split(c.String(excFlag.Name), ",")...); err != nil {
   156  				utils.Fatalf("Failed to parse excludes: %v", err)
   157  			}
   158  		}
   159  		var contracts map[string]*compiler.Contract
   160  
   161  		if c.IsSet(jsonFlag.Name) {
   162  			var (
   163  				input      = c.String(jsonFlag.Name)
   164  				jsonOutput []byte
   165  				err        error
   166  			)
   167  			if input == "-" {
   168  				jsonOutput, err = io.ReadAll(os.Stdin)
   169  			} else {
   170  				jsonOutput, err = os.ReadFile(input)
   171  			}
   172  			if err != nil {
   173  				utils.Fatalf("Failed to read combined-json: %v", err)
   174  			}
   175  			contracts, err = compiler.ParseCombinedJSON(jsonOutput, "", "", "", "")
   176  			if err != nil {
   177  				utils.Fatalf("Failed to read contract information from json output: %v", err)
   178  			}
   179  		}
   180  		// Gather all non-excluded contract for binding
   181  		for name, contract := range contracts {
   182  			// fully qualified name is of the form <solFilePath>:<type>
   183  			nameParts := strings.Split(name, ":")
   184  			typeName := nameParts[len(nameParts)-1]
   185  			if exclude != nil && exclude.Matches(name) {
   186  				fmt.Fprintf(os.Stderr, "excluding: %v\n", name)
   187  				continue
   188  			}
   189  			abi, err := json.Marshal(contract.Info.AbiDefinition) // Flatten the compiler parse
   190  			if err != nil {
   191  				utils.Fatalf("Failed to parse ABIs from compiler output: %v", err)
   192  			}
   193  			abis = append(abis, string(abi))
   194  			bins = append(bins, contract.Code)
   195  			sigs = append(sigs, contract.Hashes)
   196  			types = append(types, typeName)
   197  
   198  			// Derive the library placeholder which is a 34 character prefix of the
   199  			// hex encoding of the keccak256 hash of the fully qualified library name.
   200  			// Note that the fully qualified library name is the path of its source
   201  			// file and the library name separated by ":".
   202  			libPattern := crypto.Keccak256Hash([]byte(name)).String()[2:36] // the first 2 chars are 0x
   203  			libs[libPattern] = typeName
   204  		}
   205  	}
   206  	// Extract all aliases from the flags
   207  	if c.IsSet(aliasFlag.Name) {
   208  		// We support multi-versions for aliasing
   209  		// e.g.
   210  		//      foo=bar,foo2=bar2
   211  		//      foo:bar,foo2:bar2
   212  		re := regexp.MustCompile(`(?:(\w+)[:=](\w+))`)
   213  		submatches := re.FindAllStringSubmatch(c.String(aliasFlag.Name), -1)
   214  		for _, match := range submatches {
   215  			aliases[match[1]] = match[2]
   216  		}
   217  	}
   218  	// Generate the contract binding
   219  	code, err := bind.Bind(types, abis, bins, sigs, c.String(pkgFlag.Name), lang, libs, aliases)
   220  	if err != nil {
   221  		utils.Fatalf("Failed to generate ABI binding: %v", err)
   222  	}
   223  	// Either flush it out to a file or display on the standard output
   224  	if !c.IsSet(outFlag.Name) {
   225  		fmt.Printf("%s\n", code)
   226  		return nil
   227  	}
   228  	if err := os.WriteFile(c.String(outFlag.Name), []byte(code), 0600); err != nil {
   229  		utils.Fatalf("Failed to write ABI binding: %v", err)
   230  	}
   231  	return nil
   232  }
   233  
   234  func main() {
   235  	log.Root().SetHandler(log.LvlFilterHandler(log.LvlInfo, log.StreamHandler(os.Stderr, log.TerminalFormat(true))))
   236  
   237  	if err := app.Run(os.Args); err != nil {
   238  		fmt.Fprintln(os.Stderr, err)
   239  		os.Exit(1)
   240  	}
   241  }