Hardhat Smart Contract Development
Prerequisites
MetaMask installed & connected to a local Creditcoin node or public testnet
A funded account
Node.js & NPM installed
Setting up Hardhat
To create a Hardhat project you must initialize a node project using npm
. Navigate to the folder where you want to build your project and run:
If you don’t have Hardhat installed globally, you’ll be prompted to do so.
Follow the prompts to set up your project. You can choose options like creating a sample project or starting an empty project. For this tutorial, we will crate a TypeScript project.
Writing your first contract
Inside the contracts
directory of your Hardhat project, create a new Solidity file (e.g., MyContract.sol
).
For simplicity, we will first delete the example contract Hardhat created for us. Remove the Lock.sol
file from the contracts
folder, its associated test Lock.ts
from the test
folder and deploy.ts
in the scripts
directory. We will write their replacements.
For this tutorial we will use a simple Counter contract. You can copy and paste the following code into the contract file you have just created.
Compiling
Before you can deploy or test your contract. You need to compile it. Run npx hardhat compile
to do so.
Testing
Before we deploy the contract, we want to make sure it works as expected. We can use Hardhat to write and run some tests for our Counter contract.
Create a file inside the test
folder called Counter.test.ts
and add the following basic test.
Test the contract by running npx hardhat test
. You should see the following output.
To add more tests to the contract, add more it
statements to the test file.
Deploying a smart contract
To deploy your contract, you will need to write a deploy script. Create a file named deploy.ts
You can deploy the contract by running:
Without the --network
flag, the deployment will run against the local Hardhat Network, which means it gets lost after the command finishes running. But it is useful for testing that our deployment script works.
To deploy the contract to a remote network, we will need to add a network to hardhat.config.ts
. In this example we will use Creditcoin Testnet.
Avoid at all costs hard-coding credentials into source code. Use the vars.get
method in combination with the vars set
Hardhat command to set them up in a safe way. You can also use environment variables prefixed with HARDHAT_VAR_
to override the values of configuration variables.
HARDHAT_VAR_CC3TEST_PRIVATE_KEY=123
You will then need to set the CC3 development private key by running the Hardhat vars set
command:
After setting up the new config, run:
Forking CC3 EVM
If you wish to test using the current state of a network, you can use Hardhat to fork a Creditcoin network and test locally against it.
This will spin up a local node using the state from the forked network. It comes with all its deployed contracts, current balances and new funded accounts.
Last updated