Demystifying Web3 - My Notes

April 18, 2024

10 min

Last November, I dove headfirst into the exciting world of Web3 at a bootcamp. Over a few intense weeks, able to developed an NFT marketplace using Next.js. It was a rollercoaster of code, concepts, and caffeine. Here's what I learned, along with a sprinkle of blockchain basics.

What is Blockchain Anyway?

Picture a magic notebook that records transactions and stores them across thousands of computers worldwide. This is the blockchain. Every page in this notebook is a "block," and they're linked in a chain (hence the name). The beauty of blockchain is its transparency and security: once a transaction is recorded, it's there for good. Say goodbye to shady edits and hello to trustless systems!

Sooo, by definition:

The blockchain is a distributed and decentralized ledger that stores data such as transactions, and that is publicly shared across all the nodes of its network.

chain

What is NFT You May Ask?

NFT stands for ‘non-fungible token’. Non-fungible means that something is unique and can’t be replaced. By contrast, physical money and cryptocurrencies are fungible, which means they can be traded or exchanged for one another. Every NFT contains a digital signature which makes each one unique. NFTs are digital assets and could be photos, videos, audio files, or another digital format. NFT examples include artwork, comic books, sports collectibles, trading cards, games and more.

And There is a Token and Test Token?

A token is a unit of value on a blockchain that relies on an existing cryptocurrency's blockchain and represents its equity. Tokens can be bought and sold, and they are often used in fundraising through ICOs (Initial Coin Offerings), similar to IPOs (Initial Public Offerings) for companies. Just as a central bank's currency represents the state's existence, tokens correspond to the value of the cryptocurrency they represent.

A test token is a non-monetary digital asset used in the development and testing phases of blockchain projects. Unlike regular tokens, test tokens have no real value and are utilized in test networks (testnets) to allow developers to experiment with applications and smart contracts without financial risk. They help ensure the functionality and security of projects before launching on the main network.

In decentralized applications, not just CHZ, test tokens play a crucial role in the development and optimization stages of new applications and platforms. In this bootcamp, we are utilizing test tokens in the CHZ blockchain's testnet, we can simulate trading scenarios, auction dynamics, and smart contract executions for our NFT marketplace.

Wallets: Your Gateway to the Blockchain

A wallet is like your digital keyring. It stores your private keys the magic codes that prove you own stuff on the blockchain. You'll need one to interact with any Web3 application. During the camp, we worked a lot with MetaMask, a popular browser extension wallet, and we also worked a lot with thirdweb, a powerful platform for building Web3 applications. Connecting it to our marketplace was surprisingly simple:

  1. Install MetaMask: Download it as a browser extension or mobile app.

  2. Set Up Your Wallet: Create a password and note down your seed phrase (never share it!).

  3. Connect to Your App: use thirdweb to let your app talk to the wallet.

Here's how we connected a wallet:

  • Install thirdweb: Add the necessary package to your project.

    npm install @thirdweb-dev/react
    
  • Set Up the Provider: Wrap your app with ThirdwebProvider to enable wallet connections.

    import "@/styles/globals.css";
    import type { AppProps } from "next/app";
    import { ThirdwebProvider, metamaskWallet } from "@thirdweb-dev/react";
    import { SpicyChain } from "@thirdweb-dev/chains";
    
    export default function App({ Component, pageProps }: AppProps) {
      return (
        <ThirdwebProvider
          activeChain={SpicyChain}
          clientId={process.env.NEXT_PUBLIC_CLIENT_ID}
          supportedWallets={[metamaskWallet()]}
        >
          <Component {...pageProps} />
        </ThirdwebProvider>
      );
    }
    
  • Connect the Wallet: Use the useMetamask hook to allow users to connect their wallets.

    import { useMetamask, useAddress } from "@thirdweb-dev/react";
    
    function ConnectWalletButton() {
      const connectWithMetamask = useMetamask();
      const address = useAddress();
    
      return (
        <div>
          {address ? (
            <div>Connected wallet: {address}</div>
          ) : (
            <button onClick={connectWithMetamask}>Connect Wallet</button>
          )}
        </div>
      );
    }
    
    export default ConnectWalletButton;
    

See, With just these steps, users could connect their wallets and start interacting with the blockchain seamlessly.

Smart Contracts: The Brains of the Blockchain

Think of a smart contract as a vending machine. You insert a coin, and it gives you a snack---no human needed. In the blockchain world, smart contracts are self-executing programs that run when specific conditions are met.

For our NFT marketplace, we deployed a contract on Thirdweb that handled:

  • Minting NFTs: Creating new tokens for users.
  • Listing NFTs for Sale: Setting a price and putting items on the marketplace.
  • Transferring Ownership: Automatically updating who owns what.

Here's a simple example of a smart contract that you've deployed on Thirdweb websites for minting an NFT:

const handleSubmit = async (event: React.FormEvent) => {
        try {
            event.preventDefault();

            if (name === "" || description === "" || image === "") {
                return;
            }

            const metadata: MintMetadata = {
                metadata: {
                    name,
                    description,
                    image,
                },
                to: address ?? "",
                supply: 1,
            };

            mintNFT(metadata);
        } catch (e) {
            console.log("Error Minting", e);
        }
    };

Deploying this contract felt like magic and seeing it work in our app? Pure joy.

The Building Process

Populate the .env.local file with the necessary environment variables. These are crucial for linking the application with your specific resources on Thirdweb. Below is a list of the required variables:

  • NEXT_PUBLIC_CLIENT_ID: Your unique client identifier from Thirdweb. You can find this by logging into your account, navigating to "Settings," then "API Keys," and selecting your key to view the clientID.
  • NEXT_PUBLIC_NETWORK: "SpicyChain"
  • NEXT_PUBLIC_NFT_CONTRACT_ADDRESS: The address corresponding to your smart contract.
  • NEXT_PUBLIC_MARKET_CONTRACT_ADDRESS: The address corresponding to your smart contract.

Lessons Learned

  • Expect Errors: Debugging Web3 apps is like solving a Rubik's Cube in the dark. Errors can come from the frontend, the wallet, or the blockchain itself.
  • Gas Fees Are Real: Every blockchain transaction costs gas, a fee paid to miners. Watching our CHZ drain away on the testnet was both funny and painful.
  • The Community Rocks: Web3 developers are some of the most helpful people around. Stack Overflow, Discord, and Twitter became our best friends.