How to Mint an NFT with ChatGPT, Infura, and Truffle

Learn how to use ChatGPT with Infura and Truffle to mint your next NFT.

How to Mint an NFT with ChatGPT, Infura, and Truffle

Learn how to use ChatGPT with Infura and Truffle to mint your next NFT.

In part one of the ChatGPT + Infura series, we learned four ways you can use ChatGPT to improve your dapp development: asking questions, compiling code, testing code, and practice coding to improve your skills. In part two, you’ll learn how to use ChatGPT and Infura to mint an NFT.

The most valuable aspect of incorporating ChatGPT into my development process has been the time I save compiling my smart contract code. Having said that, let’s go over a quick disclaimer before we start minting.

ChatGPT Disclaimer  

Although ChatGPT is good at explaining relevant web3 concepts and in some cases, even auditing code for security loopholes, the answers it provides are not always accurate. ChatGPT can produce code that is wrong or worse, riddled with loopholes that a bad actor could take advantage of.

Therefore, although ChatGPT can be used to significantly speed up the development process, it is NOT a replacement for a developer with strong fundamentals. Nor is it advisable to use code generated by ChatGPT unless you can verify the code yourself.

Keep in mind, ChatGPT is only aware of development practices up to 2021 and in a fast-paced industry like web3, this can be an issue.

Step 1: Install MetaMask and Acquire SepoliaETH

In order to deploy smart contracts locally or to a public blockchain, you’ll need a web3 wallet and some gas for the blockchain you wish to deploy to.

If you don’t have a wallet installed, one of the most reliable and easy to use is MetaMask. You can install the MetaMask wallet as an extension for your web browser. Setting up the wallet is fairly straightforward. Follow the instructions given by MetaMask carefully, and save your wallet’s secret phrase in a secure location.

You can switch to the Sepolia test network by clicking the Network tab on the top-right of your extension and then, clicking on show/hide networks. Once MetaMask displays test networks, switch to Sepolia.

If this is your first time using Sepolia, chances are you won’t have any SepoliaETH. Fortunately, it’s easy to acquire some for free using the Infura faucet. Once this is done, you should see up to .5 test Sepolia ETH in your wallet:

Step 2: Setup an Infura Sepolia RPC endpoint

To send requests to the Sepolia network in order to deploy smart contracts and mint NFTs, you first need an RPC endpoint. This is easy to do with Infura!

Simply create an Infura account and set up a new project. You can create an Infura account here. Next, you can generate a Sepolia RPC endpoint by creating a new key here.

Choose Web3 API from the network dropdown. You can name the key anything you want. Keep in mind that you can use a single key to power multiple projects. Infura RPCs are capable of processing thousands of requests a day for free.

Creating a key will give you access to a number of blockchain networks, including the Ethereum mainnet and Sepolia.

Your Sepolia RPC endpoint will be of the following format:

sepolia.infura.io/vs/<YOUR API KEY>

Step 3: Set up the NFT Project using Truffle

Let’s now set up a Truffle project, and install all necessary packages and libraries required to write NFT smart contracts. Truffle is a development framework with tooling and devnets to compile and test your code.

First, make sure you have a node and npm installed by running the follow prompt:

$ node -v

$ npm -v

If you get a version number for each command, you’re good. If not, install both on your local machine here and try again.

Once you have the node installed, go ahead and set up the project with these steps:

  1. Create an empty node repository.
  2. Install Truffle and set up a new project.
  3. Install OpenZeppelin to get access to base implementations of the ERC-721 standard.
  4. Install hdwalletprovider for wallet and key management.
  5. Install dotenv for secret keeping.

Next, run the following commands one after the other:

$ mkdir my-nft && cd my-nft
$ npm init -y

$ npm install –save truffle

$ npx truffle init && npx truffle test

$ npm install @openzeppelin/contracts @truffle/hdwallet-provider dotenv

Step 4: Create an OpenAI account and access ChatGPT

At the time of writing this, version 3.5 of ChatGPT is free to use. All you need is a free OpenAI account. You can create one here and access ChatGPT’s interface here. It will look like this:

Get comfortable with the interface by asking it some questions like what are some of EE. Cummings’ best poems? Or what is the difference between Solidity and Rust programming languages?

Step 5: Ask ChatGPT to Generate NFT Smart Contract Code

Now, let’s prompt ChatGPT to create an NFT smart contract by with these instructions:

I want to create an NFT smart contract.


The contract will mint a single NFT and assign a URL that points to its metadata.

Use OpenZeppelin as the base for this contract.

ChatGPT will produce an output that looks something like this:

Sure, here's an example of an NFT smart contract that mints a single NFT and assigns a URL pointing to its metadata using OpenZeppelin as the base:


