Claude
Skills
Sign in
Back

soroban

Included with Lifetime
$97 forever

Soroban smart contract development on Stellar (Rust SDK). Covers project setup, contract structure, storage types, authorization, cross-contract calls, events, error handling, testing (unit, integration, fuzz, property, mutation, fork, differential), security patterns and vulnerability classes, advanced architecture patterns (upgrades, factories, governance, DeFi primitives), and common pitfalls. Use when writing, testing, securing, or shipping Soroban contracts.

Backend & APIs

What this skill does


# Soroban Smart Contracts

End-to-end guide for building Soroban contracts: writing them, testing them, securing them, and shipping advanced architectures. This skill bundles five concerns that live and die together — the contract code, the tests, the security posture, the design patterns, and the gotchas.

## When to use this skill
- Writing a Soroban contract in Rust
- Setting up unit, integration, fuzz, or property tests
- Reviewing a contract for security issues (authorization, reentrancy-adjacent bugs, storage hygiene, TTL, overflow)
- Architecting upgradeable contracts, factories, governance, or DeFi primitives
- Debugging a Soroban-specific error (auth, storage, archival, resource limits)

## Related skills
- Assets, trustlines, and SAC bridge → `../assets/SKILL.md`
- Frontend/wallets that call your contract → `../dapp/SKILL.md`
- Chain data queries (RPC/Horizon) → `../data/SKILL.md`
- ZK cryptography (BLS12-381, BN254, Poseidon) → `../zk-proofs/SKILL.md`
- SEP/CAP standards and ecosystem links → `../standards/SKILL.md`

---

# Part 1: Contract Development


## When to use Soroban
Use Soroban when you need:
- Custom on-chain logic beyond Stellar's built-in operations
- Programmable escrow, lending, or DeFi primitives
- Complex authorization rules
- State management beyond account balances
- Interoperability with Stellar Assets via SAC

