If you happen to’d wish to learn to construct a Web3 ChatGPT dapp to mint NFTs, this text is for you! The ChatGPT dapp we’re about to construct will allow you to question ChatGPT and convert the supplied reply into an NFT. Sounds difficult? Luckily, it’s fairly simple, due to OpenAI’s API and the Moralis Web3 API. Now, concerning the implementation of the ChatGPT performance, the next strains of code do many of the heavy lifting:
app.get("/", async (req, res) => { const { question } = req; strive { const response = await openai.createCompletion({ mannequin: "text-davinci-003", immediate: question.message, max_tokens: 30, temperature: 0, }); return res.standing(200).json(response.information); } catch (e) { console.log(`One thing went flawed ${e}`); return res.standing(400).json(); } });
With the intention to mint chats as NFTs, you have to retailer them in a decentralized method. That is the place you should use IPFS through the Moralis IPFS API. Right here’s the snippet of code that covers that half:
app.get("/uploadtoipfs", async (req, res) => { const { question } = req; strive { const response = await Moralis.EvmApi.ipfs.uploadFolder({ abi: [ { path: "conversation.json", content: { chat: query.pair }, }, ], }); console.log(response.end result); return res.standing(200).json(response.end result); } catch (e) { console.log(`One thing went flawed ${e}`); return res.standing(400).json(); } });
After all, so far as the precise NFT minting goes, you additionally want a correct good contract. So, in case you are taken with creating your Web3 ChatGPT dapp by implementing the above-presented strains of code and creating an acceptable good contract, observe alongside on this article or watch the video above. Simply create your free Moralis account and observe our lead!

Overview
Nearly all of at this time’s article consists of a tutorial demonstrating the way to create a Web3 ChatGPT dapp utilizing our code. You’ll find out how your JavaScript abilities can cowl each the frontend and backend parts of your ChatGPT dapp. Alongside the way in which, you’ll additionally learn to use instruments akin to OpenAI’s API, the Moralis Web3 Information API, and wagmi. You’ll additionally study the fundamentals of Solidity. In spite of everything, it’s worthwhile to deploy your occasion of our instance good contract to create your ChatGPT minter.
For the sake of this tutorial, we’ll be utilizing the Goerli testnet. As such, ensure to attach your MetaMask pockets to this Ethereum testnet and equip your pockets with some Goerli ETH. A dependable Goerli faucet will do the trick.
As a bonus, we’ll additionally present you the way to use the Moralis NFT API to fetch and examine the small print of NFTs minted along with your Web3 ChatGTP dapp. Beneath the tutorial, you too can discover extra particulars about ChatGPT and its use circumstances.

Tutorial: Construct Your Web3 ChatGPT NFT Minter Dapp
If you happen to had been to construct your Web3 ChatGPT minter dapp from scratch, you’d want to finish the next steps:
- Create a NodeJS app and an Categorical server.
- Set up all required dependencies to your backend: CORS, dotenv, Categorical, Moralis, and OpenAI.
- Create a correct backend “index.js” script overlaying the backend functionalities of incorporating ChatGPT and the Moralis IPFS API as outlined above.
- Construct a frontend NextJS app.
- Set up all required frontend dependencies: Moralis, wagmi, NextAuth, and so on.
- Code a number of “.jsx” and “.js” scripts.
- Write and deploy a wise contract that mints a chat when you hit the “Mint NFT” button within the above screenshot.
Nevertheless, as a substitute of taking up all these steps, you’ll be able to merely entry our “moralis-chatgpt” GitHub repo and clone the whole code. When you do this and open the challenge in Visible Studio Code (VSC), you’ll be taking a look at three folders: “backend”, “hardhat”, and “nextjs_moralis_auth”:

Word: Transferring ahead, we are going to proceed as when you’ve cloned our challenge, and we are going to perform a code walkthrough of probably the most vital scripts.
ChatGPT NFT Minting Sensible Contract
In case you are conversant in Hardhat, you’ll be able to take the identical path as we did and use Hardhat to create your occasion of our good contract. Nevertheless, you too can use Remix IDE utilizing your favourite browser to compile and deploy the required good contract. Both approach, use our instance good contract template (“MessageNFT.sol“) positioned contained in the “hardhat/contracts” folder:
Like all Solidity good contracts, “MessageNFT.sol” begins with an MIT license and a pragma line:
// SPDX-License-Identifier: MIT pragma solidity ^0.8.17;
Subsequent, it imports three verified good contracts from OpenZeppelin to inherit the ERC-721 normal, the power to rely NFTs and assign NFT IDs, and performance that enables solely the proprietor of the good contract to mint NFTs:
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/entry/Ownable.sol";
Following the imports, the script defines the contract title and contract kind (ERC-721). Contained in the contract, the “constructor” will get executed when the contract is deployed, and the “mintNFT” operate will get executed each time this contract is known as to mint a related NFT:
contract messageNFT is ERC721URIStorage, Ownable { utilizing Counters for Counters.Counter; Counters.Counter non-public _tokenIds; constructor() ERC721("Chapt GPT Dialog", "CGPTC") {} operate mintNFT(handle recipient, string reminiscence tokenURI) public onlyOwner returns (uint256) { _tokenIds.increment(); uint256 newItemId = _tokenIds.present(); _mint(recipient, newItemId); _setTokenURI(newItemId, tokenURI); return newItemId; } }
Wanting on the “mint” operate parameters, you’ll be able to see that it takes within the pockets handle of the recipient and token URI. The previous will seize the related pockets’s handle, and the latter will fetch the URI that the IPFS API returns after importing a chat in query.
Word: When deploying the above good contract, ensure to give attention to the Goerli testnet.

