Contract creation

Create a Rust project

The easiest and recommended way to start working on a new Sylvia (opens in a new tab) contract is to generate it from the sylvia-template (opens in a new tab).

TERMINAL
cargo generate CosmWasm/sylvia-template

The sylvia-template (opens in a new tab) will generate a lot of code for you. Because this tutorial aims to guide you step-by-step through the process of creating your first contract we will omit the use of the template and show you how to create it from the start.

New project

Smart contracts are Rust library crates. We will start with creating one:

TERMINAL
cargo new --lib ./contract

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:

Cargo.toml
[package]
name = "contract"
version = "0.1.0"
edition = "2021"
 
[lib]
crate-type = ["cdylib"]
 
[dependencies]
sylvia = "1.3.1"
💡

Notice lack of cosmwasm-std dependency. Sylvia reexports it as well as other necessary crates for CosmWasm smart contracts. You can find list of reexported crates in the documentation (opens in a new tab).

As you can see, I added a crate-type field for the library section. Generating the cdylib (opens in a new tab) 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.

Additionally, we added a single dependency - sylvia (opens in a new tab). This is the only dependency you need to start since sylvia (opens in a new tab) reexports all the necessary crates for CosmWasm smart contracts. The most important reexported crates are:

  • cosmwasm-std (opens in a new tab) - Crate that is a standard library for smart contracts. It provides essential utilities for communication with the outside world, helper functions, and types. Every smart contract we will build will use this dependency.
  • schemars (opens in a new tab) - Crate used to create JSON schema documents for our contracts. It is automatically derived on types generated by ^sylvia and will be later used to provide concise API for blockchain users, who might not be Rust developers.
  • cosmwasm-schema (opens in a new tab) - Similar to schemars. This crate expands on schemars and provides us with trait QueryResponses (opens in a new tab) which ties query variants to their responses. I will expand on that later in the book.
  • serde (opens in a new tab) - Framework for serializing and deserializing Rust data structures efficiently and generically.