Skip to content
JournalTORIS / FIELD NOTES

← Blog Learning notes

A Next.js-Based Web3 Product Stack: Toris Engineering Notes

Notes on the Next.js stack Toris validated building Web3 products like PEPEBear and CryptoTrade.gg: deploying contracts with Hardhat, OpenZeppelin, thirdweb, and ethers.js, plus NFT and points systems.

6 min read Read the Korean original

Joohwan Yu · Founder, Full Stack Developer

Toris · Published

Contents

Q. How do you build blockchain and Web3 apps with Next.js? You connect Hardhat, thirdweb, and ethers.js to Next.js, deploy smart contracts, and build Web3 apps such as NFTs and point systems. This guide is organized around the stack setup Toris validated while building real products.

Toris validated this stack while building Web3-flavored products such as PEPEBear and CryptoTrade.gg. PEPEBear is a memecoin frontend with Phantom and Solflare wallet integration plus gamification through points, achievements, and levels. CryptoTrade.gg is a dashboard that visualizes trading history using Next.js, TypeScript, and Recharts. This post is written around the EVM (Ethereum-family) toolchain, but PEPEBear is Solana-based, so at the contract layer I used Anchor and Web3.js instead of Hardhat and Solidity. Even so, the frontend decisions, such as wallet connection UX, transaction state handling, and on-chain data caching, carried over unchanged regardless of the chain.

When validating a Web3 prototype, what matters is not the contract itself but how fast you can try out the UX up to the moment of “connecting a wallet and sending a transaction.” Next.js alone can cover the landing page, dashboard, and contract integration, so Toris reaches for this stack as the default whenever starting a Web3-flavored product. Below are my EVM development notes organized on that basis.

📋 Table of Contents

  1. Development environment setup
  2. NFT development: from contract to Next.js UI
  3. Implementing a points system
  4. Real-world integration example
  5. Deployment and operations strategy

🚀 Development Environment Setup

I use Hardhat for the contract development environment, and thirdweb plus ethers.js for frontend integration. It’s a proven combination, and it had the lowest onboarding cost.

Installing the required tools

# 1. Initialize the Next.js project (with TypeScript)
# Next.js 15 supports React 19, and the Turbopack dev server has stabilized.
npx create-next-app@latest my-web3-app --typescript
cd my-web3-app

# 2. Install blockchain development tools
# Hardhat: Ethereum development environment (compile, test, and deploy contracts)
npm install --save-dev hardhat @nomiclabs/hardhat-ethers ethers
# OpenZeppelin Contracts: security-audited smart contract library
npm install @openzeppelin/contracts
# thirdweb SDK: library that simplifies blockchain interaction in Next.js
npm install @thirdweb-dev/react @thirdweb-dev/sdk

# 3. Developer convenience tools (optional)
# Next.js 15 supports the next.config.ts file and offers improved TypeScript support.
# npm install web3modal @walletconnect/web3-provider

Hardhat configuration

Define the Solidity compiler version and network information in hardhat.config.js.

// hardhat.config.js
require('@nomiclabs/hardhat-ethers');
require('@nomiclabs/hardhat-waffle'); // Add the Waffle plugin (makes testing easier)

module.exports = {
  solidity: '0.8.19', // Solidity compiler version to use
  networks: {
    hardhat: {
      // Hardhat network for local development
      chainId: 31337 // Commonly used local chain ID
    },
    mumbai: {
      // Polygon Mumbai testnet configuration
      url: 'https://rpc-mumbai.maticvigil.com', // Mumbai RPC URL
      accounts: [process.env.PRIVATE_KEY] // Load the private key from the .env file
    }
    // Other networks (e.g., Sepolia, Polygon Mainnet) can be added here too
  },
  paths: {
    artifacts: './artifacts', // Where compiled contract artifacts are stored
    sources: './contracts', // Solidity source code path
    cache: './cache', // Cache path
    tests: './test' // Test file path
  }
};

Environment variable setup

Store sensitive information (API keys, private keys) in .env.local and exclude it from version control with .gitignore. A private key getting pushed to a repository is the most common and most fatal accident in Web3.

