Hardhat Beginners To Advanced Guides

Download as pdf or txt
Download as pdf or txt
You are on page 1of 212

2/13/23, 4:04 AM Hardhat for Solidity development.

The JS framework for Ethereum… | by Keno Leon | Coinmonks | Medium

Published in Coinmonks

You have 2 free member-only stories left this month. Sign up for Medium and get an extra one

Keno Leon Follow

Mar 22, 2022 · 6 min read · · Listen

Save

Photo by Andrea Piacquadio from Pexels

Hardhat for Solidity development


The JS framework for Ethereum development ?
https://medium.com/coinmonks/hardhat-for-solidity-development-b11e9f174f3a#:~:text=Hardhat is an Ethereum development,them on a development … 1/9
2/13/23, 4:04 AM Hardhat for Solidity development. The JS framework for Ethereum… | by Keno Leon | Coinmonks | Medium

As part me getting back into solidity I started looking into upgrading my setup with
frameworks, brownie for python was my first one ( great if you are into python but read
on ):

A quick look at Brownie


Ethereum Smart Contract framework in python !
coinsbench.com

Today I’ll check what from the outset looks like the choice Javascript framework for
Solidity… Hardhat:

Ethereum development environment for professionals by Nomic


Foundation
Hardhat is an Ethereum development environment. Compile your
contracts and run them on a development network. Get…
hardhat.org

Even before starting Hardhat has a clear advantage since there is a


lot of tooling written in javascript and well if you are going down
the web3 rabbit hole you will most likely need things like
Node/Webpack/React and other JS or Typescript libraries and tools for
your Dapp, hence why Javascript is recommended as a starting language
for blockchain development and hardhat seems to be a shoo-in.

Ease of Use/Setup/First Impression


Hardhat is a node package, so if you have some experience or are comfortable working
with node it should be a familiar experience, there is some defaults and boilerplates,
but overall you are left to organize your files (within reason) and plugins ( more on this
later ) as you see fit.

https://medium.com/coinmonks/hardhat-for-solidity-development-b11e9f174f3a#:~:text=Hardhat is an Ethereum development,them on a development … 2/9


2/13/23, 4:04 AM Hardhat for Solidity development. The JS framework for Ethereum… | by Keno Leon | Coinmonks | Medium

I don't say this often but Hardhat's documentation is top notch,


especially when it comes to onboarding and if you've made up your mind
or will test Hardhat regardless you can stop reading and head directly
to the tutorial which does a great job at introducing you to the
framework :
Hardhat Tutorial for Beginners
The Docs are equally high quality with plenty of easy to follow
examples:
Hadhat documentation

Once you are done installing hardhat ( took about 20 seconds with no errors for me, Yay !
), you do need to spend some time becoming familiar with the workflow, in a gist you
run commands from your terminal (test, compile for instance ) and use config files and
plugins to adapt your development environment to your project, this might seem like
too much work or somehow disorganized, but the unopinionated/flexible approach I
think works great, especially with the changing/modular nature of Ethereum and smart
contract development, just be prepared to think a bit about what your project needs
and set some time aside to config your hardhat build.

If you'd rather test the waters Hardhat provides an excellent list of


options for scaffolding and boilerplates when you first run it :
? What do you want to do? …
❯ Create a sample project
Create an advanced sample project
Create an advanced sample project that uses TypeScript
Create an empty hardhat.config.js
Quit

If for instance you choose the sample project you get boilerplates and
starter files :
├── README.md
├── artifacts
├── cache
├── contracts >> contains Greeter.sol
├── hardhat.config.js
├── node_modules
├── package-lock.json
├── package.json

https://medium.com/coinmonks/hardhat-for-solidity-development-b11e9f174f3a#:~:text=Hardhat is an Ethereum development,them on a development … 3/9


2/13/23, 4:04 AM Hardhat for Solidity development. The JS framework for Ethereum… | by Keno Leon | Coinmonks | Medium

├── scripts >> contains sample-script.js


└── test >> contains sample-test.js
Much like brownie you get a well organized build directory with sample
files, but unlike brownie you have some liberty on what/how this
structure looks like.

Features
Beyond the basics of writing, compiling and deploying contracts which are
straightforward (and well covered in the tutorial), Hardhat has a couple of features I
think are super useful which I’ll try summarizing :

Console.log for smart contracts


Import a login contract into your contract:

import "hardhat/console.sol";

Then sprinkle login calls wherever you need them:

console.log("Will try X function");

And upon testing or interacting with the contract you will get these logs which will
help you trouble shoot your contracts !

Hardhat Network
Blockchain/Ethereum development has always seemed clunky to me because when
you are writing contracts the feedback loop which is critical for learning, testing and
iterating can be a bottleneck; inspecting contracts against remix and soft launching
them against a test-net work but they might take you out of the flow of writing and if

https://medium.com/coinmonks/hardhat-for-solidity-development-b11e9f174f3a#:~:text=Hardhat is an Ethereum development,them on a development … 4/9


2/13/23, 4:04 AM Hardhat for Solidity development. The JS framework for Ethereum… | by Keno Leon | Coinmonks | Medium

you have a complex dApp or contract interactions it quickly becomes a slog. Hardhat’s
solution is not new ( a virtual local node ), but I found it easier to use than the
alternatives ( mainly truffle/ganache or ethereum node APIs) since you hardly need to
leave your IDE ( VsCode in my case ).

Hardhat spins up an in memory Vm that goes away when whatever task you
are doing ends (like testing), but if you need permanence so you can
test your dApp with calls (via JSON-RPC) and whatnot you can with:
$ npx hardhat node
You can also fork from mainnet ( requires an API with archive data
like Alchemy ) and more, check the docs :
Hardhat Network

Plugins, Tasks & Scripts


As mentioned Hardhat has an open design that allows you to build your own
environment to taste, the first part are Plugins which are libraries and other tools you
install and include ,( node packages really ) so for instance there are official plugins like
ethers and web3 that inject them and more specialized community ones like abi

exporters , coverage and autodocs to name a few, you can check them all here to get an
idea:

Ethereum development environment for professionals by Nomic


Foundation
Plugins are the backbone of Hardhat, and they're built using the same
config DSL that you use in your Hardhat…
hardhat.org

Tasks on the other hand are meant for automation and can be called from the
command line ( things like compile, clean run scripts and test ), but you can also
make your own tasks :

https://medium.com/coinmonks/hardhat-for-solidity-development-b11e9f174f3a#:~:text=Hardhat is an Ethereum development,them on a development … 5/9


2/13/23, 4:04 AM Hardhat for Solidity development. The JS framework for Ethereum… | by Keno Leon | Coinmonks | Medium

Ethereum development environment for professionals by Nomic


Foundation
This guide will explore the creation of tasks in Hardhat, which are the
core component used for automation. A task is a…
hardhat.org

And finally you have Scripts which do more specific things related to your project and
use hardhat as a library you require:

Ethereum development environment for professionals by Nomic


Foundation
In this guide we will go through the steps of creating a script with
Hardhat. For a general overview of using Hardhat…
hardhat.org

Along with the network features already mentioned you can build complex
development pipelines with these elements or just stick to the basics with some
customization, a truly flexible architecture.

Testing
In comparison testing is fairly standard which is a good thing and the recommended
path is ethers.js & Waffle (with Mocha and Chai which are also testing standards ), but
you can also use Web3 & Truffle

Not much else to say about testing (it works, it still doesn’t automagically write test for you
😕), I recommend you read the tutorial section which goes in depth on the actual
usage:

Ethereum development environment for professionals by Nomic


Foundation
Writing automated tests when building smart contracts is of crucial
importance, as your user's money is what's at…
https://medium.com/coinmonks/hardhat-for-solidity-development-b11e9f174f3a#:~:text=Hardhat is an Ethereum development,them on a development … 6/9
2/13/23, 4:04 AM Hardhat for Solidity development. The JS framework for Ethereum… | by Keno Leon | Coinmonks | Medium

hardhat.org

Vscode extension
To end the feature tour I should also mention the Solidity +Hardhat plugin for vsCode:

Solidity + Hardhat - Visual Studio Marketplace


This extension adds language support for Solidity to Visual Studio
Code, and provides editor integration for Hardhat…
marketplace.visualstudio.com

There’s another popular VsCode extension for solidity (Juan Blancos


Solidity) its a bit more mature and both offer similar features(code
completion, formatting) but you can't have both and the workflow is
different, try them both I guess, in my case I felt more at home with
Hardhat's

Conclusions
Tooling for Ethereum is fast evolving along with contract, dApp and web3 complexity,
it’s hard to keep up and if you are just starting out and feel overwhelmed I believe it is
normal and deserved. I found Hardhat to be a lifesaver in this regard, yes you still need
to spend some time learning how to use it and it is a framework after all, so it won’t do
everything for you, but I think it helps keep your Ethereum development organized
and the learning curve and documentation were excellent.

As an aside I've been writing python code pretty much every day for
the last 3 yrs so why not go with brownie/vyper ? For me at least it
makes more sense to switch to JS/TS/Solidity for Ethereum development
and use Hardhat to tie everything together rather than do a mix of
Python/JS, the DX just felt better but it is admittedly a personal
choice, for newcomers though I still think JS is the right first

https://medium.com/coinmonks/hardhat-for-solidity-development-b11e9f174f3a#:~:text=Hardhat is an Ethereum development,them on a development … 7/9


2/13/23, 4:04 AM Hardhat for Solidity development. The JS framework for Ethereum… | by Keno Leon | Coinmonks | Medium

language followed by TS and Solidity and so I would recommend Hardhat


over brownie for now.

Thanks for reading !

Join Coinmonks Telegram Channel and Youtube


Channel learn about crypto trading and investing
Also, Read
10 Best Books on Crypto | 5 Best Crypto Bots in the UK

Koinly Review | Binaryx Review | Hodlnaut vs CakeDefi

MoonXBT vs Bybit vs Binance | Hardware Wallets

Huobi Trading Bot | How to buy ADA | Geco.One Review

Binance vs Bitstamp | Bitpanda vs Coinbase vs Coinsbit

Ethereum Blockchain Web 3 Software Development Cryptocurrency

Sign up for Coinmonks


By Coinmonks

A newsletter that brings you day's best crypto news, Technical analysis, Discount Offers, and MEMEs directly in your
inbox, by CoinCodeCap.com Take a look.

Your email

Get this newsletter

https://medium.com/coinmonks/hardhat-for-solidity-development-b11e9f174f3a#:~:text=Hardhat is an Ethereum development,them on a development … 8/9


2/13/23, 4:04 AM Hardhat for Solidity development. The JS framework for Ethereum… | by Keno Leon | Coinmonks | Medium
By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy
practices.

About Help Terms Privacy

Open in app Sign up Sign In

Get the Medium app


Search Medium

https://medium.com/coinmonks/hardhat-for-solidity-development-b11e9f174f3a#:~:text=Hardhat is an Ethereum development,them on a development … 9/9


2/13/23, 4:06 AM Hardhat — ethereum development evolution? So, let’s figure it out. | by Rostyslav Bortman | Coinmonks | Medium

Published in Coinmonks

Rostyslav Bortman Follow

Dec 7, 2020 · 5 min read · Listen

Save

Hardhat — ethereum development evolution?


So, let’s figure it out.
For those of you who don’t know, Hardhat is a development
environment to compile, deploy, test, and debug your Ethereum
software. © Franco Zeoli
First of all, I would like to highlight three main components in the development of
ethereum software for me as for Web3 engineer:

1. Compiling & Deployment


For me it’s very important to be able to quickly compile&deploy contracts (to check if
they are still deployable — for example eip-170, if you know what I mean) and quickly
call needed functions to check outputs&functionality;

2. Testing
Everything that is possible has already been said on this topic, I will just say that it is
critically important to be able to quickly and conveniently cover with unit tests what
you wrote;

3. Debug
This is a topic for a completely separate article. Most of the headache in Ethereum
development comes from here. For example in 2017–2018 I was debugging with
events(!) which were really annoying (could be that I missed some pretty tools for
https://medium.com/coinmonks/hardhat-ethereum-development-evolution-so-lets-figure-it-out-34f4656bc1a9 1/8
2/13/23, 4:06 AM Hardhat — ethereum development evolution? So, let’s figure it out. | by Rostyslav Bortman | Coinmonks | Medium

debugging, you can share your favorite approach to debug solidity smart contracts in
comments).

Let’s take a look at how Hardhat manages these three vital tasks. Here are the results of
my research:

Compiling & Deployment


I created two test contracts with different solidity version 0.6.12 and 0.7.3 for
testing(see links section at the end). In their documentation, you can find:

Hardhat supports projects that use different, incompatible versions of solc. For example, if
you have a project where some files use Solidity 0.5 and others use 0.6, you can configure
Hardhat to use compiler versions compatible with those files like this

I tried it, and it works well:

By the way, this is a big advantage in comparison with the closest competitor Truffle.
Whenever you work with a project which has legacy contracts already deployed to the
mainnet and you need to add new contracts to collaborate with previous (and you don’t
want to use the old deprecated solidity version) — it’s become a huge issue. Details on
how to configure it you can find on their official documentation which is detailed
enough. Also, the compilation is much faster in comparison with the already
mentioned truffle.

Regarding deployment, there is not much to say — Hardhat doesn’t have its own
deployment system yet, but as I understand they are actively working on it, here is an
open issue on the git. Meanwhile, you can use truffle migrations (they are fully
compatible with Hardhat) or just your own js scripts.

Testing
When it comes to tests, Hardhat proposes to developers to choose between Web3.js &
Truffle and ethers.js & Waffle. I always use the first variant in my projects but there are
https://medium.com/coinmonks/hardhat-ethereum-development-evolution-so-lets-figure-it-out-34f4656bc1a9 2/8
2/13/23, 4:06 AM Hardhat — ethereum development evolution? So, let’s figure it out. | by Rostyslav Bortman | Coinmonks | Medium

no limits to use the most suitable for you. For the Web3.js & Truffle everything you need
to do — install the Truffle and Web3.js plugins ( @nomiclabs/hardhat-truffle5 ,
@nomiclabs/hardhat-web3).

Generally, Hardhat doesn’t have its own testing system — but it’s not a problem because
you can easily use solutions from other projects inside your Hardhat project.

Debug
The most interesting thing for me as for Ethereum engineer comes with Hardhat
improvements in debugging contracts.

Solidity stack traces

I created a simple interface to test the case with the non-existed selector call on other
contract and check Hardhat console output:

Example 1 — function call to a non-contract account

Example 2 — function call with non-existed selector

So, you can see that it works as expected (all code samples you can find under the link
section).

https://medium.com/coinmonks/hardhat-ethereum-development-evolution-so-lets-figure-it-out-34f4656bc1a9 3/8
2/13/23, 4:06 AM Hardhat — ethereum development evolution? So, let’s figure it out. | by Rostyslav Bortman | Coinmonks | Medium

Automatic error messages

Goal — reproduce several error messages declared in Hardhat documentation.

Example 1 — Calling a non-payable function with ETH

Example 2— Sending ETH to a contract without a payable fallback or receive function

Example 3— Calling a non-existent function when there’s no fallback function

See Solidity stack traces section — we already tested this case there.

Example 4 — Calling a function with incorrect parameters

https://medium.com/coinmonks/hardhat-ethereum-development-evolution-so-lets-figure-it-out-34f4656bc1a9 4/8
2/13/23, 4:06 AM Hardhat — ethereum development evolution? So, let’s figure it out. | by Rostyslav Bortman | Coinmonks | Medium

I will not cover all error messages here, there is no reason for it, but I tried all of them
locally and I can say — everything works as expected ✅

Console.log

Several important notes I want to highlight:

It always works, regardless of the call or transaction failing or being successful.

It works with any library: ethers.js, web3.js, waffle, truffle-contract, etc.

console.log calls can run in other networks, like mainnet, kovan, ropsten, etc.
They do nothing in those networks but spend a minimal amount of gas. (It means
whenever you want to test your solidity code in the Kovan network, for example,
there is no need to delete all console.log commands in the code, which is
fantastic)

Example of console.log usage:

Everything works as expected here as well ✅

Conclusion
So, is Hardhat the next generation of ethereum development experience? I can
definitely answer yes, it is. There are still a lot of things to do, but so far, at list solidity

https://medium.com/coinmonks/hardhat-ethereum-development-evolution-so-lets-figure-it-out-34f4656bc1a9 5/8
2/13/23, 4:06 AM Hardhat — ethereum development evolution? So, let’s figure it out. | by Rostyslav Bortman | Coinmonks | Medium

debugging — fantastic feature. Go ahead and try it yourself, I am sure you will be
pleasantly surprised!

Links:
Code samples:
https://github.com/RostyslavBortman/HardhatSample
Hardhat documentation:
https://hardhat.org/getting-started/#overview

Also, Read
The Best Crypto Trading Bot

Deribit Review | Options, Fees, APIs and Testnet

FTX Crypto Exchange Review

Bybit Exchange Review

The Best Bitcoin Hardware wallet

Crypto Copy Trading Platforms

The Best Crypto Tax Software

Best Crypto Trading Platforms

Best Crypto Lending Platforms

Ledger Nano S vs Trezor one vs Trezor T vs Ledger Nano X

BlockFi vs Celsius vs Hodlnaut

Bitsgap review — A Crypto Trading Bot That Makes Easy Money

Quadency Review- A Crypto Trading Bot Made For Professionals

PrimeXBT Review | Leverage Trading, Fee and Covesting

HaasOnline Review and Get a 10% discount

Ellipal Titan Review

https://medium.com/coinmonks/hardhat-ethereum-development-evolution-so-lets-figure-it-out-34f4656bc1a9 6/8
2/13/23, 4:06 AM Hardhat — ethereum development evolution? So, let’s figure it out. | by Rostyslav Bortman | Coinmonks | Medium

SecuX Stone Review

BlockFi Review | Earn up to 8.6% interests on your Crypto

Best Crypto APIs for Developers

Best Blockchain Analysis Tools

Crypto arbitrage guide: How to make money as a beginner

Top Bitcoin Node Providers

Best Crypto Charting Tool

What are the best books to learn about Bitcoin?

Get Best Software Deals Directly In Your Inbox

https://medium.com/coinmonks/hardhat-ethereum-development-evolution-so-lets-figure-it-out-34f4656bc1a9 7/8
2/13/23, 4:06 AM Hardhat — ethereum development evolution? So, let’s figure it out. | by Rostyslav Bortman | Coinmonks | Medium

Ethereum Smart Contracts Solidity

Sign up for Coinmonks


By Coinmonks

A newsletter that brings you day's best crypto news, Technical analysis, Discount Offers, and MEMEs directly in your
inbox, by CoinCodeCap.com Take a look.

Open
Emails in
willapp
be sent to waledmunker@gmail.com. Not you? Get unlimited access

Get this newsletter


Search Medium

https://medium.com/coinmonks/hardhat-ethereum-development-evolution-so-lets-figure-it-out-34f4656bc1a9 8/8
2/13/23, 4:08 AM Hardhat or Truffle? As a beginner blockchain developer, which one do I pick? | BuildBear Labs

Published in BuildBear Labs

Pari Tomar Follow

May 31, 2022 · 7 min read · Listen

Save

Hardhat or Truffle? As a beginner blockchain


developer, which one do I pick

In a blockchain developer’s life, one of the major pain point is to find the best-suited
framework or tool for him/her. People spend days or weeks finding the right tool for
them.

Similarly, in the Blockchain world, one of the major debate is on choosing between
Hardhat or Truffle.

https://medium.com/buildbear/hardhat-or-truffle-as-a-beginner-blockchain-developer-which-one-do-i-pick-34a6924a6983 1/13
2/13/23, 4:08 AM Hardhat or Truffle? As a beginner blockchain developer, which one do I pick? | BuildBear Labs

These development environments help developers to manage many of the tasks that
are inherent to developing decentralized applications and smart contracts.

If you just starting out your career in the blockchain world and, just like us, albeit
sometime back, are wondering which one to choose: Hardhat or Truffle, then you’re at
the right place!! 🥳🥳 In the below paragraphs, we have discussed both these
frameworks and have proceeded further to do a small comparison of sorts.

Hardhat Tool

Hardhat is an Ethereum development environment for developers that allows performing


frequent tasks.

Other than just deploying and running tests, Hardhat also provides some more
features that make it more powerful and unique.

Let’s consider these features one by one.

1. Hardhat Network

Hardhat comes built-in with Hardhat Network, a local Ethereum network node
designed for development providing multiple features like automated error messages,

https://medium.com/buildbear/hardhat-or-truffle-as-a-beginner-blockchain-developer-which-one-do-i-pick-34a6924a6983 2/13
2/13/23, 4:08 AM Hardhat or Truffle? As a beginner blockchain developer, which one do I pick? | BuildBear Labs

mainnet forking, and, mining modes.

So if you’re using Hardhat, then by default you’re already using Hardhat Network. It
mines a block with each transaction that it receives, in order and with no delay.

2. Plugins

Next up is Plugins.

Plugins, in simpler words, are extensions that can be loaded on a program to improve
its functionality.

There are 30+ plugins used in development with Hardhat which is why it is considered
the backbone of Hardhat.

We have listed some of the popular plugins below with their functionalities:

@nomiclabs/hardhat-ethers: It allows developers to inject ethers.js into the


Hardhat Runtime Environment.

@nomiclabs/hardhat-waffle: It allows you to add a Waffle-compatible provider to


the Hardhat Runtime Environment.

@nomiclabs/hardhat-etherscan: It automatically verifies contracts on Etherscan

hardhat-gas-reporter: Gas reporter helps to acknowledge the gas usage per unit
test and average gas usage per method.

3. Testing

Hardhat provides a very simple procedure for testing smart contracts, providing
developers to write automated tests when building smart contracts.

Hardhat provides great documentation for understanding testing methods with


Hardhat.

If you’re new to Hardhat Testing, try our previous article to get a better understanding of
Hardhat Testing.

https://medium.com/buildbear/hardhat-or-truffle-as-a-beginner-blockchain-developer-which-one-do-i-pick-34a6924a6983 3/13
2/13/23, 4:08 AM Hardhat or Truffle? As a beginner blockchain developer, which one do I pick? | BuildBear Labs

The Universe of Truffle Tools

Like Hardhat, Truffle is also a development environment dedicated to Ethereum


blockchain.

Truffle is a highly popular development framework and provides a large community


behind the tool.

For decentralized applications development, the developer uses Truffle Suite.

The Truffle Suite is an ecosystem for Web3 development that consists of three different
tools: Truffle, Ganache, and Drizzle

https://medium.com/buildbear/hardhat-or-truffle-as-a-beginner-blockchain-developer-which-one-do-i-pick-34a6924a6983 4/13
2/13/23, 4:08 AM Hardhat or Truffle? As a beginner blockchain developer, which one do I pick? | BuildBear Labs

Truffle: It is a development environment that uses the EVM for smart contract
development.

Ganache: Ganache is a tool used to set up your own local Ethereum blockchain that
you can use to deploy and test your smart contracts.

Other than that, Ganache enables developers to avoid paying unnecessary gas fees
during the developing process.

Drizzle: Drizzle is a collection of frontend libraries with a Redux store as its basis.

With this, the frontend development becomes a lot easier for the developers.

Truffle offers several different features like:

1. Smart Contract Management:

Truffle helps you manage the artifacts of the smart contracts so that you can focus on
the other parts of the development process and spend less time on the file
organization.

2. Scriptable Migration and Deployment:

With Truffle, you can write deployment scripts that allow you to account for the fact
that your Dapps will change over time.

3. Powerful Interactive Console:

Truffle provides 2 different consoles to choose the best tool for your needs.
https://medium.com/buildbear/hardhat-or-truffle-as-a-beginner-blockchain-developer-which-one-do-i-pick-34a6924a6983 5/13
2/13/23, 4:08 AM Hardhat or Truffle? As a beginner blockchain developer, which one do I pick? | BuildBear Labs

(A) Truffle Console: A basic interactive console connecting to any Ethereum client. To
launch the console, use the truffle console command. When you load the console,
you'll immediately see the following prompt:

Truffle console will let you connect with the contracts deployed on the EVM client and
interact with the contracts in a manner similar to the one that you would use through
javascript.

(B) Truffle Develop: An interactive console that also spawns a development blockchain.
It serves the same purpose as the hardhat node

You can simply launch the Truffle Develop by using the truffle develop command

https://medium.com/buildbear/hardhat-or-truffle-as-a-beginner-blockchain-developer-which-one-do-i-pick-34a6924a6983 6/13
2/13/23, 4:08 AM Hardhat or Truffle? As a beginner blockchain developer, which one do I pick? | BuildBear Labs

4. Truffle Dashboard:

