Building and deploying a smart contract with OpenZepplin and Solidity in less than 10 minutes
Josh Fischer
Posted on November 8, 2024
I've been developer for over 10 years now. I've been lucky enough to become an Apache committer and PPMC, speak at Google, write a book for Manning Publications, and a few other things. As the job market is not great and people are struggling to find good work, I'm starting to see business opportunities in blockchain, more specifically - I see some great opportunities to help others build their own businesses. I'd like to share some technical things I've learned in the last few weeks.
I’ve been working through understanding the pros and cons of distributed applications (DApps). There are many tools out there for you to choose from to get started in building them. In this article I’m giving you an opinionated approach to building, deploying and interacting with smart contracts locally. No web based tools, only command line.
Prerequisites:
I'm using Node 18.17, however, this should work with a later version of node.
Install node 18.17, if you don't have it already
$ nvm install 18.17
First, create your folder and cd
into it
$ mkdir hello-world && cd hello-world
Initialize the project
$ npm init -y
Install Hardhat locally in our project
$ npm install --save-dev hardhat
Sidenote about npx
npx
is used to run executables installed locally in your project. It’s recommended to install Hardhat locally in each project so that you can control the version on a project by project basis.
Setting up a Project
$ npx hardhat init
Need to install the following packages:
hardhat@2.22.15
Ok to proceed? (y)
You should see the option show up. Select “ Create an empty hardhat.config.js”
You'll see this upon successful creation.
✔ What do you want to do? · Create an empty hardhat.config.js
✨ Config file created ✨
To verify everything executed as expected you should now see two field in your current directory.
See what's been created in your directory
$ ls -lta
package.json
hardhat.config.js
Build you first contract
When using Hardhat you can store Solidity source files (.sol) in a contracts
directory. We will write our first simple smart contract, called Storage: it will let people store a value that can be later retrieved. It's a variation of another starter contract with Hardhat. I'm working through the process manually so we understand all of the moving pieces.
Create the contracts folder and open the file for editing
$ mkdir contracts && vim contracts/Storage.sol
Add the following to the Storage.sol
file
// contracts/Storage.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Storage {
uint256 private _value;
// Emitted when the stored value changes
event ValueChanged(uint256 value);
// Stores a new value in the contract
function store(uint256 value) public {
_value = value;
emit ValueChanged(value);
}
// Reads the last stored value
function retrieve() public view returns (uint256) {
return _value;
}
}
After writing the above to the file close vim
with :wq
or :x
Compiling Solidity
The Ethereum Virtual Machine (EVM) cannot execute Solidity code directly: we first need to compile it into EVM bytecode. Our Storage.sol contract uses Solidity 0.8 so we need to first configure Hardhat to use an appropriate solc version. We specify a Solidity 0.8 solc version in our hardhat.config.js
.
/** @type import('hardhat/config').HardhatUserConfig */
module.exports = {
solidity: "0.8.27",
};
Run the command
$ npx hardhat compile
Compiled 1 Solidity file successfully (evm target: paris).
Deployment set up
We will create a script to deploy our Storage contract. We will save this file as scripts/deploy.js.
$ mkdir scripts && vim scripts/deploy.js
// scripts/deploy.js
async function main () {
// We get the contract to deploy
const Storage = await ethers.getContractFactory('Storage');
console.log('Deploying...');
const storage = await Storage.deploy();
await storage.waitForDeployment();
console.log('Storage deployed to:', await storage.getAddress());
}
main()
.then(() => process.exit(0))
.catch(error => {
console.error(error);
process.exit(1);
});
We use ethers in our script, so we need to install it and the @nomicfoundation/hardhat-ethers
plugin.
$ npm install --save-dev @nomicfoundation/hardhat-ethers ethers
We need to add in our configuration that we are using the @nomicfoundation/hardhat-ethers plugin.
Our hard hat config should now look like this;
require("@nomicfoundation/hardhat-ethers");
/** @type import('hardhat/config').HardhatUserConfig */
module.exports = {
solidity: "0.8.27",
};
Set up a local blockchain
We need an environment where we can deploy our contracts. The Ethereum blockchain (often called "mainnet", for "main network") requires spending real money to use it, in the form of Ether (its native currency). This makes it a poor choice when trying out new ideas or tools.
To solve this, a number of "testnets" (for "test networks") exist: However, you will still need to deal with private key management, blocktimes of 12 seconds or more, and actually getting this free Ether.
During development, it is a better idea to instead use a local blockchain. It runs on your machine, provides you with all the Ether that you need, and mines blocks instantly.
Create a local instance
$ npx hardhat node
Started HTTP and WebSocket JSON-RPC server at http://127.0.0.1:8545/
Accounts
========
WARNING: These accounts, and their private keys, are publicly known.
Any funds sent to them on Mainnet or any other live network WILL BE LOST.
Deploying the Smart Contract
Deploy your smart contract
$ npx hardhat run --network localhost scripts/deploy.js
Deploying Storage...
Storage deployed to: 0x5FbDB2315678afecb367f032d93F642f64180aa3
Interacting from the Console
With our Storage contract deployed, we can start using it right away.
We will use the Hardhat console to interact with our deployed Storage contract on our localhost network.
We need to specify the address of our Storage contract we displayed in our deploy script.
It’s important that we explicitly set the network for Hardhat to connect our console session to. If we don’t, Hardhat will default to using a new ephemeral network, which our Storage contract wouldn’t be deployed to.
$ npx hardhat console --network localhost
Welcome to Node.js v20.17.0.
Type ".help" for more information.
> const Storage = await ethers.getContractFactory('Storage');
undefined
> const storage = Storage.attach('0x5FbDB2315678afecb367f032d93F642f64180aa3');
undefined
Sending transactions
The first function, store, receives an integer value and stores it in the contract storage. Because this function modifies the blockchain state, we need to send a transaction to the contract to execute it.
We will send a transaction to call the store function with a numeric value:
> await storage.store(76);
ContractTransactionResponse {
provider: HardhatEthersProvider {
_hardhatProvider: LazyInitializationProviderAdapter {
_providerFactory: [AsyncFunction (anonymous)],
_emitter: [EventEmitter],
_initializingPromise: [Promise],
provider: [BackwardsCompatibilityProviderAdapter]
},
_networkName: 'localhost',
_blockListeners: [],
_transactionHashListeners: Map(0) {},
_eventListeners: []
},
blockNumber: 3,
blockHash: '0xb643517cd642a31404381fc32fcb7ba3ae03a63b5a863e8b4d9b6232abb8688f',
index: undefined,
hash: '0x8b1065f715f7f93528dcea2b726d976cf8eeddf3689079330737e34cfb0b6d1c',
type: 2,
to: '0x5FbDB2315678afecb367f032d93F642f64180aa3',
from: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266',
nonce: 2,
gasLimit: 30000000n,
gasPrice: 849344383n,
maxPriorityFeePerGas: 203635707n,
maxFeePerGas: 849344383n,
maxFeePerBlobGas: null,
data: '0x6057361d000000000000000000000000000000000000000000000000000000000000004c',
value: 0n,
chainId: 31337n,
signature: Signature { r: "0x351be9ab4359f037abbf2e41c64f13f4c060d64eb6467fd35e42c0133b71234f", s: "0x45b473c2cc793a1a5a6d8cb1482efbda5c90c263196e3475d093ec788ea63bf9", yParity: 1, networkV: null },
accessList: [],
blobVersionedHashes: null
}
Querying state
The other function is called retrieve, and it returns the integer value stored in the contract. This is a query of blockchain state, so we don’t need to send a transaction:
> await storage.retrieve();
76n
Because queries only read state and don’t send a transaction, there is no transaction hash to report. This also means that using queries doesn’t cost any Ether, and can be used for free on any network.
Wrapping up
We've created a minimal smart contract and deployed it to a local blockchain instance to demonstrate how we can write and read values from the blockchain. If you found this article helpful, please give it a like and/or a share.
Please feel free to comment with suggestions or corrections you see fit. I write these articles before and after work, I get them out as quickly as I can.
Thanks!
Reference:
Hardhat docs
Posted on November 8, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.