Writing smart contracts using Ethereum
In my previous blog, I discussed how you can build a simple Blockchain using Ethereum and Python on a Linux/Ubuntu box. Now that you are aware of a Blockchain using Ethereum, you may want to know about the next popular thing in the crypto space i.e. smart contracts. “What is smart contracts” has become one of the most-asked technology questions. So, let's talk more about smart contracts.
A smart contract is just an idiom used to describe a computer code that can promote and ease the exchange of money, content, property, shares, or anything of value. When implemented with Blockchain, a smart contract becomes a self-operating computer program that is automatically executed when pre-specified unique conditions are met. Since smart contracts run on Blockchain, they are executed exactly as programmed without any probability of censorship, downtime, fraud, or third-party interference.
Smart contracts can act as ‘multi-signature’ accounts so that the funds are spent only when a required percentage of people sign. Also, they can manage agreements between users whenever there is an exchange of the aforementioned things. Smart contracts provide utility to other contracts (similar to how a software library works) along with storing information about an application, such as domain registration information or membership records. So to cut it short, I have highlighted three key points regarding what is a smart contract:
- A smart contract is a computer code that acts as an agreement between two parties. They run on the blockchain, so they are stored in a public database and cannot be changed.
- The transactions that happen in a smart contract are prepared by the blockchain, which means they can be sent automatically without a third party. This means the dependency is almost zero.
- The transactions only happen when the conditions in the agreement are met. There is no third-party intervention, so there are no trust issues.
Smart contracts can be created on multiple blockchain platforms, including Ethereum and NEO. As Ethereum is the most preferred choice for developers, I will try to elaborate on Ethereum’s smart contracts execution with an example. Ethereum’s Contracts are written using Solidity language. Let’s create a smart contract called “simple” and save it in a file called simple. sol
pragma solidity ^0.4.0; contract Simple { struct Student { string city; string country; } mapping (string => Student) students; function Simple() public { createStudent("Harsh","California","USA"); createStudent("Raj","London","UK"); createStudent("Rahil","Kolkata","India"); } function createStudent(string key, string city, string country) public payable { students[key] = Student(city,country); } function changeStudentDetails(string key, string newCity) public payable { students[key].city = newCity; } function queryStudent(string key) public view returns (string, string) { return (students[key].city, students[key].country); } }
Let’s see what exactly I am trying to say in this code snippet:
- Everything is contained within a single Contract called “Simple”.
- In this smart contract, students have different types of identities to which a student record can be associated. Here, the contract for students have only 2 properties, because we want to implement changeStudentcountry, I’m going with “city” and “country” properties.
- Students are defined as a (self-explanatory) Struct comprising the aforementioned two (in this case: string) properties.
- Mapping is a data-type that always accepts any value for the key type and returns the value type. In this case, per fabStudent, I’m using a string key (name), and, our value type is an instance of the Student Struct.
- With Solidity, we can create a constructor for the Contract by specifying a function named the same as the Contract (“Simple”). Let’s call it “createStudent”.
- createStudent takes a key (name) and, in this case, only two properties, viz. ‘city’ and ‘country’. Using these values, it creates a mapping between the key and a Student Struct.
- changeStudentcountry does not check whether the key is valid, which is the “name” of the student. This assumes that every key exists and is valid.
- queryStudent returns the Student values (city, country) for any key that is given to it. If the key is invalid, e.g., “X”, then it will still return a result albeit empty (“”) strings for both properties.
Now, you will have to compile this smart contract in order to deploy it on the Blockchain. You can use below online utility to do so:
http://remix.ethereum.org/
You will be presented with a default Contract (Ballot). You can add your file using the “+” icon in the top left-hand corner, create a new file called “simple.sol” (your contract name), and paste the contents of the Simple “sol” file that I have included above.
Click “Start to compile” on the right side, although it should compile automatically. Look for the green box on the right-hand side, “browser/simple.sol: Simple”. The file is called “simple.sol”. The contract is called “Simple”.
Click the “Details” button:
The 5th box is called “WEB3DEPLOY” and it has a “copy-to-clipboard” icon. Click it.
Just paste this content as it is without any alterations to your Ethereum console. Here is how it will look like:
var simpleContract = web3.eth.contract([{"constant":false,"inputs":[{"name":"key","type":"string"},{"name":"newCity","type":"string"}],"name":"changeStudentDetails","outputs":[],"payable":true,"type":"function","stateMutability":"payable"},{"constant":false,"inputs":[{"name":"key","type":"string"},{"name":"city","type":"string"},{"name":"country","type":"string"}],"name":"createStudent","outputs":[],"payable":true,"type":"function","stateMutability":"payable"},{"constant":false,"inputs":[{"name":"key","type":"string"}],"name":"queryStudent","outputs":[{"name":"","type":"string"},{"name":"","type":"string"}],"payable":false,"type":"function","stateMutability":"nonpayable"},{"inputs":[],"payable":false,"type":"constructor","stateMutability":"nonpayable"}]); var simple = simpleContract.new( { from: web3.eth.accounts[0], data: '0x6060604052341561000c57fe5b5b6100cd604060405190810160405280600581526020017f4861727368000000000000000000000000000000000000000000000000000000', gas: '4700000' }, function (e, contract){ console.log(e, contract); if (typeof contract.address !== 'undefined') { console.log('Contract mined! address: ' + contract.address + ' transactionHash: ' + contract.transactionHash); } })
The output displayed will be something like this:
null [object Object] Undefined
Note: The smart contract isn’t deployed yet. You’ll need to start the mining process using the following command:
> miner.start() Null
After a few seconds, you will see the below message:
> null [object Object] Contract mined! address: 0x3863fd5720ac5a6f24a70310b51c58f3e9174576 transactionHash: 0x8e07fecaed26ba6402fbd401f80a59af864ebee8ed1d4a8d8028723606acb022
Congrats! Your smart contract is successfully deployed on Blockchain. Let’s play with it now.
> simple.queryStudent("Raj") ["London", "UK"] > simple.queryStudent("Harsh") ["California", "USA"] > simple.createStudent("Akhil","Delhi","India") "0xeab1a4285c0b96c7c06580cf95f29f7d326ca9942950256ff77678e2158accc8" > simple.queryStudent("Akhil") ["", ""] > simple.queryStudent("Akhil") ["", ""] > > simple.queryStudent("Akhil") ["Delhi", "India"] > simple.changeStudentDetails("Raj","Bristol") "0xbad469befb201ed92b009c64d399d48473b1c3a29a4e57a31fd217a7604bdb79" > simple.queryStudent("Raj") ["Bristol", "UK"] > miner.stop()
Now that mining is stopped, transactions can’t be committed to the Blockchain. Let’s try the command again:
> simple.changeStudentDetails("Raj","Manchester") "0xbad469befb201ed92b009c64d399d48473b1c3a29a4e57a31fd217a7604bdb79" "0xd54d35175e8d586924fe00616b89a6a34b78a4a3d8197325e342907d2040ece2" Note: Here the record is not updated. > simple.queryStudent("Raj") ["Bristol", "UK"] > simple.queryStudent("Raj") ["Bristol", "UK"] > simple.queryStudent("Raj") ["Bristol", "UK"] > simple.queryStudent("Raj") ["Bristol", "UK"]
Congratulations, your simple smart contract using Ethereum is ready.
In my next blog, I will take you deep down the oceans of smart contracts, where I will talk more about complex smart contracts. Stay tuned!