Writing smart contracts using Ethereum

January 7, 2019 0 5
Share
Writing smart contracts using Ethereum

In my previous blog, I had discussed about 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 which 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 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 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), 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:

Ethereum console

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: '0x6060604052341561000c57fe5b5b6100cd604060405190810160405280600581526020017f4861727368000000000000000000000000000000000000000000000000000000815250604060405190810160405280600a81526020017f43616c69666f726e696100000000000000000000000000000000000000000000815250604060405190810160405280600381526020017f55534100000000000000000000000000000000000000000000000000000000008152506102536401000000000261039f176401000000009004565b61018d604060405190810160405280600381526020017f52616a0000000000000000000000000000000000000000000000000000000000815250604060405190810160405280600681526020017f4c6f6e646f6e0000000000000000000000000000000000000000000000000000815250604060405190810160405280600281526020017f554b0000000000000000000000000000000000000000000000000000000000008152506102536401000000000261039f176401000000009004565b61024d604060405190810160405280600581526020017f526168696c000000000000000000000000000000000000000000000000000000815250604060405190810160405280600781526020017f4b6f6c6b61746100000000000000000000000000000000000000000000000000815250604060405190810160405280600581526020017f496e6469610000000000000000000000000000000000000000000000000000008152506102536401000000000261039f176401000000009004565b5b6103ba565b604060405190810160405280838152602001828152506000846040518082805190602001908083835b6020831061029f578051825260208201915060208101905060208303925061027c565b6001836020036101000a038019825116818451168082178552505050505050905001915050908152602001604051809103902060008201518160000190805190602001906102ee929190610315565b50602082015181600101908051906020019061030b929190610315565b509050505b505050565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061035657805160ff1916838001178555610384565b82800160010185558215610384579182015b82811115610383578251825591602001919060010190610368565b5b5090506103919190610395565b5090565b6103b791905b808211156103b357600081600090555060010161039b565b5090565b90565b6107f0806103c96000396000f30060606040526000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063d0345a5914610051578063eabbf0c7146100e6578063f8923300146101be575bfe5b6100e4600480803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509190803590602001908201803590602001908080601f01602080910402602001604051908101604052809392919081815260200183838082843782019150505050505091905050610319565b005b6101bc600480803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509190803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509190803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509190505061039f565b005b34156101c657fe5b610216600480803590602001908201803590602001908080601f01602080910402602001604051908101604052809392919081815260200183838082843782019150505050505091905050610461565b604051808060200180602001838103835285818151815260200191508051906020019080838360008314610269575b80518252602083111561026957602082019150602081019050602083039250610245565b505050905090810190601f1680156102955780820380516001836020036101000a031916815260200191505b508381038252848181518152602001915080519060200190808383600083146102dd575b8051825260208311156102dd576020820191506020810190506020830392506102b9565b505050905090810190601f1680156103095780820380516001836020036101000a031916815260200191505b5094505050505060405180910390f35b806000836040518082805190602001908083835b60208310610350578051825260208201915060208101905060208303925061032d565b6001836020036101000a0380198251168184511680821785525050505050509050019150509081526020016040518091039020600001908051906020019061039992919061068b565b505b5050565b604060405190810160405280838152602001828152506000846040518082805190602001908083835b602083106103eb57805182526020820191506020810190506020830392506103c8565b6001836020036101000a0380198251168184511680821785525050505050509050019150509081526020016040518091039020600082015181600001908051906020019061043a92919061070b565b50602082015181600101908051906020019061045792919061070b565b509050505b505050565b61046961078b565b61047161078b565b6000836040518082805190602001908083835b602083106104a75780518252602082019150602081019050602083039250610484565b6001836020036101000a03801982511681845116808217855250505050505090500191505090815260200160405180910390206000016000846040518082805190602001908083835b6020831061051357805182526020820191506020810190506020830392506104f0565b6001836020036101000a0380198251168184511680821785525050505050509050019150509081526020016040518091039020600101818054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156105de5780601f106105b3576101008083540402835291602001916105de565b820191906000526020600020905b8154815290600101906020018083116105c157829003601f168201915b50505050509150808054600181600116156101000203166002900480601f01602080910402602001604051908101604052809291908181526020018280546001816001161561010002031660029004801561067a5780601f1061064f5761010080835404028352916020019161067a565b820191906000526020600020905b81548152906001019060200180831161065d57829003601f168201915b50505050509050915091505b915091565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106106cc57805160ff19168380011785556106fa565b828001600101855582156106fa579182015b828111156106f95782518255916020019190600101906106de565b5b509050610707919061079f565b5090565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061074c57805160ff191683800117855561077a565b8280016001018555821561077a579182015b8281111561077957825182559160200191906001019061075e565b5b509050610787919061079f565b5090565b602060405190810160405280600081525090565b6107c191905b808211156107bd5760008160009055506001016107a5565b5090565b905600a165627a7a72305820cedb3bdd9883cb96f5b14efbc7e76a46206974d1c2768aeabe1b3d2da739ee090029', 
     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 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!

Tags
Leave Comment

Your email address will not be published.

Stay up to date with the latest and the best from the world of automation!