Home  >  Article  >  Learn how to display NFT collectibles on Flow and IPFS: an NFT tutorial

Learn how to display NFT collectibles on Flow and IPFS: an NFT tutorial

王林
王林forward
2024-01-26 19:54:26891browse

php editor Zimo brings you a tutorial on displaying NFT collections on Flow and IPFS. As a highly discussed digital asset in recent years, NFT has gradually become popular in fields such as art, music, and games. This tutorial will teach you how to use the Flow and IPFS platforms to display and share your NFT collections, allowing you to better display and promote your digital art works. Whether you are a beginner or an experienced NFT collector, this tutorial will provide you with comprehensive guidance and techniques so that you can easily showcase your creations. Let's dive into this exciting world of digital collectibles!

In this article, we will build a simple React application that interacts with the Flow smart contract to verify and obtain user-owned NFTs. We will also parse the NFT's metadata to obtain the IPFS location of the NFT's underlying asset (in this case, the video). The app is similar to NBA Top Shot, but it showcases different video content.

Learn how to display NFT collectibles on Flow and IPFS: an NFT tutorial

Project settings

In this tutorial, you need to use the Flow simulator. If you forget how to start the emulator, you can check out the previous article or the Flow CLI documentation. It should be noted that the Flow simulator is a tool that simulates the Flow blockchain in memory. If you closed the emulator, you need to continue with the following steps:

Start the Flow emulator
Deploy the project
Mint your NFT
In the first part of this tutorial NFT Tutorial - Using Flow and IPFS Creating NFTs details each of these steps.

In addition, NodeJS needs to be installed on your machine. You can install it here.

As before, you need a text editor.

Initialize React and install dependencies

Create the React application in the pinata-party project directory created in the first part of the tutorial (you can also create your React application in a brand new directory).

To create our application, run the following command:

npx create-react-app pinata-party-frontend

When everything is installed, you will have a new directory called pinata-party-frontend, switch to that directory, Install dependencies.

First, refer to the Flow documentation and you need to install the Flow JS SDK. For the front-end settings, we only need to follow Flow's documentation:

npm i @onflow/fcl @onflow/types

Some values ​​need to be stored as global variables of the application, and environment variables are used here. In react, create a .env file and set key-value pairs, where the key-value prefix is ​​REACT_APP. In Flow's documentation, set it to connect to Flow's testnet. In this tutorial we will connect to the Flow emulator. So, some changes need to be made. Add the following content to the .env file:

REACT_APP_ACCESS_NODE=http://localhost:8080REACT_APP_WALLET_DISCOVERY=https://fcl-discovery.onflow.org/testnet/authnREACT_APP_CONTRACT_PROFILE=0xf8d6e0586b0a20c7

Replace the value of REACT_APP_ACCESS_NODE with the local emulator url mentioned above. Replace the REACT_APP_CONTRACT_PROFILE value with the address obtained when deploying the project.

You also need to create a configuration file to interact with the Flow JS SDK. Create a file named config.js in the src directory. Add the following:

import {config} from "@onflow/fcl"config().put("accessNode.api", process.env.REACT_APP_ACCESS_NODE) .put("challenge.handshake", process.env.REACT_APP_WALLET_DISCOVERY) .put("0xProfile", process.env.REACT_APP_CONTRACT_PROFILE)

This configuration file just helps the JS SDK work with the Flow blockchain (or the emulator in this case). To make this file available throughout the application, open the index.js file and add this line.

import "./config"

Now, let’s connect some authentication. If you don't want to, you don't have to force people to authenticate to enter the website. In the third article of the tutorial, authentication will be very important when implementing the transfer of NFT assets.

We need to create an authentication component. In your src directory, create a file called AuthCluster.js. Inside the file, add the following:

import React, {useState, useEffect} from 'react'import * as fcl from "@onflow/fcl"const AuthCluster = () => {  const [user, setUser] = useState({loggedIn: null})  useEffect(() => fcl.currentUser().subscribe(setUser), [])  if (user.loggedIn) {    return (      <div>        <span>{user?.addr ?? "No Address"}</span>        <button className="btn-primary" onClick={fcl.unauthenticate}>Log Out</button>      </div>    )  } else {    return (      <div>        <button className="btn-primary" onClick={fcl.logIn}>Log In</button>        <button className="btn-secondary" onClick={fcl.signUp}>Sign Up</button>      </div>    )  }}export default AuthCluster//  rawAuthCluster.js 

