Writing e2e tests with ink-wrapper

Introduction

While this tutorial focuses on writing e2e (end-to-end) tests, the same approach can be utilized to call your contracts from any backend application written in Rust.

The default tooling for calling contracts provided by subxt and similar tools relies on runtime checks on input data and received responses. In order to provide compile-time checks as well as easy access to code completion and documentation for contracts, we've developed ink-wrapper. Simply put, it's a tool that generates a bunch of strongly-typed wrapper code around submitting contract-related transactions. You can include this generated code in your project and use it, instead of calling primitives like subxt directly.

Setup

To get started you will need to install ink-wrapper itself (this tutorial uses 0.4.1 so please install the same version to follow along):

cargo install ink-wrapper --locked --force --version 0.4.1

In this guide we will write e2e tests for an example PSP22 contract that we use to test ink-wrapper itself. You will need docker to run a chain for testing and use the tooling provided in the repo to compile contracts. With that:

git clone [email protected]:Cardinal-Cryptography/ink-wrapper.git

Finally, let's create a new project that will house our tests:

cargo new --lib psp22-tests

Generating contract wrappers

The ink-wrapper takes a .json metadata file generated while compiling the contract and produces a Rust file based on that. First, setup a node with the contract in question compiled and deployed. This will also run ink-wrapper's own tests at the end - just ignore that.

cd ink-wrapper
make all-dockerized

Then, invoke ink-wrapper on the produced .json metadata file and put the results in the src directory in the psp22-tests project:

Notice that we're piping the output of ink-wrapper through rustfmt - the output is not guaranteed to be formatted, so in order to commit nicely formatted code into your repo, it's recommended to use this method when regenerating the wrapper files.

Using the wrappers

Now, let's move to the psp22-tests project. We will need to add some dependencies to make the wrappers compile:

As well as switch to nightly by putting the following in rust-toolchain.toml:

Attach the module produced by ink-wrapper to psp22-tests:

Now add the following test code:

With that, you should be able to run cargo test and have it pass with 1 test run!

Last updated

Was this helpful?