Homestead_17 – 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.

Solidity

Solidity is a language similar to JavaScript which allows you to develop contracts and compile to EVM bytecode. It is currently the flagship language of Ethereum and the most popular.

Solidity Documentation – Solidity is the flagship Ethereum high level language that is used to write contracts.

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:

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:

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:

contracts=eth.compile.solidity(globalRegistrarSrc)

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.

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.

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.

Contract metadata

In the previous sections we explained how you create a contract on the blockchain. Now we will deal with the rest of the compiler output, the contract metadata or contract info.

When interacting with a contract you did not create you might want documentation or to look at the source code. Contract authors are encouraged to make such information available by registering it on the blockchain or through a third party service, such as EtherChain. The admin API provides convenience methods to fetch this bundle for any contract that chose to register.

contract info is uploaded somewhere identifiable by a URI which is publicly accessible

anyone can find out what the URI is only knowing the contracts address

These requirements are achieved using a 2 step blockchain registry. The first step registers the contract code (hash) with a content hash in a contract called HashReg. The second step registers a url with the content hash in the UrlHint contract. These registry contracts were part of the Frontier release and have carried on into Homestead.

By using this scheme, it is sufficient to know a contract’s address to look up the url and fetch the actual contract metadata info bundle.

So if you are a conscientious contract creator, the steps are the following:

Deploy the contract itself to the blockchain

Get the contract info json file.

Deploy contract info json file to any url of your choice

Register codehash ->content hash -> url

The JS API makes this process very easy by providing helpers. Call admin.register to extract info from the contract, write out its json serialisation in the given file, calculates the content hash of the file and finally registers this content hash to the contract’s code hash. Once you deployed that file to any url, you can use admin.registerUrl to register the url with your content hash on the blockchain as well. (Note that in case a fixed content addressed model is used as document store, the url-hint is no longer necessary.)

source="contract test { function multiply(uint a) returns(uint d) { return a * 7; } }"// compile with solccontract=eth.compile.solidity(source).test// create contract objectvarMyContract=eth.contract(contract.info.abiDefinition)// extracts info from contract, save the json serialisation in the given file,contenthash=admin.saveInfo(contract.info,"~/dapps/shared/contracts/test/info.json")// send off the contract to the blockchainMyContract.new({from:primaryAccount,data:contract.code},function(error,contract){if(!error&&contract.address){// calculates the content hash and registers it with the code hash in `HashReg`// it uses address to send the transaction.// returns the content hash that we use to register a urladmin.register(primaryAccount,contract.address,contenthash)// here you deploy ~/dapps/shared/contracts/test/info.json to a urladmin.registerUrl(primaryAccount,hash,url)}});

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: