Introduction
Since learning about web3, blockchain, dapps and NFTs I've been so fascinated with the different technologies and how they come together to make an ecosystem. The problem I've been having however is directly tied into hiding my credentials when pushing my code to GitHub, essentially I had no idea how to hide my private keys, and when you're dealing with smart contracts this is an essential skill. With that being said, let us begin.
Disclaimer: you MUST have a basic understanding of javascript and the hardhat environment for any of this to make sense.
Step 1: Install dotenv
This is an npm package that allows us to load environment variables from a .env file.
npm install dotenv
run that snippet of code in the terminal
Step 2: Create a .env file in the root directory of your project
This is where you will keep your confidential credentials
Step 3: Add the variables to the hardhat.config.js
In this part of the article, I will be going through the screenshot below line by line to explain to you the lines of code that are necessary to hide the environment variables.
This essentially allows us to use the dotenv package in our code
require("dotenv").config();
Instead of pasting your private key and your alchemy API key bare-bones inside the URL and account we use process.env.ALCHEMY_API_KEY and [process.env.PRIVATE_KEY] this essentially hides your credentials when you're ready to push to github.
networks:{
rinkeby:{
url: process.env.ALCHEMY_API_KEY,
accounts: [process.env.PRIVATE_KEY],
},
},
Extra step
Check your gitignore file and ensure that the .env file is inside it. Below I will show you what i mean.
Conclusion
Knowing how to hide your environment variables is extremely important when we're writing smart contracts and building dapps, I made the very silly mistake of uploading a token smart contract with all my credentials out in the open, it was a dummy account with only fake eth but at the end of the day it could've been worse. I really hope this tutorial will help you understand how to write more secure smart contracts.