Full Stack Hello World Voting Ethereum Dapp Tutorial — Part 1
[Tutorial was last updated in January 2018]
In my previous post, I explained the high level architecture of Ethereum platform comparing it to a web application. As a developer, the best way to learn any new technology is by diving in and building toy applications. In this post, let’s build a simple ‘Hello World!’ application which is a Voting application.
The application is extremely simple, all it does is initialize a set of contestants, let anyone vote for the candidates and display the total votes received by each candidate. The goal is not to just code an application but to learn the process of compiling, deploying and interacting with it.
I have deliberately avoided using any dapp frameworks to build this application because the frameworks abstract away lot of the details and you fail to understand the internals of the system. Also, when you do use a framework, you will have more appreciation for all the heavy lifting the framework does for you!
In lot of ways, this article is a continuation of the previous post. If you are new to the world of Ethereum, I recommend reading it before continuing.
The goal of this exercise is to:
- Set up the development environment.
- Learn the process of writing a contract, compiling it and deploying it in your development environment.
- Interact with the contract on the blockchain through a nodejs console.
- Interact with the contract through a simple web page to display the vote counts and vote for candidates through the page.
The entire application set up and build was done on a fresh installation of ubuntu 16.04 xenial. I have set up and tested the application on macos as well.
This is how I would visualize this application we are going to build.
1. Setting up the development environment
Instead of developing the app against the live blockchain, we will use an in- memory blockchain (think of it as a blockchain simulator) called ganache. In Part 2 of the tutorial, we will interact with the real blockchain. Below are the steps to install ganache, web3js and start the test blockchain on a linux operating system. The exact same instructions work on macos as well. For windows, you can follow the instructions here (Thanks Prateesh!).
Note: This tutorial currently works with web3js version 0.20.2. I will update the tutorial once web3js 1.0 stable is released
Notice that the ganache-cli creates 10 test accounts to play with automatically. These accounts come preloaded with 100 (fake) ethers.
2. Simple voting contract
We are going to use the solidity programming language to write our contract. If you are familiar with object oriented programming, learning to write solidity contracts should be a breeze. We will write a contract (think of contract as a class in your favorite OOP language) called Voting with a constructor which initializes an array of candidates. We will write 2 methods, one to return the total votes a candidate has received and another method to increment vote count for a candidate.
Note: The constructor is invoked once and only once when you deploy the contract to the blockchain. Unlike in the web world where every deploy of your code overwrites the old code, deployed code in the blockchain is immutable. i.e, If you update your contract and deploy again, the old contract will still be in the blockchain untouched along with all the data stored in it, the new deployment will create a new instance of the contract.
Below is the voting contract code with inline comment explanation:
Copy the above code to a file named Voting.sol in the hello_world_voting directory. Now let’s compile the code and deploy it to ganache blockchain.
To compile the solidity code, we will first install npm module called solc
[email protected]:~/hello_world_voting$ npm install solc
We will use this library within a node console to compile our contract. Remember from the previous article, web3js is a library which lets you interact with the blockchain through RPC. We will use that library to deploy our application and interact with it.
First, run the ‘node’ command in your terminal to get in to the node console and initialize the solc and web3 objects. All the code snippets below need to be typed in the node console.
[email protected]:~/hello_world_voting$ node
> Web3 = require('web3')
> web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
To make sure web3 object is initialized and can communicate with the blockchain, let’s query all the accounts in the blockchain. You should see a result like below:
> web3.eth.accounts
['0x9c02f5c68e02390a3ab81f63341edc1ba5dbb39e', '0x7d920be073e92a590dc47e4ccea2f28db3f218cc', '0xf8a9c7c65c4d1c0c21b06c06ee5da80bd8f074a9', '0x9d8ee8c3d4f8b1e08803da274bdaff80c2204fc6', '0x26bb5d139aa7bdb1380af0e1e8f98147ef4c406a', '0x622e557aad13c36459fac83240f25ae91882127c', '0xbf8b1630d5640e272f33653e83092ce33d302fd2', '0xe37a3157cb3081ea7a96ba9f9e942c72cf7ad87b', '0x175dae81345f36775db285d368f0b1d49f61b2f8', '0xc26bda5f3370bdd46e7c84bdb909aead4d8f35f3']
To compile the contract, load the code from Voting.sol in to a string variable and compile it.
> code = fs.readFileSync('Voting.sol').toString()
> solc = require('solc')
> compiledCode = solc.compile(code)
When you compile the code successfully and print the ‘contract’ object (just type compiledCode in the node console to see the contents), there are two important fields you will notice which are important to understand:
- compiledCode.contracts[‘:Voting’].bytecode: This is the bytecode you get when the source code in Voting.sol is compiled. This is the code which will be deployed to the blockchain.
- compiledCode.contracts[‘:Voting’].interface: This is an interface or template of the contract (called abi) which tells the contract user what methods are available in the contract. Whenever you have to interact with the contract in the future, you will need this abi definition. You can read more details about ABI here
Let’s now deploy the contract. You first create a contract object (VotingContract below) which is used to deploy and initiate contracts in the blockchain.
> abiDefinition = JSON.parse(compiledCode.contracts[':Voting'].interface) > VotingContract = web3.eth.contract(abiDefinition) > byteCode = compiledCode.contracts[':Voting'].bytecode > deployedContract = VotingContract.new(['Rama','Nick','Jose'],{data: byteCode, from: web3.eth.accounts[0], gas: 4700000}) > deployedContract.address > contractInstance = VotingContract.at(deployedContract.address)
VotingContract.new above deploys the contract to the blockchain. The first argument is an array of candidates who are competing in the election which is pretty straightforward. Let’s see what are all in the hash in the second argument:
- data: This is the compiled bytecode which we deploy to the blockchain.
- from: The blockchain has to keep track of who deployed the contract. In this case, we are just picking the first account we get back from calling web3.eth.accounts to be the owner of this contract (who will deploy it to the blockchain). Remember that web3.eth.accounts returns an array of 10 test accounts ganache created when we started the test blockchain. In the live blockchain, you can not just use any account. You have to own that account and unlock it before transacting. You are asked for a passphrase while creating an account and that is what you use to prove your ownership of that account. Ganache by default unlocks all the 10 accounts for convenience.
- gas: It costs money to interact with the blockchain. This money goes to miners who do all the work to include your code in the blockchain. You have to specify how much money you are willing to pay to get your code included in the blockchain and you do that by setting the value of ‘gas’. The ether balance in your ‘from’ account will be used to buy gas. The price of gas is set by the network.
We have now deployed the contract and have an instance of the contract (variable contractInstance above) which we can use to interact with the contract. There are hundreds of thousands of contracts deployed on the blockchain. So, how do you identify your contract in that blockchain? Answer: deployedContract.address. When you have to interact with your contract, you need this deployed address and abi definition we talked about earlier.
3. Interact with the contract in the nodejs console
> contractInstance.totalVotesFor.call('Rama')
{ [String: '0'] s: 1, e: 0, c: [ 0 ] }
> contractInstance.voteForCandidate('Rama', {from: web3.eth.accounts[0]})
'0xdedc7ae544c3dde74ab5a0b07422c5a51b5240603d31074f5b75c0ebc786bf53'
> contractInstance.voteForCandidate('Rama', {from: web3.eth.accounts[0]})
'0x02c054d238038d68b65d55770fabfca592a5cf6590229ab91bbe7cd72da46de9'
> contractInstance.voteForCandidate('Rama', {from: web3.eth.accounts[0]})
'0x3da069a09577514f2baaa11bc3015a16edf26aad28dffbcd126bde2e71f2b76f'
> contractInstance.totalVotesFor.call('Rama').toLocaleString()
'3'
Try the above commands in your node console and you should see the vote count increment. Every time you vote for a candidate, you get back a transaction id: Example: ‘0xdedc7ae544c3dde74ab5a0b07422c5a51b5240603d31074f5b75c0ebc786bf53’ above). This transaction id is the proof that this transaction occurred and you can refer back to this at any time in the future. This transaction is immutable. This immutability is one of the big advantages of blockchains such as Ethereum. In future tutorials, we will build applications leveraging this immutability.
4. Webpage to connect to the blockchain and vote
Now that most of the work is done, all we have to do now is create a simple html file with candidate names and invoke the voting commands (which we already tried and tested in the nodejs console) in a js file. Below you can find the html code and the js file. Drop both of them in the hello_world_voting directory and open the index.html in your browser.
If you remember, we said earlier we will need the abi and the address to interact with any contract. You can see above in the index.js file how they are used to interact with the contract.
This is what you should see when you open the index.html file in your browser.
If you are able to enter the candidate name in the text box and vote and see the vote count increment, you have successfully created your first application! Congratulations! To summarize, you set up your dev environment, coded a simple contract, compiled and deployed the contract on the blockchain and interacted with it via nodejs console and then through a webpage. Now would be a good time to pat yourself on the back if you haven’t already :)
In part 2, we will deploy this contract to the public test network so the entire world can see it and vote for a candidate. We will also get more sophisticated and use the truffle framework for development (and not have to use the nodejs console to manage the entire process). Hope this tutorial helped you get a practical idea on how to get started with developing decentralized application on the Ethereum platform.
As always thanks Raine Rupert Revere for corrections/edits of this post.
If you run into issues getting the application working, feel free to DM me on twitter @zastrinlab
If you want a more challenging project, I created a course to build adecentralized eBay on Ethereum & IPFS.
If you would like to get notified when I write more tutorials, you can subscribe here.
Thanks to Raine Rupert Revere.
原文地址:https://medium.com/@mvmurthy/full-stack-hello-world-voting-ethereum-dapp-tutorial-part-1-40d2d0d807c2