Skip to main content

2. compiling a contract

In this section, we will download the code for a sample contract and compile it into a wasm binary executable.

Prerequisites

Please refer to the Setting up environment guide to install the required dependencies before proceeding.

Download contract

Begin by downloading the cw-contracts repository. You will be compiling the nameservice contract.

Clone the repository:

git clone https://github.com/InterWasm/cw-contracts
cd cw-contracts
git checkout main
cd contracts/nameservice

Compile contract

Compile using cargo

Execute the following command to compile the contract:

cargo wasm

Upon compilation, the file target/wasm32-unknown-unknown/release/cw_nameservice.wasm should be generated. The file size is approximately 1.9 MB, indicating that it is a release build but has not yet been stripped of all unnecessary code. To store the contract on-chain, optimization is required. See the Optimized compilation section below for instructions on optimizing a contract.

Optimized compilation

Optimize using cargo

The following command should give an optimized contract that can be stored on chain:

RUSTFLAGS='-C link-arg=-s' cargo wasm

Optimize using rust-optimizer

info

You will need Docker installed in order to run rust-optimizer.

Navigate to the project root and run the following command:

docker run --rm -v "$(pwd)":/code \
--mount type=volume,source="$(basename "$(pwd)")_cache",target=/code/target \
--mount type=volume,source=registry_cache,target=/usr/local/cargo/registry \
cosmwasm/rust-optimizer:0.12.12

This command will optimize the .wasm file and generate an optimized .wasm file in the artifacts directory.