Blockchain technology allows the creation of distributed digital ledgers that can track every transaction on a distributed network. The ledger is accessible to all network participants at the same time, so promoting accountability and transparency is easy.
Since the ledger is accessible to all participants in a network, it promotes accountability and transparency. Even if one ledger is compromised, it cannot change anything in other accounts. Nearly every decentralized system, all cryptocurrencies, and smart contracts use blockchain technologies.
As the name denotes, blockchain is a series of blocks with each block holding a list of transactions. Every transaction or information in this network updates simultaneously. This system has a series of nodes with a copy of the blockchain. Similarly, if there is a new block added to the chain, the information updates and becomes viewable to all the other blocks on the network. Each transaction, either big or small, is shown in the records and cannot be altered or deleted by anyone.
Remix is an open-source tool that helps developers write solidity contracts via the browser. You will need to learn solidity mainly because it is the primary language used for writing smart contracts on different blockchain platforms like Ethereum.
For reference, here is a simple storage contract that you can review. With this contract code, you can store and retrieve a number.
Check out this code example for reference:
pragma solidity ^0.8.0;
contract SimpleStorage {
uint public data;
function set(uint x) public {
data = x;
}
function get() public view returns (uint) {
return data;
}
}
Now that you have mastered a simple storage contract, you can now learn something more advanced. Here is a code to help you create a contract with the use of the SimpleStorage contract.
Check out this StorageFactory code example for reference:
pragma solidity ^0.8.0;
import "./SimpleStorage.sol";
contract StorageFactory {
SimpleStorage[] public simpleStorageArray;
function createSimpleStorageContract() public {
SimpleStorage simpleStorage = new SimpleStorage();
simpleStorageArray.push(simpleStorage);
}
//... more code here ...
}
FundMe is a simple contract that works for crowdfunding. This contract allows the users to send and donate money to the owner of the contract. Once the transaction takes place and the owner has recovered money, he can withdraw funds when needed.
Check out the example of a “fund me” contract below:
pragma solidity ^0.8.0;
contract FundMe {
mapping(address => uint) public contributors;
address public admin;
constructor() {
admin = msg.sender;
}
function contribute() public payable {
contributors[msg.sender] += msg.value;
}
function getBalance() public view returns(uint) {
return address(this).balance;
}
function withdraw() public {
require(msg.sender == admin, "Only admin can withdraw");
payable(admin).transfer(getBalance());
}
}
Now that you have an understanding of the “fund me” contract, let us look at ways to interact with these contracts. You will mainly use Ethers.js and Hardhat for this interaction and then look at ways to create the front end of these contracts. For the front end, our primary languages will be HTML/JavaScript and Next.js.
You will also look at some other complex topics including ERC20s, DeFi, Aave, NFTs, and DAOs, in the later part. Make sure to practice it as you learn. Hands-on experience will offer you a much better understanding of this.
You can practice by creating your own contracts, altering the contracts, and then trying to rewrite and understand the contract. In this process, copy one line at a time and see it function before you paste it.
Ethers.js is mainly used for interacting with Ethereum and its smart contracts. Since Ethers.js is a JavaScript library, you can use it for interaction.
Here is a simple code that uses Ethers.js to interact with SimpleStorage contracts.
You can start by installing ethers.js using npm. Here is an example of this:
npm install --save ethers
Now, look at this code for the reference. The below-mentioned code is interacting with the SimpleStorage contract:
const ethers = require('ethers');
// Connect to the network
let provider = ethers.getDefaultProvider('ropsten');
// The address that the Contract WILL have once mined
let contractAddress = "your_contract_address_here";
// The ABI (interface)
let abi = [ "function get() view returns (uint)", "function set(uint)" ];
// Init contract
let contract = new ethers.Contract(contractAddress, abi, provider);
// Call the contract's 'get' function
and let value = await contract.get();
console.log('Stored value in Remix contract:', value.toString());
// Set a new value (only works if you're the contract owner)
let newValue = 7;
let tx = await contract.set(newValue);
await tx.wait();
Hardhat is a complete development environment for interacting with Ethereum software. By using this you cannot just compile, test, and deploy your Ethereum software but also you can debug it. This is mainly useful in developing Ethereum applications. With the help of this, you can make these applications fun to use and much more efficient.
You can start using Hardhat by installing it with the help of npm. Here is a code for installation:
npm install --save-dev hardhat
Now that you have installed it, it is time to create the Hardhat config file (hardhat.config.js). After that, you can set up a local Ethereum network. Here is a code for the reference:
module.exports = {
networks: {
hardhat: {
chainId: 1337
}
},
solidity: "0.8.0",
};
Now it is time to deploy and interact with your SimpleStorage contract in a script. You can follow the code below for that as well:
const ethers = require('ethers');
const { ethers } = hre;
async function main() {
const SimpleStorage = await hre.ethers.getContractFactory("SimpleStorage");
const simpleStorage = await SimpleStorage.deploy();
await simpleStorage.deployed();
console.log("SimpleStorage deployed to:", simpleStorage.address);
let tx = await simpleStorage.set(23);
await tx.wait();
let value = await simpleStorage.get();
console.log('Stored value in Hardhat contract:', value.toString());
}
main();
For deploying your FundMe contract, you can also use Hardhat. You can follow the code below to deploy it on your system:
const ethers = require('ethers');
const { ethers } = hre;
async function main() {
const FundMe = await hre.ethers.getContractFactory("FundMe");
const fundMe = await FundMe.deploy();
await fundMe.deployed();
console.log("FundMe deployed to:", fundMe.address);
}
main();
To make sure that your code is running in the balance, you need to write a code as well. Here is a quick overview of the code that will help you ensure that your contribution to the contract is working fine and has the balance it needs:
let tx = await fundMe.contribute({ value: ethers.utils.parseEther("1.0") });
await tx.wait();
let balance = await fundMe.getBalance();
console.log('Contract balance:', ethers.utils.formatEther(balance));
Interacting with smart contracts from your webpage is made possible by using the JavaScripr library. Developers mainly use a combination of both JavaScript along with the ethers.js library.
Here is a quick example of how you can create an HTML page for interacting with your FundMe contract:
Contribute
Get Balance
For the app.js, a developer can use ether.js to communicate with the contract. Here is a quick overview of how you can do that:
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();
const contractAddress = "your_contract_address_here";
const contractABI = [ "function contribute() public payable", "function getBalance() public view returns (uint)", "function withdraw() public" ];
const fundMeContract = new ethers.Contract(contractAddress, contractABI, signer);
document.getElementById('contribute').addEventListener('click', async () => {
const tx = await fundMeContract.contribute({ value: ethers.utils.parseEther("0.1") });
await tx.wait();
});
document.getElementById('getBalance').addEventListener('click', async () => {
const balance = await fundMeContract.getBalance();
document.getElementById('balance').innerText = `Balance: ${ethers.utils.formatEther(balance)} ETH`;
});
Now that you have mastered the basics, you should move to something more complex. For that, you need to learn ways to create a basic lottery smart contract by using Hardhat.
Within the lottery smart contract, players can enter the lottery by simply transferring some ether to each other. To make this work, you need enough players. Once you have enough players, any player can end the lottery and by the end of it, a winner will be picked randomly.
Once there are enough players, anyone can participant can end the lottery, and the contract will randomly pick a winner:
pragma solidity ^0.8.0;
contract Lottery {
address payable[] public players;
address public manager;
constructor() {
manager = msg.sender;
}
function enter() public payable {
require(msg.value >= 0.01 ether, "Not enough ether");
players.push(payable(msg.sender));
}
function random() private view returns(uint) {
return uint(keccak256(abi.encodePacked(block.difficulty, block.timestamp, players.length)));
}
function pickWinner() public {
require(msg.sender == manager, "Only manager can pick a winner");
require(players.length >= 3, "Not enough players");
address payable winner;
uint r = random();
uint index = r % players.length;
winner = players[index];
// Transfer the entire contract balance to the winner
winner.transfer(address(this).balance);
// Reset the players array for the next round of the lottery
players = new address payable[](0);
}
}
It is one of the most popular frameworks used for making serve-side rendered react applications. You can use this to interact with lottery contracts. A simple way of doing that is by creating a simple Next.js app.
Start by setting up a new Next.js project by using npx create-next-app.
Now, you can make a new file within your page directory and the name is lottery.js. This will work as the lottery page. Here is a code that you can follow to create the lottery page:
import { ethers } from 'ethers';
import { useState } from 'react';
export default function Lottery() {
const [players, setPlayers] = useState([]);
async function loadPlayers() {
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();
const contractAddress = "your_lottery_contract_address_here";
const contractABI = [ "function enter() public payable", "function pickWinner() public" ];
const lotteryContract = new ethers.Contract(contractAddress, contractABI, signer);
setPlayers(await lotteryContract.getPlayers());
}
return (
Load players
);
}
To develop Ethereum dApps, you will need a template. Hardhat Starter Kit is one of the most used templates and it offers everything that you need to kick-start the dApp development process. Within the Hardhat Starter Kit, you will get all the essential scripts and pre-configured tools.
Before using it, you need to clone the kit from the GitHub repository. To clone this, here is a code that can help you:
git clone https://github.com/nomiclabs/hardhat-starter-kit.git
Now, it’s time to install all the dependencies that you will be required for the kit. Here is a code that will help you install that:
cd hardhat-starter-kit
npm install
Within this starter kit, you will get all the smart contract samples that you will need. Moreover, you will have all the essential scripts and test files to help you comprehend the format of the dApp project.
For the hands-on experience, you can copy it and then try altering the code. It will offer you a much better understanding of the function.
To interact with the other platforms and dApps, you will need something. This is where interface tokens come in. ERC20 is the token that is known for predictability and will help you interact with other platforms as well as dApps.
To create an ERC20 token you will need to use Hardhat.
You can start by installing the OpenZeppelin library. This will offer you reusable, secure smart contracts that are used for interacting with Ethereum. Not only this, but it will also help you interact with EVM-compatible blockchains as well.
Here is a code to install this:
npm install @openzeppelin/contracts
Now that you have installed it, it’s time to create a new contract MyToken.sol. this will be able to use the ERC20 implementation from OpenZeppelin.
Here is a quick overview of the code that you can follow:
// contracts/MyToken.sol
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
contract MyToken is ERC20 {
constructor(uint256 initialSupply) ERC20("MyToken", "MTK") {
_mint(msg.sender, initialSupply);
}
}
For the next phase, you are required to deploy your token.
To make this possible, you need to write the script. Here is a script that will enable you to deploy your token:
// scripts/deploy.js
async function main() {
const [deployer] = await ethers.getSigners();
console.log("Deploying contracts with the account:", deployer.address);
const Token = await ethers.getContractFactory("MyToken");
const token = await Token.deploy(1000000);
console.log("Token address:", token.address);
}
main();
This script will help you create a token with a vast supply of nearly 1,000,000 units. All these units will be assigned to the owner of the account deploying the contract.
Lending and borrowing cryptocurrencies in certain protocols is very crucial so, Aavi is a DeFi lending protocol that will help the developer with this. It mainly helps in lending different cryptocurrencies and does so at a very stable interest rate. Developers can use Aave in the hardhat project. This will help in interacting with the Aave protocol.
We have discussed this in detail in later sections as well.
NFTs or non-fungible tokens are like a trademark. Each token represents a unique item or asset in the blockchain. NFTs are used for representing both real-world assets as well as virtual-world assets.
For making an NFT, a developer can use the ERC721 standard. The developer can then use OpenZeppelin and the rest of the process will be simple.
Here is a quick overview of the code-creating NFT that you can try:
// contracts/MyNFT.sol
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
contract MyNFT is ERC721 {
constructor() ERC721("MyNFT", "MNFT") {}
function mint(address to, uint256 tokenId) public {
_mint(to, tokenId);
}
}
Now that you have your NFT contract set up, you need a front end to interact with it. For the front end, you can use Next.js and ethers.js. This will help you build an NFT marketplace where users can view and mint NFTs.
Start by creating a new file in the pages directory named nft.js. Here is a code that can help you do it:
import { ethers } from 'ethers';
import { useState } from 'react';
export default function NFTMarket() {
const [tokenID, setTokenID] = useState(0);
async function mintNFT() {
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();
const contractAddress = "your_NFT_contract_address_here";
const contractABI = [ "function mint(address to, uint256 tokenId) public" ];
const nftContract = new ethers.Contract(contractAddress, contractABI, signer);
const tx = await nftContract.mint(signer.getAddress(), tokenID);
await tx.wait();
setTokenID(tokenID + 1);
}
return (
Mint NFT
Minted NFTs: {tokenID}
);
}
Smart contracts are a stable entity so after completion of development and deployment, they stay the same. You cannot change the contract or alter the code in any way.
This is the reason it is crucial to resolve everything before you deploy your contract. In case there is a big or you want to add functionality later, you will be required to deploy a new contract. However, there is another way that can help you avoid this hassle – upgradable contracts.
Upgradable contracts are a great way to resolve this issue and now most smart contracts are upgradable as well. If you want to create your own upgradeable contract in hardhat, you will be required to use Hardhat Upgrades plugin.
Here is a command that will help you install it:
npm install @openzeppelin/hardhat-upgrades
Now that you have installed the Hardhat Upgrades plugin, you can now require it in your hardhat.config.js:
require('@openzeppelin/hardhat-upgrades');
module.exports = {
solidity: "0.8.4",
};
Finally, you can deploy the contracts as upgradeable. For deploying the upgradable contract you will need a deployProxy function and then upgrade it using the upgradeProxy function.
Here is a code that can help you perform both these steps:
const { ethers, upgrades } = require("hardhat");
async function main() {
const MyContract = await ethers.getContractFactory("MyContract");
const instance = await upgrades.deployProxy(MyContract);
console.log("Deployed at:", instance.address);
}
main();
DAO or decentralized autonomous organization is a system of hard-coded rules. These rules are used to define the actions that an organization can take. DAO helps replace the need for traditional documents and documentation processes. Instead, token holders replace management and smart contracts replace traditional documents.
To implement the DOA with solidity, the developer needs to create smart contracts that can help token holders propose and then vote on the proposals.
Here is an example of DOA implementation code:
// contracts/SimpleDAO.sol
pragma solidity ^0.8.0;
contract SimpleDAO {
struct Proposal {
string description;
uint voteCount;
}
mapping(address => bool) public voters;
Proposal[] public proposals;
function propose(string memory description) public {
voters[msg.sender] = true;
proposals.push(Proposal({
description: description,
voteCount: 0
}));
}
function vote(uint proposalIndex) public {
require(voters[msg.sender], "Only voters can vote");
proposals[proposalIndex].voteCount++;
}
}
Security is the most important parameter while creating smart contracts. Security is especially important in smart contracts because it is irreversible. Once it is deployed, there is no way to change it. To make sure that the deployed contract does not require any change, it is very important to debug and check before deploying. Any flaw in the contract can lead to irreversible damage or even loss of funds in some cases.
Most organizations have a regular audit process for the contracts so that security can be prioritized. Within the audit process, contracts are reviewed thoroughly and any vulnerability can be spotted and fixed right away.
For conducting an audit, check for any vulnerabilities. Some of the common issues that you must check include reentrancy, integer overflow, and underflow. Another important thing to check is that your contract uses the latest and upgraded version of Solidity.
Now check if your contract has the right access controls and if the function visibility is working properly and is visible as well.
Within the audit, you also need to ensure that the contract handles expectations properly and fallback function is working all fine. Another thing that most auditors miss is the external contract calls. Make sure the external contract calls are handled properly.
A simpler way to include all these things in your testing process is to write a unit test for all the functions included. You can then run these unit tests with coverage. The process will be automated and you will not miss anything. To make sure your test runs smoothly, use property-based and fuzz testing. You can use static analysis tools like Slither or Securify for the audit.
Since contract auditing is a very difficult task and requires attention to detail, you need to be well-versed in Ethereum and Solidity. Most organizations have professional auditors for contract audits. This is common in companies that specialize in contracts and need to manage large volumes of contracts. However, small companies with low volumes do not have to hire professionals.
Simply put, blockchain is a very vast field that has a lot of exciting details and real-life applications. Within the blockchain, Ethereum holds the center in the centralized world but there are so many other domains as well. To become a professional, make sure to practice and keep exploring advanced technologies. It is also encouraged to practice the code or break it down to understand every line.
This tutorial offers information about all the techniques that are important for building a stronger foundation for blockchain, however, it is better to stay updated.
Within the domain of smart contracts, remix plays an important role. It is an open-source website and a desktop application that developers use for not just coding but also testing and then debugging their smart contracts.
Smart contracts for Ethereum are written in Solidity and Remix has all the tools that a developer can need for analyzing the contracts. The remix is user-friendly and has a very simple interface. It is a powerful Solidity editor that can help with syntax highlighting and auto-completion.
Another very important tool within the Ethereum blockchain is Ethers.js. It is a complete library that can help the developer interact with the Ethereum blockchain. Most developers use it for finance-based projects so you can use it for creating wallets, signing transactions, and interacting with smart contracts. While these are just a few popular functions, you can do much more with them. Ethers.js is a very popular alternative to web3.js because of its lightweight and cleaner design.
Web3.js and ethers.js are libraries that offer tools for interacting with the Ethereum blockchain. You can use them for handling transactions, smart contracts, etc. Since most of these functions are similar, developers think they are the same. There is no doubt they have similar functions but there are so many differences as well.
One of the biggest differences is that their design philosophy and API structure are quite different. Moreover, web3.js as a library is unique, complex, and quite challenging to use for some developers.
On the contrary, ethers.js is a compact, easy-to-use, and lightweight option that most developers prefer.
It is another development environment used for Ethereum software. Hardhat is mainly used by developers for managing and automating recurring tasks while making smart contracts and blockchain applications. Hardhat is especially helpful because it keeps suggesting new features that can eventually help with JavaScript and Solidity.
Most developers think that hardhat is a truffle. However, there are two different development frameworks used for interacting with Ethereum. There are some similarities in function for instance, both frameworks offer tools for contract development, testing, developing, etc.
One of the biggest differences between these frameworks is their design and functionality. Hardhat offers many advanced debugging tools, it has better configuration properties and it is much more flexible. You will also get TypeScript support with this framework.
However, for the truffle, you will get a detailed feature set and much larger community support.
A smart contract is a fully automated, self-exciting, and unchangeable contract. You will have all the terms of the agreement written in code form and it uses blockchain for running the contract. You can store it in a public database but once deployed you cannot change anything. In case you need to change something, you will be required to write another contract. When a smart contract commits a transaction, it all updates automatically in real-time and gets sent to a third party.
ERC stands for Ethereum Request for Comment. The 20 in ERC20 denotes the specification. For the Ethereum blockchain, using ERC20 is considered the technical standard for implementing tokens. It has all the set of rules for implementing the token for instance; it has rules for transferring the token, accessing the data about the token, and then signaling the approval for accepting third party token.
It is a common term used in finance services that is short for Decentralized Finance. DeFi is a software-based finance service so you do not have a third party like banks, brokers, or any other things involved. However, you will still need a smart contract. Common examples of DeFi services include decentralized exchanges, prediction markets, lending websites, and borrowing platforms.
It is known to be a decentralized money marketer protocol that comes with no mediators or custodial rules. Users can carry out transactions as a borrower or a depositor depending on the need.
Within the system, Depositors offer market liquidity and borrowers get to lend in an overcollateralized or undercollateralized manner.
NFTs stand for Non-Fungible Tokens. While most people think, they are digital currency they are actually digital assets. These assets are created via blockchain technology.
NFTs are opposite to cryptocurrencies because they are non-fungible. This means that they can be exchanged, and sold to anyone on a one-on-one basis without involving anyone. NFTs are unique assets and they can’t be replaced or exchanged like for like.
Decentralized Autonomous Organizations or DAOs are organizations handled by code. These organizations are built on blockchain technologies and operated by using smart contracts.
Python is simple, easy, and much simpler so, it is recommended to beginners. Most beginners feel that Python is easy to read and understand compared to other languages like Solidity.
On the contrary, solidity is a statically typed language. It has a syntax that resembles JavaScript and C++, This is a primary language used for creating smart contracts on the Ethereum blockchain.
As a beginner, learning Solidity is quite difficult because it involves all the fundamental blockchain concepts. Moreover, the code-running environment is much more difficult and different because it is segmented and has sections like gas fees and immutability.
Solidity is difficult for a beginner but it is not quite difficult for a developer who is well versed in blockchain technologies. If you have good experience in blockchain and you are familiar with other languages like JavaScript or another C-style language, then you can master Solididty easily.
Another thing to keep in mind is that you need to be familiar with finance services within the blockchain realm. This includes basic concepts like transaction mechanisms, gas fees, immutability, etc. Similarly, Solidity's environment is very rigid. A mistake committed here can be challenging to tackle and much more expensive as well.
Since contracts cannot be altered later, the developer needs to be very careful while deploying the contract.
With so many concepts and technologies to keep in mind, it is quite understandable that even experienced developers struggle with Solidity.
On the plus side, with the right resources and dedication, solidity can be mastered in no time. As a high-demand skill, there are so many good resources, tools, and tutorials available online. These resources can help you master solidity in no time.
Ethereum Virtual Machine also known as EVM is an Operating environment for smart contracts in Ethereum. EVM works separately from the main network, so it works as a perfect sandbox for executing smart contracts.
A node within Ethereum has its own EVM implementation and can commit the same instructions as well. As the smart contract is deployed, each node works independently and runs the same contract within EVM. This redundancy helps them work independently yet come up with the same result. Moreover, it is a very important contributing factor to the security of Blockchain like Ethereum.
The EVM can run any algorithm when given enough time and gas. EVM can infer a stackable bytecode language. This language is mainly designed to work with the Ethereum blockchain. You will also notice that it helps with the compilation of the solidity smart contracts.
EVM is also responsible for managing the state of Ethereum. This means that if EVM doesn’t work, the developer will face issues with account balances, smart contract code and data, and more. For every transaction when Ethereum changes the state, RVM ensures that the transition works seamlessly.
It also handles the internal cryptocurrency of Ethereum or Ether. This system helps in avoiding spam transactions and abuse of the network which eventually makes the system secure.
It is another library that you will be using while working with Ethereum. This library helps in developing secure and smart contracts. You can use this for implementing ERC20 and ERC721. In most cases, you will get to deploy it without changing anything but in some cases, you might have to change things as per your requirement.
Within this library, you will find Solidity components used for building custom contracts and other decentralized systems.
The focus of this library is on security because it is used for smart contract building. You will get to manage different assets so contracts are quite prone to attacks. With OpenZeppelin library, your team can keep track of all the testing and audits, which will eventually help you, avoid vulnerabilities and keep things secure. It also offers detailed documentation and development guidelines that can help ensure the safety of contracts.
Within the library, you will have access to different tools used for Ethereum development. Some of the tools include:
OpenZeppelin Contracts:
It offers a library of different smart contracts for Ethereum and other EVM and eWASM blockchains.
OpenZeppelin Defender:
It helps in automating operations within Ethereum, managing the system as well as automating the transactions process.
OpenZeppelin Test Environment:
It offers different customized tests used for quick and easy debugging of Ethereum applications.
With OpenZeppelin's suite of tools and libraries, you can easily develop secure and reliable blockchain applications.