Downloading and Compiling a Contract
In this section, we will download the code for a sample contract and compile it into a wasm binary executable.
If you haven't already, please review the "Setting up Environment" page first and either configure the Node.js REPL or the wasmd Go CLI before you proceed.
In this example, we will be utilizing example smart contract code from InterWasm DAO. InterWasm DAO is the organization for CosmWasm ecosystem development.
Compiling and Testing the Contract Code
Let's download the repository in which we keep cw-contracts
and compile the existing code for a simple name service contract that mimics a name service marketplace.
First, clone the repo and try to build the wasm bundle:
The compilation should output the file target/wasm32-unknown-unknown/release/cw_nameservice.wasm
. With a quick ls -lh
you can see that the file size is around 1.8 MB. This is a release build, but not stripped of all the unneeded code. To produce a much smaller version, you can run the following command which tells the compiler to strip the unused parts of the code out:
This produces a file that is about 165kB in size. We either use the command above or utilize another Rust optimizer, the use of which will be covered in the optimized compilation section below, to produce the smallest final wasm binary before it is uploaded to the blockchain.
Unit Tests
Let's try running the unit tests:
After some compilation steps, you should see:
RUST_BACKTRACE=1
will provide you with full stack traces on any error, which is super useful. This only works for unit tests (which test native rust code, not the compiled wasm). Also, if you want to know where cargo wasm
and cargo unit-test
come from, they are just aliases defined in the file .cargo/config
located in the project directory. Take a look at the file contents to understand the cargo flags better.
Optimized Compilation
To reduce gas costs, the binary size should be as small as possible. This will result in a less costly deployment, and lower fees on every interaction. Luckily, there is tooling to help with this. You can optimize production codeusing the rust-optimizer. rust-optimizer
produces reproducible builds of CosmWasm smart contracts. This means third parties can verify that the contract is actually the claimed code.
You will need Docker installed in order to run rust-optimizer
.
Navigate to the project root and run the following command:
On Windows, you can use the following command instead
The binary will be under the folder artifacts
and its size will be 138 kB
.
Last updated