Hardhat Developer Workflow
Introduction
In this tutorial, we'll walk through the Hardhat development environment in the context of launching a pooled staking DAO contract. We'll walk through the typical developer workflow in detail from start to finish.
We'll assemble the components of the staking DAO and compile the necessary contracts. Then, we'll build a test suite with a variety of test cases relevant to our staking DAO, and run it against a local development node. Finally, we'll deploy the staking DAO to both Phronbase Alpha and Phron and verify the contracts via the Hardhat Etherscan plugin. If this is your first time exploring Hardhat, you may wish to start with the introduction to Hardhat guide.
The information presented herein is for informational purposes only and has been provided by third parties. Phron does not endorse any project listed and described on the Phron docs website.
Checking Prerequisites
To get started, you will need the following:
A Phron account funded with DEV. You can get DEV tokens for testing on Phron once every 24 hours from the Phron Faucet
A Phronscan API Key
For the Testing section, you'll need to have a local Phron node up and running
To test out the examples in this guide on Phron, you will need to have your own endpoint and API key, which you can get from one of the supported Endpoint Providers
Creating a Hardhat Project
You will need to create a Hardhat project if you don't already have one. You can create one by completing the following steps:
Create a directory for your project
mkdir stakingDAO && cd stakingDAOInitialize the project which will create a
package.jsonfilenpm init -yInstall Hardhat
npm install hardhatCreate a project
npx hardhat init
Note
npxis used to run executables installed locally in your project. Although Hardhat can be installed globally, it is recommended to install it locally in each project so that you can control the version on a project by project basis.
A menu will appear allowing you to create a new project or use a sample project. For this example, you can choose Create an empty hardhat.config.js
This will create a Hardhat config file (hardhat.config.js) in your project directory.
Add Smart Contracts
The smart contract featured in this tutorial is more complex than the one in the Introduction to Hardhat but the nature of the contract means it's perfect to demonstrate some of the advanced capabilities of Hardhat. DelegationDAO.sol is a pooled staking DAO that uses StakingInterface.sol to autonomously delegate to a collator when it reaches a determined threshold. Pooled staking contracts such as DelegationDAO.sol allow delegators with less than the protocol minimum bond to join together to delegate their pooled funds and earn a share of staking rewards.
Note
DelegationDAO.solis unreviewed and unaudited. It is designed only for demonstration purposes and not intended for production use. It may contain bugs or logic errors that could result in loss of funds.
To get started, take the following steps:
Create a
contractsdirectory to hold your project's smart contractsCreate a new file called
DelegationDAO.solCopy and paste the contents of DelegationDAO.sol into
DelegationDAO.solCreate a new file called
StakingInterface.solin thecontractsdirectoryCopy and paste the contents of StakingInterface.sol into
StakingInterface.solDelegationDAO.solrelies on a couple of standard OpenZeppelin contracts. Add the library with the following command:
Hardhat Configuration File
When setting up the hardhat.config.js file, we'll need to import a few plugins that we'll use throughout this guide. So to get started, we'll need the Hardhat Toolbox plugin, which conveniently bundles together Hardhat plugins that can be used to deploy and interact with contracts using Ethers, test contracts with Mocha and Chai, verify contracts with Etherscan, and more. You can run the following command to install the plugin:
If you're curious about additional Hardhat plugins, here is a complete list of official Hardhat plugins.
For the examples in this guide, you'll need to add your private keys for your two accounts on Phron. Since some of the testing will be done on a development node, you'll also need to add the private keys of two of the prefunded development node accounts, which for this example, we can use Alice and Bob. In addition, you'll add your Phronscan API key, which can be used for Phron.
Add your Phronscan API key, which is required for the verification steps we'll be taking later in this tutorial
NoteAny real funds sent to the Alice and Bob development accounts will be lost immediately. Take precautions to never send MainNet funds to exposed development accounts.
You're now ready to move on to compilation and testing.
Compiling the Contract
To compile the contract you can simply run:
After compilation, an artifacts directory is created: it holds the bytecode and metadata of the contract, which are .json files. Adding this directory to your .gitignore is a good idea.
Testing
A robust smart contract development workflow is complete with a testing suite. Hardhat has a number of tools that make it easy to write and run tests. In this section, you'll learn the basics of testing your smart contracts and some more advanced techniques.
Hardhat tests are typically written with Mocha and Chai. Mocha is a JavaScript testing framework and Chai is a BDD/TDD JavaScript assertion library. BDD/TDD stands for behavior and test-driven development respectively. Effective BDD/TDD necessitates writing your tests before writing your smart contract code. The structure of this tutorial doesn't strictly follow these guidelines, but you may wish to adopt these principles in your development workflow. Hardhat recommends using Hardhat Toolbox, a plugin that bundles everything you need to get started with Hardhat, including Mocha and Chai.
Because we will initially be running our tests on a local Phron node, we need to specify Alice's address as the address of our target collator (Alice's account is the only collator for a local development node):
If instead you prefer to run your tests against Phron, you can choose the below collator, or any other collator on Phron you would like the DAO to delegate to:
Configuring the Test File
To set up your test file, take the following steps:
Create a
testsdirectoryCreate a new file called
Dao.jsThen copy and paste the contents below to set up the initial structure of your test file. Be sure to read the comments, as they can clarify the purpose of each line
Deploying a Staking DAO for Testing
Before we can run any test cases we'll need to launch a staking DAO with an initial configuration. Our setup here is relatively simple - we'll be deploying a staking DAO with a single administrator (the deployer) and then adding a new member to the DAO. This simple setup is perfect for demonstration purposes, but it's easy to imagine more complex configurations you'd like to test, such as a scenario with 100 DAO members or one with multiple admins of the DAO.
Mocha's describe function enables you to organize your tests. Multiple describe functions can be nested together. It's entirely optional but can be useful, especially in complex projects with many test cases. You can read more about constructing tests and getting started with Mocha on the Mocha docs site.
We'll define a function called deployDao containing the setup steps for our staking DAO. To configure your test file, add the following snippet:
Writing your First Test Cases
First, you'll create a subsection called Deployment to keep the test file organized. This will be nested within the Dao contract describe function. Next, you'll define your first test case by using the it Mocha function. This first test checks to see that the staking DAO correctly stores the address of the target collator.
Add the snippet below to the end of your Dao contract function.
Now, add another test case. When a staking DAO is launched, it shouldn't have any funds. This test verifies that is indeed the case. Go ahead and add the following test case to your Dao.js file:
Function Reverts
Now, you'll implement a more complex test case with a slightly different architecture. In prior examples, you've verified that a function returns an expected value. In this one, you'll be verifying that a function reverts. You'll also change the caller's address to test an admin-only function.
In the staking DAO contract, only admins are authorized to add new members to the DAO. One could write a test that checks to see if the admin is authorized to add new members but a more important test is to ensure that non-admins can't add new members. To run this test case under a different account, you will ask for another address when you call ethers.getSigners() and specify the caller in the assertion with connect(member1). Finally, after the function call you'll append .to.be.reverted to indicate that the test case is successful if the function reverts. And if it doesn't revert, it's a failed test!
Signing Transactions from Other Accounts
For this example, you'll verify whether the newly added DAO member can call the check_free_balance() function of staking DAO, which has an access modifier such that only members can access it.
And that's it! You're now ready to run your tests!
Running your Tests
If you've followed all of the prior sections, your Dao.js test file should be all set to go.
Since our test cases encompass mostly configuration and setup of the staking DAO and don't involve actual delegation actions, we'll be running our tests on a Phron development node (local node). Remember that Alice (0xf24FF3a9CF04c71Dbc94D0b566f7A27B94566cac) is the only collator on a local development node. You can use the flag --network phronbase to run the tests using Phronbase. In that case, ensure your deployer address is sufficiently funded with DEV tokens.
Challenge
Try to create an additional test case that verifies the staking DAO successfully delegates to a collator once minDelegationStk is met. You must test this on Phron rather than a local development node.
First, make sure that your local Phron node is running by following the instructions for launching a local development node. Take precautions because you could inadvertently send real funds to the Alice and Bob development accounts, resulting in a loss of those funds.
You can run your tests with the following command:
If everything was set up correctly, you should see output like the following:
Deploying to Phron
In the following steps, we'll deploy the DelegationDAO to the Phron TestNet. Before deploying to Phron, double-check that you're not using the Alice and Bob accounts, which should only be used on a local development node.
As a side note, DelegationDAO relies on StakingInterface.sol, which is a Substrate-based offering unique to Phron networks. The Hardhat Network and forked networks are simulated EVM environments which do not include the Substrate-based precompiles like StakingInterface.sol. Therefore, DelegationDAO will not work properly if deployed to the local default Hardhat Network or a forked network.
To deploy DelegationDAO, you'll use Hardhat Ignition, a declarative framework for deploying smart contracts. Hardhat Ignition is designed to make it easy to manage recurring tasks surrounding smart contract deployment and testing. For more information about Hardhat Ignition and its architecture, be sure to check out the Hardhat Ignition docs.
To set up the proper file structure for your Ignition module, create a folder named ignition and a subdirectory called modules. Then, add a new file to it called DelegationDao.js. You can take all three of these steps with the following command:
Next, you can write your Hardhat Ignition module. To get started, take the following steps:
Import the
buildModulefunction from the Hardhat Ignition moduleExport a module using
buildModuleSpecify the target collator candidate for the DAO to delegate to
Use the
getAccountmethod to select the deployer accountDeploy
DelegationDAO.solReturn an object from the module. This makes the
DelegationDaocontract accessible for interaction in Hardhat tests and scripts
When all is said and done your deployment script should look similar to the following:
To run the script and deploy the DelegationDAO.sol contract, use the following command, which requires you to specify the network name as defined in your hardhat.config.js. If you don't specify a network, Hardhat will deploy the contract to a local Hardhat network by default.
You'll be prompted to confirm the network you wish to deploy to. After a few seconds after you confirm, the contract is deployed, and you'll see the contract address in the terminal.
Congratulations, your contract is live on Phron! Save the address, as you will use it to interact with this contract instance in the next step.
Verifying Contracts on Phron
Contract verification is an essential step of any developer's workflow, particularly in the theoretical example of this staking DAO. Potential participants in the DAO need to be assured that the smart contract works as intended - and verifying the contract allows anyone to observe and analyze the deployed smart contract.
While it's possible to verify smart contracts on the Phronscan website, the Hardhat Etherscan plugin enables us to verify our staking DAO in a faster and easier manner. It's not an exaggeration to say that the plugin dramatically simplifies the contract verification process, especially for projects that include multiple Solidity files or libraries.
Before beginning the contract verification process, you'll need to acquire a Phronscan API Key. Note that Phron use the same Phronscan API key, whereas you'll need a distinct API key for Phron.
To verify the contract, you will run the ignition verify command and pass the name of your deployment you set in the prior step.
NoteIf you're deploying
DelegationDAO.solverbatim without any changes, you may get anAlready Verifiederror because Phronscan automatically recognizes and verifies smart contracts that have matching bytecode. Your contract will still show as verified, so there is nothing else you need to do. However, if you'd prefer to verify your ownDelegationDAO.sol, you can make a small change to the contract (such as changing a comment) and repeating the compilation, deployment and verification steps.
In your terminal, you should see the source code for your contract was successfully submitted for verification. If the verification was successful, you should see Successfully verified contract and there will be a link to the contract code on Phronscan. If the plugin returns an error, double check that your API key is configured correctly and that you have specified all necessary parameters in the verification command. You can refer to the guide to the Hardhat Etherscan plugin for more information.
Deploying to Production on Phron Mainnet
Note
DelegationDAO.solis unreviewed and unaudited. It is designed only for demonstration purposes and not intended for production use. It may contain bugs or logic errors that could result in loss of funds.
In the following steps, we'll be deploying the DelegationDAO contract to the Phron MainNet network. Remember to add the Phron network to your hardhat.config.js and update the private keys of your accounts on Phron if you haven't done so already. Before deploying DelegationDAO to Phron, we need to change the address of the target collator, since our target collator on Phron does not exist on Phron. Head to your deploy script and change the target collator to 0x1C86E56007FCBF759348dcF0479596a9857Ba105 or another Phron collator of your choice. Your deployment script, named DelegationDao.js, should thus look like the following:
To run the script and deploy the DelegationDAO.sol contract, use the following command, which requires you to specify the network name as defined in your hardhat.config.js. If you don't specify a network, Hardhat will deploy the contract to a local Hardhat network by default.
You'll be prompted to confirm the network you wish to deploy to. After a few seconds after you confirm, the contract is deployed, and you'll see the contract address in the terminal.
Congratulations, your contract is live on Phron! Save the address, as you will use it to interact with this contract instance in the next step.
Verifying Contracts on Phron
In this section, we'll be verifying the contract that was just deployed on Phron. Before beginning the contract verification process, you'll need to acquire a Phronscan API Key. Note that Phron use the same Phronscan API key, whereas you'll need a distinct API key.
To verify the contract, you will run the ignition verify command and pass the name of your deployment you set in the prior step.
NoteIf you're deploying
DelegationDAO.solverbatim without any changes, you may get anAlready Verifiederror because Phronscan automatically recognizes and verifies smart contracts that have matching bytecode. Your contract will still show as verified, so there is nothing else you need to do. However, if you'd prefer to verify your ownDelegationDAO.sol, you can make a small change to the contract (such as changing a comment) and repeating the compilation, deployment, and verification steps.
In your terminal you should see the source code for your contract was successfully submitted for verification. If the verification was successful, you should see Successfully verified contract and there will be a link to the contract code on Phronscan. If the plugin returns an error, double check that your API key is configured correctly and that you have specified all necessary parameters in the verification command. You can refer to the guide to the Hardhat Etherscan plugin for more information.
And that's it! We covered a lot of ground in this tutorial, but there's more resources available if you'd like to go deeper, including the following:
This tutorial is for educational purposes only. As such, any contracts or code created in this tutorial should not be used in production.The information presented herein has been provided by third parties and is made available solely for general information purposes. Phron does not endorse any project listed and described on the Phron Doc Website (https://docs.Phron.ai/). Phron does not warrant the accuracy, completeness or usefulness of this information. Any reliance you place on such information is strictly at your own risk. Phron disclaims all liability and responsibility arising from any reliance placed on this information by you or by anyone who may be informed of any of its contents. All statements and/or opinions expressed in these materials are solely the responsibility of the person or entity providing those materials and do not necessarily represent the opinion of Phron. The information should not be construed as professional or financial advice of any kind. Advice from a suitably qualified professional should always be sought in relation to any particular matter or circumstance. The information herein may link to or integrate with other websites operated or content provided by third parties, and such other websites may link to this website. Phron has no control over any such other websites or their content and will have no liability arising out of or related to such websites or their content. The existence of any such link does not constitute an endorsement of such websites, the content of the websites, or the operators of the websites. These links are being provided to you only as a convenience and you release and hold Phron harmless from any and all liability arising from your use of this information or the information provided by any third-party website or service.
Last updated