Your First Contract
Let’s build a simple smart contract that demonstrates core Soroban SDK concepts. We’ll create an addition contract based on real examples from the SDK test suite.Write the Contract
Replace
src/lib.rs with this simple addition contract:src/lib.rs
This example is taken from
tests/add_u64/src/lib.rs:1 in the Soroban SDK repository.Understanding the Code
Let’s break down the key components:Contract Declaration
#[contract] attribute marks this struct as a Soroban smart contract. The struct itself can be a simple unit struct or contain state.
Contract Implementation
#[contractimpl] attribute designates this implementation block as containing contract methods. Public functions become callable contract entry points.
Testing with Env
ContractClient for testing. This client provides type-safe methods to invoke your contract functions.
More Complex Examples
Contract with Storage
Here’s an example using persistent storage fromtests/contract_data/src/lib.rs:1:
- Storage API: Using
e.storage().persistent()for permanent data - Key-value operations:
set,get, andremove - Option types:
getreturnsOption<Symbol>for missing keys
Contract with Constructor
Contracts can have initialization logic using__constructor from tests/constructor/src/lib.rs:1:
- Constructor: The
__constructorfunction runs when the contract is deployed - Custom types: Using
#[contracttype]for enums as storage keys - Storage types: Persistent, temporary, and instance storage
Contract with Events
Emit events to track contract activity fromtests/events/src/lib.rs:1:
- Event definition:
#[contractevent]defines event structure - Topics:
#[topic]marks indexed fields for efficient filtering - Publishing:
.publish(&env)emits the event
Testing Best Practices
Use Env::default()
The default environment simulates a clean contract execution context
Register Contracts
Use
env.register() to deploy contracts in the test environmentGenerate Test Data
Use
Address::generate(&env) for random addresses in testsAssert Events
Verify events with
env.events().all() after contract callsCommon Patterns
Error Handling
Authorization
Logging (Development)
Build Commands Reference
Next Steps
Now that you’ve built your first contract, explore more advanced topics:Example Contracts
Explore production-ready contract examples
Developer Guides
Learn advanced patterns and best practices
SDK Documentation
Comprehensive API reference
Soroban CLI
Deploy and interact with contracts