Full working code: The complete source code for this example is available in
example-contracts/hello-world/Project Structure
Step 1: Workspace Configuration
RootCargo.toml:
The paths shown assume the
Documentation and Kontor repos are siblings. If you cloned them to different locations, adjust these paths to point to your Kontor installation. See Getting Started for setup details.Step 2: Contract Configuration
contract/Cargo.toml:
crate-type = ["cdylib"]- Builds a dynamic library for WASMstdlibprovides thecontract!macro and runtime primitives
Step 3: Define the Contract Interface (WIT)
Createcontract/wit/contract.wit:
init- Called once when contract is deployedhello-world- Returns a greeting string (read-only)
kontor:built-in types are available via a symlink at wit/deps/built-in.wit.
Step 4: Implement the Contract
Createcontract/src/lib.rs:
contract/src/lib.rs
contract!(name = "hello-world")- Generates theGuesttrait and WASM bindingsimpl Guest for HelloWorld- The contract name is converted to PascalCaseinit()- Empty because we don’t need storagehello_world()- Returns a static string
Step 5: Build and Test
The contract is automatically built when you run tests. The test directory’sbuild.rs handles compilation, optimization, and compression:
build.rs automatically:
- Compiles the contract to WASM
- Optimizes with
wasm-opt -Oz --enable-bulk-memory --enable-sign-ext - Compresses with
brotlito create.wasm.br
Step 6: Write Tests
Createtest/src/lib.rs:
test/src/lib.rs
interface!- Generates type-safe bindings from the WIT file#[testlib::test]- Auto-injects theruntimevariableruntime.identity()- Creates a test user with gas fundingruntime.publish()- Deploys the contract and returns its addresshello_world::hello_world()- Calls the contract function
Common First-Time Issues
contract! macro not found
use stdlib::*; at the top of your file
Missing Guest trait implementation
include kontor:built-in/built-in; in your WIT world
Build target not installed
rustup target add wasm32-unknown-unknown