Git Product home page Git Product logo

reddit's Introduction

Important

This repository is referencing the mumbai chain.

Mumbai is deprecated since 08/04/2024, meaning the code in this repository will no longer work out of the box.

You can still use this repository, however you will have to switch any references to mumbai to another chain.

Reddit NFT Drop

Create a seamless user experience for onboarding web2 users into the NFT world, including:

  • Creating web3 wallets for users using their email address
  • Paying the gas fees for minting NFTs from an admin wallet
  • Deploying an NFT Drop onto the Polygon network.

For the full guide, check out our YouTube video

Using This Template

Create a copy of this template by running the following command:

npx thirdweb@latest create --template reddit

Set yourself up with a Magic.Link account, and create a new project.

Add your Magic Link public API key to the .env.local file:

NEXT_PUBLIC_MAGIC_PUBLISHABLE_KEY=YOUR_API_KEY=xxx

In this project, we use environment variables to store our private key (not recommended). Inside .env.local, add your private key:

PRIVATE_KEY=xxx

Guide

Below, we'll explore the key areas of this template.

Setting Up Magic Link Wallet Connector

We use Magic.Link to create a seamless user experience for onboarding web2 users into the NFT world.

In the _app.tsx page, we set up the Magic Link wallet connector in the ThirdwebProvider:

const magicLinkConnector = new MagicConnector({
  options: {
    apiKey: process.env.NEXT_PUBLIC_MAGIC_PUBLISHABLE_KEY!,
    rpcUrls: {
      [ChainId.Mumbai]: "https://mumbai.magic.io/rpc",
    },
  },
});

// This is the chainId your dApp will work on.
const activeChainId = ChainId.Mumbai;

function MyApp({ Component, pageProps }: AppProps) {
  return (
    <ThirdwebProvider
      desiredChainId={activeChainId}
      walletConnectors={[magicLinkConnector]}
    >
      <Component {...pageProps} />
    </ThirdwebProvider>
  );
}

Then, on the home page, we use the useMagic hook to allow users to connect with magic link:

const connectWithMagic = useMagic(); // Hook to connect with Magic Link.
const [email, setEmail] = useState<string>(""); // State to hold the email address the user entered.

With an input field to enter their email, and a button to connect with Magic Link:

<>
  <h2>Login With Email</h2>
  <div>
    <input
      type="email"
      placeholder="Your Email Address"
      onChange={(e) => setEmail(e.target.value)}
    />

    <button
      onClick={() => {
        connectWithMagic({ email });
      }}
    >
      Login
    </button>
  </div>
</>

Minting NFTs.

We mint NFTs from the NFT Drop from the admin wallet in an API route called mint-nft.ts.

This way, the user never accepts a transaction or needs to pay gas fees:

// Boilerplate Nextjs API route with TypeScript
import { ThirdwebSDK } from "@thirdweb-dev/sdk";
import type { NextApiRequest, NextApiResponse } from "next";

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  try {
    // 1. Grab the address from the request body
    const { address } = req.body;

    // 2. Let's instantiate the thirdweb SDK using our private key.
    const sdk = ThirdwebSDK.fromPrivateKey(
      // Learn more about securely accessing your private key:
      // https://portal.thirdweb.com/sdk/set-up-the-sdk/securing-your-private-key
      process.env.PRIVATE_KEY as string,
      "mumbai" // configure this to your network
    );

    // 2B. Let's connect to our smart contract using it's address
    const contractAddress = "0xBB1B8021e31Ac8A34ba5963e48f65d6a4B43aa42";
    const contract = await sdk.getContract(contractAddress, "nft-drop");

    // 3. Mint an NFT to the address from the NFT drop
    const transaction = await contract.claimTo(address as string, 1);

    // 4. Let's return the transaction info to the client.
    const metadata = (await transaction[0].data()).metadata;

    res.status(200).json(metadata);
  } catch (error) {
    console.log(error);
    res.status(500).json(error);
  }
}

We then call this API route on the UI when the user clicks the "Mint NFT" button on the index.tsx page:

// 1. Call the mint-nft API Route
const result = await fetch("/api/mint-nft", {
  method: "POST",
  body: JSON.stringify({ address }),
  headers: {
    "Content-Type": "application/json",
  },
});

We store the metadata of the NFT in the mintedNft state variable when it comes back from the API route:

const [mintedNft, setMintedNft] = useState<NFTMetadata | undefined>(undefined);

And display it on the UI:

<>
  <h2>You&apos;re Connected! ๐Ÿ‘‹</h2> <p>{address}</p>
  <button onClick={() => mintNft()} disabled={loading}>
    {loading ? "Loading..." : "Mint NFT"}
  </button>
  {loading && <p>Loading...</p>}
  {/* Show the minted NFT when it comes back */}
  {mintedNft && (
    <div>
      <h3>Your Minted NFT</h3>
      <ThirdwebNftMedia
        metadata={mintedNft}
        style={{
          width: 300,
        }}
      />
      <p>{mintedNft.name}</p>
    </div>
  )}
</>

Got Questions?

Join our Discord to speak with our team directly.

reddit's People

Contributors

jarrodwatts avatar jnsdls avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.