Blockchain development introduction — based on the creation of NFT

Altimetrik Poland Tech Blog
6 min readMar 4, 2024

--

Overview of Blockchain Development​

Before diving into NFT creation, let’s briefly cover some essential concepts in blockchain development:

  • Blockchain — is a decentralized and distributed database that records transactions across a network of computers in a secure and transparent manner.
  • Smart Contracts — self-executing co ntracts with the terms of the agreement directly written into code. Smart contracts enable automation and facilitate interactions on the blockchain.
  • Ethereum — a popular blockchain platform known for its programmability, allowing developers to build decentralized applications (DApps) and issue tokens, including NFTs, using its native programming language, Solidity.
  • Hardhat — is a development environment and testing framework tailored for Ethereum smart contract development. It simplifies tasks such as compiling contracts, automating testing, managing Ethereum networks, and integrating with popular libraries like Web3.js and Ethers.js. Developers typically run Hardhat on their localhost. With its streamlined functionalities, Hardhat accelerates the development process and ensures the reliability of Ethereum-based applications.
  • MetaMask — is a popular browser extension and mobile app that serves as a blockchain wallet and gateway to the decentralized web. It allows users to manage their Ethereum accounts, interact with decentralized applications (DApps), and securely store cryptocurrencies. MetaMask provides a user-friendly interface for accessing Ethereum-based services and dApps directly from a web browser, enabling seamless integration of blockchain technology into everyday online activities. With MetaMask, users can easily send and receive Ether (ETH), manage non-fungible tokens (NFTs), and participate in decentralized finance (DeFi) protocols, all while maintaining control over their private keys and personal data. MetaMask, in conjunction with Hardhat, offers the capability to seamlessly import testing accounts generated during the development process. These accounts, typically seeded with test Ether (ETH) for experimentation, can be imported into MetaMask.

Prerequisites

  1. Node.js installed on your machine. I recommend installing Node using nvm.
  2. MetaMask wallet installed as a browser extension.

Creating NFTs and NFTMarketplace

Choose a Blockchain Platform — Select a suitable blockchain platform, considering factors like scalability, transaction costs, and community support. In this example I’ll use Ethereum which is the most popular choice due to its scalability, active community support, and wide adoption. However, alternative options like Binance Smart Chain (BSC), Polygon, Solana, and Avalanche also offer unique features such as low transaction costs, high throughput, and fast transaction speeds. The choice depends on factors like project requirements, scalability needs, and transaction costs.

Set Up project — I’m going to use Next.js for frontend part about which I will write later.

npx create-next-app nft-marketplace

Set Up Development Environment — Install necessary tools and frameworks like Hardhat or Ethers, facilitating smart contract development and deployment. Next, Configure it.

//install tools
npm install ethers hardhat @nomiclabs/hardhat-waffle \
ethereum-waffle chai @nomiclabs/hardhat-ethers \
web3modal @openzeppelin/contracts ipfs-http-client \
axios
//configure hardhat
npx hardhat

Write Smart Contract — After configuring hardhat you can start developing a smart contract defining the NFT’s properties and functionalities, including metadata and ownership tracking. Example of code you can check on my github :) here is a file path: nft-frontend/contracts/NFTMarketplace.sol

Compile and Deploy Contract — Firstly we should run our local network and then run script to compile the smart contract code and deploy it to the chosen blockchain network.

// run local network
npx hardhat node
// deploy contract
npx hardhat run scripts/deploy.js --network localhost

Importing Accounts into MetaMask

You have the option to import accounts created by the node into your MetaMask wallet for experimentation within the application.

Each of these imported accounts is initially endowed with 10,000 ETH.

To import one of these accounts, begin by switching your MetaMask wallet network to Localhost 8545. Within MetaMask, navigate to the accounts menu and select “Import Account.”

Copy and paste one of the Private Keys previously displayed by the CLI, then click “Import.” Once the account is successfully imported, you will observe the corresponding ETH balance in the account.

Creating frontend

