如何通过 javascript 代码将元数据 json 上传到 IPFS 以及如何通过前端以编程方式生成此 URL

6 javascript solidity web3js

我已经开始研究如何使用 Solidity 和 IPFS 铸造 NFT。

项目流程为:

  1. 安装IPFS
  2. 通过IPFS上传资产照片并获取其哈希值
  3. metadata.json使用上面的哈希创建一个文件
{
  "name": "NFT",
  "description": "This image shows the true nature of NFT.",
  "image": "https://ipfs.io/ipfs/QmUnMkaEB5FBMDhjPsEtLyHr4ShSAoHUrwqVryCeuMosNr"
}
Run Code Online (Sandbox Code Playgroud)

4:将此json文件上传到IPFS并获取其哈希url

https://ipfs.io/ipfs/QmNSKewexhgY4rYwPoxPgNFN7BSjeiLXJif9q5FjeCrsmg
Run Code Online (Sandbox Code Playgroud)

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);
  }
}
Run Code Online (Sandbox Code Playgroud)

6:部署智能合约后,NFT 被铸造。

薄荷

  1. 进入 OpenSea 测试网,选择孟买测试网,并插入 NFT 所有者的地址。

  2. 终于看到测试网集合上的NFT了。

但我想在 JavaScript、ReactJS 和 web3 库中以编程方式执行此操作。如何实现这一目标?

Ped*_*lin 0

在 javascript 中可以通过多种方法执行此操作。\n如果您想在单个文件上完成所有操作,首先需要将文件部署到 IPFS。我建议使用少数现有 API 之一来简化操作,例如 Moralis、Nft.storage 或 Pi\xc3\xb1ata。

\n

使用 NFT.storage,您可以执行以下操作来部署到 IPFS:

\n
\nconst names = [\n  "Test nft 1",\n  "Test nft 2"\n];\n\nasync function storeImage() {\n  const content = await fs.readFile(\n    path.resolve(__dirname, "../images/owl_articles.png")\n  );\n\n  const promisesToAwait: Promise<any>[] = [];\n\n  names.forEach((name) => {\n    promisesToAwait.push(\n      client.store({\n        name,\n        description: `At vero eos et accusamus et iusto odio dignissimos.`,\n        image: new File([content], "owl_articles.png", { type: "image/*" }),\n      })\n    );\n  });\n\n  const responses = await Promise.all(promisesToAwait);\n  console.log(responses);\n}\n\nasync function main() {\n  await storeImage();\n}\n\nmain();\n
Run Code Online (Sandbox Code Playgroud)\n

上面的代码将把一组 json 文件部署到 IPFS,给定数组names。为了示例简单起见,它们都有相同的内容imagedescription

\n

在道德中,你可以做类似的事情:

\n
const jsonFile = new Moralis.File(\'file.json\', {\n        base64: btoa(JSON.stringify({ name, description, image: imageURL }))\n});\n
Run Code Online (Sandbox Code Playgroud)\n

上面的代码也将部署到 ipfs,但以不同的方式。 \n我现在不知道为什么,但是虽然此 Moralis 方法使用ipfs://{hash}NFt.storage 方法将其部署为ipfs://{hash}/metadata.json.

\n

无论如何,在使用上述任何过程之后,您必须通过 URI 作为参数来创建 NFT。

\n

使用道德,你可以这样做:

\n
      const jsonIpfsLink = `ipfs://${(jsonFile as any).hash()}/metadata.json`;\n\n      await Moralis.Web3.executeFunction({\n        ...options,\n        functionName: \'create\',\n        params: {\n          _initialSupply: \'10\',\n          _uri: jsonIpfsLink\n        }\n      });\n
Run Code Online (Sandbox Code Playgroud)\n

上面的代码正在调用我的 ERC1155 合约中的方法create。合约方式如下图:

\n
    /**\n     * @dev Creates a new token type and assigns _initialSupply msg.sender address\n     * @param _initialSupply amount to supply the first owner\n     * @param _uri URI for this token\n     */\n    function create(uint256 _initialSupply, string memory _uri) public {\n        _uris[lastId.current()] = _uri;\n        creators[lastId.current()] = msg.sender;\n        _mint(msg.sender, lastId.current(), _initialSupply, "");\n        emit ArticleMinted(msg.sender, _uri, lastId.current(), _initialSupply);\n        lastId.increment();\n    }\n
Run Code Online (Sandbox Code Playgroud)\n

我的示例使用 ERC1155 模式,但它在 ERC721 模式上应该非常相似。看来您在合同中没有使用它们,但我强烈建议您这样做。\n此外,Moralis 会让您的生活更轻松。我建议在您的前端项目中使用它。

\n

我正在创建一个 NFT 市场,我使用上面的代码来部署到 IPFS 并立即进行铸造。

\n