6

I have started studying how to mint an NFT using solidity and IPFS.

The project flow is:

  1. Install IPFS
  2. Upload asset photo by IPFS and get its hash
  3. Create a metadata.json file using the above hash
{
  "name": "NFT",
  "description": "This image shows the true nature of NFT.",
  "image": "https://ipfs.io/ipfs/QmUnMkaEB5FBMDhjPsEtLyHr4ShSAoHUrwqVryCeuMosNr"
}

4: Upload this json file to IPFS and get its hash url

https://ipfs.io/ipfs/QmNSKewexhgY4rYwPoxPgNFN7BSjeiLXJif9q5FjeCrsmg

5: Create a solidity smart contract with a minting function. Deploy this using Polygon Mumbai network (using MATIC token).

 // 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: After deploying the smart contract, the NFT is minted.

MINT

  1. Go to OpenSea testnet, chose Mumbai testnet, and insert the address of the NFT owner.

  2. Finally see the NFT on the testnet collection.

But I want to do this programatically in JavaScript, ReactJS and web3 library. How to achieve this?

Robin Thomas
  • 1,317
  • 8
  • 15

1 Answers1

0

There are many ways to do this in javascript. If you want to do it all on a single file, first you need to deploy your files to IPFS. I recommend using one of the few existing APIs to make it easier, such as Moralis, Nft.storage or Piñata.

With NFT.storage, you can do something like this to deploy to 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();

The peice of code above will deploy an array of json files to IPFS, given the array names. They all have the same image and description for the sake of simplicity of the example.

In moralis, you can do something similar:

const jsonFile = new Moralis.File('file.json', {
        base64: btoa(JSON.stringify({ name, description, image: imageURL }))
});

The code above will also deploy to ipfs, but in a different way. I don't know why right now, but while this Moralis approach deploys it with ipfs://{hash} NFt.storage approach deploys it as ipfs://{hash}/metadata.json.

Anyway, after you use any of the processes above, you have to mint your NFT passing the URI as a param.

Using moralis, you can do it like this:

      const jsonIpfsLink = `ipfs://${(jsonFile as any).hash()}/metadata.json`;

      await Moralis.Web3.executeFunction({
        ...options,
        functionName: 'create',
        params: {
          _initialSupply: '10',
          _uri: jsonIpfsLink
        }
      });

The code above is calling the method createfrom my ERC1155 contract. The contract method is shown below:

    /**
     * @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();
    }

My example uses ERC1155 pattern, but it should be very similar on ERC721 pattern. It looks like you are using neither of them in your contract, but I strongly advise you to. Also, Moralis would make your life easier. I would suggest using it in your front-end project.

I'm making a NFT marketplace and I use pretty much the code above to deploy to IPFS and mint right after.