When it comes to building a frontend for your NFT marketplace, selecting the right tools and frameworks is crucial to ensure a seamless user experience and efficient interaction with the blockchain. In this section, we’ll explore how you can leverage Next.js, Ethers, and Web3 to develop a robust and user-friendly frontend for your NFT marketplace.

  • Next.js — is a popular React framework that offers server-side rendering, automatic code splitting, and other powerful features out of the box. Its intuitive routing system and pre-rendering capabilities make it an excellent choice for building dynamic web applications, including NFT marketplaces. With Next.js, you can create a responsive and performant frontend that seamlessly integrates with the backend infrastructure.
  • Ethers — is a JavaScript library that provides a simple and intuitive API for interacting with the Ethereum blockchain. It allows developers to send transactions, deploy contracts, and interact with smart contracts directly from the frontend code. By integrating Ethers.js into your Next.js application, you can enable users to buy, sell, and trade NFTs with ease, all while ensuring security and reliability.
  • Web3 — is another popular JavaScript library that serves as the Ethereum JavaScript API, providing a wide range of functionalities for interacting with Ethereum-based applications. With Web3.js, you can connect your frontend to the Ethereum blockchain, retrieve data from smart contracts, and listen for events emitted by the blockchain. By leveraging Web3.js in conjunction with Next.js and Ethers, you can create a seamless and interactive user experience for your NFT marketplace users.

Integrating Next.js, Ethers, and Web3 into your frontend development workflow involves several steps:

nft-frontend/context/NFTMarketplaceContext.js

Connect to Ethereum Network — Use Ethers.js or Web3.js to connect your frontend application to the Ethereum network. Configure the provider to connect to the desired network (e.g., localhost for development or a public Ethereum network for production).

const connectWithSmartContract = async() => {
try{
const web3Modal = new Web3Modal()
const connection = await web3Modal.connect()
const provider = new ethers.providers.Web3Provider(connection)
const signer = provider.getSigner()
const contract = fetchContract(signer)
return contract
} catch (error){
console.log("Error while connecting with the smart contract: " + error)
}
}

Display NFT Listings — Retrieve NFT listings and display them on your marketplace frontend. Use Ethers.js or Web3.js to query smart contracts for available NFTs and render them dynamically on your Next.js application.

const fetchNFTs = async() => {
try {
const provider = new ethers.providers.JsonRpcProvider();
const contract = fetchContract(provider)
        const data = await contract.fetchMarketItems()        const items = await Promise.all(
data.map(
async({tokenId, seller, owner, creator, price: unformattedPrice, sold}) => {
const tokenURI = await contract.tokenURI(tokenId)
const {
data: {fileUrl, name, description}
} = await axios.get(tokenURI)
const price = ethers.utils.formatUnits(
unformattedPrice.toString(),
"ether"
)
return {
price,
tokenId: tokenId.toNumber(),
seller,
owner,
creator,
fileUrl,
name,
description,
tokenURI,
sold
}
}
)
)
return items
} catch (error) {
console.log("Error while fetching NFTs")
}
}

Enable Buying and Selling — Implement functionalities to enable users to buy and sell NFTs directly from the frontend. Use Ethers.js or Web3.js to interact with smart contracts, execute transactions, and update user balances accordingly.

Handle Transaction Confirmation — Provide feedback to users on transaction status and handle transaction confirmation and error handling gracefully. Use Ethers.js or Web3.js event listeners to monitor transaction status and update UI accordingly.

By implementing a provider pattern with the NFTMarketplace provider component, you can efficiently manage NFTs data and make it accessible across all components within your Next.js application. This approach ensures consistency and reusability while fetching and displaying data from the Ethereum blockchain.

Summary

Now you know how to:

  • work with hardhat
  • create smart contracts
  • connect your frontend to blockchain network
  • how to provide blockchain data to your frontend components

Words by Grzegorz Święcicki, Altimetrik Poland

https://medium.com/@g.swiecickii

You can find Github repository here.

--

--

Altimetrik Poland Tech Blog

This is a Technical Blog of Altimetrik Poland team. We focus on subjects like: Java, Data, Mobile, Blockchain and Recruitment. Waiting for your feedback!