Neural networks, large language models and particularly ChatGPT have become the most exciting topic of recent years. You’ve probably already asked ChatGPT to write a poem, write a song or explain string theory in simple language. But this is far from the only way this tool can be used. AI can become an effective aid in work and training.
In this article we will tell you how web3-developers can use ChatGPT to their advantage today: for quick research, improving smart contract development, fixing bugs and practicing programming skills. If used properly, an AI can speed up smart contracts writing by 10 times.
Getting started with ChatGPT
Currently, ChatGPT can be used for free via the web interface, so that’s what we’ll do. Create an account in OpenAI and get to the Welcome to ChatGPT page. It looks something like this:
Now let’s try out four ways ChatGPT can help with web3 development:
- Consulting
- Writing smart contract code
- Bug fixing and testing
- Programming skills training
1. Consulting with ChatGPT
Usually, when a problem with code arises, developers go to StackOverflow and look at the documentation for the language, library or tool they are using, or just google it. It brings results but takes a lot of time. ChatGPT is a simpler alternative. It immediately gives a detailed answer with all the nuances. NeuralNet is well versed in web3 development and knows most of the well-known tools like Solidity, Infura, Ethers and MetaMask. It’s like having a more experienced mentor to whom you can ask any questions and he won’t send you to «learn the math». For example, let’s ask ChatGPT about the meaning of the keyword «payable»:
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:
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.
ChatGPT’s explanation is surprisingly accurate. You can see this by comparing it to the Solidity documentation or the answers on the Ethereum StackExchange. However, it is much easier to understand and is obtained in a second.
Of course, it’s pretty easy to find an answer to a question like this online. What ChatGPT shows really well is answering conceptual questions that don’t have an obvious and accessible answer. For 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 AI’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.»
2. Writing a smart contract code using ChatGPT
ChatGPT is a fairly powerful language model. It can write smart contract code and provide instructions for creating a dapp or smart contract. If we formulate the request well, the AI will provide everything we need: from creating the project to deploying the contract on the blockchain.
Let’s say we want to create a smart contract for NFT mining. All we know is the availability of tools such as Solidity, Truffle, and OpenZeppelin. Let’s formulate the request:
Please provide detailed steps and code on how to do so using Solidity, Truffle, and OpenZeppelin.
ChatGPT writes a detailed tutorial. 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.
- 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.
- 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.
- Install OpenZeppelin: In your project directory, run the following command to install OpenZeppelin:
```
npm install @openzeppelin/contracts
```
- 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.
- 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.
- 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.
- 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.
- 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 = «0×1 234 567 890 123 456 846 996 462 118 072 609 669 120»; // replace with the recipient’s address
let tokenURI = «https://
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.
Tips for improving the ChatGPT user experience:
- Don’t rely only on ChatGPT.It may not always be aware of the latest techniques and tools and in web3 this is especially important given the pace of technology development. It is worth monitoring events yourself to judge the relevance of the AI’s responses.
- Concretize the questions. The request to develop a smart contract in our example was extremely vague. The AI’s answer could be greatly improved by specifying whether we wanted a single NFT or a collection, whether we wanted users to be able to pay and mine, whether we wanted to be able to open and close sales. The more detailed the question, the higher the quality of the answer.
- Setting Context. ChatGPT can be trained to generate responses the way the user expects it to: ask it to respond as an expert developer or functional programmer, use descriptive names, criticize itself, check its own code for bugs. Feedback systems work surprisingly well in language models.
- Use the paid version. At the time of writing, only the GPT-3.5 model is available for free. The more advanced GPT-4 gives better answers, but requires a subscription fee. If you want to make ChatGPT your full-fledged assistant and assign important work issues to it, it is better to use the commercial version.
3. Code auditing and testing with ChatGPT
Another application of ChatGPT is to request feedback about the smart contract code. A AI can perform a basic audit and point out security holes. For our example, we created a very simple Ethereum smart contract that allows us to accept donations from anyone in the world and then withdraw the amount received from the smart contract. Let’s suggest to ChatGPT to find 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:
- 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.
- 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.
- 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.
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.
4.Practicing Programming Skills with ChatGPT
The last method we will consider is using ChatGPT as a training simulator. It is quite capable of replacing tools such as Ethernaut. Let’s say we want to practice securing smart contracts:
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?
That’s exactly what ChatGPT does:
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?
Explore ChatGPT to improve web3 development
We’ve barely touched on what can be done with ChatGPT for smart contract and dapp development. This tool can be seen as an extremely knowledgeable mentor, capable of answering almost any question a developer might have on their web3 journey.