当前位置:网站首页>NFT system development - Tutorial
NFT system development - Tutorial
2022-07-27 10:02:00 【51CTO】
- First step : install web3
- The first 2 Step : establish mint-nft.js file
- The first 3 Step : Get your contract ABI
- The first 4 Step : Use IPFS For you NFT Configuration metadata
- The first 5 Step : Create an instance of the contract
- The first 6 Step : to update .env file
- The first 7 Step : Create your transaction
- The first 8 Step : Sign a deal
- The first 9 Step : call mintNFT And run the node contract-interact.js
They all use Alchemy Powerful API Cast their NFT. In this tutorial , We will teach you how to 10 Complete the same operation in minutes .
“ Casting NFT” Is to publish your... On the blockchain ERC-721 The behavior of a unique instance of a token . Use book NFT Tutorial Series No 1 Smart contracts in section , Let's show our web3 Skills and create NFT. At the end of this tutorial , You will be able to follow your heart ( And wallets ) Need to cast as many as possible NFT!
Let's get started !
First step : install WEB3
If you follow the instructions about creating NFT The first tutorial of smart contract , Then you already have access to Ethers.js Experience .Web3 Be similar to Ethers, Because it is a library to make it easier to create requests for Ethereum blockchain . In this tutorial , We will use Alchemy Web3, This is an enhanced web3 library , Provides automatic retry and powerful WebSocket Support .
Run... In your project home directory :
1npm install @alch/alchemy-web32
The first 2 Step : establish MINT-NFT.JS file
In your script directory , Create a mint-nft.js File and add the following line of code :
1 need (“dotenv” ). To configure ()2const API_URL = process .ENV .API_URL 3const { createAlchemyWeb3 } = need (“@alch/alchemy-web3” ) 4const web3 = createAlchemyWeb3 ( API_URL ) 5 Copy
The first 3 Step : Get your contract ABI
Our contract ABI( Application Binary Interface ) It is the interface to interact with our smart contract . You can learn about the contract here ABI For more information . The helmet will automatically generate a ABI And save it in MyNFT.json In file . To use it , We need to add the following lines of code to mint-nft.js File to parse the content :
1const contract = require ( "../artifacts/contracts/MyNFT.sol/MyNFT.json" ) 2 Copy
If you want to see ABI, You can print it to your console :
1 Console . journal (JSON . String ( contract .ABI ))2 Copy
To run mint-nft.js And view the... Printed to the console ABI, Please navigate to your terminal and run
1 Node script / mint - nft .js2 Copy
The first 4 Step : Use IPFS For you NFT Configuration metadata
If you still remember that we are in the 1 Part of the tutorial , our mintNFT The smart contract function accepts a tokenURI Parameters , This parameter should resolve to a description NFT Metadata JSON file —— This is what makes NFT Lifelike reasons , Allow it to have configurable properties , For example, as a name 、 describe 、 Images and other properties .
Interstellar file system (IPFS) It's a decentralized protocol and a point-to-point network , Used to store and share data in a distributed file system .
We will use the convenient IPFS API And the kit Pinata To store our NFT Assets and metadata , To make sure our NFT Really decentralizing . If you don't Pinata account , Please register a free account here and complete the steps to verify your email .
After creating an account :
- Navigate to “ file ” page , Then click the blue in the upper left corner of the page “ Upload ” Button .
- Upload the image to pinata — This will be your NFT Image assets . Name any asset you want
- After the upload , You will be at “ file ” See the file information in the table of the page . You will also see CID Column . You can copy by clicking the copy button next to CID. You can view your upload in the following location :
https://gateway.pinata.cloud/ipfs/<CID>. for example , You can find us here at IPFS Images used on .
For more intuitive learners , The above steps are summarized as follows :
Now? , We're going to upload another file to Pinata. But before we do that , We need to create it !
In your root directory , Create a file called nft-metadata.json And add the following json Code :
1{2 “ attribute ” :[ 3 {4 "trait_type" : " Varieties " , 5 “ value ” :“ Martip ” 6 } ,7 {8 "trait_type" : " Eye color " , 9 “ value ” :“ mocha ” 10 }11 ] ,12 “ describe ” :“ The cutest in the world 、 The most sensitive dog .” , 13 " picture " : " https://gateway.pinata.cloud/ipfs/QmWmvTJmJU3pozR9ZHFmQC2DNDwi2XJtf3QGyYiiagFSWb" , 14 “ name ” :“ Ramses ” 15}16 Show all Copy
Change at will json Data in . You can delete or add to the Properties section . most important of all , Make sure the image field points to your IPFS The location of the image —— otherwise , Your NFT Will include a ( Very cute !) Pictures of dogs .
complete json After editing the file , Save it and upload it to Pinata, Follow the same steps we did for uploading images .

