Building an NFT Lottery: Step-by-Step Guide for Creating a Smart Contract and Frontend

·

7 min read

In this tutorial, we will learn how to create an NFT lottery smart contract along with a front-end to let the user buy the tickets.

Step 1: Developing the NFT lottery Smart Contract

To create the smart contract, we need to define a few common properties of the lotteries, such as start_time, end_time, ticket price, and the contract address and tokenId of the NFT. We can store these details as follows:

We then need to create a function for users to start a lottery. This function should take the user’s NFT address, start and end times, and ticket price, and transfer the NFT from the user to the lottery contract. as follows.

We also need to create a function for users to buy a ticket for the NFT lottery.

Since blockchains are not self-executing, we need to create a function to end the lottery. We first check that we have reached the end time for the lottery, then use a random function to generate a number to determine the winner of the NFT. The NFT is then transferred to the winner, and the creator of the lottery receives the total payout that is paid by the participants.

Putting everything together here final smart contract:

For any smart contract to receive NFTs, it has to inherit the ERC712Holder.sol contract as shown above.

Step 2: Getting up the infra needed to deploy and test our smart contract

Most commonly public Testnet such as the Goreli, and Sepolia Testnet are used for projects. However, we will be using Buildbear to create our own Testnet, as one of our users recently shared their win at EthDenver using BuildBear. You can read their article here

2.1. Visit the BuildBear App. Once you login with your Github or Google Account, you will see a page similar to the image added below:

2.3. Create your private node forking from the Ethereum Mainnet, feel free to fork any Chain where you own an NFT so that we don’t need to redeploy any NFT smart contract while creating a lottery.

2.4. Add your Private Testnet to your MetaMask wallet by using the “Add to Metamask” button:

2.5. Click on Open Faucet you will be redirected to Faucet Pages, and then Mint native Tokens to pay for gas for the transactions.

Step 3: Deploying the Smart Contract

For contract deployment, we will be using Remix.

3.1. Navigate to the Remix Online IDE website and accept the terms and conditions.

3.2. Create a new contract and paste the Smart Contract Code, available over here 👉 GitHub Link

3.3. Compile the Smart Contract.

Please note that the ABI of the Contract is available only once the Contract is compiled. You can see in the above image the ABI which can be copied. Please keep this handy. We will need it momentarily.

3.4. Select the “Deploy and Run Transactions” tab: and deploy the contract as follows:

  • Make sure that you update the Environment to “Injected provider — MetaMask” | CRITICAL,

3.5. Click on the “transact” button to deploy the contract to your private node network; once done, you will see something similar to the following:

3.6. Copy the address of the Contract and visit the Blockchain Explorer for your personal forked Testnet (link available on the dashboard page at home.buildbear.io) and locate your contract.

3.6.1. Submitting the ABI of the contract for ease of interaction

You can visit your contract page on BuildBear’s Blockchain Explorer and then visit the Contract tab. You should see something similar to the following:

Submit the ABI that we copied from Step 3.3; once done, you should see the Read and Write Contract buttons made available to you on the Contract Page:

WOOT WOOT 🎉 🎉

Let’s create a lottery

Move to the Write contract section and connect your wallet, enter the details lottery id, start time, end time, (Use https://www.epochconverter.com/ to get in the epoch time)NFT contract address, NFT ID, and ticket price. and click on write.

After the transaction is successful move to the Read contract section and enter your lottery Id to see the Lottery details.

Let’s move to the front-end development. we will be using Next.js

Step 4: Next.js App

Installation and Setup

The easiest way to create a new Next.js application is by using the create-next-app CLI tool. You can install it via npm:

$ npm install create-next-app

Once installed, you can initialize a new Next.js application by calling the tool and supplying a name for your project:

$ npx create-next-app nft-app

Note: If you don’t already have create-next-app installed - npx will prompt you to install it automatically.

Once the tool finished initializing a skeleton project, let’s move to the directory and take a peek inside:

The standard package.json, package-lock.json and node_modules are there, however, we've also got the /pages, /public and /styles directories, as well as a next.config.js file!

Let’s take a look at what these are.

Features of Next.js

Next.js is ultimately an extension for React, and it does introduce a couple of new things that make React application development simpler and faster — starting with Next.js pages.

Pages

Next.js makes creating multi-page applications with React ridiculously easy with its default file-system-based router. You don’t need to install any additional packages, such as react-router-dom, or configure a router at all.

All Next.js projects include a default /pages directory, which is the home of all of the React components you'll be using. For each component - a router will serve a page based on that component.

Next.js project setup is done

Step 5: Connecting our application with the blockchain and UI

we need something that connects our client to one of these nodes of blockchain so they can start using the full power of the blockchain, that’s exactly what ether.js is it’s a library written in javascript that lets as create any javascript application that talks to the blockchain so we can use and create many applications which are going to be based on decentralized application (daps). It’s the bridge that essentially that takes your client and it allows it to connect to the blockchain.

Ether.js Modules

  • Ether.js consists of some important modules that can be used to interact with blockchain nodes easily, and get the transaction data as required. To get started with the modules of Ehter.js, let’s take an overview of all the Ether.js modules.

  • Ethers.Provider: In this module it lets you initialize a connection with the Ethereum blockchain, and it provides you the features to issue queries and send signed transactions. Managing the state of the blockchain is also possible through this module.

  • Ethers.Contract: In this module, you can deploy and interact with smart contracts, during the deployment part of smart contracts and to make it successful is part of Ethers.Contract module. It also offers some unique packs of functions that let the developer “listen” to smart contract events and after listening to the contracts you can also get information about them.

  • Ethers.Utils: This module lets you process the user data inputs and format them according to your requirements. Ether. utils make it easy to build decentralized applications.

  • Ethers.Wallet: As the name suggests it provides a way to connect to any co-existing Ethereum address to a proper wallet. It also has important features like it lets you create new wallets and also make sign transactions too.

Installing

npm install --save ethers

Let’s Create a Connectwallet function that connects our application with Metmask wallet. This checks if the wallet is installed if so then MetaMask will pop up to connect.

Our focus will not be on elaborate UI design, instead, we will utilize simple HTML to present Lottery details and enable users to purchase tickets as shown below.

To facilitate ticket purchases, we will utilize the following code. By using the ethers.contract as previously described, we can interact with the contract and initiate the participate function with the required amount of Ether for the ticket price. To execute this function, the User simply has to click the buy button.

Start the Website by running the cmd npx run dev in Your Terminal.

npx run dev

We have successfully built the NFT Lottery!!! 🎉🎉🎉

Share your project on Twitter and LinkedIn as tag BuildBear.

If you appreciate what we are doing, please follow us on Twitter, and LinkedIn and Join the Telegram group if you haven’t done yet.

And please give us a clap 👏 if you like our work.

About BuildBear:

BuildBear is a platform for testing dApps at scale, for teams. It provides users with their own private Testnet to test their smart contracts and dApps, which can be forked from any EVM chain. It also provides a Faucet, Explorer, and RPC for testing purposes.

BuildBear aims to build an ecosystem of tools for testing dApps at scale for the teams.

Create your Private and Customized Testnet with BuildBear

Authors: Chandan,