[英]How to link my IPFS content to ERC721 contract?
我正在嘗試制作一個簡單的 ERC721 NFT 鑄幣合約。 我創建了一個圖像及其相應的元數據,並將它們上傳到 ipfs。 此圖像和元數據何時與智能合約中創建的令牌鏈接? 我試圖使用 Openzeppelin 合約向導生成的這段代碼:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
contract MyToken is ERC721, Ownable {
using Counters for Counters.Counter;
Counters.Counter private _tokenIdCounter;
constructor() ERC721("MyToken", "MTK") {}
function safeMint(address to) public onlyOwner {
uint256 tokenId = _tokenIdCounter.current();
_tokenIdCounter.increment();
_safeMint(to, tokenId);
}
}
但是我看不到在哪里可以將我的 nft 圖像和元數據鏈接到合同。 我已經看到,在 openzeppelin 的 ERC721 標准中,您可以使用函數tokenURI
和 _baseURI 設置基本 URI 和_baseURI
,但我不知道如何使用它們。 我計划創建一個多項目集合(在 ipfs 中),所以我不知道在我的情況下使用什么。
你寫的函數不夠用。 當你使用 NFT 時,你必須設置一些狀態變量。 您必須跟蹤列出的項目、令牌 ID、使用的令牌 URL。 (您的合約邏輯可能不同)。 此外,在鑄造令牌之前,您必須添加一些驗證語句。 首先定義你的狀態變量:
using Counters for Counters.Counter;
// initially 0
Counters.Counter private _listedItems;
Counters.Counter private _tokenIds;
uint public listingPrice=0.025 ether;
// mapping is similar to object in javascript
mapping(string=>bool) private _usedTokenURIs;
然后編寫鑄幣邏輯:
function mintToken(string memory tokenURI,uint price) public payable returns (uint){
// make sure you do not mint same uri
require( _usedTokenURIs[tokenURI]==false,"Token URI already exists");
// since this function is payable, the amount that you sent is stored in msg.value by ethereum evm
require(msg.value==listingPrice,"Price must be equal to listing fee");
_tokenIds.increment();
_listedItems.increment();
uint newTokenId=_tokenIds.current();
// this is a wrapper for _mint
_safeMint(msg.sender,newTokenId);
_setTokenURI(newTokenId, tokenURI);
_createNftItem(newTokenId,price);
// update _usedTokenURIs mapping
_usedTokenURIs[tokenURI]=true;
return newTokenId;
}
現在要將 ipfs 鏈接存儲在區塊鏈中,您必須在前端調用mintToken
函數。 您創建一個表單,添加與元數據相關的輸入,並將 json 元數據和圖像發布到 ipfs。 當您發布數據時,您將獲得 nft uri。 將 nft uri 存儲在狀態中。 然后你在前端寫一個 createNft 函數。 成功調用contract.mintToken
函數后,您的 ipfs 鏈接將存儲在區塊鏈上。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.