Recently, Truffle has introduced Truffle Dashboard, providing an easier way to use your
existing Metamask wallet for your deployments and transactions. Using Truffle
Dashboard is not only easy but is a plug and play. You can use the Truffle Dashboard
inside any Hardhat projects also. Truffle has provided great documentation to follow
along and use Truffle Dashboard in your project.

Which one is more powerful?


Let us compare some of their features and get a final answer to our question!! 💪

1. Debugging

https://medium.com/buildbear/hardhat-or-truffle-as-a-beginner-blockchain-developer-which-one-do-i-pick-34a6924a6983 7/13
2/13/23, 4:08 AM Hardhat or Truffle? As a beginner blockchain developer, which one do I pick? | BuildBear Labs

Solidity is hard to debug. You just get an error message when something breaks and
more often than not, it is painful to debug what exactly went wrong.

Thankfully, Hardhat introduced something known as the console.log feature for


Solidity.

So you can simply import the console plugin and can use it inside your functions.

This is what it looks like:

Add some console.log inside the function

https://medium.com/buildbear/hardhat-or-truffle-as-a-beginner-blockchain-developer-which-one-do-i-pick-34a6924a6983 8/13
2/13/23, 4:08 AM Hardhat or Truffle? As a beginner blockchain developer, which one do I pick? | BuildBear Labs

The logging output will show when you run your tests:

https://medium.com/buildbear/hardhat-or-truffle-as-a-beginner-blockchain-developer-which-one-do-i-pick-34a6924a6983 9/13
2/13/23, 4:08 AM Hardhat or Truffle? As a beginner blockchain developer, which one do I pick? | BuildBear Labs

The EVM created by hardhat specifically supports this feature and hence is native to
Hardhat Node. This feature alone is a heavy pro for Hardhat.

On the other hand, Truffle has been improving its debugger and it also has some
plugins for it but Hardhat is considered a more easier and powerful tool used for
debugging.

2. Libraries (Ethers and Web3)


Hardhat uses ethersjs by default but can be easily modified to use Web3. Whereas,
Truffle uses Web3 as default plugin for development.

You can also use Etherjs with Truffle but it is considered to be trickier and hard to
implement.

While ethers-js and web3-js are similar, there is a very high uptick in the number of
developers using ethers-js as default; this should presumably give you some hint on
what you could / should consider for developing.

3. Local Ethereum Network Node


Hardhat comes inbuilt with Hardhat Node. However, it does not have a GUI for
developers to see account info in real-time.

Truffle, on the other hand, uses Ganache which has to be set up separately. However, it
comes with both a CLI and a GUI version allowing flexibility for the developer.

If you prefer the GUI you should choose Ganache.

4. Deployment
For deploying a contract, Hardhat uses basic javascript scripts to deploy, so it’s easier to
get started with it and is relatively simple to use.

Whereas, Truffle uses a migration-based deployment procedure (which are js files


themselves, but have a sequential order of execution) which is a bit more complicated for a
beginner, but can be helpful in the long term keeping in mind that your deployment
needs might change in the future.

But for ease of getting started with deployment, hardhat definitely takes the prize.

https://medium.com/buildbear/hardhat-or-truffle-as-a-beginner-blockchain-developer-which-one-do-i-pick-34a6924a6983 10/13
2/13/23, 4:08 AM Hardhat or Truffle? As a beginner blockchain developer, which one do I pick? | BuildBear Labs

5. Testing
To perform various tests, both Truffle and Hardhat use the Chai assertion library and
Mocha as their testing framework but hardhat also includes waffle. They’re both strong
when it comes to testing.

6. Statistics
Before Hardhat was launched, Web3 was the most popular framework for testing out
smart contracts.

Later on, now you can see that the trend changes over time, and Hardhat has gained
more popularity as compared Truffle.

According to the NPMJS Statistics, Truffle has almost 30k weekly downloads. Whereas,
Hardhat has around 86k weekly downloads, which is twice as compared Truffle’s.

7. Availability of Support / Helping Hand


Truffle’s Github community is quite active and helpful, whereas Hardhat provides a
Discord server for their community support. It must be noted that the entire Truffle
offering is supported by Consensys and hence you can expect a “support helpdesk”
treatment. Hardhat too is developed and managed through an organization: the Nomic

https://medium.com/buildbear/hardhat-or-truffle-as-a-beginner-blockchain-developer-which-one-do-i-pick-34a6924a6983 11/13
2/13/23, 4:08 AM Hardhat or Truffle? As a beginner blockchain developer, which one do I pick? | BuildBear Labs

Foundation and has an amazing and equally good support system through its discord
server.

Conclusion
It is really hard to say which is the best. The choice of Truffle vs Hardhat comes down
to one’s own preferences and use cases, as they both are two powerful tools.

If you’re absolutely new to both frameworks, then you should definitely explore both of
them and decide which one is the best for ‘you’.

However, we hope this article was able to give you an insight into the differences
between them and was able to help you to find which one to use.

Tell us which framework do you prefer over the other by tagging us on Twitter at
@uv_labs

Give us a clap if you liked our work.

Authors (open to feedback): 👇

Pari Tomar, Mayon Francis and Amateur-Dev

Hardhat Truffle Web 3 Blockchain Solidity

48 1

Sign up for Biting the Blockchain Bullet


By BuildBear Labs

Beginner friendly, simple to understand and easy to execute steps to build a career in blockchain Take a look.

https://medium.com/buildbear/hardhat-or-truffle-as-a-beginner-blockchain-developer-which-one-do-i-pick-34a6924a6983 12/13
2/13/23, 4:08 AM Hardhat or Truffle? As a beginner blockchain developer, which one do I pick? | BuildBear Labs

Emails will be sent to waledmunker@gmail.com. Not you?

Get this newsletter


Open in app Get unlimited access

Search Medium

https://medium.com/buildbear/hardhat-or-truffle-as-a-beginner-blockchain-developer-which-one-do-i-pick-34a6924a6983 13/13
2/13/23, 4:11 AM How to Setup Hardhat and compile, test and deploy contracts using it ? | by Dheeraj Kumar | Medium

Dheeraj Kumar Follow

Jul 22, 2021 · 2 min read · Listen

Save

How to Setup Hardhat and compile, test and


deploy contracts using it ?
This tutorial is about how to setup Hardhat and how to compile, test and deploy smart
contract using this.

Firstly, Hardhat is basically a development environment to compile, deploy, test and


debug Ethereum smart contracts. It serves as an alternative to truffle. However, it is a
lot better than the latter. Hardhat had a built-in Hardhat Network (like Ganache, your
local blockchain) designed for development. Its main functionality focuses around
Solidity, debugging, featuring stack traces, console.log() and explicit error messages
when transactions fail.

Hardhat is used through local installation in your project.

To install it, create an npm project by going to an empty folder, running npm init in the
terminal.

Then, run npm install — save-dev hardhat to install hardhat as a development


dependency.

Create your Hardhat project by running npx hardhat in project folder.

Then you’ll get two options:

1. Create a sample project

https://medium.com/@imdheeraj28/how-to-setup-hardhat-and-compile-test-and-deploy-contracts-using-it-30b1d57b4602 1/3
2/13/23, 4:11 AM How to Setup Hardhat and compile, test and deploy contracts using it ? | by Dheeraj Kumar | Medium

2. create an empty hardhat.config.js file

If you select the second option, an empty hardhat.config.js file will be created and you
can then configure the dependencies as per your requirements (we’ll discuss about
this in next article).

Follow the steps to get an idea how to compile, test and deploy contracts.

Select the option to create a sample project.

Then, you’ll have to install hardhat-waffle and hardhat-ethers.

You can use hardhat-waffle plugin to build tests for smart contract using Waffle in
Hardhat and hardhat-ethers brings to you the Ethereum library ethers.js that allows
you to interact with the Ethereum blockchain in a easier way.

You can install it by running npm install — save-dev @nomiclabs/hardhat-ethers


ethers chai @nomiclabs/hardhat-waffle ethereum-waffle

To get an idea about what’s there in hardhat for you, run npx hardhat in your project
folder. This will give you a list of built-in tasks.
To execute any task, say you want to check version( — version), run npx hardhat —
version

Or if you want to execute accounts, run npx hardhat accounts

Compiling your contracts: You’ll find a sample contract in our project. However, you
can add your own. To compile it, simply run: npx hardhat compile

The sample project comes with tests that use waffle and ethers.js . You would see a
sample-test.js in test folder. You can write your own tests in your project.

You can run your tests with npx hardhat test.

Next, to deploy your contracts we’ll use Hardhat script. The sample code is there inside
scripts/ in the sample-script.js file

Run it with npx hardhat run scripts/sample-script.js

https://medium.com/@imdheeraj28/how-to-setup-hardhat-and-compile-test-and-deploy-contracts-using-it-30b1d57b4602 2/3
2/13/23, 4:11 AM How to Setup Hardhat and compile, test and deploy contracts using it ? | by Dheeraj Kumar | Medium

And whoa! You’re done. You have deployed contract to the local Hardhat Network.

Blockchain Truffle Ethereum Hardhat Solidity

Get an email whenever Dheeraj Kumar publishes.


Emails will be sent to waledmunker@gmail.com. Not you?

Subscribe
Open in app Get unlimited access

Search Medium

https://medium.com/@imdheeraj28/how-to-setup-hardhat-and-compile-test-and-deploy-contracts-using-it-30b1d57b4602 3/3
2/13/23, 4:13 AM Writing your first smart contract with Hardhat | Coinmonks

Published in Coinmonks

Foad Rashidi Follow

Aug 13, 2022 · 6 min read · Listen

Save

Writing your first smart contract with Hardhat

Everyone loves Remix, but you may want to have your files locally and test your
contracts offline! Here comes the Hardhat. Hardhat is a development environment to
write and deploy your contracts. It gives you a variety of plugins and accessibilities to
make everything easier for you. It has many tools to deploy, run, test, and debug your
contracts. Without further ado, Let’s see how to write your first contract with it.

Setup the project

https://medium.com/coinmonks/writing-your-first-smart-contract-with-hardhat-b93e8d07eaeb 1/23
2/13/23, 4:13 AM Writing your first smart contract with Hardhat | Coinmonks

As a starting point, you should install npm on your device. If it is already installed, so
good for you. If not, you can use this tutorial to install it. (Remember that Hardhat
suggests using Node.js version 12 to 16. Although it works on version 18 as I used)

Then, we create a directory for our project.

mkdir awesome_contract && cd $_

Follow these commands to initialize the npm and install the Hardhat plugin.

npm init

https://medium.com/coinmonks/writing-your-first-smart-contract-with-hardhat-b93e8d07eaeb 2/23
2/13/23, 4:13 AM Writing your first smart contract with Hardhat | Coinmonks

npm install --save-dev hardhat@2.9.9

npx hardhat

Set the type of the project to Advanced sample project that uses TypeScript. It gives us more options.

Your Node.js project should now have the hardhat library if everything went smoothly.

https://medium.com/coinmonks/writing-your-first-smart-contract-with-hardhat-b93e8d07eaeb 3/23
2/13/23, 4:13 AM Writing your first smart contract with Hardhat | Coinmonks

https://medium.com/coinmonks/writing-your-first-smart-contract-with-hardhat-b93e8d07eaeb 4/23
2/13/23, 4:13 AM Writing your first smart contract with Hardhat | Coinmonks

The file structure should be something like this.

Install Hardhat-deploy
This hardhat plugin adds a mechanism to deploy contracts to any network, keeping
track of them and replicating the same environment for testing.

You can easily install it with this simple command.

npm install -D hardhat-deploy

One last thing to do is to import hardhat-deploy in the hardhat.config.ts file.

import "hardhat-deploy";

Get the API keys and private key for the deployment
1. Etherscan

https://medium.com/coinmonks/writing-your-first-smart-contract-with-hardhat-b93e8d07eaeb 5/23
2/13/23, 4:13 AM Writing your first smart contract with Hardhat | Coinmonks

The first API key that you need to get is for the Etherscan. Go here and create an
account for yourself.

Yes! Ethereum’s price was $1712. I also find it hard to believe.

Then go to the API keys section and create a new API key.

https://medium.com/coinmonks/writing-your-first-smart-contract-with-hardhat-b93e8d07eaeb 6/23
2/13/23, 4:13 AM Writing your first smart contract with Hardhat | Coinmonks

Now that you have the API key, save it somewhere for yourself because we are going to
use it soon.

2. Infura

When we write our contracts, we need to test them before we deploy them to the
mainnet. One of the popular testnet is the Ropsten. Infura gives us access to this
testnet. So we need to create an account and take access to the Ropsten testnet. First,
you need to go here and create an account.

https://medium.com/coinmonks/writing-your-first-smart-contract-with-hardhat-b93e8d07eaeb 7/23
2/13/23, 4:13 AM Writing your first smart contract with Hardhat | Coinmonks

Then go to your dashboard and create a new key.

Be aware that the network of the project should be Web3

Once you create it, go to the key page. Change the network endpoint to Ropsten and
save the URL for later.

https://medium.com/coinmonks/writing-your-first-smart-contract-with-hardhat-b93e8d07eaeb 8/23
2/13/23, 4:13 AM Writing your first smart contract with Hardhat | Coinmonks

3. MetaMask

The last thing to do is that you should create a test wallet and export its private key
(Don’t use your main wallet here cause it leads to loss of properties).

You can use MetaMask on almost anything, here we use the Brave (Yes, it’s better than
Chrome) extension.

https://medium.com/coinmonks/writing-your-first-smart-contract-with-hardhat-b93e8d07eaeb 9/23
2/13/23, 4:13 AM Writing your first smart contract with Hardhat | Coinmonks

After you installed the extension, follow these steps to complete the wallet creation
process.

Fox’s head moves with the mouse cursor. Pretty cool, ha?

https://medium.com/coinmonks/writing-your-first-smart-contract-with-hardhat-b93e8d07eaeb 10/23
2/13/23, 4:13 AM Writing your first smart contract with Hardhat | Coinmonks

Hit Create a Wallet button to create a new one.

It’s up to you to share your data with them or not.

https://medium.com/coinmonks/writing-your-first-smart-contract-with-hardhat-b93e8d07eaeb 11/23
2/13/23, 4:13 AM Writing your first smart contract with Hardhat | Coinmonks

Choose a password for your MetaMask account.

Write down your 12-word recovery phrase somewhere safe. You might need it to recover your wallet in the future.

https://medium.com/coinmonks/writing-your-first-smart-contract-with-hardhat-b93e8d07eaeb 12/23
2/13/23, 4:13 AM Writing your first smart contract with Hardhat | Coinmonks

Now, hit the three dots button and open Account details.

Click Export Private Key and enter your MetaMask password. Finally, it gives you the private key. Write it down
cause we need it soon.

https://medium.com/coinmonks/writing-your-first-smart-contract-with-hardhat-b93e8d07eaeb 13/23
2/13/23, 4:13 AM Writing your first smart contract with Hardhat | Coinmonks

So now we got what we need. Go to the main directory of your project. Rename the
.env.example file into .env. Fill the environment variables with the ones that you got
from the above steps.

Writing the script


Currently, there is a simple contract called Greeter.sol in the contracts folder. Let’s ignore
that and write a simple ERC20 token. There are many implementations for the ERC20
token, but here we use the OpenZeppelin’s.

OpenZeppelin is a framework that provides blockchain standards to help you write


secure smart contracts. Here, we’re gonna add its contracts to our project and then use
them in our smart contract.

npm install --save @openzeppelin/contracts

After the installation, you can find the contracts in the node_modules directory.

https://medium.com/coinmonks/writing-your-first-smart-contract-with-hardhat-b93e8d07eaeb 14/23
2/13/23, 4:13 AM Writing your first smart contract with Hardhat | Coinmonks

https://medium.com/coinmonks/writing-your-first-smart-contract-with-hardhat-b93e8d07eaeb 15/23
2/13/23, 4:13 AM Writing your first smart contract with Hardhat | Coinmonks

Now that everything is ready, create a new file in the contracts folder (I’m calling it
SimpleToken.sol) and start writing the contract.

https://medium.com/coinmonks/writing-your-first-smart-contract-with-hardhat-b93e8d07eaeb 16/23
2/13/23, 4:13 AM Writing your first smart contract with Hardhat | Coinmonks

