- Docs
- Developers
- Build Smart Contracts with Cursor AI
Build smart contracts with Cursor AI
This guide will take you through the process of building a "Simple Voting" smart contract with the Assistance of Cursor AI. 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 optimization. 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. To get started, follow the installation guide 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 to generate a blank smart contract project.
Building the smart 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:
- Open the
state.rs
file, which should be empty. - Press
Command + K
to initiate the AI assistance in your editor. - 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.
- Ensure that the structures are serializable using
serde
and ready to be stored withcw-storage-plus
.- Include comments explaining the purpose of each data structure.
You should see something similar to the following:
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.
- Open the
contract.rs
file, delete its contents, and pressCommand + K
to launch the AI assistance. - Enter the following prompt:
Prompt:
Generate the
contract.rs
file for a voting smart contract. The contract should include:
- A function to initialize the contract.
- A function to create a new poll, accepting a poll ID, a question, and a list of options.
- A function to allow users to vote on a poll by specifying the poll ID and their chosen option.
- A 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 and you should see something like the following:
Click the Accept
button and save the file. You may encounter some errors in the file because the necessary messages haven't been created. 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.
- Open the
msg.rs
file, delete its contents, and pressCommand + K
to launch the chat. - Use the following prompt:
Prompt:
Generate the
msg.rs
file for the voting smart contract based on thecontract.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:
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.
- Open the
error.rs
file, delete its contents, and pressCommand + K
to launch the chat. - Use the following prompt:
Prompt:
Generate the
error.rs
file based on the relevant errors used within thecontract.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.
For the solution, in the chat on the right click the Apply
button:
You will then need to click the Accept
button to apply the changes to the file:
Build and optimize the contract
Once all errors have been resolved, the next step is to build and optimize your smart contract for deployment on-chain. This process compiles your code and generates the necessary WASM executable.
From within your project folder, run the following command to build the contract:
archway contracts build
This command will generate a .wasm
file, which is the executable version of your smart contract. Once compiled, you can deploy this contract on-chain and create instances to begin using your smart contract. Make sure to review any warnings or errors that arise during the build process to ensure the contract is properly optimized for on-chain performance.
Storing the contract on-chain
With your optimized .wasm
file, you’re now ready to deploy the contract on-chain. Before proceeding, ensure that you have tokens in your account to cover the transaction fees.
- For the
Constantine
testnet, you will needCONST
tokens. These can be obtained for free through our testnet faucet available on Discord. - For Mainnet, you will need to acquire
ARCH
tokens, which are available through the Archway Connect platform.
To store the contract on-chain, execute the following command from the root of your project:
archway contracts store CONTRACT
Arguments:
CONTRACT
(required): The name of the contract.
Create an instance of the contract
Once the contract is stored on-chain, you can instantiate it using the following command. Replace <contract-name> with the name of the contract you want to instantiate:
archway contracts instantiate <contract-name> --args '{"key":"my_value"}'
To determine the required fields for instantiation, refer to the msg.rs
file and review the InstantiateMsg
struct. Each field corresponds to a key
, and you will need to set the appropriate value for each field.
In this particular case, since the InstantiateMsg
struct for the voting contract is most likely empty, you can simply instantiate it with an empty JSON object.
For example, if the contract name is voting
, the following command would work:
archway contracts instantiate voting --args '{}'
Execute transactions
This smart contract allows for executing two main transactions: creating a poll and voting on a poll. In the msg.rs
file, you will find the ExecuteMsg
enum, which defines the messages that can be called. Each message has associated fields that need to be provided when executing the transaction.
To see the required fields for each transaction, refer to the ExecuteMsg
enum in msg.rs
. For example:
- The
CreatePoll
message might require the following fields:poll_id
: A unique identifier for the poll.question
: The question or prompt for the poll.options
: A list of options that users can vote on.
- The
Vote
message:poll_id
: The unique identifier of the poll.vote_option
: The index (position) of the chosen option in the list of options.
Creating a poll
To send a transaction to create a poll, you would use the following command and replace the placeholder values with your data:
archway contracts execute voting --args '{"create_poll": {"poll_id": "poll_1", "question": "Your favorite programming language?", "options": ["Rust", "Go", "Solidity"]}}'
In this example:
poll_id
is set to"poll_1"
,question
is"Your favorite programming language?"
, andoptions
are["Rust", "Go", "Solidity"]
.
Voting on a poll
To send a vote on an existing poll, use the Vote
function like this:
archway contracts execute voting --args '{"vote": {"poll_id": "poll_1", "vote_option": 0}}'
In this example:
poll_id
is"poll_1"
, andvote_option
is0
, which corresponds to the first option,"Rust"
.
Query the contract
In addition to executing transactions, this contract allows you to query data such as poll results. The QueryMsg
enum in the msg.rs
file defines the available query messages. For this contract, the primary query is for retrieving poll results.
To find the required fields for querying, refer to the QueryMsg
enum in msg.rs
. In this case, the PollResults
query requires:
poll_id
: The unique identifier of the poll you want to query.
Querying poll results
To query the results of a specific poll, use the following command, replacing the placeholder poll_id
with the ID of the poll you want to retrieve results for:
archway contracts query smart voting --args '{"poll_results": {"poll_id": "poll_1"}}'
In this example, the query fetches the results for the poll with poll_id
set to "poll_1"
.
The query will return a JSON object containing the current vote counts for each option in the specified poll.