Building NFT Apps to Collect and Generate NFTs From IoT Data

Data is collected using an ADXL345 accelerometer interfacing a RaspberryPi 4 and transmitted over a socket session using the socketio library for Python on the client side and Javascript on the server side. The server receives the data and uploads it to the Inter Planetary File System, from which a content ID (hash of the data) is returned, triggering a call to the NFT Smart Contract. The NFT smart contract subsequently mints (creates) an NFT record of the data, rendering the reference image (NFT) to the frontend GUI. The NFT application comprises a WebApp using React on the frontend and Node.js on the backend. The goal of this project was to implement a full stack IoT system with the added features of web3 integration to prove Data Ownership and Traceability.

Points to note:

  • Initial development can be seen on the Master Branch, however moved the project to main for further development after deciding to leverage the starter kit
  • Source Code for the IoT component (RPi and ADXL345) can be found in the /src/backend/iotcomponent/* directory

Libraries, Modules & Dependencies

  • Hardhat local testnet
  • react-router-dom@6 (for routing between pages in the app)
  • ipfs-http-client@56.0.1
  • @openzeppelin/contracts@4.5.0 library
  • ethers library
  • react.js
  • node.js
  • express
  • cors
  • nodemon
  • socket.io

Testing

Smart Contracts Testing

  • A key consideration in the development of this project was the integrtiy and stability of the smart contracts. Smart contract live on the blockchain. This means that once deployed, they cannot be changed. As a result, extensive testing of transaction scenarios was carried out to ensure the rigidity of the contracts. These are described in /test/NFTMarketplace.test.js.
  • Tests

Harhat framework allows for writing tests for contracts during development. The script was written using the Waffle testing framework. The framework allows us to test scenarios using 3 key declarations; Should, Expect, Assert. A beforeEach hook ensures the neccessary data is gathered prior to running tests!

  1. NFT/Marketplace deployment Verify that post deployment, the NFT contract will successfully track the 'Name' and 'Symbol' of an NFT collection and the Marketplace contract will successfully track the pre-defined 'Fee Account' and 'Fee Percentage'. The test "pass" criteria is defined using an 'expect' statement from the chai library.
  • Pass:
    • The deployed NFT name should equal ("IoT-NFT Dapp") - custom name set for the NFT collection
    • The deployed NFT symbol should equal ("IOTD") - custom symbol set for the NFT collection
    • The marketplace fee account should equal the deployers address
    • The marketplace fee percentage should equal the fee percent passed in code (1)
  1. NFT (Create) Mint function

To test that the mint function works correctly (ie. that an NFT record will be successfully created and stored from the data). A user account and NFT metadata URI (could be for an image/iot data or other) is passed and a test NFT created.

  • Pass:
    • The number of tokens should now be 1 (ie. After 1 token is minted, there is now 1 token in circulation)
    • The number of NFT tokens at the buyers address should now be 1
    • The NFT token URI is equal to the URI passed to the test
    • A second buyer should increase the tokenCount() to 2
  1. Marketplace Create Items function Verify that a user can create nft from their uploaded data using the mint function , followed by listing the minted NFT on the marketplace for buyers to purchase. Listing an NFT requires the seller to transfer ownership of the NFT to the marketplace. Therefore the function should be robust against errors in transferring the NFT. For the seller and also subsequently for incorrect (buyers). To test this, addr1 mints an nft and offers their nft at a price of 1 ether by calling the makeItem function. The function should Successfully track a newly created item by making an NFT with makeItem, Emit an offered event once the NFT has been created, and successfully transfer ownership of the NFT from seller to marketplace.

Pass:

  • An offered event should be emitted
  • NFT owner attribute should equal marketplace address
  • The itemCount on the marketplace should equal (1)
  • All mappings of the NFT attributes on the marketplace (id, price, address etc.) should equal the expected NFT attributes to indicate a successful mapping fof data

Fail:

  • Additional fail test here, checks that the price is not set at 0 - ie. no free transfers are possible. This is tested by passing a price of zero to the makeItem function and expecting an error message.
  1. NFT Purchase function To test the purchase capability, the test script connects a user account to mint an nft record. It then approves spend of NFT on the marketplace (ie. sends to marketplace), followed by calling the makeItem function to list the NFT on the marketplace. It expects a user account to connect and purchase an NFT, the marketplace contract should emit a bought event with arguments in the nft mappings struct updated appropriately.
  • Pass:
    • Function will check the log following bough event to confirm mappings have been updated ie. same itemId, nft address, price, seller and buyer adresses match up
    • The sellers final eth balance is equal to the price of the total price of NFT + the sellers initial eth balance

Project Log

18/July

  • Install dependencies
  • Launch the starter pack (react server) with 'npm run start' (opens basic html index page)
  • Create Smart Contract (mkdir contracts/NFT.sol)
  • NOTE: import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol" requires you to open the project in Root folder
  • Deploy the NFT contract on local blockchain 'npx hardhat run src/backend/scripts/deploy.js --network localhost'
  • Created NFT Transfer contract (Marketplace)
  • Deployed and tested on the blockchain (hardhat as above)

** NOTE: Failed to run tests/deployments because hardhat wasn't running. Resolved by running 'npm hardhat node' in the terminal and then running the deployment command in a new terminal. Node also needs to be running.

image.png

  • Created testing scripts for smart contract testing (hardhat framework lets us write tests for these)
  • Tested contracts using 'npx hardhat test' - Passed!!

image.png

  • Contracts Test 2 failing on 'npx hardhat test' (TypeError: nft.tokenCount is not a function)
  • TokenCount() function is not listed in the contract (this may be due to an update so removing that reuqirement in the test)

21/07/22 - update deploy contracts

  • Testing Deployment, Minting and CreateItems contract functions. Passed! image.png

02/08/2022

  • Created purchase item function
  • Implemented purchase function test script - failure due to price discrepencies ** NEED TO REVIEW THIS ^ before deploying the Smart Contract to the blockchain
  • After deploying the contracts to the Blockchain, meta files are stored in '/frontend/components/contractsData/' to be imported into App.js later

03/08/2022

  • Front end improvements
  • Connected hardhat node dev net to metamask wallet ** 1. Set up connection to the blockchain with ethers library - improvement ** 2. Load contracts form the blockchain

07/08/2022

  • Connect app to wallet --> hardhat chain (import { ethers } from "ethers")
  • web4handler function to manafe metamask connections
  • Create navbar component for the front end app
  • Created pages for each nav component : Home, Create, MyListedItem, MyPurchases
  • Build out home page and markeplace interface with marketplace Load and Buy functions*
  • TESTING - Connecting to Metamask failing -- need to debug
  • Happy with front end look though, massive step up in UX design (more simplified, way nicer to view)

08/08/2022

  • Connect Wallet functionality fixed. Typo in the code calling the wrong function (rookie mistake)
  • Built out the Create page with a data upload form for NFT metadata
    • tested using a simple image for upload
    • Getting caught on the makeItem() function in the marketplace contract
    • Everything else works well so far

10/08/2022

  • Parked front end and NFT/Blockchain application to build out the IoT system
  • Components used are ADXL345 accelerometer and Raspberry Pi 4
  • Libraries and dependencies;
    • WiringPi
    • npm i ws (node.js websocket package) (not working )
  • GOAL:
  • GUI-Connect opens a socket connection (listening***)
  • RPi opens a client connection and connects to the listening port
  • RPi gathers and sends accelerometer data as payload to the server - displays the data for the user
  • The user proceeds to upload the data with an image to IPFS to mint the NFT

11/08/2022

  • Install express, cors nodemon and socket.io libraries
  • Implemented socket.io client (App.js) and backend server (Receiver - index.js)
  • The server will listen for incoming messages (connections) and take in the message/object
  • It will then render the received data to useState variables on the front end
  • Working with simple "Hello Messages" - need to pass objects now

13/08/2022

  • Implement iotclient on the Raspberry pi
    • The IoT client is a socket.io client that interfaces the adxl345 on the backend and passes data over http to the webservice (NFT Application)
  • Libraries and dependencies
    • pip3 install "python-socketio[client]"
    • pip3 install "python-socketio[asyncio_client]"
  • Successfull implementation of client/server system between the RPi and Application backend server
  • The RPi sends a basic payload to the server and waits for a received event

14/08/2022

  • Ineterface ADXL345 to RPi4 and begin collecting data
  • Accessing the device via SMbus protocol over the I2C interface on the raspberry pi
  • Dependencies
    • install cffi on the RPi to call C code using Python (pip install cffi)
    • install smbus via cffi (pip install smbus-cffi)
  • Pin setup
    • Pin1 3.3v -to- ADXL345 Vcc
    • Pin3 I2C SDA -to- ADXL345 SDA
    • Pin5 I2C SCL -to- ADXL345 SCL
    • Pin6 GND -to- ADXL345 GND
  • Client (RPi) successfully gather data and sending JSON loads to the Server
  • TO DO: Render the received data on the server side to the upload page in the frontend web app ******
  • SUCCESS - Test and confirmed the following;
    •  
      1. Start the server (index.js) - server is listening
    •  
      1. Start the App - the frontend page loads
      2. The user connects to backend (automatic when the server starts)
      3. The user connects his wallet
    •  
      1. The iot client (RPI) starts and sends a connect request to the server
      2. On receipt of connection request;
        • The iot client calls the timeout function which triggers the ADXL345
        • When the treshold is reached, data gathered from the ADXL345 is written to a file, serialized and sent over socket connection to the server
    •  
      1. When the Server receives the message;
      2. It sends a broacast message to indicate to the front end that a file was received
      3. The frontend (App.js) renders the file object and stores in state variable 'file'
      4. The front end Alerts to say the file is received!

NEXT: Need to pass the file to the upload field in the create form This starts the NFT creation mechanism of the system

* Successfully rendering the fileobject to dropdown on Create.js page
* Issue calling the upload to IPFS function on the object

17/08/2022

  • Completed frontend application by adding two pages for lised items and purchased items
  • Carried out testing on IoT component and Frontend application components.
  • Errors in Creating and rendering the NFT from the data - to be reviewed and tested again tomorrow

Credits:

DAPP University Open Source Blockchain Starter kit developed by Ethan-Crypto leveraged as a starting point for the project on NFT side. The code can be found here: https://github.com/dappuniversity/starter_kit_2/tree/c7557aa2518c4338f1562abe3afd03ae244d42ef

Smart contract guidelines and templates used from Openzeppelin.com: https://docs.openzeppelin.com/contracts/3.x/erc721

DAPP university bootcamp for blockchain development was excellent for learning the ins and outs of blockchain/NFT development. Tutorials and Bootcamps can be found here: https://www.dappuniversity.com/bootcamp

Download details:

Author: cconn8
Source code: https://github.com/cconn8/NFT-Project

#solidity #smartcontract #blockchain #web3 #iot #nft #javascript #python

Building NFT Apps to Collect and Generate NFTs From IoT Data

TOP 16 NFT Marketplace React Templates

NFT React Templates

Non-fungible tokens (NFTs) may appear to be a fad.Developing an NFT marketplace website could be the most efficient way of assisting various clusters of people in the buying and selling of digital art tokens.

We’ve carefully handpicked 16 of the Best NFT Marketplace React Templates from the internet to offer you a head start.

1.NFT WorkSea - Full NFT Marketplcae with React & Solidity

Our item is a Full NFT Marketplace built with smart contracts (Solidity, Web3, IPFS and React js) powered by Ethereum, it can be deployed on any ETH chain like Polygon, Binance Smart Chain. It is full NFT platform with High quality front-end and Clean code in the Backend, where each user can mint his own NFT and expose it on a marketplace which work like Opensea and rarible.

Code-2022-20-15-51

View Demo | Download Source

2.Nuron - NFT React Template

Meet Nuron, a fully-featured React Next JS template for NFT Marketplace, We just released the fully coded version in latest React Next JS

Nuron is suitable for NFT marketplace, digital marketplace, crypto collectibles, NFT world buying selling, digital art, crypto art, DeFi website and non-fungible tokens.

Code-2022-26-28-02

View Demo | Download Source

3.Axies - NFT Marketplace React Js Template

This is the React Js Template, only provide front-end React Js interface NO back-end for NFT Marketplace traders and creators. With 08 Home Page styles, 04 types item, Item detail, Live Auctions, Connect Wallet, Create Item, Edit Profile, Ranking, Login, Signup, FAQ, Activity

Code-2022-26-19-29

View Demo | Download Source

4.Gigaland - NFT Marketplace React Js Template

Gigaland is a responsive, pixel-perfect, and the most complete React template for NFTS marketplace, crypto-collectibles, digital items, non-fungible tokens websites, and more. Gigaland has a lot of styles and elements to help you make beauty and modern website in no time. Gigaland is built with latest technologies like Bootstrap 5.

Code-2022-26-21-07

View Demo | Download Source

5.Ciscryp - NFT Marketplace React Template

Ciscryp | NFT Marketplace React Template – a responsive React template theme with NFT Marketplace and NFTs Store. Ciscryp is built by the latest React typescript and tailwindcss.

Code-2022-26-22-35

View Demo | Download Source

6.NFTMAK - NFT Marketplace React JS Template

NFTMAK is an NFT Marketplace where you can display your NFT arts. NFTMAK comes with a unique and awesome design, It has one premade beautiful Home page design as well as 14 inner pages. It’s suitable for digital items, digital marketplace, crypto-collectibles, and non-fungible tokens. So, build whatever you want to build with this.

Code-2022-26-23-48

View Demo | Download Source

7.Unitar - React NFT Marketplace Template

Unitar – React JS NFT Marketplace TemplateToday we want to share a design, a topic that is not known to everyone. NFT is a “non-fungible token”, a new method of payment on the Internet using electronic currency. Each of the NFTs is unique and exists in a single copy, it cannot be divided, and all information about its author, buyer and all transactions with it is securely stored in the blockchain.

Code-2022-26-25-06

View Demo | Download Source

8.NafLab - NFT Marketplace React Template

NafLab is an React template for the modern crypto art market which is made with modern features and technologies. It will be used for buying, selling various types of digital art products by using the NFT method. It will help people to get more familiar with the NFT and transection the products with the digital currency.

Code-2022-26-27-36

View Demo | Download Source

9.Netstorm - React NFT Marketplace

Netstorm – React NFT Marketplace Template is a new method of payment on the Internet using electronic currency. Each of the NFTs is unique and exists in a single copy, it cannot be divided and all information about its author, buyer and all transactions with it is securely stored in the blockchain. Netstorm is a dedicated React Template for NFTs shops and NFT assets stores, crypto Art markets and for Digital assets biding websites. It is very nicely designed with modern features & coded with the latest technology.

Code-2022-26-29-04

View Demo | Download Source

10.Gible - React Next NFT Marketplace Template

Gible is a clean modern React Next template for NFT Crypto Art Digital Assets Marketplace website. It is built with ReactJS, Next.js, Strapi CMS, PostgreSQL, Bootstrap, and without any jQuery dependencies! This template is suitable for NFT marketplace, collectibles, NFT world buying selling, crypto art, digital art, and DeFi website.

Code-2022-26-30-36

View Demo | Download Source

11.Cryptoki - React Template for Digital and NFT Marketplace

We designed Cryptoki so you can have everything you need to build your own NFT market or digital shop. From several versions of products and bids, product views, profiles, contact, complete profile pages, item pages, and much more.

Code-2022-26-33-02

View Demo | Download Source

12.Nift - React NFT Marketplace

Nift – React NFT Marketplace Is perfectly build for NFT buy & Sell. This is a Responsive REACT Template and ready to use for your NFT Platform.

Code-2022-26-15-24

View Demo | Download Source

13.Funto - React NFT Marketplace

It’s crafted with the latest trend of design & code with all modern approaches. It’s SEO-friendly, easy to customize, robust & multi-dimensional NFT marketplace React JS template.

Code-2022-26-16-59

View Demo | Download Source

14.IUC - NFT Marketplace React Template

IUC (Iconic Ultimate Crypto) , a next-generation modern and clean & flat Design, It is fully responsive.

Code-2022-26-26-17

View Demo | Download Source

15.OenSky -NFT Marketplace Nextjs Template

OpenSky -NFT Marketplace Next js Web Template

Code-2022-20-17-24

View Demo | Download Source

16.Raroin - NFT Marketplace React Js Template

Raroin is a React Js NFT Marketplace Platform template. It’s come with a creative design, three home page options, different explore and digital asset pages and items. It’s suitable for virtual items, digital marketplace, crypto-collectibles, and non-fungible tokens. So, build whatever you like with this.

Code-2022-26-30-57

View Demo  | Download Source


Source: https://reactjsexample.com/

#nft #react-native 

TOP 16 NFT Marketplace React Templates
Maryjane  Olson

Maryjane Olson

1660470900

Digital Asset Ownership and Transfer using NFT and Hyperledger

NFT as a proof of Digital Ownership-reward system integrated to a Secure Distributed Computing system Managed by Blockchain

*** Se video below for a quick demo and usage of the tool. Demo

Summary

This is a Thesis project for my masters degree in Data Science provided by University of Stavanger. The purpose of this work is to demonstrate the feasibility and potential to implement an NFT-Based system to store and manage ownership of data, contribute to the newtork and use Proof of Ownership as the consensus mechanism.

Hyperledger architecture

A permissioned Blockchain-based network

The project simulates the interaction between two organization in a permissioned blockchain network where they can:

  • Upload a data file system with its metadata
  • Mint uploaded data as an NFT and store the resulted hash or IPFS-CID into their own database as a proof of ownership.
  • Transfer the generated NFT Asset
  • Burn the NFT
  • Extend the NFT

Thus, the project aims to show the potential a solution like this has to be implemented in real applications for corporate organizations.

Purpose

This thesis project emerged by the need to overcome security threats and data breaches as well as to explore a way to share and contribute in a commonly shared data repository similar to what current oil companies use in Norway.

Technologies

Hyperledger Fabric 2.2

Open-source enterprise blockchain technology, with particular permissioned capabilities, authorization and consensus.

IPFS

Decentralized file storage system used content-addressed capabilities.

ExpressJS

Backend web application framework for Node.js designed for building web applications and APIs.

Typescript

A programming language superset of JavaScript developed and maintained by Microsoft.

React

Open-source front-end JavaScript library for building user interfaces based on UI components.

Docker

Set of platform as a service products that use OS-level virtualization to deliver software in packages called containers.

System Components

Architecture components

Hyperledger Fabric

Chaincode

  • Uses NFT (Erc-721) smart contract extension to allow data management

Private IPFS Network

  • It is a private network that controls content addressed files and shares the files among different nodes

Backend

  • Server application that communicates with the hyperledger network and extends its functionality by an API.

Frontend

  • User interface that enables organizations to issue NFT's by uploading data files.

Repository Structure

network

Contains all the hyperlesdger fabric implementation for the development of this project

thesis

Source code for the thesis report written in Latex. Final version can be found here:

web

Contains all web components for the application program.

client

Frontend application developed in React and Typescript

server

Backend server appplication developed in ExpressJS and Typescript

common

Common data types and utils used by both Backened and server

REST

A Postman collection to explore and use all the API calls created. Related documentation can be found there to further extend to other applications

chaincode

Contains the smart contracts and code developed for Fabric NFT system

token-erc-721

Implementation and extension of Ethereum Standart ERC-721 (NFT) smart contract built in TypeScript.

resources

Miscelaneous, images and diagrams build to present and explain the system architecture, technologies used and workflows.

Instructions

To run the project follow the following steps:

Prerequisites

  • A linux operating system or bash scripting shell is required.
  • On a windows machine the usage of WSL (any linux distribution) can help to run the project
  • Docker Desktop installed (if using Windows with WSL make sure the option 'Use WSL 2 Based engine' or similar is selected).

Docker WSL Selection

1. Clone the repository

git clone https://github.com/asahicantu/NFT-Thesis.git

2. Change to network folder

Move to the repository's directory and then to the network directory

cd NFT-Thesis/network

3. Enable execution mode for all .sh (shell scripting files)

find . -name "*.sh" -exec chmod +x {} \;

4. Run the network infrastructure

Execute the following command to create all the network infrastructure in docker, certificates, organizations nad connection files.

./network start

This process will take some minutes to finish running, what it does:

  1. Invokes Docker-compose commands to create the docker containers for:
  2. Hyperledger fabric
  3. Hyperledger explorer and explorerdb (Interface to visualize the blocks in the Ledger)
  4. Hyperledger orderer (Orderer node)
  5. Peer nodes (Peer and CA Orderers for organizations 1 and 2)
  6. IPFS nodes (Bootstrap, and 2 nodes for private network)

5. Run web application

  1. It is recommended to use two terminals and change to directory cd web
  2. Execute: cd server && ./npm run dev this will execute ExpressJS Web Server

2.1. Important to run this environment in dev mode to visualize logs and potential resistance to failures 3. In the second terminal execute cd client && ./npm run start this will execute React Web App 4. Navigate to the web application (localhost:3000) and select the option menu "Register Organizations" 4.1. Register Organization 1 By selecting the file "network/organizations/peerOrganizations/org1.example.com/connection-org1.json" 4.2. Register Organization 2 By selecting the file "network/organizations/peerOrganizations/org2.example.com/connection-org2.json" 5. Select the option menu "Enroll User" 5.1. Select the organizstion that user will belong, user name (add 'minter' as a default option) and department (set 'deptartment1' as default option) 5.2 Submit the user enrollment proces. Repeat the process to add more users for both organization 1 and 2 6. Select 'Mint NFT' Option to issue a new NFT. 6.1 In 'Organization' field set 'Org1', 'minter' as owner and select a file as follows: MintNFT 6.2. Repeat the process to mint as any NFT as desired 7. Use the menu 'View Tokens' to visualize issued NFTS residing on the IPFS Server

Stopping the network or restarting the system

To ensure all files are removed after using the system it is recommended to run the following command with super user privileges:

cd network
sudo ./network.sh stop

This will remove all running docker containers and organization related connectivity profiles.

Bencharming with Hyperledger Caliper

For the test and benchmark performances Hyperledger Caliper was used.

 docker pull hyperledger/caliper:0.5.0

Usage:

docker run --rm hyperledger/caliper:0.5.0 -it bash calipper --version

Running benchmarking with Hyperledger fabric

If additional statistics are desired to be run against the Fabric system it is recommended to use and follow the instructions provided by Hyperlesdger Caliper. Copy all the contents from network/organizations into network/compose/caliper and run docker compose command.

cd network
sudo cp -r organizations compose/caliper/ 
docker-compose -f docker-compose-caliper.yaml up
npm install --only=prod @hyperledger/caliper-cli@0.5.0
npx caliper bind --caliper-bind-sut fabric:2.2
npx caliper launch manager --caliper-workspace . --caliper-benchconfig scenarios/config.yaml --caliper-networkconfig networks/fabric/network-config.yaml
npx caliper launch manager --caliper-workspace ./ --caliper-networkconfig networks/fabric/test-network.yaml --caliper-benchconfig benchmarks/samples/fabric/fabcar/config.yaml --caliper-flow-only-test --caliper-fabric-gateway-enabled

Author: asahicantu
Source code: https://github.com/asahicantu/NFT-Thesis
License: Apache-2.0 license
#react-native  #typescript #nft 

Digital Asset Ownership and Transfer using NFT and Hyperledger
Best of Crypto

Best of Crypto

1660346580

The Client for Artion NFT Marketplace on Fantom Opera

A client side implementation of the Artion Marketplace for NFT trading on Fantom Opera network.

Artion allows users:

  • to explore existing NFTs on Fantom Opera network.
  • to create a new collection of a new NFT
  • to register a collection of already deployed NFT.
  • to buy / sell / collect rare NFTs.

See Guide

Project Setup

npm install / yarn

Compile

npm run start

Compiles and minifies for production

npm run build

.env file sample

REACT_APP_API_URL=
SKIP_PREFLIGHT_CHECK=true
REACT_APP_ENV=
REACT_APP_USDC=
REACT_APP_FUSDT=

Download details:

Author: Fantom-foundation
Source code: https://github.com/Fantom-foundation/Artion-Client
License: GPL-3.0 license

#fantom #blockchain #nft #javascript

The Client for Artion NFT Marketplace on Fantom Opera
Quinten  Boehm

Quinten Boehm

1660329480

Sol Mint Nft: Anchor Based Project to Mint A NFT on Solana

sol-mint-nft

Anchor based project to mint a NFT on solana.

🏆

🏆🏆🏆 Sol Mint NFT 🏆🏆🏆

Anchor based project to mint a nft.

📜 Program

⚔️ Used technologies

Rust: Solana program development language.

Metaplex: Wonderful library for the NFT protocol.

Anchor: Solana development framework.

📝 Description

I have built Anchor based solana program to mint NFT and deployed to devnet.

Devnet Address: https://explorer.solana.com/address/9FKLho9AUYScrrKgJbG1mExt5nSgEfk1CNEbR8qBwKTZ

📺 DApp

⚔️ Used technologies

@solana/web3.js: Node.js library to integrate the front end website into the solana program backend.

@project-serum/anchor: Anchor client node.js library to communicate with Anchor based solana program.

Antd: Excellent UI template library for react.js.

React.js: For our front end building.

ipfs: Decentralized storage service. We stores all images and metadata here.

📝 Description

This is react.js based decentralized front-end application to mint animal images.
Now it has the following features.

Wallet connection: It supports major solana wallets such as Phantom, Solflare and Sollet.

Mint: Any user can mint his/her own animal's NFT on solana(devnet) here.

Market(TODO): All animals' NFTs will be listed here. And users can trade NFTs with SOL like Opensea or Magic Eden.


Author: dany-armstrong
Source code: https://github.com/dany-armstrong/sol-mint-nft
 

#react-native #typescript  #javascript #nft 

Sol Mint Nft: Anchor Based Project to Mint A NFT on Solana
Best of Crypto

Best of Crypto

1660305420

A Tracker Implementation Of Marketplace for NFT Trading on Fantom

Fantom NFT Marketplace 

A tracker implementation of Marketplace contract for NFT trading on Fantom Opera network

Project Setup

npm install 

Compile

npm run start / npm run dev (nodemon)

.env file sample

NETWORK_RPC=
NETWORK_CHAINID=
DB_URL=
API_ENDPOINT=
CONTRACTADDRESS=
DECIMAL_ENDPOINT=

Download details:

Author: Fantom-foundation
Source code: https://github.com/Fantom-foundation/artion-marketplace-tracker
License: GPL-3.0 license

#fantom #blockchain #nft #javascript #solidity

A Tracker Implementation Of Marketplace for NFT Trading on Fantom

NFT Drop: Mint Your Own NFT on The Rinkeby Network

NFT Drop

Mint your own NFT on the Rinkeby network.

User flow

  • Select a NFT Collection.
  • Sign In using Metamask, ensure you are on the Rinkeby test network.
  • Click on the Mint button to mint an NFT from the collection.

Built using

Live Demo

https://nft-drop-nine-bice.vercel.app/

License

Code released under the MIT License.


Author: Tushar-Indurjeeth
Source code: https://github.com/Tushar-Indurjeeth/NFT-Drop
License:  MIT license
 

#react-native #typescript  #javascript #nft 

NFT Drop: Mint Your Own NFT on The Rinkeby Network
Maryjane  Olson

Maryjane Olson

1660287900

NFT Marketplace: A Fullstack DApp NFT Marketplace Made with ReactJS

🖼️ NFT Marketplace 

This is a fullstack DApp NFT Marketplace built as a study project to learn more about blockchain and smart contract development.
Made with NodeJS, Hardhat, Solidity, ReactJS, NextJS and Vercel.

Demo

Demo

Checkout the live demo: https://nft-marketplace-markkop.vercel.app/


Market basic actions

You can create (mint) new tokens, uploading their image and metadata on IPFS using Pinata.
If you've created or bought an NFT, you may also sell it by setting a price and paying a listing fee.
When buying an NFT, the price will be transferred to the seller and the listing fee to the NFT Marketplace owner.
It's also possible to cancel a market item, transferring it back to the owner.


Lean NFTs Visualization

There are only two pages to view market's NFTs:

  • Market Page

Shows all NFTs that are available to be bought.
This page will show NFTs even if the user doesn't have the Metamask extension or isn't connected to the dapp.

NFTs available
NFTs available


  • My NFTs Page

Show all account's created, owned and on sale NFTs.
Here you keep track of NFT's you've created and check for how much they've been last sold and their current owner.
You can also list your current owned NFTs or cancel existing ones.
To view this page, you must have Metamask installed and have it connected to Polygon's Testnet network.

Created and owned NFTs
Created and owned NFTs


User Experience

If the Metamask extension is not detected on "My NFTs" page, a message with a download button will be prompted to the user.

Download metamask message and buttons Download metamask message and buttons


If the user has the extension, but is not connected, a message and a connect button will be shown.

Connect wallet message and button
Connect wallet message and button


If the Polygon's Testnet network is not detected, a message and an ADD/CHANGE network button will be available.

Add/Change Network message and button
Add/Change Network message and button


If the connected account is low on balance of Matic tokens, a message with a faucet link is provided.

A low on balance message with a faucet link
A low on balance message with a faucet link


When changing account or network, the page will refresh updating only the affected components.

Components update on account change
Components update on account change


When performing an action, a loading feedback is shown and the card updates to its new state automatically.

Buying an NFT and its feedbacks
Buying an NFT and its feedbacks

Easy Deployment

Frontend is automatically deployed using Vercel's Github integration, but contracts have to be manually deployed to keep a better control on them.
However, new deployed contract addresses can be updated on the frontend simply by running a script that modifies Vercel's project environment variables and triggers a new frontend deployment.

How to run

  • Copy .env.local.example to .env.local and fill it with environment variables
  • Run npm run node to start a local EVM blockchain testnet
  • Run npm run setup to deploy NFT and Marketplace contracts and perform some initial actions to the local blockchain
  • Run npm run dev to start frontend application
  • Make sure to use Localhost 8545 as the Metamask's network
  • Make sure to import local Account #0 and #1 into Metamask accounts.

How to deploy

  • Frontend is deployed automatically on main branch using Vercel's github integration
  • Set ACCOUNT_PRIVATE_KEY in .env.local and send it some Polygon's Testnet Matic tokens
  • Run npm run deploy:mumbai to deploy contracts to Polygon`s Testnet (Mumbai)
  • Optional: do the same for ACCOUNT2_PRIVATE_KEY env and run npm run setup-marketplace:mumbai to setup the marketplace with existing tokens and sales.
  • Run npm run env to update Vercel's environment variables with the new deployed contract addresses.*
  • Make sure to use Polygon Testnet Mumbai as Metamask's network

* You'll need to create the envs on Vercel first

Development Challenges

* They're usually caused by incorrect contract addresses and wrong default gas values

Wishlist

  • Refactor frontend code to accept other networks besides Mumbai
  • Lazyload for NFTs images and metadata
  • Add support for custom ERC20 tokens as payment (started on #2)

Troubleshooting

Mumbai marketplace setup command is breaking with a 'estimate gas failed' error

Try changing hardhat.config.js mumbai gas values.
I'm using the ones I've found here:
https://forum.moralis.io/t/deploy-to-polygon-matic-mumbai-fails/700

Nouce is too high

Reset your Metamask account transaction history.
Find out more on:
https://medium.com/@thelasthash/solved-nonce-too-high-error-with-metamask-and-hardhat-adc66f092cd

References


Author: johnoseni1
Source code: https://github.com/johnoseni1/East-Marketplace-Full

#react-native  #javascript #nft 

NFT Marketplace: A Fullstack DApp NFT Marketplace Made with ReactJS
Blockchain Dev

Blockchain Dev

1660284702

Learn Solidity: DeFi, Flash Loans, Hacking, NFTs & more!

In this ultimate Solidity tutorial, we'll learn about DeFi, Flash Loans, Hacking, NFTs & more! This tutorial demonstrates a basic Hardhat use case. It comes with a sample contract, a test for that contract, and a script that deploys that contract.

Sample Hardhat Project

Try running some of the following tasks:

npx hardhat help
npx hardhat test
GAS_REPORT=true npx hardhat test
npx hardhat node
npx hardhat run scripts/deploy.js

TABLE OF CONTENTS
00:00 Intro
02:19 First Contract
30:32 Testing Contracts
01:00:59 NFT Real Estate Escrow
02:13:08 Flash Loans
03:06:52 Hacking: Reentrancy

CODE: https://github.com/dappuniversity/solidity_tutorial 

#solidity #defi #flashloans #hacking #nft #blockchain #web3

 

Learn Solidity: DeFi, Flash Loans, Hacking, NFTs & more!
Ruthie  Blanda

Ruthie Blanda

1660215840

Ethereum's Missing P2p NFT and token Swap Library for Web3 Developers

NFT Swap Banner

Swap SDK

The missing peer-to-peer swap library for Ethereum and EVM-compatible chains, powered by the 0x protocol, written in TypeScript for web3 developers. Trade tokens (ERC20s), NFTs, and other collectibles (ERC721 and ERC1155) with just a few lines of code. Seriously, easily trade anything on Ethereum with this library.

🎉 Update 1/31/22: Swap SDK now supports 0x v4, check out the docs. 🎉

Overview

tl;dr: NFT Swap SDK is the easiest, most-powerful swap library available on the EVM. Supports Ethereum and EVM-compatible chains (Polygon, Avalanche, BSC, etc.). Works in both browser and Node.js. Written in TypeScript, built using the 0x protocol. With this library, you can build support for NFT marketplaces, over-the-counter (OTC) exchanges, and/or peer-to-peer exchanges.

The NFT Swap SDK developed by Trader.xyz offers swap support for ERC20s, ERC721s, and ERC1155s. Exchange NFTs for NFTs, NFTs for ERC20 tokens, or bundles of NFTs and tokens. This library provides the ultimate swap flexibility combined with a simple API surface area so you can be productive immediately and focus on building your web3 app.

This library is powered and secured by the 0x v3 protocol. The 0x v3 protocol has been in production for multiple years securing billions of dollars with of trades.

Goals

We want to share all underlying technology trader.xyz uses with the community. While we won't be open-sourcing our frontend, as we think design and UX is our differentiator, we believe in open-sourcing and freely sharing all underlying technology.

Our end goal is every piece of tech you see trader.xyz use (protocol, swap libraries, open-source orderbook, order monitor, high-performance NFT indexer, property-based orders, specific React hooks, and NFT aggregation) end up open-source. This library is the first step to achieving our goal.

Installation

You can install the SDK with yarn:

yarn add @traderxyz/nft-swap-sdk

or npm:

npm install @traderxyz/nft-swap-sdk

Configuration

To use the SDK, create a new NftSwap instance.

import { NftSwap } from '@traderxyz/nft-swap-sdk';

// From your app, provide NftSwap the web3 provider, signer for the user's wallet, and the chain id.
const nftSwapSdk = new NftSwap(provider, signer, chainId);

Now you're set up and ready to use the SDK in your program. Check out the examples below to learn how to swap with the library.

Examples

Example 1: NFT <> NFT swap

In this first example, we're going to do a 1:1 NFT swap. We're going to swap User A's CryptoPunk NFT for User B's Bored Ape NFT.

Terminology: maker: Since User A will initiate the trade, we'll refer to User A as the maker of the trade.

Terminology: taker: Since User B will be filling and completing the trade created by User A, we'll refer to User B as the taker of the trade.

// Setup the sample data...
const CHAIN_ID = 1; // Chain 1 corresponds to Mainnet. Visit https://chainid.network/ for a complete list of chain ids

const CRYPTOPUNK_420 = {
  tokenAddress: '0xb47e3cd837ddf8e4c57f05d70ab865de6e193bbb', // CryptoPunk contract address
  tokenId: '420', // Token Id of the CryptoPunk we want to swap
  type: 'ERC721', // Must be one of 'ERC20', 'ERC721', or 'ERC1155'
};

const BORED_APE_69 = {
  tokenAddress: '0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D', // BAYC contract address
  tokenId: '69', // Token Id of the BoredApe we want to swap
  type: 'ERC721',
};

// User A Trade Data
const walletAddressUserA = '0x1eeD19957E0a81AED9a80f09a3CCEaD83Ea6D86b';
const assetsToSwapUserA = [CRYPTOPUNK_420];

// User B Trade Data
const walletAddressUserB = '0x44beA2b43600eE240AB6Cb90696048CeF32aBf1D';
const assetsToSwapUserB = [BORED_APE_69];

// ............................
// Part 1 of the trade -- User A (the 'maker') initiates an order
// ............................

// Initiate the SDK for User A.
// Pass the user's wallet signer (available via the user's wallet provider) to the Swap SDK
const nftSwapSdk = new NftSwap(provider, signerUserA, CHAIN_ID);

// Check if we need to approve the NFT for swapping
const approvalStatusForUserA = await nftSwapSdk.loadApprovalStatus(
  assetsToSwapUserA[0],
  walletAddressUserA
);
// If we do need to approve User A's CryptoPunk for swapping, let's do that now
if (!approvalStatusForUserA.contractApproved) {
  const approvalTx = await nftSwapSdk.approveTokenOrNftByAsset(
    assetsToSwapUserA[0],
    makerAddress
  );
  const approvalTxReceipt = await approvalTx.wait();
  console.log(
    `Approved ${assetsToSwapUserA[0].tokenAddress} contract to swap with 0x (txHash: ${approvalTxReceipt.transactionHash})`
  );
}

// Create the order (Remember, User A initiates the trade, so User A creates the order)
const order = nftSwapSdk.buildOrder(
  assetsToSwapUserA,
  assetsToSwapUserB,
  walletAddressUserA
);
// Sign the order (User A signs since they are initiating the trade)
const signedOrder = await nftSwapSdk.signOrder(order, makerAddress);
// Part 1 Complete. User A is now done. Now we send the `signedOrder` to User B to complete the trade.

// ............................
// Part 2 of the trade -- User B (the 'taker') accepts and fills order from User A and completes trade
// ............................
// Initiate the SDK for User B.
const nftSwapSdk = new NftSwap(provider, signerUserB, CHAIN_ID);

// Check if we need to approve the NFT for swapping
const approvalStatusForUserB = await nftSwapSdk.loadApprovalStatus(
  assetsToSwapUserB[0],
  walletAddressUserB
);
// If we do need to approve NFT for swapping, let's do that now
if (!approvalStatusForUserB.contractApproved) {
  const approvalTx = await nftSwapSdk.approveTokenOrNftByAsset(
    assetsToSwapUserB[0],
    walletAddressUserB
  );
  const approvalTxReceipt = await approvalTx.wait();
  console.log(
    `Approved ${assetsToSwapUserB[0].tokenAddress} contract to swap with 0x. TxHash: ${approvalTxReceipt.transactionHash})`
  );
}
// The final step is the taker (User B) submitting the order.
// The taker approves the trade transaction and it will be submitted on the blockchain for settlement.
// Once the transaction is confirmed, the trade will be settled and cannot be reversed.
const fillTx = await nftSwapSdk.fillSignedOrder(signedOrder);
const fillTxReceipt = await nftSwapSdk.awaitTransactionHash(fillTx.hash);
console.log(`🎉 🥳 Order filled. TxHash: ${fillTxReceipt.transactionHash}`);

Example 2: Swap bundles -- Bundle of mixed ERC721s and ERC20 <> Bundle of ERC20s

Here we show an example of what the swap library is capable of. We can even swap arbitrary ERC tokens in bundles. We call it a bundle when we have more than one item that a party will swap. Bundles can have different ERC types within the same bundle.

In other words, we can swap [ERC721, ERC1155, ERC20] <> [ERC721, ERC1155, ERC20]. There's really no limit to what we can swap.

More concrete example: We can swap [2 CryptoPunks and 1,000 DAI] for [420 WETH and 694,200 USDC]. In this case we'd be swapping two ERC721s and an ERC20 (Punk NFT and DAI, respectively) for two ERC20s (WETH and USDC).

This is just one example. In reality, you can swap as many things as you'd like, any way you'd like. The underlying 0x protocol is extremely flexible, and the NFT swap library abstracts all the complexity away so you don't have to worry about protocol nuances.

// Set up the sample data for the swap...
const CHAIN_ID = 1; // Mainnet

const CRYPTOPUNK_420 = {
  tokenAddress: '0xb47e3cd837ddf8e4c57f05d70ab865de6e193bbb',
  tokenId: '420',
  type: 'ERC721',
};

const CRYPTOPUNK_421 = {
  tokenAddress: '0xb47e3cd837ddf8e4c57f05d70ab865de6e193bbb',
  tokenId: '421',
  type: 'ERC721',
};

const ONE_THOUSAND_DAI = {
  tokenAddress: '0x6b175474e89094c44da98b954eedeac495271d0f', // DAI contract address
  amount: '1000000000000000000000', // 1,000 DAI (DAI is 18 digits) -- amount to swap
  type: 'ERC20',
};

const SIXTY_NINE_USDC = {
  tokenAddress: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC contract address
  amount: '69000000', // 69 USDC (USDC is 6 digits)
  type: 'ERC20',
};

const FOUR_THOUSAND_TWENTY_WETH = {
  tokenAddress: '0x6b175474e89094c44da98b954eedeac495271d0f', // WETH contract address
  amount: '420000000000000000000', // 420 Wrapped-ETH (WETH is 18 digits)
  type: 'ERC20',
};

// User A Trade Data
const walletAddressUserA = '0x1eeD19957E0a81AED9a80f09a3CCEaD83Ea6D86b';
const assetsToSwapUserA = [CRYPTOPUNK_420, CRYPTOPUNK_421, ONE_THOUSAND_DAI];

// User B Trade Data
const walletAddressUserB = '0x44beA2b43600eE240AB6Cb90696048CeF32aBf1D';
const assetsToSwapUserB = [SIXTY_NINE_USDC, FOUR_THOUSAND_TWENTY_WETH];

// ............................
// Part 1 of the trade -- User A (the 'maker') initiates an order
// ............................
const nftSwapSdk = new NftSwap(provider, signerUserA, CHAIN_ID);
// Note: For brevity, we assume all assets are approved for swap in this example.
// See previous example on how to approve an asset.

const order = nftSwapSdk.buildOrder(
  assetsToSwapUserA,
  assetsToSwapUserB,
  walletAddressUserA
);
const signedOrder = await nftSwapSdk.signOrder(order, makerAddress);

// ............................
// Part 2 of the trade -- User B (the 'taker') accepts and fills order from User A and completes trade
// ............................
const nftSwapSdk = new NftSwap(provider, signerUserB, CHAIN_ID);

const fillTx = await nftSwapSdk.fillSignedOrder(signedOrder);
const fillTxReceipt = await nftSwapSdk.awaitTransactionHash(fillTx);
console.log(`🎉 🥳 Order filled. TxHash: ${fillTxReceipt.transactionHash}`);

// Not so bad, right? We can arbitrarily add more assets to our swap without introducing additional complexity!

Example 3: React Hooks + Swap SDK

In this example, we'll leverage the amazing web3-react React Hook library.

const App = () => {
  const { library, chainId } = useWeb3React<Web3React>();

  const [swapSdk, setSwapSdk] = useState(null);
  useEffect(() => {
    const sdk = new NftSwap(library, library.getSigner(), chainId);
    setSwapSdk(sdk);
  }, [library, chainId])

  // Use the SDK however you'd like in the app...
  const handleClick = useCallback(() => {
    if (!swapSdk) {
      return;
    }
    swapSdk.buildOrder(...)
  }, [swapSdk])

  // ...
}

FAQ

Which ERCs does this library support?

  • ERC20, ERC721, and ERC1155

What EVM chains are currently supported?

  • Mainnet (1)
  • Kovan (42)
  • Rinkeby (4)
  • Polygon (137)
  • Binance Smart Chain (56)
  • Avalanche (43114)

What protocol does this library use?

  • trader.xyz and trader.xyz libraries are powered by 0x v3 Protocol. This protocol is mature and lindy, and has been extremely well-audited.
  • Check out the 0x v3 spec here
  • Check out the 0x v3 Consensys audit here

Are there any protocol fees to execute swaps?

  • No

How do I get the user's signer object?

  • Generally you can get it from the user's web3 wallet provider, by something like this: provider.getSigner().
  • See this ethers guide (control-f for getSigner).
  • In web3-react you can do:
    • const { library } = useWeb3React();
    • const signer = library.getSigner();

How do I store a SignedOrder

  • That's up to you. This library has no opinions on how to store orders. You can throw them in a centralized SQL database, save them to localstorage, use a decentralized messaging solution -- it's really up to you and your app concerns. You can even serialize and compress an order to fit in a tweet or shareable URL! 🤯

Support

For personalized help, please join the #dev-help channel in our Discord: https://discord.gg/2kAbrHs7 OR our Slack channel: https://join.slack.com/t/bcto-workspace/shared_invite/zt-18je7lax0-VSsTFeMh_PH3VnKeIr3QkA

For general documentation, check out https://docs.swapsdk.xyz

Roadmap

We're currently working on the following features for the next iteration of this library:

  • ✅ LIVE -- Persistent data store of orders (off-the-shelf storage in trader.xyz's public order storage server). Think of it as a public good
  • ✅ LIVE -- Property-based orders
  • ✅ LIVE -- Order validation
  • ✅ LIVE -- Live order status
  • Order event streaming via WebSockets

If you have feature requests, reach out in our Discord. OR our Slack: https://join.slack.com/t/bcto-workspace/shared_invite/zt-18je7lax0-VSsTFeMh_PH3VnKeIr3QkA

We want to make this library a one-stop shop for all your NFT swapping needs.


Author: serenesky0914
Source code: https://github.com/serenesky0914/nft-swap-sdk
License: MIT license

#react-native #typescript #nft #web3 #P2p 

Ethereum's Missing P2p NFT and token Swap Library for Web3 Developers
Marisol  Kuhic

Marisol Kuhic

1660194600

Crypto Wiz NFT Minting DApp using React and TailwindCSS

Crypto Wiz NFT Minting dApp

This is CryptoWiz NFT minting dApp(BETA). This application describes the CryptoWiz collections and allows the mint of the NFTs.

To see the demo check this link:

vercel

This application is a complete example of fullstack NFT minting dApp inspired by "Udemy The Fullstack Nft Minting Website Course". To better understand this source take thise course:

udemy

Installation

You can use the default CryptoWiz smart contract and play with it or you can also put your own smart contract and make changes as needed. Remember to make .env file with your own variables like this.


 NEXT_PUBLIC_ALCHEMY_RPC_URL=<PERSONAL_NEXT_PUBLIC_ALCHEMY_RPC_URL>
 NEXT_PUBLIC_FORTMATIC_KEY=<PERSONAL_NEXT_PUBLIC_FORTMATIC_KEY>
 NEXT_PUBLIC_DAPP_ID=<PERSONAL_NEXT_PUBLIC_DAPP_ID>
 METAMASK_PRIVATE_KEY=<PERSONAL_METAMASK_PRIVATE_KEY>
 ETHERSCAN_API_KEY=<PERSONAL_ETHERSCAN_API_KEY>

Use the default CryptoWiz Smart Contract:


  # Clone the repository and change directory into it
  git clone https://github.com/codingwithdidem/CryptoWiz-minting-dapp.git
  cd CryptoWiz-nft-minting-dapp

  npm install            # Download packages
  npm run dev            # Run the dev server

Making Changes

First of all change .env variables with yours. And update the dapp.config.js file according to your needs.

If you want to make changes on CryptoWiz smart contract, you can find CryptoWiz.sol inside /contractsfolder. After making changes you need to recompile your smart contract using npx hardhat compile command. It will recompile the smart contract and create & update /artifacts folder. Smart contract ABI is also in this folder.

After making changes you need to update the scripts/whitelist.js with your whitelisted users accounts and deploy & verify your smart contract on ethereum blockchain. Use the scripts I created for you to do that. You can find the deploy & verify scripts inside /scriptsfolder.

  # This command will deploy your smart contract on rinkeby test network
  npx hardhat run scripts/deployContract.js --network rinkeby

  # This command will verify your smart contract on rinkeby etherscan
  npx hardhat run scripts/verifyContract.js --network rinkeby

IMPORTANT

When deploying the contract the state of the presaleM and publicM properties is false. Set at least one of the properties to true with togglePresale and togglePublicSale if no causes fee calculation error.

Client:

** If you want to use a different network you need to pass its name instead of rinkeby. Also make sure you configured it in hardhat.config.js file as a network option.

Finally update the /utils/interact.js file so that it uses the related functions from your updated contract. Also change the contract address and the imported ABI in this file with your newly deployed contract.

Deploying on mainnet

When you are done with making changes and your minting dapp is just as you wanted it is time to deploy on ethereum mainnet. To do that;

  • Make sure you changed all env variables with yours. And also for the network you need to chose ethereum mainnet.
  • Update hardhat.config.js so that as network option you use mainnet not rinkeby. hardhat
  • While deploying your contract with hardhat you need to use mainnet as network-name
  # This command will deploy your smart contract on ethereum mainnet
  npx hardhat run scripts/deployContract.js --network mainnet

  # This command will verify your smart contract on mainnet etherscan
  npx hardhat run scripts/verifyContract.js --network mainnet

Tech Stack

Client: React, TailwindCSS, web3.js

Server: Alchemy, NextJS, Hardhat

Support

Write me on mnz3553@gmail.com

"Buy Me A Coffee"


Author: VanMenoz92
Source code: https://github.com/VanMenoz92/cryptowiz-minting-dapp-main
 

#react-native #javascript #nft #tailwindcss 

Crypto Wiz NFT Minting DApp using React and TailwindCSS

How to Create NFT Staking Landing Page using ERC20, ERC721 in Next JS

NOTE: 
 

it's built on rinkeby ethereum testnet 
It's still on process.

what you can get from this project: 
 

  1. wallet integration with web3react
  2. erc721 staking
  3. erc20 coin to reward

Preparations 
 

  1. fullfill .env 
    NEXT_PUBLIC_ALCHEMY_RPC_URL
    NEXT_PUBLIC_ALCHEMY_API_KEY
    NEXT_PUBLIC_INFURA_API_KEY 
     

Images of The NFT Collection Website:

staking-dashboard unstaked-apes minting-dapp emergency-call wallet-connection

View Demo👇: 
https://nft-staking-master.netlify.app/ 

Download details:

Author: nft-utilz
Source code: https://github.com/nft-utilz/staking_boilerplate_frontend

#next #nextjs #react #javscript #nft #staking #erc20 #erc721 #web3 

How to Create NFT Staking Landing Page using ERC20, ERC721 in Next JS

A Full Stack DApp Starter for Minting NFTs Built on Ethereum, Nextjs

NFT Minting dApp Starter

A full stack dApp starter for minting NFTs built on Ethereum (Solidity) with Next.js (React).

This repo contains code for minting NFTs from the client-side using Solidity, React and TailwindCSS.

Prerequisites

  • Node.js
  • MetaMask wallet browser extension.

Getting Started

Clone This Repo

Use git clone https://github.com/tomhirst/nft-minting-dapp-starter.git to get the files within this repository onto your local machine.

Environment Setup

Duplicate .env.example to .env and fill out the HARDHAT_CHAIN_ID environment variable. The port from the example file, if it's free, will be fine in most cases.

Run npm install.

Running The Smart Contract Locally

Compile the ABI for the smart contract using npx hardhat compile.

If you're successful, you'll recieve a confirmation message of:

Compilation finished successfully

And, a src/artifacts folder will be created in your project.

Deploy the smart contract to the local blockchain for testing with npx hardhat node.

If you're successful, you'll be presented with a number of account details in the CLI. Here's an example:

Account #0: 0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266 (10000 ETH)
Private Key: 0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80

Then in a new terminal window, npx hardhat run scripts/deploy.js --network localhost.

If you're successful, you'll get something like the following CLI output:

Minter deployed to: 0x9fE46736679d2D9a65F0992F2272dE9f3c7fa6e0

Adding A Local Account To MetaMask

Open your MetaMask browser extension and change the network to Localhost 8545.

Next, import one of the accounts by adding its Private Key (for example, 0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80 to MetaMask.

If you're successful, you should see the a balance resembling something like 10000 ETH in the wallet.

Connecting The Front-End

In .env set the NEXT_PUBLIC_MINTER_ADDRESS environment variable to the address your smart contract was deployed to. For example, 0x9fE46736679d2D9a65F0992F2272dE9f3c7fa6e0.

In a new terminal window, load the front-end with npm run dev. If you want to use an alternate port from 3000, use npm run dev -- --port=1234, or whatever port number you prefer.

Demo'ing The Functionality

Once set up, go to localhost:3000 (or whatever post number you used), to view your dApp in the browser.

First, connect your wallet by clicking Connect wallet. Ensure you're connected to the Localhost 8454 network in your MetaMask extension. Select the wallet that you imported earlier.

You can now test minting tokens, between 1 and 10 per transaction, by filling out the input with your desired amount and clicking the Mint button.

If you successfully mint a number of NFTs, you should see the Tokens minted amount increment.

Switching accounts in MetaMask will update the wallet address in the top right hand corner. Disconnecting all accounts will prompt you to connect your wallet.

All state is retained on browser refresh.

Editing The Front-End

To modify the front page of your application, edit pages/index.js.

All TailwindCSS classes are available to you.

To lint your front-end code, use npm run lint.

Testing

To test the smart contract, run npx hardhat test.

Basic tests can be found in test/Minter.test.js.

Roadmap

  • Show the funds available in the connected account's wallet
  • Add common owner functionality to the contract
    • Reserve tokens
    • Flip sale state
    • Set starting index
    • Set base URI for asset metadata
    • Set provenance hash
    • Withdraw funds
  • Attach image data to minted tokens with IPFS
  • Deploy to the Ropsten test network
  • Introduce code style rules and linting
  • Write more extensive tests
  • Create a TypeScript fork

Download details:

Author: yunkiwon
Source code: https://github.com/yunkiwon/mapsNFT

#next #nextjs #react #javscript #nft #dapp

A Full Stack DApp Starter for Minting NFTs Built on Ethereum, Nextjs

Building Epic NFT Game Using React.js, Solidity, Nextjs

Epic Game

In our last repo we learnt how to create a DAO on your own and how to use governance tokens and NFTs for voting purposes. Now we will be stepping into the world of games with NFTs where a user has to play games with their character being an NFT which has unique powers, unique traits etc etc.

Gaming and Crypto

It's worth briefly talking about why gaming + crypto is so interesting. I feel like when most people talk about this topic they throw out really big numbers like, "Blah game did $1.2 billion in revenue this quarter" or something like that. But, it's more than that! It helps to explain why this stuff is cool.

For example, Axie Infinity is an NFT-based game that has done $2.6 billion dollars in NFT trades so far. But... what the f does that even mean?! lol.

Why are people losing their minds over things like this?

Note: this is an "Axie" NFT — which is the character you play as in Axie Infinity! Players buy Axie NFTs first, and then go play the game. Pretty weird, right? Buying the characters before you even play the game!

An Example with Nintendo

Let's say you're Nintendo and you made Super Mario Bros. Mario is now your IP. You're the creator. No one is allowed to create more games with Mario except you. You also want to control who makes % from your characters/universe.

Let's imagine a world instead, where we bring NFTs into the mix.

Let's say Nintendo comes out and says "Hey players! Here are 1,000,000 Mario NFTs. Go buy one for $10. We (Nintendo) are going to be making games that require players to own the Mario NFT in their crypto wallet to play them."

For example, players would be able to take their Mario NFT to play as Mario in Super Smash Bros, then maybe they could take their Mario NFT to play Super Mario Galaxy, etc.

The most important thing here is that the Mario NFTs smart contract code would have something special implemented by Nintendo around royalties.

For example, players would be able to sell their Mario NFTs on a marketplace.

In this case, Nintendo could say: "every time this NFT sells, we take 10% of whatever it sells for" and they can code that into the NFT contract itself. That means the original creators (Nintendo) can always get in on the profits in a variety of ways that don't require trusting anyone other than the blockchain.

That means as Mario rises in popularity, the NFT needed to play Mario games also rise in value. Nintendo could sell more Mario NFTs as well once the original 1,000,000 are gone. Up to them!

Coolest part? Players retain a ton of the value. Players can always hold/sell the original NFTs that would increase in value as the games/characters get more popular. It incentivizes players to help make the game huge as well. Everyone wins :).

This may sounds crazy but this is pretty much exactly how Axie Infinity works. It's doing billions of dollars in revenue every year. You can buy some Axie NFTs here and start playing. As the Axie universe grows more popular, the NFTs increase in value as well!

Issue: Inflation

You'll notice the Axies cost like $300+!!! That's insane and a major turn off for new players. You need three of them to even start playing, so, thats $1K right there.

This is basically caused by inflation in the marketplace. Only a certain # of Axies are being created today but the player base is growing far faster. The result? Crazy prices. There are solutions here that are being explored, but this is definitely a concern when it comes to NFT games. From the official Axie whitepaper:

"Axie population growth is a major factor within the Axie ecosystem. At any given moment, there exists some ideal inflation rate that allows us to grow to our maximum potential. Too slow and Axie prices are too high for everyday people to join; especially competitive Axies. Too fast and you get unhealthy inflation."

Bulding open games

I want to go over another benefit. Easily making games and universes that anyone else can build on via NFTs.

Imagine trying to get a deal with Nintendo to make a game with Mario in it. It would be near impossible unless you were a massive gaming company!! Nintendo would want to do a ton of paperwork detailing how royalties would work.

But, a cool aspect of NFT games is that anyone would be able to build on top of the Mario NFTs and the original creators can retain value.

For example, random game devs would be able to make games that required players to connect their wallet and verify they have the Mario NFT. If they did, then the game would start and the player's game would be able to access various Mario assets! But, what's in it for Nintendo? Well, as these games made by random devs get more popular it means the original Mario NFTs would rise in value which is good for Nintendo. Let's say you think all this stuff around "selling the NFT" is nonsense.

Well, Nintendo could even code the Mario NFT to say, "every time the Mario NFT is used in a new game, ask player to pay $10 from their Ethereum wallet."

$5 would go right to Nintendo's wallet. $5 would go right to the dev's wallet.

The possibilities are literally endless because we can program the royalty system to work however we want.

Get local env up

et's head to the terminal. Go ahead and cd to the directory you want to work in. Once you're there run these commands:

mkdir epic-game
cd epic-game
npm init -y
npm install --save-dev hardhat

Cool, now we should have hardhat. Let's get a sample project going.

npx hardhat

You'll also want to install something called OpenZeppelin which is another library that's used a lot to develop secure smart contracts. We'll learn more about it later. For now, just install it :).

npm install @openzeppelin/contracts

Then run:

npx hardhat run scripts/sample-script.js

Setup data for character NFTs.

How we're going to use playable NFTs

We already know what is an NFT. The goal of our game will be to destroy a boss. Let's say that boss has 1,000,000 HP. What players do is when they start the game, they mint a character NFT that has a certain amount of Attack Damage and HP. Players can order their character NFT to attack the boss and deal damage to it. Kinda like a Pokemon!

The goal? Players need to work together to attack the boss and bring its HP down to 0. The catch? Every time a player hit the boss, the boss hits the player back! If the NFT's HP goes below 0, the player's NFT dies and they can't hit the boss anymore. Players can only have one character NFT in their wallet. Once the character's NFT dies, it's game over. That means many players need to join forces to attack the boss and kill it.

Note: If you want your player to be able to hold multiple character in their wallet (like Pokemon) feel free to make the modifications on your own!

The important thing to know here is that the characters themselves are NFTs.

So, when a player goes to play the game:

  • They'll connect their wallet.
  • Our game will detect they don't have a character NFT in their wallet.
  • We'll let them choose a character and mint their own character NFT to play the game. Each character NFT has its own attributes stored on the NFT directly like: HP, Attack Damage, the image of the character, etc. So, when the character's HP hits 0, it would say hp: 0 on the NFT itself.

This is exactly how the world's most popular NFT games work :). We're going to build it ourselves! What we need to do first is basically set up our minting NFT code because, without that, players can't even get into our game to play!

Setup the data for your NFTs

Time for the fun part, setting up our character NFTs. Each character will have a few attributes: an image, a name, HP value, and attack damage value. These attributes will live directly on the NFT itself. We may add some more attributes later on.

The way our character NFTs will work is there will only be a set # of characters (ex. 3). But, an unlimited # of NFTs of each character can be minted. Again, you can change this if you want — for example if you want only a small # of a certain character to be minted.

So that means if five people mint character #1, that means all five people will have the exact same character but each person will have a unique NFT and each NFT holds its own state. For example, if Player #245's NFT gets hit and loses HP, only their NFT should lose HP!

If that doesn't make sense, don't worry! Let's just jump in the code — it'll slowly make more sense.

The first thing we need to do is actually have a way to initialize a character's default attributes (ex. their default HP, default attack damage, default image, etc). For example, if we have a character named "Pikachu", then we need to set Pikachu's base HP, base attack damage, etc.

Check comments in MyEpicGame.sol!!!

Next in run.js I will define my characters and their attributes

Check comments in run.js!!!

don't copy my characters. Come up with you own before moving on.

Maybe your characters can be from your fav anime or video game.

Maybe you don't even want characters. Maybe instead you want people to mint "weapons" that players using in the game like a sword, machine gun, or a laser cannon.

Maybe you want your characters to have things like "mana", "energy", or "chakra" where your character can cast certain "spells" using these attributes.

Customize your characters. It's what makes this fun + your own. For example, I added Leonardo DiCaprio and Pikachu as characters because I thought it'd be funny as hell lol — and I chuckle every time I see it haha.

Changing around little things like the character will make you feel more like it's your own thing and you'll be a little more motivated to build this thing all the way :).

Actually mint your NFTs locally.

Mint the NFTs

Now that we have all the data nicely set up for our characters, the next thing to do is actually mint the NFT. Let's go through that process.

Check comments in MyEpicGame.sol!!!

Remember, every player has their own character NFT. And, every single NFT has their own state like HP, Attack Damage, etc! So if Player #172 owns a "Pikachu" NFT and their Pikachu NFT loses health in a battle then only Player 172's Pikachu NFT should be changed everyone else's Pikachu should stay the same! So, we store this player character level data in a map.

Next, I have nftHolders which basically lets me easily map the address of a user to the ID of the NFT they own. For example, I would be able to do nftHolders[INSERT_PUBLIC_ADDRESS_HERE] and instantly know what NFT that address owns. It's just helpful to keep this data on the contract so it's easily accessible.

We have also inhertied ERC721 from OpenZepplin. The NFT standard is known as ERC721 which you can read a bit about here. OpenZeppelin essentially implements the NFT standard for us and then lets us write our own logic on top of it to customize it. That means we don't need to write boilerplate code.

Holding dynamic data on an NFT

So, as players play the game, certain values on their character will change, right? For example, If I have my character attack the boss, the boss will hit back! In that case, my NFT's HP would need to go down. We need a way to store this data per player:

nftHolderAttributes[newItemId] = CharacterAttributes({
  characterIndex: _characterIndex,
  name: defaultCharacters[_characterIndex].name,
  imageURI: defaultCharacters[_characterIndex].imageURI,
  hp: defaultCharacters[_characterIndex].hp,
  maxHp:defaultCharacters[_characterIndex].maxHp,
  attackDamage: defaultCharacters[_characterIndex].attackDamage
});

A lot happening here! Basically, our NFT holds data related to our player's NFT. But, this data is dynamic. For example, let's say I create an NFT. By default my NFT starts with default stats like:

{
  characterIndex: 1,
  name: "Aang",
  imageURI: "https://i.imgur.com/xVu4vFL.png",
  hp: 200,
  maxHp: 200,
  attackDamage: 50
} 

Remember, every player has their own character NFT and the NFT itself holds data on the state of the character.

Let's say my character is attacked and loses 50 HP, well then HP would go from 200 → 150, right? That value would need to change on the NFT!

Or maybe we want our game to have upgradeable characters, where you can give your character a sword and add +10 attack damage from 50 → 60. Then, attackDamage would need to change on the NFT!

People often think that NFTs metadata isn't allowed to change, but, that's not true. It's actually up to the creator!!!

In this case, our character name and character image never change, but it's HP value definitely does! Our NFTs must be able to maintain the state of our specific player's character.

Running Locally

We run using run.js to test locally.

Check comments in run.js!!!

nftHolderAttributes hasn't actually attached to our NFT in any way. It's just a mapping that lives on the contract right now. What we're going to do next is basically attach nftHolderAttributes to the tokenURI by overriding it :).

Setup tokenURI

The tokenURI actually has a specific format! It's actually expecting the NFT data in JSON.

Let's go over how to do this :).

Create a new folder under contracts called libraries. We will use Base64 from OpenZepplin. This basically provides us with some helper functions to let us encode any data into a Base64 string — which is a standard way to encode some piece of data into a string. Don't worry, you'll see how it works in a bit!

We'll need to import that library into our contract. For that, add the following snippet near the top of your file, with the other imports.

Check comments in MyEpicGame.sol!!!

Deploy to Rinkeby, see on OpenSea.

Getting our NFTs online

When we use run.js, it's just us working locally.

The next step is a testnet which you can think of as like a "staging" environment. When we deploy to a testnet we'll actually be able to to view our NFT online and we are a step closer to getting this to real users.

Setup a deploy.js file

It's good practice to separate your deploy script from your run.js script. run.js is where we mess around a lot, we want to keep it separate. Go ahead and create a file named deploy.js under the scripts folder. Copy-paste all of run.js into deploy.js. It's going to be exactly the same right now.

I added a few extra calls to mintCharacterNFT as well just to test stuff out!

Check comments in deploy.js!!!

Deploy to Rinkeby testnet

We'll need to change our hardhat.config.js file. You can find this in the root directory of your smart contract project.

require('@nomiclabs/hardhat-waffle');

module.exports = {
  solidity: '0.8.0',
  networks: {
    rinkeby: {
      url: 'YOUR ALCHEMY_API_URL',
      accounts: ['YOUR_PRIVATE_RINKEBY_ACCOUNT_KEY'],
    },
  },
};

You can grab your API URL from the Alchemy dashboard and paste that in. Then, you'll need your private rinkeby key (not your public address!) which you can grab from metamask and paste that in there as well.

Run this command from the root directory of epic-game.

npx hardhat run scripts/deploy.js --network rinkeby

Check out your contract on Etherscan and OpenSea.

Here's my contract on Rinkeby Testnet: https://rinkeby.etherscan.io/address/0xcd22a5Ee85ACa288cc59504fe4c623a833dcaEf9

Here's my NFT Collection on OpenSea: https://testnets.opensea.io/collection/heroes-foeitungc0

Why is this epic?

It’s worth talking about why what you just did is a big deal.

Basically, you made an NFT. So, that’s already cool. People can own a character from your game in their wallet, yay!

But, these NFTs actually have attributes as well! Like attack damage, health, mana, or whatever else you added. So, that means the NFT itself is more than just a JPG — it has other elements that make it more interactive.

The biggest NFT game in the world, Axie Infinity, functions just like this as well. It's a turn-based, Pokemon style game where you fight against other players 1v1.

Check out all the different attributes it has on properties, levels, etc. Get inspired :). All these attributes they have actually affect how this character actually plays in the game itself!

What we’re going to do next is we’re going to actually program in logic to our NFT to “fight” a “boss” in our game. So, that means players will be able to take their NFT to the arena and collaborate with other players to “attack” a big boss you’ll create! When an NFT attacks this boss, the boss can attack the NFT back and the player's NFT will lose health. The HP value on OpenSea would change :).

Sorta like Pokemon!

That means our NFT will have utility outside of just being cool to look at.

This is pretty awesome. In normal games today, you’d buy a game and then pick your character (ex. like in Super Smash Brothers).

In this case, players pick their character NFT, then can play their NFT in-game, and own that character in their wallet forever or until they want to sell it to another player. The selling aspect is extremely interesting, because it means as the player you get something back for playing the game or helping it increase in popularity.

Another interesting thing is that players would be able to take their character NFT to other games that support it.

This is a pretty wild thing to think about. It’s one of the biggest reasons crypto + gaming is so cool.

Remember that Mario NFT example earlier, where others could build on top of Mario? Same deal here with our character NFTs!

For example, let’s say I have 100,000 people mint my “Pikachu” NFT for my game. Now, there are 100,000 unique players who own this NFT.

Another developer could come in and build another game on top of the Pikachu NFT and allow any player who has the NFT to enter their game and play it! They could make it where anyone w/ the Pikachu NFT would be able to play as Pikachu in their game. It’s totally up to them.

Note: In this case, the Pokemon creators might get mad lol. But, imagine Pikachu was your own original character!

Maybe stuff like HP and attack damage is even shared between games, meaning different games could build on top of the original attributes we created.

For example, let’s say we have other devs start building “items” on top of our NFT characters — like swords, shields, potions, etc. Maybe a dev builds something where an NFT character could “equip” a shield in and gain +50 defense. This can all be done in an open, permission-less way :).

On top of that, as the creator of the original Pikachu NFTs — I can charge a royalty fee every time someone buys/sells the original NFTs and that means as my NFTs gain popularity I would make money on every sale.

Okay — lets get to actually programming our game logic now :).

Build boss + attack logic.

Building our boss

So, in our game our character NFT will be able to attack a boss.

The whole goal of the game is to attack the boss and bring its HP to 0! But, the catch is that the boss has a lot of HP and every time we hit the boss it will hit us back and bring our HP down. If our character's HP falls below 0, then our character will no longer be able to hit the boss and it'll be “dead”.

Maybe in the future, someone else would be able to build a “revive” function that allows our dead NFTs to regain 100% health points ;). But for now, if our character dies it’s game over. And we can rest easy knowing our character did its best and took one for the team. That means we need other players to attack the boss as well, we can't do this alone.

Let’s first just build a basic boss struct and initialize its data, similar to how we did for our characters. The boss will basically have a name, an image, attack damage, and HP. The boss will not be an NFT. The boss’s data will just live on our smart contract.

We can add the following code right under where we declared nftHolderAttributes.

Check comments in MyEpicGame.sol!!!

We made good amount functions like attack boss where the player attacks boss and boss attacks the player back, we also coded some more function to get the reterival of all data from the contract and display it in frontend.

Getting the frontend

Now that we have access to a wallet address we can start minting character NFTs from our contract!

This section is going to help you understand how we will be rendering each state of our app. Why don't we just break down the logic real quick:

  • Scenario #1: If user has not connected to your app - Show Connect To Wallet Button
  • Scenario #2: If user has connected to your app AND does not have a character NFT - Show SelectCharacter Component
  • Scenario #3: If user has connected to your app AND does have a character NFT - Show Arena Component. The Arena is where users will be able to attack our boss!

Nice. So it looks like we have three different views we need to create! We are going to be getting into some pretty cool React.js that may be new to you. If you don't fully understand it - don't worry! Remember, Google is your friend :).

Getting started with React.js

Now this is where the fun REALLY starts. Writing and deploying your smart contract is one thing, but building a portal where anyone in the world can interact with the blockchain is just pure magic ✨.

We are going to be using react.js to build our web app. If you are already familiar with React, this will be a breeze. If you haven't done much React, don't worry! You can still make it through this project, but it may feel a bit more difficult. Don't give up! The more you struggle the more you learn 🧠.

Create a basic react app and then we start coding.

Building a connect to wallet button.

We will be doing this in the same manner as we have done in all the other projects.

Check comments in app.js!!!

Setting up the SelectCharacter Component

Let's start off with creating our SelectCharacter Component! Head to the src/Components/SelectCharacter folder and create a new file named index.js. This directory will hold the core logic for our SelectCharacter component as well as it's styling! You should already see a SelectCharacter.css file in there with a bunch of styling!

Oh, one thing to note - you probably see the LoadingIndicator component in the Components folder. Don't worry about that just yet, we will get to it later 🤘.

Go ahead and add the following code to the index.js.

Check comments in src/Components/SelectCharacter/index.js!!!

Showing the SelectCharacter Component

We are going to need to go back to the App.js file and import our newly created component. Right under where you import your App.css file add this line:

import SelectCharacter from './Components/SelectCharacter';

You now have access to your new component! We need to add just a tad bit of fanciness here to get our component to render, though.

Check comments in app.js!!!

Checking for a Character NFT.

The cool part about our game? We mint actual NFTs that are used to play and all the game logic happens on-chain. Earlier in this project, we set up all of our smart contract logic. Now it's time to actually interact with it.

The flow

The first thing we are going to start with is to check whether the wallet address connected to our app has a character NFT already. If it does, we can go ahead and grab the metadata from the wallet's NFT and use it to battle a boss in the metaverse ⚔️.

Here's the flow of getting our web app connected to our deployed smart contract on the Rinkeby Testnet:

  • Copy latest deployed contract address, paste it in to our web app.
  • Copy the latest ABI file, paste it into our web app's directory. (Later, we will delve more into what an ABI is).
  • Import ethers.js to help us talk to our smart contract from the client.
  • Call a function on our contract to make it do something!

Pretty straight forward, right? Let's dive in!

Get smart contract address

We are going to be using this address in multiple components, so, let's make it ezpz to get to! At the root of your project under src go ahead and create a constants.js file and add the following code:

const CONTRACT_ADDRESS = 'YOUR_CONTRACT_ADDRESS_GOES_HERE';
export { CONTRACT_ADDRESS };

Then head back to your App.js file and import this at the top of your file to get access to it, like so:

import { CONTRACT_ADDRESS } from './constants';

We get the abi from the artifacts folder as we did before in other projects.

ome notes on updating your Smart Contract.

Deployed contracts are permanent. You can't change them. The only way to update a contract is to actually re-deploy it.

Let's say you wanted to randomly change your contract right now. Here's what we'd need to do:

Deploy it again.

Update the contract address on our frontend (copy/paste from console log).

Update the abi file on our frontend (copy/paste from artifacts folder).

People constantly forget to do these 3 steps when they change their contract. Don't forget lol.

Why do we need to do all this? Because smart contracts are immutable. They can't change. They're permanent. That means changing a contract requires a full redeploy. Redeploying will also reset all the variables since it'd be treated as a brand new contract. That means we lose all our NFT data when we update the contract's code.

So, what you'll need to do is:

Deploy again using npx hardhat run scripts/deploy.js --network rinkeby

Change contractAddress in constants.js to be the new contract address we got from the step above in the terminal (just like we did before the first time we deployed).

Get the updated abi file from artifacts and copy-paste it into your web app just like we did above.

Again -- you need to do this every time you change your contract's code or else you'll get errors :).

Building the Character Select page.

We setup a resuable contract obj in src/Components/SelectCharacter/index.js to get the rendering of all available characters on the frontend.

Check comments in src/Components/SelectCharacter/index.js!!!

Building the Arena page.

At this point, we have been introduced to pretty much everything we need to know to build our React app. Let's jump right into setting up our Arena Component:

Just like with the SelectCharacter Component, let's create a new file in the Components/Arena folder called index.js. Again, you should already see an Arena.css file in this folder! Once you setup your base don't forget to get fancy with your styling 💅.

Check comments in src/Components/Arena/index.js!!!

Finishing touches on the UI.

Finishing touches on the UI

You've probably noticed quite a few spots where it wasn't indicated to the user that something was happening - when you did things like minted a character NFT or fetched big boss data. I wanted to go through and show you the loading indicators I thought could be cool to add!

We are going to setup a few loading indicators:

  • App.js - Waiting to see if the user has a minted NFT
  • SelectCharacter Component - Waiting for our character NFT to mint
  • Arena Component - Waiting for an attack action to finish

Remember that one LoadingIndicator component that was given to you? We are finally going to be able to use it!

Just like with the SelectCharacter Component, let's create a new file in the Components/LoadingIndicator folder called index.js. Again, you should already see an LoadingIndicator.css file in this folder! Once you setup your base don't forget to get fancy with your styling 💅.

Check comments in src/Components/LoadingIndicator/index.js!!!

Images

Contract link on Etherscan deployed on Rinkeby Testnet: https://rinkeby.etherscan.io/address/0xcd22a5Ee85ACa288cc59504fe4c623a833dcaEf9

NFT Collection on OpenSea: https://testnets.opensea.io/collection/heroes-foeitungc0

Download details:

Author: dakshp07
Source code: https://github.com/dakshp07/epic-games

#next #nextjs #react #javscript #nft #blockchain #nfts #solidity

Building Epic NFT Game Using React.js, Solidity, Nextjs