Recipe ID: hsts-r37
We offer blockchain introduction, Hyperledger for system admin, Ethereum, Solidity, Corda R3, Hyperledger for developers, blockchain cybersecurity and more classes in self-paced video format starting at $60. Click here to learn more and register. For complete self-paced blockchain training, visit our Complete Blockchain Development Training page.
The latest version of this tutorial along with all updated source codes is available via the below link:
Ethereum is a general-purpose blockchain that is more suited to describing business logic, through advanced scripts, also known as smart contracts. Ethereum was designed with a broader vision, as a decentralized or world computer that attempts to marry the power of the blockchain, as a trust machine, with a Turing-complete contract engine. Although Ethereum borrows many ideas that were initially introduced by bitcoin, there are many divergences between the two.
The Ethereum virtual machine and smart contracts are key elements of Ethereum, and constitute its main attraction. In Ethereum, smart contracts represent a piece of code written in a high-level language (Solidity, LLL, Viper) and stored as bytecode in the blockchain, in order to run reliably in a stack-based virtual machine (Ethereum Virtual Machine), in each node, once invoked. The interactions with smart contract functions happen through transactions on the blockchain network, with their payloads being executed in the Ethereum virtual machine, and the shared blockchain state being updated accordingly.
For those who are not familiar with blockchain technology reading History and Evolution of Blockchain Technology from Bitcoin article is strongly recommended. Also, if you wish to learn and practice Hyperledger blockchain development, visit Comprehensive Hyperledger Training Tutorials page to get the outline of our Hyperledger tutorial articles.
We have written two sets of tutorials to explore Ethereum and Solidity programming in depth. First set covers the following nine recipes:
In short, you learn about how to set up and configure Ethereum and develop blockchain applications using Solidity programming language. We explore its key components, including smart contracts and Web3.JS API via an Auction Decentralized Application (DApp) step-by-step.
In second set, we will discuss more advance topics in Ethereum blockchain development and solidity while building a Tontine DApp game step-by-step. Specifically, we cover Truffle and Drizzle. For instance, we show you how a tool such as Truffle can be an assistant in building, testing, debugging, and deploying DApps. In summary, we are going to cover four main topics:
The 2nd set consists of 8 recipes as follows:
IMPORTANT: Understanding and completing the first set of recipes are required prior to working on second set of recipes.
At this level, you should have already deployed your contract on one of the deployment environments presented beforehand. To try what we have built so far, follow these instructions:
To start interacting with this DApp, the easiest method is to use MetaMask connected to Ganache. In this case, we'll need to import some of the accounts created by Ganache into MetaMask. To do that, we copy the private key from the Ganache interface and in MetaMask, we import the corresponding accounts by following the instructions presented in the official documentation (https://metamask.zendesk.com/hc/en-us/articles/360015489351-Importing-Accounts) or if you're using the new UI (https://metamask.zendesk.com/hc/en-us/articles/360015489331-Importing-an-Account-New-UI-). Once the accounts have been imported, write your bid amount in the bid input and press the Bid! button. MetaMask will prompt you to accept this transaction and let you know the fee you have to pay. To make it competitive, change the bidder account in MetaMask and make a new bid. Each time a new bid is accepted, the auction details board on the right will be updated.
One of good signs of good Solidity code is the cheap cost of its operations, thus in your contract you should optimize your code cost as much as possible.
As we stated in the introduction, Ethereum is a "paying" network and you're invoiced in gas. We learned earlier that gas has multiple metrics associated with it:
The idea behind the gas system is to have a dedicated unit to quantify transaction or computation cost on the Ethereum network. This fueling system is used to incentivize miners and to avoid denial of service attacks through malicious scripts that run forever. If the smart contract cannot complete before running out of ether, it is halted at that point.
In general, gas is consumed by a contract in two situations: Contract deployment
Contract execution through transactions
Higher-level languages such as Solidity compile down to EVM bytecode, translating the contract code into a list of smallest units of computation, called opcodes. These include operations such as ADD (addition operation), SLOAD (load word from storage), and CREATE (create a new account with associated code). The gas cost for each opcode can be found in the yellow paper, and is also listed at https://github.com/bellaj/evm-opcode-gas-costs. The total cost for a given instruction is the sum of the executed corresponding opcodes.
The Ethereum yellow paper defines approximately 130 opcodes. Each of these opcodes has an associated fixed gas price, with some opcodes costing more gas than others. For example, ADD uses three gas units while MUL (multiply two integers) uses five gas,
hence MUL is more complex than ADD. Knowing these costs mean that you can optimize your code by avoiding expensive operations (opcodes).
To deploy the contract, you have to pay for adding bytecode (the runtime bytecode stripped of initialization data) to the blockchain at a cost of 200 gas/byte, plus a fee of 32,000 gas for creating the contract account (create opcode), as indicated in the Ethereum yellow paper. In our case, the contract deployment costs approximately 1,054,247 gas units, and with a gas price of 2 gwei (1 ether = 1000000000 gwei), it will cost a total of 0.002108494 ether.
To reduce your cost, at this level, you'll need to optimize the code size and get rid of useless code and state variables.
You can use Remix connected to the testnet to get an estimation cost of each function call. The following table presents the cost of the main methods defined in the auction contract according to Remix:
A basic transaction (simple transfer of ETH) has a minimum gas requirement of 21,000 gas. Consequently, if you are just transferring funds and not interacting with a contract, your transaction takes 21,000 gas. If you are interacting with a contract, your transaction takes 21,000 gas, plus any gas associated with the executed method.
The selfdestruct() function has an interesting feature as it enables us to reduce the cost of the destruction transaction. It's based on the SUICIDE opcode, which uses negative gas because the operation frees up space on the blockchain by clearing all of the contract's state data. This negative gas is deducted from the total gas cost of the transaction, therefore reducing your gas cost. In our case, this method costs 14,211 gas, less than a normal transfer (which costs 21,000 gas):
The opcode gas prices give us an idea about which operations to use with moderation. For instance, reading from storage costs 200 gas per SLOAD instruction, and writing to storage SSTORE costs 5,000 gas, but reading from the EVM's memory and writing to it costs only 3 gas. Therefore, it's preferable to avoid extensive reading/writing operations from and into storage but instead use the memory.
The cost also depends on data size, with the fee being 20,000 gas to store a 256-bit word. For example, a kilobyte (8,000 bits) costs 640k gas, and with a gas price of 18 Gwei, you'll have to pay 11,520,000 Gwei (0.01152 Ether), or about 6.8659 USD (at 595.997$ per ether), making Ethereum an expensive storage infrastructure. Another bottleneck of storing data is the current block gas limit of approximately 8,000,000 gas/block (https://ethstats.net/). At this cap of gas per block, it would take over 80 blocks to write 1 MB of data to the blockchain, and that is assuming you can manage to reserve all of the gas per block and that there are no other operations required!
The following is some optimization advice related to data storage:
For a better design in our example, we can use an off-chain environment to store the car or user details, and only keep in the contract a referencing URL. In general, it's wise to find the balance between using on-chain and off-chain environments, while still leveraging the decentralized capabilities of the blockchain.
We end this recipe with some recommendations and best practices you can adopt while you write your smart contracts:
Hopefully, throughout first set of recipes, you were able to develop an understanding of the fundamentals of DApps and smart contract development. We covered, in a simplified way, the basics of Solidity and web3.js and how to build and deploy a simple full DApp.
While we have created a working DApp, it's by no means the final word in smart contract security and structural optimization. You'll still need to define functions to transfer ownership and open a bid, and add over- and underflow protection measures, just to name a few.
In the next round of recipes, we will take the learning process a step further, covering new concepts in Ethereum and digging deeper into Solidity's advanced features, such as optimization, debugging, and security.
To conclude this recipe, we like to recommend our Learn Hands-on Blockchain Ethereum Development & Get Certified in 30 Hrs, and Become Blockchain Certified Security Architect in 30 hours courses to those interested in pursuing a blockchain development career. This recipe is written by Brian Wu who is our senior Blockchain instructor in Washington DC. His Blockchain By Example book is highly recommended for learning more about blockchain development.
Hands-on Node.JS, MongoDB and Express.js Training
Learn Hands-on Blockchain Ethereum Development & Get Certified in 30 Hrs
Learn Blockchain Hyperledger Development & Get Certified in 30 Hrs
Become Blockchain Certified Security Architect in 30 hours
Blockchain Certified Solution Architect in 30 hours
Introduction to Python Programming
Object Oriented Programming with UML
We provide private tutoring classes online and offline (at our DC site or your preferred location) with custom curriculum for almost all of our classes for $50 per hour online or $75 per hour in DC. Give us a call or submit our private tutoring registration form to discuss your needs.