Contracts
Contracts
What is a contract?
A contract is a collection of code (its functions) and data (its state) that resides at a specific address on the Ethereum blockchain. Contract accounts are able to pass messages between themselves as well as doing practically Turing complete computation. Contracts live on the blockchain in a Ethereum-specific binary format called Ethereum Virtual Machine (EVM) bytecode.
Contracts are typically written in some high level language such as Solidity and then compiled into bytecode to be uploaded on the blockchain.
See also
Other languages also exist, notably Serpent and LLL, which are described further in the Ethereum high level languages section of this documentation.
Dapp development resources lists the integrated development environments, developer tools that help you develop in these languages, offering testing, and deployment support among other features.
Ethereum high level languages
Contracts live on the blockchain in an Ethereum-specific binary format (EVM bytecode) that is executed by the Ethereum Virtual Machine (EVM). However, contracts are typically written in a higher level language and then compiled using the EVM compiler into byte code to be deployed to the blockchain.
Below are the different high level languages developers can use to write smart contracts for Ethereum.
Serpent
Serpent is a language similar to Python which can be used to develop contracts and compile to EVM bytecode. It is intended to be maximally clean and simple, combining many of the efficiency benefits of a low-level language with ease-of-use in programming style, and at the same time adding special domain-specific features for contract programming. Serpent is compiled using LLL.
Mutan (deprecated)
Mutan is a statically typed, C-like language designed and developed by Jeffrey Wilcke. It is no longer maintained.
Writing a contract
No language would be complete without a Hello World program. Operating within the Ethereum environment, Solidity has no obvious way of “outputting” a string. The closest we can do is to use a log event to place a string into the blockchain:
This contract will create a log entry on the blockchain of type Print with a parameter “Hello, World!” each time it is executed.
See also
Solidity docs has more examples and guidelines to writing Solidity code.
Compiling a contract
Compilation of solidity contracts can be accomplished via a number of mechanisms.
Using the
solc
compiler via the command line.Using
web3.eth.compile.solidity
in the javascript console provided bygeth
oreth
(This still requires thesolc
compiler to be installed).
Note
More information on solc and compiling Solidity contract code can be found here.
Setting up the solidity compiler in geth
If you start up your geth
node, you can check which compilers are available.
This command returns an array of strings indicating which compilers are currently available.
Note
The solc
compiler is installed with cpp-ethereum
. Alternatively, you can build it yourself.
If your solc
executable is in a non-standard location you can specify a custom path to the solc
executable using th --solc
flag.
Alternatively, you can set this option at runtime via the console:
Compiling a simple contract
Let’s compile a simple contract source:
This contract offers a single method multiply which is called with a positive integer a
and returns a * 7
.
You are ready to compile solidity code in the geth
JS console using eth.compile.solidity():
Note
The compiler is also available via RPC and therefore via web3.js to any in-browser Ðapp connecting to geth
via RPC/IPC.
The following example shows how you interface geth
via JSON-RPC to use the compiler.
The compiler output for one source will give you contract objects each representing a single contract. The actual return value of eth.compile.solidity
is a map of contract name to contract object pairs. Since our contract’s name is test
, eth.compile.solidity(source).test
will give you the contract object for the test contract containing the following fields:code
The compiled EVM bytecodeinfo
Additional metadata output from the compilersource
The source codelanguage
The contract language (Solidity, Serpent, LLL)languageVersion
The contract language versioncompilerVersion
The solidity compiler version that was used to compile this contract.abiDefinition
The Application Binary Interface DefinitionuserDoc
The NatSpec Doc for users.developerDoc
The NatSpec Doc for developers.
The immediate structuring of the compiler output (into code
and info
) reflects the two very different paths of deployment. The compiled EVM code is sent off to the blockchain with a contract creation transaction while the rest (info) will ideally live on the decentralised cloud as publicly verifiable metadata complementing the code on the blockchain.
If your source contains multiple contracts, the output will contain an entry for each contract, the corresponding contract info object can be retrieved with the name of the contract as attribute name. You can try this by inspecting the most current GlobalRegistrar code:
Create and deploy a contract
Before you begin this section, make sure you have both an unlocked account as well as some funds.
You will now create a contract on the blockchain by sending a transaction to the empty address with the EVM code from the previous section as data.
All binary data is serialised in hexadecimal form. Hex strings always have a hex prefix 0x
.
Note
Note that arg1, arg2, ...
are the arguments for the contract constructor, in case it accepts any. If the contract does not require any constructor arguments then these arguments can be omitted.
It is worth pointing out that this step requires you to pay for execution. Your balance on the account (that you put as sender in the from
field) will be reduced according to the gas rules of the EVM once your transaction makes it into a block. After some time, your transaction should appear included in a block confirming that the state it brought about is a consensus. Your contract now lives on the blockchain.
The asynchronous way of doing the same looks like this:
Interacting with a contract
Interaction with a contract is typically done using an abstraction layer such as the eth.contract() function which returns a javascript object with all of the contract functions available as callable functions in javascript.
The standard way to describe the available functions of a contract is the ABI definition. This object is an array which describles the call signature and return values for each available contract function.
Now all the function calls specified in the ABI are made available on the contract instance. You can just call those methods on the contract instance in one of two ways.
When called using sendTransaction
the function call is executed via sending a transaction. This will cost ether to send and the call will be recorded forever on the blockchain. The return value of calls made in this manner is the hash of the transaction.
When called using call
the function is executed locally in the EVM and the return value of the function is returned with the function. Calls made in this manner are not recorded on the blockchain and thus, cannot modify the internal state of the contract. This manner of call is referred to as a constant function call. Calls made in this manner do not cost any ether.
You should use call
if you are interested only in the return value and use sendTransaction
if you only care about side effects on the state of the contract.
In the example above, there are no side effects, therefore sendTransaction
only burns gas and increases the entropy of the universe.
Testing contracts and transactions
Often you need to resort to a low level strategy of testing and debugging contracts and transactions. This section introduces some debug tools and practices you can use. In order to test contracts and transactions without real-word consequences, you best test it on a private blockchain. This can be achieved with configuring an alternative network id (select a unique integer) and/or disable peers. It is recommended practice that for testing you use an alternative data directory and ports so that you never even accidentally clash with your live running node (assuming that runs using the defaults. Starting your geth
with in VM debug mode with profiling and highest logging verbosity level is recommended:
Before you can submit any transactions, you need set up your private test chain. See Test Networks.
After you create transactions, you can force process them with the following lines:
You can check your pending transactions with:
If you submitted contract creation transaction, you can check if the desired code actually got inserted in the current blockchain:
Last updated
Was this helpful?