Backend of the Web3 ChatGPT Minter Dapp
Contained in the “backend” folder, you could find the “index.js”, “package-lock.json”, and “bundle.json” information. You’ll be able to open the latter to see which dependencies are required by this challenge. Apart from putting in the required dependencies, you additionally must create a “.env” file. Inside that file, you need to retailer your Moralis Web3 API key beneath the “MORALIS_API_KEY” variable.
To acquire your API key, you’ll want a Moralis account. So, in case you haven’t executed so but, create your free Moralis account now. Then, log in and replica your API key out of your admin space:
Together with your Web3 API key in place, you’ll be capable to make the most of the backend “index.js” script. In spite of everything, that is the script that features the snippets of code outlined within the introduction. With that stated, let’s take a better have a look at “index.js”.
On the high, the script imports all related dependencies utilizing CORS and Categorical and imports your API key:
const categorical = require("categorical"); const app = categorical(); const port = 5001; const Moralis = require("moralis").default; const cors = require("cors"); require("dotenv").config(); app.use(cors()); app.use(categorical.json()); const MORALIS_API_KEY = course of.env.MORALIS_API_KEY;
Wanting on the strains of code above, you’ll be able to see that your backend will run on localhost 5001. After importing Moralis and your API key, the next snippet (which you could find on the backside of “index.js”) initializes Moralis:
Moralis.begin({ apiKey: MORALIS_API_KEY, }).then(() => { app.hear(port, () => { console.log(`Listening for API Calls`); }); });
The script additionally imports the OpenAI API configuration strains supplied by the OpenAI documentation:
const { Configuration, OpenAIApi } = require("openai"); const configuration = new Configuration({ apiKey: course of.env.OPENAI_API_KEY, }); const openai = new OpenAIApi(configuration);
That is additionally all the encircling code that can make the snippets of code from the intro work correctly. So, let’s take a better have a look at these two Categorical server endpoints.

Root Categorical Server Endpoint
When constructing a Web3 ChatGPT dapp that mints your chats into NFTs, your backend must cowl ChatGPT performance. That is the place the OpenAI API enters the scene:
app.get("/", async (req, res) => { const { question } = req; strive { const response = await openai.createCompletion({ mannequin: "text-davinci-003", immediate: question.message, max_tokens: 30, temperature: 0, }); return res.standing(200).json(response.information); } catch (e) { console.log(`One thing went flawed ${e}`); return res.standing(400).json(); } });
The above strains of code fetch the message out of your entry subject on the frontend, cross it to ChatGPT, and return ChatGPT’s reply.
The “/uploadtoipfs” Categorical Server Endpoint
When creating NFTs, you don’t retailer the NFT metadata and the NFT-representing information on the blockchain. As a substitute, you utilize cloud storage options offering you with URIs, that are saved on the blockchain. After all, you could possibly use any centralized storage resolution. Nevertheless, if you wish to take a preferable decentralized method, it is best to use one of many main Web3 storage options. IPFS is arguably the only option if you goal to make information public. Due to this, our backend “index.js” script makes use of IPFS through the IPFS API from Moralis. Listed below are the strains of code overlaying the “uploadtoipfs” endpoint:
app.get("/uploadtoipfs", async (req, res) => { const { question } = req; strive { const response = await Moralis.EvmApi.ipfs.uploadFolder({ abi: [ { path: "conversation.json", content: { chat: query.pair }, }, ], }); console.log(response.end result); return res.standing(200).json(response.end result); } catch (e) { console.log(`One thing went flawed ${e}`); return res.standing(400).json(); } });
Above, you’ll be able to see the “Moralis.EvmApi.ipfs.uploadFolder“ technique that makes use of “dialog.json” as an IPFS path and the forex ChatGPT dialog because the corresponding content material.
At this level, it is best to’ve already deployed your occasion of the “MessageNFT.sol” good contract and have the above-presented backend up and operating. Thus, it’s time to sort out the ultimate piece of the “Web3 ChatGPT dapp” puzzle: the frontend.
Frontend of the Web3 ChatGPT Minter Dapp
Contained in the “_app.jsx” script, positioned within the “nextjs_moralis_auth/pages” folder, you’ll be able to see how we wrap “WagmiConfig” and “SessionProvider” round our app. This allows you to use authentication throughout the whole app:
operate MyApp({ Part, pageProps }) { return ( <WagmiConfig consumer={consumer}> <SessionProvider session={pageProps.session} refetchInterval={0}> <Part {...pageProps} /> </SessionProvider> </WagmiConfig> ); }
After all, to make the above work, it’s worthwhile to import the correct suppliers on the high.
Contained in the “signin.jsx” script, our code renders the header and the “Join” button. By way of “handleAuth“, you’ll be able to join or disconnect MetaMask. As soon as related, the frontend of the Web3 ChatGPT dapp makes use of the “person.jsx” web page, which comprises a unique header. The “person.js” script additionally comprises the “loggedIn.js” element, which bridges the information between the backend and the frontend. On the backside of this element, the “loggedIn.js” script renders your frontend:
return ( <part> <part className={types.chat_box}> <part className={types.chat_history} id="chatHistory"></part> <part className={types.message_input}> <enter kind="textual content" id="inputField" placeholder="Sort your message..." onChange={getMessage} /> <button onClick={sendMessage}>Ship</button> </part> </part> {showMintBtn && ( <button className={types.mint_btn} onClick={mint}> MINT NFT </button> )} </part> ); }
Word: For a extra detailed code walkthrough of the “loggedIn.js” script, use the video on the high of this text, beginning at 5:53. That is additionally the place you’ll be able to find out how we used ChatGPT to generate the styling code for our frontend.
Closing Construct – ChatGPT Minter Demo
Right here’s what our ChatGPT NFT minter dapp appears to be like like earlier than connecting MetaMask:

