Your first Ethereum smart contract

In this tutorial we are going to write a smart contact in Solidity language that can prove file ownership.

Hi guys! So I’m starting this series of tutorials to get to grips with Ethereum and how to work with it. I highly recommend study the following docs at first(though it took me ~3 weeks it was worth it):

Ethereum documentation
Solidity documentation. Solidity is one of the languages for creating smart contracts(programs) for Ethereum blockchain.
JSON RPC API. It is a protocol for communication with your mining node(server). You may just look through the methods it provides.
Web3 JavaScript API. This is a client side API. For example you can control your node from a web browser.

Your first smart contract

We will store the hash of the file and the owner’s name to achieve proof of ownership. We will also store the hash of the file and the block timestamp to achieve proof of existence. Finally, the file integrity is achieved by storing the file hash. When you change the file its hash is also modified.

I’m going to use VS Code for writing smart contracts with this extension.

So create a new file proof.sol with the following code:

Compiling and deploying your first contract

There are 2 ways to compile your smart contract(the .sol file):
1. solc compiler
2. Remix – Solidity IDE.

We’re going to user Remix – the online Solidity IDE with the built in compile function.

So open Remix and paste the contract code there.

eth1_img1

Then click on “Start to compile” and “Details”. In the “WEB3DEPLOY” section you will find the code similar to the following:

data is the compiled version of the contract for the EVM(Ethereum Virtual Machine). The first argument to the web3.eth.contract is the ABI(Application Binary Interface) definition. The ABI contains the prototype of all contract’s methods.

Now run geth in development mode with mining enabled:

geth --dev --mine

Open another terminal window and run geth‘s interactive JavaScript console:

geth attach --ipcpath /tmp/geth.ipc

Now copy your web3 deployment code, paste in the Javascript console terminal window and hit “Enter”. You will get the transaction hash and the contract address(it may take ~15 sec). The transaction hash is…surprisingly the unique hash of the transaction. All deployed contracts have a unique contract address.

eth1_img2

Now paste the following code to create a transaction to store file’s details:

You should replace the first argument of the proofContract.at method with your contract address. We don’t provide the gas so it is automatically calculated.

Now run the following code to find file’s details:

You will see the following output:

eth1_img3

The call method is used to run a contract’s method on EVM without broadcasting a transaction.

That’s all for now. Have a good day!

Leave a Reply

Your email address will not be published. Required fields are marked *