Compiling an ethereum smart contract
These days many developers use tools like hardhat or truffle to compile, test and deploy their smart contracts. Although these tools serve their purpose by abstracting all the ‘complexity’ of deploying a smart contract, it may also be good to know what these tools do under the hood.
As the tools automate many facets of the lifecycle of a smart contract, we will focus on just the compilation of a smart contract in todays post. Future posts will focus on other aspects as we go.
The contract under investigation
In order to compile a contract, we need to have a contract. Let’s write up a very small, simple contract:
|
|
This contract is pretty straight-foward, it takes an integer in the set
function and stores it in its assigned memory. When one wants to retrieve the
value, they can call the get
method to see to which value the the last call to
set
has set the value.
Compiling the contract
We first need to obtain the solidity compiler. For your system it may be
available as an installable package (meaning, someone bothered it enough to
create a release), but we can also use the standalone solc
static compiler.
I obtained a copy from the github release page, version v0.8.19, but any version
up until 0.9.0 should suffice (that is what we defined on line 2 of the sample
contract. solc
compiler.
Compiling is as easy as running
|
|
By default, the compiler will spit out the compiled contract on the command line:
$ ./solc-static-linux --bin numbers.sol
======= numbers.sol:Numbers =======
Binary:
608060405234801561001057600080fd5b50610150806100206000396000f3fe608
060405234801561001057600080fd5b50600436106100365760003560e01c806360
fe47b11461003b5780636d4ce63c14610057575b600080fd5b61005560048036038
1019061005091906100c3565b610075565b005b61005f61007f565b60405161006c
91906100ff565b60405180910390f35b8060008190555050565b600080549050905
65b600080fd5b6000819050919050565b6100a08161008d565b81146100ab576000
80fd5b50565b6000813590506100bd81610097565b92915050565b6000602082840
312156100d9576100d8610088565b5b60006100e7848285016100ae565b91505092
915050565b6100f98161008d565b82525050565b600060208201905061011460008
301846100f0565b9291505056fea26469706673582212203348ae7f432a616fb455
eed18f433359e2280405a0b263717374b5996e1d662164736f6c63430008130033
On the command line these numbers are not very useful, so we need to pipe the output of the compiler to a file prior to be able to test- or publish it. These numbers are called ‘bytecode’. Bytecode is the machine intruction language which tells the Ethereum Virtual Machine how to execute a contract. More on that later!