Table of Contents
Smart contracts are like regular contracts with rules except that these are programs deployed across computers on a network. And, instead of being enforced by a legal entity, it is auto-enforced by software codes.
Smart contracts are stored on a blockchain that run when predetermined conditions are met. They are typically used to automate the execution of an agreement so that all participants can be immediately certain of the outcome, without any intermediary’s involvement or loss of time.
The Ethereum Virtual Machine or EVM is a system that tracks changes on a blockchain in a decentralized manner. It keeps track of the ‘state’/the latest version of the blockchain. Users can run the Ethereum Virtual Machine on a computer and use it to create their own programs (smart contracts) and make them part of the Ethereum ecosystem.
The EVM works the same way as a normal CPU/computer. It executes written code according to instructions written using programming languages (in this case, Solidity, mostly). The code (bytes) executed by the EVM are Ethereum smart contracts. EVM is a virtual CPU/computer aka software. It doesn’t exist in a physical form and rather in a virtual form virtualizing and deploying client servers in remote devices across the world. Blockchain helps to record transactions made on the environment immutably minus any intermediary.
Shardeum is an EVM-compatible or EVM-based smart contract platform. It basically means Ethereum developers, who are tired of gas fees and low throughput on Ethereum or any other EVM network, can migrate their smart contracts to Shardeum without having to write the code from scratch again. This is considering Shardeum will have low gas fees and high throughput forever. And this is important because when you build you dApps (decentralized applications) on a network, the last thing you want is your customers or clients complaining about high transaction fees or latency/slowness in the network for using your service.
Bitcoin and Ethereum networks are run on open source blockchains which means anyone can propose changes and implement them with consensus. Ethereum network’s value essentially comes from its EVM architecture which are used by a ton of dependent and independent networks who make use of the open source code and customize it to fit their needs. This in turn means such networks doesn’t have to reinvent the wheel to host and enable various Web 3 products and services themselves.
Since first and second generation blockchain networks like Bitcoin and Ethereum rely on an arduous consensus mechanism along with their self imposed data limits to secure the network (which was the need of the hour since 2008 financial crisis), the transactions are processed at a very low speed. Today a network like Visa processes up to 10,000 transactions per second while Ethereum barely crosses 45 TPS. Shardeum, through its innovative technology, will be capable to process over 1 million TPS while keeping high security and decentralization features intact. Shardeum launched its testnet in April 2022 with the mainnet expected in Q4 of 2022. This blog will show you how to deploy your first smart contract on Shardeum’s Sphinx Dapp testnet using Hardhat which is a testing/development environment used by Ethereum developers.
First, we’ll need to create a folder for our project. Navigate to your command line and type following commands
mkdir sphinx-hardhat-app
cd sphinx-hardhat-app
Now that we’re inside our project folder, we’ll use ‘npm init’ to initialize the project. If you haven’t installed npm already, download from here Node
npm init
This command will create package.json
file. It doesn’t really matter how you answer the installation questions, here is how we did it for reference.
package name: (sphinx-hardhat-app)
version: (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to G:\sphinx-hardhat-app\package.json:
{
"name": "sphinx-hardhat-app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
Is this OK? (yes) yes
As mentioned, Hardhat is a development environment to compile, deploy, test, and debug your Ethereum based software. It helps developers when building smart contracts and dApps locally before deploying to a live chain.
Inside sphinx-hardhat-app
project run:
npm install --save-dev hardhat
Inside sphinx-hardhat-app
project run:
npx hardhat
You should then see a welcome message and an option to select what you want to do. Select “create an empty hardhat.config.js”.
G:\sphinx-hardhat-app>npx hardhat
888 888 888 888 888
888 888 888 888 888
888 888 888 888 888
8888888888 8888b. 888d888 .d88888 88888b. 8888b. 888888
888 888 "88b 888P" d88" 888 888 "88b "88b 888
888 888 .d888888 888 888 888 888 888 .d888888 888
888 888 888 888 888 Y88b 888 888 888 888 888 Y88b.
888 888 "Y888888 888 "Y88888 888 888 "Y888888 "Y888
Welcome to Hardhat v2.9.5
? What do you want to do? ...
> Create a basic sample project
Create an advanced sample project
Create an advanced sample project that uses TypeScript
Create an empty hardhat.config.js
Quit
This will generate a hardhat.config.js
file for us, which is where we will specify all about the set up for our project.
To keep our project organized, Hardhat creates two new folders. Navigate to the root directory of your sphinx-hardhat-app
contracts/
is where we’ll keep our hello world smart contract code filescripts/
is where we’ll keep scripts to deploy and interact with our contractOpen up the sphinx-hardhat-app
project in your favorite editor. Smart contracts are largely written in a language called Solidity which is what we will use to write our Disperse.sol
smart contract.
1. Navigate to the “contracts” folder and create a new file called Disperse.sol
2. Below is a sample Disperse
smart contract from the disperse.shardeum.us that we will be using for this tutorial. Copy and paste in the contents below into your Disperse.sol
file.
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "hardhat/console.sol";
contract Disperse {
function disperseShardeum(address[] memory recipients, uint256[] memory values)
external
payable
{
for (uint256 i = 0; i < recipients.length; i++)
payable(recipients[i]).transfer(values[i]);
uint256 balance = address(this).balance;
// Refund remaining amount to msg.sender
if (balance > 0) payable(msg.sender).transfer(balance);
}
}
This is a super simple smart contract that disperses Shardeum tokens to array of addresses with values by calling disperseShardeum
Now that we have created smart contract, we need to deploy this smart contract to Shardeum Sphinx Dapp testnet.
MetaMask allows users to store and manage account keys, broadcast transactions, send and receive Ethereum-based cryptocurrencies and tokens, and securely connect to decentralized applications through a compatible web browser or the mobile app’s built-in browser. Click here to install the MetaMask extension on your browser.
And follow this instruction to add Shardeum to MetaMask wallet and claim test 100 $SHM tokens from Sphinx Dapp testnet faucet.
We’ve created a Metamask wallet and written our smart contract, now it’s time to connect these two.
Every transaction sent from your virtual wallet requires a signature using your unique private key. To enable our program with this permission, we can safely store our private key in an environment file.
First, install the dotenv package in your project directory :
npm install dotenv --save
.env
- Your environment file must be named .env or it won’t be recognized as an environment file. Do not name it process.env or .env-custom or anything else.
Your .env
should look like this:
SHARDEUM_RPC=https://dapps.shardeum.org/
PRIVATE_KEY= Your_Metamask_Private_Key
In order to connect them to our code, we’ll reference these variables in our hardhat.config.js
file
Ethers.js is a library that makes it easier to interact and make requests to Ethereum by wrapping standard JSON-RPC methods with more user friendly methods.
Hardhat makes it super easy to integrate Plugins for additional tooling and extended functionality. We’ll be taking advantage of the Ethers plugin for contract deployment (Ethers.js has some super clean contract deployment methods).
In your project directory type:
npm install --save-dev @nomiclabs/hardhat-ethers "ethers@^5.0.0"
We’ll also require ethers in our hardhat.config.js
in the next step.
Now that we have added few dependencies and plugins so far, we need to update hardhat.config.js so that our project knows about all of them.
Update your hardhat.config.js
to look like this:
require("@nomiclabs/hardhat-ethers");
require("dotenv").config();
const SHARDEUM_RPC = process.env.SHARDEUM_RPC;
const privateKey = process.env.PRIVATE_KEY;
/**
* @type import('hardhat/config').HardhatUserConfig
*/
module.exports = {
defaultNetwork: "hardhat",
solidity: {
version: "0.8.4",
settings: {
optimizer: {
enabled: true,
runs: 200,
},
},
},
networks: {
shardeum: {
url: SHARDEUM_RPC,
accounts: [privateKey],
chainId: 8080,
}
},
};
To make sure everything is working so far, let’s compile our contract. The compile task is one of the built-in hardhat tasks.
From the command line run:
npx hardhat compile
If there are no errors, it will compile successfully
Compiled 3 Solidity files successfully
Now that our contract is written and our configuration file is good to go, it’s time to write our contract deploy script.
Navigate to the /scripts
folder and create a new file called deploy.js
, adding the following contents to it:
const hre = require("hardhat");
async function main() {
const Disperse = await hre.ethers.getContractFactory("Disperse");
const disperse = await Disperse.deploy();
await disperse.deployed();
console.log(`Disperse contract address: ${disperse.address}`);
}
// We recommend this pattern to be able to use async/await everywhere
// and properly handle errors.
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});
Hardhat has done an amazing job of explaining what each line of the code does in their Contracts tutorial. We’ve adopted their explanations here.
const Disperse = await hre.ethers.getContractFactory("Disperse");
A ContractFactory
in ethers.js is an abstraction used to deploy new smart contracts, so Disperse
here is a factory for instances of our Disperse
contract. When using the hardhat-ethers
plugin ContractFactory
and Contract
, instances are connected to the first signer (owner) by default.
const disperse = await Disperse.deploy();
Calling deploy()
on a ContractFactory
will start the deployment, and return a Promise that resolves to a Contract object. This is the object that has a method for each of our smart contract functions.
We’re finally ready to deploy our smart contract! Navigate to the command line and run:
npx hardhat run scripts/deploy.js --network shardeum
You should then see something like this:
Disperse contract address: 0x64B1f5069D2965f5e0B4b1d8494f21bD560e69cB
If we go to the Shardeum explorer and search for our contract address we should able to see that it has been deployed successfully. The transaction will look something like this in the image below with the URL: https://explorer-dapps.shardeum.org/account/0x64B1f5069D2965f5e0B4b1d8494f21bD560e69cB
Click on Transaction hash to see the full details of contract creation, it will look something like this in the image below with the URL: https://explorer.liberty10.shardeum.org/transaction/0xc84a25c6d91d7a83d2451de846253cb160e51efbdc393fe7f5f6f5cfcd5f250c
Congrats! You just deployed a smart contract to the Shardeum Sphinx Dapp testnet!!
To learn more about shardeum : Visit https://docs.shardeum.org/
Why to Invest in DeFi Coins and Token | Mobile App Technology Stack | How to Buy Real Estate in the Metaverse | Blockchain Scalability Solutions | Public Blockchain Examples | Top Altcoins | What is Proof of Work in Blockchain | Crypto Cloud Mining | Best Place to Mint NFT | What is Stake in Crypto | What is a Governance Token | Benefits of Blockchain | What is Blockchain Security | Can Blockchain be Hacked | What is Crypto Metaverse | How to Keep Crypto Safe | Bitcoin VS Ethereum | What is a Crypto Whale | What is Staking in Crypto | Ethereum that are Compatible with the EVM
Opinions expressed in this publication are those of the author(s). They do not necessarily purport to reflect the opinions or views of Shardeum Foundation.
About the Author : Naresh Golla is a front end Web 3.0 developer with experience in Vue, React, web3.js, Ethers.js, Hardhat and Alchemy. He is one of the first developers to deploy a smart contract and a NFT project on Shardeum. You can follow him on LinkedIn.