What You’ll Build
A simple counter contract that:- Stores a
Uint128
value in persistent storage - Allows anyone to increase the value (with a limit of 100 per transaction)
- Provides a query interface to read the current value
Prerequisites
- Rust installed with
wasm32-unknown-unknown
target - Basic understanding of Rust syntax
- Docker for contract optimization
Understanding Neutron Smart Contracts
Neutron is a Cosmos SDK chain that uses CosmWasm for smart contracts. Contracts are WebAssembly modules that can store state and process messages.
Contract Lifecycle
- Compile: Build your Rust code into a WebAssembly binary
- Upload: Store the binary on-chain with
MsgStoreCode
(receives acode_id
) - Instantiate: Create a contract instance with
MsgInstantiateContract
(receives a contract address) - Execute: Send messages to the contract using
MsgExecuteContract
Entry Points
Every CosmWasm contract has three main entry points:instantiate
: Called when the contract is first createdexecute
: Handles incoming messages that modify statequery
: Handles read-only queries (doesn’t modify state)
Creating the Contract
1. Initialize the Project
2. Set Up Dependencies
Add to yourCargo.toml
:
3. Define Storage
Insrc/state.rs
:
4. Define Messages
Insrc/msg.rs
:
5. Implement Contract Logic
Insrc/contract.rs
:
6. Wire Everything Together
Insrc/lib.rs
:
Building and Optimizing
1. Compile the Contract
artifacts/minimal_contract.wasm
.
Deploying to Neutron
1. Set Up Environment
Ensure you have a local Neutron node running (see Cosmopark Setup) or access to a testnet.2. Store the Contract
3. Instantiate the Contract
4. Interact with the Contract
Key Concepts Learned
- Storage: Using
cw-storage-plus::Item
for persistent data - Entry Points: Implementing
instantiate
,execute
, andquery
- Message Handling: Pattern matching on message types
- Error Handling: Using
StdResult
for operations that can fail - Deployment Flow: Store → Instantiate → Execute/Query
Next Steps
Now that you have a working contract, proceed to Part 2 to learn how to interact with Neutron’s unique modules and other contracts.Troubleshooting
Compilation Errors
Compilation Errors
Ensure you have the
wasm32-unknown-unknown
target installed:Gas Estimation Failed
Gas Estimation Failed
Try using a fixed gas amount instead of
auto
:Contract Not Found
Contract Not Found
Make sure you’re using the correct contract address from the instantiation transaction.