Skip to main content
Full working code: The complete source code for this example is available in test-contracts/test-token/
This example demonstrates persistent storage, user balances, transactions, and error handling for a fungible token.

WIT Interface

Exports functions for a fungible token with minting, burning, transfers, and balance queries:

Rust Implementation

The token contract uses a Map to store account balances, with helper functions for validation and a total supply tracker:
Key points:
  • Storage accessed via ctx.model(), not a separate storage() function
  • Map operations: ledger.get(&key) and ledger.set(key, value) - no extra ctx parameter
  • Errors use Error::Message(...to_string()) variant
  • Uses checked arithmetic (.add(n)?, .sub(n)?) for overflow safety
  • Helper validation function (assert_gt_zero)
  • Total supply tracking with try_update_* closures

Testing

The test demonstrates minting, transferring, and error handling with proper use of the double ?? operator for functions returning Result:
Key points:
  • Uses interface! to generate bindings, not import!
  • #[testlib::test] auto-injects runtime variable
  • runtime.identity() creates test users
  • runtime.publish() deploys the contract
  • Functions returning Result use ?? to unwrap both the runtime Result and contract Result
  • Integers created with .into() or Integer::from()