miguelmota / ethereum-development-with-go-book

📖 A little guide book on Ethereum Development with Go (golang)

Home Page:https://goethereumbook.org

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Suggestion: Inline solidity compilation

visopsys opened this issue · comments

I find the Smart Contract Compilation & ABI could use inline solidity compilation using go instead of using external command and use abi file. Here's an example:

  • Counter.sol
pragma solidity >=0.6.0;

contract Counter {
    uint256 x;

    constructor() public {
        x = 42;
    }

    function add(uint256 y) public returns (uint256) {
        x = x + y;
        return x;
    }
}
  • test_counter.go
	import (
		"github.com/ethereum/go-ethereum/common"
		"github.com/ethereum/go-ethereum/common/compiler"
	)
..........
	counterSrc, err := filepath.Abs(PATH_TO_SOL_FILE)
	if err != nil {
		t.Fatal(err)
	}
	contracts, err := compiler.CompileSolidity("", counterSrc)
	if err != nil {
		t.Fatal(err)
	}
	contract, _ := contracts[fmt.Sprintf("%s:%s", source, "Counter")]
	code := common.Hex2Bytes(contract.Code[2:])

	nonce := uint64(0)
	tx := types.NewContractCreation(nonce, big.NewInt(0), uint64(gasLimit), gasPrice, code)
	signedTx, err := types.SignTx(tx, types.NewEIP155Signer(chainID),  privateKey)

Please node that you can cache the code if contract does not change so you don't have to compile again. This removes one additional step for beginner and make sure that our go code always works with most up-to-date solidity file.

User still needs to install solc though since the go compiler still call solc externally.

Ah, we still need the generated go file to make function call.