Hardhat Beginners To Advanced Guides
Hardhat Beginners To Advanced Guides
Hardhat Beginners To Advanced Guides
Published in Coinmonks
You have 2 free member-only stories left this month. Sign up for Medium and get an extra one
Save
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 ):
Today I’ll check what from the outset looks like the choice Javascript framework for
Solidity… Hardhat:
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 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
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 :
import "hardhat/console.sol";
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
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
exporters , coverage and autodocs to name a few, you can check them all here to get an
idea:
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 :
And finally you have Scripts which do more specific things related to your project and
use hardhat as a library you require:
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:
hardhat.org
Vscode extension
To end the feature tour I should also mention the Solidity +Hardhat plugin for vsCode:
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
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
Published in Coinmonks
Save
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:
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
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.
I created a simple interface to test the case with the non-existed selector call on other
contract and check Hardhat console output:
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
See Solidity stack traces section — we already tested this case there.
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
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)
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
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
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
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
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
Save
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
Other than just deploying and running tests, Hardhat also provides some more
features that make it more powerful and unique.
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
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:
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.
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 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 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.
With Truffle, you can write deployment scripts that allow you to account for the fact
that your Dapps will change over time.
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.
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.
So you can simply import the console plugin and can use it inside your functions.
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.
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.
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.
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.
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.
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
48 1
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
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
Save
To install it, create an npm project by going to an empty folder, running npm init in the
terminal.
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
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.
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.
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
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.
Next, to deploy your contracts we’ll use Hardhat script. The sample code is there inside
scripts/ in the sample-script.js file
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.
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
Save
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.
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)
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
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
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.
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.
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
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
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
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.
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
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.
As you can see, the contract is deployed to the Ropsten network and you can see it on
the explorer.
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
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.
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.
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
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.
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
Save
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.
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.
Introducing products from external sources like npm packages, with truffle help.
Set-Up
Make ready the project and install Hardhat as a dependency.
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.
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
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
});
/ 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:
Contract
We will import a Solidity contract from Open Zeppelin.
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
Script Deployment
We will control the hardhat-deploy plugin to deploy the contracts.
The first deployment script, located in the deploy folder, would be the following:
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:
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
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
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
Save
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?
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.
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!
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
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
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
With npx hardhat the hardhat wizard will kickstart helping you configure your project.
Choose the default Hardhat project root because in this tutorial we are only
configuring hardhat.
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
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 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
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
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
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
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
solhint+solhint prettier
{
"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
hardhat-solhint
If you want to know more follow the Hardhat solhint plugin documentation.
and update the hardhat config adding this line to the import
import “@nomiclabs/hardhat-solhint”;
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
If you want to dig deeper into these projects and know all the possible configuration
options you can follow these links:
Typechain Hardhat
Let’s do it
import '@typechain/hardhat'
import '@nomiclabs/hardhat-ethers'
import '@nomiclabs/hardhat-waffle'
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!
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
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:
Now if you want to simply run the Hardhat node you can write in your console yarn
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.
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
Mapping
Structs
Functions
Events
Payable functions
Let’s now define some state variables to track both the current Purpose and user’s
investment
Last but not least define an Event that will be emitted when a new World Purpose has
been set
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 msg.value (amount of ether sent with the transaction) is empty (0 ethers)
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 }
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 }
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
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
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!',
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
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:
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
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!
This is just the start, I’m planning to add more features in time like for example:
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!
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
Search Medium
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 …
You have 2 free member-only stories left this month. Sign up for Medium and get an extra one
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 …
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.
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 …
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 …
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
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:
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 …
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 …
Search Medium
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 …
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 …
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
You have 2 free member-only stories left this month. Sign up for Medium and get an extra one
Save
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
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.
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
an ounce of silver
Not to be confused with coins which are just methods of payment while tokens may
perform many other functions.
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.
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.
Setting Up
1. Install Chrome
If your not already using Chrome as your browser, you’ll need to download it for this
project.
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.
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.
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.
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
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.
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 {
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
Line 30:
Line 31:
Line 32:
Line 33:
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:
This function lets anybody query to see what is the allowance that one address ( owner )
lets another address ( spender ) spend.
Line 36–38:
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:
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:
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.
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:
Line 66–68:
Line 70–75:
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:
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:
This function will check if the total supply has the amount of token which needs to be
allocated to a user.
Line 91–93:
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:
This function will execute the transactions of buying and spending tokens.
Line 102–105:
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.
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
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
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!
Subscribe to receive top 10 most read stories of Geek Culture — delivered straight into your inbox, once a week. Take a
look.
Your email
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/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
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
Save
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).
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
Is it scalable?
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.
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.
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.
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?
Token Allocation
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
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 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)?
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.
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
@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
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
Save
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.
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
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.
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
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
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:
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)
})
})
})
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.
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
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.
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
Save
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:
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.
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
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
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.
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
Save
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.
In the terminal and within your project, type npm install --save mocha ganache-cli
Next, create a test folder, a sibling of the contracts folder. Inside of the test folder,
create a file called hello.test.js .
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.
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!
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.
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
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
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
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
Save
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
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"
}
}
Note that for the sake of compatibility, in some dependencies, we need to define the
package version.
"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 :
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 ;
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.
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 () => {
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 :
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.
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
Time to Deploy
Now we will write our deploy.js file
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
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.
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
Save
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
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.
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.
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.
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
Search Medium
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
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.
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
Save
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
import "hardhat/console.sol";
Then create a Hardhat node to run your code within. You can do this with the following
terminal command:
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.
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.
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!
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
Search 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.
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
Save
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
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.
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.
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.
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.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
contract SimpleStorage {
uint private 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:
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
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
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.
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.
// 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-
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
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
*
*/
// JavaScript
const { network } = require("hardhat");
log: true,
args: [],
waitConfirmations: chainId == 31337 ? 1 : 6,
});
};
Let me explain what’s going on; (I am going to explain JavaScript but the Concepts are
the same for both).
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.
The code exports a deploy function, which will be passed an object, known as the
Hardhat Runtime Environment, by the Hardhat Deploy plugin.
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.
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.
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
// 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?
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.
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
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
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.
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
Save
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 ):
Today I’ll check what from the outset looks like the choice Javascript framework for
Solidity… Hardhat:
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
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 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
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 :
import "hardhat/console.sol";
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
exporters , coverage and autodocs to name a few, you can check them all here to get an
idea:
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
And finally you have Scripts which do more specific things related to your project and
use hardhat as a library you require:
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:
hardhat.org
Vscode extension
To end the feature tour I should also mention the Solidity +Hardhat plugin for vsCode:
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
18
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
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.
Search Medium
https://medium.com/coinmonks/hardhat-for-solidity-development-b11e9f174f3a 9/9