1 // SPDX-License-Identifier: MIT
2
3 pragma solidity ^0.8.0;
4
5 import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
6
7 contract SimpleToken is ERC20 {
8 address public owner;
9 struct Minter {
10 bool canMint;
11 uint256 allowance;
12 }
13 mapping(address => Minter) private minters;
14
15 modifier onlyOwner() {
16 require(msg.sender == owner, "Caller is not the owner.");
17 _;
18 }
19
20 modifier onlyMinters() {
21 require(minters[msg.sender].canMint == true, "Only minters can call this function");
22 _;
23 }
24
25 constructor(
26 string memory name,
27 string memory symbol,
28 uint256 initialSupply
29 ) ERC20(name, symbol) {
30 owner = msg.sender;
31 minters[owner].canMint = true;
32 _mint(msg.sender, initialSupply);
33 }
34
35 function mint(address account, uint256 amount) public onlyMinters {
36 require(msg.sender == owner || minters[msg.sender].allowance >= amount, "You don't have all
37 _mint(account, amount);
38 minters[msg.sender].allowance -= amount;
39 }
40
41 function addMinter(address minterAddress, uint256 allowance) public onlyOwner {
Open
42 in app Getexists.");
require(minters[minterAddress].canMint == false, "This minter is already unlimited access

43 minters[minterAddress].canMint = true;
44 Search Medium
minters[minterAddress].allowance = allowance;
45 }
https://medium.com/coinmonks/writing-your-first-smart-contract-with-hardhat-b93e8d07eaeb 17/23
2/13/23, 4:13 AM Writing your first smart contract with Hardhat | Coinmonks
45 }
This
46
is a simple ERC20 token I wrote. Other than basic token functionalities, I added
one
47 more. The owner
function of the contract
removeMinter(address can give allowance
minterAddress) to anybody
public onlyOwner { to mint the token.
It’s
48 not that hard, but it’s a good!=practice
require(minterAddress to advance
owner, "Owner can't be your solidity
removed from theskills.
minters.");
49 require(minters[minterAddress].canMint == true, "This minter doesn't exist.");
50 minters[minterAddress].canMint = false;
You can compile the contracts with this command to see if there is anything wrong
51 minters[minterAddress].allowance = 0;
with
52
your} code.
53
54 function setMintAllowance(address minterAddress, uint256 allowance) public onlyOwner {
55npx hardhat compile
require(minters[minterAddress].canMint == true, "This minter doesn't exist.");
56 minters[minterAddress].allowance = allowance;
57 }

After
58 }that, you need to write a deploy script to send your contract to the blockchain.

Create a newhosted
SimpleToken.sol file in the
with scripts
❤ by GitHubdirectory (Let’s call it deployToken.ts). This is where you
view raw

should know a little bit of TypeScript. It’s simple and don’t worry, we won’t use it that
much.

https://medium.com/coinmonks/writing-your-first-smart-contract-with-hardhat-b93e8d07eaeb 18/23
2/13/23, 4:13 AM Writing your first smart contract with Hardhat | Coinmonks

1 // We require the Hardhat Runtime Environment explicitly here. This is optional


2 // but useful for running the script in a standalone fashion through `node <script>`.
3 //
4 // When running the script with `npx hardhat run <script>` you'll find the Hardhat
5 // Runtime Environment's members available in the global scope.
6 import { ethers } from "hardhat";
7
8 async function main() {
9 // Hardhat always runs the compile task when running scripts with its command
10 // line interface.
11 //
12 // If this script is run directly using `node` you may want to call compile
13 // manually to make sure everything is compiled
14 // await hre.run('compile');
15
16 // We get the contract to deploy
17 const SimpleToken = await ethers.getContractFactory("SimpleToken");
18 const simpleToken = await SimpleToken.deploy("Awesome Mintable Token", "AMT", 100000);
19
20 await simpleToken.deployed();
21
22 console.log("Your token deployed to:", simpleToken.address);
23 }
24
25 // We recommend this pattern to be able to use async/await everywhere
26 // and properly handle errors.
27 main().catch((error) => {
28 console.error(error);
29 process.exitCode = 1;
30 });

deployToken.ts hosted with ❤ by GitHub view raw

The deployment script consists of 4 important parts (Line 17–22). First, we get the
contract object. Second, we fill the contract’s constructor. Next, we wait until the
contract sent to the blockchain and finally, we print the contract address in the
console.

https://medium.com/coinmonks/writing-your-first-smart-contract-with-hardhat-b93e8d07eaeb 19/23
2/13/23, 4:13 AM Writing your first smart contract with Hardhat | Coinmonks

You can easily deploy the contract with this simple command.

npx hardhat --network ropsten run scripts/deployToken.ts

As you can see, the contract is deployed to the Ropsten network and you can see it on
the explorer.

The contract is not verified yet

https://medium.com/coinmonks/writing-your-first-smart-contract-with-hardhat-b93e8d07eaeb 20/23
2/13/23, 4:13 AM Writing your first smart contract with Hardhat | Coinmonks

Our Awesome Mintable Token :)

Verifying the contract


Every contract that you send to the blockchain is unverified in the first place. The
problem is that the contract is in ByteCode and people can’t see your code so they can’t
trust you.

You can send your code to the blockchain and tell the explorers to show your code.

With the help of the Hardhat, it can simply be done by a single command. You just
need the contract address plus the data that you used in the contract’s constructor to
create it.

npx hardhat verify --network ropsten


0x9c6BF2C5954327f62c3536eC9CC00bc9b48341D0 "Awesome Mintable Token"
"AMT" "100000"

https://medium.com/coinmonks/writing-your-first-smart-contract-with-hardhat-b93e8d07eaeb 21/23
2/13/23, 4:13 AM Writing your first smart contract with Hardhat | Coinmonks

It gives us the contract’s code in the explorer and when you go to the website, you can
see your code that is verified and is public to read.

New to trading? Try crypto trading bots or copy


trading

Hard Hat Solidity Smart Contracts Ethereum Web 3

https://medium.com/coinmonks/writing-your-first-smart-contract-with-hardhat-b93e8d07eaeb 22/23
2/13/23, 4:13 AM Writing your first smart contract with Hardhat | Coinmonks

Sign up for Coinmonks


By Coinmonks

A newsletter that brings you day's best crypto news, Technical analysis, Discount Offers, and MEMEs directly in your
inbox, by CoinCodeCap.com Take a look.

Emails will be sent to waledmunker@gmail.com. Not you?

Get this newsletter

https://medium.com/coinmonks/writing-your-first-smart-contract-with-hardhat-b93e8d07eaeb 23/23
2/13/23, 4:15 AM Deploy Smart Contracts Using Hardhat | by Technologies In Industry 4.0 | Nerd For Tech | Medium

Published in Nerd For Tech

Technologies In Industry 4.0 Follow

Nov 3, 2021 · 4 min read · Listen

Save

Deploy Smart Contracts Using Hardhat

Introduction
Smart contracts are just programs kept on a blockchain. That runs when preset
conditions are met. They normally are used to automate the performance of an
https://medium.com/nerd-for-tech/deploy-smart-contracts-using-hardhat-3bf9e6e07d2a 1/7
2/13/23, 4:15 AM Deploy Smart Contracts Using Hardhat | by Technologies In Industry 4.0 | Nerd For Tech | Medium

agreement. Therefore, that all participants may be directly sure of the outcome,
deprived of any mediator’s participation or time loss.

Hardhat plugin enhances a mechanism to deploy contracts to any network. It makes


available an environment to compile, test and deploy Solidity smart contracts. In this
post, we will understand that how to deploy a smart contract with Hardhat.

Description
Hardhat as well improves a mechanism to associate names to addresses. Therefore,
test and deployment scripts may be reconfigured by merely shifting the address a
name points to, permitting different configurations per network. This also
consequences in much clearer tests and deployment scripts.

Main features
Hardhats trust ethers.js, the 2nd generation Ethereum JavaScript API library.

It mixes well with TypeScript — a second-generation JavaScript.

It brings a better debugging ability with console.log functionality in Solidity code.

Deterministic deployment through networks.

Ability to access deployment from mate networks.

Introducing products from external sources like npm packages, with truffle help.

Chain configuration export.

Listing deployed contracts’ addresses and their abis.

Library linking at time of deployment.

Set-Up
Make ready the project and install Hardhat as a dependency.

$ npm init --yes


$ npm install --save-dev hardhat

https://medium.com/nerd-for-tech/deploy-smart-contracts-using-hardhat-3bf9e6e07d2a 2/7
2/13/23, 4:15 AM Deploy Smart Contracts Using Hardhat | by Technologies In Industry 4.0 | Nerd For Tech | Medium

After installation, we may run npx hardhat. This will make a Hardhat config file
(hardhat.config.js) in the project directory.

$ 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.2.1
What do you want to do? · Create an empty hardhat.config.js
Config file created

Solidity source files (.sol) are stored in a contacts directory. This is the same as the
src directory we may be familiar with from other languages.

We may now write our first simple smart contract, named Box.

It would allow people to store a value that can be later saved.

We will save this file as contracts/Box.sol.

Each .sol file should have the code for a single contract, and be called after it.

/ contracts/Box.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Box {
uint256 private _value;

https://medium.com/nerd-for-tech/deploy-smart-contracts-using-hardhat-3bf9e6e07d2a 3/7
2/13/23, 4:15 AM Deploy Smart Contracts Using Hardhat | by Technologies In Industry 4.0 | Nerd For Tech | Medium

// Emitted when the stored value changes


event ValueChanged(uint256 value);
// Stores a new value in the contract
function store(uint256 value) public {
_value = value;
emit ValueChanged(value);
}
// Reads the last stored value
function retrieve() public view returns (uint256) {
return _value;
}
}

We now will generate a script to deploy our Box contract. We would save this file as
scripts or deploy.js.

// scripts/deploy.js
async function main () {
// We receive the contract to deploy
const Box = await ethers.getContractFactory('Box');
console.log('Deploying Box...');
const box = await Box.deploy();
await box.deployed();
console.log('Box deployed to:', box.address);
}
main()
.then(() => process.exit(0))
.catch(error => {
console.error(error);
process.exit(1);

https://medium.com/nerd-for-tech/deploy-smart-contracts-using-hardhat-3bf9e6e07d2a 4/7
2/13/23, 4:15 AM Deploy Smart Contracts Using Hardhat | by Technologies In Industry 4.0 | Nerd For Tech | Medium

});

Now, install ethers in the script by using the below command.

$ npm install --save-dev @nomiclabs/hardhat-ethers ethers

Then, we need to add in the configuration.

/ hardhat.config.js
require('@nomiclabs/hardhat-ethers');
...
module.exports = {
...
};

We can deploy the Box contract to the local network (Hardhat Network) by using the
run command:

$ npx hardhat run --network localhost scripts/deploy.js


Deploying Box...
Box deployed to: 0x5FbDB2315678afecb367f032d93F642f64180aa3

Contract
We will import a Solidity contract from Open Zeppelin.

Create a file named ERC20.sol under a new folder contract.

The ERC20 contract would take name and symbol arguments at deployment.

/SPDX-License-Identifier: Unlicense
https://medium.com/nerd-for-tech/deploy-smart-contracts-using-hardhat-3bf9e6e07d2a 5/7
2/13/23, 4:15 AM Deploy Smart Contracts Using Hardhat | by Technologies In Industry 4.0 | Nerd For Tech | Medium

pragma solidity 0.8.3;


import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
contract _ERC20 is ERC20 {
constructor (string memory _name, string memory _symbol)
ERC20(_name, _symbol) {}
}

Script Deployment
We will control the hardhat-deploy plugin to deploy the contracts.

It permits us to perform and track deployments, besides a range of features.

The first deployment script, located in the deploy folder, would be the following:

The deployer constant remains the namedAccounts feature in action. It enables us to


associate custom names to addresses based on their index in the accounts array of the
given network in hardhat.config.js

In our example, therefore, setting deployer to zero permits us to access the private key
using const { deployer } = await getNamedAccounts().

Otherwise, the args must be in the order expected by the smart contract, and tags can
be used to identify or group contracts for deployment.

Deployment
We can compile our contract with the following command:

$ npx hardhat deploy --network kovan --tags ERC20

For more details visit:https://www.technologiesinindustry4.com/2021/11/deploy-smart-


contracts-using-hardhat.html

https://medium.com/nerd-for-tech/deploy-smart-contracts-using-hardhat-3bf9e6e07d2a 6/7
2/13/23, 4:15 AM Deploy Smart Contracts Using Hardhat | by Technologies In Industry 4.0 | Nerd For Tech | Medium

Blockchain Blockchain Technology Blockchain Development Smart Contracts


Hard Hat

Sign up for NFT Weekly Digest


By Nerd For Tech

Subscribe to our weekly News Letter to receive top stories from the Industry Professionals around the world Take a look.

Open
Emails in
willapp
be sent to waledmunker@gmail.com. Not you? Get unlimited access

Get this newsletter


Search Medium

https://medium.com/nerd-for-tech/deploy-smart-contracts-using-hardhat-3bf9e6e07d2a 7/7
2/13/23, 4:17 AM How to deploy your first smart contract on Ethereum with Solidity and Hardhat | by StErMi | Medium

StErMi Follow

Sep 17, 2021 · 12 min read · Listen

Save

How to deploy your first smart contract on


Ethereum with Solidity and Hardhat

Hardhat

I was planning to release a tutorial on how to deploy your first NFT smart contract but
while I was writing it I understood that more than half of the content was about how to
set up Hardhat to have the perfect development environment ready to go for your next
project.

So let’s start from here and when I’ll release the NFT tutorial you can leverage the work
we have done today to be ready instantly to start developing your next smart contract.
https://stermi.medium.com/how-to-deploy-your-first-smart-contract-on-ethereum-with-solidity-and-hardhat-22f21d31096e 1/26
2/13/23, 4:17 AM How to deploy your first smart contract on Ethereum with Solidity and Hardhat | by StErMi | Medium

Shall we proceed?

What are you going to learn today?


Configure Hardhat to compile, deploy, test, and debug your Solidity code

Write a smart contract

Test your smart contract

Deploy your smart contract on Rinkeby

Get your smart contract verified by Etherscan

Hardhat
Hardhat is the core tool we will be using today and a must-have if you need to develop
and debug your smart contract locally before deploying it on the test net and then on
the main net.

What is Hardhat?
Hardhat is a development environment to compile, deploy, test, and debug your
Ethereum software. It helps developers manage and automate the recurring tasks that
are inherent to the process of building smart contracts and dApps, as well as easily
introducing more functionality around this workflow. This means compiling, running,
and testing smart contracts at the very core.

Why use hardhat?


You can run Solidity locally to deploy, run, test, and debug your contracts without
dealing with live environments.

You get Solidity stack traces, console.log, and explicit error messages when
transactions fail. Yeah, you heard it right, console.log in your Solidity contract!

Tons of plugins to add cool functionalities and allows you to integrate your existing
tools. We will use a couple of them to feel that magic!

Full native support for TypeScript.

Useful links to learn more

https://stermi.medium.com/how-to-deploy-your-first-smart-contract-on-ethereum-with-solidity-and-hardhat-22f21d31096e 2/26
2/13/23, 4:17 AM How to deploy your first smart contract on Ethereum with Solidity and Hardhat | by StErMi | Medium

Official website

Plugins

Documentation

Tutorial

GitHub Repository

Discord Community

Create your first Hardhat project


It’s time to open your Terminal, your Visual Studio code IDE, and start building!

What project are we going to build?


In this tutorial, we are going to build an “easy” smart contract. It will be pretty stupid
but our main goal here is to configure hardhat and deploy the contract, not for the
contract purpose.

What will the contract do?

Track the “purpose” of the contract in a string that will be publicly visible

You can change the purpose only if you pay more than the previous owner

You cannot change the purpose if you are already the owner

You can withdraw your ETH only if you are not the current purpose’s owner

Emit a PurposeChange event when the purpose has changed

Create the project, init it and configure Hardhat


Open your terminal and let’s go. We will call our project world-purpose!

mkdir world-purpose
cd world-purpose
npm init -y

https://stermi.medium.com/how-to-deploy-your-first-smart-contract-on-ethereum-with-solidity-and-hardhat-22f21d31096e 3/26
2/13/23, 4:17 AM How to deploy your first smart contract on Ethereum with Solidity and Hardhat | by StErMi | Medium

yarn add --dev hardhat


npx hardhat

With npx hardhat the hardhat wizard will kickstart helping you configure your project.

Choose Create a basic sample project

Choose the default Hardhat project root because in this tutorial we are only
configuring hardhat.

Confirm to add the .gitignore

Confirm to install the sample project's dependecies with yarn this will install some
required dependencies for your project that we will use along the way

Now your project structure should have these files/folder

contracts where all your contracts will be stored

scripts where all your scripts/tasks will be stored

test where your smart contract tests will be stored

hardhat.config.js where you will configure your hardhat project

Important hardhat commands and concepts you should master


Hardhat Configuration file

Hardhat Tasks

npx hardhat node — Run the node task to start a JSON-RPC server on top of Hardhat
Network (your local ethereum blockchain)

npx hardhat test — To run tests stored in the test folder

npx hardhat compile — To compile the entire project, building your smart contracts

npx hardhat clean — To clean the cache and delete compiled smart contracts

https://stermi.medium.com/how-to-deploy-your-first-smart-contract-on-ethereum-with-solidity-and-hardhat-22f21d31096e 4/26
2/13/23, 4:17 AM How to deploy your first smart contract on Ethereum with Solidity and Hardhat | by StErMi | Medium

npx hardhat run —-network <network> script/path — To run a specific script in a


specific network

Add TypeScript Support


As we said Hardhat supports typescript natively and we will be using it. Using
javascript or typescript doesn’t change much but this is my personal preference
because I think that it allows you to make fewer errors and understand better how to
use external libraries.

Let’s install some needed dependencies

yarn add --dev ts-node typescript


yarn add --dev chai @types/node @types/mocha @types/chai

Change the hardhat configuration file extension to .ts and update the content with
this

https://stermi.medium.com/how-to-deploy-your-first-smart-contract-on-ethereum-with-solidity-and-hardhat-22f21d31096e 5/26
2/13/23, 4:17 AM How to deploy your first smart contract on Ethereum with Solidity and Hardhat | by StErMi | Medium

1 import { task } from 'hardhat/config';


2 import '@nomiclabs/hardhat-waffle';
3
4 // This is a sample Hardhat task. To learn how to create your own go to
5 // https://hardhat.org/guides/create-task.html
6 task('accounts', 'Prints the list of accounts', async (taskArgs, hre) => {
7 const accounts = await hre.ethers.getSigners();
8
9 for (const account of accounts) {
10 console.log(account.address);
11 }
12 });
13
14 // You need to export an object to set up your config
15 // Go to https://hardhat.org/config/ to learn more
16 export default {
17 solidity: '0.8.4',
18 };

hardhat.config.ts hosted with ❤ by GitHub view raw

Now create a default tsconfig.json in the root of your project with this content

{
"compilerOptions": {
"target": "es2018",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"outDir": "dist"
},
"include": ["./scripts", "./test"],
"files": ["./hardhat.config.ts"]
}

Now update also the test file and script file to the typescript file type .ts and change
their code.

https://stermi.medium.com/how-to-deploy-your-first-smart-contract-on-ethereum-with-solidity-and-hardhat-22f21d31096e 6/26
2/13/23, 4:17 AM How to deploy your first smart contract on Ethereum with Solidity and Hardhat | by StErMi | Medium

1 import { expect } from 'chai';


2 import { ethers } from 'hardhat';
3
4 describe('Greeter', function () {
5 it("Should return the new greeting once it's changed", async function () {
6 const Greeter = await ethers.getContractFactory('Greeter');
7 const greeter = await Greeter.deploy('Hello, world!');
8 await greeter.deployed();
9
10 expect(await greeter.greet()).to.equal('Hello, world!');
11
12 const setGreetingTx = await greeter.setGreeting('Hola, mundo!');
13
14 // wait until the transaction is mined
15 await setGreetingTx.wait();
16
17 expect(await greeter.greet()).to.equal('Hola, mundo!');
18 });
19 });

sample-test.ts hosted with ❤ by GitHub view raw

https://stermi.medium.com/how-to-deploy-your-first-smart-contract-on-ethereum-with-solidity-and-hardhat-22f21d31096e 7/26
2/13/23, 4:17 AM How to deploy your first smart contract on Ethereum with Solidity and Hardhat | by StErMi | Medium

1 // We require the Hardhat Runtime Environment explicitly here. This is optional


2 // but useful for running the script in a standalone fashion through `node <script>`.
3 //
4 // When running the script with `npx hardhat run <script>` you'll find the Hardhat
5 // Runtime Environment's members available in the global scope.
6 import { ethers } from 'hardhat';
7
8 async function main() {
9 // Hardhat always runs the compile task when running scripts with its command
10 // line interface.
11 //
12 // If this script is run directly using `node` you may want to call compile
13 // manually to make sure everything is compiled
14 // await hre.run('compile');
15
16 // We get the contract to deploy
17 const Greeter = await ethers.getContractFactory('Greeter');
18 const greeter = await Greeter.deploy('Hello, Hardhat!');
19
20 await greeter.deployed();
21
22 console.log('Greeter deployed to:', greeter.address);
23 }
24
25 // We recommend this pattern to be able to use async/await everywhere
26 // and properly handle errors.
27 main()
28 .then(() => process.exit(0))
29 .catch((error) => {
30 console.error(error);
31 process.exit(1);
32 });

sample-script.ts hosted with ❤ by GitHub view raw

Let’s test that everything is working correctly

https://stermi.medium.com/how-to-deploy-your-first-smart-contract-on-ethereum-with-solidity-and-hardhat-22f21d31096e 8/26
2/13/23, 4:17 AM How to deploy your first smart contract on Ethereum with Solidity and Hardhat | by StErMi | Medium

npx hardhat test


npx hardhat node
npx hardhat run --network localhost scripts/sample-script.ts

Let’s add some Hardhat plugins and some code utilities

add solhint, solhint-plugin-prettier, and hardhat-solhint plugin


Now we want to add support to solhint a linting utility for Solidity code that will help
us to follow strict rules while we develop our smart contract. These rules a useful for
both follow the code style standard best practice and adhering to the best security
approaches.

solhint+solhint prettier

yarn add --dev solhint solhint-plugin-prettier prettier prettier-plugin-solidity

Add a .solhint.json configuration file in your root folder

{
"plugins": ["prettier"],
"rules": {
"prettier/prettier": "error"
}
}

Add a .prettierrc config file and add styles as you prefer. This is my personal choice

{
"arrowParens": "always",
"singleQuote": true,
"bracketSpacing": false,
"trailingComma": "all",
"printWidth": 120,
"overrides": [
{
"files": "*.sol",
"options": {
"printWidth": 120,

https://stermi.medium.com/how-to-deploy-your-first-smart-contract-on-ethereum-with-solidity-and-hardhat-22f21d31096e 9/26
2/13/23, 4:17 AM How to deploy your first smart contract on Ethereum with Solidity and Hardhat | by StErMi | Medium

"tabWidth": 4,
"useTabs": false,
"singleQuote": false,
"bracketSpacing": false,
"explicitTypes": "always"
}
}
]
}

If you want to know more about solhint and its prettier plugin checkout their
documentation site

Solhint

Prettier Plugin Solidity

Solhint plugin Prettier

hardhat-solhint

If you want to know more follow the Hardhat solhint plugin documentation.

yarn add --dev @nomiclabs/hardhat-solhint

and update the hardhat config adding this line to the import

import “@nomiclabs/hardhat-solhint”;

typechain for typed contract support


This part is totally optional. As I said I love typescript and I like to use it everywhere
whenever it’s possible. Adding support to contract types allow me to know perfectly
which functions are available, which parameters are needed of which type, and what
are they returning.

You could totally go without it but I highly suggest you follow this step.

Why typechain?

https://stermi.medium.com/how-to-deploy-your-first-smart-contract-on-ethereum-with-solidity-and-hardhat-22f21d31096e 10/26
2/13/23, 4:17 AM How to deploy your first smart contract on Ethereum with Solidity and Hardhat | by StErMi | Medium

Zero Config Usage — Run the compile task as normal, and Typechain artifacts will
automatically be generated in a root directory called typechain .

Incremental generation — Only recompiled files will have their types regenerated

Frictionless — return type of ethers.getContractFactory will be typed properly - no


need for casts

If you want to dig deeper into these projects and know all the possible configuration
options you can follow these links:

Typechain Hardhat

Typechain GitHub Repository

Let’s do it

yarn add --dev typechain @typechain/hardhat @typechain/ethers-v5

Add these imports to your Hardhat config file

import '@typechain/hardhat'
import '@nomiclabs/hardhat-ethers'
import '@nomiclabs/hardhat-waffle'

Add "resolveJsonModule": true to your tsconfig.json

Now when you compile your contract typechain will generate the corresponding types
into the typechain folder and you will be able to use it in your tests and web app!

Updated the tests file to use Typechain generated types

https://stermi.medium.com/how-to-deploy-your-first-smart-contract-on-ethereum-with-solidity-and-hardhat-22f21d31096e 11/26
2/13/23, 4:17 AM How to deploy your first smart contract on Ethereum with Solidity and Hardhat | by StErMi | Medium

1 import {ethers, waffle} from 'hardhat';


2 import chai from 'chai';
3
4 import GreeterArtifact from '../artifacts/contracts/Greeter.sol/Greeter.json';
5 import {Greeter} from '../typechain/Greeter';
6
7 const {deployContract} = waffle;
8 const {expect} = chai;
9
10 describe('Greeter', function () {
11 let greeter: Greeter;
12
13 it("Should return the new greeting once it's changed", async function () {
14 const signers = await ethers.getSigners();
15 greeter = (await deployContract(signers[0], GreeterArtifact, ['Hello, world!'])) as Greeter;
16
17 expect(await greeter.greet()).to.equal('Hello, world!');
18
19 const setGreetingTx = await greeter.setGreeting('Hola, mundo!');
20
21 // wait until the transaction is mined
22 await setGreetingTx.wait();
23
24 expect(await greeter.greet()).to.equal('Hola, mundo!');
25 });
26 });

sample-test.ts hosted with ❤ by GitHub view raw

Update scripts in package.json

This part is totally optional but it allow you to run command faster and preconfigure
them. Open your package.json and override the scripts section with these
commands:

"clean": "npx hardhat clean",


"chain": "npx hardhat node",
"deploy": "npx hardhat run --network localhost scripts/deploy.ts",
https://stermi.medium.com/how-to-deploy-your-first-smart-contract-on-ethereum-with-solidity-and-hardhat-22f21d31096e 12/26
2/13/23, 4:17 AM How to deploy your first smart contract on Ethereum with Solidity and Hardhat | by StErMi | Medium

"deploy:rinkeby": "npx hardhat run --network rinkeby


scripts/deploy.ts",
"test": "npx hardhat test"

Now if you want to simply run the Hardhat node you can write in your console yarn

chain and boom! We are ready to go!

If you have skipped the TypeScript part and you want to use only Javascript just change those
.ts back to .js and everything will work as expected.

Developing the smart contract


Ok, now we are really ready to go. Rename Greeter.sol in your contracts folder to
WorldPurpose.sol and we will start building from here.

Our contract needs to do these things:

Track the “purpose” of the contract in a struct

You can change the purpose only if you pay more than the previous owner

You cannot change the purpose if you are already the owner

You can withdraw your ETH only if you are not the current purpose’s owner

Emit a PurposeChange event when the purpose has changed

Concepts you should master


Variable Types

Mapping

Structs

Functions

Events

Payable functions

Smart Contract Code


https://stermi.medium.com/how-to-deploy-your-first-smart-contract-on-ethereum-with-solidity-and-hardhat-22f21d31096e 13/26
2/13/23, 4:17 AM How to deploy your first smart contract on Ethereum with Solidity and Hardhat | by StErMi | Medium

Let’s start by creating a Struct to store the Purpose information

/// @notice Purpose struct


struct Purpose {
address owner;
string purpose;
uint256 investment;
}

Let’s now define some state variables to track both the current Purpose and user’s
investment

/// @notice Track user investments


mapping(address => uint256) private balances;
/// @notice Track the current world purpose
Purpose private purpose;

Last but not least define an Event that will be emitted when a new World Purpose has
been set

/// @notice Event to track new Purpose


event PurposeChange(address indexed owner, string purpose, uint256
investment);

Let’s create some utility functions to get the current purpose and the user’s balance
that is still in the contract. We need to do that because balances and purpose variables
are private so they cannot be accessed directly from external contract/web3 apps. We
need to expose them via these functions

/**
@notice Getter for the current purpose
@return currentPurpose The current active World purpose
*/
function getCurrentPurpose() public view returns (Purpose memory
currentPurpose) {
https://stermi.medium.com/how-to-deploy-your-first-smart-contract-on-ethereum-with-solidity-and-hardhat-22f21d31096e 14/26
2/13/23, 4:17 AM How to deploy your first smart contract on Ethereum with Solidity and Hardhat | by StErMi | Medium

return purpose;
}
/**
@notice Get the total amount of investment you have made. It returns
both the locked and unloacked investment.
@return balance The balance you still have in the contract
*/
function getBalance() public view returns (uint256 balance) {
return balances[msg.sender];
}

Now let’s create the setPurpose function. It takes one parameter as input: _purpose .
The function must be payable because we want to accept some Ether in order to set
the purpose (those ethers will be withdrawable by the owner the purpose has been
overridden by someone else).

The transaction will revert if some conditions are not met:

_purpose input parameter is empty

the msg.value (amount of ether sent with the transaction) is empty (0 ethers)

the msg.value is less than the current purpose

the current world purpose owner tries to override his purpose ( msg.sender must be
different from the current owner)

https://stermi.medium.com/how-to-deploy-your-first-smart-contract-on-ethereum-with-solidity-and-hardhat-22f21d31096e 15/26
2/13/23, 4:17 AM How to deploy your first smart contract on Ethereum with Solidity and Hardhat | by StErMi | Medium

1 /**
2 @notice Modifier to check that the prev owner of the purpose is not the same as the new proposer
3 */
4 modifier onlyNewUser() {
5 // Check that new owner is not the previous one
6 require(purpose.owner != msg.sender, "You cannot override your own purpose");
7 _;
8 }
9
10 /**
11 @notice Set the new world purpose
12 @param _purpose The new purpose content
13 @return newPurpose The new active World purpose
14 */
15 function setPurpose(string memory _purpose) public payable onlyNewUser returns (Purpose memory new
16 // Check that the new owner has sent us enough funds to override the previous purpose
17 require(msg.value > purpose.investment, "You need to invest more than the previous purpose own
18
19 // Check if the new purpose is empty
20 bytes memory purposeBytes = bytes(_purpose);
21 require(purposeBytes.length > 0, "You need to set a purpose message");
22
23 // Update the purpose with the new one
24 purpose = Purpose(msg.sender, _purpose, msg.value);
25
26 // Update the sender value
27 balances[msg.sender] += msg.value;
28
29 // Emit the PurposeChange event
30 emit PurposeChange(msg.sender, _purpose, msg.value);
31
32 // Return the new purpose
33 return purpose;
34 }

gistfile1.txt hosted with ❤ by GitHub view raw

If everything works we set the new purpose, update the balance and emit the event.
https://stermi.medium.com/how-to-deploy-your-first-smart-contract-on-ethereum-with-solidity-and-hardhat-22f21d31096e 16/26
2/13/23, 4:17 AM How to deploy your first smart contract on Ethereum with Solidity and Hardhat | by StErMi | Medium

Now we want to allow users to withdraw their investment from previous purposes.
Please note that only the current purpose’s investment is “locked”. It will be unlocked
only when a new person will set the new purpose.

1 /**
2 @notice Withdraw the funds from the old purpose. If you have an active purpose those funds are "l
3 */
4 function withdraw() public {
5 // Get the user's balance
6 uint256 withdrawable = balances[msg.sender];
7
8 // Now we need to check how much the user can withdraw
9 address currentOwner = purpose.owner;
10 if (currentOwner == msg.sender) {
11 withdrawable -= purpose.investment;
12 }
13
14 // Check that the user has enough balance to withdraw
15 require(withdrawable > 0, "You don't have enough withdrawable balance");
16
17 // Update the balance
18 balances[msg.sender] -= withdrawable;
19
20 // Transfer the balance
21 (bool sent, ) = msg.sender.call{value: withdrawable}("");
22 require(sent, "Failed to send user balance back to the user");
23 }

gistfile1.txt hosted with ❤ by GitHub view raw

Deploy it locally just to test that everything works as expected. You should see
something like this:

https://stermi.medium.com/how-to-deploy-your-first-smart-contract-on-ethereum-with-solidity-and-hardhat-22f21d31096e 17/26
2/13/23, 4:17 AM How to deploy your first smart contract on Ethereum with Solidity and Hardhat | by StErMi | Medium

Contract deployment on local blockchain successful

Add local Test


Now I will not go into detail about the code inside the testing file but I’ll explain the
concept behind it. You should always create test cases for your contract. It’s a fast way
to understand if the contact’s logic is working as expected and allows you to prevent
deploying something that it’s not working.

My current workflow is like this: I take every function and I test that they do what I
expect them to do in both success cases and revert cases. Nothing more, nothing less.

When you write tests for Solidity contracts you are going to use Waffle. Head over to
their website to have an overview of the library, it’s really well made and offers a lot of
utilities.

Now, delete the file you have in your test folder, create a new one called
worldpurpose.ts and replace the content with this

https://stermi.medium.com/how-to-deploy-your-first-smart-contract-on-ethereum-with-solidity-and-hardhat-22f21d31096e 18/26
2/13/23, 4:17 AM How to deploy your first smart contract on Ethereum with Solidity and Hardhat | by StErMi | Medium

1 import {ethers, waffle} from 'hardhat';


2 import chai from 'chai';
3
4 import WorldPurposeArtifact from '../artifacts/contracts/WorldPurpose.sol/WorldPurpose.json';
5 import {WorldPurpose} from '../typechain/WorldPurpose';
6 import {SignerWithAddress} from '@nomiclabs/hardhat-ethers/signers';
7
8 const {deployContract} = waffle;
9 const {expect} = chai;
10
11 describe('WorldPurpose Contract', () => {
12 let owner: SignerWithAddress;
13 let addr1: SignerWithAddress;
14 let addr2: SignerWithAddress;
15 let addrs: SignerWithAddress[];
16
17 let worldPurpose: WorldPurpose;
18
19 beforeEach(async () => {
20 // eslint-disable-next-line no-unused-vars
21 [owner, addr1, addr2, ...addrs] = await ethers.getSigners();
22
23 worldPurpose = (await deployContract(owner, WorldPurposeArtifact)) as WorldPurpose;
24 });
25
26 describe('Test setPurpose', () => {
27 it("set purpose success when there's no purpose", async () => {
28 const purposeTitle = 'Reduce the ETH fee cost in the next 3 months';
29 const purposeInvestment = ethers.utils.parseEther('0.1');
30 await worldPurpose.connect(addr1).setPurpose(purposeTitle, {
31 value: purposeInvestment,
32 });
33
34 // Chdck that the purpose has been set
35 const currentPurpose = await worldPurpose.getCurrentPurpose();
36 expect(currentPurpose.purpose).to.equal(purposeTitle);
37 expect(currentPurpose.owner).to.equal(addr1.address);
38 expect(currentPurpose.investment).to.equal(purposeInvestment);
39
40 // Check that the balance has been updated
41 const balance = await worldPurpose.connect(addr1).getBalance();
42 expect(balance).to.equal(purposeInvestment);
43 });
44
45 it('override the prev purpose' async () => {
https://stermi.medium.com/how-to-deploy-your-first-smart-contract-on-ethereum-with-solidity-and-hardhat-22f21d31096e 19/26
2/13/23, 4:17 AM How to deploy your first smart contract on Ethereum with Solidity and Hardhat | by StErMi | Medium
45 it( override the prev purpose , async () => {
Execute
46
your tests with yarn test and see if everything pass as expected
await worldPurpose.connect(addr2).setPurpose("I'm the old world purpose", {
47 value: ethers.utils.parseEther('0.1'),
48 });
49
50 const purposeTitle = "I'm the new world purpose!";
51 const purposeInvestment = ethers.utils.parseEther('0.11');
52 await worldPurpose.connect(addr1).setPurpose(purposeTitle, {
53 value: purposeInvestment,
54 });
55
56 // Chdck that the purpose has been set
57 const currentPurpose = await worldPurpose.getCurrentPurpose();
58 expect(currentPurpose.purpose).to.equal(purposeTitle);
59 expect(currentPurpose.owner).to.equal(addr1.address);
60 expect(currentPurpose.investment).to.equal(purposeInvestment);
61
62 // Check that the balance has been updated
63 const balance = await worldPurpose.connect(addr1).getBalance();
64 expect(balance).to.equal(purposeInvestment);
65 });
66
67 it('Check PurposeChange event is emitted ', async () => {
Tests execution
68 const purposeTitle = "I'm the new world purpose!";
69 const purposeInvestment = ethers.utils.parseEther('0.11');
Deploy
70 your contract
const tx = awaiton test net
worldPurpose.connect(addr1).setPurpose(purposeTitle, {
71 value: purposeInvestment,
=====
72 HUGE
});DISCLAIMER START =====
73

DO
74 NOT USE YOUR
await MAIN WALLET PRIVATE'PurposeChange').withArgs(addr1.address,
expect(tx).to.emit(worldPurpose, FOR TESTING PURPOSES purposeTitl
75 });
76
USE A BURNER WALLET OR CREATE A NEW WALLET
77 it("You can't override your own purpose", async () => {
78 await worldPurpose.connect(addr1).setPurpose("I'm the new world purpose!", {
===== HUGE DISCLAIMER END =====
79 value: ethers.utils.parseEther('0.10'),
80 });
We81have already seen how to deploy the contract in our local hardhat chain but now
we82want to do it for
const tx =the Rinkeby test net (the procedure want
worldPurpose.connect(addr1).setPurpose('I is the
to same one
override thefor
my the main
own purpose!',

net83but it’s notvalue: ethers.utils.parseEther('0.11'),


the scope of the tutorial).
84 });
85
To deploy on the local chain we just need to type on console this command
86 await expect(tx).to.be.revertedWith('You cannot override your own purpose');
87 });
npx hardhat run --network localhost scripts/deploy.ts
88
89 it('Investment needs to be greater than 0', async () => {
https://stermi.medium.com/how-to-deploy-your-first-smart-contract-on-ethereum-with-solidity-and-hardhat-22f21d31096e 20/26
2/13/23, 4:17 AM How to deploy your first smart contract on Ethereum with Solidity and Hardhat | by StErMi | Medium

To90deploy your
constcontracts on another network we just need
tx = worldPurpose.connect(addr1).setPurpose('I tolike
would change the
to pay parameter
nothing to set a pur
91 value: ethers.utils.parseEther('0'),
value of --network but before doing that need to do some preparation step.
92 });
93
Get
94some ETH from
await testnet Faucet
expect(tx).to.be.revertedWith('You need to invest more than the previous purpose owne

Deploying
95 a contact cost
}); gas so we need some from a Faucet. Choose one test network
96
and head over to the faucet to get funds.
97 it('Purpose message must be not empty', async () => {
98 const tx = worldPurpose.connect(addr1).setPurpose('', {
99
Kovan faucet
value: ethers.utils.parseEther('0.1'),
100 });
101
Rinkeby faucet
102 await expect(tx).to.be.revertedWith('You need to set a purpose message');
103
Goerli});
faucet
104
In105
our case, we decided
it('New to use Rinkeby
purpose investment needs to so go andthan
be greater get some fundsone',
the previous overasync
there.
() => {
106 await worldPurpose.connect(addr1).setPurpose("I'm the old purpose!", {
Choose
107 an Ethereum Provider
value: ethers.utils.parseEther('0.10'),
108 });
In order to deploy our contract, we need a way to interact directly with the Ethereum
109
network.
110
Nowadays we have two possible options:
const tx = worldPurpose
111 .connect(addr2)
112Infura .setPurpose('I want to pay less than the previous owner of the purpose, can I?', {
113 value: ethers.utils.parseEther('0.01'),
114Alchemy });
115
In116
our case,await
we are going to use Alchemy, so go
expect(tx).to.be.revertedWith('You over
need there,more
to invest create
than an
theaccount, createowne
previous purpose a
117 });
new app and grab the Rinkeby API Key.
118 });
119
Update the Hardhat Config file
120 describe('Test withdraw', () => {
Install
121 theit('Withdraw
dotenv dependencies, this nodejs
your previous investment', library
async () =>allow
{ us to create a .env
122 const firstInvestment = ethers.utils.parseEther('0.10');
environment file to store our variables without exposing them to the source code.
123 await worldPurpose.connect(addr1).setPurpose('First purpose', {
124 value: ethers.utils.parseEther('0.10'),
yarn add --dev dotenv
125 });
126
Now
127
create await
in the root of your project a .env file and paste all the information you
worldPurpose.connect(addr2).setPurpose('Second purpose', {
have
128 collected
value: ethers.utils.parseEther('0.11'),
129 });
130
131 const tx = await worldPurpose.connect(addr1).withdraw();
RENKEBY_URL=https://eth-rinkeby.alchemyapi.io/v2/<YOUR_ALCHEMY_APP_ID>
132
PRIVATE_KEY=<YOUR_BURNER_WALLET_PRIVATE_KEY>
133 // Check that my current balance on contract is 0
134 const balance = await worldPurpose connect(addr1) getBalance();
https://stermi.medium.com/how-to-deploy-your-first-smart-contract-on-ethereum-with-solidity-and-hardhat-22f21d31096e 21/26
2/13/23, 4:17 AM How to deploy your first smart contract on Ethereum with Solidity and Hardhat | by StErMi | Medium
134 const balance = await worldPurpose.connect(addr1).getBalance();
I can’t
135 stressexpect(balance).to.equal(0);
enough. Don’t use your main wallet private case for testing purposes.
Create
136 a separate wallet or use a burning wallet to do this type of testing!
137 // Check that I got back in my wallet the whole import

The
138 last step is toexpect(tx).to.changeEtherBalance(addr1,
await update the hardhat.config.ts file to add dotenv and update the
firstInvestment);
139 });
rinkeby information.
140
141 it('Withdraw only the unlocked investment', async () => {
At142
the top ofconst
the firstInvestment
file add require("dotenv").config(); and now update the config like
= ethers.utils.parseEther('0.10');
this
143 await worldPurpose.connect(addr1).setPurpose('First purpose', {
144 value: ethers.utils.parseEther('0.10'),
145 });
146
const config: HardhatUserConfig = {
147 await worldPurpose.connect(addr2).setPurpose('Second
solidity: '0.8.4', purpose', {
148 networks: { ethers.utils.parseEther('0.11'),
value:
149 rinkeby:
}); {
150 url: process.env.RENKEBY_URL || '',
151
accounts: process.env.PRIVATE_KEY !== undefined ?
const secondInvestment = ethers.utils.parseEther('0.2');
[process.env.PRIVATE_KEY] : [],
152 await worldPurpose.connect(addr1).setPurpose('Third purpose from the first addr1', {
},
153 }, value: secondInvestment,

};
154 });
155
156 const tx = await worldPurpose.connect(addr1).withdraw();
157 we ready? Let’s deploy it!
Are
158 // In this case the user can Withdraw only it's first investment
159 // The second one is still "locked" because he's the owner of the current purpose
npx hardhat run --network rinkeby scripts/deploy.ts
160
161 // Check that my current balance on contract is 0
If162
everything goes well you should see something like this in your console
const balance = await worldPurpose.connect(addr1).getBalance();
163 expect(balance).to.equal(secondInvestment);
164
165 // Check that I got back in my wallet the whole import
166 await expect(tx).to.changeEtherBalance(addr1, firstInvestment);
167 });
If168
you copy that contract address and past it on Etherscan Rinkeby you should be able
to169 it('You cant withdraw when your balance is empty', async () => {
see it live! Mine is located here: 0xAf688A3405531e0FC274F6453cD8d3f3dB07D706
170 const tx = worldPurpose.connect(addr1).withdraw();
171
Get your contract verified by Etherscan
172 await expect(tx).to.be.revertedWith("You don't have enough withdrawable balance");
173 });
Source
174
code verification provides transparency for users interacting with smart contracts. By
uploading
175 the source code,
it('Withdraw Etherscan
only the unlocked will match the
investment', compiled
async () => { code with that on the

blockchain.
176 Just like
await contracts, a “smart contract” should provide
worldPurpose.connect(addr1).setPurpose('First end
purpose', { users with more
177 value: ethers.utils.parseEther('0.10'),
178 });

https://stermi.medium.com/how-to-deploy-your-first-smart-contract-on-ethereum-with-solidity-and-hardhat-22f21d31096e 22/26
2/13/23, 4:17 AM How to deploy your first smart contract on Ethereum with Solidity and Hardhat | by StErMi | Medium

179
information on what they are “digitally signing” for and give users an opportunity to audit
180 const tx = worldPurpose.connect(addr1).withdraw();
the code to independently verify that it actually does what it is supposed to do.
181
182 // Your funds are still "locked" because your are the owner of the current purpose

So183let’s do it.await
It’s really an easy step because Hardhat
expect(tx).to.be.revertedWith("You provide
don't have a specific Plugin
enough withdrawable to do
balance");
184 });
that: hardhat-etherscan.
185 });
186 });
Let’s install yarn add --dev @nomiclabs/hardhat-etherscan

worldpurpose.ts hosted with ❤ by GitHub view raw


and include it in your hardhat.config.ts adding import "@nomiclabs/hardhat-

etherscan"; at the end of your imports.

The next step is to register an account on Etherscan and generate an API Key.

Once you have it we need to update our .env file adding this line of code

ETHERSCAN_API_KEY=<PAST_YOU_API_KEY>

and update the hardhat.config.ts adding the Etherscan config needed by the plugin.

The last thing to do is to run the verify task that has been added by the plugin:

npx hardhat verify --network rinkeby <YOUR_CONTRACT_ADDRESS>

The plugin have a lot of configurations and different options so check out their
documentation if you want to know more.

If everything goes well you should see something like this in your console

Contract verified by Etherscsan

https://stermi.medium.com/how-to-deploy-your-first-smart-contract-on-ethereum-with-solidity-and-hardhat-22f21d31096e 23/26
2/13/23, 4:17 AM How to deploy your first smart contract on Ethereum with Solidity and Hardhat | by StErMi | Medium

If you go over the Etherscan contract page again you should see a green checkmark on
top of the Contract section. Well done!

Conclusion and next steps


If you want to use this solidity-template to kickstart you next smart contract project
just head over to the GitHub repo https://github.com/StErMi/solidity-template and it
the “Use this template” green button and boom, you are ready to go!

This is just the start, I’m planning to add more features in time like for example:

Support to eslint for the typescript testing lib

Support for hardhat-deploy, an Hardhat Plugin to better manage deployment

Add support to solidity-coverage plugin

Add support to hardhat-gas-reporter plugin

TBD

Do you have any feedback or do you want to contribute to the Solidity Template? Just
create a Pull Request on the GitHub page and let’s discuss it!

Did you like this content? Follow me for more!


GitHub: https://github.com/StErMi

Twitter: https://twitter.com/StErMi

Medium: https://medium.com/@stermi

Dev.to: https://dev.to/stermi

https://stermi.medium.com/how-to-deploy-your-first-smart-contract-on-ethereum-with-solidity-and-hardhat-22f21d31096e 24/26
2/13/23, 4:17 AM How to deploy your first smart contract on Ethereum with Solidity and Hardhat | by StErMi | Medium

https://stermi.medium.com/how-to-deploy-your-first-smart-contract-on-ethereum-with-solidity-and-hardhat-22f21d31096e 25/26
2/13/23, 4:17 AM How to deploy your first smart contract on Ethereum with Solidity and Hardhat | by StErMi | Medium

Open in app Get unlimited access

Search Medium

Solidity Web 3 Ethereum Blockchain Hardhat

Get an email whenever StErMi publishes.


Emails will be sent to waledmunker@gmail.com. Not you?

Subscribe

https://stermi.medium.com/how-to-deploy-your-first-smart-contract-on-ethereum-with-solidity-and-hardhat-22f21d31096e 26/26
2/13/23, 4:20 AM Creating Your Own Crypto Tokens. Within the Ethereum blockchain, we can… | by Prof Bill Buchanan OBE | ASecuritySite: When …

Published in ASecuritySite: When Bob Met Alice

You have 2 free member-only stories left this month. Sign up for Medium and get an extra one

Prof Bill Buchanan OBE Follow

Mar 29, 2022 · 4 min read · · Listen

Save

https://medium.com/asecuritysite-when-bob-met-alice/creating-your-own-crypto-tokens-9293e832e6e5 1/17
2/13/23, 4:20 AM Creating Your Own Crypto Tokens. Within the Ethereum blockchain, we can… | by Prof Bill Buchanan OBE | ASecuritySite: When …

Photo by Jievani Weerasinghe on Unsplash

Creating Your Own Crypto Tokens


https://medium.com/asecuritysite-when-bob-met-alice/creating-your-own-crypto-tokens-9293e832e6e5 2/17
2/13/23, 4:20 AM Creating Your Own Crypto Tokens. Within the Ethereum blockchain, we can… | by Prof Bill Buchanan OBE | ASecuritySite: When …

Within the Ethereum blockchain, we can record transactions and run smart contracts.
These things allow us to run DApps (decentralized applications) and which can support
the running of the infrastructure in return for some payment (Ether). A DApp can also
create tokens for new currencies, shares in a company or to prove the ownership of an
asset. ERC-20 is a standard that allows for the sharing, transfer and storage of tokens.

Making some tokens


Now, let’s say that you want to create some crypto tokens for student work, and where
they could be rewarded for their good work. So, let’s create a token named
“ENUToken”. First, we open up remix.ethereum, and enter the following Solidy
contract [code]:

https://medium.com/asecuritysite-when-bob-met-alice/creating-your-own-crypto-tokens-9293e832e6e5 3/17
2/13/23, 4:20 AM Creating Your Own Crypto Tokens. Within the Ethereum blockchain, we can… | by Prof Bill Buchanan OBE | ASecuritySite: When …

1 pragma solidity ^0.4.24;


2
3 // ----------------------------------------------------------------------------
4 // 'ENU Token' token contract
5 //
6 // Deployed to : 0xbB15B38e4ef6aF154b89A2E57E03Cd5cbD752233
7 // Symbol : ENUToken
8 // Name : ENU Token
9 // Total supply: 100000000
10 // Decimals : 18
11
12 // Based on https://github.com/bitfwdcommunity/Issue-your-own-ERC20-token/tree/master/contracts
13
14
15 // ----------------------------------------------------------------------------
16 // Safe maths
17 // ----------------------------------------------------------------------------
18 contract SafeMath {
19 function safeAdd(uint a, uint b) public pure returns (uint c) {
20 c = a + b;
21 require(c >= a);
22 }
23 function safeSub(uint a, uint b) public pure returns (uint c) {
24 require(b <= a);
25 c = a - b;
26 }
27 function safeMul(uint a, uint b) public pure returns (uint c) {
28 c = a * b;
29 require(a == 0 || c / a == b);
30 }
31 function safeDiv(uint a, uint b) public pure returns (uint c) {
32 require(b > 0);
33 c = a / b;
34 }
35 }
36
37
38 // ----------------------------------------------------------------------------
39 // ERC Token Standard #20 Interface
40 // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
41 // ----------------------------------------------------------------------------
42 contract ERC20Interface {
43 function totalSupply() public constant returns (uint);
44 function balanceOf(address tokenOwner) public constant returns (uint balance);
45 function allowance(address tokenOwner address spender) public constant returns (uint remaini
https://medium.com/asecuritysite-when-bob-met-alice/creating-your-own-crypto-tokens-9293e832e6e5 4/17
2/13/23, 4:20 AM Creating Your Own Crypto Tokens. Within the Ethereum blockchain, we can… | by Prof Bill Buchanan OBE | ASecuritySite: When …
45 function allowance(address tokenOwner, address spender) public constant returns (uint remaini
When
46
youfunction
create transfer(address
your own contract, make sure you change the public constructor()
to, uint tokens) public returns (bool success);
with:
47 the symbol, the name, and
function approve(address the wallet
spender, ID:
uint tokens) public returns (bool success);
48 function transferFrom(address from, address to, uint tokens) public returns (bool success);
49
50 event Transfer(address indexed from, address indexed to, uint tokens);
constructor() public {
51 symbol = "ENUToken";
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
52 } name = "ENU Token";
53 decimals = 18;
54 _totalSupply = 100000000000000000000000000;
balances[0xbB15B38e4ef6aF154b89A2E57E03Cd5cbD752233] =
55 // ----------------------------------------------------------------------------
_totalSupply;
56 // Contract function to receive approval and execute function in one call
emit Transfer(address(0),
0xbB15B38e4ef6aF154b89A2E57E03Cd5cbD752233, _totalSupply);
57 //
58 } Borrowed from MiniMeToken
//
59 // ----------------------------------------------------------------------------
60 contract ApproveAndCallFallBack {

The
61 walletfunction
ID is the public ID of your from,
receiveApproval(address wallet in Metamask.
uint256 You token,
tokens, address thus need
bytes to change
data) public;
62 }
“0xbB15B38e4..33” or for your public ID on the test network. This will allow you to
63
transfer
64 the tokens into your wallet. Now we can compile the contract:
65 // ----------------------------------------------------------------------------
66 // Owned contract
67 // ----------------------------------------------------------------------------
68 contract Owned {
69 address public owner;
70 address public newOwner;
71
72 event OwnershipTransferred(address indexed _from, address indexed _to);
73
74 constructor() public {
75 owner = msg.sender;
76 }
77
78 modifier onlyOwner {
79 require(msg.sender == owner);
80 _;
81 }
82
83 function transferOwnership(address _newOwner) public onlyOwner {
84 newOwner = _newOwner;
85 }
Next,
86 we will deploy
function to the Ropsten
acceptOwnership() test
public { network:
87 require(msg.sender == newOwner);
88 emit OwnershipTransferred(owner, newOwner);
89 owner = newOwner;
https://medium.com/asecuritysite-when-bob-met-alice/creating-your-own-crypto-tokens-9293e832e6e5 5/17
2/13/23, 4:20 AM Creating Your Own Crypto Tokens. Within the Ethereum blockchain, we can… | by Prof Bill Buchanan OBE | ASecuritySite: When …

90 newOwner = address(0);
91 }
92 }
93
94
95 // ----------------------------------------------------------------------------
96 // ERC20 Token, with the addition of symbol, name and decimals and assisted
97 // token transfers
98 // ----------------------------------------------------------------------------
99 contract BillToken is ERC20Interface, Owned, SafeMath {
100 string public symbol;
101 string public name;
102 uint8 public decimals;
103 uint public _totalSupply;
104
After
105 this,mapping(address
our contract =>will be balances;
uint) shown as being pending deployment:
106 mapping(address => mapping(address => uint)) allowed;
107
108
109 // ------------------------------------------------------------------------
110 // Constructor
111 // ------------------------------------------------------------------------
112 constructor() public {
113 symbol = "ENUToken";
114 name = "ENU Token";
115 decimals = 18;
116 _totalSupply = 100000000000000000000000000;
117 balances[0xbB15B38e4ef6aF154b89A2E57E03Cd5cbD752233] = _totalSupply;
118 emit Transfer(address(0), 0xbB15B38e4ef6aF154b89A2E57E03Cd5cbD752233, _totalSupply);
119 }
120
121
122 // ------------------------------------------------------------------------
It will take 10–15 minutes to deploy, but can be speeded up by increasing the gas limit:
123 // Total supply
124 // ------------------------------------------------------------------------
125 function totalSupply() public constant returns (uint) {
126 return _totalSupply - balances[address(0)];
127 }
128
129
130 // ------------------------------------------------------------------------
131 // Get the token balance for account tokenOwner
132 // ------------------------------------------------------------------------
133 function balanceOf(address tokenOwner) public constant returns (uint balance) {
134 return balances[tokenOwner];
https://medium.com/asecuritysite-when-bob-met-alice/creating-your-own-crypto-tokens-9293e832e6e5 6/17
2/13/23, 4:20 AM Creating Your Own Crypto Tokens. Within the Ethereum blockchain, we can… | by Prof Bill Buchanan OBE | ASecuritySite: When …
134 return balances[tokenOwner];
135 }
136
137
138 // ------------------------------------------------------------------------
139 // Transfer the balance from token owner's account to to account
140 // - Owner's account must have sufficient balance to transfer
141 // - 0 value transfers are allowed
142 // ------------------------------------------------------------------------
143 function transfer(address to, uint tokens) public returns (bool success) {
144 balances[msg.sender] = safeSub(balances[msg.sender], tokens);
145 balances[to] = safeAdd(balances[to], tokens);
146 emit Transfer(msg.sender, to, tokens);
147 return true;
148 }
149
150
151 // ------------------------------------------------------------------------
152 // Token owner can approve for spender to transferFrom(...) tokens
153 // from the token owner's account
154 //
155 // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
156 // recommends that there are no checks for the approval double-spend attack
157 // as this should be implemented in user interfaces
158 // ------------------------------------------------------------------------
159 function approve(address spender, uint tokens) public returns (bool success) {
160 allowed[msg.sender][spender] = tokens;
161 emit Approval(msg.sender, spender, tokens);
162 return true;
163 }
164
165
166 // ------------------------------------------------------------------------
167 // Transfer tokens from the from account to the to account
168 //
169 // The calling account must already have sufficient tokens approve(...)-d
170 // for spending from the from account and
171 // - From account must have sufficient balance to transfer
172 // - Spender must have sufficient allowance to transfer
173 // - 0 value transfers are allowed
174 // ------------------------------------------------------------------------
175 function transferFrom(address from, address to, uint tokens) public returns (bool success) {
176 balances[from] = safeSub(balances[from], tokens);
177 allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
178 balances[to] = safeAdd(balances[to], tokens);

https://medium.com/asecuritysite-when-bob-met-alice/creating-your-own-crypto-tokens-9293e832e6e5 7/17
2/13/23, 4:20 AM Creating Your Own Crypto Tokens. Within the Ethereum blockchain, we can… | by Prof Bill Buchanan OBE | ASecuritySite: When …

179 emit Transfer(from, to, tokens);


Once deployed, we can view the contract details:
180 return true;
181 }
182
183
184 // ------------------------------------------------------------------------
185 // Returns the amount of tokens approved by the owner that can be
186 // transferred to the spender's account
187 // ------------------------------------------------------------------------
188 function allowance(address tokenOwner, address spender) public constant returns (uint remaini
189 return allowed[tokenOwner][spender];
190 }
191
192
193 // ------------------------------------------------------------------------
194 // Token owner can approve for spender to transferFrom(...) tokens
195 // from the token owner's account. The spender contract function
196 // receiveApproval(...) is then executed
197 // ------------------------------------------------------------------------
And can then view the transaction for the contact [here]:
198 function approveAndCall(address spender, uint tokens, bytes data) public returns (bool succes
199 allowed[msg.sender][spender] = tokens;
200 emit Approval(msg.sender, spender, tokens);
201 ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
202 return true;
203 }
204
205
206 // ------------------------------------------------------------------------
207 // Don't accept ETH
208 // ------------------------------------------------------------------------
209 function () public payable {
210 revert();
211 }
212
213
214 // ------------------------------------------------------------------------
215 // Owner can transfer out any accidentally sent ERC20 tokens

And
216 then //
view the contact [here]:
------------------------------------------------------------------------
217 function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (b
218 return ERC20Interface(tokenAddress).transfer(owner, tokens);
219 }
220 }
221

i fil 1 h d i h ❤ b Gi H b i
https://medium.com/asecuritysite-when-bob-met-alice/creating-your-own-crypto-tokens-9293e832e6e5 8/17
2/13/23, 4:20 AM Creating Your Own Crypto Tokens. Within the Ethereum blockchain, we can… | by Prof Bill Buchanan OBE | ASecuritySite: When …
gistfile1.txt hosted with ❤ by GitHub view raw

Next, we select the Contract tab:

And then select “Verify and Publish” and enter the details of the compiler version
(v0.4.26):

https://medium.com/asecuritysite-when-bob-met-alice/creating-your-own-crypto-tokens-9293e832e6e5 9/17
2/13/23, 4:20 AM Creating Your Own Crypto Tokens. Within the Ethereum blockchain, we can… | by Prof Bill Buchanan OBE | ASecuritySite: When …

We then need to copy-and-pasete the contract code into the Source Code text box:

After less than 45 seconds, the contract will be approved:

https://medium.com/asecuritysite-when-bob-met-alice/creating-your-own-crypto-tokens-9293e832e6e5 10/17
2/13/23, 4:20 AM Creating Your Own Crypto Tokens. Within the Ethereum blockchain, we can… | by Prof Bill Buchanan OBE | ASecuritySite: When …

When the contact is run there is a constructor to transfer the tokens to the wallet we
have defined (and who will be the owner of the token). We can now go back to the
wallet which is specified, to see if the tokens have been transferred:

Next, we can transfer the tokens into our wallet, by defining the contract address:

https://medium.com/asecuritysite-when-bob-met-alice/creating-your-own-crypto-tokens-9293e832e6e5 11/17
2/13/23, 4:20 AM Creating Your Own Crypto Tokens. Within the Ethereum blockchain, we can… | by Prof Bill Buchanan OBE | ASecuritySite: When …

We will now have our new tokens in the wallet:

And with:

https://medium.com/asecuritysite-when-bob-met-alice/creating-your-own-crypto-tokens-9293e832e6e5 12/17
2/13/23, 4:20 AM Creating Your Own Crypto Tokens. Within the Ethereum blockchain, we can… | by Prof Bill Buchanan OBE | ASecuritySite: When …

Open in app Sign up Sign In

Search Medium

We can now transfer the cryptocurrency to students:

Conclusions
And that’s how you create cryptocurrency!

https://medium.com/asecuritysite-when-bob-met-alice/creating-your-own-crypto-tokens-9293e832e6e5 13/17
2/13/23, 4:20 AM Creating Your Own Crypto Tokens. Within the Ethereum blockchain, we can… | by Prof Bill Buchanan OBE | ASecuritySite: When …

https://medium.com/asecuritysite-when-bob-met-alice/creating-your-own-crypto-tokens-9293e832e6e5 14/17
2/13/23, 4:20 AM Creating Your Own Crypto Tokens. Within the Ethereum blockchain, we can… | by Prof Bill Buchanan OBE | ASecuritySite: When …

https://medium.com/asecuritysite-when-bob-met-alice/creating-your-own-crypto-tokens-9293e832e6e5 15/17
2/13/23, 4:20 AM Creating Your Own Crypto Tokens. Within the Ethereum blockchain, we can… | by Prof Bill Buchanan OBE | ASecuritySite: When …

Cryptography Blockchain Ethereum

Get an email whenever Prof Bill Buchanan OBE publishes.

Your email

Subscribe

By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy
practices.

https://medium.com/asecuritysite-when-bob-met-alice/creating-your-own-crypto-tokens-9293e832e6e5 16/17
2/13/23, 4:20 AM Creating Your Own Crypto Tokens. Within the Ethereum blockchain, we can… | by Prof Bill Buchanan OBE | ASecuritySite: When …

About Help Terms Privacy

Get the Medium app

https://medium.com/asecuritysite-when-bob-met-alice/creating-your-own-crypto-tokens-9293e832e6e5 17/17
2/13/23, 4:22 AM How to Create Your Own Crypto Token | by Sarah Roff | Geek Culture | Medium

Published in Geek Culture

You have 2 free member-only stories left this month. Sign up for Medium and get an extra one

Sarah Roff Follow

Nov 26, 2021 · 9 min read · · Listen

Save

How to Create Your Own Crypto Token


A Step-by-Step Guide

https://medium.com/geekculture/how-to-create-your-own-crypto-token-4097a173dd73 1/24
2/13/23, 4:22 AM How to Create Your Own Crypto Token | by Sarah Roff | Geek Culture | Medium

Photo Credit: Vladimir Melentev

Overview
Back in 2015 when the Ethereum network first launched, there weren’t any templates
or guidelines for token development. This meant that there were a large variety of
tokens, each unique from one another. In order to make tokens more uniform, the
community came up with an ERC-20 Standard.

In this article, I’ll be walking you through the process of creating your very own ERC-
20 Token.

but let's take a step back…

What is a Token?
Tokens are used to interact with decentralized applications built on top of different
blockchains. A token can represent almost anything in Ethereum including:

https://medium.com/geekculture/how-to-create-your-own-crypto-token-4097a173dd73 2/24
2/13/23, 4:22 AM How to Create Your Own Crypto Token | by Sarah Roff | Geek Culture | Medium

lottery tickets

financial assets like a share in a company

skills of a character in a game

a fiat currency like CAD

reputation points in an online platform

an ounce of silver

Not to be confused with coins which are just methods of payment while tokens may
perform many other functions.

What is an ERC-20 Token?


ERC stands for Ethereum Request for Comment, and 20 is the proposal identifier
number. The ERC-20 Token was designed to improve the ETH network by
standardizing token creation.

ERC-20 Token Standards


ERC-20 contains a list of rules that Ethereum based tokens must follow. The standard
defines six mandatory functions and three optional ones to implement in your smart
contract.

totalSupply: this method defines the total number of tokens in circulation (the token
supply). The smart contract will refuse to create new tokens once the limit is reached.

balanceOf: this method returns the number of tokens a wallet address has.

transfer: this method executes transfers of a specified number of tokens to a specified


address.

transferFrom: executes transfers of a specified number of tokens from a specified


address

https://medium.com/geekculture/how-to-create-your-own-crypto-token-4097a173dd73 3/24
2/13/23, 4:22 AM How to Create Your Own Crypto Token | by Sarah Roff | Geek Culture | Medium

approve: this method verifies whether a user can withdraw a set number of tokens
considering the total supply.

allowance: this method verifies whether a user has enough balance to send a certain
amount of tokens to another.

Creating Your Own Token


let's get started…

Setting Up
1. Install Chrome

If your not already using Chrome as your browser, you’ll need to download it for this
project.

2. Install Metamask Browser Extension

https://medium.com/geekculture/how-to-create-your-own-crypto-token-4097a173dd73 4/24
2/13/23, 4:22 AM How to Create Your Own Crypto Token | by Sarah Roff | Geek Culture | Medium

Once your on Chrome, you’ll need to install the Metamask browser extension.
MetaMask is a software cryptocurrency wallet used to interact with the Ethereum
blockchain. After its downloaded, follow the instructions to set up your wallet account.

3. Select Ropsten Test Network

https://medium.com/geekculture/how-to-create-your-own-crypto-token-4097a173dd73 5/24
2/13/23, 4:22 AM How to Create Your Own Crypto Token | by Sarah Roff | Geek Culture | Medium

Within your Metmask account, switch from the Ethereum Mainnet to the Ropsten Test
Network. The Ropsten Test Net is an exact copy of the real, main-net Network but it
allows for blockchain developers to test their work without the need for real ETH.

4. Get Test ETH

https://medium.com/geekculture/how-to-create-your-own-crypto-token-4097a173dd73 6/24
2/13/23, 4:22 AM How to Create Your Own Crypto Token | by Sarah Roff | Geek Culture | Medium

Use the Ropsten Ethereum Faucet to get some test ETH by inputting your wallet
address (you can copy and paste it from your Metamask extension), you will only need
0.3 ETH.

5. Set up your file

https://medium.com/geekculture/how-to-create-your-own-crypto-token-4097a173dd73 7/24
2/13/23, 4:22 AM How to Create Your Own Crypto Token | by Sarah Roff | Geek Culture | Medium

Head over to the Ethereum Remix IDE and create a new file. Name the file
YourTokenName.sol (incase it wasn’t obvious, replace YourTokenName with the name
of your token)

You should be left with an empty file that looks like this. Now you’re all set up and
ready to begin coding!

Coding
*any missing line numbers indicate a blank line

Line 1: //SPDX-License-Identifier: MIT

In the first line we are setting the licensing specifications to MIT (open source). You
can view a full list of SPDX Licensing options HERE.

Line 3: pragma solidity ^0.4.24;

Next, we declare the Solidity version that we’re using. It is import to specify this, as
Solidity is constantly evolving, so old code may not be compatible with newer versions.

Line 5–26:

https://medium.com/geekculture/how-to-create-your-own-crypto-token-4097a173dd73 8/24
2/13/23, 4:22 AM How to Create Your Own Crypto Token | by Sarah Roff | Geek Culture | Medium

In these lines, we are calling the SafeMath Interface so we can utilize math functions
in our contract. SafeMath protects against overflows when adding, subtracting,
multiplying, and dividing integers. Overflow occurs when an arithmetic operation trys
to create a numeric value that is outside the range that can be represented with a given
number of bits.

contract SafeMath {

function add(uint a, uint b) public pure returns (uint c) {


c = a + b;
require(c >= a);
}

function sub(uint a, uint b) public pure returns (uint c) {


require(b <= a);
c = a — b;
}

function mul(uint a, uint b) public pure returns (uint c) {


c = a * b;
require(a == 0 || c / a == b);
}

function div(uint a, uint b) public pure returns (uint c) {


require(b > 0);
c = a / b;
}
}

For each arthritic operation, we create a function that we can call on later (eg.
‘function add’ is a function for addition.)

Line 28:

Here we are calling the ERC Token Standard #20 Interface to implement its functions.

contract ERC20Interface {

Line 29:

https://medium.com/geekculture/how-to-create-your-own-crypto-token-4097a173dd73 9/24
2/13/23, 4:22 AM How to Create Your Own Crypto Token | by Sarah Roff | Geek Culture | Medium

function totalSupply() public constant returns (uint);

This function returns the amount of tokens in existence.

Line 30:

function balanceOf(address owner) public constant returns (uint


balance);

This function returns the balance of an account.

Line 31:

function transfer(address to, uint tokens) public returns (bool


success);

This function transfers a tokens from the caller to a different address.

Line 32:

function transferFrom(address from, address to, uint tokens) public


returns (bool success);

This function is used by the spender to spend the allowance.

Line 33:

function approve(address spender, uint tokens) public returns (bool


success);

This function function creates an allowance.

https://medium.com/geekculture/how-to-create-your-own-crypto-token-4097a173dd73 10/24
2/13/23, 4:22 AM How to Create Your Own Crypto Token | by Sarah Roff | Geek Culture | Medium

Line 34:

function allowance(address owner, address spender) public constant


returns (uint remaining);

This function lets anybody query to see what is the allowance that one address ( owner )
lets another address ( spender ) spend.

Line 36–38:

event Transfer(address indexed from, address indexed to, uint


tokens);
event Approval(address indexed owner, address indexed spender, uint
tokens);
}

These events are emitted when the state of the ERC-20 contract changes.

Line 40–42:

contract ApproveAndCallFallBack {
function getApproval(address from, uint256 tokens, address token,
bytes data) public;
}

This is a contract function to receive approval and execute function in one call.

Line 44–48:

contract TokenName is ERC20Interface, SafeMath {


uint public _totalSupply;
string public name;
string public symbol;
uint8 public decimals;

https://medium.com/geekculture/how-to-create-your-own-crypto-token-4097a173dd73 11/24
2/13/23, 4:22 AM How to Create Your Own Crypto Token | by Sarah Roff | Geek Culture | Medium

Now we starting our actual token contract. Replace TokenName with the name of your
token. From there, you’ll see we define four variables, the first will keep track of the
total supply, and the other three are used to imporve readibility.

Line 50–51:

mapping(address => uint) private balances;


mapping(address => mapping(address => uint)) allowed;

This creates two mapping functions that will give users the ability to spend these
tokens.

Line 53–60:

constructor() public {
name = "Token Name";
symbol = "Token Symbol";
decimals = Token Decimals;
_totalSupply = Token Supply;
balances[Wallet Address] = _totalSupply;
emit Transfer(address(0), Wallet Address, _totalSupply);
}

Here we are initializing the constructor, setting symbol, name, decimals, and total
supply value for our token and then declaring the total supply of the token to be equal
to your wallet’s balance for this token.

Here is where you’ll be able to customize your token.

Replace Token Name with the name of your token

Replace Token Symbol with the symbol of your token (this can be any three capital
letter combination, for example, ABC)

Replace Token Decimals with an integer value. This will determine how users can
divide your token. The standard is 18, however, if you want to keep things simple,
then you can make the value 0 which means your token is not divisible.
https://medium.com/geekculture/how-to-create-your-own-crypto-token-4097a173dd73 12/24
2/13/23, 4:22 AM How to Create Your Own Crypto Token | by Sarah Roff | Geek Culture | Medium

Replace Token Supply with an integer value. This will determine the total amount
of tokens in circulation. Note that the total supply value must have additional zeros
depending on your decimals; For instance if your Token Decimals value is 2 and you
want 100 tokens, then you would enter 10000

Replace Wallet Address with your MetaMask Wallet Address (you can copy and
paste this directly from the MetaMask extension in your browser)

Line 62–64:

function totalSupply() public constant returns (uint) {


return _totalSupply - balances[address(0)];
}

This function will govern the total supply of our token.

Line 66–68:

function balanceOf(address owner) public constant returns (uint


balance) {
return balances[owner];
}

This function will check the balance of a wallet address.

Line 70–75:

function transfer(address to, uint tokens) public returns (bool


success) {
balances[msg.sender] = sub(balances[msg.sender], tokens);
balances[to] = add(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}

https://medium.com/geekculture/how-to-create-your-own-crypto-token-4097a173dd73 13/24
2/13/23, 4:22 AM How to Create Your Own Crypto Token | by Sarah Roff | Geek Culture | Medium

This function will execute the transfer of tokens from the from the sender’s account to
a different one.

Line 77–83:

function transferFrom(address from, address to, uint tokens) public


returns (bool success) {
balances[from] = sub(balances[from], tokens);
allowed[from][msg.sender] = sub(allowed[from][msg.sender],
tokens);
balances[to] = add(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}

This function is what a spender calls to spend an allowance. It requires two operations:
transfer the amount being spent and reduce the allowance by that amount.

Line 85–89:

function approve(address spender, uint tokens) public returns (bool


success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}

This function will check if the total supply has the amount of token which needs to be
allocated to a user.

Line 91–93:

function allowance(address owner, address spender) public constant


returns (uint remaining) {
return allowed[owner][spender];
}

https://medium.com/geekculture/how-to-create-your-own-crypto-token-4097a173dd73 14/24
2/13/23, 4:22 AM How to Create Your Own Crypto Token | by Sarah Roff | Geek Culture | Medium

This function will allow anybody to check if a user has enough balance to perform the
transfer to another user.

Line 95–100:

function approveAndCall(address spender, uint tokens, bytes data)


public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).getApproval(msg.sender,
tokens, this, data);
return true;
}

This function will execute the transactions of buying and spending tokens.

Line 102–105:

function () public payable {


revert();
}
}

This function prevents accounts from directly sending ETH to the contract, and from
users spending gas on transactions where they forget to mention the function name.

Click HERE to view the full code on Github.

Deploying
Now that we’re done coding our token, its time to compile the file and deploy it! Before
compiling, ensure that your MetaMask account is set to the Ropsten Test Network.

https://medium.com/geekculture/how-to-create-your-own-crypto-token-4097a173dd73 15/24
2/13/23, 4:22 AM How to Create Your Own Crypto Token | by Sarah Roff | Geek Culture | Medium

Start by heading over to the Solidity Compiler

Next, ensure that you have selected the the correct compiler (0.4.26+commit.4563c3fc).

https://medium.com/geekculture/how-to-create-your-own-crypto-token-4097a173dd73 16/24
2/13/23, 4:22 AM How to Create Your Own Crypto Token | by Sarah Roff | Geek Culture | Medium

Then hit ‘Compile’. Once your file is compiled, you should see a green check mark on
the Solidity Compiler icon.

Once your file is compiled, click the ‘Deploy and Run Transactions’ button on the left.

https://medium.com/geekculture/how-to-create-your-own-crypto-token-4097a173dd73 17/24
2/13/23, 4:22 AM How to Create Your Own Crypto Token | by Sarah Roff | Geek Culture | Medium

Set Environment to Injected Web3.

Set Contract to YourTokenName.

https://medium.com/geekculture/how-to-create-your-own-crypto-token-4097a173dd73 18/24
2/13/23, 4:22 AM How to Create Your Own Crypto Token | by Sarah Roff | Geek Culture | Medium

Hit ‘Deploy’.

https://medium.com/geekculture/how-to-create-your-own-crypto-token-4097a173dd73 19/24
2/13/23, 4:22 AM How to Create Your Own Crypto Token | by Sarah Roff | Geek Culture | Medium

After hitting Deploy, your MetaMask extension will open and ask you to pay gas fees to
deploy the contract, but don’t fret, we’ll be using the test ETH we got from the Ropsten
Faucet earlier. Click confirm.

https://medium.com/geekculture/how-to-create-your-own-crypto-token-4097a173dd73 20/24
2/13/23, 4:22 AM How to Create Your Own Crypto Token | by Sarah Roff | Geek Culture | Medium

Once you click confirm, wait a few seconds for the creation of your token. Then extend
the terminal at the bottom of your code and click on the ‘block’ to reveal more details.

In the block details, locate your contract address (it will be after “from”:)and copy it.

https://medium.com/geekculture/how-to-create-your-own-crypto-token-4097a173dd73 21/24
2/13/23, 4:22 AM How to Create Your Own Crypto Token | by Sarah Roff | Geek Culture | Medium

Then, go into your MetaMask extension and click ‘Assets’ then ‘Import Tokens’ and
paste your contract address. Then, click ‘Add Custom Token’ and then ‘Import Tokens’
and your done!

Open in app Sign up Sign In


https://medium.com/geekculture/how-to-create-your-own-crypto-token-4097a173dd73 22/24
2/13/23, 4:22 AM How to Create Your Own Crypto Token | by Sarah Roff | Geek Culture | Medium
Ope app S g up Sg
Congratulations, you successfully created your very own crypto token!
Search Medium

Crypto Coding Solidity Tutorial Blockchain

Sign up for Geek Culture Hits


By Geek Culture

Subscribe to receive top 10 most read stories of Geek Culture — delivered straight into your inbox, once a week. Take a
look.

Your email

Get this newsletter

By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy
practices.

About Help Terms Privacy

https://medium.com/geekculture/how-to-create-your-own-crypto-token-4097a173dd73 23/24
2/13/23, 4:22 AM How to Create Your Own Crypto Token | by Sarah Roff | Geek Culture | Medium

Get the Medium app

https://medium.com/geekculture/how-to-create-your-own-crypto-token-4097a173dd73 24/24
2/13/23, 4:25 AM Tokenomics & the Importance of Strategic Token Structure | by Audrey Nesbitt | DataDrivenInvestor

Published in DataDrivenInvestor

You have 2 free member-only stories left this month. Sign up for Medium and get an extra one

Audrey Nesbitt Follow

Jul 24, 2018 · 7 min read · · Listen

Save

Tokenomics & the Importance of Strategic Token


Structure

Token: A privately issued/company issued currency. A unit of value within a specific


cryptocurrency ecosystem (the project, the community created within it, and the

https://medium.datadriveninvestor.com/tokenomics-1c79f2b796e4 1/9
2/13/23, 4:25 AM Tokenomics & the Importance of Strategic Token Structure | by Audrey Nesbitt | DataDrivenInvestor

dynamic interaction of all the participants within it including tokens, users, team
members, etc).

One of the major ways blockchain projects attract investors and users is through an
ICO — Initial Coin Offering (Crowdsale or also a TGE — Token Generating Event). How
well that token is structured will have a direct effect on the project. The value of the
network vastly increases alongside the number of users that adopt it, therefore the
tokenomics of the token, the how and why; the set of rules of the ecosystem of
where/how it will be used — is so important to the success of a project.

Tokenomics is the designing of the architecture of a token that will persuade investors
and or users to adopt it and help the ecosystem built around the currency to grow. The
tokens are the ‘fuel’ or currency that is used within the ecosystem — and are used to
exchange goods, services (utility token) or to own a piece of equity or debt (security
token).

Tokenomics can be further decomposed in ‘Microtokenomics’ (deals with single ledger


system) and ‘Macrotokenomics’ (to deal with entire ecosystem of a DLT network
(distributed ledger technology)[1]including its interaction with 3rd parties like
exchanges, regulators, partners, etc.

If you are looking at creating a token for an ICO/Crowdsale you need to know how you
are going to incentivize someone to buy it, hold it, use it, and trade it.

Design

Functionality, Token Distribution, Token Governance and value should be clearly


present in well-designed token. Token design or structure needs to be clear.

What action or utility does the token perform?

Is it scalable?

Does it have or require mass adoption (economies of scale)?

Is there a market for it?

Can it be traded on an exchange?


https://medium.datadriveninvestor.com/tokenomics-1c79f2b796e4 2/9
2/13/23, 4:25 AM Tokenomics & the Importance of Strategic Token Structure | by Audrey Nesbitt | DataDrivenInvestor

How many tokens will be created?

How will tokens be distributed?

How will the tokens be governed?

Usability
The usability of the token — how and why -need to be clearly defined. Tokens can be
multi-purpose instruments that can be utilized in various ways such as: to bestow
governance rights, to create a transactional economy between buyers and sellers
(Value Exchange), to make payments or for the purpose of profits/benefits sharing.
Token usability in any economic ecosystem must be clear and well explained.

Utility or Security
The design and attributes of token structure have significant importance, not just to
investors and users but to government regulators.

If a token is classified as a security they must be regulated. Many ICO’s try to fall under
the blanket of a utility token to avoid regulation and have access to a larger selling pool
however doing so, especially if they are selling to US citizens, puts the project and
project team members at great legal risk.

SEC Chairman Jay Clayton has stated, tokens and offerings that feature and market the
potential for profits based on the entrepreneurial or managerial efforts of others
contain the hallmarks of a security under U.S. law.

https://medium.datadriveninvestor.com/tokenomics-1c79f2b796e4 3/9
2/13/23, 4:25 AM Tokenomics & the Importance of Strategic Token Structure | by Audrey Nesbitt | DataDrivenInvestor

Security Tokens
If a token gains its value from an external, tradable asset, it is a security token. Security
tokens have evolved to empower traditional initial public offerings (IPOs) on top of
blockchain technology. The main reason to buy a security token is to, at some point,
earn a profit whether that is in the form of profits, revenue share or price
appreciation. Security tokens are heavily regulated and can only be sold to accredited
investors.

The SEC web site contains the full definition of accredited investors:

Individuals with annual income over $200K (individually) or $300K (with spouse) over the
last 2 years and an expectation of the same this year
Individuals with net assets over $1 million, excluding the primary residence (unless more is
owed on the mortgage than the residence is worth)
An institution with over $5 million in assets, such as a venture fund or a trust
An entity made up entirely of accredited investors

https://medium.datadriveninvestor.com/tokenomics-1c79f2b796e4 4/9
2/13/23, 4:25 AM Tokenomics & the Importance of Strategic Token Structure | by Audrey Nesbitt | DataDrivenInvestor

Utility Tokens
Utility tokens are also named as app tokens or user tokens. These tokens are issued by
companies to fund the development of the ecosystem or project where the utility token
will be utilized. The buyer is basically buying into the future use of a service or
product. Utility tokens are not designed as investments.

Dual Token Offerings


Security tokens may offer some level of security on behalf of the investor but there are
some issues. Compliance to the security token must continue after the token sale. This
includes a 12 month hold or lock-up period where the tokens can’t be sold and then
when they can be sold they can only do so to other accredited investors. If the project
needs the tokens at play in the ecosystem and or on the market to be sold to end users
this tied up capital could derail the project.

Startups are looking at presenting ‘dual token offerings’. In this type of offering a
security token is sold to an accredited investor and the second token is a utility token
sold to a user/customer.

RATE — Real Agreement for Tokens and Equity

The RATE structure allows a company to issue two tokens, one as equity compliant
with securities laws and the second token is offered to the investors as a bonus.[2]

The second token is the one that will be used to perform a specific service in the
ecosystem.

DATE — Debt Agreement for Tokens and Equity

This structure offers a convertible note (bond) or straight debt token with the utility
token as a perk.[3]

FACTS — [4]
The FACTS model uses both a security token and a utility token. The first is the security
token with is offered through an ICO or Crowdsale to accredited investors and is
compliant with the SEC. The second part is a token is distributed after the ICO in the
form of a property dividend to investors. The number of the second token issued

https://medium.datadriveninvestor.com/tokenomics-1c79f2b796e4 5/9
2/13/23, 4:25 AM Tokenomics & the Importance of Strategic Token Structure | by Audrey Nesbitt | DataDrivenInvestor

match exactly the number of the first token purchased and are not considered a
security.

Governance

How are rules going to be established? Will the founders set the rules or will there be a
board of directors? Do contributors get voting rights? To contributors have the
opportunity to elect the board?

What structures and processes are in place to oversee the direction of the company to
make sure it stays on course?

In decentralized communities, good governance is critical for the long-term success of


the industry. For the growth of the industry and to continue attracting investors to
blockchain startups as a whole we need to be accountable, to the best of our ability, to
those investing in us.

Token Allocation

Who gets what?

How many tokens are up for public sale? What percentage of tokens is going to team
members? Is that number fair? Is a large percentage being sold to investors privately?
Does that affect the number of tokens available to users whom ultimately run the
ecosystem?

Many ICO’s show a large chunk of initial funds going to team members. A concern of
that approach is team members not being incentivized to further develop the project
because they have already received large paychecks.

A good project will link its token distribution to the roadmap and use escrow to protect
investors funds. If a milestone is not met the funds can be released back to the
investor.

Token Distribution

What is the potential of the token increase in value once it is released?

https://medium.datadriveninvestor.com/tokenomics-1c79f2b796e4 6/9
2/13/23, 4:25 AM Tokenomics & the Importance of Strategic Token Structure | by Audrey Nesbitt | DataDrivenInvestor

Supply and Demand

Supply is defined as the total quantity of a product or service that the marketplace can
offer; demand refers to the quantity of a good that is desired by buyers. In regards to
an ICO is there a token cap or limited supply? Or is there an unlimited supply of tokens
that are supplied at a fixed price (like a one-time-use ticket or for the use of a service or
to play a game)?

Unlimited number of tokens — fixed

Set number of tokens — volatile

If it’s important that the tokens are being utilized (used in the ecosystem) and a large
number of investors are HODLing (holding) than the ecosystem does not grow causing
price volatility.

What does it all mean?

To upcoming ICO’s, how well you structure your token will dictate how successful it
will be during the ICO and after. From the perspective of the investor it shows the
potential in the project and at the end of the day it’s investors and or users you need to
get to believe in your token design, therefore your project.

Audrey Nesbitt

SpinSpirational Marketing & PR

Audrey Nesbitt on Linkedin

@AudreyNesbitt11 on Twitter

https://medium.datadriveninvestor.com/tokenomics-1c79f2b796e4 7/9
2/13/23, 4:25 AM Tokenomics & the Importance of Strategic Token Structure | by Audrey Nesbitt | DataDrivenInvestor

[1] https://www.he3labs.com/blog/2018/6/4/what-is-tokenomics

[2] https://hackernoon.com/security-tokens-are-doa-8ba1bb9f9368

[3] https://hackernoon.com/security-tokens-are-doa-8ba1bb9f9368

[4]https://www.coindesk.com/basics-facts-new-model-compliant-icos/

https://medium.datadriveninvestor.com/tokenomics-1c79f2b796e4 8/9
2/13/23, 4:25 AM Tokenomics & the Importance of Strategic Token Structure | by Audrey Nesbitt | DataDrivenInvestor

Blockchain Cryptocurrency Investment Security ICO

About Help Terms Privacy

Open in app Sign up Sign In

Get the Medium app


Search Medium

https://medium.datadriveninvestor.com/tokenomics-1c79f2b796e4 9/9
2/13/23, 4:27 AM Javascript testing with Mocha: A Series | by Cedric Damian | Practical Software Testing | Medium

Published in Practical Software Testing

Cedric Damian Follow

Apr 28, 2021 · 4 min read · Listen

Save

Javascript testing with Mocha: A Series


Part 1: Introduction and running a sample test with Mocha and Chai

Mocha is an open-source Javascript test framework that runs on Nodejs and on the
browser and is used for testing Synchronous and Asynchronous code. Being my
favorite type of coffee and also one of the most depended upon modules on npm
according to Libraries.io, I thought it would be a good idea to write a series of articles
about it. This first article will give you a solid introduction to Mocha and using it with
Node.js. For this series, you will need to have Node and npm installed.

Mocha provides functions that are executed in a specific order and logs their results to
a terminal window. Mocha uses hooks to organize its structure. They include:

describe(): Used to group one or more test cases and can be nested.

it(): the test case is laid down here

https://medium.com/practical-software-testing/javascript-testing-with-mocha-a-series-f4bfcab26532 1/8
2/13/23, 4:27 AM Javascript testing with Mocha: A Series | by Cedric Damian | Practical Software Testing | Medium

before(): It’s a hook to run before the first it() or describe();

beforeEach(): It’s a hook to run before each it() or describe();

after(): It’s a hook to run after it() or describe();

afterEach(): It’s a hook to run after each it() or describe();

The keywords describe and it provide structure to the tests by grouping them into Test
cases and Test suites. A Test case is a set of actions executed to validate a feature or
functionality of your software. A Test Suite is a collection of tests all relating to a
similar functionality or behavior.

Mocha can be used with any assertion library but for this series, we will use Chai(local
for Tea), a popular assertion library for Node.js and the browser. It provides functions
and methods which help you compare the output of a test with the expected result.
Chai provides clean syntax that reads almost like English. An example of a Chai
assertion is expect(exampleArray).to.have.lengthOf(3);

This simply validates whether the variable ‘exampleArray’ has a length of 3 or not.
Alright, enough talk, let us dive into the code already.

Setting up Mocha and Chai


The code for this tutorial will be updated here. First things first, you will need to install
Mocha. To install globally, fire up your terminal and run this:

npm i — global mocha

This will make the mocha CLI binary available for use in your command line terminal.
You can now run tests in your terminal with the command mocha . Next, we will write a
unit test for a simple functionality and configure a script to run it with Mocha.
Mocha.js automatically looks for tests inside the test folder of your project so go ahead
and create this in your project root.

https://medium.com/practical-software-testing/javascript-testing-with-mocha-a-series-f4bfcab26532 2/8
2/13/23, 4:27 AM Javascript testing with Mocha: A Series | by Cedric Damian | Practical Software Testing | Medium

mkdir test

Configure the test script in your package.json to run tests in mocha. It should look like
this:

{
"scripts": {
"test": "mocha"
}
}

Now you can simply run your tests with this simple command:

npm test

Next, we will install Chai. Simply run:

npm install chai

Writing tests using Mocha and Chai


Now the Setup is all done, let us create a test case of A calculator which will perform
the basic arithmetic operations:

Addition

Subtraction

Division

Multiplication

We will need to first set up a file to store the configuration of our arithmetic methods.
Create a file src/calculator.js and add the following code:
https://medium.com/practical-software-testing/javascript-testing-with-mocha-a-series-f4bfcab26532 3/8
2/13/23, 4:27 AM Javascript testing with Mocha: A Series | by Cedric Damian | Practical Software Testing | Medium

const add = (a, b) => a + b


const subtract = (a, b) => a - b
const multiply = (a, b) => a * b
const divide = (a, b) => b !== 0 ? (a / b) : undefined module.exports
= {
add,
subtract,
multiply,
divide,
}

Here, we define the rules that our functions will follow. Notice that in divide , we
create a condition to check whether the denominator passed is 0 and return undefined

in that case.

Create a test.js file inside your test directory and add the following code:

const chai = require('chai')


const expect = chai.expect
const calculator = require('../src/calculator')
describe('Calculator', () => {
describe('Addition', () => {
it('should sum two numbers', () => {
expect(calculator.add(2, 2)).to.equal(4)
expect(calculator.add(50, 39)).to.equal(89)
})
})
describe('Subtraction', () => {
it('should subtract two numbers', () => {
expect(calculator.subtract(6, 2)).to.equal(4)
expect(calculator.subtract(50, 39)).to.equal(11)
})
})
describe('Multiplication', () => {
https://medium.com/practical-software-testing/javascript-testing-with-mocha-a-series-f4bfcab26532 4/8
2/13/23, 4:27 AM Javascript testing with Mocha: A Series | by Cedric Damian | Practical Software Testing | Medium

it('should multiply two numbers', () => {


expect(calculator.multiply(3, 2)).to.equal(6)
expect(calculator.multiply(-31, 32)).to.equal(-992)
expect(calculator.multiply(-5, -2)).to.equal(10)
})
})

describe('Division', () => {
it('should divide two numbers', () => {
expect(calculator.divide(4, 2)).to.equal(2)
expect(calculator.divide(50, 5)).to.equal(10)
})
it('should return NaN if the denominator is zero', () => {
expect(calculator.divide(4, 0)).to.equal(undefined)
expect(calculator.divide(-15, 0)).to.equal(undefined)
})
})
})

The code, in Addition , Subtraction and Multiplication is pretty straightforward. You


describe what the test case does in English and inside that function, describe the
assertions using Chai syntax, passing in sample inputs. More about Chai assertions can
be found in the Chai documentation.

Note that under Division , we have nested two it functions. I want to emphasize the
second function which handles the division in case the denominator is 0. This is an
important feature to note.

You can now run your test case using:

npm test

https://medium.com/practical-software-testing/javascript-testing-with-mocha-a-series-f4bfcab26532 5/8
2/13/23, 4:27 AM Javascript testing with Mocha: A Series | by Cedric Damian | Practical Software Testing | Medium

This should return the following results:

And that’s all for the first tutorial of this series! You have successfuly run your first test
suite with Mocha and Chai.

https://medium.com/practical-software-testing/javascript-testing-with-mocha-a-series-f4bfcab26532 6/8
2/13/23, 4:27 AM Javascript testing with Mocha: A Series | by Cedric Damian | Practical Software Testing | Medium

Since you’ve made it this far, please consider following me for other articles on this
series.

Cheers.

Java Script Testing Mocha Chai


Open in app Get unlimited access

https://medium.com/practical-software-testing/javascript-testing-with-mocha-a-series-f4bfcab26532 7/8
2/13/23, 4:27 AM Javascript testing with Mocha: A Series | by Cedric Damian | Practical Software Testing | Medium

Search Medium

https://medium.com/practical-software-testing/javascript-testing-with-mocha-a-series-f4bfcab26532 8/8
2/13/23, 4:29 AM Testing NodeJS app using Mocha and Chai | by Ashish | Medium

Ashish Follow

Aug 26, 2019 · 3 min read · Listen

Save

Testing NodeJS app using Mocha and Chai

Introduction:

Once you are done with coding the main features of your app, it is very important to
implement standard software testing methodologies. In order to make sure that your
app behaves as expected, you have to write code coverage test cases.

Software testing is very useful when you are introducing new modules in your app.
Having a testing environment with test cases already in place makes it very easy to
quickly check if this new module is introducing new bugs in the app.

In this tutorial, we will learn how to write unit test cases using Mocha and Chai in a
NodeJS application. Just to give a basic introduction of these libraries, Mocha is a
feature-rich JavaScript test framework running on Node.js and in the browser. Chai is
an assertion library for node.

https://medium.com/@ashish_fagna/testing-nodejs-app-using-mocha-and-chai-ce76a077f947 1/10
2/13/23, 4:29 AM Testing NodeJS app using Mocha and Chai | by Ashish | Medium

In this tutorial, I will show a Simple ToDo list endpoints along with User authentication
endpoints and then show how test cases are written for code coverage. Below are the
two APIs written followed by the test cases for the same.

1. ToDo APIs:

First, we need to create ToDo model. Here is the document structure for the same:

Here are the basic end points for reading and writing entries in ToDo list :

https://medium.com/@ashish_fagna/testing-nodejs-app-using-mocha-and-chai-ce76a077f947 2/10
2/13/23, 4:29 AM Testing NodeJS app using Mocha and Chai | by Ashish | Medium

The below shown code is another route to retrieve a todo list item given its id.

https://medium.com/@ashish_fagna/testing-nodejs-app-using-mocha-and-chai-ce76a077f947 3/10
2/13/23, 4:29 AM Testing NodeJS app using Mocha and Chai | by Ashish | Medium

2. User APIs:

Here is the structure for the User Model.

https://medium.com/@ashish_fagna/testing-nodejs-app-using-mocha-and-chai-ce76a077f947 4/10
2/13/23, 4:29 AM Testing NodeJS app using Mocha and Chai | by Ashish | Medium

Here are the basic end points for user signup and login :

https://medium.com/@ashish_fagna/testing-nodejs-app-using-mocha-and-chai-ce76a077f947 5/10
2/13/23, 4:29 AM Testing NodeJS app using Mocha and Chai | by Ashish | Medium

3. Test Cases:

In order to do test coverage, we will add dummy data to both User and ToDo
Collections. Here are a few tests written for ToDo routes:

https://medium.com/@ashish_fagna/testing-nodejs-app-using-mocha-and-chai-ce76a077f947 6/10
2/13/23, 4:29 AM Testing NodeJS app using Mocha and Chai | by Ashish | Medium

This below code will test retrieving items from ToDo collection.

Open in app Get unlimited access

The below shown route will add new items to the ToDo list and test it.
Search Medium

https://medium.com/@ashish_fagna/testing-nodejs-app-using-mocha-and-chai-ce76a077f947 7/10
2/13/23, 4:29 AM Testing NodeJS app using Mocha and Chai | by Ashish | Medium

Here are a few tests for User Route :

This test demonstrates how we can test the user login route.

https://medium.com/@ashish_fagna/testing-nodejs-app-using-mocha-and-chai-ce76a077f947 8/10
2/13/23, 4:29 AM Testing NodeJS app using Mocha and Chai | by Ashish | Medium

The below shown code tests the user signup route.

https://medium.com/@ashish_fagna/testing-nodejs-app-using-mocha-and-chai-ce76a077f947 9/10
2/13/23, 4:29 AM Testing NodeJS app using Mocha and Chai | by Ashish | Medium

Conclusion:

You can access the complete code on this Github link. I hope this tutorial helps you get
a good understanding of how you can write test cases for your application in NodeJS.

Mocha Chai Nodejs Testing Unit Testing

https://medium.com/@ashish_fagna/testing-nodejs-app-using-mocha-and-chai-ce76a077f947 10/10
2/13/23, 4:31 AM How To: Test A Smart Contract Using The Mocha Testing Framework | by Morgan Fogarty | Medium

Morgan Fogarty Follow

Oct 25, 2018 · 5 min read · Listen

Save

How To: Test A Smart Contract Using The Mocha


Testing Framework
In two previous blog posts, we’ve written a smart contract using the Solidity
programming language and compiled the smart contract to prepare it for deployment.
Now we’ll test the code using the Mocha testing framework.

If you’re unfamiliar with Mocha, take a look at the Mocha docs and/or spend some time
with this tutorial.

In addition to Mocha, we’ll use Ganache and Web3. Ganache will provide us with a set
of unlocked accounts we will use in our local testing environment. In this case
“unlocked” means that there is no need to use a public or private key to access them.
Web3 provides libraries which will allow us access to a local or remote Ethereum node.
For testing purposes, we’ll be connecting to a local node, also provided by Ganache.

Let’s get started.

In the terminal and within your project, type npm install --save mocha ganache-cli

web3@1.0.0-beta.28 (or whichever is the latest version of web3).

Next, create a test folder, a sibling of the contracts folder. Inside of the test folder,
create a file called hello.test.js .

Let’s start coding :)

https://morganfogarty.medium.com/how-to-test-a-smart-contract-using-the-mocha-testing-harness-e700913ec26c 1/7
2/13/23, 4:31 AM How To: Test A Smart Contract Using The Mocha Testing Framework | by Morgan Fogarty | Medium

First, require the Mocha assertion library, Ganache and Web3. Notice that we capitalize
Web3 . It is a constructor, and we’ll be using an instance of it in our code.

Require interface and the bytecode from our compile.js file that we created in the
previous blog post.

Create a provider variable and pass it into our instance of Web3 . This lets Web3 know
where it will be getting account information.

That’s our prep code! Now we need to decide what we’ll be testing and why. As of right
now, we have access to unlocked accounts and a connection to a local Ethereum node.
Let’s take a look at our smart contract to decide what its behaviors should be.

https://morganfogarty.medium.com/how-to-test-a-smart-contract-using-the-mocha-testing-harness-e700913ec26c 2/7
2/13/23, 4:31 AM How To: Test A Smart Contract Using The Mocha Testing Framework | by Morgan Fogarty | Medium

The contract has two functions which we’ll want to test. Does it set an initial message?
Does it set a new message?

For either of these functions to be tested, we need to deploy the contract to the local
testing environment.

So in addition to testing the functions, we’ll want to make sure that the contract is
deploying in the first place. To test this, we’ll check to see that it has an address.

Let’s start with a beforeEach() hook. Since we need to deploy an instance of the
contract each time we run the tests, we’ll make that happen in the beforeEach() .

https://morganfogarty.medium.com/how-to-test-a-smart-contract-using-the-mocha-testing-harness-e700913ec26c 3/7
2/13/23, 4:31 AM How To: Test A Smart Contract Using The Mocha Testing Framework | by Morgan Fogarty | Medium

On line 13 we get a list of all accounts. To do this, we use the eth (Ethereum) module of
the Web3 library. On that module we use the getAccounts() method. Every action in
Web3 is asynchronous and will return a promise. This accounts variable will return a
promise that gets resolved with a list of accounts. We will be using one of those
accounts to deploy our contract.

On line 14 we create an instance of our contract, passing in the parsed interface from
our compile.js file. On line 15 we’re not actually deploying, despite the method’s
name. What we’re doing is setting up the contract instance with the data in the form of
bytecode from compile.js and with the initial string we want to use. We wrap the
arguments value in brackets, because the method can take more than one argument.
The send() method actually deploys the contract. We specify the address the contract
is coming from. In this case we’ll use the first of the unlocked accounts provided to us
by Ganache accounts[0] . And we’ll specify the amount of gas to send along to
complete the deployment. Remember, we’re using fake gas in a local environment, so
let’s use more than enough. 1000000 gas will do.

On lines 18 and 19 we set the provider and log the accounts.

Let’s add at least one test so that we can see the logged accounts (a beforeEach() hook
will not run without a test).

Remember, we are checking to be sure the contract deploys, so here we are asserting
that the contract has an address.

Before we run our test, let’s hop over to our package.json and in scripts , replace the
current value of test with "mocha" .

Go to your terminal at the root of your project and type npm run test .

https://morganfogarty.medium.com/how-to-test-a-smart-contract-using-the-mocha-testing-harness-e700913ec26c 4/7
2/13/23, 4:31 AM How To: Test A Smart Contract Using The Mocha Testing Framework | by Morgan Fogarty | Medium

Your test should pass and you should get a list of the ten unlocked accounts you’ll be
using for the rest of your tests!

This is exciting. Let’s finish writing our tests.

We know that a contract has an address, now we’d like to test that the contract has a
default message, and that the message can be changed.

has a default message test

https://morganfogarty.medium.com/how-to-test-a-smart-contract-using-the-mocha-testing-harness-e700913ec26c 5/7
2/13/23, 4:31 AM How To: Test A Smart Contract Using The Mocha Testing Framework | by Morgan Fogarty | Medium

The “default message” test is relatively simple. On line 28 we reference the hello

contract. We then reference one of the methods on the hello contract, which we
delved into in the previous blog post, and we use the call() method to invoke the
function. We get to use the call() method for free, sans gas, because we are not
updating information on the contract. We assert that the default message will be "Hey

world" because that is what we set in our beforeEach() hook.

Let’s test it.

Woohoo! Two passing tests. Can we make it three?

changes the message

On line 34 we again reference the hello contract. This time we access the contract’s
setMessage() method, which requires a new message to be passed in. The send()

method requires an address, which tells us which account is paying the gas for this
transaction. Unlike the call() method the send() method is modifying the hello

contract, and will cost gas.

Let’s try it.

https://morganfogarty.medium.com/how-to-test-a-smart-contract-using-the-mocha-testing-harness-e700913ec26c 6/7
2/13/23, 4:31 AM How To: Test A Smart Contract Using The Mocha Testing Framework | by Morgan Fogarty | Medium

Yay

Our Smart Contract deploys an account, has a default message and changes the
message.
Open in app Tune in next time when we deploy our Smart Contract to a test
Getnetwork.
unlimited access

Search Medium

Java Script Solidity Mocha Smart Contracts Nodejs

https://morganfogarty.medium.com/how-to-test-a-smart-contract-using-the-mocha-testing-harness-e700913ec26c 7/7
2/13/23, 4:33 AM Solidity Smart Contract Interaction and Testing with Web3.Js and Mocha | by Anindio Daneswara | Jakarta Blockchain | Medium

Anindio Daneswara | Jakarta Blockchain Follow

Aug 19, 2021 · 7 min read · Listen

Save

Solidity Smart Contract Interaction and Testing


with Web3.Js and Mocha

Photo by Executium on Unsplash

In this article we will discuss how to connect, interact and deploy our smart contract
written in Solidity from our JavaScript environment and using JavaScript libraries such

https://daneswa.medium.com/solidity-smart-contract-interaction-and-testing-with-web3-js-and-mocha-3a0467a01805 1/9
2/13/23, 4:33 AM Solidity Smart Contract Interaction and Testing with Web3.Js and Mocha | by Anindio Daneswara | Jakarta Blockchain | Medium

as Truffle, web3.js to interact with our smart contract and lastly, we will test it with
Mocha and deploy it to Rinkeby testnet using Infura node API.

Writing a clean and (cost-) efficient smart contract poses a challenge, however,
interacting it with DApps using truffle framework and web3.js introduces another
challenges. Since when we’re writing smart contract , will somehow sooner or later
involves real money, we need to test each of the function in the smart contract.

Let’s start with the smart contract. We will just write a short smart contract with a
getter function and a setter function so we know the different between “calling a
function” and “invoking/sending a transaction”.

// SPDX-License-Identifier:GPL-3.0

pragma solidity ^0.4.17;

contract Inbox {
string public message;
function Inbox(string initialMessage) public {
message = initialMessage;
}
function setMessage(string memory newMessage) public {
message = newMessage;
}
function getMessage() public view returns(string memory) {
return message;
}
}

Please note that since we’re using Solidity version 0.4.17 (which is an outdated version,
for the sake of compatibility), the constructor function is still using the function with
the same exact name as the contract name which is Inbox.

Looking at the contract, we have one getter function message and getMessage() , (two to
be exact, but perform the same operation), and one setter function setMessage() to
update the value of state variable message.

https://daneswa.medium.com/solidity-smart-contract-interaction-and-testing-with-web3-js-and-mocha-3a0467a01805 2/9
2/13/23, 4:33 AM Solidity Smart Contract Interaction and Testing with Web3.Js and Mocha | by Anindio Daneswara | Jakarta Blockchain | Medium

A couple of notes here when writing the contract, this contract was written using
Remix and somehow it threw errors when writing all the functions without saving the
arguments in the memory. This should not be happen if we use the updated version
^0.8.0.

Project Boilerplate
The project boilerplate will consist of following files and folders :

contract
--->Inbox.sol
|
|
node_modules
|
|
test
--->Inbox.test.js
|
|
compile.js
deploy.js
package-lock.json
package.json

There are three folders; contracts, node_modules and test. We will discuss each one of
them and the files inside each folders.

After running npm init, we need to define and install our dependencies for this project
:

{
"name": "inbox",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "mocha"
},
"author": "",
"license": "ISC",
"dependencies": {
https://daneswa.medium.com/solidity-smart-contract-interaction-and-testing-with-web3-js-and-mocha-3a0467a01805 3/9
2/13/23, 4:33 AM Solidity Smart Contract Interaction and Testing with Web3.Js and Mocha | by Anindio Daneswara | Jakarta Blockchain | Medium

"ganache-cli": "^6.12.2",
"mocha": "^9.0.3",
"solc": "^0.4.17",
"truffle-hdwallet-provider": "0.0.3",
"web3": "^1.0.0-beta.26"
}
}

To install the dependencies we run the following command :

npm install --save ganache-cli mocha solc@0.4.17 truffle-hdwallet-


provider@0.0.3 web3@1.0.0-beta.26

Note that for the sake of compatibility, in some dependencies, we need to define the
package version.

For testing with mocha, we change the test script to mocha.

"test": "mocha"

Now we have our smart contract and node.js dependencies ready, we will try to
compile it first by writing the compile.js file :

const path = require('path');


const fs = require('fs');
const solc = require('solc');
//pointing to file location
const inboxPath = path.resolve(__dirname, 'contracts', 'Inbox.sol');
//read the file content
const source = fs.readFileSync(inboxPath, 'utf8');
//exporting solc compiler output for consumption by other file
module.exports = solc.compile(source, 1).contracts[':Inbox'];

We will walkthrough each of the line in code snippet above;

https://daneswa.medium.com/solidity-smart-contract-interaction-and-testing-with-web3-js-and-mocha-3a0467a01805 4/9
2/13/23, 4:33 AM Solidity Smart Contract Interaction and Testing with Web3.Js and Mocha | by Anindio Daneswara | Jakarta Blockchain | Medium

JavaScript can import content from another file using require statement, however, our
smart contract is not a JavaScript file hence can not be read using require syntax. We
will need to read the solidity file manually and to do so, we will need to import 2 built-
in functions to read the content of the file which are; path and fs.

We’ll assign path to point to the contract directory location and pass the variable to fs
module to read the file.

Then we’ll compile the contract using solc and make it available by exporting using
module.exports.

After our attempt to compile it, we want to write a test to test out each getter/setter
function in the contract.

We will now create a new file called Inbox.test.js which has following lines of code and
walkthrough it ;

const assert = require('assert');


const ganache = require('ganache-cli');
const Web3 = require('web3');
const { interface, bytecode } = require('../compile');

We use assert module to perform testing and ganache to become our provider to
communicate with our Ethereum network later on.

Notice that we pass the module web3 to Web3, by using uppercase. This is because
Web3 is not a variable, instead it will serve as constructor function, from which web3
instances can be created from using lowercase.

To create a web3 provider, we add the following code

const web3 = new Web3(ganache.provider());

Then we will write the testing environment using Mocha

https://daneswa.medium.com/solidity-smart-contract-interaction-and-testing-with-web3-js-and-mocha-3a0467a01805 5/9
2/13/23, 4:33 AM Solidity Smart Contract Interaction and Testing with Web3.Js and Mocha | by Anindio Daneswara | Jakarta Blockchain | Medium

let accounts;
let inbox;
beforeEach(async () => {
// get list of all accounts
accounts = await web3.eth.getAccounts();
// this variable teaches web3 what methods an Inbox contract has and
//access the ABI
inbox = await new web3.eth.Contract(JSON.parse(interface))
// tells web3 we want to deploy a copy of the contract with an
//argument
.deploy({
data: bytecode,
arguments: ['Hi there!'],
})
// tells web3 to send out a transaction that creates this contract
//and point which account and how many gas responsible in contract
//deployment
.send({ from: accounts[0], gas: '1000000' });
});
describe('Inbox', () => {
it('deploys a contract', () => {
assert.ok(inbox.options.address);
});
it('has a default message', async () => {

const message = await inbox.methods.message().call();


assert.equal(message, 'Hi there!');
});
it('updates the message', async () => {
await inbox.methods.setMessage('bye').send({ from:accounts[0]
});
const message = await inbox.methods.message().call();
assert.equal(message, 'bye');
});
});

As we know, using Mocha for testing, will involve 3 components :

beforeEach()

describe()

https://daneswa.medium.com/solidity-smart-contract-interaction-and-testing-with-web3-js-and-mocha-3a0467a01805 6/9
2/13/23, 4:33 AM Solidity Smart Contract Interaction and Testing with Web3.Js and Mocha | by Anindio Daneswara | Jakarta Blockchain | Medium

it()

I will not deep dive into each one of the components and will have a short tutorial on
how to use Mocha, but in short, beforeEach() is used as some sort of constructor
function where it will run commands which invoked in every test and to make our
code more cleaner and to have a DRY code, we will put the command in this
component.

describe() is basically a group of commands to do testing. it() will run each command to
test, in this case we will use assert.ok and assert.equal.

First we will declare 2 global variables to be use in Mocha, accounts and inbox. Then we
will use web3.eth.getAccounts() module to get the accounts address and
web3.eth.Contract(JSON.parse(interface)) to parse the JSON ABI after we compile the
contract.

Remember that every time we compile a Solidity smart contract, the compiler will spit
out two files :

ABI in form of JSON

Bytecode

Since we will actually going to deploy this contract in order to test it, and every
command in web3 is async by nature (starting from web3 1.x), we will chain inbox
function variable with .deploy and .send. We will deploy the bytecode to EVM provided
by Ganache and sending Ether for the gas fee. We have to put also the initial message
[‘Hi There’] because the smart contract requires us to pass the initial message when
deploying the contract.

There are 2 assert method in the testing script :

assert.ok, to test the contract has been deployed and spit out the smart contract
address

assert.equal, to check the both the initial message in the getter function and to
check the setter function really doing its job by updating the message.

https://daneswa.medium.com/solidity-smart-contract-interaction-and-testing-with-web3-js-and-mocha-3a0467a01805 7/9
2/13/23, 4:33 AM Solidity Smart Contract Interaction and Testing with Web3.Js and Mocha | by Anindio Daneswara | Jakarta Blockchain | Medium

Notice there 2 type of methods in both inbox.methods.message().call() and


inbox.methods.setMessage(‘bye’).send({ from:accounts[0] }). This part is, in my opinion is
the most important thing in this post, that .call() will actually only calling a value of a
function and does not modify the blockchain, hence costs no gas and .send() will
actually modify the blockchain by updating the value hence will cost gas for this
operation.

To run the test, invoke this

npm run test

Time to Deploy
Now we will write our deploy.js file

const HDWalletProvider = require('truffle-hdwallet-provider');


const Web3 = require('web3');
const { interface, bytecode} = require('./compile');
const provider = new HDWalletProvider(

'[put your 12 mnemonic phrases here]',


'https://rinkeby.infura.io/v3/087d0eb82bcf4c8eb2dcb9dfde3xxxxx'
);
const web3 = new Web3(provider);
// we have to create a function in order to use async await syntax
// all functions are the same as in the testing script
const deploy = async () => {
const accounts = await web3.eth.getAccounts();
console.log('Attempting to deploy from account', accounts[0]);
const result = await new web3.eth.Contract(JSON.parse(interface))
.deploy({
data:bytecode,
arguments:['Hi There!'],
})
.send({
from:accounts[0],

https://daneswa.medium.com/solidity-smart-contract-interaction-and-testing-with-web3-js-and-mocha-3a0467a01805 8/9
2/13/23, 4:33 AM Solidity Smart Contract Interaction and Testing with Web3.Js and Mocha | by Anindio Daneswara | Jakarta Blockchain | Medium

gas:'30000000',
});
console.log('Contract deployed to ', result.options.address);
};

We will use Infura node to connect to Rinkeby Test Network .The code itself is pretty
much straight forward and basically almost the same as our testing script without the
assert methods but with added console.log so we know what happen in the background.
However we import truffle-hdwallet-provider NPM package as our provider so that we
can use our own address derived from 12 mnemonic phrases and sign the transaction
with it.

Basically we’re done writing the code and we can deploy by typing

Open in app Get unlimited access


node deploy.js
Search Medium

As we can see from the code above, we will spend most of the time to test the function
in the contract, and this will be our the most important thing since the transaction on
the Mainnet will involve real money and we want to make sure our contract and
application running properly in Testnet before deploying in to Mainnet.

Blockchain Solidity Ethereum Web 3 Programming

https://daneswa.medium.com/solidity-smart-contract-interaction-and-testing-with-web3-js-and-mocha-3a0467a01805 9/9
2/13/23, 4:39 AM How to Debug Solidity contracts in Webstorm + Hardhat | by Allen | Coinmonks | Medium

Published in Coinmonks

Allen Follow

Aug 12, 2021 · 4 min read · Listen

Save

Debug Solidity contracts in Webstorm and Hardhat

How to Debug Solidity contracts in Webstorm +


Hardhat
https://medium.com/coinmonks/how-to-debug-solidity-contracts-in-webstorm-hardhat-2ea0d3c4d582 1/8
2/13/23, 4:39 AM How to Debug Solidity contracts in Webstorm + Hardhat | by Allen | Coinmonks | Medium

This is a continuation of my learnings from debugging Solidity contracts with Truffle. If you
are using Truffle for local development environment, you might want to start there.

Hardhat is now my preferred tool for local Solidity development. Although, there is not
a fancy GUI, the CLI has does more than enough to support serious Solidity
development. It just works. The speed at which you can develop and test is really
unmatched (from what I’ve seen). On top of that, there are lots of open-source plugins
for many different use-cases.

Alright, so if this is your first bout with Hardhat you’ll need to prepare somethings.
Grab the latest NodeJS LTS version installed (I tested with v.14.17.5) and then open a
Terminal.

https://medium.com/coinmonks/how-to-debug-solidity-contracts-in-webstorm-hardhat-2ea0d3c4d582 2/8
2/13/23, 4:39 AM How to Debug Solidity contracts in Webstorm + Hardhat | by Allen | Coinmonks | Medium

Installing NodeJS with NVM

With that open terminal, let’s call our first Hardhat task to start our simple project.
Move to a new and clean directory then run the following command.

mkdir -p ~/code/hardhat/welcome && cd "$_" && npx hardhat init

After running that, NPM will take care downloading, installing, and then running
Hardhat with the supplied argument. Which in turn, should present you with a
Hardhat welcome screen.

Hardhat welcome screen. All journeys start somewhere.

https://medium.com/coinmonks/how-to-debug-solidity-contracts-in-webstorm-hardhat-2ea0d3c4d582 3/8
2/13/23, 4:39 AM How to Debug Solidity contracts in Webstorm + Hardhat | by Allen | Coinmonks | Medium

From this welcome screen, Hardhat starts the project survey. Respond with the
following answers (it should be enough to hit Enter 4 times). Upon answering the final
question, Hardhat will create your project at the specified root file path with some
sample files and then install the dependencies. This part could take a few minutes
depending on your Internet speed + CPU.

✔ What do you want to do? · Create a sample project


✔ Hardhat project root: · hardhat-sample
✔ Do you want to add a .gitignore? (Y/n) · y
✔ Do you want to install the sample project's dependencies with npm
(hardhat @nomiclabs/hardhat-waffle ethereum-waffle chai
@nomiclabs/hardhat-ethers ethers)? (Y/n) · y

Hardhat welcome project

https://medium.com/coinmonks/how-to-debug-solidity-contracts-in-webstorm-hardhat-2ea0d3c4d582 4/8
2/13/23, 4:39 AM How to Debug Solidity contracts in Webstorm + Hardhat | by Allen | Coinmonks | Medium

Now, let’s point our terminal at the new project and take a peek. If everything looks
similar to this, we can continue.

~/code/hardhat/welcome ⌚ 6:22:38
$ ls
contracts node_modules package.json test
hardhat.config.js package-lock.json scripts

From here, we need to switch over to Webstorm. Open this new project in Webstorm.
Then, open up the package.json file. The only thing missing from having Webstorm
build run/debug configurations is the scripts field. Let’s add a new NPM run script for
executing our Hardhat tests. Your package.json should look something like this.

{
"name": "hardhat-project",
"scripts": {
"test": "hardhat test"
},
"devDependencies": {
"@nomiclabs/hardhat-ethers": "2.0.2",
"@nomiclabs/hardhat-waffle": "2.0.1",
"chai": "4.3.4",
"ethereum-waffle": "3.4.0",
"ethers": "5.4.4",
"hardhat": "2.6.0"
}
}

If everything went according to plan, after you save the file, Webstorm should
automatically recognize the new configurations, and give you a neat play icon in the
left gutter of the editor pane. Let’s click that and then in the pop-up menu, click Debug

"test" .

https://medium.com/coinmonks/how-to-debug-solidity-contracts-in-webstorm-hardhat-2ea0d3c4d582 5/8
2/13/23, 4:39 AM How to Debug Solidity contracts in Webstorm + Hardhat | by Allen | Coinmonks | Medium

Click the play icon on the scripts field in the package.json to automatically create a run configuration.

Once you do that, Webstorm takes care of starting a NodeJS debugger process and you
can start setting breakpoints in your test scripts. If you open up the sample-test.js file
and start setting breakpoints to try it out.

https://medium.com/coinmonks/how-to-debug-solidity-contracts-in-webstorm-hardhat-2ea0d3c4d582 6/8
2/13/23, 4:39 AM How to Debug Solidity contracts in Webstorm + Hardhat | by Allen | Coinmonks | Medium

Open in app Get unlimited access

Search Medium

Breakpoint set within JavaScript to test Solidity contract.

From here, there are a ton of awesome things you can test. This setup can take you
pretty far in your Solidity development. I know it’s not a true debug of Solidity. I am
still looking for a plugin to help debug Solidity code directly from Webstorm. Remix
IDE seems to be the only option AFAIK. But, I leave that for another day. — Allen

Solidity Hardhat Ethereum Java Script Blockchain Development

Sign up for Coinmonks


By Coinmonks

https://medium.com/coinmonks/how-to-debug-solidity-contracts-in-webstorm-hardhat-2ea0d3c4d582 7/8
2/13/23, 4:39 AM How to Debug Solidity contracts in Webstorm + Hardhat | by Allen | Coinmonks | Medium

A newsletter that brings you day's best crypto news, Technical analysis, Discount Offers, and MEMEs directly in your
inbox, by CoinCodeCap.com Take a look.

Emails will be sent to waledmunker@gmail.com. Not you?

Get this newsletter

https://medium.com/coinmonks/how-to-debug-solidity-contracts-in-webstorm-hardhat-2ea0d3c4d582 8/8
2/13/23, 4:41 AM Tips for Testing in Hardhat. How I test and debug my smart… | by Elim Poon | Coinmonks | Medium

Published in Coinmonks

Elim Poon Follow

Feb 13, 2022 · 3 min read · Listen

Save

Tips for Testing in Hardhat


How I test and debug my smart contracts.

Image by @whoisdenilo on Unsplash.com

Introduction
https://medium.com/coinmonks/tips-for-testing-in-hardhat-c59e03837c92 1/4
2/13/23, 4:41 AM Tips for Testing in Hardhat. How I test and debug my smart… | by Elim Poon | Coinmonks | Medium

This article will be an extension of the official Hardhat docs. If you have not already, I
would highly suggest that you take a look there first. With that said, let’s get right to it!

it

Should use console.log()


If you have done any sort of programming, you know how helpful it is to be able to
read your variables during code execution. I personally love to spam this method,
particularly console.log("Got here!"); when I am trying to locate errors. But using this
within your smart contract is a bit tricky. First you have to import hardhat console by
adding the following line to your Solidity code:

import "hardhat/console.sol";

Then create a Hardhat node to run your code within. You can do this with the following
terminal command:

npx hardhat node

You can also fork mainnet or a testnet if needed. Now when you run your tests/code (in
a different terminal window), you will be able to see the values that you console.logged
in the node terminal!

An alternative is to use a service called Tenderly that will allow you to view console.logs
from deployed contracts. This method is more tedious but does allow you to test in
production.

Should use .only to isolate tests


Sometimes you .only want to run certain tests in your suite of millions. You can do this
by adding .only after the describe or it commands like so:

describe.only("Blah blah blah",...);

https://medium.com/coinmonks/tips-for-testing-in-hardhat-c59e03837c92 2/4
2/13/23, 4:41 AM Tips for Testing in Hardhat. How I test and debug my smart… | by Elim Poon | Coinmonks | Medium

Hardhat will then only run that particular test, ignoring all other tests (and files). You
can .only multiple tests, but there are certain rules that I have not yet had the time to
figure out. Remember to remove the modifier when you are done.

Should organize tests


If you have lots of tests (security is important in crypto, or so they say), then the .only
method might not be enough. Luckily, Hardhat has an option that will allow you to
specify where the tests are located. You can group your tests into folders and change
the specified folder path in the config file, running only the tests within that folder.

Closing words
As you have probably already noticed, documentation in the crypto space ranges from
highly limited to non-existent. Thus, even as a non-writer, I feel compelled to take up
the mantle and shine some light into this vast archival void. Hopefully, readers will
find my articles helpful. I am new to this, so comments are highly welcomed. Happy
coding!

Join Coinmonks Telegram Channel and Youtube


Channel learn about crypto trading and investing
Also Read

BlockFi Review : Pros, Cons And Interest Rates 2022 | CoinCodeCap


Today, we came up with a comprehensive BlockFi review, a crypto
lending platform founded in 2017 and has its…
coincodecap.com

How to Buy Bitcoin in India? 7 Best Apps to Buy Bitcoin 2021 [Mobile
Version]
How to buy Bitcoin India using a Mobile App
medium.com

https://medium.com/coinmonks/tips-for-testing-in-hardhat-c59e03837c92 3/4
2/13/23, 4:41 AM Tips for Testing in Hardhat. How I test and debug my smart… | by Elim Poon | Coinmonks | Medium

Crypto Tax Software — Top 5 Best Bitcoin Tax Calculators [2021]


Whether you’re new to crypto or if you have been in the space for a
while, you’ll need to pay taxes.
medium.com

Hardhat Solidity Ethereum Smart Contracts Testing

Open in app Get unlimited access

Search Medium

Sign up for Coinmonks


By Coinmonks

A newsletter that brings you day's best crypto news, Technical analysis, Discount Offers, and MEMEs directly in your
inbox, by CoinCodeCap.com Take a look.

Emails will be sent to waledmunker@gmail.com. Not you?

Get this newsletter

https://medium.com/coinmonks/tips-for-testing-in-hardhat-c59e03837c92 4/4
2/13/23, 4:45 AM Learn to Deploy Smart Contracts more Professionally with Hardhat | by Ali Murtaza Memon | Coinmonks | Jan, 2023 | Medium

Published in Coinmonks

Ali Murtaza Memon Follow

Jan 21 · 11 min read · Listen

Save

Learn to Deploy Smart Contracts more


Professionally with Hardhat
“A Step-by-Step Guide for Advanced Smart Contract Deployment”

Hardhat is an open-source development environment for Ethereum smart contracts. It


allows developers to test, debug and deploy their contracts on a local Hardhat network,

https://medium.com/coinmonks/learn-to-deploy-smart-contracts-more-professionally-with-hardhat-1fec1dab8eac 1/18
2/13/23, 4:45 AM Learn to Deploy Smart Contracts more Professionally with Hardhat | by Ali Murtaza Memon | Coinmonks | Jan, 2023 | Medium

providing a safe and secure environment for experimentation and development.

One of the key features of Hardhat is its built-in Hardhat network, which allows
developers to deploy and test their contracts without the need for a live network. This
eliminates the risk of deploying untested code to the mainnet and incurring costly
errors.

But when it comes to deployment, this is what their statement is;

There are no official plugins that implement a deployment system for Hardhat yet. We are
working on it.

In the meantime, we recommend deploying your smart contracts using scripts, or using
the hardhat-deploy community plugin.

This means either we can use this type of Hardhat script to deploy our smart contracts.

EXAMPLE OF Lock SAMPLE CONTRACT;

const hre = require("hardhat");

async function main() {


const currentTimestampInSeconds = Math.round(Date.now() / 1000);
const ONE_YEAR_IN_SECS = 365 * 24 * 60 * 60;
const unlockTime = currentTimestampInSeconds + ONE_YEAR_IN_SECS;

const lockedAmount = hre.ethers.utils.parseEther("1");

const Lock = await hre.ethers.getContractFactory("Lock");


const lock = await Lock.deploy(unlockTime, { value: lockedAmount });

await lock.deployed();

console.log(
`Lock with 1 ETH and unlock timestamp ${unlockTime} deployed to ${lock.address
);
}

main().catch((error) => {
console.error(error);

https://medium.com/coinmonks/learn-to-deploy-smart-contracts-more-professionally-with-hardhat-1fec1dab8eac 2/18
2/13/23, 4:45 AM Learn to Deploy Smart Contracts more Professionally with Hardhat | by Ali Murtaza Memon | Coinmonks | Jan, 2023 | Medium

process.exitCode = 1;
});

or we can use the hardhat-deploy community plugin to deploy our contracts more
professionally.

When working with smart contract scripts, there are several scenarios where the script
process can become a headache for developers. Here are a few examples:

1. When deploying a large number of smart contracts, the process can become quite
cumbersome, especially when using the default Hardhat deploy script. The script
must be run individually for each contract, which can be time-consuming and
prone to errors ( One approach to mitigate this issue is to create a separate script
that can deploy all of the contracts together. While this can be an effective solution,
it may not be ideal in situations where only a subset of the contracts need to be
deployed. In such cases, it would be necessary to manually select which contracts
to include in the deployment script, which can be time-consuming and prone to
errors).

2. When testing smart contracts, it is often necessary to deploy the contracts on a test
network before running the tests. This can be a time-consuming and error-prone
process, especially when dealing with complex projects with a large number of
smart contracts. Hardhat provides a way to manage this process with fixtures, but
even with this feature, developers still need to write deploy fixtures functions at
the start of the test script. This can be a headache when dealing with complex
projects with many smart contracts.

To mitigate these issues, it is important to adopt a more professional approach in order


to overcome the challenges and headaches that can arise during the deployment
process.

The solution? “The hardhat-deploy community plugin, as suggested by Hardhat


documentation, provides a comprehensive solution for streamlining the deployment
process of smart contracts, eliminating the challenges and headaches that can arise
during the process.”
https://medium.com/coinmonks/learn-to-deploy-smart-contracts-more-professionally-with-hardhat-1fec1dab8eac 3/18
2/13/23, 4:45 AM Learn to Deploy Smart Contracts more Professionally with Hardhat | by Ali Murtaza Memon | Coinmonks | Jan, 2023 | Medium

Let’s explore the process of deploying smart contracts utilizing the Hardhat Deploy
community plugin, and learn how to effectively utilize its features to streamline the
deployment process.

Here is an example of a basic smart contract written in Solidity:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

contract SimpleStorage {
uint private storedData;

function set(uint x) public {


storedData = x;
}

function get() public view returns (uint) {


return storedData;
}
}

This contract, called SimpleStorage, has two functions: “set” and “get”. The “set”
function allows you to store a value (in this case, a uint, or unsigned integer) in the
contract’s storage, and the “get” function allows you to retrieve the stored value.

To deploy this contract using the hardhat-deploy plugin, you will first need to set up a
local development environment. Follow these steps:

1. Install Node.js and npm (Node Package Manager) on your computer.

2. Install Hardhat by running the command “npm install -g hardhat” in your


terminal.

3. Create a new directory for your project and navigate to it in your terminal.

4. Run the command “npx hardhat” to set up a new Hardhat project in your current
directory. This will show you these options;

https://medium.com/coinmonks/learn-to-deploy-smart-contracts-more-professionally-with-hardhat-1fec1dab8eac 4/18
2/13/23, 4:45 AM Learn to Deploy Smart Contracts more Professionally with Hardhat | by Ali Murtaza Memon | Coinmonks | Jan, 2023 | Medium

Hardhat Projects Options

5. Select the “Create a JavaScript project” or “Create a TypeScript project” option.

Hardhat Project Root Location

6. Upon executing the command, the plugin will prompt for the root location of the
project. Simply press the tab key to confirm the default location and press Enter.

https://medium.com/coinmonks/learn-to-deploy-smart-contracts-more-professionally-with-hardhat-1fec1dab8eac 5/18
2/13/23, 4:45 AM Learn to Deploy Smart Contracts more Professionally with Hardhat | by Ali Murtaza Memon | Coinmonks | Jan, 2023 | Medium

gitignore File Option rompt

7. The plugin will then prompt for the inclusion of a .gitignore file, you can choose to
add it by typing ‘y’ or to skip it by typing ’n’ depending on your preference.

Hardhat Dependencies Prompt

8. The plugin will then prompt to install the @nomicfoundation/hardhat-toolbox


plugin, you can choose to install it by typing ‘y’ or to skip it by typing ’n’ depending on
your requirement.

With the local development environment now set up, we can proceed with deploying
the contract utilizing the Hardhat Deploy plugin. Before doing so, it is recommended
to remove the default contract, script and test files provided by Hardhat. These files
can be found in the contracts/, scripts/, and test/ folders, they should be removed to
avoid confusion and potential errors.

https://medium.com/coinmonks/learn-to-deploy-smart-contracts-more-professionally-with-hardhat-1fec1dab8eac 6/18
2/13/23, 4:45 AM Learn to Deploy Smart Contracts more Professionally with Hardhat | by Ali Murtaza Memon | Coinmonks | Jan, 2023 | Medium

1. In order to utilize the Hardhat Deploy plugin, it must first be installed. To do this,
run the command in the terminal or command prompt.

npm install -D hardhat-deploy

2. The Hardhat Deploy plugin recommends installing hardhat-deploy-ethers to access


additional features related to deployments as ethers contract. However, it is important
to note that as hardhat-deploy-ethers is a fork of @nomiclabs/hardhat-ethers , other
plugins might have a hardcoded dependency on @nomiclabs/hardhat-ethers . To ensure
compatibility, it is recommended to install hardhat-deploy-ethers by following the
command

npm install — save-dev @nomiclabs/hardhat-ethers@npm:hardhat-deploy-ethers ethers

3. Add the following statement to your hardhat.config.js :

// JavaScript
require('hardhat-deploy');

// TypeScript
import "hardhat-deploy";

4. Now if you run the command npx hardhat --help it will reveal a new task available,
named 'deploy', which will be used to deploy the smart contracts.

https://medium.com/coinmonks/learn-to-deploy-smart-contracts-more-professionally-with-hardhat-1fec1dab8eac 7/18
2/13/23, 4:45 AM Learn to Deploy Smart Contracts more Professionally with Hardhat | by Ali Murtaza Memon | Coinmonks | Jan, 2023 | Medium

Deploy Task

5. To proceed with the deployment process, a new folder named ‘deploy’ should be
created, and a new file, named 01-deploy-simple-storage.ts or 01-deploy-simple-

storage.js , should be created within it. It is important to ensure that the


SimpleStorage contract is added to the ‘contracts’ folder and named SimpleStorage.sol

before proceeding. The structure will look like this (I am using Typescript);

https://medium.com/coinmonks/learn-to-deploy-smart-contracts-more-professionally-with-hardhat-1fec1dab8eac 8/18
2/13/23, 4:45 AM Learn to Deploy Smart Contracts more Professionally with Hardhat | by Ali Murtaza Memon | Coinmonks | Jan, 2023 | Medium

Project Structure

Why are we adding the 01 prefixes to the file?

The inclusion of numerical prefixes, such as ‘01’, before the file names serves the
purpose of indicating the sequence in which the deployment scripts should be
executed when utilizing the ‘npx hardhat deploy’ task command. This ensures that all
scripts present within the ‘deploy’ folder are executed in a specific order. Although this
is a simple example with one smart contract, it is important to note that when working
with multiple smart contracts, this method allows for a clear and organized structure,
ensuring that the contracts are deployed in a specific sequence.

https://medium.com/coinmonks/learn-to-deploy-smart-contracts-more-professionally-with-hardhat-1fec1dab8eac 9/18
2/13/23, 4:45 AM Learn to Deploy Smart Contracts more Professionally with Hardhat | by Ali Murtaza Memon | Coinmonks | Jan, 2023 | Medium

6. The following code should be added to the previously created deployment file,
depending on the language being used, either JavaScript or TypeScript.

// TypeScript
import { DeployFunction, DeployResult } from "hardhat-deploy/dist/types";
import { HardhatRuntimeEnvironment } from "hardhat/types";
import { network } from "hardhat";

/**
* * Important Notes
*
* * In order to run `npx hardhat deploy --typecheck` command we need to add `impo
*
*/

const deploySimpleStorage: DeployFunction = async (


hre: HardhatRuntimeEnvironment
) => {
const { deploy } = hre.deployments;
const { deployer } = await hre.getNamedAccounts();
const chainId = network.config.chainId!;

const simpleStorage: DeployResult = await deploy("SimpleStorage", {


from: deployer,
log: true,
args: [],
waitConfirmations: chainId == 31337 ? 1 : 6,
});
};

export default deploySimpleStorage;


deploySimpleStorage.tags = ["all", "simpleStorage"];

// JavaScript
const { network } = require("hardhat");

module.exports = async (hre) => {


const { deploy } = hre.deployments;
const { deployer } = await hre.getNamedAccounts();
const chainId = network.config.chainId;

const simpleStorage = await deploy("SimpleStorage", {


from: deployer,
https://medium.com/coinmonks/learn-to-deploy-smart-contracts-more-professionally-with-hardhat-1fec1dab8eac 10/18
2/13/23, 4:45 AM Learn to Deploy Smart Contracts more Professionally with Hardhat | by Ali Murtaza Memon | Coinmonks | Jan, 2023 | Medium

log: true,
args: [],
waitConfirmations: chainId == 31337 ? 1 : 6,
});
};

module.exports.tags = ["all", "simpleStorage"];

Let me explain what’s going on; (I am going to explain JavaScript but the Concepts are
the same for both).

const { network } = require("hardhat");

This line of code imports the network from Hardhat, which will be used to
automatically detect the network being used, whether it is localhost, testnet, or
mainnet, from the command used.

module.exports = async (hre) => {

The code exports a deploy function, which will be passed an object, known as the
Hardhat Runtime Environment, by the Hardhat Deploy plugin.

const { deploy } = hre.deployments;


const { deployer } = await hre.getNamedAccounts();
const chainId = network.config.chainId;

The hre object is used to extract the deploy function from the deployments, which will
assist in deploying the smart contract with specified options. The deployer is obtained
through the hre’s getNamedAccounts function, and the chainId is obtained from the
network.

https://medium.com/coinmonks/learn-to-deploy-smart-contracts-more-professionally-with-hardhat-1fec1dab8eac 11/18
2/13/23, 4:45 AM Learn to Deploy Smart Contracts more Professionally with Hardhat | by Ali Murtaza Memon | Coinmonks | Jan, 2023 | Medium

The deployer is a label assigned to the first account on the network. To utilize this
feature, the hardhat.config.js file needs to be configured accordingly, as outlined
below (Make sure it contains both JavaScirpt and TypeScript versions, select only one).

// TypeScript
const config: HardhatUserConfig = {
solidity: "0.8.17",
defaultNetwork: "hardhat",
networks: {
hardhat: {
chainId: 31337,
},
},
namedAccounts: {
deployer: {
default: 0,
},
},
};

// JavaScript
module.exports = {
defaultNetwork: "hardhat",
networks: {
hardhat: {
chainId: 31337,
},
},
namedAccounts: {
deployer: {
default: 0
},
},
}

With the deployer obtained, the smart contract can now be deployed using the deploy
function provided by hre.deployments.

const simpleStorage = await deploy("SimpleStorage", {


from: deployer,
log: true,

https://medium.com/coinmonks/learn-to-deploy-smart-contracts-more-professionally-with-hardhat-1fec1dab8eac 12/18
2/13/23, 4:45 AM Learn to Deploy Smart Contracts more Professionally with Hardhat | by Ali Murtaza Memon | Coinmonks | Jan, 2023 | Medium

args: [],
waitConfirmations: chainId == 31337 ? 1 : 6,
});

In this step, the smart contract’s name is provided as the first parameter of the deploy
function. The second parameter of the deploy function is an object that contains
additional information for deployment.

from : field within the object specifies the address of the deployer or owner of the
contract.

log : field within the object, if set to true , will log information about the deployed
smart contract’s address in the terminal.

args : field within the object, is an array that contains the parameters required for
the smart contract’s constructor. Since our smart contract in this example does not
have a constructor, an empty array is passed.

waitConfirmations : field within the object specifies the time delay for waiting for
the confirmation of the transaction of the deployed smart contract. Here, the
condition to wait for 1 block confirmation for the Hardhat chain, and 6 block
confirmations for testnets or mainnets is added. This is a recommended practice.

With all necessary setup and configuration completed, the smart contract can now be
deployed by executing the following command in the terminal.

npx hardhat deploy

// deploy on goerli - make sure to setup goerli network in hardhat.config.js file


npx hardhat deploy --network goerli

// deploy on any network - just add the network in hardhat.config.js file.


npx hardhat deploy --network <network-name>

https://medium.com/coinmonks/learn-to-deploy-smart-contracts-more-professionally-with-hardhat-1fec1dab8eac 13/18
2/13/23, 4:45 AM Learn to Deploy Smart Contracts more Professionally with Hardhat | by Ali Murtaza Memon | Coinmonks | Jan, 2023 | Medium

The same process should be followed for deploying any additional smart contracts.
Once the initial setup is completed, all contracts can be deployed simultaneously using
this single command.

With the Hardhat Deploy plugin, the need to run individual deployment scripts for
each smart contract on the Hardhat node is eliminated. The plugin automatically
deploys all smart contracts when the Hardhat node is opened, as demonstrated in the
example provided.

https://medium.com/coinmonks/learn-to-deploy-smart-contracts-more-professionally-with-hardhat-1fec1dab8eac 14/18
2/13/23, 4:45 AM Learn to Deploy Smart Contracts more Professionally with Hardhat | by Ali Murtaza Memon | Coinmonks | Jan, 2023 | Medium

With this setup in place, there is no need to redeploy your smart contract each time it
is used in other scripts. By including the following line of code, the instance of the
previously deployed contract can be accessed and utilized.

https://medium.com/coinmonks/learn-to-deploy-smart-contracts-more-professionally-with-hardhat-1fec1dab8eac 15/18
2/13/23, 4:45 AM Learn to Deploy Smart Contracts more Professionally with Hardhat | by Ali Murtaza Memon | Coinmonks | Jan, 2023 | Medium

const { deployer } = await getNamedAccounts();


const simpleStorage = await ethers.getContract("SimpleStorage", deployer);

// now you can call your smart contract public function and variable with just thi

What if we only want to deploy selective deploy scripts from the deploy folder?

Do you remember this line we added at the end of our 01-simple-storage.js file?

module.exports.tags = ["all", "simpleStorage"];

In scenarios where only a specific set of smart contracts from the ‘deploy’ folder are
intended to be deployed, the Hardhat Deploy plugin offers the capability to selectively
deploy those contracts by providing their tags names as arguments to the command
npx hardhat deploy --tags <tag-name> , this allows for a more efficient deployment
process by enabling the selective deployment of only the necessary smart contracts.

Use Deployed Smart Contracts in Tests


An additional benefit of using the Hardhat Deploy plugin is the ability to ensure the
deployment scripts are executed in tests as well.

By calling await deployments.fixture(['MyContract']) in your test, the same


deployment is used for all tests, which eliminates the need to replicate the deployment
procedure.

To deploy all smart contracts before running tests, an ‘all’ tag feature can be added to
all deployment scripts, and this await deployments.fixture(['all']) can be added to
https://medium.com/coinmonks/learn-to-deploy-smart-contracts-more-professionally-with-hardhat-1fec1dab8eac 16/18
2/13/23, 4:45 AM Learn to Deploy Smart Contracts more Professionally with Hardhat | by Ali Murtaza Memon | Coinmonks | Jan, 2023 | Medium

the test file. This enables the deployment of all contracts before the tests are executed,
ensuring that the test environment accurately reflects the deployed state of the smart
contracts.

The 'tag' feature, as well as dependencies, also simplify the process of writing complex
deployment procedures. The plugin also allows for the organization of the deploy
scripts into sub-folders and execution in a logical order.

Conclusion
Overall, Hardhat Deploy is a powerful and versatile tool that can greatly simplify and
streamline the deployment process for smart contracts. It is widely used by developers
and organizations in the Ethereum community and can be a great addition to your
development workflow.

This comprehensive guide aims to provide assistance to developers of all skill levels
and is intended to be beneficial for a wide range of developers. Despite its length, the
information provided is intended to be easily understandable and actionable for all
readers.

If you found this content helpful, please consider giving it a clap and leaving any
feedback for future improvements. Your suggestions and comments are greatly
appreciated and will help make these articles even more valuable for you and other
readers.

Be sure to follow me to receive updates on my future articles and stay informed of new
content.

Thank you

Ali Murtaza Memon

New to trading? Try crypto trading bots or copy


trading on best crypto exchanges

https://medium.com/coinmonks/learn-to-deploy-smart-contracts-more-professionally-with-hardhat-1fec1dab8eac 17/18
2/13/23, 4:45 AM Learn to Deploy Smart Contracts more Professionally with Hardhat | by Ali Murtaza Memon | Coinmonks | Jan, 2023 | Medium

Blockchain Smart Contracts Solidity Deploy Smart Contract Hardhat

Sign up for Coinmonks


By Coinmonks

A newsletter that brings you day's best crypto news, Technical analysis, Discount Offers, and MEMEs directly in your
inbox, by CoinCodeCap.com Take a look.

Emails will be sent to waledmunker@gmail.com. Not you?


Open in app Get unlimited access

Get this newsletter


Search Medium

https://medium.com/coinmonks/learn-to-deploy-smart-contracts-more-professionally-with-hardhat-1fec1dab8eac 18/18
2/13/23, 4:57 AM Hardhat for Solidity development. The JS framework for Ethereum… | by Keno Leon | Coinmonks | Medium

Published in Coinmonks

You have 2 free member-only stories left this month. Sign up for Medium and get an extra one

Keno Leon Follow

Mar 22, 2022 · 6 min read · · Listen

Save

Photo by Andrea Piacquadio from Pexels

Hardhat for Solidity development


The JS framework for Ethereum development ?
https://medium.com/coinmonks/hardhat-for-solidity-development-b11e9f174f3a 1/9
2/13/23, 4:57 AM Hardhat for Solidity development. The JS framework for Ethereum… | by Keno Leon | Coinmonks | Medium

As part me getting back into solidity I started looking into upgrading my setup with
frameworks, brownie for python was my first one ( great if you are into python but read
on ):

A quick look at Brownie


Ethereum Smart Contract framework in python !
coinsbench.com

Today I’ll check what from the outset looks like the choice Javascript framework for
Solidity… Hardhat:

Ethereum development environment for professionals by Nomic


Foundation
Hardhat is an Ethereum development environment. Compile your
contracts and run them on a development network. Get…
hardhat.org

Even before starting Hardhat has a clear advantage since there is a


lot of tooling written in javascript and well if you are going down
the web3 rabbit hole you will most likely need things like
Node/Webpack/React and other JS or Typescript libraries and tools for
your Dapp, hence why Javascript is recommended as a starting language
for blockchain development and hardhat seems to be a shoo-in.

Ease of Use/Setup/First Impression


Hardhat is a node package, so if you have some experience or are comfortable working
with node it should be a familiar experience, there is some defaults and boilerplates,
but overall you are left to organize your files (within reason) and plugins ( more on this
later ) as you see fit.

https://medium.com/coinmonks/hardhat-for-solidity-development-b11e9f174f3a 2/9
2/13/23, 4:57 AM Hardhat for Solidity development. The JS framework for Ethereum… | by Keno Leon | Coinmonks | Medium

I don't say this often but Hardhat's documentation is top notch,


especially when it comes to onboarding and if you've made up your mind
or will test Hardhat regardless you can stop reading and head directly
to the tutorial which does a great job at introducing you to the
framework :
Hardhat Tutorial for Beginners
The Docs are equally high quality with plenty of easy to follow
examples:
Hadhat documentation

Once you are done installing hardhat ( took about 20 seconds with no errors for me, Yay !
), you do need to spend some time becoming familiar with the workflow, in a gist you
run commands from your terminal (test, compile for instance ) and use config files and
plugins to adapt your development environment to your project, this might seem like
too much work or somehow disorganized, but the unopinionated/flexible approach I
think works great, especially with the changing/modular nature of Ethereum and smart
contract development, just be prepared to think a bit about what your project needs
and set some time aside to config your hardhat build.

If you'd rather test the waters Hardhat provides an excellent list of


options for scaffolding and boilerplates when you first run it :
? What do you want to do? …
❯ Create a sample project
Create an advanced sample project
Create an advanced sample project that uses TypeScript
Create an empty hardhat.config.js
Quit

If for instance you choose the sample project you get boilerplates and
starter files :
├── README.md
├── artifacts
├── cache
├── contracts >> contains Greeter.sol
├── hardhat.config.js
├── node_modules
├── package-lock.json
├── package.json

https://medium.com/coinmonks/hardhat-for-solidity-development-b11e9f174f3a 3/9
2/13/23, 4:57 AM Hardhat for Solidity development. The JS framework for Ethereum… | by Keno Leon | Coinmonks | Medium

├── scripts >> contains sample-script.js


└── test >> contains sample-test.js
Much like brownie you get a well organized build directory with sample
files, but unlike brownie you have some liberty on what/how this
structure looks like.

Features
Beyond the basics of writing, compiling and deploying contracts which are
straightforward (and well covered in the tutorial), Hardhat has a couple of features I
think are super useful which I’ll try summarizing :

Console.log for smart contracts


Import a login contract into your contract:

import "hardhat/console.sol";

Then sprinkle login calls wherever you need them:

console.log("Will try X function");

And upon testing or interacting with the contract you will get these logs which will
help you trouble shoot your contracts !

Hardhat Network
Blockchain/Ethereum development has always seemed clunky to me because when
you are writing contracts the feedback loop which is critical for learning, testing and
iterating can be a bottleneck; inspecting contracts against remix and soft launching
them against a test-net work but they might take you out of the flow of writing and if

https://medium.com/coinmonks/hardhat-for-solidity-development-b11e9f174f3a 4/9
2/13/23, 4:57 AM Hardhat for Solidity development. The JS framework for Ethereum… | by Keno Leon | Coinmonks | Medium

you have a complex dApp or contract interactions it quickly becomes a slog. Hardhat’s
solution is not new ( a virtual local node ), but I found it easier to use than the
alternatives ( mainly truffle/ganache or ethereum node APIs) since you hardly need to
leave your IDE ( VsCode in my case ).

Hardhat spins up an in memory Vm that goes away when whatever task you
are doing ends (like testing), but if you need permanence so you can
test your dApp with calls (via JSON-RPC) and whatnot you can with:
$ npx hardhat node
You can also fork from mainnet ( requires an API with archive data
like Alchemy ) and more, check the docs :
Hardhat Network

Plugins, Tasks & Scripts


As mentioned Hardhat has an open design that allows you to build your own
environment to taste, the first part are Plugins which are libraries and other tools you
install and include ,( node packages really ) so for instance there are official plugins like
ethers and web3 that inject them and more specialized community ones like abi

exporters , coverage and autodocs to name a few, you can check them all here to get an
idea:

Ethereum development environment for professionals by Nomic


Foundation
Plugins are the backbone of Hardhat, and they're built using the same
config DSL that you use in your Hardhat…
hardhat.org

Tasks on the other hand are meant for automation and can be called from the
command line ( things like compile, clean run scripts and test ), but you can also
make your own tasks :

https://medium.com/coinmonks/hardhat-for-solidity-development-b11e9f174f3a 5/9
2/13/23, 4:57 AM Hardhat for Solidity development. The JS framework for Ethereum… | by Keno Leon | Coinmonks | Medium

Ethereum development environment for professionals by Nomic


Foundation
This guide will explore the creation of tasks in Hardhat, which are the
core component used for automation. A task is a…
hardhat.org

And finally you have Scripts which do more specific things related to your project and
use hardhat as a library you require:

Ethereum development environment for professionals by Nomic


Foundation
In this guide we will go through the steps of creating a script with
Hardhat. For a general overview of using Hardhat…
hardhat.org

Along with the network features already mentioned you can build complex
development pipelines with these elements or just stick to the basics with some
customization, a truly flexible architecture.

Testing
In comparison testing is fairly standard which is a good thing and the recommended
path is ethers.js & Waffle (with Mocha and Chai which are also testing standards ), but
you can also use Web3 & Truffle

Not much else to say about testing (it works, it still doesn’t automagically write test for you
😕), I recommend you read the tutorial section which goes in depth on the actual
usage:

Ethereum development environment for professionals by Nomic


Foundation
Writing automated tests when building smart contracts is of crucial
importance, as your user's money is what's at…
https://medium.com/coinmonks/hardhat-for-solidity-development-b11e9f174f3a 6/9
2/13/23, 4:57 AM Hardhat for Solidity development. The JS framework for Ethereum… | by Keno Leon | Coinmonks | Medium

hardhat.org

Vscode extension
To end the feature tour I should also mention the Solidity +Hardhat plugin for vsCode:

Solidity + Hardhat - Visual Studio Marketplace


This extension adds language support for Solidity to Visual Studio
Code, and provides editor integration for Hardhat…
marketplace.visualstudio.com

There’s another popular VsCode extension for solidity (Juan Blancos


Solidity) its a bit more mature and both offer similar features(code
completion, formatting) but you can't have both and the workflow is
different, try them both I guess, in my case I felt more at home with
Hardhat's

Conclusions
Tooling for Ethereum is fast evolving along with contract, dApp and web3 complexity,
it’s hard to keep up and if you are just starting out and feel overwhelmed I believe it is
normal and deserved. I found Hardhat to be a lifesaver in this regard, yes you still need
to spend some time learning how to use it and it is a framework after all, so it won’t do
everything for you, but I think it helps keep your Ethereum development organized
and the learning curve and documentation were excellent.

As an aside I've been writing python code pretty much every day for
the last 3 yrs so why not go with brownie/vyper ? For me at least it
makes more sense to switch to JS/TS/Solidity for Ethereum development
and use Hardhat to tie everything together rather than do a mix of
Python/JS, the DX just felt better but it is admittedly a personal
choice, for newcomers though I still think JS is the right first

https://medium.com/coinmonks/hardhat-for-solidity-development-b11e9f174f3a 7/9
2/13/23, 4:57 AM Hardhat for Solidity development. The JS framework for Ethereum… | by Keno Leon | Coinmonks | Medium

language followed by TS and Solidity and so I would recommend Hardhat


over brownie for now.

Thanks for reading !

Join Coinmonks Telegram Channel and Youtube


Channel learn about crypto trading and investing
Also, Read
10 Best Books on Crypto | 5 Best Crypto Bots in the UK

Koinly Review | Binaryx Review | Hodlnaut vs CakeDefi

MoonXBT vs Bybit vs Binance | Hardware Wallets

Huobi Trading Bot | How to buy ADA | Geco.One Review

Binance vs Bitstamp | Bitpanda vs Coinbase vs Coinsbit

Ethereum Blockchain Web 3 Software Development Cryptocurrency

18

Sign up for Coinmonks


By Coinmonks

A newsletter that brings you day's best crypto news, Technical analysis, Discount Offers, and MEMEs directly in your
inbox, by CoinCodeCap.com Take a look.

Your email

Get this newsletter

https://medium.com/coinmonks/hardhat-for-solidity-development-b11e9f174f3a 8/9
2/13/23, 4:57 AM Hardhat for Solidity development. The JS framework for Ethereum… | by Keno Leon | Coinmonks | Medium
By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy
practices.

Open in app Sign up Sign In

Search Medium

About Help Terms Privacy

Get the Medium app

https://medium.com/coinmonks/hardhat-for-solidity-development-b11e9f174f3a 9/9

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy