Skip to content

Commit

Permalink
New guide on building smart contracts with the help of Cursor AI (#527)
Browse files Browse the repository at this point in the history
  • Loading branch information
emperorjm authored Sep 20, 2024
1 parent 577bb0a commit 02bf3c5
Show file tree
Hide file tree
Showing 6 changed files with 168 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
---
objectID: developers_guides_ai-assistance-development_build-smart-contrcts-with-cursor-ai
title: Build Smart Contracts with Cursor AI
description: How to use Cursor AI to build smart contract on Archway
parentSection: Developers
parentSectionPath: /developers
---

# Overview

This guide will take you through the process of building a "Simple Voting" smart contract with the Assistance of [Cursor AI](https://www.cursor.com). Cursor AI is an AI-powered code editor designed to enhance the software development process by leveraging artificial intelligence to improve coding productivity, reduce development time, and assist with code generation, error detection, and real-time collaboration. Go to https://www.cursor.com to download and install the application.

## Features of the voting smart contract

- **Create Polls**: Anyone can create a poll with multiple options.
- **Vote on Polls**: Users can cast a vote on an option in a poll.
- **Query Poll Results**: Anyone can query the results of a poll to see the vote counts.

## Create a blank smart contract

For this project, we’ll utilize the [Archway Developer CLI](/developers/developer-tools/developer-cli). To get started, follow the [installation guide](/developers/getting-started/install) to set up your development environment.

The Developer CLI follows a specific structure and configuration, so we need to begin by creating a blank smart contract as the foundation for our dapp. Once your environment is ready, refer to this [setup guide](/developers/getting-started/setup#creating-a-blank-project) to generate a blank smart contract project.

## Building the smmart contract: working with key files

Now that we’ve set up the foundation of our project, it's time to begin working on the key files that will make up the smart contract. Each file plays a critical role in defining how the contract operates, manages data, and allows for user interactions. We’ll go through each file step by step, focusing on how they contribute to the overall functionality of the contract.

The main files we’ll be working on include:

- **`state.rs`**: Manages the contract’s state and data storage.
- **`msg.rs`**: Defines the messages and parameters that users can send to interact with the contract.
- **`contract.rs`**: Contains the core logic and execution flow of the smart contract.
- **`error.rs`**: Handles error management and reporting in the contract.

In each section, we will walk through what needs to be done in the file, providing guidance and instructions for building out the voting smart contract and the prompts that will be submited to Cursor AI for it to generate the necessary code.

## State

The `state.rs` file in an Archway smart contract is crucial for defining how the contract's data (state) is stored and managed on the blockchain. This file specifies the variables, data structures, and storage mechanisms that persist data between contract executions.

In this section, we'll set up the state management for our voting smart contract. The `state.rs` file will include structures to represent the polls and their related data, allowing us to store and track voting information.

### Steps:

1. Open the `state.rs` file, which should be empty.
2. Press `Command + K` to initiate the AI assistance in your editor.
3. Use the following prompt to generate the required data structures:

**Prompt:**

> Generate the data structures for a voting smart contract. The contract should include:
>
> - A structure to represent a poll, including fields for the poll ID, the question, a list of options, and a corresponding list to track votes.
> - A mapping of all polls, where the poll ID serves as the key.
> - Ensure that the structures are serializable using `serde` and ready to be stored with `cw-storage-plus`.
> - Include comments explaining the purpose of each data structure.
You should see something similar to the following:

![](/images/docs/cursor_ai/state/prompt.png)

Click the `Accept` button to confirm the generated code, then save the changes to the file.

## Contract logic

Once the `state.rs` file has been generated, the next step is to have Cursor AI assist in generating the `contract.rs` file. This file will house the core functionality of the smart contract, including the logic for creating polls, voting, and querying results.

1. Open the `contract.rs` file, delete its contents, and press `Command + K` to launch the AI assistance.
2. Enter the following prompt:

**Prompt:**

> Generate the `contract.rs` file for a voting smart contract. The contract should include:
>
> - An `instantiate` function to initialize the contract.
> - An `execute_create_poll` function to create a new poll, accepting a poll ID, a question, and a list of options.
> - An `execute_vote` function to allow users to vote on a poll by specifying the poll ID and their chosen option.
> - A `query_poll_results` function that allows anyone to query the current results of a poll.
>
> Use CosmWasm's standard response and error handling patterns, ensuring that each function interacts with the state using the structures defined in `state.rs`.
Click the `generate` button:

![](/images/docs/cursor_ai/contract/prompt.png)

Click the `Accept` button and save the file. You may encounter some errors because the necessary messages haven't been created yet. We will address these errors in the next step.

## Messages

With the `contract.rs` file generated, the next step is to update the `msg.rs` file. This file defines the messages that are used to interact with the smart contract, such as inputs for creating polls, voting, and querying results.

1. Open the `msg.rs` file, delete its contents, and press `Command + K` to launch the chat.
2. Use the following prompt:

**Prompt:**

> Generate the `msg.rs` file for the voting smart contract based on the `contract.rs` file. It should include:
>
> - An `InstantiateMsg` struct for initializing the contract.
> - An `ExecuteMsg` enum with variants executing required transactions
> - A `QueryMsg` enum with variant for querying poll results.
>
> Ensure that all structs and enums are serializable using `serde`.
Click the `generate` button and you should see something like the following as the output:

```rust
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct InstantiateMsg {}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum ExecuteMsg {
CreatePoll {
poll_id: String,
question: String,
options: Vec<String>,
},
Vote {
poll_id: String,
vote_option: usize,
},
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum QueryMsg {
PollResults { poll_id: String },
}
```

Now click the `Accept` button and then save the file.

## Errors

The `error.rs` file is where custom error types for the smart contract are defined. These error types help handle contract-specific issues more effectively, providing clear and informative feedback to users when something goes wrong.

1. Open the `error.rs` file, delete its contents, and press `Command + K` to launch the chat.
2. Use the following prompt:

**Prompt:**

> Generate the `error.rs` file based on the relevant errors used within the `contract.rs` file. It should also follow CosmWasm's best practices for error handling.
## Rectify any errors

There may be errors in the `contract.rs` and other files. To address these, hover over each error and click the "**AI fix in chat**" button to ask Cursor AI to resolve the errors.

![](/images/docs/cursor_ai/errors/ai-fix-in-chat.png)

For the solution in the chat on the right click the `Apply` button:

![](/images/docs/cursor_ai/errors/apply.png)

You will then need to click the `Accept` button to apply the changes to the file:

![](/images/docs/cursor_ai/errors/accept.png)

## Summary

In this tutorial, we walked through the process of building a simple voting smart contract using Cursor AI and the Archway Developer CLI. We covered key steps such as generating the `state.rs` file to manage contract data, creating the core contract logic in `contract.rs`, defining messages in `msg.rs`, and handling custom errors in `error.rs`. Throughout the process, we utilized AI to assist with code generation, fixing potential errors, and ensuring smooth development.

By the end of this guide, you should have a fully functional voting smart contract that allows users to create polls, vote, and query results. This contract can be a foundation for more complex dapps, expanding on the principles we covered.

With your contract complete, you’re now ready to deploy and test it on the Archway blockchain or continue developing additional features.
Binary file added public/images/docs/cursor_ai/contract/prompt.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added public/images/docs/cursor_ai/errors/accept.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added public/images/docs/cursor_ai/errors/apply.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added public/images/docs/cursor_ai/state/prompt.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit 02bf3c5

Please sign in to comment.