Are you new to the Web3 domain and everything seems so overwhelming to you??? Are you just stuck in trying to understand what's going onn in the 'deploy.js' code ???
Don't worry Bro I got your back😉
In this blog I will try to simplify what's going onn in the backend and what you really need to know to conquer it.
Before starting ,I am assuming that you have already installed hardhat and created its basic sample project . If you haven't then just make a folder at your desired place , open it on VS Code and run the following command in your terminal ;
yarn add --dev hardhat
then select the basic sample project ( sometime it doesn't install the other dependencies like ethers , chai , waffel and many others ; make sure you have installed all that.
The Top 3 contenders in Web3 Backend are the
- deploy.js
- test.js || run.js
- Contract.sol
The "deploy.js" file;
Most of the (90%) deploy.js files are same everywhere . There will be a little bit of difference depending on which language are you using (like web3.js or ethers.js or any other...) Newbie like me when saw it for first time will got worried for sure . So lets simplified it a bit🤏.
See the codes carefully🧐
const {ethers} = require('hardhat');
// understood it as a type of import
const main = async () => {
/*
ExtraCodes-1
-------------------------
abcd = xyz
-------------------------
*/
const contractYouWantToDeploy = await ethers.getContractFactory('Contract_Name');
const startDeployingContract = await contractYouWantToDeploy.deploy();
await startDeployingContract.deployed(); // wait until deployment is not finished
console.log(
`Your contract is deployed to ADDRESS ${startDeployingContract.address}`
);
};
// you can copy this 👇 code , it basically catches the error , if you have made any;
const runMain = async () => {
// you can copy this code , it basically catches the error , if you have made any;
try {
await main();
process.exit(0);
} catch (err) {
console.log(`This is a error ${err}`);
process.exit(1);
}
};
runMain();
And that's it ; let me explain you what just happened
In the first line of code you basically extracting {ethers} from hardhat .
There is a another way of doing it also without importing it in a 'require' statement , there is a hre
variable that we get at the time of installing the hardhat dependencies , it basically means hardhat runtime environment
so you may often see this 👇 at ExtraCode-1(see in codes)👆 ;
const contract = await hre.ethers.getContractFactory('Contract_name');
But they are basically same;
The getContractFactory
in ethers.js is an abstraction (cleaned version) used to deploy new smart contracts, so Contract_Name
here is a factory for instances of our OriginalContract.sol
.
.deploy()
is starting the process of deploying the contract.
rest of the things are in code.
The "test.js" file;
The test.js
will test your contracts (obviously).
Tests are done using Waffel
which is written in 'Mocha' alongside 'Chai'.
Mocha is a feature-rich JavaScript test framework running on Node.js and in the browser, making asynchronous testing simple and fun.
Chai provides some usefull assertions like
expect
,assert
,should
.
const { expect , assert , should } = require("chai");
const { ethers } = require("hardhat");
describe("Describes what is going to happen when you run the *test*" , function () {
it("This should happen, if *test* is started... ", async function () {
//These lines to initialize the test , explained earlier;
const whatContract = await ethers.getContractFactory("Contract_Name");
const deployingContract = await WhatContract.deploy("Hello, world!");
await deployingContract.deployed();
// It expects something to be equal to another thing.
expect(await deployingContract.someContractFunction()).to.equal("Hello, world!");
const setOtherValueTx = await deployingContract.setOtherValue("abcd"); //Setting the value of something else*optional*
// wait until the transaction is mined
await setOtherValueTx.wait();
expect(await deployingContract.someContractFunction()).to.equal("abcd");
});
});
After writing all your logic you have to run it using;
yarn hardhat test
in the Terminal and output will be something like:
$ npx hardhat test
Contract: Contract_Name
✓ This should happen, if *test* is started... (762ms) //The string that we putted in it()
1 passing (762ms)
This types of test are done to check wether our contract is working fine or not. You can get more detail about it in hardhat's tutorial here.
Then what the heck is run.js
?🤔
When your contract is not too long and you have no plan of deploying it on Mainnet . Then you can make a run.js
file in "scripts" folder and can run it using;
yarn hardhat run scripts/run.js
The run.js
will be directly interacting to the smart contract , it will seems similar to the deploy.js
file;
const main = async () => {
// when we want to write something to the blokchain we use signer
const [owner, randomPerson] = await hre.ethers.getSigners();
//explained earlier
const contract = await hre.ethers.getContractFactory("ContractName");
const deployContract = await contract.deploy();
await deployContract.deployed();
console.log(
`Your contract has beeen deployed at ${deployContract.address}`
);
console.log(`This contract has beeen deployed by ${owner.address}`); //.address is a global function given by ethers (google more about it)
let count;
count = await deployContract.getTotalCount(); //some contract function
let txn = await deployContract.sendMessage("Shikhar sends a Goodluck"); // wait for mining
await txn.wait(); // wait till the block is mined
/// random person to send the message
//const [owner, randomPerson] = await hre.ethers.getSigners();
txn = await deployContract
.connect(randomPerson)
.sendMessage("SomeoneElse sended some message");
await txn.wait();
count = await deployContract.getTotalCount();
};
async function runMain() {
try {
await main();
process.exit(0);
} catch (err) {
console.log("This is the error" + err);
process.exit(1);
}
}
runMain();
The 3rd Contender Contract.sol
For the Simple Explanation I have taken example of Greeter.sol file;
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "hardhat/console.sol";
contract Greeter {
string private greeting;
constructor(string memory _greeting) {
console.log("Deploying a Greeter with greeting:", _greeting);
greeting = _greeting;
}
function greet() public view returns (string memory) {
return greeting;
}
function setGreeting(string memory _greeting) public {
console.log("Changing greeting from '%s' to '%s'", greeting, _greeting);
greeting = _greeting;
}
}
The import "hardhat/console.sol";
is a console.log feature which is given by hardhat itself.
The first thing that happens in every solidity contract that constructor()
is the first function that runs while parsing.
If someone is comming from JAVASCRIPT here are some tips for you😉
Solidity is a statically typed programming language . While writing solidity keep one thing in mind Just replace
let
&const
with the type of variable that you want to use like
const something = "string "
will bestring public something;
Follow the pattern of TVV(type , visibility , variable)
Visibility is ignored when we are writing something inside function
More detailed Explanation of Solidity code will be in next Blog. Hope you like This ♥