This site requires Javascript to be enabled.

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-contractscd cw-contractsgit checkout maincd 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.

Compile using archway developer cli

Execute the following command to compile the contract:

archway build

This process also generates an unoptimized version of the contract, which will need to be Optimized before being stored on-chain.

Optimized compilation

To reduce gas costs, the binary size should be as small as possible. This will lead to less costly deployment and lower fees for each interaction. Fortunately, there are tools available to assist with this. These optimization tools produce reproducible builds of CosmWasm smart contracts. This means that third parties can verify that the contract indeed contains the claimed code.

Optimize using archway developer cli

To build an optimized wasm binary for storage on the blockchain, use the --optimize flag. The Archway Developer CLI uses the rust-optimizer in the background:

archway build --optimize

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

On Windows, you can run the following command instead from the root of your smart contract's project folder.

docker run --rm -v ${pwd}:/code `
 --mount type=volume,source="$("$(Split-Path -Path $pwd -Leaf)")_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.

Drop Camp is here!

Join the queue and be one of the first to get in!.

Go Camping ↗