```

// SPDX-License-Identifier: MIT


pragma solidity ^0.8.0;


import "@openzeppelin/contracts/token/ERC721/ERC721.sol";

import "@openzeppelin/contracts/utils/Counters.sol";


contract MyNFT is ERC721 {

    using Counters for Counters.Counter;

    Counters.Counter private _tokenIds;

    string private _metadataUrl;


    constructor(string memory name, string memory symbol, string memory metadataUrl) ERC721(name, symbol) {

        _metadataUrl = metadataUrl;

    }


    function mintNFT(address recipient) public returns (uint256) {

        _tokenIds.increment();


        uint256 newItemId = _tokenIds.current();

        _mint(recipient, newItemId);

        _setTokenURI(newItemId, _metadataUrl);


        return newItemId;

    }

}

```


In this example, we import `ERC721` from OpenZeppelin, which provides the core functionality for creating NFTs. We also use `Counters` to keep track of the token IDs and `_metadataUrl` to store the URL for the NFT metadata.


The constructor takes three parameters: `name` and `symbol`, which are used to identify the NFT, and `metadataUrl`, which is the URL for the NFT metadata.


The `mintNFT` function takes an `address` argument for the recipient of the NFT and returns the ID of the newly minted token. It increments the token ID using `Counters`, mints a new token using `_mint`, and sets the token URI using `_setTokenURI` with the `_metadataUrl` value.


You can deploy this contract to your preferred Ethereum network using a tool like Remix or Truffle, and then call the `mintNFT` function to mint a new NFT and assign its metadata URL.

As you can see, the code snippet that ChatGPT provides is mostly correct.

The only mistake is in importing ERC721 instead of ERC721Storage, which has the implementation of the _setTokenURI method.

It also gives a very useful explanation of what the code does.

Next, create a new file in the contracts folder called MyNft.sol and copy-paste the following corrected code:

// SPDX-License-Identifier: MIT


pragma solidity ^0.8.0;


import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";

import "@openzeppelin/contracts/utils/Counters.sol";


contract MyNft is ERC721URIStorage {

    using Counters for Counters.Counter;

    Counters.Counter private _tokenIds;

    string private _metadataUrl;


    constructor(string memory name, string memory symbol, string memory metadataUrl) ERC721(name, symbol) {

        _metadataUrl = metadataUrl;

    }


    function mintNFT(address recipient) public returns (uint256) {

        _tokenIds.increment();


        uint256 newItemId = _tokenIds.current();

        _mint(recipient, newItemId);

        _setTokenURI(newItemId, _metadataUrl);


        return newItemId;

    }

}

Step 6: Configure Truffle Settings

Now let’s configure Truffle so that we’re able to deploy this smart contract to the Sepolia network. Replace the contents of truffle-config.js with the following:

require('dotenv').config();

const HDWalletProvider = require('@truffle/hdwallet-provider');

const { INFURA_API_KEY, MNEMONIC } = process.env;


module.exports = {

  networks: {

    development: {

      host: "127.0.0.1",

      port: 8545,

      network_id: "*"

    },

    sepolia: {

      provider: () => new HDWalletProvider(MNEMONIC, INFURA_API_KEY),

      network_id: '11155111',

    },

  },

  compilers: {

    solc: {

      version: "0.8.19",

    }

  }

};

We don’t want to expose private information such as wallet key or your Infura API key when uploading your project to a service like GitHub.

Therefore, let’s create a .env file to store our secrets. Add the following to the aforementioned file.

INFURA_API_KEY = "https://sepolia.infura.io/v3/<Your-API-Key>"

MNEMONIC = "<Your-MetaMask-Secret-Recovery-Phrase>"

We’re all set! Let’s compile the smart contract from the previous step by running:

npx truffle compile

Step 7: Upload NFT Image and Metadata to Infura IPFS (Optional)

Next, you can upload the image and the metadata representing the NFT to the internet, using a decentralized storage system like IPFS. Note that uploading your own image and metadata is optional for this tutorial.

Infura has a service that allows you to do this. However, since ChatGPT has a knowledge cutoff of 2021, it’s not in a position to give you instructions on how to use this service. Infura has useful documentation on how to do this here.

If you do not wish to do so, you can simply use the metadata we provide here: ipfs://QmUyZoK21qb8YknXGfDB34RTY8vMqPb6Bsj9U9iLEnyrZR

This is the image we’ll convert into an NFT:


You can open this IPFS link by pasting it directly in the address bar of a compatible browser like Brave.

Step 8: Deploy the NFT smart contract to Sepolia

Now you can deploy your smart contract to Sepolia so let’s ask ChatGPT for the deployment script with the prompt below:

