Building an NFT Lottery: Step-by-Step Guide for Creating a Smart Contract and Frontend
Published: 2023-04-04 09:01:59



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: Develop 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:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/opnowi5bq3qa8y8ctdso.png)

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.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2bek2kp7af8mrtqc0duj.png)
We also need to create a function for users to buy a ticket for the NFT lottery.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xjh6q6smdm7ophdlhjjq.png)

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.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kv9cqdv373mc2tcs4njd.png)
Putting everything together here final smart contract:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j3ctam8g0eewnljo3jif.png)

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:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pmn0rwn7x9cvfu42lqs4.png)

2.2. 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.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/45xap1ycx5j52qzl358z.png)
2.3. Add your Private Testnet to your MetaMask wallet by using the “Add to Metamask” button:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6ha5sdsejdh37giz96dk.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cj3c98lprxr6czlorf3f.png)

**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.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/apo7m1t5sq9gx6fuzqx0.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u47aa3w18ent9n9l4llj.png)
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:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yxg8zig9pjgr657bg1po.png)

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:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/parh8ctsbfcfk6rwu0i2.png)

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:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/65lc5g6bddel5r5slpyb.png)

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:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/chugi9dymmw49qj2891g.png)

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.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fdiq010iyeeq9901a83s.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8iquhqjhro5i64qv1fs0.png)

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:


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5b3szrxc9113psc5ing5.png)
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**

1. **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.
2.** 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.
3. **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.
4. **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.
5. **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.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i12hewfduby75n7t7053.png)

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.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s2yooft47ke0qfv6mq7k.png)

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.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m1uc26kobqhokc977l4w.png)

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

`npx run dev`
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/df8bc0j3roh85t1lupqa.png)

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](https://twitter.com/_BuildBear), and [LinkedIn](https://www.linkedin.com/company/build-bear/) and Join the [Telegram](https://t.me/+6mjOnBFUR9xjN2U1) group if you haven’t done yet.


**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](https://buildbear.io/) aims to build an ecosystem of tools for testing dApps at scale for the teams.

Read our past articles and keep learning :

[Learn how to Create, Deploy an NFT Smart Contract and Develop a Front End App in 15mins](https://medium.com/buildbear/learn-how-to-create-deploy-an-nft-smart-contract-and-develop-a-front-end-app-in-15mins-a7d9c2a16237)
[Learn how to create, Deploy a Soul Bound Token(SBT)](https://medium.com/buildbear/find-out-what-is-sbt-auth-and-learn-to-create-your-own-system-12c5f65e40b7)
[Generate NFT with AI and Deploy the NFT smart contract, and the Front End App](https://medium.com/buildbear/generate-nft-with-ai-and-deploy-the-nft-smart-contract-and-the-front-end-app-94c64a93d8b1)
[Learn, code, and deploy your own MultiSig Wallet](https://medium.com/buildbear/learn-code-and-deploy-your-own-multisig-wallet-and-test-it-with-your-friends-now-cb86cdcb8c8)
[Let’s understand Subscription NFTs and mint a few](https://medium.com/buildbear/lets-understand-subscription-nfts-and-mint-a-few-6ae9e695a1fc)
Authors: [Chandan](https://twitter.com/chandan1_)