The code is simple, using a login and register button, leveraging the ability of the Flow JS SDK to connect to the wallet provider, you can register an account or log in with an existing account .

Now we need to put this component into our application. Let’s keep it simple first. Replace your App.js file with the following content.

import './App.css';import AuthCluster from './AuthCluster';function App() {  return (    <div className="App">      <AuthCluster />    </div>  );}export default App;

If you start the application now (npm start), you should see a page with login and register buttons. In fact, both buttons are functional, give it a try.

Okay, now that the React app is basically set up, let’s start building the NFTs that get accounts and display them.

Getting NFTs from Flow

In order to display the NFT we minted in the first article, communication with the Flow blockchain is required. Now it's time to communicate with the Flow simulator. When you set up the .env file, you tell the application that the emulator is running on port 8080. But now, how do you interact with Flow using JavaScript?

Luckily, Flow has this functionality built into their JS SDK. If you remember, we previously wrote a script that looked up an NFT based on its token id and returned the token's metadata. It looks like this:

import PinataPartyContract from 0xf8d6e0586b0a20c7pub fun main() : {String : String} {    let nftOwner = getAccount(0xf8d6e0586b0a20c7)    // log("NFT Owner")        let capability = nftOwner.getCapability<&{PinataPartyContract.NFTReceiver}>(/public/NFTReceiver)    let receiverRef = capability.borrow()        ?? panic("Could not borrow the receiver reference")    return receiverRef.getMetadata(id: 1)}

CheckTokenMetadata.cdc

现在,我们只需要将其转换为 JavaScript 调用即可。 让我们创建一个新的组件,既能获取数据,又能最终显示 NFT 数据。 在你的 src 目录下,创建一个名为 TokenData.js 的文件。 在该文件中,添加以下内容:

import React, { useState } from "react";import * as fcl from "@onflow/fcl";const TokenData = () => {  const [nftInfo, setNftInfo] = useState(null)  const fetchTokenData = async () => {    const encoded = await fcl      .send([        fcl.script`        import PinataPartyContract from 0xf8d6e0586b0a20c7        pub fun main() : {String : String} {          let nftOwner = getAccount(0xf8d6e0586b0a20c7)            let capability = nftOwner.getCapability<&{PinataPartyContract.NFTReceiver}>(/public/NFTReceiver)                let receiverRef = capability.borrow()              ?? panic("Could not borrow the receiver reference")                return receiverRef.getMetadata(id: 1)        }      `      ])        const decoded = await fcl.decode(encoded)    setNftInfo(decoded)  };  return (    <div className="token-data">      <div className="center">        <button className="btn-primary" onClick={fetchTokenData}>Fetch Token Data</button>              </div>      {        nftInfo &&        <div>          {            Object.keys(nftInfo).map(k => {              return (                <p>{k}: {nftInfo[k]}</p>              )            })          }          <button onClick={() => setNftInfo(null)} className="btn-secondary">Clear Token Info</button>        </div>      }    </div>  );};export default TokenData;//rawTokenData.js  

在这个文件中,创建了一个组件,有一个按钮来获取代币数据。 当点击获取按钮时,它会调用我们创建的一个名为 fetchTokenData 的函数。 该函数使用 Flow JS SDK 来执行与在本教程第一部分中从命令行执行的脚本完全相同的脚本,但在 React 中。 我们把执行的结果,设置到一个名为 nftInfo 的状态变量中。React 会根据 nftInfo 显示 NFT 元数据中的键值对。另外还有一个让清除数据的按钮。

我还加了一点 CSS,让他漂亮一些,App.css 定义如下:

.App {  display: flex;  flex-direction: column;  min-height: 500px;  justify-content: center;  align-items: center;}button {  padding: 10;  height: 30px;  min-width: 100px;  cursor: pointer;}.btn-primary {  border: none;  background: rgb(255, 224, 0);  color: #282828;}.btn-secondary {  border: none;  background: rgb(0, 190, 221);  color: #282828;}.center {  text-align: center;}.token-data {  margin-top: 100px;}

现在,只要将新组件添加到 App.js 中,放在 AuthCluster 组件下面:

import './App.css';import AuthCluster from './AuthCluster';import TokenData from './TokenData';function App() {  return (    <div className="App">      <AuthCluster />      <TokenData />    </div>  );}export default App;

运行应用程序并尝试获取代币数据,它应该是这样:

Learn how to display NFT collectibles on Flow and IPFS: an NFT tutorial

这真是太酷了! 我们正在查找指定的账户所拥有的 NFT,然后从该代币中获取元数据。 并显示该元数据,我们知道该元数据中的一个值解析为一个视频文件。 让我们把它显示出来。

从IPFS获取媒体文件

你已经注册了一个 Pinata 账户,并通过 Pinata 上传界面将你的视频文件添加到 IPFS。 这意味着你已经可以从 IPFS 中获取内容了。 在 Pin Explorer 中,当你点击一个哈希值时,你会被带到 Pinata IPFS 网关,在那里你的 IPFS 内容被解析并显示。 为了教程更通用,我们还是从 Protocol Labs 网关中获取它。

回到 TokenData.js 文件中,让我们添加一个方法来显示从 IPFS 中检索到的视频文件,修改代码:

import React, { useState } from "react";import * as fcl from "@onflow/fcl";const TokenData = () => {  const [nftInfo, setNftInfo] = useState(null)  const fetchTokenData = async () => {    const encoded = await fcl      .send([        fcl.script`        import PinataPartyContract from 0xf8d6e0586b0a20c7        pub fun main() : {String : String} {          let nftOwner = getAccount(0xf8d6e0586b0a20c7)            let capability = nftOwner.getCapability<&{PinataPartyContract.NFTReceiver}>(/public/NFTReceiver)                let receiverRef = capability.borrow()              ?? panic("Could not borrow the receiver reference")                return receiverRef.getMetadata(id: 1)        }      `      ])        const decoded = await fcl.decode(encoded)    setNftInfo(decoded)  };  return (    <div className="token-data">      <div className="center">        <button className="btn-primary" onClick={fetchTokenData}>Fetch Token Data</button>              </div>      {        nftInfo &&        <div>          {            Object.keys(nftInfo).map(k => {              return (                <p>{k}: {nftInfo[k]}</p>              )            })          }          <div className="center video">            <video id="nft-video" canplaythrough controls width="85%">              <source src={`https://ipfs.io/ipfs/${nftInfo["uri"].split("://")[1]}`}                    type="video/mp4" />            </video>            <div>              <button onClick={() => setNftInfo(null)} className="btn-secondary">Clear Token Info</button>            </div>          </div>                  </div>      }    </div>  );};export default TokenData;//  rawTokenData.js 

我们已经添加了一个 video 标签,它指向 IPFS 上的文件。 你会注意到,这里拆分了 uri 值,以获得 IPFS 哈希值,这样就可以从 IPFS 网关获取对应内容。 先介绍下那个 URI。

我们用 NFT 创建的 uri 看起来像 ipfs://Qm...。 我们之所以这样创建,是因为 IPFS 桌面客户端默认允许你点击并打开这样的链接。 另外,Brave 浏览器也支持粘贴这样的链接。 并且我们认为这种链接形式会随着 IPFS 的发展得到越来越多的支持。

然而,在这里下,我们需要在利用哈希来从 IPFS 公共网关获取内容,并在页面上显示。因此链接会是这样:

https://ipfs.io/ipfs/QmRZdc3mAMXpv6Akz9Ekp1y4vDSjazTx2dCQRkxVy1yUj6

现在,如果你访问我们的应用程序中获取代币数据,会看到如下界面:

Learn how to display NFT collectibles on Flow and IPFS: an NFT tutorial

这是一个真正的活的数字资产! 你的视频可能会有所不同,但希望你在应用中感受到相同的体验。

最后

这是一个非常简单的应用,你可以做很多事情让它变得更漂亮,让它的交互性更强,甚至可以为它添加更多的 Flow 元素。 Flow JS SDK 的功能很强大,所以我推荐大家阅读一下文档。

在第二部分成功地使用 Flow 为应用添加了身份验证,创建了一个接口来获取 NFT 的信息,创建了一种方法来显示了原始元数据以及对应的底层标的资产。 这一切都由 Flow 区块链和 IPFS 来保障。 我们知道 NFT 是由谁拥有,也知道显示的内容是有效性,因为哈希值被编码到 NFT 中。

在本教程的最后一篇,我们将专注于创建一个迷你交易市场,让我们转移 NFT。

The above is the detailed content of Learn how to display NFT collectibles on Flow and IPFS: an NFT tutorial. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:jb51.net. If there is any infringement, please contact admin@php.cn delete