iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
😗

How to Mint NFTs with Custom Contracts: A Guide to Fully Understanding NFTs

に公開
2022/06/27

In this article, I will explain how to issue an NFT using a custom contract for those who don't understand blockchain at all. The goal is to reach the so-called "I completely understand it" level.

Also, since it's only been about two months since I started catching up on these technologies, there might be some errors. I would appreciate it if you could point them out.

Prerequisite Knowledge

First, there are many things to understand as prerequisite knowledge, so I will briefly organize each of them. Development in the blockchain world is different from the regular web world in many ways, so it's important to grasp the overall picture first.

Basic Terminology

Starting a conversation about NFTs abruptly might be overwhelming due to the number of unfamiliar terms, so I will first provide a rough image of each term that will appear. Note that to keep things simple, the focus will be on Ethereum.

  • Blockchain
    • Public database
  • Node
    • The PCs and servers of blockchain participants worldwide are called nodes. These connect to form a blockchain network.
  • Wallet
    • Something necessary to access the blockchain network. Inside is a set of a public key and a private key. In the regular Web world, it's like an email address and a password. It's common to be installed as a browser extension. For Ethereum, MetaMask is famous.
    • For now, it's okay to understand it as Wallet = Account and Wallet Address = Public Key.
  • Ethereum
    • One of many blockchains in the world. In Ethereum, a cryptocurrency called ETH is used.
  • Smart Contract
    • It's not precise, but it's easy to imagine it as something like an app (or a class) that can be deployed to the blockchain network. By writing this program called a smart contract, various systems and activities such as currency transactions and NFT issuance can be developed.
    • Each smart contract has its own storage and memory, where information such as the ID of the issued NFT and how many were issued can be stored.
  • Token
    • Both FT (e.g., cryptocurrency) and NFT (Non-FT, meaning things that aren't FT) are digital representations of objects in the form of tokens. It might be abstract and not click, but these tokens are at the center of data flowing through the blockchain. For example, by writing a smart contract, you can record a transfer of tokens on the blockchain, such as "sending Ebata-san's cryptocurrency (token) to Irie-san."
  • Gas Fee
    • Money required to record something on the blockchain or deploy a smart contract. In Ethereum, it's paid as ETH. Part of this ETH is paid to nodes performing so-called mining.
    • This gas fee fluctuates based on the safety guarantees of the blockchain network and supply and demand. In Ethereum, demand has exploded due to the rising NFT fever, and gas fees are currently very high. It can sometimes cost 10,000 to 20,000 yen to issue an NFT on your own.

For now, knowing just this is enough to understand the overall picture of contracts in the blockchain network. It's good to have at least a minimum image like "participating in a blockchain network with a unique account called a wallet."

There are many other things I want to write about, such as consensus algorithms, transaction mechanisms, Web 3.0 in general, and IPFS, but there's no end to it if I start explaining. If you want to know more, the official Ethereum documentation is very, very easy to understand, so I recommend giving it a read.

https://ethereum.org/en/developers/docs/

About NFTs

As mentioned earlier, an NFT (Non-Fungible Token) is a token that can represent something unique. Digital data such as illustrations and photos, or even movie tickets, can be handled as NFTs depending on the application.

To get a bit technical, for Ethereum, a standard called ERC721 has been established. This defines a common interface so that details like how tokens are transferred, who owns them, and how many exist on the network can be understood. Contracts that implement NFTs must implement these interfaces as methods.

For example, there is a method called tokenURI(uint256 _tokenId) defined in ERC721, which is designed to return a URL such as "https://enftxamplebucket.s3.amazonaws.com/my-tokens/" + _tokenId. In this case, if the argument _tokenId is 42, it returns https://enftxamplebucket.s3.amazonaws.com/my-tokens/42. Accessing that URL should return a simple JSON like the following:

{
  "name": "Juice=Juice",
  "image": "https://enftxamplebucket.s3.amazonaws.com/assets/hoge.jpeg",
  "external_url": "http://www.helloproject.com/juicejuice/",
  "description": "We are J=J."
}

By including the URL of the image you want to sell as an NFT in the image field, marketplaces (NFT sales sites such as OpenSea, Foundation, and Rarible) can call this through the common interface to understand "which image should be displayed for this NFT?".

The Significance of Custom Contracts

Actually, on these marketplaces, as long as you have your own wallet, you can sell NFTs with a feeling similar to uploading an image to a photo-sharing site, without writing a custom smart contract. However, if you don't issue it with a custom contract, technically the marketplace issues the NFT, so the initial owner of the NFT will not be the creator. If you want to avoid this, your only option is to issue the NFT with a custom contract to own it yourself first, and then sell that NFT on the marketplace of your choice.

Diving deep into the advantages and disadvantages of this further would be a distraction, so I'll leave the details to the following link:
https://note.com/cryptopilot/n/n1383f5093b68

Let's actually write it

Now, let's actually implement a smart contract. Here are the simple specifications:

  • Only the person who deployed the contract can issue NFTs.
  • NFT IDs are auto-incremented (this refers to the "42" part in a URL like https://enftxamplebucket.s3.amazonaws.com/my-tokens/42).

Tools to use

  • Node.js
    • Used for running scripts.
    • Prepare an appropriate version (v12 or higher) using nodenv or similar.
  • Hardhat
    • A tool that provides a full development environment, from compiling and deploying smart contracts to setting up a blockchain network for local development.
    • Install via npm.
  • Solidity
    • Ethereum's unique language for writing smart contracts. No need to install a runtime yourself.

Preparing the development environment

Assuming Node is already available.

First, create a development template with hardhat.

mkdir minimal-nft
cd minimal-nft
npm init --yes
npm install --save-dev hardhat
npm install @openzeppelin/contracts web3
npx hardhat

You will be asked What do you want to do?, so select Create a basic sample project. This will generate the template.

Once everything is created, run the following to check if the tests pass. If it says 1 passing, you're good to go.

npx hardhat test

Writing the contract

Delete contracts/Greeter.sol, create contracts/MYNFT.sol, and write the following code.

//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.4;

import "hardhat/console.sol";
import "@openzeppelin/contracts/token/ERC721/presets/ERC721PresetMinterPauserAutoId.sol";

contract MYNFT is ERC721PresetMinterPauserAutoId {
    constructor()
        ERC721PresetMinterPauserAutoId("MYNFT", "nft", "https://enftxamplebucket.s3.amazonaws.com/my-tokens/")
    {}
}

That's it for the contract. If anything, https://enftxamplebucket.s3.amazonaws.com/my-tokens/ is important. This URL will be the base for the NFT content URL.

For a simple NFT, you can just inherit the library provided by OpenZeppelin, so there's no need to define anything else.

Deployment (Local Network)

First, let's start a network in the local environment and try deploying the contract we just wrote. Running the following will create a local network and simultaneously generate about 20 accounts, each with 10,000 ETH.

npx hardhat node

Next, delete scripts/sample-script.js, create scripts/deploy.js, and write the following code.

scripts/deploy.js
const hre = require("hardhat");

async function main() {
  const NFT = await hre.ethers.getContractFactory("MYNFT");
  const nft = await NFT.deploy();

  await nft.deployed();

  console.log("NFT deployed to:", nft.address);
}

main()
  .then(() => process.exit(0))
  .catch((error) => {
    console.error(error);
    process.exit(1);
  });

Then, open another tab and run the following:

npx hardhat run --network localhost scripts/deploy.js

You should see a message like MYNFT deployed to: 0x5FbDB2315678afecb367f032d93F642f64180aa3, so make a note of the 0x5FbDB2315678afecb367f032d93F642f64180aa3 part.

Issuing the NFT

First, create scripts/mint.js and write the following code.

For CONTRACT_ADDRESS, use the one you just noted. For PUBLIC_KEY and PRIVATE_KEY, choose Account #0: from the accounts automatically created when you ran npx hardhat node. Set the address of Account #0: as PUBLIC_KEY and its Private Key: as PRIVATE_KEY. (* By default, the account used for deployment is Account #0. Currently, we have set it up so that only the account that deployed the contract can issue NFTs.)

scripts/mint.js
const Web3 = require("web3");

// ADDRESS, KEY and URL are examples.
const CONTRACT_ADDRESS = "0x5FbDB2315678afecb367f032d93F642f64180aa3";
const PUBLIC_KEY = "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266";
const PRIVATE_KEY =
  "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80";
const PROVIDER_URL = "http://localhost:8545";

async function mintNFT() {
  const web3 = new Web3(PROVIDER_URL);
  const contract = require("../artifacts/contracts/MYNFT.sol/MYNFT.json");
  const nftContract = new web3.eth.Contract(contract.abi, CONTRACT_ADDRESS);
  const nonce = await web3.eth.getTransactionCount(PUBLIC_KEY, "latest");
  const tx = {
    from: PUBLIC_KEY,
    to: CONTRACT_ADDRESS,
    nonce: nonce,
    gas: 500000,
    data: nftContract.methods.mint(PUBLIC_KEY).encodeABI(),
  };

  const signPromise = web3.eth.accounts.signTransaction(tx, PRIVATE_KEY);
  signPromise
    .then((signedTx) => {
      const tx = signedTx.rawTransaction;
      if (tx !== undefined) {
        web3.eth.sendSignedTransaction(tx, function (err, hash) {
          if (!err) {
            console.log("The hash of your transaction is: ", hash);
          } else {
            console.log(
              "Something went wrong when submitting your transaction:",
              err
            );
          }
        });
      }
    })
    .catch((err) => {
      console.log("Promise failed:", err);
    });
}

mintNFT();

Then, run the following. This will issue an NFT with Token ID 1 to the account set in PUBLIC_KEY. If you run it again, an NFT with Token ID 2 will be issued.

npx hardhat run --network localhost scripts/mint.js

Verification

To verify if the NFT was issued correctly, create scripts/view.js. This script will allow you to display the number of tokens owned.

Enter the CONTRACT_ADDRESS and PUBLIC_KEY as you did previously.

scripts/view.js
const Web3 = require("web3");

// ADDRESS, KEY and URL are examples.
const CONTRACT_ADDRESS = "0x5FbDB2315678afecb367f032d93F642f64180aa3";
const PUBLIC_KEY = "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266";
const PROVIDER_URL = "http://localhost:8545";

async function viewNFT() {
  const web3 = new Web3(PROVIDER_URL);
  const contract = require("../artifacts/contracts/MYNFT.sol/MYNFT.json");
  const nftContract = new web3.eth.Contract(contract.abi, CONTRACT_ADDRESS);
  nftContract.methods.balanceOf(PUBLIC_KEY).call().then(console.log);
}

viewNFT();

Then, run the following. You should see the count of how many times you executed scripts/mint.js displayed.

npx hardhat run --network localhost scripts/view.js

Deployment (Test Network / Main Network)

There are several points to keep in mind when deploying to networks other than the local environment.

  • First, once a smart contract is deployed, it basically cannot be changed. If there is a security issue, you're stuck. Therefore, you must thoroughly verify it in local and test environments before deploying.
  • Additionally, deployment costs gas fees. For ETH, this usually exceeds several thousand yen, so proceed with caution.
  • You'll need your own wallet. Install MetaMask.

Keeping these in mind, I will explain how to deploy to an external network.

Wallet Setup

First, install the MetaMask Chrome Extension. Then, complete the new registration.

Now that you have your own wallet (account), you'll perform the deployment using this wallet address and the wallet's private key. In the previous local environment, we used Account #0; now, that will simply be replaced by your own wallet's information.

By the way, it goes without saying, but if you expose your wallet's private key, you're doomed, so be extremely careful. The same applies to your passphrase.

Preparing to connect to the network

Addendum
Since this is an old article, I am explaining with Ropsten below, but Ropsten will be shut down in the future due to The Merge. Therefore, please use Goerli as your testnet.

Regarding how to connect to test networks or the main network: locally, the node exists only on your own machine, and the blockchain, contracts, and accounts are all contained within that node. However, to connect to an external network, you must first connect to a node belonging to the network you wish to join.

There are several services that provide nodes already connected to the network, so we will use one of those. Here, we will use Alchemy. Infura is another option, and either is fine.

I'll skip the registration process for Alchemy, but what you need is an HTTP URL, like https://eth-ropsten.alchemyapi.io/v2/abcddddaeeaonviabibviasiexample, which you can obtain from the "VIEW KEY" section after creating a project. By executing the deployment against this URL, just as we did locally, the contract will become usable on the network.

Alchemy allows you to choose between the Ethereum and Polygon blockchains. Since we will only go as far as deploying to a test network (honestly, gas fees are too high to deploy to the mainnet...), we'll proceed assuming the Ropsten network on Ethereum is selected.

Ropsten is one of the test networks existing on Ethereum. There are others like Kovan, Rinkeby, and Goerli. You are free to use whichever you like. I chose Ropsten this time because the faucet was still barely functioning. Naturally, gas fees occur even on test networks, but you don't need to use real ETH. A faucet is a place to obtain cryptocurrency that can only be used on test networks. I used the Ropsten Ethereum Faucet. After entering your wallet address (the public key, not the private key) into the form and waiting, test ETH will be sent to your wallet. However, it's common to wait up to a day for it to be sent, so you may need to be patient or look for other faucets. As long as you avoid sites that ask for your private key, passphrase, or excessive wallet permissions, you should be fine.

Deployment configuration

Edit hardhat.config.js as follows.

hardhat.config.js
require("@nomiclabs/hardhat-waffle");

task("accounts", "Prints the list of accounts", async (taskArgs, hre) => {
  const accounts = await hre.ethers.getSigners();

  for (const account of accounts) {
    console.log(account.address);
  }
});

/**
 * @type import('hardhat/config').HardhatUserConfig
 */
module.exports = {
  solidity: "0.8.4",
  networks: {
    ropsten: {
      url: "Ropsten URL obtained from Alchemy",
      accounts: "Your wallet's private key",
    },
    mainnet: {
      url: "Ethereum mainnet URL obtained from Alchemy",
      accounts: "Your wallet's private key",
    },
  },
};

With this, you can deploy by running the following command. However, this assumes you have enough gas in your wallet. If you haven't received anything from a faucet, you won't even be able to deploy.

npx hardhat run --network ropsten scripts/deploy.js

Issuing/Verifying NFTs

Change the PUBLIC_KEY and PRIVATE_KEY in the scripts we used for the local environment to your own wallet's address and private key, and update the PROVIDER_URL to the URL you obtained from Alchemy. After that, just run the scripts by changing the --network parameter to the name of the network you want to use.

About Content Uploading

I mentioned earlier that a URL like https://enftxamplebucket.s3.amazonaws.com/my-tokens/42 should return a JSON that conforms to ERC721. So, in reality, you also need to ensure that https://enftxamplebucket.s3.amazonaws.com/my-tokens/42 returns JSON.

For example, in the above case, you would first place a JSON file named 42 in S3. It is important that the token ID when the NFT is issued matches the file name.

{
  "name": "Juice=Juice",
  "image": "https://enftxamplebucket.s3.amazonaws.com/assets/hoge.jpeg",
  "external_url": "http://www.helloproject.com/juicejuice/",
  "description": "We are J=J."
}

The contents of the JSON file can be as above for now. Don't forget to upload the image mentioned in image to S3 as well.

After that, if the issued NFT ID is 1, you place a JSON file named 1 in the same location on S3, and if it's 2, you place a JSON file named 2. This is how the NFT issued by the contract is linked to the image URL indicated by the JSON file.

Some people might wonder, "Wait, aren't the images on the blockchain??" That's correct; basically, they are not on the chain. What's on the chain is only the record of "who owns which NFT". If the JSON file returned by the URL https://enftxamplebucket.s3.amazonaws.com/my-tokens/42 disappears, that's it. You will end up holding a token of nothingness.

Therefore, it is recommended to use IPFS (a system that splits and distributes files across decentralized nodes in a P2P manner, like a blockchain) so that they don't disappear as much as possible. If you use the Brave browser, you can access content with an IPFS protocol URL like ipfs://ipfs.io/Qme7ss3ARVgxv6rXqVPiikMJ8u2NLgmgszg13pYrDKEoiu. Note that Chrome does not support it yet.

Summary

I have mainly explained Ethereum smart contracts and NFTs, along with a simple implementation of how to issue an NFT using a custom contract. The code is available on GitHub.

https://github.com/YuheiNakasaka/minimal-nft

Also, my study notes are loosely organized in Zenn scraps, which might be helpful to see the order in which I was studying.

https://zenn.dev/razokulover/scraps/b85e061d8c06fd

Additionally, there are many good learning resources for Ethereum, so I'll briefly introduce them below. They are all in English, but it's impossible to avoid English because you can't get decent information on Blockchain (especially smart contracts and Web 3.0) otherwise. I think it'll be tough if you can't read at least at the level of the Ethereum documentation.

Finally, if this article was helpful, I would appreciate it if you could tip me some ETH, Polygon, etc.
0xfB9AaE55f46F03a2FF53882b432Fbf52Fc6B668F

For anything else, feel free to contact me at @razokulover, and I might respond if I feel like it.

Discussion