# .env.local (create it in the project root)
# API key from a node provider such as Alchemy or Infura (optional)
NEXT_PUBLIC_ALCHEMY_API_KEY=your_alchemy_key
# Client ID issued from the thirdweb dashboard (required)
NEXT_PUBLIC_THIRDWEB_CLIENT_ID=your_thirdweb_client_id
# Private key of the wallet used to deploy contracts (never expose it! Use for testing only)
PRIVATE_KEY=your_wallet_private_key
# API keys for an IPFS service (e.g., Pinata) (needed to upload NFT images/metadata)
PINATA_API_KEY=your_pinata_key
PINATA_SECRET_KEY=your_pinata_secret

Advertisement

🎨 NFT Development: From Contract to Next.js UI

An NFT (Non-Fungible Token) is a unique, non-interchangeable digital asset. This section walks through the flow of building an NFT frontend with Next.js, from the contract to the minting UI.

1. Writing the NFT contract (Solidity)

Inherit OpenZeppelin’s standard ERC-721 contract and implement the basic logic on top of it. The rule is not to write token standards yourself. Audited code already exists, and rewriting it only adds risk.

// contracts/MyNFT.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";

// The MyNFT contract follows the ERC721 standard, with URI storage and owner permissions.
contract MyNFT is ERC721, ERC721URIStorage, Ownable {
    using Counters for Counters.Counter; // Library for safely incrementing token IDs
    Counters.Counter private _tokenIds; // Counter for the unique ID of each minted NFT

    // Set the NFT's name and symbol when the contract is deployed.
    constructor() ERC721("MyAwesomeNFT", "MANFT") {}

    // Override the NFT's URI to use the ERC721URIStorage feature.
    function _baseURI() internal view virtual override returns (string memory) {
        return ""; // Leave the base URI empty and set a URI for each token.
    }

    // Function that mints a new NFT. Only the contract owner can call it.
    function mintNFT(address recipient, string memory tokenURI)
        public onlyOwner
        returns (uint256)
    {
        _tokenIds.increment(); // Increment to the next token ID
        uint256 newItemId = _tokenIds.current(); // Get the current token ID
        _mint(recipient, newItemId); // Mint the NFT to the given address
        _setTokenURI(newItemId, tokenURI); // Set the NFT's metadata URI
        return newItemId; // Return the ID of the minted NFT
    }

    // Function override required to use ERC721URIStorage
    function tokenURI(uint256 tokenId) public view override(ERC721, ERC721URIStorage) returns (string memory) {
        return super.tokenURI(tokenId);
    }
}

2. NFT marketplace contract (Solidity)

This is the marketplace logic for selling and buying NFTs. Any function that moves funds gets ReentrancyGuard by default.

// contracts/NFTMarketplace.sol
pragma solidity ^0.8.19;

import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";

contract NFTMarketplace is ReentrancyGuard {
    // Define the market item struct
    struct MarketItem {
        uint256 itemId; // Unique item ID within the marketplace
        address nftContract; // NFT contract address
        uint256 tokenId; // The NFT's unique ID
        address payable seller; // Seller address
        address payable owner; // Current owner address (the buyer after a sale)
        uint256 price; // Sale price
        bool sold; // Whether the sale is complete
    }

    mapping(uint256 => MarketItem) private idToMarketItem; // Look up a MarketItem by itemId
    uint256 private _itemIds; // Market item ID counter
    uint256 private _itemsSold; // Counter of sold items
    uint256 public listingPrice = 0.025 ether; // NFT listing fee

    // Define events
    event MarketItemCreated (
        uint256 indexed itemId,
        address indexed nftContract,
        uint256 indexed tokenId,
        address seller,
        address owner,
        uint256 price,
        bool sold
    );

    // Function that lists an NFT on the marketplace
    function createMarketItem(
        address nftContractAddress, // Address of the NFT contract to list
        uint256 tokenId, // Token ID of the NFT to list
        uint256 price // Sale price
    ) public payable nonReentrant {
        require(price > 0, "Price must be greater than 0");
        require(msg.value == listingPrice, "Price must be equal to listing price"); // Verify the listing fee

        _itemIds++;
        uint256 itemId = _itemIds;

        idToMarketItem[itemId] = MarketItem(
            itemId,
            nftContractAddress,
            tokenId,
            payable(msg.sender), // The seller is the function caller
            payable(address(0)), // No owner initially
            price,
            false // Not sold yet
        );

        // Transfer the NFT from the seller to the marketplace contract
        IERC721(nftContractAddress).transferFrom(msg.sender, address(this), tokenId);

        emit MarketItemCreated(
            itemId,
            nftContractAddress,
            tokenId,
            msg.sender,
            address(0),
            price,
            false
        );
    }

    // Function that buys an NFT
    function createMarketSale(
        address nftContractAddress, // Address of the NFT contract to buy from
        uint256 itemId // ID of the market item to buy
    ) public payable nonReentrant {
        uint256 price = idToMarketItem[itemId].price;
        uint256 tokenId = idToMarketItem[itemId].tokenId;

        require(msg.value == price, "Please submit the asking price"); // Verify the exact price was paid

        // Send the payment to the seller
        idToMarketItem[itemId].seller.transfer(msg.value);
        // Transfer the NFT from the marketplace contract to the buyer
        IERC721(nftContractAddress).transferFrom(address(this), msg.sender, tokenId);

        idToMarketItem[itemId].owner = payable(msg.sender); // Set the buyer as the owner
        idToMarketItem[itemId].sold = true; // Mark the sale as complete
        _itemsSold++;
    }
}

