diff --git a/src/README.md b/src/README.md index e58fb45..5f09859 100644 --- a/src/README.md +++ b/src/README.md @@ -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. \ No newline at end of file diff --git a/src/basics.md b/src/basics.md index 46e719a..8fec67c 100644 --- a/src/basics.md +++ b/src/basics.md @@ -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. \ No newline at end of file diff --git a/src/basics/entry-points.md b/src/basics/entry-points.md index 39ef7c3..83f1aa8 100644 --- a/src/basics/entry-points.md +++ b/src/basics/entry-points.md @@ -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 { - 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](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](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`](https://docs.rs/cosmwasm-std/1.0.0/cosmwasm_std/type.StdResult.html) for this simple example, -which is an alias for `Result`. 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](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. diff --git a/src/basics/rust-project.md b/src/basics/rust-project.md index a0beaee..c364e0a 100644 --- a/src/basics/rust-project.md +++ b/src/basics/rust-project.md @@ -1,35 +1,39 @@ -# Create a Rust project +# Creating a Rust Project for CosmWasm Smart Contracts -As smart contracts are Rust library crates, we will start with creating one: +Developing smart contracts for the CosmWasm platform requires a structured approach, starting from setting up a Rust project. This dedicated guide will walk you through creating a Rust library crate designed to work as a CosmWasm smart contract, including configuring the cargo.toml file to meet the requirements of compiling to WebAssembly (Wasm), the format needed for deploying on the CosmWasm platform. +### Step 1: Initialize Your Rust Library + +You'll need to create a new Rust library to kick off your smart contract development. Open your terminal and execute the following command, which creates a new directory named empty-contract and initializes a Rust project configured as a library: +```rust +cargo new --lib ./empty-contract ``` -$ cargo new --lib ./empty-contract -``` +This command sets up a basic Rust project structure, including a Cargo. The toml file will be used to manage your project's settings and dependencies, and a src directory will be used where your Contract's Rust source code will reside. -You created a simple Rust library, but it is not yet ready to be a smart contract. The first thing -to do is to update the `Cargo.toml` file: +### Step 2: Configuring the Cargo.toml file + +After setting up your project, the next crucial step is configuring the cargo.toml file. This file resides at the root of your project and dictates how your project is built. Navigate to the empty-contract directory and open the cargo.toml file in your preferred editor to make the following adjustments: ```toml -[package] -name = "contract" +[package] name = "contract" version = "0.1.0" -edition = "2021" +edition = "2021" -[lib] -crate-type = ["cdylib"] +[lib] +crate-type = ["cdylib"] -[dependencies] +[dependencies] cosmwasm-std = { version = "1.0.0-beta8", features = ["staking"] } ``` +### Explanation of Key Configurations: + +- **[package]**: This section defines basic metadata about your project. The edition field specifies which edition of Rust you are targeting, with "2021" being the most recent as of this writing. +- **[lib]**: By specifying crate-type as ["cdylib"], you are instructing Rust to compile your library into a dynamic library, specifically a WebAssembly (Wasm) binary. This is required for the Contract to run in the CosmWasm environment. Note that this configuration means the compiled library cannot be included as a dependency in other Rust crates. +- **[dependencies]**: The cosmwasm-std dependency is essential for smart contract development on the CosmWasm platform. It acts as the standard library, providing the types, functions, and utilities necessary to interact with the blockchain. The version should be the latest stable version compatible with your project's requirements, and the features field enables specific functionalities, such as staking in this case, which may be necessary depending on your Contract's use case. -As you can see, I added a `crate-type` field for the library section. Generating the `cdylib` is -required to create a proper web assembly binary. The downside of this is that such a library cannot -be used as a dependency for other Rust crates - for now, it is not needed, but later we will show -how to approach reusing contracts as dependencies. +### Final Steps: -Additionally, there is one core dependency for smart contracts: the `cosmwasm-std`. This crate is a -standard library for smart contracts. It provides essential utilities for communication with the -outside world and a couple of helper functions and types. Every smart contract we will build will -use this dependency. +With your Rust project correctly configured, you can start writing your smart contract code within the src/lib.rs file. This involves implementing the Contract's logic, including handling initialization, execute, and query operations according to the CosmWasm standard. +As you develop your smart Contract, regularly compile and test your code to ensure that it meets the expected functionalities and security standards required for deployment on the blockchain. Utilizing the comprehensive tooling and resources available in the Rust and CosmWasm communities will aid in this process, helping you to develop robust, efficient, and secure smart contracts. \ No newline at end of file diff --git a/src/setting-up-env.md b/src/setting-up-env.md index a3d35b2..f07e029 100644 --- a/src/setting-up-env.md +++ b/src/setting-up-env.md @@ -1,86 +1,70 @@ -# Setting up the environment - -To work with CosmWasm smart contract, you will need rust installed on your -machine. If you don't have one, you can find installation instructions on [the -Rust website](https://www.rust-lang.org/tools/install). - -I assume you are working with a stable Rust channel in this book. - -Additionally, you will need the Wasm rust compiler backend installed to build -Wasm binaries. To install it, run: - -``` -rustup target add wasm32-unknown-unknown -``` - -Optionally if you want to try out your contracts on a testnet, you will need a -[wasmd](https://github.com/CosmWasm/wasmd) binary. We would focus on testing -contracts with Rust unit testing utility throughout the book, so it is not -required to follow. However, seeing the product working in a real-world -environment may be nice. - -To install `wasmd`, first install the [golang](https://github.com/golang/go/wiki#working-with-go). Then -clone the `wasmd` and install it: - -``` -$ git clone git@github.com:CosmWasm/wasmd.git -$ cd ./wasmd -$ make install -``` - -Also, to be able to upload Rust Wasm Contracts into the blockchain, you will need -to install [docker](https://www.docker.com/). To minimize your contract sizes, -it will be required to run CosmWasm Rust Optimizer; without that, more complex -contracts might exceed a size limit. - -## cosmwasm-check utility - -An additional helpful tool for building smart contracts is the `cosmwasm-check`[utility](https://github.com/CosmWasm/cosmwasm/tree/main/packages/check). It allows you to check if the wasm binary is a proper smart contract ready to upload into the blockchain. You can install it using cargo: - -``` -$ cargo install cosmwasm-check -``` - -If the installation succeeds, you should be able to execute the utility from your command line. - -``` -$ cosmwasm-check --version -Contract checking 1.2.3 -``` - -## Verifying the installation - -To guarantee you are ready to build your smart contracts, you need to make sure you can build examples. -Checkout the [cw-plus](https://github.com/CosmWasm/cw-plus) repository and run the testing command in -its folder: - -``` -$ git clone git@github.com:CosmWasm/cw-plus.git -$ cd ./cw-plus -cw-plus $ cargo test -``` - -You should see that everything in the repository gets compiled, and all tests pass. - -`cw-plus` is a great place to find example contracts - look for them in `contracts` directory. The -repository is maintained by CosmWasm creators, so contracts in there should follow good practices. - -To verify the `cosmwasm-check` utility, first, you need to build a smart contract. Go to some contract directory, for example, `contracts/cw1-whitelist`, and call `cargo wasm`: - -``` -cw-plus $ cd contracts/cw1-whitelist -cw-plus/contracts/cw1-whitelist $ cargo wasm -``` - -You should be able to find your output binary in the `target/wasm32-unknown-unknown/release/` -of the root repo directory - not in the contract directory itself! Now you can check if contract -validation passes: - -``` -cw-plus/contracts/cw1-whitelist $ cosmwasm-check ../../target/wasm32-unknown-unknown/release/cw1_whitelist.wasm -Available capabilities: {"iterator", "cosmwasm_1_1", "cosmwasm_1_2", "stargate", "staking"} - -../../target/wasm32-unknown-unknown/release/cw1_whitelist.wasm: pass - -All contracts (1) passed checks! -``` +# **Setting Up Your Environment for CosmWasm Development** + +A properly configured development environment is crucial to begin working with CosmWasm smart contracts. This guide will walk you through setting up the necessary tools and verifying that everything is in place to build and deploy smart contracts on the Cosmos blockchain. + +### Prerequisites + +1. **Rust Installation:** You need Rust installed on your machine. You can find the installation instructions on the Rust website if Rust is not already installed. This guide assumes you are using the stable Rust channel. +2. **Wasm Compiler Backend:** The Wasm rust compiler backend is required for building Wasm binaries. Install it using the following Rust toolchain command: + + ```rust + rustup target add wasm32-unknown-unknown + ``` + +3. **[Wasmd](https://github.com/CosmWasm/wasmd):** If you want to deploy your contracts on a testnet, you'll need the **`wasmd`** binary. While this guide focuses on Rust unit testing for contract validation, testing in a real-world scenario can be beneficial. To install **`wasmd`**: + - Install [golang](https://github.com/golang/go/wiki#working-with-go) on your machine. + - Clone and install **`wasmd`** with the following commands: + + ```rust + git clone git@github.com:CosmWasm/wasmd.git + cd ./wasmd + make install + ``` + +4. **[docker](https://www.docker.com/):** Installing Docker is necessary for utilizing the CosmWasm Rust Optimizer, which is crucial for minimizing contract sizes. Complex contracts without optimization might exceed the blockchain's size limit. +5. **cosmwasm-check [utility](https://github.com/CosmWasm/cosmwasm/tree/main/packages/check)** A valuable tool for smart contract development is **`cosmwasm-check`**. It checks if the wasm binary is a valid smart contract ready for blockchain deployment. Install it using cargo: + + ```rust + cargo install cosmwasm-check + ``` + + Verify the installation by checking the utility's version: + + ```rust + cosmwasm-check --version + ``` + + You should see an output like **`Contract checking 1.2.3`**. + + +### Verifying Installation + +To ensure your development environment is correctly set up, it's essential to test building and running examples: + +1. **Test Building with cw-plus:** Clone the **`cw-plus`** repository and run tests to confirm everything compiles and passes as expected. + + ```rust + git clone git@github.com:CosmWasm/cw-plus.git + cd ./cw-plus + cargo test + ``` + + The **`cw-plus`** repository contains example contracts and is maintained by the CosmWasm team, adhering to best practices. + +2. **Verifying cosmwasm-check Utility:** Build a smart contract to test the **`cosmwasm-check`** utility. For example, navigate to the **`contracts/cw1-whitelist`** directory and build the contract: + + ```rust + cd contracts/cw1-whitelist + cargo wasm + ``` + + Then, check if the contract validation passes: + + ```rust + cosmwasm-check ../../target/wasm32-unknown-unknown/release/cw1_whitelist.wasm + ``` + + Successful output should list available capabilities and confirm that the contract passed checks. + + +Following these steps will set your environment up for CosmWasm smart contract development. You are ready to build, test, and deploy smart contracts on the Cosmos blockchain. \ No newline at end of file diff --git a/src/wasmd-quick-start.md b/src/wasmd-quick-start.md index a629cb3..ca3c8ec 100644 --- a/src/wasmd-quick-start.md +++ b/src/wasmd-quick-start.md @@ -1,8 +1,45 @@ -# Quick start with `wasmd` - -In the past, we suggested playing with contracts on the `malaga` testnet using `wasmd`. -Now `malaga` is no longer operative, and the best way to test the contract in the -real environment is to use one of the big CosmWasm chains testnets - Osmosis, Juno, -Terra, or other ones. -[Here](https://docs.osmosis.zone/cosmwasm/testnet/cosmwasm-deployment/) is the -recommended introduction on how to start with the Osmosis testnet. +# Getting Started with wasmd + +Welcome to the world of CosmWasm development! If you want to dive into smart contract development on the Cosmos network, starting with wasmd is a fantastic choice. wasmd is the backbone for deploying and managing CosmWasm smart contracts on various Cosmos SDK-based blockchains. This guide will walk you through the initial steps of getting started with wasmd, focusing on using the Osmosis testnet as your playground for deploying and testing your contracts. + +### Step 1: Setting Up Your Development Environment + +Before you begin, ensure your development environment is ready. You'll need: + +- **Go:** Install the latest version of Go (at least version 1.17). +- **Rust:** CosmWasm contracts are written in Rust, so you'll need the Rust toolchain. +- **Node.js and Yarn:** For managing front-end applications and script tooling. + +After setting up the necessary tools, install wasmd by cloning the repository and following the build instructions in the README file. + +### Step 2: Joining the Osmosis Testnet + +The Osmosis testnet offers a vibrant environment for testing your CosmWasm contracts. To join the testnet:[Here](https://docs.osmosis.zone/cosmwasm/testnet/cosmwasm-deployment/) + +1. **Get Testnet Tokens:** Visit the Osmosis faucet to obtain testnet tokens. These tokens are used for deploying contracts and executing transactions on the testnet. +2. **Configure wasmd:** Follow the Osmosis documentation to configure your wasmd instance for the Osmosis testnet. This typically involves setting the correct endpoints and configuring your wallet. + +### Step 3: Writing Your First Contract + +With your environment set up and connected to the Osmosis testnet, it's time to write your first Contract. Start with a simple contract, such as a "Hello, World!" or a basic counter. The CosmWasm documentation provides templates and tutorials to get you started. + +### Step 4: Compiling and Deploying + +Once your Contract is ready: + +1. **Compile Your Contract:** Use cargo wasm to compile your Rust contract into WebAssembly (Wasm). +2. **Deploy to the Testnet:** Use wasmd to deploy your compiled Contract to the Osmosis testnet. You must specify your Contract's Wasm file and provide an instantiation message. + +### Step 5: Interacting with Your Contract + +After deployment, interact with your Contract through wasmd by sending executed transactions. You can also query your Contract's state to see the results of your interactions. + +### Next Steps + +Congratulations! You've just deployed your first CosmWasm contract to the Osmosis testnet. From here, you can: + +- Explore more complex contract logic. +- Participate in the CosmWasm community for support and collaboration. +- Test your contracts on other CosmWasm chain testnets like Juno and Terra for broader exposure. + +This quick start guide is just the beginning of your journey with wasmd and CosmWasm. As you become more comfortable with contract development, you'll discover the power and flexibility of the CosmWasm ecosystem. Happy coding! \ No newline at end of file