As soon as we click on on the “Authenticate through MetaMask” button, MetaMask pops up and asks us to signal the authentication message:

After signing the above signature request, our dapp shows a ChatGPT field and modifications the header:

As soon as we kind a message within the entry subject and hit “Ship”, ChatGPT replies. This additionally prompts the “Mint NFT” button on the backside:

If we determine to transform our chat into an NFT, we have to click on on the “Mint NFT” button after which verify the minting transaction with our MetaMask:
As quickly as our transaction goes by means of, we will view our new ChatGPT NFT on Etherscan or OpenSea. After all, we will additionally use the “Get NFTs by contract” API reference web page. In that case, we simply want to stick in our good contract’s handle and choose the Goerli chain:

As we scroll down the “Get NFTs by contract” API reference web page, we see the response, which comprises the small print concerning our NFT:
What’s ChatGPT?
ChatGPT is a complicated chatbot developed by OpenAI on high of its GPT-3 household. Nevertheless, who finest to clarify what ChatGPT is than ChatGPT itself:

Needless to say ChatGPT is in its early phases and comprises some limitations. As an example, it often supplies incorrect data. For instance, it could present dangerous or biased content material, and it has restricted data of present affairs. With that in thoughts, ChatGPT should be used cautiously, and its solutions should be checked correctly.
Nonetheless, the ability of this device is kind of spectacular. In spite of everything, it speaks many of the pure languages (although it’s most correct in English) in addition to all of the main laptop programming languages. Let’s have a look at some typical ChatGPT use circumstances.
Web3 ChatGPT Use Circumstances
In some ways, this superior AI device is properly on its approach to turning into for writing what the calculator is for math – a extremely highly effective device. Listed below are some widespread examples of what customers across the globe are utilizing ChatGPT for:
- Growth/programming to degenerate Web2 and Web3 code or code templates and discover/repair code errors
- Content material improvement
- Advertising and gross sales pitches
- Accounting and information analytics
The above are simply a few of the commonest ChatGPT use circumstances. After all, we will additionally use OpenAI’s API and implement the ability of ChatGPT into all kinds of dapps (like we did in at this time’s instance). Furthermore, since ChatGPT has already confirmed itself as a extremely dependable supply of data and superior synthesizing capabilities, specialists, akin to psychologists and psychiatrists, have reported utilizing it as an aiding device.
Construct a Web3 ChatGPT Dapp – Abstract
In at this time’s article, you had an opportunity to make use of our instance challenge and steerage to create your occasion of our Web3 ChatGPT NFT minting dapp. Utilizing our scripts, you had been in a position to have your good contract, backend, and frontend prepared in minutes. Primarily, you simply needed to deploy your occasion of our good contract with Hardhat or Remix, set up the required frontend and backend dependencies, get hold of your Moralis Web3 API key and retailer it in a “.env” file, and launch your frontend and backend apps. Lastly, you additionally had a possibility to take a look at our instance dapp demo and see the ability of one of many Moralis NFT API endpoints. Nonetheless, we additionally defined what ChatGPT is and its widespread use circumstances.
Transferring ahead, we encourage you to make use of this text as an concept generator and as a proof-of-concept instance and exit and construct distinctive dapps that incorporate ChatGPT. If it’s worthwhile to broaden your Web3 improvement data and abilities first, ensure to make use of the Moralis docs, our blockchain improvement movies, and our crypto weblog. Among the newest subjects revolve round Ethereum improvement instruments, utilizing IPFS with Ethereum, creating blockchain purposes, good contract safety, Solana blockchain app improvement, Aptos testnet faucet, and way more. As well as, in case you are taken with turning into blockchain-certified, Moralis Academy is the place to be. As soon as enrolled, ensure to first get your blockchain and Bitcoin fundamentals so as.