current position:Home>Create a full stack NFT market on the polygon network
Create a full stack NFT market on the polygon network
2022-05-14 21:19:43【A program ape】
Know how to use hardhat,IPFS and Next js establish NFT market
picture source : shykhman
Marketplace Functions
Market function
When users sell NFT when ,NFT Ownership of is transferred from the creator to the market contract .
When users buy NFT when , The purchase money is transferred from the buyer to the seller , The NFT It will also shift from the market to the buyer .
Market owners can set users to sell NFT Service charge . This fee is charged from the seller , And transferred to the contract owner after each transaction . The market contract owner can earn income from all sales in the market .
In this paper , We will be in Polygon Sign a market contract on the network .
Polygon How it works ?
Polygon It is a multi-layer platform , The goal is to expand Ethereum through a large number of side chains , All side chains are designed to dredge the main platform in an efficient and economical way .
Polygon The main chain of is the proof of interest (PoS) Side chain , Participants can pledge MATIC Tokens to verify transactions and vote for network upgrades .
Environmental Science
- Create a next-js application
npx create-next-app marketplace
- Installation package
npm install ethers hardhat ethereum-waffle chai @nomiclabs/hardhat-waffle @nomiclabs/hardhat-ethers web3modal @openzeppelin/contracts ipfs-http-client axios react-toastify
Back end
npx hardhat
If README.md File error , Delete and try again
- Edit like this hardhat.config.js file :
require("@nomiclabs/hardhat-waffle");const fs = require('fs');module.exports = { defaultNetwork: "hardhat", networks: { hardhat: { chainId: 1337 }, // polygon testnet mumbai: { url: "https://rpc-mumbai.maticvigil.com", accounts: [process.env.privateKey] // your wallet private key }, //polygon mainnet matic: { url: "https://rpc-mainnet.maticvigil.com", accounts: [process.env.privateKey] } }, solidity: { version: "0.8.4", settings: { optimizer: { enabled: true, runs: 200 } } }};
- hardhat.config.js -
- Create... Under the contract folder NFTMarketplace.sol file :
// SPDX-License-Identifier: MITpragma solidity ^0.8.4;import "@openzeppelin/contracts/utils/Counters.sol";import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";import "@openzeppelin/contracts/token/ERC721/ERC721.sol";contract NFTMarketplace is ERC721URIStorage { using Counters for Counters.Counter; Counters.Counter private _tokenIds; Counters.Counter private _itemsSold; /* platform fee */ uint256 listingPrice = 0 ether; address payable owner; mapping(uint256 => MarketItem) private idToMarketItem; struct MarketItem { uint256 tokenId; address payable seller; address payable owner; uint256 price; bool sold; } event MarketItemCreated ( uint256 indexed tokenId, address seller, address owner, uint256 price, bool sold ); constructor() ERC721("Metaverse Tokens", "METT") { owner = payable(msg.sender); } /* Updates the listing price of the contract */ function updateListingPrice(uint _listingPrice) public payable { require(owner == msg.sender, "Only marketplace owner can update listing price."); listingPrice = _listingPrice; } /* Returns the listing price of the contract */ function getListingPrice() public view returns (uint256) { return listingPrice; } /* Mints a token and lists it in the marketplace */ function createToken(string memory tokenURI, uint256 price) public payable returns (uint) { _tokenIds.increment(); uint256 newTokenId = _tokenIds.current(); _mint(msg.sender, newTokenId); _setTokenURI(newTokenId, tokenURI); createMarketItem(newTokenId, price); return newTokenId; } function createMarketItem( uint256 tokenId, uint256 price ) private { require(price > 0, "Price must be at least 1 wei"); require(msg.value == listingPrice, "Price must be equal to listing price"); idToMarketItem[tokenId] = MarketItem( tokenId, payable(msg.sender), payable(address(this)), price, false ); _transfer(msg.sender, address(this), tokenId); emit MarketItemCreated( tokenId, msg.sender, address(this), price, false ); } /* allows someone to resell a token they have purchased */ function resellToken(uint256 tokenId, uint256 price) public payable { require(idToMarketItem[tokenId].owner == msg.sender, "Only item owner can perform this operation"); require(msg.value == listingPrice, "Price must be equal to listing price"); idToMarketItem[tokenId].sold = false; idToMarketItem[tokenId].price = price; idToMarketItem[tokenId].seller = payable(msg.sender); idToMarketItem[tokenId].owner = payable(address(this)); _itemsSold.decrement(); _transfer(msg.sender, address(this), tokenId); } /* Creates the sale of a marketplace item */ /* Transfers ownership of the item, as well as funds between parties */ function createMarketSale( uint256 tokenId ) public payable { uint price = idToMarketItem[tokenId].price; address seller = idToMarketItem[tokenId].seller; require(msg.value == price, "Please submit the asking price in order to complete the purchase"); idToMarketItem[tokenId].owner = payable(msg.sender); idToMarketItem[tokenId].sold = true; idToMarketItem[tokenId].seller = payable(address(0)); _itemsSold.increment(); _transfer(address(this), msg.sender, tokenId); payable(owner).transfer(listingPrice); payable(seller).transfer(msg.value); } /* Returns all unsold market items */ function fetchMarketItems() public view returns (MarketItem[] memory) { uint itemCount = _tokenIds.current(); uint unsoldItemCount = _tokenIds.current() - _itemsSold.current(); uint currentIndex = 0; MarketItem[] memory items = new MarketItem[](unsoldItemCount); for (uint i = 0; i < itemCount; i++) { if (idToMarketItem[i + 1].owner == address(this)) { uint currentId = i + 1; MarketItem storage currentItem = idToMarketItem[currentId]; items[currentIndex] = currentItem; currentIndex += 1; } } return items; } /* Returns only items that a user has purchased */ function fetchMyNFTs() public view returns (MarketItem[] memory) { uint totalItemCount = _tokenIds.current(); uint itemCount = 0; uint currentIndex = 0; for (uint i = 0; i < totalItemCount; i++) { if (idToMarketItem[i + 1].owner == msg.sender) { itemCount += 1; } } MarketItem[] memory items = new MarketItem[](itemCount); for (uint i = 0; i < totalItemCount; i++) { if (idToMarketItem[i + 1].owner == msg.sender) { uint currentId = i + 1; MarketItem storage currentItem = idToMarketItem[currentId]; items[currentIndex] = currentItem; currentIndex += 1; } } return items; } /* Returns only items a user has listed */ function fetchItemsListed() public view returns (MarketItem[] memory) { uint totalItemCount = _tokenIds.current(); uint itemCount = 0; uint currentIndex = 0; for (uint i = 0; i < totalItemCount; i++) { if (idToMarketItem[i + 1].seller == msg.sender) { itemCount += 1; } } MarketItem[] memory items = new MarketItem[](itemCount); for (uint i = 0; i < totalItemCount; i++) { if (idToMarketItem[i + 1].seller == msg.sender) { uint currentId = i + 1; MarketItem storage currentItem = idToMarketItem[currentId]; items[currentIndex] = currentItem; currentIndex += 1; } } return items; }}
- NFTMarketplace.sol -
- stay scripts folders creating deploy.js Script :
const hre = require("hardhat");const fs = require('fs');async function main() { const NFTMarketplace = await hre.ethers.getContractFactory("NFTMarketplace"); const nftMarketplace = await NFTMarketplace.deploy(); await nftMarketplace.deployed(); console.log("nftMarketplace deployed to:", nftMarketplace.address); fs.writeFileSync('./config.js', ` export const marketplaceAddress = "${nftMarketplace.address}" `)}main() .then(() => process.exit(0)) .catch((error) => { console.error(error); process.exit(1); });
- deploy.js -
- establish
config.js
file - Now in Polygon Mumbai Test online deployment of smart contracts
npx hardhat run scripts/deploy.js --network mumbai
After deployment , You can see the market contract address
If you are in the here No request , Must test in your account Matic To successfully deploy the contract
front end
In this part , We'll see how to align the deployed contract with the next js Front end correlation .
- install Tailwind CSS
npm install -D [email protected] [email protected] [email protected] tailwindcss init -p
- stay
tailwind.config.js
Configuration path
module.exports = { content: [ "./pages/**/*.{js,ts,jsx,tsx}", "./components/**/*.{js,ts,jsx,tsx}", ], theme: { extend: {}, }, plugins: [],}
- Delete
styles/globals.css
And update it as follows :
@tailwind base;@tailwind components;@tailwind utilities;
- Get into pages Folder , And create four
.js
filecreate.js
、myNft.js
,dashboard.js
andresellNft.js
. - open
_app.js
And edit as follows :
import '../styles/globals.css'import Link from 'next/link'function MyApp({ Component, pageProps }) { return ( <div> <nav className="border-b p-6"> <p className="text-4xl font-bold">Metaverse Marketplace</p> <div className="flex mt-4"> <Link href="/"> <a className="mr-4"> Home </a> </Link> <Link href="/create"> <a className="mr-6"> Create NFT </a> </Link> <Link href="/nftowns"> <a className="mr-6"> My NFTs </a> </Link> <Link href="/dashboard"> <a className="mr-6"> Dashboard </a> </Link> </div> </nav> <Component {...pageProps} /> </div> )}export default MyApp
- _app.js -
- open
index.js
And edit as follows :
import { ethers } from 'ethers'import { useEffect, useState } from 'react'import axios from 'axios'import Web3Modal from 'web3modal'import { marketplaceAddress} from '../config'import NFTMarketplace from '../artifacts/contracts/NFTMarketplace.sol/NFTMarketplace.json'export default function Home() { const [nfts, setNfts] = useState([]) const [loadingState, setLoadingState] = useState('not-loaded') useEffect(() => { loadNFTs() }, []) /* * map over items returned from smart contract and format * them as well as fetch their token metadata */ async function loadNFTs() { /* create a generic provider and query for unsold market items */ const provider = new ethers.providers.JsonRpcProvider("https://rpc-mumbai.maticvigil.com") //console.log('1.1. provider------Success', provider) //console.log('1.02. marketplaceAddress, NFTMarketplace.abi, provider----', marketplaceAddress, NFTMarketplace.abi, provider) const contract = new ethers.Contract(marketplaceAddress, NFTMarketplace.abi, provider) //console.log('1.2. contract------Success', contract) let data = null try { data = await contract.fetchMarketItems() //console.log('2.1. contract.fetchMarketItems------Success', data) } catch (error) { //console.log('2.2. contract.fetchMarketItems------failed', error) return toast.error(error || 'Error contract.fetchMarketItems') } /* * map over items returned from smart contract and format * them as well as fetch their token metadata */ try { const items = await Promise.all(data.map(async (i) => { const tokenUri = await contract.tokenURI(i.tokenId) const meta = await axios.get(tokenUri) const price = ethers.utils.formatUnits(i.price.toString(), 'ether') const item = { price, tokenId: i.tokenId.toNumber(), seller: i.seller, owner: i.owner, image: meta.data.image, name: meta.data.name, description: meta.data.description, } return item })) setNfts(items) setLoadingState('loaded') //console.log('3.1. get NFT List-----------Success', items) } catch (error) { //console.log('3.2. Error get NFT List-----------', error) setLoadingState('loaded') return toast.error(error || 'Error get NFT List') } } async function buyNft(nft) { /* needs the user to sign the transaction, so will use Web3Provider and sign it */ const web3Modal = new Web3Modal() let connection = null try { connection = await web3Modal.connect() //console.log('1.1. Connection-----------Success', connection) } catch (error) { //console.log('1.2. Connection-----------Error', error) return toast.error(error || 'Error Connection') } const provider = new ethers.providers.Web3Provider(connection) //console.log('2. provider-----------Success', provider) const signer = provider.getSigner() //console.log('3. signer-----------Success', signer) //console.log('4.01. marketplaceAddress, NFTMarketplace.abi, signer----', marketplaceAddress, NFTMarketplace.abi, signer) const contract = new ethers.Contract(marketplaceAddress, NFTMarketplace.abi, signer) //console.log('4.2. contract------Success', contract) /* user will be prompted to pay the asking proces to complete the transaction */ const price = ethers.utils.parseUnits(nft.price.toString(), 'ether') //console.log('5. price------Success', price) let transaction = null try { transaction = await contract.createMarketSale(nft.tokenId, { value: price }) //console.log('6.1. transaction-----------Success', transaction) } catch (error) { //console.log('6.2. transaction-----------Error', error) return toast.error(error || 'Error transaction') } try { await transaction.wait() loadNFTs() //console.log('7.1. transaction.wait-----------Success', transaction) } catch (error) { //console.log('7.2. transaction.wait-----------Error', error) return toast.error(error || 'Error transaction.wait') } } if (loadingState === 'loaded' && !nfts.length) return (<h1 className="px-20 py-10 text-3xl">No items in marketplace</h1>) return ( <div className="flex justify-center"> <div className="px-4" style={{ maxWidth: '1600px' }}> <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 pt-4"> { nfts.map((nft, i) => ( <div key={i} className="border shadow rounded-xl overflow-hidden"> <img src={nft.image} /> <div className="p-4"> <p style={{ height: '64px' }} className="text-2xl font-semibold">{nft.name}</p> <div style={{ height: '70px', overflow: 'hidden' }}> <p className="text-gray-400">{nft.description}</p> </div> </div> <div className="p-4 bg-black"> <p className="text-2xl font-bold text-white">{nft.price} ETH</p> <button className="mt-4 w-full bg-pink-500 text-white font-bold py-2 px-12 rounded" onClick={() => buyNft(nft)}>Buy</button> </div> </div> )) } </div> </div> </div> )}
- index.js -
- Edit as follows
create.js
establish NFT :
import { useState } from 'react'import { ethers } from 'ethers'import { create as ipfsHttpClient } from 'ipfs-http-client'import { useRouter } from 'next/router'import Web3Modal from 'web3modal'import { toast } from 'react-toastify'import { marketplaceAddress} from '../config'import NFTMarketplace from '../artifacts/contracts/NFTMarketplace.sol/NFTMarketplace.json'export default function CreateItem() { const [fileUrl, setFileUrl] = useState('') const [formInput, updateFormInput] = useState({ price: '', name: '', description: '' }) const router = useRouter() const client = ipfsHttpClient({ host: 'ipfs.infura.io', port: 5001, protocol: 'https', apiPath: 'api/v0' }) // convert image to URL async function onChange(e) { const file = e.target.files[0] try { const added = await client.add( file, // { // progress: (prog) => //console.log(`received: ${prog}`) // } ) const url = `https://ipfs.infura.io/ipfs/${added.path}` setFileUrl(url) } catch (error) { //console.log('Error uploading file: ', error) toast.error(error || 'Error on Onchange File') } } // upload to ipfs and return ipfs url async function uploadToIPFS() { const { name, description, price } = formInput if (!name || !description || !price || !fileUrl) return /* first, upload to IPFS */ const data = JSON.stringify({ name, description, image: fileUrl }) try { const added = await client.add(data) const url = `https://ipfs.infura.io/ipfs/${added.path}` /* after file is uploaded to IPFS, return the URL to use it in the transaction */ return url } catch (error) { //console.log('Error uploading file: ', error) toast.error(error || 'Error on uploadToIPFS') } } async function listNFTForSale() { const url = await uploadToIPFS() //console.log('1. uploadToIPFS Success------', url) const web3Modal = new Web3Modal() //console.log('2. Web3Modal------', web3Modal) let connection = null try { connection = await web3Modal.connect() //console.log('3.1. connection------success', connection) } catch (error) { //console.log('3.2. connection------failed', error) toast.error(error || 'Error on web3Modal Connect') } if (!connection) return const provider = new ethers.providers.Web3Provider(connection) //console.log('4. Provider ------success', provider) const signer = provider.getSigner() //console.log('5. signer ------success', signer) /* next, create the item */ if (!formInput.price) return toast.error('Please enter price') const price = ethers.utils.parseUnits(formInput.price, 'ether') //console.log('6. price ------success', price) //console.log('00.7. marketplaceAddress ------NFTMarketplace.abi, ---signer', marketplaceAddress, NFTMarketplace.abi, signer) const contract = new ethers.Contract( marketplaceAddress, NFTMarketplace.abi, signer ) //console.log('7. contract ------success', contract) let listingPrice = null try { listingPrice = await contract.getListingPrice() listingPrice = listingPrice.toString() //console.log('8.1. listingPrice------success', listingPrice) } catch (error) { //console.log('8.2. listingPrice------error', error) toast.error(error || 'Error on getListingPrice') } if (!listingPrice) return let transaction = null try { transaction = await contract.createToken(url, price, { value: listingPrice }) //console.log('9.1. contract.createToken------success', transaction) } catch (error) { //console.log('9.2. contract.createToken------error', error) toast.error(error?.data?.message || 'Error while creating token') } if (!transaction) return try { await transaction.wait() //console.log('10.1 transaction.wait------success') } catch (error) { //console.log('10.2 transaction.wait------error', error) toast.error(error || 'Error while transaction.wait') } //console.log(transaction); } return ( <div className="flex justify-center"> <div className="w-1/2 flex flex-col pb-12"> <input placeholder="Asset Name" className="mt-8 border rounded p-4" onChange={e => updateFormInput({ ...formInput, name: e.target.value })} /> <textarea placeholder="Asset Description" className="mt-2 border rounded p-4" onChange={e => updateFormInput({ ...formInput, description: e.target.value })} /> <input placeholder="Asset Price in Eth" className="mt-2 border rounded p-4" onChange={e => updateFormInput({ ...formInput, price: e.target.value })} /> <input type="file" name="Asset" className="p-4 w-80 rounded" onChange={onChange} /> { fileUrl && ( <div className="text-black">File Url: {fileUrl}</div> ) } <button onClick={listNFTForSale} className="font-bold mt-4 bg-gray-500 text-white rounded p-4 shadow-lg"> Create NFT </button> </div> </div> )}
- create.js -
- edit
myNft.js
:
import { ethers } from 'ethers'import { useEffect, useState } from 'react'import axios from 'axios'import Web3Modal from 'web3modal'import { useRouter } from 'next/router'import { marketplaceAddress} from '../config'import NFTMarketplace from '../artifacts/contracts/NFTMarketplace.sol/NFTMarketplace.json'export default function MyAssets() { const [nfts, setNfts] = useState([]) const [loadingState, setLoadingState] = useState('not-loaded') const router = useRouter() useEffect(() => { loadNFTs() }, []) async function loadNFTs() { const web3Modal = new Web3Modal({ network: "mainnet", cacheProvider: true, }) // console.log('1. web3Modal-------------success', web3Modal) let connection = null try { connection = await web3Modal.connect() // console.log('2.1. connection-------------success', connection) } catch (error) { // console.log('2.2. connection-------------error', error) return toast.error(error || 'Error web3Modal.connect') } const provider = new ethers.providers.Web3Provider(connection) // console.log('3. provider-------------success', provider) const signer = provider.getSigner() // console.log('4. signer-------------success', signer) // console.log('5.01. marketplaceAddress, NFTMarketplace.abi, signer----', marketplaceAddress, NFTMarketplace.abi, signer) const marketplaceContract = new ethers.Contract(marketplaceAddress, NFTMarketplace.abi, signer) // console.log('5.2. marketplaceContract----------Success', marketplaceContract) let data = null try { data = await marketplaceContract.fetchMyNFTs() // console.log('6.1. marketplaceContract.fetchMyNFTs-------------success', data) } catch (error) { // console.log('6.2. marketplaceContract.fetchMyNFTs-------------error', error) return toast.error(error || 'Error marketplaceContract.fetchMyNFTs') } try { const items = await Promise.all(data.map(async (i) => { const tokenURI = await marketplaceContract.tokenURI(i.tokenId) const meta = await axios.get(tokenURI) const price = ethers.utils.formatUnits(i.price.toString(), 'ether') const item = { price, tokenId: i.tokenId.toNumber(), seller: i.seller, owner: i.owner, image: meta.data.image, tokenURI } return item })) setNfts(items) setLoadingState('loaded') // console.log('7.1. get NFT List-----------Success', items) } catch (error) { // console.log('7.2. Error get NFT List-----------', error) setLoadingState('loaded') return toast.error(error || 'Error get NFT List') } } function listNFT(nft) { // console.log('nft:', nft) router.push(`/nft-demo/resell-nft?id=${nft.tokenId}&tokenURI=${nft.tokenURI}`) } if (loadingState === 'loaded' && !nfts.length) return (<h1 className="py-10 px-20 text-3xl">No NFTs owned</h1>) return ( <div className="flex justify-center"> <div className="p-4"> <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 pt-4"> { nfts.map((nft, i) => ( <div key={i} className="border shadow rounded-xl overflow-hidden"> <img src={nft.image} className="rounded" /> <div className="p-4 bg-black"> <p className="text-2xl font-bold text-white">Price - {nft.price} Eth</p> <button className="mt-4 w-full bg-pink-500 text-white font-bold py-2 px-12 rounded" onClick={() => listNFT(nft)}>List</button> </div> </div> )) } </div> </div> </div> )}
- myNft.js -
dashboard.js
:
import { ethers } from 'ethers'import { useEffect, useState } from 'react'import axios from 'axios'import Web3Modal from 'web3modal'import { marketplaceAddress} from '../config'import NFTMarketplace from '../artifacts/contracts/NFTMarketplace.sol/NFTMarketplace.json'export default function CreatorDashboard() { const [nfts, setNfts] = useState([]) const [loadingState, setLoadingState] = useState('not-loaded') useEffect(() => { loadNFTs() }, []) async function loadNFTs() { const web3Modal = new Web3Modal({ network: 'mainnet', cacheProvider: true, }) //console.log('1. web3Modal------success', web3Modal) let connection = null try { connection = await web3Modal.connect() //console.log('2.1. connection------success', connection) } catch (error) { //console.log('2.2. connection------failed', error) return toast.error(error || 'Error on web3Modal Connect') } const provider = new ethers.providers.Web3Provider(connection) //console.log('3. Provider ------success', provider) const signer = provider.getSigner() //console.log('4. signer ------success', signer) //console.log('005. marketplaceAddress ------NFTMarketplace.abi, ---signer', marketplaceAddress, NFTMarketplace.abi, signer) const contract = new ethers.Contract(marketplaceAddress, NFTMarketplace.abi, signer) //console.log('5. contract ------success', contract) let data = null try { data = await contract.fetchItemsListed() //console.log('6.1. contract fetchItemsListed------success', data) } catch (error) { //console.log('6.1. contract fetchItemsListed------success', error) return toast.error(error || 'Error contract fetchItemsListed') } try { const items = await Promise.all(data.map(async (i) => { const tokenUri = await contract.tokenURI(i.tokenId) const meta = await axios.get(tokenUri) const price = ethers.utils.formatUnits(i.price.toString(), 'ether') const item = { price, tokenId: i.tokenId.toNumber(), seller: i.seller, owner: i.owner, image: meta.data.image, } return item })) //console.log('7.1. get Token List-----------Success', items) setNfts(items) setLoadingState('loaded') } catch (error) { //console.log('7.2. Error get List-----------', error) setLoadingState('loaded') return toast.error(error || 'Error get List') } } if (loadingState === 'loaded' && !nfts.length) return ( <h1 className="text-xl p-4 w-96 my-10 mx-auto">No NFTs listed</h1> ) return ( <div> <div className="p-4"> <h2 className="text-2xl py-2">Items Listed</h2> <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 pt-4"> { nfts.map((nft, i) => ( <div key={i} className="border shadow rounded-xl overflow-hidden"> <img src={nft.image} className="rounded" /> <div className="p-4 bg-black"> <p className="text-2xl font-bold text-white">Price - {nft.price} Eth</p> </div> </div> )) } </div> </div> </div> )}
- dashboard.js -
- Last , edit
resellNft.js
:
import { ethers } from 'ethers'import { useEffect, useState } from 'react'import axios from 'axios'import Web3Modal from 'web3modal'import { useRouter } from 'next/router'import { marketplaceAddress} from '../config'import NFTMarketplace from '../artifacts/contracts/NFTMarketplace.sol/NFTMarketplace.json'export default function MyAssets() { const [nfts, setNfts] = useState([]) const [loadingState, setLoadingState] = useState('not-loaded') const router = useRouter() useEffect(() => { loadNFTs() }, []) async function loadNFTs() { const web3Modal = new Web3Modal({ network: "mainnet", cacheProvider: true, }) // console.log('1. web3Modal-------------success', web3Modal) let connection = null try { connection = await web3Modal.connect() // console.log('2.1. connection-------------success', connection) } catch (error) { // console.log('2.2. connection-------------error', error) return toast.error(error || 'Error web3Modal.connect') } const provider = new ethers.providers.Web3Provider(connection) // console.log('3. provider-------------success', provider) const signer = provider.getSigner() // console.log('4. signer-------------success', signer) // console.log('5.01. marketplaceAddress, NFTMarketplace.abi, signer----', marketplaceAddress, NFTMarketplace.abi, signer) const marketplaceContract = new ethers.Contract(marketplaceAddress, NFTMarketplace.abi, signer) // console.log('5.2. marketplaceContract----------Success', marketplaceContract) let data = null try { data = await marketplaceContract.fetchMyNFTs() // console.log('6.1. marketplaceContract.fetchMyNFTs-------------success', data) } catch (error) { // console.log('6.2. marketplaceContract.fetchMyNFTs-------------error', error) return toast.error(error || 'Error marketplaceContract.fetchMyNFTs') } try { const items = await Promise.all(data.map(async (i) => { const tokenURI = await marketplaceContract.tokenURI(i.tokenId) const meta = await axios.get(tokenURI) const price = ethers.utils.formatUnits(i.price.toString(), 'ether') const item = { price, tokenId: i.tokenId.toNumber(), seller: i.seller, owner: i.owner, image: meta.data.image, tokenURI } return item })) setNfts(items) setLoadingState('loaded') // console.log('7.1. get NFT List-----------Success', items) } catch (error) { // console.log('7.2. Error get NFT List-----------', error) setLoadingState('loaded') return toast.error(error || 'Error get NFT List') } } function listNFT(nft) { // console.log('nft:', nft) router.push(`/nft-demo/resell-nft?id=${nft.tokenId}&tokenURI=${nft.tokenURI}`) } if (loadingState === 'loaded' && !nfts.length) return (<h1 className="py-10 px-20 text-3xl">No NFTs owned</h1>) return ( <div className="flex justify-center"> <div className="p-4"> <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 pt-4"> { nfts.map((nft, i) => ( <div key={i} className="border shadow rounded-xl overflow-hidden"> <img src={nft.image} className="rounded" /> <div className="p-4 bg-black"> <p className="text-2xl font-bold text-white">Price - {nft.price} Eth</p> <button className="mt-4 w-full bg-pink-500 text-white font-bold py-2 px-12 rounded" onClick={() => listNFT(nft)}>List</button> </div> </div> )) } </div> </div> </div> )}
- resellNft.js -
function app
We can test now app 了
Run the command :
npm run dev
Link to the original text :https://betterprogramming.pub/create-a-full-stack-nft-marketplace-on-the-polygon-network-20176b3a9e33?source=user_profile---------1-------------------------------
copyright notice
author[A program ape],Please bring the original link to reprint, thank you.
https://en.netfreeman.com/2022/132/202205121208281569.html
The sidebar is recommended
- There is more than axie infinity in the field of p2e games. One article reviews the latest 5 chain games
- US SEC Commissioner Hester Peirce: the regulatory framework of stable currency needs to allow room for failure
- During token exchange, sometimes the transaction will fail, 'pancakerouter: expired'. What causes it?
- Ten thousand words long article captures the era value of ZK Rollup
- A good play by Luna, UST, anchor and LFG -- understand ust disturbing the encryption market sentiment in the past two days
- Is there a risk that the data will be monitored?
- CCR intelligent coin frying robot: what is the difference between bitcoin and traditional currency?
- Demand for cryptocurrency has increased significantly, and Nomura has launched bitcoin derivatives to Asian customers
- The panic of "big brother" crypto currency market began to subside
- Bear market Survival Guide: what are the potential airdrop opportunities for L2?
guess what you like
Would you like to ask if anyone has made a similar NAS mining machine scheme
What is the recommended research direction of blockchain?
On the underlying mathematical law of Luna crash from the change of hands of real gold and silver funds
What should educators know about the meta universe
Mount Tai, Mount Hua and other scenic spots have launched digital collections to help the cultural and tourism industry upgrade
ASUS confirmed that the demand for graphics cards for cryptocurrency mining is "disappearing"
Blockchain + supply chain: build a unified national market
Encrypted dark week: review of the $10 billion Terra ecological collapse
Inventory of 13 largest defi hackers and robberies in the history of cryptocurrency
Mount Tai, Mount Hua and other scenic spots have launched digital collections to help the cultural and tourism industry upgrade
Random recommended
- Bitcoin crash is now a chain reaction: listed companies have lost money, Tesla and Mito have become "leeks"
- [paper sharing] decentralized Society: looking for the soul of Web3 (Part 2)
- Bitcoin futures fell 17% this week
- Encrypted dark week: review of the $10 billion Terra ecological collapse
- Etherscan, coingecko and other encrypted data websites report malicious pop-up events to remind users not to confirm any transactions
- Guangzhou Radio Group: carry out blockchain business and promote the implementation of digital RMB application scenarios
- What imagination does yuancosmos bring to finance? A new version of the map will be opened for the banking, insurance and securities industries
- Aiyouteng lost money and the cinema closed down. Is the way out of the film in the meta universe?
- Meta universe weekly | Google develops instant translation ar glasses; The market scale of meta universe may be comparable to that of mobile phones; Meta integrates horizon ventures into its meta universe platform
- Beijing will provide legislative guarantee for the development of digital economy such as blockchain
- Use the transmitandswap function to interact with the smart contract. How do you generate the two parameters, auxiliarydata and thesignature
- web3. JS how to monitor the specific contract interaction of pending status
- Sendrawtransaction gets the original transaction data from the fox
- Using the graph to realize the 10000 times speed optimization of DAPP
- Ethereum real-time exchange rate acquisition
- Who is the next star group favorite after "boring ape"?
- The web 3 decentralization debate focused on the wrong issues
- Nansen: not just JPEG, how did bayc build the NFT Empire?
- It may be a good thing to talk about NFT falling into the altar
- Dao: a new possibility to realize "freedom to work"
- Twelve lessons learned from the terra crash
- TVL suffered the biggest decline in a single week and NFT market belief collapsed
- Nansen: not just JPEG, how did bayc build the NFT Empire?
- Luna: a gluttonous feast for arbitragers
- Diem, who broke Facebook's dream, still has blood flowing in the crypto industry
- 13 pictures to understand the investment and financing trend of blockchain industry in the first quarter of 2022
- Take advantage of Web3 "for the better": slowing down is faster
- How is the virtual human "living" in the meta universe? You don't know behind the skin bag
- How can ust and Luna save themselves from Terra's defeat and current situation?
- Tencent Ma Xiaoyi: NFT games are still very early. Cloud games are an infrastructure of the metauniverse
- How can ust and Luna save themselves from Terra's defeat and current situation?
- Algorithm stable currency ust thunder Luna fell from $90 to $0.05, and the "bloody" moment of cryptocurrency has come
- The founder of twitter said that the largest cryptocurrency exchange in the United States is a casino
- The "stable currency" is also unstable! Luna plummeted, approaching 1 cent, and 370000 overseas cryptocurrency players broke their positions
- The collapse of cryptocurrency wiped out more than $200 billion in wealth in one day
- The temporary decoupling of the TEDA coin from the US dollar scares the entire cryptocurrency world
- Coinbase, the largest cryptocurrency exchange in the United States, fell sharply for the sixth consecutive day, and its share price has fallen 80% this year
- Bitcoin once fell below $26000, and the value of cryptocurrency evaporated more than $200 billion a day
- The cryptocurrency market reappeared the selling frenzy, evaporating more than $200 billion a day
- Bloody wash! 170000 people broke their positions, and the "currency circle Maotai" Luna plunged 99%