How to use ChatGPT AI for Smart Contract Development

Here’s how ChatGPT and AI can be used with Infura to level up your smart contract development.

How to use ChatGPT AI for Smart Contract Development

Here’s how ChatGPT and AI can be used with Infura to level up your smart contract development.

ChatGPT and AI have become the most exciting new technologies of the past decade. You’ve likely already seen some of the fascinating use cases of the tool like writing poems, lyrics in the style of renowned musicians, film scripts, college essays, and more. In this blog, you'll learn how to use ChatGPT to improve your smart contract development.

For many developers, ChatGPT has already become a key part of their workflow, helping them to debug code, analyze code snippets, and even generate code. This begs the question, will AI eventually replace developers?

I don’t have that answer. But I do know that web3 developers can use ChatGPT to their advantage today. Used properly and with care, ChatGPT can make writing smart contracts 10x more productive.

Let’s look at how.

Getting Started with ChatGPT

First you’ll need to create an account with OpenAI. ChatGPT is currently free to use through its web UI interface and this is what we’ll use in this tutorial. In subsequent tutorials, I'll cover how to access ChatGPT programmatically through an API, which will require paid OpenAI credits.

Once you’ve signed up for an account, visit the Welcome to ChatGPT page where you will an interface that looks something like this:

Before you start leveraging the tool for smart contract development, go ahead and play around with the tool if you haven’t before.

You can ask for answers to general knowledge questions like, who is the Prime Minister of Canada, have ChatGPT design an itinerary for a trip to Paris, and even write song lyrics with a prompt like: write a song on loneliness in the style of Pink Floyd’s Dark Side of the Moon.

Once you feel like you’ve gotten a hang of it, let’s move on to coding and four ways ChatGPT can help:

  • Ask questions to ChatGPT
  • Write smart contract code with ChatGPT
  • Debug and test code with ChatGPT
  • Practice coding skills with ChatGPT

Method 1: Ask Questions to ChatGPT

ChatGPT is extremely proficient at web3 development, and it has knowledge of most well-known web3 tools like Solidity, Infura, Ethers, and MetaMask.

Normally, when stuck on a problem, you’d visit StackOverflow, check the docs of the language, library, or tool that you’re using, or just Google it.

Although this usually works (given enough time for trial and error), ChatGPT provides a much easier alternative. You just ask. Here are some examples:

Can you explain the use of the “payable” keyword in the Solidity language? Please give an example showing its usage.

You’ll get a response like this. Note: it won’t be exactly like this. That’s because this isn’t a search or a lookup—it’s an LLM, large language model. You’ll get a unique answer.

In Solidity, the "payable" keyword is used to specify that a function can receive Ether (the cryptocurrency used on the Ethereum blockchain) as part of a transaction. 


When a function is marked as payable, it means that when someone calls that function, they can send Ether along with their transaction, which can then be stored in the contract's address. Without the "payable" keyword, a function cannot receive Ether and any transaction that tries to send Ether to it will fail.


Here's an example of a simple Solidity contract with a payable function:


```

contract MyContract {

    mapping(address => uint256) public balances;


    function deposit() external payable {

        balances[msg.sender] += msg.value;

    }

}

```


In this contract, we define a mapping called "balances" that stores the balance of each address that interacts with the contract. The "deposit" function is marked as payable, which means that when someone calls it, they can send some amount of Ether along with their transaction.


The function then adds the amount sent by the caller (accessed via the "msg.value" variable) to their balance in the "balances" mapping. 


Note that in order to use the "payable" keyword, the contract must have a fallback function that can handle unexpected incoming transactions. If the contract does not have a fallback function, any transactions that send Ether to it will fail.

The explanation provided by ChatGPT is accurate and frankly, amazing.

Compare this answer to what you’d get from reading Solidity documentation or an answer on the Ethereum StackExchange. You’ll find that the answer we got here is arguably easier to understand.

Let’s try another question. Let’s say you’ve been hearing of Infura a lot in the context of web3 development, but you’re not exactly sure how it fits into the bigger picture. Let’s see if ChatGPT is able to answer this question for us.

What is the use of Infura when it comes to smart contract development?

Here is the response:

Infura is a web3 infrastructure provider that offers developers easy access to Ethereum and IPFS networks without having to run their own nodes. It provides a reliable and scalable way for developers to interact with blockchain networks, including deploying and executing smart contracts.


Here are some ways Infura can be useful for smart contract development:


1. Access to blockchain networks: Infura allows developers to easily access Ethereum and IPFS networks without the need for setting up and maintaining their own nodes. This can save time and resources, as developers can focus on building and testing their applications without having to worry about node infrastructure.


2. Scalability: Infura provides scalable infrastructure, allowing developers to scale their applications without having to worry about the limitations of their own nodes.


3. Reliability: Infura offers a reliable and secure infrastructure, with redundant nodes that ensure uptime and minimize downtime, allowing developers to deploy their applications with confidence.


4. Ease of use: Infura offers a simple API that developers can use to interact with blockchain networks, making it easy for developers to integrate their applications with blockchain technology.


Overall, Infura can be a valuable tool for smart contract development, offering developers a reliable, scalable, and easy-to-use infrastructure to build and deploy their applications on Ethereum and IPFS networks.

Although a little verbose, ChatGPT answers the question thoroughly and accurately: Infura is used to interact with blockchains in an easy, reliable, and scalable manner.

These questions are admittedly pretty simple to find answers for on the internet. Where ChatGPT truly shines is answering conceptual questions that might not have an obvious and readily available answer. Here’s an example:

Is it fair to say that no L2 Rollup is actually a chain but just a protocol? Because data availability is on L1 calldata and L2 is just a way to sequence and validate.

And here is ChatGPT’s response:

It depends on how one defines a "chain" versus a "protocol." In general, a chain refers to a blockchain network where blocks are produced and validated through a consensus mechanism, while a protocol refers to a set of rules and standards for communication and interaction between different systems. 


In the case of L2 rollups, they are a type of layer 2 scaling solution that uses a sidechain or similar mechanism to batch multiple transactions and submit them to the L1 chain as a single transaction, thereby reducing congestion and increasing throughput. However, as you mentioned, the data availability is still ultimately guaranteed by the L1 chain, and the rollup relies on L1 for finality and security. 


Therefore, some may argue that L2 rollups are not truly standalone chains but rather a protocol for scaling transactions on top of an existing chain. However, others may argue that the use of a separate consensus mechanism and the ability to batch and verify multiple transactions on the L2 chain make it more than just a protocol. Ultimately, it comes down to how one chooses to define a "chain" versus a "protocol."

The next time you feel you’re stuck on a particular concept, use ChatGPT. It will automatically give you an advantage over developers that don’t.

Having said that, always keep in mind that ChatGPT could be wrong. Never use ChatGPT as the sole source of truth. AI sometimes hallucinates. What’s AI hallucination? Let’s ask ChatGPT itself!

What is AI hallucination? 

AI hallucination is a term used to describe situations where an artificial intelligence model generates outputs that are seemingly irrelevant, nonsensical, or detached from the input provided. While the term "hallucination" is borrowed from human experiences, it is used metaphorically in the context of AI to highlight unexpected or bizarre behavior.

If what you’re working on is important, verify your data and information from additional sources.

Method 2: Write Smart Contract Code with ChatGPT

ChatGPT is powerful enough to write smart contract code—and provide instructions for that code—to create your next dapp or smart contract.

If you engineer your prompt well, ChatGPT will provide you with everything you need, from setting up a project to deploying the contract to a blockchain.

Let’s say we want to create an NFT smart contract, but not much beyond that, and all we know are tools like Solidity, Truffle, and OpenZeppelin are available.

Here is a way to engineer a prompt.

I want to create a smart contract that mints an NFT. The contract should be deployed to Ethereum.


Please provide detailed steps and code on how to do so using Solidity, Truffle, and OpenZeppelin. 

When I provide this prompt, ChatGPT writes a detailed tutorial for me. Here is a snippet:

Sure, I can help you with that. Here are the step-by-step instructions to create a smart contract that mints an NFT, using Solidity, Truffle, and OpenZeppelin.


1. Set up your development environment: You will need to install Node.js, Truffle, and the OpenZeppelin library. You can follow the installation instructions on their respective websites.


2. Create a new Truffle project: Open your terminal and create a new directory for your project. Then, navigate into that directory and run the following command: 


```

truffle init

```


This will create a basic Truffle project structure.


3. Install OpenZeppelin: In your project directory, run the following command to install OpenZeppelin:


```

npm install @openzeppelin/contracts

```


4. Write the contract: In the `contracts` directory of your Truffle project, create a new Solidity file called `MyNFT.sol`. This will contain the code for your smart contract.


```solidity

// 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;


    constructor() ERC721("MyNFT", "MNFT") {}


    function mintNFT(address recipient, string memory tokenURI)

        public

        returns (uint256)

    {

        _tokenIds.increment();


        uint256 newItemId = _tokenIds.current();

        _mint(recipient, newItemId);

        _setTokenURI(newItemId, tokenURI);


        return newItemId;

    }

}

```


In this contract, we are importing the `ERC721` contract from OpenZeppelin, which provides us with the functionality we need to create an NFT. We are also using the `Counters` library to keep track of the token IDs.


Our `MyNFT` contract inherits from `ERC721` and has a single function `mintNFT`, which takes an address for the recipient and a string for the token URI. The function generates a new token ID, mints a new NFT to the recipient, and sets the token URI.


5. Compile the contract: In your terminal, navigate to your Truffle project directory and run the following command:


```

truffle compile

```


This will compile your Solidity contract.


6. Deploy the contract: In your Truffle project, create a new migration file in the `migrations` directory called `2_deploy_my_nft.js`. This will contain the code to deploy your contract to Ethereum.


```javascript

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


module.exports = function (deployer) {

  deployer.deploy(MyNFT);

};

```


In this migration, we are simply deploying our `MyNFT` contract.


7. Deploy the contract to a local blockchain: In your terminal, navigate to your Truffle project directory and run the following command:


```

truffle migrate

```


This will deploy your contract to a local blockchain.


8. Mint an NFT: In your terminal, open the Truffle console by running the following command:


```

truffle console

```


Once you are in the console, run the following commands to mint a new NFT:


```javascript

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


let instance = await MyNFT.deployed();


let recipient = "0x1234567890123456789012345678901234567890"; // replace with the recipient's address

let tokenURI = "https://

Note: Sometimes ChatGPT stops midway. This is because it has run out of tokens. In such cases, simply respond with a Continue and it will finish its response.

Here are a few tips and tricks for improving code responses from ChatGPT:

  • Remember that ChatGPT has (at the time of writing this blog) limited knowledge of events after September 2021. Keep in mind that it won’t always know the latest best practices and tools. This is especially important in web3, given the pace at which tooling and technologies develop.
  • Ask specific questions. The prompt we provided was extremely vague. We did not tell the AI if we wanted one NFT or a collection, if we wanted the public to be able to pay and mint, if we wanted to be able to open and close sales, etc. A general rule of thumb is that the more detailed and explicit you are with your requests, the better the quality of response is going to be.
  • Prep ChatGPT by instructing it. Ask it to be an expert programmer. Or a functional programmer. Ask it to use descriptive names. Ask it to critique itself. Ask it to check its own code for errors. Feedback loops with AI models work surprisingly well.
  • GPT-4 is a more advanced model, and tends to give better answers, but requires (at the time of writing) a paid plan. GPT-3.5 is free.
  • The space moves fast—even faster than web3! Stay up to date on Twitter and through the use of other platforms. Consider taking a class in prompt engineering for developers.

Method 3: Audit and Test Code with ChatGPT

Another excellent use of ChatGPT is asking for feedback on your smart contract code by performing a basic security audit. Let’s see this in action.

We’ve created a very simple Ethereum smart contract that allows a user to accept donations from anyone in the world, and then withdraw the donated amount from the smart contract.

Let’s pass the source code to ChatGPT and ask it for any security loopholes.

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.9;


import "@openzeppelin/contracts/access/Ownable.sol";


contract Donation is Ownable {


    constructor() {}


    // Keep track of everyone's donations

    mapping(address => uint) donations;


    // Let anyone donate money

    function donate() public payable {

        donations[msg.sender] += msg.value;

    }


    // Let the owner withdraw money

    function withdraw() public {

        uint balance = address(this).balance;

        require(balance > 0, "No ether left to withdraw");


        (bool success, ) = (msg.sender).call{value: balance}("");

        require(success, "Transfer failed.");

    }

}


Can you audit this smart contract and tell me if there are any security loopholes?

The loophole we were looking for was that anyone can withdraw money from the smart contract, not just the owner. ChatGPT not only identifies this, but also gives some additional helpful advice.

This is a simple smart contract that allows anyone to donate money and the owner of the contract to withdraw the donated money. From a security standpoint, the contract appears to be relatively safe and follows some good practices, such as using the `msg.value` variable to track the amount of ether sent with a transaction.


However, there is a potential security risk to consider:


1. Ownership control: Similar to the previous version of the contract, the `withdraw` function does not include the `onlyOwner` modifier from the `Ownable` contract. This means that anyone can call the `withdraw` function and withdraw the contract's funds, which could result in a loss of funds if a malicious actor gains access to the contract's private key. To mitigate this risk, you can add the `onlyOwner` modifier to the `withdraw` function to restrict the functionality to the contract owner only.


2. Lack of input validation: The `donate` function does not validate the input parameters, which could allow an attacker to send negative values or values greater than their account balance, resulting in unexpected behavior or errors. You can add input validation to the function to prevent these kinds of issues.


3. Limited functionality: The contract does not include any additional features or business logic beyond accepting donations and allowing the owner to withdraw funds. While this may not be a security risk per se, it may limit the contract's usefulness in a real-world application.


Overall, the contract appears to be relatively safe, but adding the `onlyOwner` modifier to the `withdraw` function and addressing the other potential risks can further improve the contract's security.

Note that ChatGPT audits are not a replacement for standard security audits. And it’s not a replacement for thorough testing either. But it’s definitely a helpful place to start. It’s also a good way to get feedback on your code as a beginner.

As with generating code from scratch, keep in mind that ChatGPT has a knowledge cutoff date, meaning it may not be aware of the newest exploits.

Method 4: Practice Code with ChatGPT

The last method we’ll cover is asking ChatGPT for coding challenges. ChatGPT is capable of functioning as a substitute to tools like Ethernaut.

Let’s say you want to practice Solidity contract security. Here is a prompt that could help you.

I want to practice identifying security risks in Solidity smart contracts. Can you provide a challenge where you give me a contract with a loophole and I have to identify it correctly?

This is what ChatGPT provides:

Sure, I can give you a smart contract with a potential security vulnerability for you to analyze and identify. Here's the contract:


```

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;


contract Token {

    mapping(address => uint) balances;


    function transfer(address recipient, uint amount) public {

        require(balances[msg.sender] >= amount, "Insufficient balance");

        balances[msg.sender] -= amount;

        balances[recipient] += amount;

    }


    function balanceOf(address account) public view returns (uint) {

        return balances[account];

    }

}

```


Can you identify the potential security vulnerability in this contract?

Try answering! And if you’re not able to crack it, ask ChatGPT for the answer. (Hint: it has to do with a denial of service attack.)

Explore ChatGPT with Infura to Improve Dapp Development

We’ve only scratched the surface with what can be done with ChatGPT and smart contract coding for dapp development.

You can think of the tool as an extremely knowledgeable and helpful mentor who is able to answer almost any question you may have in your web3 journey. It’s quite possibly the best sounding board there is on the market right now.

Over the next two blogs we’ll continue our journey toward becoming a 10x blockchain developer with AI.

We’ll use ChatGPT to create a complex smart contract using Solidity, Truffle, and Infura. We’ll then launch a fully functional dapp, again using instructions and code generated by ChatGPT. Stay tuned!