Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cw book #61

Draft
wants to merge 11 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 10 additions & 22 deletions src/README.md
Original file line number Diff line number Diff line change
@@ -1,35 +1,23 @@
# Introduction
# [Introduction](https://book.cosmwasm.com/#introduction)

This book is a guide for creating CosmWasm smart contracts. It will lead you
step by step, and explain relevant topics from the easiest to the trickier
ones.
This book is a guide for creating CosmWasm smart contracts. It will lead you step by step and explain relevant topics from easiest to trickier.

The idea of the book is not only to tell you about smart contracts API but also
to show you how to do it in a clean and maintainable way. We will show you
patterns that CosmWasm creators established and encouraged you to use.
The idea of the book is not only to tell you about smart contracts API but also to show you how to make it clean and maintainable. We will show you patterns that CosmWasm creators established and encouraged you to use.

## Prerequirements
## [Requirements](https://book.cosmwasm.com/#prerequirements)

This book explores CosmWasm smart contracts. It is not a Rust tutorial, and it
assumes basic Rust knowledge. As you will probably learn it alongside this
book, I strongly recommend grasping the language itself first. You can find
great resources to start with Rust on [Learn
Rust](https://www.rust-lang.org/learn) page.
This book explores CosmWasm smart contracts. It is not a Rust tutorial, and it assumes basic Rust knowledge. As you will probably learn it alongside this book, I recommend first graspinGrammarly contributed to this text by responding to these AI prompts:

## CosmWasm API documentation
## [CosmWasm API documentation](https://book.cosmwasm.com/#cosmwasm-api-documentation)

This is the guide-like documentation. If you are looking for the API
documentation, you may be interested in checking one of the following:
This is the guide-like documentation. If you are looking for the API documentation, you may be interested in checking one of the following:

- [cosmwasm-std](https://crates.io/crates/cosmwasm-std)
- [cw-storage-plus](https://crates.io/crates/cw-storage-plus)
- [cw-multi-test](https://crates.io/crates/cw-multi-test)
- [cw-utils](https://crates.io/crates/cw-utils)
- [sylvia framework](https://crates.io/crates/sylvia)
- [Sylvia framework](https://crates.io/crates/sylvia)

## Contributing to the book
## [Contributing to the book](https://book.cosmwasm.com/#contributing-to-the-book)

This book is maintained on [Github](https://github.com/CosmWasm/book) and auto
deployed from there. Please create an
[issue](https://github.com/CosmWasm/book/issues) or pull request if you find
any mistakes, bugs, or ambiguities.
This book is maintained on [GitHub](https://github.com/CosmWasm/book) and auto-deployed from there. Please create an [issue](https://github.com/CosmWasm/book/issues) or pull request for corrections, bugs, or ambiguities.
121 changes: 119 additions & 2 deletions src/basics.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,121 @@
# Basics

In this chapter, we will go through creating basic smart contracts step by step.
I will try to explain the core ideas behind CosmWasm and the typical contract structure.
In this chapter, we will go through creating essential smart contracts step by step. I will explain the core ideas behind CosmWasm and the typical contract structure.

### **Introduction to CosmWasm**

**How to Understand Core Concepts:**

- **Wasm**: Experiment with compiling simple Rust programs to WebAssembly to understand the compilation process. Tools like **`wasm-pack`** can help in this learning phase.
- **Interoperability**: Explore the Cosmos SDK documentation and IBC protocol to grasp how CosmWasm facilitates cross-chain interactions. Look for simple IBC examples or tutorials to see this in action.
- **Rust Programming Language**: If new to Rust, start with "The Rust Programming Language" book (often referred to as "The Book") available for free online. Rust's ownership model and safety guarantees are crucial for writing secure smart contracts.

### **Typical Contract Structure**

1. **Contract Entry Points**

**How to Implement Entry Points:**

- **Instantiate**: Begin by defining what initial state your contract will have. Implement the **`instantiate`** function to set initial values, ensuring to handle any necessary input validation.
- **Execute**: Identify the actions your contract must support. Implement each action as a case within the **`execute`** function, manipulating the contract's state as required.
- **Query**: Determine the data users might need to read from your contract. Implement the **`query`** function to return this data, ensuring no state modification occurs.
2. **Messages**

**How to Define Messages:**

- Use Rust's **`enum`** and **`struct`** to define messages. Each action your contract supports will be a variant in the **`ExecuteMsg`** enum. Similarly, define **`InstantiateMsg`** and **`QueryMsg`** based on what data they must carry.
3. **State Management**

**How to Manage State:**

- Design your state model carefully, considering how data is accessed and updated. Use the **`DepsMut`** for state mutations and **`Deps`** for state queries. Implement helper functions for common state operations to encapsulate the storage access patterns.
4. **Dependencies**

**How to Handle Dependencies:**

- Familiarize yourself with the **`cosmwasm_std`** library's API by reading the documentation and looking at example contracts. For external crates, ensure they support compilation to **`wasm32-unknown-unknown`** target.

### **Step-by-Step Guide to Creating a Smart Contract**

1. **Setup**
- Install Rust and **`cargo`** using rustup. Set up your IDE for Rust development (VSCode, IntelliJ, etc.). Create a new project using **`cargo new --lib your_contract_name`**.
2. **Define Messages**
- Sketch out the functionality of your contract. For each function, define a message in Rust, using structs for data and enums for differentiating message types.
3. **Implement Entry Points**
- Start with the **`instantiate`** function for setting the initial state. Proceed to **`execute`** where you'll handle different messages as per your contract's logic. Finally, implement **`query`** for data retrieval.
4. **State Management**
- Use the **`cosmwasm_std::Storage`** trait for state management. Design your key-value schema and implement getter and setter functions for interacting with the state.
5. **Business Logic**
- Flesh out the business logic within the **`execute`** function. Consider edge cases and input validation to ensure contract security and reliability.
6. **Testing**
- Write unit tests for each entry point and critical functions within your contract. Use **`cargo test`** to run your tests. Consider edge cases and invalid inputs to ensure your contract behaves as expected under various conditions.

### **Expanded Guide to Creating Essential Smart Contracts in CosmWasm**

### Error Handling

**How to Handle Errors:**

- Implement robust error handling using Rust's **`Result`** and **`Option`** types. Utilize custom error types defined with **`thiserror`** to provide clear, actionable error messages.
- Use **`?`** for error propagation within your contract functions to keep your code clean and readable.

### Migration Function

**How to Implement Migration:**

- The **`migrate`** function allows contract upgrades. Define it similarly to **`instantiate`** and **`execute`**, but focus on transitioning from one contract state version to another safely.
- Ensure data integrity and compatibility between versions. Test migrations thoroughly in a controlled environment before deploying.

### External Crates Usage

**Examples of Compatible Crates:**

- **`serde_json`** for JSON serialization/deserialization.
- **`cw-storage-plus`** for advanced storage patterns.
- Always check the crate's documentation for **`no_std`** compatibility or specific instructions for Wasm targets.

### Interaction Patterns

**Cross-Contract Calls:**

- Use the **`CosmosMsg::Wasm(WasmMsg::Execute { ... })`** pattern to call other contracts. Handle responses using the **`SubMsg`** pattern for asynchronous execution.
- Consider the implications of external calls failing and implement fallback or retry logic as needed.

### Security Practices

**Smart Contract Security:**

- Avoid common pitfalls like reentrancy by carefully managing state changes and external calls.
- Utilize Rust's strong type system to prevent issues like overflow/underflow.
- Regularly audit your contracts and consider third-party reviews for critical applications.

### Optimization Tips

**Gas Efficiency:**

- Minimize storage access, as it's typically the most expensive operation. Cache results when possible.
- Use iterators wisely. Avoid loading entire datasets into memory when a filter or map operation can be applied directly.

### Deployment and Testing on a Blockchain

**Blockchain Testing and Deployment:**

- Use **`wasmd`** for local testing and deployment simulations. Familiarize yourself with **`wasmd`** CLI commands for deploying and interacting with your contracts.
- Test your contract on a public testnet to ensure it behaves as expected in a real blockchain environment.

### Tooling and IDE Setup

**Recommended Development Tools:**

- Visual Studio Code with the Rust Analyzer extension for Rust development.
- Use **`cargo-contract`** for contract compilation and artifact generation.
- Integrate debugging tools like **`console_error_panic_hook`** for better error visibility in Wasm.

### Community Resources and Support

**Engaging with the Community:**

- Join the CosmWasm GitHub discussions and Discord server for support and to connect with other developers.
- Stay updated with the latest CosmWasm releases and best practices by following the official CosmWasm documentation and blog.

By addressing these areas, developers are equipped with a deeper understanding and practical tools to navigate the complexities of smart contract development in CosmWasm. This expanded guide aims to foster the creation of secure, efficient, and maintainable smart contracts within the Cosmos ecosystem.
134 changes: 67 additions & 67 deletions src/basics/entry-points.md
Original file line number Diff line number Diff line change
@@ -1,78 +1,78 @@
# Entry points
# **Entry Points in CosmWasm Smart Contracts**

Typical Rust application starts with the `fn main()` function called by the operating system.
Smart contracts are not significantly different. When the message is sent to the contract, a
function called "entry point" is called. Unlike native applications, which have only a single
`main` entry point, smart contracts have a couple corresponding to different message types:
`instantiate`, `execute`, `query`, `sudo`, `migrate` and more.
In CosmWasm, the concept of an entry point is fundamental to the operation of smart contracts. Unlike traditional Rust applications that start with a **`fn main()`** function, smart contracts utilize specific functions called entry points to interact with the blockchain. These entry points are crucial for the lifecycle of a smart contract, allowing it to be deployed, executed, and queried securely and predictably.

To start, we will go with three basic entry points:
### **Overview of Entry Points**

* `instantiate` which is called once per smart contract lifetime - you can think about it as
a constructor or initializer of a contract.
* `execute` for handling messages which are able to modify contract state - they are used to
perform some actual actions.
* `query` for handling messages requesting some information from a contract; unlike `execute`,
they can never affect any contract state, and are used just like database queries.
Entry points in CosmWasm smart contracts are defined functions the blockchain calls in response to various actions, such as a contract's deployment, message execution, or information requests. The primary entry points are:

Go to your `src/lib.rs` file, and start with an `instantiate` entry point:
1. **[Instantiate]**
2. **[Execute]**
3. **[Query]**

```rust,noplayground
use cosmwasm_std::{
entry_point, Binary, Deps, DepsMut, Empty, Env, MessageInfo, Response, StdResult,
};
Each entry point serves a specific purpose in the contract's lifecycle and interaction with the blockchain.

### **Instantiate Function**

The **`instantiate`** function acts as the smart contract's constructor. It is called once when the contract is first deployed to the blockchain, allowing for the initial setup of its state and configurations.

```rust
#[entry_point]
pub fn instantiate(
_deps: DepsMut,
_env: Env,
_info: MessageInfo,
_msg: Empty,
) -> StdResult<Response> {
Ok(Response::new())
deps: [DepsMut](https://docs.rs/cosmwasm-std/1.0.0/cosmwasm_std/struct.DepsMut.html),
env: [Env](https://docs.rs/cosmwasm-std/1.0.0/cosmwasm_std/struct.Env.html),
info: [MessageInfo](https://docs.rs/cosmwasm-std/1.0.0/cosmwasm_std/struct.MessageInfo.html),
msg: [InstantiateMsg](https://docs.rs/cosmwasm-std/1.0.0/cosmwasm_std/struct.InstantiateMsg.html),
) -> [StdResult<Response>](https://docs.rs/cosmwasm-std/1.0.0/cosmwasm_std/type.StdResult.html) {
// Contract initialization logic
Ok(Response::new().add_attribute("method", "instantiate"))
}
```

This function sets the foundation of the contract, establishing necessary initial conditions or parameters.

### **Execute Function**

The **`execute`** function is where the contract's business logic resides. It processes messages that cause state changes within the contract, such as updating data or transferring tokens.

```rust
#[entry_point]
pub fn execute(
deps: [DepsMut](https://docs.rs/cosmwasm-std/1.0.0/cosmwasm_std/struct.DepsMut.html),
env: [Env](https://docs.rs/cosmwasm-std/1.0.0/cosmwasm_std/struct.Env.html),
info: [MessageInfo](https://docs.rs/cosmwasm-std/1.0.0/cosmwasm_std/struct.MessageInfo.html),
msg: [ExecuteMsg](https://docs.rs/cosmwasm-std/1.0.0/cosmwasm_std/struct.ExecuteMsg.html),
) -> [StdResult<Response>](https://docs.rs/cosmwasm-std/1.0.0/cosmwasm_std/type.StdResult.html) {
// Handling of different messages to perform state changes
Ok(Response::new().add_attribute("action", "execute"))
}
```

In fact, `instantiate` is the only entry point required for a smart contract to be valid. It is not
very useful in this form, but it is a start. Let's take a closer look at the entry point structure.

First, we start with importing couple of types just for more consistent usage. Then we define our
entry point. The `instantiate` takes four arguments:

* [`deps: DepsMut`](https://docs.rs/cosmwasm-std/1.0.0/cosmwasm_std/struct.DepsMut.html)
is a utility type for communicating with the outer world - it allows querying
and updating the contract state, querying other contracts state, and gives access to an `Api`
object with a couple of helper functions for dealing with CW addresses.
* [`env: Env`](https://docs.rs/cosmwasm-std/1.0.0/cosmwasm_std/struct.Env.html)
is an object representing the blockchains state when executing the message - the
chain height and id, current timestamp, and the called contract address.
* [`info: MessageInfo`](https://docs.rs/cosmwasm-std/1.0.0/cosmwasm_std/struct.MessageInfo.html)
contains metainformation about the message which triggered an execution -
an address that sends the message, and chain native tokens sent with the message.
* [`msg: Empty`](https://docs.rs/cosmwasm-std/1.0.0/cosmwasm_std/struct.Empty.html)
is the message triggering execution itself - for now, it is `Empty` type that
represents `{}` JSON, but the type of this argument can be anything that is deserializable,
and we will pass more complex types here in the future.

If you are new to the blockchain, those arguments may not have much sense to you, but while
progressing with this guide, I will explain their usage one by one.

Notice an essential attribute decorating our entry point
[`#[entry_point]`](https://docs.rs/cosmwasm-std/1.0.0/cosmwasm_std/attr.entry_point.html). Its purpose is to
wrap the whole entry point to the form Wasm runtime understands. The proper Wasm entry points
can use only basic types supported natively by Wasm specification, and Rust structures and enums
are not in this set. Working with such entry points would be rather overcomplicated, so CosmWasm
creators delivered the `entry_point` macro. It creates the raw Wasm entry point, calling the
decorated function internally and doing all the magic required to build our high-level Rust arguments
from arguments passed by Wasm runtime.

The next thing to look at is the return type. I used
[`StdResult<Response>`](https://docs.rs/cosmwasm-std/1.0.0/cosmwasm_std/type.StdResult.html) for this simple example,
which is an alias for `Result<Response, StdError>`. The return entry point type would always be a
[`Result`](https://doc.rust-lang.org/std/result/enum.Result.html) type, with some error type implementing
[`ToString`](https://doc.rust-lang.org/std/string/trait.ToString.html) trait and a well-defined type for success
case. For most entry points, an "Ok" case would be the
[`Response`](https://docs.rs/cosmwasm-std/1.0.0/cosmwasm_std/struct.Response.html) type that allows fitting the contract
into our actor model, which we will discuss very soon.

The body of the entry point is as simple as it could be - it always succeeds with a trivial empty response.
This function can be invoked multiple times throughout the contract's life, responding to user or contract interactions.

### **Query Function**

The **`query`** function allows reading data from the contract without modifying its state. It fetches information, like contract configurations or current state details, based on the query message received.

```rust
#[entry_point]{
pub fn query(
deps: [Deps](https://docs.rs/cosmwasm-std/1.0.0/cosmwasm_std/struct.Deps.html),
env: [Env](https://docs.rs/cosmwasm-std/1.0.0/cosmwasm_std/struct.Env.html),
msg: [QueryMsg](https://docs.rs/cosmwasm-std/1.0.0/cosmwasm_std/struct.QueryMsg.html),
) -> [StdResult<Binary>](https://docs.rs/cosmwasm-std/1.0.0/cosmwasm_std/type.StdResult.html) {
// Logic to handle different queries
to_binary(&"Query response")

}
```

Queries are essential for external clients or contracts to understand the contract's current state or configurations without initiating a state change.

### **Implementing Entry Points**

When defining these entry points in CosmWasm, the **`#[entry_point]`** attribute is used to designate the corresponding functions. Developers must ensure that each function correctly processes its intended operations, adhering to the expected inputs and outputs defined by the CosmWasm standard.

### **Conclusion**

Understanding and implementing entry points are critical for developing smart contracts in CosmWasm. These functions enable the contract to interact seamlessly with the blockchain, ensuring it can be initialized, executed, and queried as intended. By following the guidelines outlined in this chapter, developers can create efficient, secure, and functional smart contracts for the CosmWasm ecosystem.
Loading
Loading