Skip to main content
Full working code: The complete source code for this example is available in test-contracts/shared-account/
This example demonstrates a simple multi-tenant shared account introducing static contract imports, complex storage structs, authorization logic, ID generation, and cross-contract calls.

WIT Interface

Exports functions for multi-tenant account management with token deposits and withdrawals:

Rust Implementation

  • The interface! macro generates an interface for cross-contract calls to the token contract with a dynamic address (passed as a parameter). Use import! when the dependency contract has been previously published and the contract address is known at compile time.
  • The StorageRoot macro, used for the root storage type, and the Storage macro, used for nested storage types in the Account struct, enable persistent storage.
  • other_tenants uses Map<String, bool> because the storage layer does not currently support list types, and Map provides a limited interface with the keys method for iteration. Even with a List type using a Map here could make sense. Instead of bool an enum or struct that defines the their “role” in the account could be written.
  • authorized Verifies procedure permissions
  • open: Verifies token balance, generates an ID using crypto::generate_id(), sets the account, and transfers tokens to ctx.contract_signer()
  • deposit/withdraw: Authorize the caller, verify balances, update storage, and call the token contract following CEI pattern
  • balance/tenants: Query the storage for account details
Key points:
  • Uses interface! not import! for dynamic token contract address
  • ctx.model() for storage access
  • Map operations: accounts().get(id) returns Option<AccountModel>
  • Nested struct updates: account.update_balance(|b| b + n)
  • Error helpers return Error::Message(...to_string())
  • authorized() function takes &AccountModel not &AccountWrapper
  • ctx.generate_id() creates unique account IDs
  • Calls token::balance() and token::transfer() with contract addresses

Testing

The test demonstrates creating accounts, depositing, withdrawing, and testing authorization: