Home Web Front-end JS Tutorial Building and deploying a smart contract with OpenZepplin and Solidity in less than minutes

Building and deploying a smart contract with OpenZepplin and Solidity in less than minutes

Nov 10, 2024 am 03:51 AM

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
Copy after login
Copy after login
Copy after login

First, create your folder and cd into it

$ mkdir hello-world && cd hello-world
Copy after login
Copy after login
Copy after login

Initialize the project

$ npm init -y
Copy after login
Copy after login

Install Hardhat locally in our project

$ npm install --save-dev hardhat
Copy after login
Copy after login

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”
Copy after login
Copy after login

Building and deploying a smart contract with OpenZepplin and Solidity in less than minutes

You'll see this upon successful creation.

✔ What do you want to do? · Create an empty hardhat.config.js
✨ Config file created ✨
Copy after login
Copy after login

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
Copy after login
Copy after login

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
Copy after login
Copy after login

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;
    }
}
Copy after login

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.

$ nvm install 18.17
Copy after login
Copy after login
Copy after login

Run the command

$ mkdir hello-world && cd hello-world
Copy after login
Copy after login
Copy after login

Deployment set up

We will create a script to deploy our Storage contract. We will save this file as scripts/deploy.js.

$ npm init -y
Copy after login
Copy after login
$ npm install --save-dev hardhat
Copy after login
Copy after login

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;

$  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”
Copy after login
Copy after login

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

✔ What do you want to do? · Create an empty hardhat.config.js
✨ Config file created ✨
Copy after login
Copy after login

Deploying the Smart Contract

Deploy your smart contract

$ ls -lta
package.json
hardhat.config.js
Copy after login
Copy after login

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.

$ mkdir contracts &&  vim contracts/Storage.sol
Copy after login
Copy after login

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:

$ nvm install 18.17
Copy after login
Copy after login
Copy after login

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:

$ mkdir hello-world && cd hello-world
Copy after login
Copy after login
Copy after login

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

The above is the detailed content of Building and deploying a smart contract with OpenZepplin and Solidity in less than minutes. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

See all articles