The first 5 Step : Create an instance of the contract
Now? , In order to interact with our contract , We need to create an instance of it in our code . So , We need our contract address , We can find the address you use to deploy the contract from deployment or Etherscan Get the address in .
In the example above , Our contract address is 0x81c587EB0fE773404c42c1d2666b5f557C470eED.
Next we will use web3 Use of contract method ABI Create our contract with the address . In your mint-nft.js In file , Add the following :
1const contractAddress = "0x81c587EB0fE773404c42c1d2666b5f557C470eED" 23const nftContract = new web3 . The etheric . contract ( contract .ABI ,contractAddress ) 4 Copy
The first 6 Step : to update .ENV file
Now? , To create a transaction and send it to the Ethereum chain , We will use your public Ethereum account address to obtain the account random number ( It will be explained below ).
Add your public key to .env In file —— If you have completed the... Of this tutorial 1 part , our .env The file should now look like this :
1API_URL = " https://eth-ropsten.alchemyapi.io/v2/your-api-key" 2PRIVATE_KEY = " Your private account address " 3PUBLIC_KEY = " Your public account address " 4 Copy
The first 7 Step : Create your transaction
First , Let's define a function called mintNFT(tokenData) And create our transaction by doing the following :
- From file obtain Your PRIVATE_KEY and PUBLIC_KEY
.env. - Next , We need to calculate the random number of accounts .nonce The specification is used to track the number of transactions sent from your address —— This is what we need for security purposes and to prevent replay . To get the number of transactions sent from your address , We use getTransactionCount.
- Last , We will use the following information to set up our transaction :
-
'from': PUBLIC_KEY — The source of our transaction is our public address -
'to': contractAddress — We want to interact with it and send the contract of the transaction -
'nonce': nonce — Random number of accounts with the number of transactions sent from our address -
'gas': estimatedGas — Estimate required to complete the transaction gas -
'data': nftContract.methods.mintNFT(PUBLIC_KEY, md).encodeABI() — The calculations we wish to perform in this transaction — In this case, it is casting NFT
Yours mint-nft.js The file should now look like this :
1 need ( 'dotenv' ) . To configure ();2 const API_URL = process .ENV .API_URL ; 3 const PUBLIC_KEY = process .ENV . The public key ; 4 const PRIVATE_KEY = process .ENV .PRIVATE_KEY ; 56 const { createAlchemyWeb3 } = requirement (“@alch/alchemy-web3” ); 7 const web3 = createAlchemyWeb3 ( API_URL ) ; 89 const contract = require ( "../artifacts/contracts/MyNFT.sol/MyNFT.json" ) ; 10 const contractAddress = "0x81c587EB0fE773404c42c1d2666b5f557C470eED" ; 11 const nftContract = new web3.eth.Contract(contract.abi, contractAddress);1213 async function mintNFT(tokenURI) {14 const nonce = await web3.eth.getTransactionCount(PUBLIC_KEY, 'latest'); //get latest nonce1516 //the transaction17 const tx = {18 'from': PUBLIC_KEY,19 “ To ” : Contract address ,20 ' Present ' : Present ,21 'gas' : 500000 , 22 “ data ” :nftContract . Method .mintNFT ( PUBLIC_KEY , tokenURI ) . code ABI ( )23 } ;24 }25 Show all Copy
The first 8 Step : Sign a deal
Now we have created our transaction , We need to sign it to send it . This is where we will use our private key .
web3.eth.sendSignedTransaction Will give us a deal , We can use it to ensure that our transactions are mined and not discarded by the network . You will notice in the transaction signature section , We added some error checking , So that we can know whether our transaction is successful or not .
1 need (“dotenv” ). To configure ( )2const API_URL = process .ENV .API_URL 3const PUBLIC_KEY = process .ENV .PUBLIC_KEY 4const PRIVATE_KEY = process .ENV .PRIVATE_KEY 56const { createAlchemyWeb3 } = need (“@alch/alchemy-web3” ) 7const web3 = createAlchemyWeb3 ( API_URL ) 89const contract = require ( "../artifacts/contracts/MyNFT.sol/MyNFT.json" ) 10const contractAddress = "0x81c587EB0fE773404c42c1d2666b5f557C470eED" 11const nftContract = new web3 . The etheric . contract ( contract .ABI ,contractAddress ) 1213async function mintNFT(tokenURI) {14 const nonce = await web3.eth.getTransactionCount(PUBLIC_KEY, "latest") //get latest nonce1516 //the transaction17 const tx = {18 from: PUBLIC_KEY,19 to: contractAddress,20 nonce: nonce,21 gas: 500000,22 data: nftContract.methods.mintNFT(PUBLIC_KEY, tokenURI).encodeABI(),23 }2425 const signPromise = web3.eth.accounts.signTransaction(tx, PRIVATE_KEY)26 signPromise27 .then((signedTx) => {28 web3.eth.sendSignedTransaction(29 signedTx.rawTransaction,30 function (err, hash) {31 if (!err) {32 console.log(33 "The hash of your transaction is: ",34 hash,35 "\nCheck Alchemy's Mempool to view the status of your transaction!"36 )37 } else {38 console.log(39 "Something went wrong when submitting your transaction:",40 err41 )42 }43 }44 )45 })46 .catch((err) => {47 Console . journal (“ Promises fail :” , error )48 } )49}50 Show all Copy
The first 9 Step : call MINTNFT And run the node CONTRACT-INTERACT.JS
Remember you uploaded to Pinata Of metadata.json Do you ? from Pinata Get its hash code and pass the following as parameters to the function mintNFThttps://gateway.pinata.cloud/ipfs/<metadata-hash-code>
Here's how to get the hash code :
How to be in Pinata Get your nft Metadata hash code
By loading into a separate window , Carefully check whether the hash code you copied is linked to your metadata.json
https://gateway.pinata.cloud/ipfs/<metadata-hash-code>. This page should look like the following screenshot :

Your page should show json Metadata
To make a long story short , Your code should look like this :
1 need (“dotenv” ). To configure ( )2const API_URL = process .ENV .API_URL 3const PUBLIC_KEY = process .ENV .PUBLIC_KEY 4const PRIVATE_KEY = process .ENV .PRIVATE_KEY 56const { createAlchemyWeb3 } = need (“@alch/alchemy-web3” ) 7const web3 = createAlchemyWeb3 ( API_URL ) 89const contract = require ( "../artifacts/contracts/MyNFT.sol/MyNFT.json" ) 10const contractAddress = "0x81c587EB0fE773404c42c1d2666b5f557C470eED" 11const nftContract = new web3 . The etheric . contract ( contract .ABI ,contractAddress ) 1213 An asynchronous function mintNFT ( tokenURI ) { 14 const nonce = await web3.eth.getTransactionCount(PUBLIC_KEY, "latest") //get latest nonce1516 //the transaction17 const tx = {18 from: PUBLIC_KEY,19 to: contractAddress,20 nonce: nonce,21 gas: 500000,22 data: nftContract.methods.mintNFT(PUBLIC_KEY, tokenURI).encodeABI(),23 }2425 const signPromise = web3.eth.accounts.signTransaction(tx, PRIVATE_KEY)26 signPromise27 .then((signedTx) => {28 web3.eth.sendSignedTransaction(29 signedTx.rawTransaction,30 function (err, hash) {31 if (!err) {32 console.log(33 "The hash of your transaction is: ",34 hash,35 "\nCheck Alchemy's Mempool to view the status of your transaction!"36 )37 } else {38 console.log(39 "Something went wrong when submitting your transaction:",40 err41 )42 }43 }44 )45 })46 .catch((err) => {47 Console . journal (“ Promises fail :” , error )48 } )49}5051 mint NFT (52 “ https://gateway.pinata.cloud/ipfs/QmYueiuRNmL4MiA2GwtVMm6ZagknXnSpQnB3z2gWbz36hP”53)54 Show all Copy
Now? , function node scripts/mint-nft.js To deploy your NFT. After a few seconds , You should see the following response in the terminal :
1 The hash value of your transaction is :0x10e5062309de0cd0be7edc92e8dbab191aa2791111c44274483fa766039e0e0023 Check Alchemy To view your transaction status !4
Next , Visit your Alchemy Memory pool to view your transaction status ( Whether it's pending 、 Mined or discarded by the network ). If your transaction is deleted , Check Ropsten Etherscan And searching your transaction hash is also helpful .

stay Etherscan View your NFT Transaction hash
this is it ! You have now deployed and cast on the Ethereum blockchain NFT
Use mint-nft.js, You can according to your heart ( And wallets ) Need to cast as many as possible NFT! Just make sure you pass in a new tokenURI To describe NFT Metadata ( otherwise , You'll end up making a bunch of different ID The same thing about ).
边栏推荐
- Understand chisel language. 27. Chisel advanced finite state machine (I) -- basic finite state machine (Moore machine)
- QT | about the problem that QT creator cannot open the project and compile it
- July training (day 09) - two point search
- Brush the title "sword finger offer" day03
- How does data analysis solve business problems? Here is a super detailed introduction
- Interview JD T5, was pressed on the ground friction, who knows what I experienced?
- How to use tdengine sink connector?
- 如何在树莓派上安装cpolar内网穿透
- After one year, the paper was finally accepted by the international summit
- 达梦 PARTGROUPDEF是自定义的对象吗?
猜你喜欢

3D修复论文:Shape Inpainting using 3D Generative Adversarial Network and Recurrent Convolutional Networks

What happens if the MySQL disk is full? I really met you!

NFT系统开发-教程

Dcgan paper improvements + simplified code

I haven't delivered books for a long time, and I feel uncomfortable all over

Food safety | is sugar free really sugar free? These truths need to be known

直播倒计时 3 天|SOFAChannel#29 基于 P2P 的文件和镜像加速系统 Dragonfly
![WordPress prohibits login or registration of plug-ins with a specified user name [v1.0]](/img/94/92ad89751e746a18edf80296db9188.png)
WordPress prohibits login or registration of plug-ins with a specified user name [v1.0]

Shell综合应用案例,归档文件、发送消息

Case of burr (bulge) notch (depression) detection of circular workpiece
随机推荐
LeetCode.565. 数组嵌套____暴力dfs->剪枝dfs->原地修改
How to install cpolar intranet penetration on raspberry pie
Acl2021 best paper released, from ByteDance
3D人脸重建:Joint 3D Face Reconstruction and Dense Alignment with position Map Regression Network
Overview of PCL modules (1.6)
Nacos configuration center dynamically refreshes the data source
Concurrent Park and unpark description
原生input标签的文件上传
July training (day 09) - two point search
3D修复论文:Shape Inpainting using 3D Generative Adversarial Network and Recurrent Convolutional Networks
如何在树莓派上安装cpolar内网穿透
Engineering survey simulation volume a
Shell中的文本处理工具、cut [选项参数] filename 说明:默认分隔符是制表符、awk [选项参数] ‘/pattern1/{action1}filename 、awk 的内置变量
刷题《剑指Offer》day03
Review summary of engineering surveying examination
安装了HAL库如何恢复原来的版本
Shell的正则表达式入门、常规匹配、特殊字符:^、$、.、*、字符区间(中括号):[ ]、特殊字符:\、匹配手机号
Live countdown 3 days sofachannel 29 P2P based file and image acceleration system Dragonfly
File upload of native input tag
Explain knative cloud function framework in simple terms!