An awesome Solidity smart contract cheatsheet to force yourself to create lots of smart contracts weekly!
Explore the docs »
View Demo
·
Report Bug
·
Request Feature
Table of Contents
This is my personal ultimate guide and cheatsheet for smart contract creations with solidity, hardhat, & React JS. If you need a starter-pack for creating web3 smart contracts, you should definetly use it!
Here's why:
- Your time is the most important thing in your life. You will save lots of time by following this cheatsheet guide.
- It was carefully planed based on what I have learned in online academies, youtube video courses, bootcamps, and personal experience making lots of mistakes on purpose so you don't have to go through them.
- Using this cheatsheet makes it fun and easy to create Smart Contracts
This project is in an early stage. Be very careful if you use this code for any purposes, I advise against it.
Built with these frameworks/libraries, add-ons/plugins will be added later
First things first: Setting up the Environment.
-
Everything is done in VST with WSL: Ubuntu.
npm+vst+wsl Have to be instalated.
-
Make github repo and clone it from inside vst | wsl: ubuntu.
gitclone your empty-just-made github's repo
-
Make the
Readme.md
file and add aLicense.txt
Copy one and tune it to the flavour of your smart contract.
-
Open the terminal in vst | Enter WSL: Ubuntu terminal and go to the project's directory.
You can get a nice wsl terminal at -link coming soon- & Pimp it.
-
You must have Git, Node, and Yarn. Check it.
git --version node --version yarn --version
-
Initialize the
package.json
.yarn init
-
Add
Hardhat
yarn add --dev hardhat
-
Initialize Hardhat. When asked, answer: | Javascript | .gitignore:
yes
| dependencies:yes
.yarn hardhat
-
Check Hardhat is runing fine and check its commands
yarn hardhat
-
Compile built-in starter contract, just because.
yarn hardhat compile
-
In the
/contracts/
folder, create a fileMyAmazingContract.sol
. You can copypaste this template:
MyAmazingContract.sol
// SPDX-License-Identifier: MIT
// 1. Pragma
pragma solidity ^0.8.checklatestversion;
// 2. Imports
// 3. Interfaces, Libraries, Contracts
/* @title: "A superb Smart Contract"
* @author: "My Name here"
* @notice: "Super brief explanation of the contract"
* @dev: "Super brief technical explanation"
*/
contract NameOfTheContract {
// Type Declarations
// State variables
// Events
// Modifiers
// Functions Order:
//// constructor
//// receive
//// fallback
//// external
//// public
//// internal
//// private
//// view / pure
}
/* @param: Explain some param here.
* @notice: Write some short ending comentary here. Be nice.
*/
For other great Smart Contract templates you can go HERE
- In the
/scripts/
folder, modifydeploy.js
deploy.js
//imports
const { ethers } = require("hardhat");
//async main
async function main() {
const NameOfTheContractFactory = await ethers.getContractFactory("NameOfTheContract")
console.log("Deploying contract...")
const nameOfTheContract = await NameOfTheContractFactory.deploy()
await nameOfTheContract.deployed()
console.log(`Deployed contract to: ${nameOfTheContract.address}`)
}
// Error handling
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error)
process.exit(1)
})
-
Add
Prettier
yarn add --dev prettier prettier-plugin-solidity
-
Create "
.prettierrc
" file in "./
"
.prettierrc
{
"tabWidth": 4,
"useTabs": false,
"semi": false,
"singleQuote": false
}
- Create "
.prettierignore
" file in "./
"
.prettierignore
node_modules
package.json
img
artifacts
cache
coverage
.env
.*
README.md
coverage.json
-
Change namings and run the script
yarn hardhat run scripts/deploy.js
-
[Optional] specific network:
yarn hardhat run scripts/deploy.js --network hardhat
-
-
Modify "
hardhat.config.js
" file in "./
"
hardhat.config.js
require("@nomiclabs/hardhat-waffle")
require("hardhat-gas-reporter")
require("@nomiclabs/hardhat-etherscan")
require("dotenv").config()
require("solidity-coverage")
require("hardhat-deploy")
// You need to export an object to set up your config
// Go to https://hardhat.org/config/ to learn more
// @type import('hardhat/config').HardhatUserConfig
const COINMARKETCAP_API_KEY = process.env.COINMARKETCAP_API_KEY || ""
const GOERLI_RPC_URL = process.env.GOERLI_RPC_URL ||
"https://eth-mainnet.alchemyapi.io/v2/your-api-key"
const PRIVATE_KEY = process.env.PRIVATE_KEY || "0x"
const ETHERSCAN_API_KEY = process.env.ETHERSCAN_API_KEY || ""
module.exports = {
defaultNetwork: "hardhat",
networks: {
hardhat: {
chainId: 31337,
// gasPrice: 130000000000,
},
goerli: {
url: GOERLI_RPC_URL,
accounts: [PRIVATE_KEY],
chainId: 5,
blockConfirmations: 6,
},
},
solidity: {
compilers: [
{
version: "^0.8.17",
},
{
version: "0.6.6",
},
],
},
etherscan: {
apiKey: ETHERSCAN_API_KEY,
// customChains: [], // uncomment this line if you are getting a TypeError: customChains is not iterable
},
gasReporter: {
enabled: true,
currency: "USD",
outputFile: "gas-report.txt",
noColors: true,
// coinmarketcap: COINMARKETCAP_API_KEY,
},
namedAccounts: {
deployer: {
default: 0, // here this will by default take the first account as deployer
1: 0, // similarly on mainnet it will take the first account as deployer. Note though that depending on how hardhat network are configured, the account 0 on one network can be different than on another
},
},
mocha: {
timeout: 500000,
},
}
- Add "
.env
" file in "./
". Make sure it is on.gitignore
before saving any changes.
.env
PRIVATE_KEY=234523425asdfasdfa
GOERLI_RPC_URL=http://0.0.0.0:8545
COINMARKETCAP_API_KEY=asdfasdfasdfasdfasdfasdfasdf
ETHERSCAN_API_KEY=asdfasdfasdfs
- [Important] : If you don't have those keys go check Lessons 3-6 of Patrick Collin's freeCodeCamp 32h Solidity course HERE
-
Run hardhat node environment (You can pick a pKey from here).
yarn hardhat node
-
Run hardhat local network
yarn hardhat console --network localhost
-
Clean hardhat cache
yarn hardhat clean
-
Add
dotenv
yarn add --dev dotenv
-
Add
hardhat-etherscan
yarn add (--save)--dev @nomiclabs/hardhat-etherscan
-
Add
hardhat-gas-reporter
yarn add hardhat-gas-reporter --dev
-
Add
hardhat-deploy-ethers ethers
yarn add --dev @nomiclabs/hardhat-ethers@npm:hardhat-deploy-ethers ethers
-
Add
Chainlink contracts
yarn add --dev @chainlink/contracts
-
Add
OpenZeppeling contracts
yarn add --dev @openzeppelin/contracts
-
Add
hardhat-deploy
. Also deletedeploy.js
from/scripts/
and make its replacement in/deploy/
with01-deploy-contractname
.yarn add hardhat-deploy --dev rm scripts/deploy.js mkdir deploy touch deploy/01-deploy-myamazingcontract.js touch helper-hardhat-config.js touch deploy/00-deploy-mocks.js
01-deploy-myamazingcontract.js
const { network } = require("hardhat")
const { networkConfig, developmentChains } = require("../helper-hardhat-config")
const { verify } = require("../utils/verify")
require("dotenv").config()
module.exports = async ({ getNamedAccounts, deployments }) => {
const { deploy, log } = deployments
const { deployer } = await getNamedAccounts()
const chainId = network.config.chainId
let ethUsdPriceFeedAddress
if (chainId == 31337) {
const ethUsdAggregator = await deployments.get("MockV3Aggregator")
ethUsdPriceFeedAddress = ethUsdAggregator.address
} else {
ethUsdPriceFeedAddress = networkConfig[chainId]["ethUsdPriceFeed"]
}
log("----------------------------------------------------")
log("Deploying MyAmazingContract and waiting for confirmations...")
const myAmazingContract = await deploy("MyAmazingContract", {
from: deployer,
args: [ethUsdPriceFeedAddress],
log: true,
// we need to wait if on a live network so we can verify properly
waitConfirmations: network.config.blockConfirmations || 1,
})
log(`MyAmazingContract deployed at ${myAmazingContract.address}`)
if (
!developmentChains.includes(network.name) &&
process.env.ETHERSCAN_API_KEY
) {
await verify(myAmazingContract.address, [ethUsdPriceFeedAddress])
}
}
module.exports.tags = ["all", "myAmazingContract"]
helper-hardhat-config.js
const networkConfig = {
31337: {
name: "localhost",
},
// Price Feed Address, values can be obtained at https://docs.chain.link/docs/reference-contracts
5: {
name: "goerli",
ethUsdPriceFeed: "0xD4a33860578De61DBAbDc8BFdb98FD742fA7028e",
},
}
const developmentChains = ["hardhat", "localhost"]
module.exports = {
networkConfig,
developmentChains,
}
00-deploy-mocks.js
const { network } = require("hardhat")
const DECIMALS = "8"
const INITIAL_PRICE = "200000000000" // 2000
module.exports = async ({ getNamedAccounts, deployments }) => {
const { deploy, log } = deployments
const { deployer } = await getNamedAccounts()
const chainId = network.config.chainId
// If we are on a local development network, we need to deploy mocks!
if (chainId == 31337) {
log("Local network detected! Deploying mocks...")
await deploy("MockV3Aggregator", {
contract: "MockV3Aggregator",
from: deployer,
log: true,
args: [DECIMALS, INITIAL_PRICE],
})
log("Mocks Deployed!")
log("------------------------------------------------")
log(
"You are deploying to a local network, you'll need a local network running to interact"
)
log(
"Please run `npx hardhat console` to interact with the deployed smart contracts!"
)
log("------------------------------------------------")
}
}
module.exports.tags = ["all", "mocks"]
- In the
/contracts/test/
folder, create a fileMockV3Aggregator.sol
.
mkdir contracts/test
touch contracts/test/MockV3Aggregator.sol
MockV3Aggregator.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "@chainlink/contracts/src/v0.6/tests/MockV3Aggregator.sol";
- Make a
/utils/
folder, create a fileverify.js
.
mkdir utils
touch utils/verify.js
verify.js
const { run } = require("hardhat")
const verify = async (contractAddress, args) => {
console.log("Verifying contract...")
try {
await run("verify:verify", {
address: contractAddress,
constructorArguments: args,
})
} catch (e) {
if (e.message.toLowerCase().includes("already verified")) {
console.log("Already verified!")
} else {
console.log(e)
}
}
}
module.exports = { verify }
-
Add
solhint
. Check Solidity writing errors.yarn add solhint touch .solhint.json touch .solhintignore
.solhint.json
{
"extends": "solhint:recommended",
"rules": {
"compiler-version": ["error", "^0.8.17"],
"func-visibility": ["warn", { "ignoreConstructors": true }]
}
}
.solhintignore
node_modules
contracts/test
-
Add
solidity-coverage
. Great for starting to test.yarn add --dev solidity-coverage
-
Make two extra testing folders, add the files, run some tests
mkdir test/staging mkdir test/unit touch test/unit/Mycontractname.test.js yarn solhint contracts/*.sol yarn hardhat coverage yarn hardhat test
-
[Optional] specific test:
``` yarn hardhat test --grep keywordOfTheTest ```
Add propper content to the
Mycontractname.test.js
tests.
-
Example on how to install/use will come in the future...
-
Clone the repo
git clone https://github.com/JPLACLAU/web3cheatsheet
-
Coming soon...
Coming soon...
You should not use this guide at this moment.
For more examples, please refer to the Documentation
- Start the proyect
- Add moar stuff
See the open issues for a full list of proposed features (and known issues).
Current version: 0.2
Version | Changes |
---|---|
0.4 |
Real usefull cheatsheet guide...at least some sections of it. |
0.3 |
Unit testing |
0.2 |
Environment requirements done. |
0.1 |
Start the proyect /write the Readme.md |
Contributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are greatly appreciated.
If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also simply open an issue with the tag "enhancement". Don't forget to give the project a star! Thanks again!
- Fork the Project
- Create your Feature Branch (
git checkout -b feature/AmazingFeature
) - Commit your Changes (
git commit -m 'Add some AmazingFeature'
) - Push to the Branch (
git push origin feature/AmazingFeature
) - Open a Pull Request
Distributed under the MIT License. See LICENSE.txt
for more information.
Jean-Paul Laclau - @jplaclau -
Project Link: https://github.com/JPLACLAU/web3cheatsheet
Thank you so much to.. no one yet! Be the first to collab!
Check the LICENSE.txt