我已经开始研究如何使用 Solidity 和 IPFS 铸造 NFT。
项目流程为:
metadata.json
文件{
"name": "NFT",
"description": "This image shows the true nature of NFT.",
"image": "https://ipfs.io/ipfs/QmUnMkaEB5FBMDhjPsEtLyHr4ShSAoHUrwqVryCeuMosNr"
}
4:将此json文件上传到IPFS并获取其哈希url
https://ipfs.io/ipfs/QmNSKewexhgY4rYwPoxPgNFN7BSjeiLXJif9q5FjeCrsmg
5:创建具有铸币功能的
solidity
智能合约。使用 Polygon Mumbai 网络(使用 MATIC 令牌)进行部署。
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.6;
import "https://github.com/0xcert/ethereum-erc721/src/contracts/tokens/nf-token-metadata.sol";
import "https://github.com/0xcert/ethereum-erc721/src/contracts/ownership/ownable.sol";
contract newNFT is NFTokenMetadata, Ownable {
constructor() {
nftName = "Synth NFT";
nftSymbol = "SYN";
}
function mint(address _to, uint256 _tokenId, string calldata _uri) external onlyOwner {
super._mint(_to, _tokenId);
super._setTokenUri(_tokenId, _uri);
}
}
6:部署智能合约后,NFT 被铸造。
进入OpenSea测试网,选择Mumbai测试网,并插入NFT所有者的地址。
终于在测试网集合上看到NFT了。
但我想在 JavaScript、ReactJS 和 web3 库中以编程方式执行此操作。如何实现这一目标?
在 javascript 中有很多方法可以做到这一点。 如果您想在单个文件上完成所有操作,首先需要将文件部署到 IPFS。我建议使用少数现有 API 之一来简化操作,例如 Moralis、Nft.storage 或 Piñata。
使用 NFT.storage,您可以执行以下操作来部署到 IPFS:
const names = [
"Test nft 1",
"Test nft 2"
];
async function storeImage() {
const content = await fs.readFile(
path.resolve(__dirname, "../images/owl_articles.png")
);
const promisesToAwait: Promise<any>[] = [];
names.forEach((name) => {
promisesToAwait.push(
client.store({
name,
description: `At vero eos et accusamus et iusto odio dignissimos.`,
image: new File([content], "owl_articles.png", { type: "image/*" }),
})
);
});
const responses = await Promise.all(promisesToAwait);
console.log(responses);
}
async function main() {
await storeImage();
}
main();
上面的代码将把一组 json 文件部署到 IPFS,给定数组
names
。为了示例简单起见,它们都具有相同的 image
和 description
。
在道德中,你可以做类似的事情:
const jsonFile = new Moralis.File('file.json', {
base64: btoa(JSON.stringify({ name, description, image: imageURL }))
});
上面的代码也将部署到 ipfs,但以不同的方式。 我现在不知道为什么,但是虽然这种 Moralis 方法将其部署为
ipfs://{hash}
NFt.storage 方法将其部署为 ipfs://{hash}/metadata.json
。
无论如何,在使用上述任何流程之后,您必须通过 URI 作为参数来铸造您的 NFT。
使用道德,你可以这样做:
const jsonIpfsLink = `ipfs://${(jsonFile as any).hash()}/metadata.json`;
await Moralis.Web3.executeFunction({
...options,
functionName: 'create',
params: {
_initialSupply: '10',
_uri: jsonIpfsLink
}
});
上面的代码正在调用我的 ERC1155 合约中的方法
create
。合约方式如下图:
/**
* @dev Creates a new token type and assigns _initialSupply msg.sender address
* @param _initialSupply amount to supply the first owner
* @param _uri URI for this token
*/
function create(uint256 _initialSupply, string memory _uri) public {
_uris[lastId.current()] = _uri;
creators[lastId.current()] = msg.sender;
_mint(msg.sender, lastId.current(), _initialSupply, "");
emit ArticleMinted(msg.sender, _uri, lastId.current(), _initialSupply);
lastId.increment();
}
我的示例使用 ERC1155 模式,但在 ERC721 模式上应该非常相似。看来您在合同中没有使用它们,但我强烈建议您这样做。 此外,Moralis 会让您的生活更轻松。我建议在您的前端项目中使用它。
我正在创建一个 NFT 市场,我几乎使用上面的代码来部署到 IPFS 并在之后立即进行铸造。