Overview
Soroban contracts are defined using procedural macros that generate the necessary code to export contract functions and integrate with the Soroban environment. The core macros are#[contract] and #[contractimpl].
Contract Definition
The #[contract] Macro
The #[contract] macro marks a type as a contract. This type will have its implementation functions exported as contract functions.
A crate can have multiple types marked with
#[contract], but when compiled to WASM and deployed, they are treated as a single contract with all their combined functions.The #[contractimpl] Macro
The #[contractimpl] macro exports the public functions in an impl block as contract functions that can be invoked.
- Only
pubfunctions are exported and callable - Private functions remain internal implementation details
- The first parameter can be
Envor&Envfor environment access
Complete Contract Example
Here’s a complete contract with state management:Constructor Support
Contracts can define a constructor that runs when the contract is deployed:Contract Traits
Defining Contract Interfaces
Use#[contracttrait] to define interfaces with default implementations:
Implementing Traits
Error Handling
Define custom error types using#[contracterror]:
Testing Contracts
Contracts can be tested using the generated client:Related Macros
contracttype
Define custom types that can be stored and passed between contracts
contractimport
Import external contracts from WASM files
contractclient
Generate clients for contract trait interfaces
contractmeta
Add metadata to contracts
Best Practices
Keep contracts focused
Keep contracts focused
Each contract should have a single, well-defined purpose. Use multiple contracts for complex applications.
Use descriptive function names
Use descriptive function names
Contract function names should clearly indicate what they do since they become part of the contract’s public API.
Document public functions
Document public functions
Add doc comments to public contract functions - they become part of the contract spec that clients use.
Validate inputs early
Validate inputs early
Perform input validation at the beginning of functions to fail fast and save resources.
Next Steps
Environment
Learn about the Env type and environment functions
Storage
Understand how to persist contract data