3. Next.js NFT component (React)

This React component displays NFT information and provides a purchase feature. NFT images vary widely in size, so it’s better to just use the Next.js Image component’s optimization as is.

// components/NFTCard.tsx
import { useState } from "react";
import { ethers } from "ethers";
import Image from "next/image"; // Use the Next.js Image component

interface NFTCardProps {
  nft: {
    tokenId: string;
    name: string;
    description: string;
    image: string; // Image URL
    price?: string; // Sale price (optional)
    owner: string; // Owner address
  };
  onBuy?: (tokenId: string) => void; // Purchase handler function
}

export default function NFTCard({ nft, onBuy }: NFTCardProps) {
  const [loading, setLoading] = useState(false);

  const handleBuy = async () => {
    if (!onBuy) return; // Do nothing if there is no purchase function

    setLoading(true);
    try {
      await onBuy(nft.tokenId);
    } catch (error) {
      console.error("NFT purchase failed:", error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="bg-white rounded-lg shadow-md overflow-hidden">
      <div className="relative h-64 w-full"> {/* Parent element for Next.js Image */}
        <Image
          src={nft.image}
          alt={nft.name}
          layout="fill"
          objectFit="cover"
          priority // High priority to improve LCP
        />
      </div>

      <div className="p-4">
        <h3 className="text-lg font-semibold mb-2">{nft.name}</h3>
        <p className="text-gray-600 mb-4">{nft.description}</p>

        {nft.price && (
          <div className="flex justify-between items-center">
            <span className="text-2xl font-bold">
              {ethers.utils.formatEther(nft.price)} ETH {/* Display the price in ETH */}
            </span>

            <button
              onClick={handleBuy}
              disabled={loading} // Disable the button while loading
              className="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600 disabled:opacity-50"
            >
              {loading ? "Buying..." : "Buy"}
            </button>
          </div>
        )}
      </div>
    </div>
  );
}

4. NFT minting page (Next.js)

This is the page where users mint NFTs themselves. Implementing the wallet connection and transaction signing flow by hand produces endless edge cases, so I chose to simplify it with thirdweb’s Web3Button.

// pages/mint.tsx
import { useState } from "react";
import { useContract, useAddress, Web3Button } from "@thirdweb-dev/react";

export default function MintPage() {
  const address = useAddress(); // Get the currently connected wallet address
  const { contract } = useContract("YOUR_NFT_CONTRACT_ADDRESS"); // Get the NFT contract instance

  const [formData, setFormData] = useState({
    name: "",
    description: "",
    image: null as File | null, // Image file object
  });

  // Image file selection handler
  const handleImageUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files[0]) {
      setFormData({ ...formData, image: e.target.files[0] });
    }
  };

  // NFT minting logic
  const mintNFT = async () => {
    if (!contract || !formData.image) {
      alert("Please enter the NFT name, description, and image.");
      return;
    }

    try {
      // 1. Upload the image to IPFS (using thirdweb storage)
      const imageUploadResult = await contract.storage.upload(formData.image);
      const imageUrl = imageUploadResult.uris[0]; // URI of the uploaded image

      // 2. Create the NFT metadata (ERC721URIStorage standard)
      const metadata = {
        name: formData.name,
        description: formData.description,
        image: imageUrl, // IPFS image URI
      };

      // 3. Send the NFT minting transaction
      // contract.call("mintNFT", [recipientAddress, tokenURI])
      // The thirdweb SDK's mintTo function takes the metadata object directly
      const tx = await contract.erc721.mintTo(address, metadata);
      console.log("NFT minted successfully:", tx);
      alert("The NFT was minted successfully!");
      // Reset the form
      setFormData({ name: "", description: "", image: null });
    } catch (error) {
      console.error("NFT minting failed:", error);
      alert(`NFT minting failed: ${error.message}`);
    }
  };

  return (
    <div className="max-w-md mx-auto p-6 bg-white rounded-lg shadow-md">
      <h1 className="text-2xl font-bold mb-6 text-center">Mint an NFT</h1>

      <form className="space-y-4">
        <div>
          <label htmlFor="name" className="block text-sm font-medium text-gray-700 mb-1">NFT name</label>
          <input
            type="text"
            id="name"
            value={formData.name}
            onChange={(e) => setFormData({ ...formData, name: e.target.value })}
            className="w-full p-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500"
          />
        </div>

        <div>
          <label htmlFor="description" className="block text-sm font-medium text-gray-700 mb-1">Description</label>
          <textarea
            id="description"
            value={formData.description}
            onChange={(e) =>
              setFormData({ ...formData, description: e.target.value })
            }
            className="w-full p-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500"
            rows={3}
          />
        </div>

        <div>
          <label htmlFor="image" className="block text-sm font-medium text-gray-700 mb-1">Image file</label>
          <input
            type="file"
            id="image"
            accept="image/*"
            onChange={handleImageUpload}
            className="w-full p-2 border border-gray-300 rounded-md file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100"
          />
        </div>

        <Web3Button
          contractAddress="YOUR_NFT_CONTRACT_ADDRESS" // Change to the address of your actually deployed NFT contract
          action={mintNFT} // Function to run when the button is clicked
          className="w-full bg-blue-600 text-white py-2 px-4 rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2"
        >
          Mint NFT
        </Web3Button>
      </form>
    </div>
  );
}

💰 Implementing a Points System

This implements a system that awards and manages points based on user activity, using the ERC-20 token standard. What I learned building points, achievements, and level gamification in PEPEBear is that it’s easier to operate if you keep only “balance, awarding, and deducting” in the contract and put the rest of the logic off-chain.

1. ERC-20 point token contract (Solidity)

This issues an ERC-20 token that serves as points. It inherits Ownable to control minting permission.

// contracts/PointToken.sol
pragma solidity ^0.8.19;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

// The MyPointToken contract follows the ERC20 standard, and only the owner can mint tokens.
contract MyPointToken is ERC20, Ownable {
    // On deployment, set the token's name and symbol, and mint the initial supply to the owner.
    constructor() ERC20("MyPoint", "MPT") {
        _mint(msg.sender, 1000000 * (10**decimals())); // Initial supply of 1,000,000 MPT tokens
    }

    // Function that mints new tokens to the given address. Only the contract owner can call it.
    function mint(address to, uint256 amount) public onlyOwner {
        _mint(to, amount);
    }

    // Function that burns tokens. Token holders can only burn their own tokens.
    function burn(uint256 amount) public {
        _burn(msg.sender, amount);
    }
}

2. Point reward system contract (Solidity)

This implements the logic for users to earn points through specific activities (e.g., daily login) and redeem them for items.

// contracts/RewardSystem.sol
pragma solidity ^0.8.19;

import "./PointToken.sol"; // Import the PointToken contract defined above
import "@openzeppelin/contracts/access/Ownable.sol";

// The RewardSystem contract manages point tokens and pays out rewards.
contract RewardSystem is Ownable {
    MyPointToken public pointToken; // Address of the deployed point token contract

    mapping(address => uint256) public lastClaimTime; // Last reward claim time per user

    uint256 public dailyReward = 100 * (10**18); // Daily reward amount (100 MPT, 18 decimals)
    uint256 public constant CLAIM_INTERVAL = 24 hours; // Reward can be claimed every 24 hours

    // Define events
    event PointsEarned(address indexed user, uint256 amount, string activity);
    event PointsRedeemed(address indexed user, uint256 amount, string item);

    // Link the point token contract address when the contract is deployed.
    constructor(address _pointTokenAddress) {
        pointToken = MyPointToken(_pointTokenAddress);
    }

    // Function for a user to claim the daily reward
    function claimDailyReward() public {
        require(
            block.timestamp >= lastClaimTime[msg.sender] + CLAIM_INTERVAL,
            "Daily reward already claimed or not enough time has passed."
        );

        lastClaimTime[msg.sender] = block.timestamp; // Update the last claim time
        pointToken.mint(msg.sender, dailyReward); // Mint point tokens to the user

        emit PointsEarned(msg.sender, dailyReward, "Daily Login");
    }

    // Function for an admin to award points to a specific user (e.g., quest completion reward)
    function earnPoints(address user, uint256 amount, string memory activity)
        public onlyOwner // Only the contract owner can call it
    {
        pointToken.mint(user, amount);
        emit PointsEarned(user, amount, activity);
    }

    // Function for a user to spend points and redeem an item
    function redeemPoints(uint256 amount, string memory item)
        public
    {
        require(pointToken.balanceOf(msg.sender) >= amount, "Insufficient points"); // Check the point balance

        // Transfer point tokens from the user to the contract (burn or recycle)
        pointToken.transferFrom(msg.sender, address(this), amount);
        emit PointsRedeemed(msg.sender, amount, item);

        // Add the actual item delivery logic (e.g., minting an NFT, updating a database) here
    }
}

3. Points system React hook (Next.js)

This bundles point balance lookup, reward claiming, and point spending into a custom hook. When contract call logic is scattered across components, maintenance costs shoot up, so my rule is to gather on-chain interaction in one hook.

// hooks/usePoints.ts
import { useState, useEffect } from 'react';
import { useContract, useAddress, useContractRead } from '@thirdweb-dev/react';
import { ethers } from 'ethers';

export function usePoints() {
  const address = useAddress(); // Currently connected wallet address
  // Point token contract instance
  const { contract: pointContract } = useContract(
    process.env.NEXT_PUBLIC_POINT_TOKEN_ADDRESS
  );
  // Reward system contract instance
  const { contract: rewardContract } = useContract(
    process.env.NEXT_PUBLIC_REWARD_SYSTEM_ADDRESS
  );

  // Look up the user's point balance
  const {
    data: balance,
    isLoading: isBalanceLoading,
    refetch: refetchBalance
  } = useContractRead(pointContract, 'balanceOf', [address]);

  // Function to claim the daily reward
  const claimDailyReward = async () => {
    if (!rewardContract) throw new Error('Reward contract not loaded.');

    try {
      const tx = await rewardContract.call('claimDailyReward');
      await tx.wait(); // Wait until the transaction is included in a block
      await refetchBalance(); // Refresh the balance
      return tx;
    } catch (error) {
      console.error('Failed to claim daily reward:', error);
      throw error;
    }
  };

  // Function to spend points
  const redeemPoints = async (amount: string, item: string) => {
    if (!rewardContract) throw new Error('Reward contract not loaded.');

    try {
      // Call ERC-20 approve first (so RewardSystem can transfer tokens on the user's behalf)
      const approveTx = await pointContract.call('approve', [
        process.env.NEXT_PUBLIC_REWARD_SYSTEM_ADDRESS,
        ethers.utils.parseEther(amount)
      ]);
      await approveTx.wait();

      const redeemTx = await rewardContract.call('redeemPoints', [
        ethers.utils.parseEther(amount),
        item
      ]);
      await redeemTx.wait();
      await refetchBalance();
      return redeemTx;
    } catch (error) {
      console.error('Failed to spend points:', error);
      throw error;
    }
  };

  return {
    balance: balance ? ethers.utils.formatEther(balance) : '0', // Convert to a readable form
    isBalanceLoading,
    claimDailyReward,
    redeemPoints,
    refetchBalance
  };
}

4. Points dashboard component (Next.js)

This UI component shows the current point balance and provides daily reward claiming and point spending.

// components/PointsDashboard.tsx
import { useState } from "react";
import { usePoints } from "../hooks/usePoints"; // Import the custom hook defined above

export default function PointsDashboard() {
  const { balance, isBalanceLoading, claimDailyReward, redeemPoints } = usePoints();
  const [loading, setLoading] = useState(false);

  // Click handler for the daily reward claim button
  const handleClaimReward = async () => {
    setLoading(true);
    try {
      await claimDailyReward();
      alert("You received your daily reward!");
    } catch (error) {
      alert(`Failed to claim reward: ${error.message}`);
    } finally {
      setLoading(false);
    }
  };

  // Click handler for the point spending button
  const handleRedeem = async (amount: string, item: string) => {
    setLoading(true);
    try {
      await redeemPoints(amount, item);
      alert(`You successfully purchased ${item}!`);
    } catch (error) {
      alert(`Purchase failed: ${error.message}`);
    } finally {
      setLoading(false);
    }
  };

  if (isBalanceLoading) return <div className="text-center text-white">Loading point balance...</div>;

  return (
    <div className="bg-gradient-to-r from-purple-500 to-pink-500 rounded-lg p-6 text-white shadow-lg">
      <div className="text-center mb-6">
        <h2 className="text-2xl font-bold mb-2">My Points</h2>
        <div className="text-4xl font-bold">
          {balance} MPT
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <button
          onClick={handleClaimReward}
          disabled={loading} // Disable while loading or when no wallet is connected
          className="bg-white text-purple-500 font-semibold py-3 px-6 rounded-lg hover:bg-gray-100 disabled:opacity-50 transition-colors"
        >
          {loading ? "Processing..." : "Claim Daily Reward"}
        </button>

        <div className="space-y-2">
          <h3 className="font-semibold text-lg">Point Shop</h3>
          <button
            onClick={() => handleRedeem("50", "Special Badge")}
            disabled={loading || parseFloat(balance) < 50} // Disable when the balance is insufficient
            className="w-full bg-yellow-500 text-white py-2 px-4 rounded-md hover:bg-yellow-600 disabled:opacity-50 transition-colors"
          >
            Special Badge (50 MPT)
          </button>
          <button
            onClick={() => handleRedeem("100", "Premium Access")}
            disabled={loading || parseFloat(balance) < 100}
            className="w-full bg-green-500 text-white py-2 px-4 rounded-md hover:bg-green-600 disabled:opacity-50 transition-colors"
          >
            Premium Access (100 MPT)
          </button>
        </div>
      </div>
    </div>
  );
}

🛠️ Real-World Integration Example

This is an example that combines NFTs and the points system into a simple blockchain game platform. As the code comments also note, awarding points, which requires admin permission, must always go through the server (an API Route).

// pages/game.tsx
import { useState, useEffect } from "react";
import { useAddress } from "@thirdweb-dev/react";
import NFTCard from "../components/NFTCard";
import PointsDashboard from "../components/PointsDashboard";
import { usePoints } from "../hooks/usePoints";

export default function GamePlatform() {
  const address = useAddress();
  const [gameScore, setGameScore] = useState(0);
  const [nfts, setNfts] = useState<any[]>([]); // Adjust to the actual NFT data type
  const { earnPoints } = usePoints(); // Get the earnPoints function from the usePoints hook

  // Game play logic
  const playGame = async () => {
    const score = Math.floor(Math.random() * 100); // Random score between 0 and 99
    setGameScore(score);

    // Award points based on the score (requires contract owner permission)
    // In a real implementation, earnPoints must be called with the admin wallet through a backend API.
    let pointsToAward = 0;
    let activity = "Participation";

    if (score > 80) {
      pointsToAward = 50;
      activity = "High Score Achievement";
    } else if (score > 50) {
      pointsToAward = 20;
      activity = "Good Score";
    } else {
      pointsToAward = 10;
      activity = "Participation";
    }

    if (address && pointsToAward > 0) {
      try {
        // In reality, this part should be called from the server (admin permission required)
        // e.g.: await fetch('/api/earn-points', { method: 'POST', body: JSON.stringify({ userAddress: address, amount: pointsToAward, activity }) });
        // For now, this is an example that calls it directly from the client (for testing)
        // await earnPoints(address, pointsToAward.toString(), activity); // earnPoints in the usePoints hook is not for admins
        alert(`Game score: ${score}! You earned ${pointsToAward} points!`);
      } catch (error) {
        console.error("Failed to award points:", error);
        alert("Failed to award points.");
      }
    }
  };

  // Example NFT data (in reality, loaded from the contract)
  useEffect(() => {
    setNfts([
      { tokenId: "1", name: "Game Item #1", description: "A powerful sword", image: "/images/item1.png", owner: "0x..." },
      { tokenId: "2", name: "Game Item #2", description: "A magic shield", image: "/images/item2.png", owner: "0x..." },
    ]);
  }, []);

  return (
    <div className="container mx-auto px-4 py-8">
      <h1 className="text-3xl font-bold text-center mb-8 text-gray-800">
        Blockchain Game Platform
      </h1>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
        {/* Points dashboard */}
        <div className="lg:col-span-1">
          <PointsDashboard />
        </div>

        {/* Game area */}
        <div className="lg:col-span-2 bg-white rounded-lg shadow-lg p-6">
          <h2 className="text-xl font-semibold mb-4 text-gray-800">Mini Game</h2>

          <div className="text-center">
            <div className="text-2xl mb-4 text-gray-700">Score: {gameScore}</div>
            <button
              onClick={playGame}
              className="bg-blue-500 text-white px-6 py-3 rounded-lg hover:bg-blue-600 transition-colors"
            >
              Play
            </button>
          </div>
        </div>
      </div>

      {/* NFT gallery */}
      <div className="mt-12">
        <h2 className="text-2xl font-semibold mb-6 text-gray-800">Game Item NFTs</h2>
        <div className="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-4 gap-6">
          {nfts.map((nft, index) => (
            <NFTCard key={index} nft={nft} />
          ))}
        </div>
      </div>
    </div>
  );
}

🚀 Deployment and Operations Strategy

This covers the deployment and operations stages for getting the application you built in front of real users.

1. Deploying smart contracts

Use Hardhat scripts to deploy smart contracts to a testnet or mainnet. Deployment order has dependencies (RewardSystem needs the PointToken address), so bundling everything into one script reduces mistakes.

// scripts/deploy.js
const { ethers } = require('hardhat');

async function main() {
  // 1. Deploy the MyNFT contract
  const MyNFT = await ethers.getContractFactory('MyNFT');
  const myNFT = await MyNFT.deploy();
  await myNFT.deployed();
  console.log('MyNFT contract address:', myNFT.address);

  // 2. Deploy the MyPointToken contract
  const MyPointToken = await ethers.getContractFactory('MyPointToken');
  const myPointToken = await MyPointToken.deploy();
  await myPointToken.deployed();
  console.log('MyPointToken contract address:', myPointToken.address);

  // 3. Deploy the NFTMarketplace contract
  const NFTMarketplace = await ethers.getContractFactory('NFTMarketplace');
  const nftMarketplace = await NFTMarketplace.deploy();
  await nftMarketplace.deployed();
  console.log('NFTMarketplace contract address:', nftMarketplace.address);

  // 4. Deploy the RewardSystem contract (needs the MyPointToken address)
  const RewardSystem = await ethers.getContractFactory('RewardSystem');
  const rewardSystem = await RewardSystem.deploy(myPointToken.address); // Pass the point token contract address
  await rewardSystem.deployed();
  console.log('RewardSystem contract address:', rewardSystem.address);

  // Add the deployed contract addresses to .env.local for use in the Next.js app
  console.log('\n--- Add these to your .env.local ---');
  console.log(`NEXT_PUBLIC_NFT_CONTRACT_ADDRESS=${myNFT.address}`);
  console.log(
    `NEXT_PUBLIC_MARKETPLACE_CONTRACT_ADDRESS=${nftMarketplace.address}`
  );
  console.log(`NEXT_PUBLIC_POINT_TOKEN_ADDRESS=${myPointToken.address}`);
  console.log(`NEXT_PUBLIC_REWARD_SYSTEM_ADDRESS=${rewardSystem.address}`);
}

main()
  .then(() => process.exit(0))
  .catch((error) => {
    console.error(error);
    process.exit(1);
  });

2. Deploying the Next.js application (Vercel)

Deploy the Next.js application to Vercel. Contract addresses go in as environment variables, so the only thing to watch is managing environment variables per deployment environment (preview/production).

// vercel.json (optional: it's common to configure this directly in the Vercel dashboard)
{
  "build": {
    "env": {
      "NEXT_PUBLIC_ALCHEMY_API_KEY": "@alchemy_api_key",
      "NEXT_PUBLIC_THIRDWEB_CLIENT_ID": "@thirdweb_client_id",
      "NEXT_PUBLIC_NFT_CONTRACT_ADDRESS": "@nft_contract_address",
      "NEXT_PUBLIC_MARKETPLACE_CONTRACT_ADDRESS": "@marketplace_contract_address",
      "NEXT_PUBLIC_POINT_TOKEN_ADDRESS": "@point_token_address",
      "NEXT_PUBLIC_REWARD_SYSTEM_ADDRESS": "@reward_system_address"
    }
  }
}

3. Monitoring and analytics

Track user activity and contract interactions and use them to improve the service.

// utils/analytics.ts
// Integrate with a real analytics tool (e.g., Google Analytics, Mixpanel, Dune Analytics)

export const trackNFTMint = (tokenId: string, userAddress: string) => {
  console.log(`[Analytics] NFT mint: Token ${tokenId}, User ${userAddress}`);
  // sendToAnalyticsService("nft_mint", { tokenId, userAddress });
};

export const trackPointsEarned = (
  userAddress: string,
  amount: string,
  activity: string
) => {
  console.log(
    `[Analytics] Points earned: ${userAddress} - ${amount} MPT for ${activity}`
  );
  // sendToAnalyticsService("points_earned", { userAddress, amount, activity });
};

export const trackMarketplaceSale = (
  tokenId: string,
  price: string,
  buyerAddress: string
) => {
  console.log(
    `[Analytics] NFT sale: Token ${tokenId}, Price ${price} ETH, Buyer ${buyerAddress}`
  );
  // sendToAnalyticsService("marketplace_sale", { tokenId, price, buyerAddress });
};

📚 Additional Learning Resources and Practical Tips

  • thirdweb Docs: The most up-to-date material for Next.js and Web3 development.
  • OpenZeppelin Contracts Docs: Smart contract development standards and security best practices.
  • Hardhat Docs: Reference for Ethereum development environment setup and testing.
  • Ethers.js Docs: Documentation for the JavaScript library that interacts with the blockchain.
  • Next.js official docs: The official reference for the whole framework, including the App Router, caching, and deployment.

Practical tips

Checklist by development stage

  1. Local development: Iterate on development and testing quickly and at no cost on the Hardhat Network.
  2. Testnet deployment: Deploy to testnets such as Mumbai (Polygon) and Sepolia (Ethereum) to test in a real network environment and get feedback.
  3. Mainnet launch: Before deploying, go through a smart contract security audit and thorough testing. Once deployed, it cannot be undone.

Performance optimization (Next.js & Web3)

  • Turbopack Dev (Stable): Turbopack, stabilized in Next.js 15, greatly speeds up local dev server startup and updates.
  • Caching control: In Next.js 15, fetch requests, GET Route Handlers, and client navigation are not cached by default, so you can control caching behavior explicitly. This is especially useful for screens where freshness matters, like on-chain data.
  • React 19 support: You can optimize rendering performance with React 19’s new features such as the React Compiler.
  • Data caching: Cache blockchain data with swr or react-query to improve UI responsiveness. RPC calls are slow and expensive. Querying on every render without caching ruins the UX.
  • Server-side rendering (SSR) / static site generation (SSG): Pre-generate rarely changing blockchain data (e.g., NFT metadata) with SSG to get faster initial loads and better SEO.
  • Using API Routes: Handle sensitive transactions that require admin permission, such as minting, on the server through API Routes to eliminate the risk of exposing private keys.
  • Image optimization: Use the Next.js Image component to automatically optimize and lazy-load NFT images.
  • Improved TypeScript support: Next.js 15 offers faster type checking and better editor integration.
  • New debugging tools: Next.js 15’s debugging tools provide more detailed error messages and stack traces.

🎯 Wrapping Up

This setup, layering a contract toolchain on top of Next.js, is the default stack Toris reaches for repeatedly when building Web3-flavored products. Whether the chain is EVM or Solana, the frontend decisions from wallet connection through transaction UX haven’t changed much.

If you need to validate a Web3 idea, get in touch with Toris.

Advertisement