Okay, now give me a script that deploys this contract to Sepolia. I am using Truffle.

ChatGPT will give you a response that looks something like this:

Sure, here's an example script that deploys the NFT smart contract you provided to the Sepolia test network using Truffle:


1. First, make sure you have Truffle installed globally. You can install it by running `npm install -g truffle`.


2. In the root directory of your Truffle project, create a new JavaScript file (e.g. `deploy.js`) and paste the following code:


```

const MyNFT = artifacts.require("MyNFT");


module.exports = async function(deployer) {

  const name = "My NFT";

  const symbol = "NFT";

  const metadataUrl = "https://example.com/metadata.json";

  await deployer.deploy(MyNFT, name, symbol, metadataUrl);

};

```


In this code, we first import the `MyNFT` contract. Then, in the `module.exports` function, we define the `name`, `symbol`, and `metadataUrl` values, and use `deployer.deploy` to deploy the contract with these values.


3. In your terminal, navigate to the root directory of your Truffle project and run `truffle migrate --network ropsten`. This will deploy the contract to the Sepolia test network.


Make sure to replace `ropsten` with the name of the network you want to deploy to in your `truffle-config.js` file.


4. Once the migration is complete, you can check the Sepolia test network to confirm that the contract has been deployed.


That's it! You now have a script that deploys your NFT smart contract to Sepolia using Truffle.

Although some of the information the AI gives is incorrect like confusing Sepolia and Ropsten testnets, the code it provides is serviceable.

In the migrations folder, create a new file called 1_deploy_contract.js (the prefix is again something that ChatGPT forgets to mention) and add the following code:

const MyNft = artifacts.require("MyNft");


module.exports = async function (deployer) {

    const name = "My NFT";

    const symbol = "NFT";

    const metadataUrl = "ipfs://QmUyZoK21qb8YknXGfDB34RTY8vMqPb6Bsj9U9iLEnyrZR";

    await deployer.deploy(MyNft, name, symbol, metadataUrl);

};

Deploy to Sepolia using:

npx truffle migrate --network sepolia

You should see output that looks something like this:

Compiling your contracts...

===========================

> Everything is up to date, there is nothing to compile.



Migrations dry-run (simulation)

===============================

> Network name:    'sepolia-fork'

> Network id:      11155111

> Block gas limit: 30000000 (0x1c9c380)



1_deploy_contract.js

====================


   Deploying 'MyNFT'

   -----------------

   > block number:        3445254

   > block timestamp:     1683573071

   > account:             0xc361Fc33b99F88612257ac8cC2d852A5CEe0E217

   > balance:             0.500641134976595178

   > gas used:            2493990 (0x260e26)

   > gas price:           2.500000007 gwei

   > value sent:          0 ETH

   > total cost:          0.00623497501745793 ETH


   -------------------------------------

   > Total cost:     0.00623497501745793 ETH


Summary

=======

> Total deployments:   1

> Final cost:          0.00623497501745793 ETH





Starting migrations...

======================

> Network name:    'sepolia'

> Network id:      11155111

> Block gas limit: 30000000 (0x1c9c380)



1_deploy_contract.js

====================


   Deploying 'MyNFT'

   -----------------

   > transaction hash:    0x14a189d5c84c2b80fb45991e45557aeecd236c07664db30ee76b21a5c5e18dfc

   > Blocks: 2            Seconds: 17

   > contract address:    0xD5B63A037FfF90ca3a73506e9856E543dE42CAA1

   > block number:        3445261

   > block timestamp:     1683573096

   > account:             0xc361Fc33b99F88612257ac8cC2d852A5CEe0E217

   > balance:             0.500641134976595178

   > gas used:            2493990 (0x260e26)

   > gas price:           2.500000007 gwei

   > value sent:          0 ETH

   > total cost:          0.00623497501745793 ETH


   > Saving artifacts

   -------------------------------------

   > Total cost:     0.00623497501745793 ETH


Summary

=======

> Total deployments:   1

> Final cost:          0.00623497501745793 ETH

The smart contract will also be live on Sepolia Etherscan and you can search it by its address.

Improve your devops with ChatGPT and Infura

In this tutorial, you learned how to use ChatGPT to mint a smart contract using Infura and Truffle. Missed part one where we reviewed more general development use cases? You can check that out here.

Remember to think of ChatGPT as a helpful assistant, not as a tool that can write flawless code that would replace an experienced developer. As we saw, ChatGPT isn’t aware of information past 2021, which impacts its knowledge and code output.

In part three of this series, we’ll launch a fully functional dapp using instructions and code generated by ChatGPT. Stay tuned!