github.com/hyperledger/burrow@v0.34.5-0.20220512172541-77f09336001d/cmd/burrow/commands/compile.go (about)

     1  package commands
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"path"
     7  
     8  	"github.com/hyperledger/burrow/deploy/compile"
     9  	"github.com/hyperledger/burrow/logging"
    10  	cli "github.com/jawher/mow.cli"
    11  )
    12  
    13  // Currently this just compiles to Go fixtures - it might make sense to extend it to take a text template for output
    14  // if it is convenient to expose our compiler wrappers outside of burrow deploy
    15  func Compile(output Output) func(cmd *cli.Cmd) {
    16  	return func(cmd *cli.Cmd) {
    17  		wasmOpt := cmd.BoolOpt("w wasm", false, "Use solang rather than solc")
    18  		sourceArg := cmd.StringsArg("SOURCE", nil, "Solidity source files to compile")
    19  		cmd.Spec = "[--wasm] SOURCE..."
    20  
    21  		cmd.Action = func() {
    22  			for _, solfile := range *sourceArg {
    23  				var resp *compile.Response
    24  				var err error
    25  
    26  				if *wasmOpt {
    27  					resp, err = compile.WASM(solfile, "", logging.NewNoopLogger())
    28  					if err != nil {
    29  						output.Fatalf("failed compile solidity to wasm: %v\n", err)
    30  					}
    31  				} else {
    32  					resp, err = compile.EVM(solfile, false, "", nil, logging.NewNoopLogger())
    33  					if err != nil {
    34  						output.Fatalf("failed compile solidity: %v\n", err)
    35  					}
    36  				}
    37  
    38  				if resp.Error != "" {
    39  					output.Fatalf(resp.Error)
    40  				}
    41  
    42  				if resp.Warning != "" {
    43  					output.Printf(resp.Warning)
    44  				}
    45  
    46  				f, err := os.Create(solfile + ".go")
    47  				if err != nil {
    48  					output.Fatalf("failed to create go file: %v\n", err)
    49  				}
    50  
    51  				f.WriteString(fmt.Sprintf("package %s\n\n", path.Base(path.Dir(solfile))))
    52  				f.WriteString("import hex \"github.com/tmthrgd/go-hex\"\n\n")
    53  
    54  				for _, c := range resp.Objects {
    55  					code := c.Contract.Evm.Bytecode.Object
    56  					if code == "" {
    57  						code = c.Contract.EWasm.Wasm
    58  					}
    59  					f.WriteString(fmt.Sprintf("var Bytecode_%s = hex.MustDecodeString(\"%s\")\n",
    60  						c.Objectname, code))
    61  					if c.Contract.Evm.DeployedBytecode.Object != "" {
    62  						f.WriteString(fmt.Sprintf("var DeployedBytecode_%s = hex.MustDecodeString(\"%s\")\n",
    63  							c.Objectname, c.Contract.Evm.DeployedBytecode.Object))
    64  					}
    65  					f.WriteString(fmt.Sprintf("var Abi_%s = []byte(`%s`)\n",
    66  						c.Objectname, c.Contract.Abi))
    67  				}
    68  			}
    69  		}
    70  	}
    71  }