Counter smart contract tutorial

Create and deploy a simple Cosmwasm smart contract locally

CosmWasm

CosmWasm is a library for writing Rust smart contracts. Gameluk supports CosmWasm 1.0.0+ smart contracts.

Dependencies

Following the instructions in the CosmWasm github to install cargo-generate and cargo-run-script

Create a boilerplate smart contract

Go to a folder in which you want to create a boilerplate smart contract and run

cargo generate --git https://github.com/CosmWasm/cw-template.git --branch 1.0 --name counter -d minimal=false

If you encounter an error saying `no such command: generate` please make sure you have cargo-generate installed

cargo install cargo-generate

This will create a repository with the following structure

.
├── Cargo.toml
├── LICENSE
├── NOTICE
├── README.md
└── src
    ├── bin
    │   └── schema.rs
    ├── contract.rs
    ├── error.rs
    ├── helpers.rs
    ├── lib.rs
    ├── msg.rs
    └── state.rs

This contract defines a simple counter app. It supports 4 basic functions:

  • Instantiate the counter with a starting count

  • Increment the counter by 1

  • Reset the counter

  • Read the current count

To run unit tests, you can run

which will give an output similar to the following

Deploy boilerplate smart contract

In order to deploy a contract, it is recommended to first compile it. Confirm that the prerequisites listed in the CosmWasm docs are met, and then run the following

Before uploading, it may be advisable to consider using the rust-optimizer to potentially reduce the size of the binary that will be uploaded. Additionally, it is important to ensure that the correct version of the optimizer is being used for your specific processor architecture.

x86 64-bits (Intel/AMD):

ARM 64-bits (M1/M2 Macs):

Then create a new file called deploy.sh

Paste the following code into deploy.sh

NB: if you are using an ARM processor (M1/M2 Mac) then you will need to change the contract name to counter-aarch64.wasm in line 2 of the deploy script above

The output will be as follows

Increment count

Next we want to increment the counter and confirm that the state is updated

Create a new file called increment.sh with the following

and then run the script twice

Last updated