Building a Dapp on Ethereum with VueJs and Solidity
Ethereum is a very good technology to get started with Blockchain. It is open-source and offers a ton of features to get started with such as smart contracts for writing the business logic, swarm for decentralized file storage, Ethereum Virtual Machine (EVM) as an underlying software where the smart contracts are executed. Ethereum offers a publicly available distributed ledger aka public blockchain. However, it does also offer a private blockchain (refer Quorum for more information).
So it's really interesting and fun to work with Ethereum as a backend service for your web application. You start to understand how the decentralized phenomena and the concept of immutability work hand in hand.
As of now, I’ll be guiding you about how to develop a simple smart contract using Solidity programming language and then using VueJs as a front-end service. This is going to be a fairly simple Solidity contract of a lottery game. The contract has been inspired by Stephen Grider ‘s lottery project. This is a simple game wherein the manager (user) creates a lottery instance and then other players can bet their money (in this case ethers) in the pool and then the manager of the instance can randomly pick the winner of the lottery. After that, the entire pool amount is then transferred to the winner’s wallet. A fairly simple game with no complexities, since our main objective here, is to understand how our frontend communicates with the smart contract.
Before starting we’ll be needing few tools.
- Metamask Extention (https://metamask.io/)
- Remix IDE (remix.ethereum)
- Infura Account (Rinkeby Test Network)
The very first step is to write the Smart Contract. I’ll recommend writing the contract on the Remix IDE since it has become a whole lot better than it was with many useful features. You can compile the contract there itself as well as deploy it from the Web IDE. The console will show you the necessary details of the contract being deployed. Before writing the contract it is very necessary to know about how our contract behaves once it is compiled and deployed.
pragma solidity ^0.4.16;contract Lottery{
address public manager;
address public lastWinner;
address[] public players;
function Lottery() public {
manager = msg.sender;
}
function enter() public payable {
require(msg.value > .01 ether);
players.push(msg.sender);
}
function random() public view returns(uint256) {
return uint(keccak256(block.difficulty, now, players));
}
function pickWinner() public restricted {
//require(msg.sender == manager);
uint index = random() % players.length;
lastWinner = players[index];
players[index].transfer(this.balance);
players = new address[](0);
}
function getPlayers() public view returns(address[]){
return players;
}
modifier restricted() {
require(msg.sender == manager);
_;
}
}
The first step is the compilation process. Solidity is an object-oriented and statically typed programming language. So it needs to be compiled and this compilation is done one EVM. Ethereum has its own Solidity Compiler. Once the source contract is compiled we get two important data fields as ABI i.e Application Binary Interface and the contract Bytecode.
As seen the ABI is the code we’re interested in since this is what allows our frontend to interact with the contract’s variables, functions, methods.
The second step is to deploy our contract on Ethereum’s blockchain. Once the contract is deployed we get the details of the contract which include the contract address (hash). This address represents where our smart contract is stored on the Ethereum’s blockchain. You can get a piece of detailed information on https://rinkeby.etherscan.io/tx/yourTransactionHash. The “to” field denotes the address of our smart contract. This is what will help our frontend to connect with the smart contract.
Now let's move on to the front-end part. We’ll be using Vue CLI 3 for creating the Vuejs project and npm for installing the dependencies.
> vue create vue-eth-dapp
Assuming that you know the project folder structure, I’ll not go in detail about each and every file. For now, two files are important. lottery.js and web3.js. Create these files in the src folder along with the main.js
The first step is to configure the web3.js
import Web3 from 'web3';const web3 = new Web3(window.web3.currentProvider);window.addEventListener("load", async () => {// Modern dapp browsers...if (window.ethereum) {window.web3 = new Web3(window.ethereum);try {// Request account access if neededawait window.ethereum.enable();} catch (error) {// User denied account access...}}// Legacy dapp browsers...else if (window.web3) {window.web3 = new Web3(web3.currentProvider);}// Non-dapp browsers...else {console.log("Non-Ethereum browser detected. You should consider trying MetaMask!");}});export default web3;
Secondly, configure the lottery.js file. This will contain the address of our contract along with the ABI.
import web3 from './web3'const contract = 'contractAddess';const abi = yourABIexport default new web3.eth.Contract(abi, contract)
The above diagram shows how our frontend application is going to communicate with the Smart Contract. For this, I have used the Rinkeby Test Network. Feel free to use the one as per your convenience.
The project after finishing looks like this.
Key points:
Only the contract manager will be able to pick the winner
Only one bet can be placed in the current from one Metamask account.
You can find the complete project on https://github.com/parag1997/vue-ethereum-lottery-dapp
App Link: http://vue-ethereum-dapp.surge.sh/