This tutorial aims to guide you through the process of setting up a blockchain for your decentralized application (DApp). You will learn how to connect to an Ethereum blockchain and get a basic understanding of how blockchain technology works.
By the end of this tutorial, you will be able to:
- Understand the basics of a blockchain
- Set up a local Ethereum blockchain
- Connect your DApp to the blockchain
First, we need to install Ganache, a personal blockchain for Ethereum development. Ganache creates a virtual Ethereum blockchain, and it generates some fake accounts that we will use for development.
In your terminal, type:
npm install -g ganache-cli
After installation, you can start Ganache with:
ganache-cli
This command starts the Ganache blockchain, and you will see 10 accounts it generated with their private keys and a balance of 100 ETH each.
Let's connect our DApp to this blockchain. For this, we will use Web3.js, a JavaScript library that allows our app to communicate with the Ethereum blockchain.
In your terminal, navigate to your project directory and type:
npm install web3
Create a new index.js
file and add the following code:
const Web3 = require('web3');
// Connect to Ganache
const web3 = new Web3('http://localhost:8545');
// List all accounts
web3.eth.getAccounts().then(accounts => {
console.log(accounts);
});
When you run node index.js
, it will print the list of account addresses. This means you've successfully connected to your local Ethereum blockchain.
In this tutorial, you learned how to set up a local Ethereum blockchain using Ganache and connect your DApp to it using Web3.js.
Next, you could learn more about Ethereum Smart Contracts and how to deploy them to your blockchain.
For additional resources, you can visit:
- Ethereum.org
- Ganache documentation
Solution: Replace 'http://localhost:8545'
with your Infura endpoint.
Exercise: Try retrieving the balance of an account.
web3.eth.getBalance(account)
function.Solution:
javascript
web3.eth.getBalance(accounts[0]).then(balance => {
console.log(balance);
});
This will print the balance of the first account in Wei. Use web3.utils.fromWei(balance, 'ether')
to convert it to Ether.
Exercise: Try sending Ether from one account to another.
web3.eth.sendTransaction({from: account1, to: account2, value: web3.utils.toWei('1', 'ether')})
function.javascript
web3.eth.sendTransaction({
from: accounts[0],
to: accounts[1],
value: web3.utils.toWei('1', 'ether')
}).then(receipt => {
console.log(receipt);
});