## Quick Navigation
- Initialization and constructors: [Project Setup](#project-setup), [Contract Constructors (Protocol 22+)](#contract-constructors-protocol-22)
- Core implementation patterns: [Core Contract Structure](#core-contract-structure), [Storage Types](#storage-types), [Authorization](#authorization)
- Advanced interactions: [Cross-Contract Calls](#cross-contract-calls), [Events](#events), [Error Handling](#error-handling)
- Delivery workflow: [Building and Deploying](#building-and-deploying), [Unit Testing](#unit-testing), [Best Practices](#best-practices)
- ZK status guidance: [Zero-Knowledge Cryptography (Status-Sensitive)](#zero-knowledge-cryptography-status-sensitive)

## Alternative Languages

Rust is the primary and recommended language for Soroban contracts. Community-maintained alternatives exist but are not recommended for production:
- **AssemblyScript**: [`as-soroban-sdk`](https://github.com/Soneso/as-soroban-sdk) by Soneso — allows TypeScript-like syntax, officially listed on Stellar docs, but may lag behind the latest protocol version
- **Solidity**: [Hyperledger Solang](https://github.com/hyperledger-solang/solang) — SDF-funded, compiles Solidity to Soroban WASM, currently **pre-alpha** ([docs](https://developers.stellar.org/docs/learn/migrate/evm/solidity-support-via-solang))

## Architecture Overview

### Host-Guest Model
Soroban uses a WebAssembly sandbox with strict separation:
- **Host Environment**: Provides storage, crypto, cross-contract calls
- **Guest Contract**: Your Rust code compiled to WASM
- Contracts reference host objects via handles (not direct memory)

### Key Constraints
- `#![no_std]` required - no Rust standard library
- 64KB contract size limit (use release optimizations)
- Limited heap allocation
- No string type (use `String` from soroban-sdk or `Symbol` for short strings)
- `Symbol` limited to 32 characters (was 10 in earlier versions)

## Project Setup

### Initialize a new contract
```bash
stellar contract init my-contract
cd my-contract
```

This creates:
```
my-contract/
├── Cargo.toml
├── src/
│   └── lib.rs
└── contracts/
    └── hello_world/
        ├── Cargo.toml
        └── src/
            └── lib.rs
```

### Cargo.toml configuration
```toml
[package]
name = "my-contract"
version = "0.1.0"
edition = "2021"

[lib]
crate-type = ["cdylib"]

[dependencies]
soroban-sdk = "25.0.1"  # check https://crates.io/crates/soroban-sdk for latest

[dev-dependencies]
soroban-sdk = { version = "25.0.1", features = ["testutils"] }  # match above

[profile.release]
opt-level = "z"
overflow-checks = true
debug = 0
strip = "symbols"
debug-assertions = false
panic = "abort"
codegen-units = 1
lto = true

[profile.release-with-logs]
inherits = "release"
debug-assertions = true
```

## Contract Constructors (Protocol 22+)

Use constructors for atomic initialization when protocol support is available. This avoids a separate `initialize` transaction and reduces front-running risk.

### Constructor pattern
```rust
#![no_std]
use soroban_sdk::{contract, contractimpl, contracttype, Address, Env};

#[contracttype]
#[derive(Clone)]
pub enum DataKey {
    Admin,
    Value,
}

#[contract]
pub struct MyContract;

#[contractimpl]
impl MyContract {
    // Runs once at deployment time.
    pub fn __constructor(env: Env, admin: Address, initial_value: u32) {
        env.storage().instance().set(&DataKey::Admin, &admin);
        env.storage().instance().set(&DataKey::Value, &initial_value);
    }
}
```

### Deploy with constructor args (CLI)
```bash
stellar contract deploy \
  --wasm target/wasm32-unknown-unknown/release/my_contract.wasm \
  --source alice \
  --network testnet \
  -- \
  --admin alice \
  --initial_value 100
```

### Rules
1. Name must be `__constructor` exactly.
2. Constructor returns `()` (no return value).
3. Runs only at creation time and does not run on upgrade.
4. If constructor fails, deployment fails atomically.

### Backwards compatibility
If targeting older protocol environments, use guarded `initialize` patterns and prevent re-initialization explicitly.

## Core Contract Structure

### Basic Contract
```rust
#![no_std]
use soroban_sdk::{contract, contractimpl, symbol_short, vec, Env, Symbol, Vec};

#[contract]
pub struct HelloContract;

#[contractimpl]
impl HelloContract {
    pub fn hello(env: Env, to: Symbol) -> Vec<Symbol> {
        vec![&env, symbol_short!("Hello"), to]
    }
}
```

### Contract with State
```rust
#![no_std]
use soroban_sdk::{contract, contractimpl, contracttype, Address, Env};

#[contracttype]
#[derive(Clone)]
pub enum DataKey {
    Counter,
    Admin,
    UserBalance(Address),
}

#[contract]
pub struct CounterContract;

#[contractimpl]
impl CounterContract {
    pub fn initialize(env: Env, admin: Address) {
        if env.storage().instance().has(&DataKey::Admin) {
            panic!("already initialized");
        }
        env.storage().instance().set(&DataKey::Admin, &admin);
        env.storage().instance().set(&DataKey::Counter, &0u32);
    }

    pub fn increment(env: Env) -> u32 {
        let mut count: u32 = env.storage().instance().get(&DataKey::Counter).unwrap_or(0);
        count += 1;
        env.storage().instance().set(&DataKey::Counter, &count);

        // Extend TTL to prevent archival
        env.storage().instance().extend_ttl(100, 518400); // threshold, ~30 days

        count
    }

    pub fn get_count(env: Env) -> u32 {
        env.storage().instance().get(&DataKey::Counter).unwrap_or(0)
    }
}
```

## Storage Types

Soroban has three storage types with different costs and lifetimes:

### Instance Storage
- Tied to contract instance lifetime
- Shared across all users
- Best for: admin addresses, global config, counters
```rust
env.storage().instance().set(&key, &value);
env.storage().instance().get(&key);
env.storage().instance().extend_ttl(min_ttl, extend_to);
```

### Persistent Storage
- Survives archival (can be restored)
- Per-key TTL management
- Best for: user balances, important state
```rust
env.storage().persistent().set(&key, &value);
env.storage().persistent().get(&key);
env.storage().persistent().extend_ttl(&key, min_ttl, extend_to);
```

### Temporary Storage
- Cheapest, automatically deleted when TTL expires
- Cannot be restored after archival
- Best for: caches, temporary flags, session data
```rust
env.storage().temporary().set(&key, &value);
env.storage().temporary().get(&key);
env.storage().temporary().extend_ttl(&key, min_ttl, extend_to);
```

### TTL Management
```rust
// Check remaining TTL
let ttl = env.storage().persistent().get_ttl(&key);

// Extend if below threshold
const MIN_TTL: u32 = 
Files: 1
Size: 69.5 KB
Complexity: 42/100
Category: Backend & APIs

Related in Backend & APIs