[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M77K93GSRS9AWX75YBP0XP5S":3,"skill-same:01M77K93GSRS9AWX75YBP0XP5S":51},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":27,"commitSha":28,"skillDirectory":29,"forksCount":30,"repositoryHtmlUrl":31,"repositoryHomepageUrl":32,"ownerHtmlUrl":33,"ownerBlogUrl":34,"ownerDescription":35,"updatedAt":36,"install":37,"resources":50},"01M77K93GSRS9AWX75YBP0XP5S","soroban",null,"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.","WritzProtocol\u002Fwritz","WritzProtocol","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F296057967?v=4","01M77K5N0T3073T814APZTAXM4","Writz Protocol","01M77K5N1WQ551ZKCCK9MR379A",6,"Apache-2.0","https:\u002F\u002Fgithub.com\u002FWritzProtocol\u002Fwritz\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fsoroban\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: soroban\ndescription: 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.\nmetadata:\n  user-invocable: \"true\"\n  argument-hint: \"[contract task]\"\n---\n\n# Soroban Smart Contracts\n\nEnd-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.\n\n## When to use this skill\n- Writing a Soroban contract in Rust\n- Setting up unit, integration, fuzz, or property tests\n- Reviewing a contract for security issues (authorization, reentrancy-adjacent bugs, storage hygiene, TTL, overflow)\n- Architecting upgradeable contracts, factories, governance, or DeFi primitives\n- Debugging a Soroban-specific error (auth, storage, archival, resource limits)\n\n## Related skills\n- Assets, trustlines, and SAC bridge → `..\u002Fassets\u002FSKILL.md`\n- Frontend\u002Fwallets that call your contract → `..\u002Fdapp\u002FSKILL.md`\n- Chain data queries (RPC\u002FHorizon) → `..\u002Fdata\u002FSKILL.md`\n- ZK cryptography (BLS12-381, BN254, Poseidon) → `..\u002Fzk-proofs\u002FSKILL.md`\n- SEP\u002FCAP standards and ecosystem links → `..\u002Fstandards\u002FSKILL.md`\n\n---\n\n# Part 1: Contract Development\n\n\n## When to use Soroban\nUse Soroban when you need:\n- Custom on-chain logic beyond Stellar's built-in operations\n- Programmable escrow, lending, or DeFi primitives\n- Complex authorization rules\n- State management beyond account balances\n- Interoperability with Stellar Assets via SAC\n\n## Quick Navigation\n- Initialization and constructors: [Project Setup](#project-setup), [Contract Constructors (Protocol 22+)](#contract-constructors-protocol-22)\n- Core implementation patterns: [Core Contract Structure](#core-contract-structure), [Storage Types](#storage-types), [Authorization](#authorization)\n- Advanced interactions: [Cross-Contract Calls](#cross-contract-calls), [Events](#events), [Error Handling](#error-handling)\n- Delivery workflow: [Building and Deploying](#building-and-deploying), [Unit Testing](#unit-testing), [Best Practices](#best-practices)\n- ZK status guidance: [Zero-Knowledge Cryptography (Status-Sensitive)](#zero-knowledge-cryptography-status-sensitive)\n\n## Alternative Languages\n\nRust is the primary and recommended language for Soroban contracts. Community-maintained alternatives exist but are not recommended for production:\n- **AssemblyScript**: [`as-soroban-sdk`](https:\u002F\u002Fgithub.com\u002FSoneso\u002Fas-soroban-sdk) by Soneso - allows TypeScript-like syntax, officially listed on Stellar docs, but may lag behind the latest protocol version\n- **Solidity**: [Hyperledger Solang](https:\u002F\u002Fgithub.com\u002Fhyperledger-solang\u002Fsolang) - SDF-funded, compiles Solidity to Soroban WASM, currently **pre-alpha** ([docs](https:\u002F\u002Fdevelopers.stellar.org\u002Fdocs\u002Flearn\u002Fmigrate\u002Fevm\u002Fsolidity-support-via-solang))\n\n## Architecture Overview\n\n### Host-Guest Model\nSoroban uses a WebAssembly sandbox with strict separation:\n- **Host Environment**: Provides storage, crypto, cross-contract calls\n- **Guest Contract**: Your Rust code compiled to WASM\n- Contracts reference host objects via handles (not direct memory)\n\n### Key Constraints\n- `#![no_std]` required - no Rust standard library\n- 64KB contract size limit (use release optimizations)\n- Limited heap allocation\n- No string type (use `String` from soroban-sdk or `Symbol` for short strings)\n- `Symbol` limited to 32 characters (was 10 in earlier versions)\n\n## Project Setup\n\n### Initialize a new contract\n```bash\nstellar contract init my-contract\ncd my-contract\n```\n\nThis creates:\n```\nmy-contract\u002F\n├── Cargo.toml\n├── src\u002F\n│   └── lib.rs\n└── contracts\u002F\n    └── hello_world\u002F\n        ├── Cargo.toml\n        └── src\u002F\n            └── lib.rs\n```\n\n### Cargo.toml configuration\n```toml\n[package]\nname = \"my-contract\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[lib]\ncrate-type = [\"cdylib\"]\n\n[dependencies]\nsoroban-sdk = \"25.0.1\"  # check https:\u002F\u002Fcrates.io\u002Fcrates\u002Fsoroban-sdk for latest\n\n[dev-dependencies]\nsoroban-sdk = { version = \"25.0.1\", features = [\"testutils\"] }  # match above\n\n[profile.release]\nopt-level = \"z\"\noverflow-checks = true\ndebug = 0\nstrip = \"symbols\"\ndebug-assertions = false\npanic = \"abort\"\ncodegen-units = 1\nlto = true\n\n[profile.release-with-logs]\ninherits = \"release\"\ndebug-assertions = true\n```\n\n## Contract Constructors (Protocol 22+)\n\nUse constructors for atomic initialization when protocol support is available. This avoids a separate `initialize` transaction and reduces front-running risk.\n\n### Constructor pattern\n```rust\n#![no_std]\nuse soroban_sdk::{contract, contractimpl, contracttype, Address, Env};\n\n#[contracttype]\n#[derive(Clone)]\npub enum DataKey {\n    Admin,\n    Value,\n}\n\n#[contract]\npub struct MyContract;\n\n#[contractimpl]\nimpl MyContract {\n    \u002F\u002F Runs once at deployment time.\n    pub fn __constructor(env: Env, admin: Address, initial_value: u32) {\n        env.storage().instance().set(&DataKey::Admin, &admin);\n        env.storage().instance().set(&DataKey::Value, &initial_value);\n    }\n}\n```\n\n### Deploy with constructor args (CLI)\n```bash\nstellar contract deploy \\\n  --wasm target\u002Fwasm32-unknown-unknown\u002Frelease\u002Fmy_contract.wasm \\\n  --source alice \\\n  --network testnet \\\n  -- \\\n  --admin alice \\\n  --initial_value 100\n```\n\n### Rules\n1. Name must be `__constructor` exactly.\n2. Constructor returns `()` (no return value).\n3. Runs only at creation time and does not run on upgrade.\n4. If constructor fails, deployment fails atomically.\n\n### Backwards compatibility\nIf targeting older protocol environments, use guarded `initialize` patterns and prevent re-initialization explicitly.\n\n## Core Contract Structure\n\n### Basic Contract\n```rust\n#![no_std]\nuse soroban_sdk::{contract, contractimpl, symbol_short, vec, Env, Symbol, Vec};\n\n#[contract]\npub struct HelloContract;\n\n#[contractimpl]\nimpl HelloContract {\n    pub fn hello(env: Env, to: Symbol) -> Vec\u003CSymbol> {\n        vec![&env, symbol_short!(\"Hello\"), to]\n    }\n}\n```\n\n### Contract with State\n```rust\n#![no_std]\nuse soroban_sdk::{contract, contractimpl, contracttype, Address, Env};\n\n#[contracttype]\n#[derive(Clone)]\npub enum DataKey {\n    Counter,\n    Admin,\n    UserBalance(Address),\n}\n\n#[contract]\npub struct CounterContract;\n\n#[contractimpl]\nimpl CounterContract {\n    pub fn initialize(env: Env, admin: Address) {\n        if env.storage().instance().has(&DataKey::Admin) {\n            panic!(\"already initialized\");\n        }\n        env.storage().instance().set(&DataKey::Admin, &admin);\n        env.storage().instance().set(&DataKey::Counter, &0u32);\n    }\n\n    pub fn increment(env: Env) -> u32 {\n        let mut count: u32 = env.storage().instance().get(&DataKey::Counter).unwrap_or(0);\n        count += 1;\n        env.storage().instance().set(&DataKey::Counter, &count);\n\n        \u002F\u002F Extend TTL to prevent archival\n        env.storage().instance().extend_ttl(100, 518400); \u002F\u002F threshold, ~30 days\n\n        count\n    }\n\n    pub fn get_count(env: Env) -> u32 {\n        env.storage().instance().get(&DataKey::Counter).unwrap_or(0)\n    }\n}\n```\n\n## Storage Types\n\nSoroban has three storage types with different costs and lifetimes:\n\n### Instance Storage\n- Tied to contract instance lifetime\n- Shared across all users\n- Best for: admin addresses, global config, counters\n```rust\nenv.storage().instance().set(&key, &value);\nenv.storage().instance().get(&key);\nenv.storage().instance().extend_ttl(min_ttl, extend_to);\n```\n\n### Persistent Storage\n- Survives archival (can be restored)\n- Per-key TTL management\n- Best for: user balances, important state\n```rust\nenv.storage().persistent().set(&key, &value);\nenv.storage().persistent().get(&key);\nenv.storage().persistent().extend_ttl(&key, min_ttl, extend_to);\n```\n\n### Temporary Storage\n- Cheapest, automatically deleted when TTL expires\n- Cannot be restored after archival\n- Best for: caches, temporary flags, session data\n```rust\nenv.storage().temporary().set(&key, &value);\nenv.storage().temporary().get(&key);\nenv.storage().temporary().extend_ttl(&key, min_ttl, extend_to);\n```\n\n### TTL Management\n```rust\n\u002F\u002F Check remaining TTL\nlet ttl = env.storage().persistent().get_ttl(&key);\n\n\u002F\u002F Extend if below threshold\nconst MIN_TTL: u32 = 17280;  \u002F\u002F ~1 day at 5s ledgers\nconst EXTEND_TO: u32 = 518400;  \u002F\u002F ~30 days\n\nif ttl \u003C MIN_TTL {\n    env.storage().persistent().extend_ttl(&key, MIN_TTL, EXTEND_TO);\n}\n```\n\n## Data Types\n\n### Primitive Types\n```rust\nuse soroban_sdk::{Address, Bytes, BytesN, Map, String, Symbol, Vec, I128, U256};\n\n\u002F\u002F Address - account or contract identifier\nlet addr: Address = env.current_contract_address();\n\n\u002F\u002F Symbol - short strings (max 32 chars)\nlet sym: Symbol = symbol_short!(\"transfer\");\n\n\u002F\u002F String - longer strings\nlet s: String = String::from_str(&env, \"Hello, Stellar!\");\n\n\u002F\u002F Fixed-size bytes\nlet hash: BytesN\u003C32> = env.crypto().sha256(&bytes);\n\n\u002F\u002F Collections\nlet v: Vec\u003Cu32> = vec![&env, 1, 2, 3];\nlet m: Map\u003CSymbol, u32> = Map::new(&env);\n```\n\n### Custom Types\n```rust\n#[contracttype]\n#[derive(Clone, Debug, Eq, PartialEq)]\npub struct TokenMetadata {\n    pub name: String,\n    pub symbol: Symbol,\n    pub decimals: u32,\n}\n\n#[contracttype]\n#[derive(Clone)]\npub enum DataKey {\n    Admin,\n    Balance(Address),\n    Allowance(Address, Address),  \u002F\u002F (owner, spender)\n}\n```\n\n## Authorization\n\n### Requiring Authorization\n```rust\n#[contractimpl]\nimpl TokenContract {\n    pub fn transfer(env: Env, from: Address, to: Address, amount: i128) {\n        \u002F\u002F Require 'from' to authorize this call\n        from.require_auth();\n\n        \u002F\u002F Or require auth for specific arguments\n        from.require_auth_for_args((&to, amount).into_val(&env));\n\n        \u002F\u002F Transfer logic...\n    }\n}\n```\n\n### Admin Patterns\n```rust\nfn require_admin(env: &Env) {\n    let admin: Address = env.storage().instance().get(&DataKey::Admin).unwrap();\n    admin.require_auth();\n}\n\npub fn set_admin(env: Env, new_admin: Address) {\n    require_admin(&env);\n    env.storage().instance().set(&DataKey::Admin, &new_admin);\n}\n```\n\n## Cross-Contract Calls\n\n### Calling Another Contract\n```rust\nuse soroban_sdk::{contract, contractimpl, Address, Env};\n\nmod token_contract {\n    soroban_sdk::contractimport!(\n        file = \"..\u002Ftoken\u002Ftarget\u002Fwasm32-unknown-unknown\u002Frelease\u002Ftoken.wasm\"\n    );\n}\n\n#[contract]\npub struct VaultContract;\n\n#[contractimpl]\nimpl VaultContract {\n    pub fn deposit(env: Env, user: Address, token: Address, amount: i128) {\n        user.require_auth();\n\n        \u002F\u002F Create client for token contract\n        let token_client = token_contract::Client::new(&env, &token);\n\n        \u002F\u002F Call transfer on token contract\n        token_client.transfer(&user, &env.current_contract_address(), &amount);\n\n        \u002F\u002F Update vault state...\n    }\n}\n```\n\n### Using Stellar Asset Contract (SAC)\n```rust\nuse soroban_sdk::token::Client as TokenClient;\n\npub fn transfer_asset(env: Env, from: Address, to: Address, asset: Address, amount: i128) {\n    from.require_auth();\n\n    let token = TokenClient::new(&env, &asset);\n    token.transfer(&from, &to, &amount);\n}\n```\n\n## Events\n\n### Emitting Events\n```rust\nuse soroban_sdk::{contract, contractevent, contractimpl, Address, Env};\n\n#[contractevent(topics = [\"transfer\"])]\npub struct TransferEvent {\n    pub from: Address,\n    pub to: Address,\n    pub amount: i128,\n}\n\n#[contract]\npub struct TokenContract;\n\n#[contractimpl]\nimpl TokenContract {\n    pub fn transfer(env: Env, from: Address, to: Address, amount: i128) {\n        \u002F\u002F ... transfer logic ...\n\n        \u002F\u002F Emit event\n        TransferEvent { from, to, amount }.publish(&env);\n    }\n}\n```\n\n## Error Handling\n\n### Custom Errors\n```rust\nuse soroban_sdk::contracterror;\n\n#[contracterror]\n#[derive(Copy, Clone, Debug, Eq, PartialEq)]\n#[repr(u32)]\npub enum ContractError {\n    AlreadyInitialized = 1,\n    NotInitialized = 2,\n    InsufficientBalance = 3,\n    Unauthorized = 4,\n    InvalidAmount = 5,\n}\n\n\u002F\u002F Usage\npub fn transfer(env: Env, from: Address, to: Address, amount: i128) -> Result\u003C(), ContractError> {\n    if amount \u003C= 0 {\n        return Err(ContractError::InvalidAmount);\n    }\n\n    let balance: i128 = get_balance(&env, &from);\n    if balance \u003C amount {\n        return Err(ContractError::InsufficientBalance);\n    }\n\n    \u002F\u002F ... transfer logic ...\n    Ok(())\n}\n```\n\n## Building and Deploying\n\n### Build Contract\n```bash\n# Build optimized WASM\nstellar contract build\n\n# Output: target\u002Fwasm32-unknown-unknown\u002Frelease\u002Fmy_contract.wasm\n```\n\n### Deploy to Testnet\n```bash\n# Generate and fund a new identity\nstellar keys generate --global alice --network testnet --fund\n\n# Deploy contract\nstellar contract deploy \\\n  --wasm target\u002Fwasm32-unknown-unknown\u002Frelease\u002Fmy_contract.wasm \\\n  --source alice \\\n  --network testnet\n\n# Returns: CONTRACT_ID (starts with 'C')\n```\n\n### Initialize Contract\n```bash\nstellar contract invoke \\\n  --id CONTRACT_ID \\\n  --source alice \\\n  --network testnet \\\n  -- \\\n  initialize \\\n  --admin alice\n```\n\n### Invoke Functions\n```bash\nstellar contract invoke \\\n  --id CONTRACT_ID \\\n  --source alice \\\n  --network testnet \\\n  -- \\\n  increment\n```\n\n## Unit Testing\n\n```rust\n#![cfg(test)]\n\nuse super::*;\nuse soroban_sdk::testutils::Address as _;\nuse soroban_sdk::Env;\n\n#[test]\nfn test_increment() {\n    let env = Env::default();\n    let contract_id = env.register(CounterContract, ());\n    let client = CounterContractClient::new(&env, &contract_id);\n\n    let admin = Address::generate(&env);\n    client.initialize(&admin);\n\n    assert_eq!(client.get_count(), 0);\n    assert_eq!(client.increment(), 1);\n    assert_eq!(client.increment(), 2);\n    assert_eq!(client.get_count(), 2);\n}\n\n#[test]\nfn test_transfer_with_auth() {\n    let env = Env::default();\n    env.mock_all_auths();  \u002F\u002F Auto-approve all auth requests\n\n    let contract_id = env.register(TokenContract, ());\n    let client = TokenContractClient::new(&env, &contract_id);\n\n    let alice = Address::generate(&env);\n    let bob = Address::generate(&env);\n\n    \u002F\u002F Mint tokens to alice\n    client.mint(&alice, &1000);\n\n    \u002F\u002F Transfer from alice to bob\n    client.transfer(&alice, &bob, &100);\n\n    assert_eq!(client.balance(&alice), 900);\n    assert_eq!(client.balance(&bob), 100);\n}\n```\n\n## Best Practices\n\n### Contract Size Optimization\n- Use `symbol_short!()` for symbols under 9 chars (more efficient)\n- Avoid unnecessary string operations\n- Use appropriate storage type for data lifetime\n- Consider splitting large contracts\n\n### Storage Efficiency\n- Use compact data structures\n- Clean up temporary storage\n- Batch storage operations when possible\n- Manage TTLs proactively to avoid archival\n\n### Security\n- Always validate inputs\n- Use `require_auth()` for sensitive operations\n- Check contract ownership in initialization\n- Prevent reinitialization attacks\n- Validate cross-contract call targets\n\n### Gas\u002FResource Optimization\n- Minimize storage reads\u002Fwrites\n- Use events for data that doesn't need on-chain queries\n- Batch operations where possible\n- Profile resource usage with `stellar contract invoke --sim`\n\n## Zero-Knowledge Cryptography (Status-Sensitive)\n\nStellar's ZK cryptography capabilities are evolving. Treat availability as protocol- and network-dependent.\n\n- [CAP-0059](https:\u002F\u002Fgithub.com\u002Fstellar\u002Fstellar-protocol\u002Fblob\u002Fmaster\u002Fcore\u002Fcap-0059.md): BLS12-381 primitives\n- [CAP-0074](https:\u002F\u002Fgithub.com\u002Fstellar\u002Fstellar-protocol\u002Fblob\u002Fmaster\u002Fcore\u002Fcap-0074.md): BN254 host functions (proposed)\n- [CAP-0075](https:\u002F\u002Fgithub.com\u002Fstellar\u002Fstellar-protocol\u002Fblob\u002Fmaster\u002Fcore\u002Fcap-0075.md): Poseidon\u002FPoseidon2 host functions (proposed)\n\nBefore implementation, always verify:\n1. CAP status in the CAP preamble (`Accepted`\u002F`Implemented` vs draft\u002Fawaiting decision)\n2. Target network software version and protocol support\n3. `soroban-sdk` release support for the target host functions\n\n### Practical guidance\n- Use BLS12-381 features where supported and documented in your target SDK\u002Fnetwork.\n- For BN254\u002FPoseidon plans, design feature flags and graceful fallbacks until support is active.\n- Keep cryptographic assumptions explicit in audits and deployment notes.\n\n### Example references\n- [Groth16 Verifier](https:\u002F\u002Fgithub.com\u002Fstellar\u002Fsoroban-examples\u002Ftree\u002Fmain\u002Fgroth16_verifier)\n- [Soroban examples repository](https:\u002F\u002Fgithub.com\u002Fstellar\u002Fsoroban-examples)\n\n> See [zk-proofs.md](..\u002Fzk-proofs\u002FSKILL.md) for Groth16 verification patterns, Poseidon usage, Noir\u002FRISC Zero integration, and implementation guidance.\n\n---\n\n# Part 2: Testing Strategy\n\n\n## Quick Navigation\n- Strategy overview: [Testing Pyramid](#testing-pyramid)\n- Core test layers: [Unit Testing with Soroban SDK](#unit-testing-with-soroban-sdk), [Local Testing with Stellar Quickstart](#local-testing-with-stellar-quickstart), [Testnet Testing](#testnet-testing)\n- Integration and CI: [Integration Testing Patterns](#integration-testing-patterns), [Test Configuration](#test-configuration), [CI\u002FCD Configuration](#cicd-configuration)\n- Advanced testing: [Fuzz Testing](#fuzz-testing), [Property-Based Testing](#property-based-testing), [Differential Testing with Test Snapshots](#differential-testing-with-test-snapshots), [Fork Testing](#fork-testing), [Mutation Testing](#mutation-testing)\n- Performance and readiness: [Resource Profiling](#resource-profiling), [Best Practices](#best-practices)\n\n## Testing Pyramid\n\n1. **Unit tests (fast)**: Native Rust tests with `soroban-sdk` testutils\n2. **Local integration tests**: Stellar Quickstart Docker\n3. **Testnet tests**: Deploy and test on public testnet\n4. **Mainnet smoke tests**: Final validation before production\n\n## Unit Testing with Soroban SDK\n\nThe Soroban SDK provides comprehensive testing utilities that run natively (not in WASM), enabling fast iteration with full debugging support.\n\n### Basic Test Setup\n\n```rust\n#![cfg(test)]\n\nuse soroban_sdk::{testutils::Address as _, Address, Env};\n\n\u002F\u002F Import your contract\nuse crate::{Contract, ContractClient};\n\n#[test]\nfn test_basic_functionality() {\n    \u002F\u002F Create test environment\n    let env = Env::default();\n\n    \u002F\u002F Register contract\n    let contract_id = env.register(Contract, ());\n\n    \u002F\u002F Create typed client\n    let client = ContractClient::new(&env, &contract_id);\n\n    \u002F\u002F Generate test addresses\n    let user = Address::generate(&env);\n\n    \u002F\u002F Call contract functions\n    client.initialize(&user);\n\n    \u002F\u002F Assert results\n    assert_eq!(client.get_value(), 0);\n}\n```\n\n### Testing Authorization\n\n```rust\n#[test]\nfn test_with_auth() {\n    let env = Env::default();\n\n    \u002F\u002F Mock all authorizations automatically\n    env.mock_all_auths();\n\n    let contract_id = env.register(TokenContract, ());\n    let client = TokenContractClient::new(&env, &contract_id);\n\n    let admin = Address::generate(&env);\n    let user1 = Address::generate(&env);\n    let user2 = Address::generate(&env);\n\n    \u002F\u002F Initialize and mint\n    client.initialize(&admin);\n    client.mint(&user1, &1000);\n\n    \u002F\u002F Transfer (requires auth from user1)\n    client.transfer(&user1, &user2, &100);\n\n    assert_eq!(client.balance(&user1), 900);\n    assert_eq!(client.balance(&user2), 100);\n\n    \u002F\u002F Verify which auths were required\n    let auths = env.auths();\n    assert_eq!(auths.len(), 1);\n    \u002F\u002F auths[0] contains (address, contract_id, function, args)\n}\n```\n\n### Testing with Specific Auth Requirements\n\n```rust\n#[test]\nfn test_specific_auth() {\n    let env = Env::default();\n    let contract_id = env.register(Contract, ());\n    let client = ContractClient::new(&env, &contract_id);\n\n    let user = Address::generate(&env);\n\n    \u002F\u002F Mock auth only for specific address\n    env.mock_auths(&[MockAuth {\n        address: &user,\n        invoke: &MockAuthInvoke {\n            contract: &contract_id,\n            fn_name: \"transfer\",\n            args: (&user, &other, &100i128).into_val(&env),\n            sub_invokes: &[],\n        },\n    }]);\n\n    client.transfer(&user, &other, &100);\n}\n```\n\n### Testing Time-Dependent Logic\n\n```rust\n#[test]\nfn test_time_based() {\n    let env = Env::default();\n    let contract_id = env.register(VestingContract, ());\n    let client = VestingContractClient::new(&env, &contract_id);\n\n    let beneficiary = Address::generate(&env);\n\n    \u002F\u002F Set initial timestamp\n    env.ledger().set_timestamp(1000);\n\n    client.create_vesting(&beneficiary, &1000, &2000); \u002F\u002F unlock at t=2000\n\n    \u002F\u002F Try to claim before unlock\n    assert!(client.try_claim(&beneficiary).is_err());\n\n    \u002F\u002F Advance time past unlock\n    env.ledger().set_timestamp(2500);\n\n    \u002F\u002F Now claim succeeds\n    client.claim(&beneficiary);\n}\n```\n\n### Testing Ledger State\n\n```rust\n#[test]\nfn test_ledger_manipulation() {\n    let env = Env::default();\n\n    \u002F\u002F Set ledger sequence\n    env.ledger().set_sequence_number(1000);\n\n    \u002F\u002F Set timestamp\n    env.ledger().set_timestamp(1704067200); \u002F\u002F Jan 1, 2024\n\n    \u002F\u002F Set network passphrase\n    env.ledger().set_network_id([0u8; 32]); \u002F\u002F Custom network ID\n\n    \u002F\u002F Get current values\n    let seq = env.ledger().sequence();\n    let ts = env.ledger().timestamp();\n}\n```\n\n### Testing Events\n\n```rust\n#[test]\nfn test_events() {\n    let env = Env::default();\n    let contract_id = env.register(Contract, ());\n    let client = ContractClient::new(&env, &contract_id);\n\n    client.do_something();\n\n    \u002F\u002F Get all events\n    let events = env.events().all();\n\n    \u002F\u002F Check specific event\n    assert_eq!(events.len(), 1);\n\n    let event = &events[0];\n    \u002F\u002F event.0 = contract_id\n    \u002F\u002F event.1 = topics (Vec\u003CVal>)\n    \u002F\u002F event.2 = data (Val)\n}\n```\n\n### Testing Storage\n\n```rust\n#[test]\nfn test_storage_ttl() {\n    let env = Env::default();\n    let contract_id = env.register(Contract, ());\n    let client = ContractClient::new(&env, &contract_id);\n\n    client.store_data();\n\n    \u002F\u002F Check TTL\n    let key = DataKey::MyData;\n    let ttl = env.as_contract(&contract_id, || {\n        env.storage().persistent().get_ttl(&key)\n    });\n\n    assert!(ttl > 0);\n}\n```\n\n### Testing Cross-Contract Calls\n\n```rust\n#[test]\nfn test_cross_contract() {\n    let env = Env::default();\n\n    \u002F\u002F Register both contracts\n    let token_id = env.register(token::WASM, ());\n    let vault_id = env.register(VaultContract, ());\n\n    let token_client = token::Client::new(&env, &token_id);\n    let vault_client = VaultContractClient::new(&env, &vault_id);\n\n    env.mock_all_auths();\n\n    let user = Address::generate(&env);\n\n    \u002F\u002F Setup: mint tokens to user\n    token_client.mint(&user, &1000);\n\n    \u002F\u002F Test: deposit tokens into vault\n    vault_client.deposit(&user, &token_id, &500);\n\n    assert_eq!(token_client.balance(&user), 500);\n    assert_eq!(vault_client.balance(&user), 500);\n}\n```\n\n## Local Testing with Stellar Quickstart\n\n### Start Local Network\n\n```bash\n# Pull and run Stellar Quickstart\ndocker run --rm -it -p 8000:8000 \\\n  --name stellar \\\n  stellar\u002Fquickstart:latest \\\n  --local \\\n  --enable-soroban-rpc\n\n# Or use Stellar CLI\nstellar container start local\n```\n\n### Configure for Local Network\n\n```typescript\nimport * as StellarSdk from \"@stellar\u002Fstellar-sdk\";\n\nconst LOCAL_RPC = \"http:\u002F\u002Flocalhost:8000\u002Fsoroban\u002Frpc\";\nconst LOCAL_HORIZON = \"http:\u002F\u002Flocalhost:8000\";\nconst LOCAL_PASSPHRASE = \"Standalone Network ; February 2017\";\n\nconst rpc = new StellarSdk.rpc.Server(LOCAL_RPC);\nconst horizon = new StellarSdk.Horizon.Server(LOCAL_HORIZON);\n```\n\n### Fund Test Accounts (Local)\n\n```bash\n# Using Stellar CLI\nstellar keys generate --global test-account --network local --fund\n\n# Or via friendbot endpoint\ncurl \"http:\u002F\u002Flocalhost:8000\u002Ffriendbot?addr=G...\"\n```\n\n### Deploy and Test Locally\n\n```bash\n# Deploy contract to local network\nstellar contract deploy \\\n  --wasm target\u002Fwasm32-unknown-unknown\u002Frelease\u002Fcontract.wasm \\\n  --source test-account \\\n  --network local\n\n# Invoke contract\nstellar contract invoke \\\n  --id CONTRACT_ID \\\n  --source test-account \\\n  --network local \\\n  -- \\\n  function_name \\\n  --arg value\n```\n\n## Testnet Testing\n\n### Network Configuration\n\n```bash\n# Testnet RPC: https:\u002F\u002Fsoroban-testnet.stellar.org\n# Testnet Horizon: https:\u002F\u002Fhorizon-testnet.stellar.org\n# Network Passphrase: \"Test SDF Network ; September 2015\"\n# Friendbot: https:\u002F\u002Ffriendbot.stellar.org\n```\n\n### Create and Fund Testnet Account\n\n```bash\n# Generate new identity\nstellar keys generate --global my-testnet-key --network testnet\n\n# Fund via Friendbot\nstellar keys fund my-testnet-key --network testnet\n\n# Or manually\ncurl \"https:\u002F\u002Ffriendbot.stellar.org?addr=G...\"\n```\n\n### Deploy to Testnet\n\n```bash\n# Deploy contract\nstellar contract deploy \\\n  --wasm target\u002Fwasm32-unknown-unknown\u002Frelease\u002Fcontract.wasm \\\n  --source my-testnet-key \\\n  --network testnet\n\n# Upload contract code (separate from deployment)\nstellar contract upload \\\n  --wasm target\u002Fwasm32-unknown-unknown\u002Frelease\u002Fcontract.wasm \\\n  --source my-testnet-key \\\n  --network testnet\n```\n\n### Testnet Reset Awareness\n\n**Important**: Testnet resets approximately quarterly:\n- All accounts and contracts are deleted\n- Plan for re-deployment after resets\n- Don't rely on persistent state for test data\n\nCheck reset schedule: https:\u002F\u002Fstellar.org\u002Fdevelopers\u002Fblog\n\n## Integration Testing Patterns\n\n### TypeScript Integration Tests\n\n```typescript\n\u002F\u002F tests\u002Fintegration\u002Fcontract.test.ts\nimport * as StellarSdk from \"@stellar\u002Fstellar-sdk\";\n\nconst RPC_URL = process.env.RPC_URL || \"http:\u002F\u002Flocalhost:8000\u002Fsoroban\u002Frpc\";\nconst NETWORK_PASSPHRASE = process.env.NETWORK_PASSPHRASE || \"Standalone Network ; February 2017\";\n\ndescribe(\"Contract Integration Tests\", () => {\n  let rpc: StellarSdk.rpc.Server;\n  let keypair: StellarSdk.Keypair;\n  let contractId: string;\n\n  beforeAll(async () => {\n    rpc = new StellarSdk.rpc.Server(RPC_URL);\n    keypair = StellarSdk.Keypair.random();\n\n    \u002F\u002F Fund account\n    await fundAccount(keypair.publicKey());\n\n    \u002F\u002F Deploy contract\n    contractId = await deployContract(keypair);\n  });\n\n  test(\"should initialize contract\", async () => {\n    const account = await rpc.getAccount(keypair.publicKey());\n    const contract = new StellarSdk.Contract(contractId);\n\n    const tx = new StellarSdk.TransactionBuilder(account, {\n      fee: \"100\",\n      networkPassphrase: NETWORK_PASSPHRASE,\n    })\n      .addOperation(\n        contract.call(\n          \"initialize\",\n          StellarSdk.Address.fromString(keypair.publicKey()).toScVal()\n        )\n      )\n      .setTimeout(30)\n      .build();\n\n    const simResult = await rpc.simulateTransaction(tx);\n    const preparedTx = StellarSdk.rpc.assembleTransaction(tx, simResult);\n\n    preparedTx.sign(keypair);\n    const result = await rpc.sendTransaction(preparedTx.build());\n\n    expect(result.status).not.toBe(\"ERROR\");\n  });\n});\n```\n\n### Rust Integration Tests\n\n```rust\n\u002F\u002F tests\u002Fintegration_test.rs\nuse soroban_sdk::{Env, Address};\nuse std::process::Command;\n\n#[test]\n#[ignore] \u002F\u002F Run with: cargo test -- --ignored\nfn integration_test_with_local_network() {\n    \u002F\u002F Requires local network running\n    let output = Command::new(\"stellar\")\n        .args([\n            \"contract\", \"invoke\",\n            \"--id\", \"CONTRACT_ID\",\n            \"--source\", \"test-account\",\n            \"--network\", \"local\",\n            \"--\",\n            \"get_count\"\n        ])\n        .output()\n        .expect(\"Failed to invoke contract\");\n\n    assert!(output.status.success());\n}\n```\n\n## Test Configuration\n\n### Cargo.toml for Tests\n\n```toml\n[dev-dependencies]\nsoroban-sdk = { version = \"25.0.1\", features = [\"testutils\"] }  # match [dependencies] version\n\n[profile.test]\nopt-level = 0\ndebug = true\n```\n\n### Running Tests\n\n```bash\n# Run unit tests\ncargo test\n\n# Run with output\ncargo test -- --nocapture\n\n# Run specific test\ncargo test test_transfer\n\n# Run ignored (integration) tests\ncargo test -- --ignored\n```\n\n## CI\u002FCD Configuration\n\n### GitHub Actions Example\n\n```yaml\nname: Test Soroban Contract\n\non: [push, pull_request]\n\njobs:\n  unit-tests:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions\u002Fcheckout@v4\n\n      - name: Install Rust\n        uses: dtolnay\u002Frust-toolchain@stable\n\n      - name: Add WASM target\n        run: rustup target add wasm32-unknown-unknown\n\n      - name: Run unit tests\n        run: cargo test\n\n      - name: Build contract\n        run: cargo build --release --target wasm32-unknown-unknown\n\n  integration-tests:\n    runs-on: ubuntu-latest\n    needs: unit-tests\n    services:\n      stellar:\n        image: stellar\u002Fquickstart:latest\n        ports:\n          - 8000:8000\n        options: >-\n          --health-cmd \"curl -f http:\u002F\u002Flocalhost:8000 || exit 1\"\n          --health-interval 10s\n          --health-timeout 5s\n          --health-retries 10\n\n    steps:\n      - uses: actions\u002Fcheckout@v4\n\n      - name: Install Stellar CLI\n        run: |\n          cargo install stellar-cli --locked\n\n      - name: Deploy and test\n        run: |\n          stellar keys generate --global ci-test --network local --fund\n          stellar contract deploy \\\n            --wasm target\u002Fwasm32-unknown-unknown\u002Frelease\u002Fcontract.wasm \\\n            --source ci-test \\\n            --network local\n```\n\n## Best Practices\n\n### Test Organization\n```\nproject\u002F\n├── src\u002F\n│   └── lib.rs\n├── tests\u002F\n│   ├── common\u002F\n│   │   └── mod.rs      # Shared test utilities\n│   ├── unit\u002F\n│   │   ├── mod.rs\n│   │   └── transfer.rs\n│   └── integration\u002F\n│       └── full_flow.rs\n└── Cargo.toml\n```\n\n### Test Utilities Module\n\n```rust\n\u002F\u002F tests\u002Fcommon\u002Fmod.rs\nuse soroban_sdk::{testutils::Address as _, Address, Env};\nuse crate::{Contract, ContractClient};\n\npub fn setup_contract(env: &Env) -> (Address, ContractClient) {\n    let contract_id = env.register(Contract, ());\n    let client = ContractClient::new(env, &contract_id);\n    let admin = Address::generate(env);\n\n    env.mock_all_auths();\n    client.initialize(&admin);\n\n    (contract_id, client)\n}\n\npub fn create_funded_user(env: &Env, client: &ContractClient, amount: i128) -> Address {\n    let user = Address::generate(env);\n    client.mint(&user, &amount);\n    user\n}\n```\n\n## Fuzz Testing\n\nSoroban has first-class fuzz testing via `cargo-fuzz` and the built-in `SorobanArbitrary` trait. All `#[contracttype]` types automatically derive `SorobanArbitrary` when the `\"testutils\"` feature is active.\n\n### Setup\n\n```bash\n# Install nightly Rust + cargo-fuzz\nrustup install nightly\ncargo install --locked cargo-fuzz\n\n# Initialize fuzz targets\ncargo fuzz init\n```\n\nUpdate `Cargo.toml` to include both crate types:\n```toml\n[lib]\ncrate-type = [\"lib\", \"cdylib\"]\n```\n\nAdd to `fuzz\u002FCargo.toml`:\n```toml\n[dependencies]\nsoroban-sdk = { version = \"25.0.1\", features = [\"testutils\"] }\n```\n\n### Writing a Fuzz Target\n\n```rust\n\u002F\u002F fuzz\u002Ffuzz_targets\u002Ffuzz_deposit.rs\n#![no_main]\n\nuse libfuzzer_sys::fuzz_target;\nuse soroban_sdk::{testutils::Address as _, Address, Env};\nuse my_contract::{Contract, ContractClient};\n\nfuzz_target!(|input: (u64, i128)| {\n    let (seed, amount) = input;\n    let env = Env::default();\n    env.mock_all_auths();\n\n    let contract_id = env.register(Contract, ());\n    let client = ContractClient::new(&env, &contract_id);\n    let user = Address::generate(&env);\n\n    \u002F\u002F Initialize\n    client.initialize(&user);\n\n    \u002F\u002F Fuzz deposit - should never panic unexpectedly\n    let _ = client.try_deposit(&user, &amount);\n});\n```\n\n### Running Fuzz Tests\n\n```bash\n# Run (use --sanitizer=thread on macOS)\ncargo +nightly fuzz run fuzz_deposit\n\n# Generate code coverage\ncargo +nightly fuzz coverage fuzz_deposit\n```\n\n### Soroban Token Fuzzer\n\nReusable library for fuzzing token contracts:\n- **GitHub**: https:\u002F\u002Fgithub.com\u002Fbrson\u002Fsoroban-token-fuzzer\n\n### Documentation\n\n- [Stellar Fuzzing Guide](https:\u002F\u002Fdevelopers.stellar.org\u002Fdocs\u002Fbuild\u002Fguides\u002Ftesting\u002Ffuzzing)\n- [Fuzzing Example Contract](https:\u002F\u002Fdevelopers.stellar.org\u002Fdocs\u002Fbuild\u002Fsmart-contracts\u002Fexample-contracts\u002Ffuzzing)\n\n## Property-Based Testing\n\nUse `proptest` with `SorobanArbitrary` for QuickCheck-style property testing that runs in standard `cargo test`.\n\n```rust\n#[cfg(test)]\nmod prop_tests {\n    use super::*;\n    use proptest::prelude::*;\n    use soroban_sdk::{testutils::Address as _, Env};\n\n    proptest! {\n        #[test]\n        fn deposit_then_withdraw_preserves_balance(amount in 1i128..=i128::MAX) {\n            let env = Env::default();\n            env.mock_all_auths();\n            let contract_id = env.register(Contract, ());\n            let client = ContractClient::new(&env, &contract_id);\n            let user = Address::generate(&env);\n\n            client.initialize(&user);\n            client.deposit(&user, &amount);\n            client.withdraw(&user, &amount);\n\n            prop_assert_eq!(client.balance(&user), 0);\n        }\n    }\n}\n```\n\n**Recommended workflow**: Use `cargo-fuzz` interactively to find deep bugs, then convert to `proptest` for regression prevention in CI.\n\n## Differential Testing with Test Snapshots\n\nSoroban automatically writes JSON snapshots at the end of every test to `test_snapshots\u002F`, capturing events and final ledger state. Commit these to source control - diffs reveal unintended behavioral changes.\n\n### Comparing Against Deployed Contracts\n\n```rust\n\u002F\u002F Fetch deployed contract for comparison\n\u002F\u002F $ stellar contract fetch --id C... --out-file deployed.wasm\n\nmod deployed {\n    soroban_sdk::contractimport!(file = \"deployed.wasm\");\n}\n\n#[test]\nfn test_upgrade_compatibility() {\n    let env = Env::default();\n    env.mock_all_auths();\n\n    \u002F\u002F Register both versions\n    let old_id = env.register(deployed::WASM, ());\n    let new_id = env.register(NewContract, ());\n\n    let old_client = deployed::Client::new(&env, &old_id);\n    let new_client = NewContractClient::new(&env, &new_id);\n\n    let user = Address::generate(&env);\n\n    \u002F\u002F Run identical operations and compare\n    old_client.initialize(&user);\n    new_client.initialize(&user);\n\n    assert_eq!(old_client.get_value(), new_client.get_value());\n}\n```\n\n- **Docs**: [Differential Tests with Test Snapshots](https:\u002F\u002Fdevelopers.stellar.org\u002Fdocs\u002Fbuild\u002Fguides\u002Ftesting\u002Fdifferential-tests-with-test-snapshots)\n\n## Fork Testing\n\nTest against real production state using ledger snapshots:\n\n```bash\n# Create snapshot of deployed contract\nstellar snapshot create --address C... --output json --out snapshot.json\n\n# Optionally at a specific ledger\nstellar snapshot create --address C... --ledger 12345678 --output json --out snapshot.json\n```\n\n```rust\n#[test]\nfn test_against_mainnet_state() {\n    let env = Env::from_ledger_snapshot_file(\"snapshot.json\");\n    env.mock_all_auths();\n\n    let contract_id = \u002F* contract address from snapshot *\u002F;\n    let client = ContractClient::new(&env, &contract_id);\n\n    \u002F\u002F Test operations against real state\n    let result = client.get_value();\n    assert!(result > 0);\n}\n```\n\n- **Docs**: [Fork Testing](https:\u002F\u002Fdevelopers.stellar.org\u002Fdocs\u002Fbuild\u002Fguides\u002Ftesting\u002Ffork-testing)\n\n## Mutation Testing\n\nUse `cargo-mutants` to verify test quality - modifies source code and checks that tests catch the changes.\n\n```bash\ncargo install --locked cargo-mutants\ncargo mutants\n```\n\n**Output interpretation**:\n- **CAUGHT**: Tests detected the mutation (good coverage)\n- **MISSED**: Tests passed despite mutation (test gap - review `mutants.out\u002Fdiff\u002F`)\n\n- **Docs**: [Mutation Testing](https:\u002F\u002Fdevelopers.stellar.org\u002Fdocs\u002Fbuild\u002Fguides\u002Ftesting\u002Fmutation-testing)\n\n## Resource Profiling\n\nSoroban uses a multidimensional resource model (CPU instructions, ledger reads\u002Fwrites, bytes, events, rent).\n\n### CLI Simulation\n\n```bash\n# Simulate contract invocation to see resource costs\nstellar contract invoke \\\n  --id CONTRACT_ID \\\n  --source alice \\\n  --network testnet \\\n  --sim-only \\\n  -- \\\n  function_name --arg value\n```\n\n### Stellar Plus Profiler (Cheesecake Labs)\n\n```typescript\nimport { StellarPlus } from 'stellar-plus';\n\nconst profilerPlugin = new StellarPlus.Utils.Plugins.sorobanTransaction.profiler();\n\u002F\u002F Collects CPU instructions, RAM, ledger reads\u002Fwrites\n\u002F\u002F Aggregation: sum, average, standard deviation\n\u002F\u002F Output: CSV, formatted text tables\n```\n\n- **Docs**: https:\u002F\u002Fdocs.cheesecakelabs.com\u002Fstellar-plus\u002Freference\u002Futils\u002Fplugins\u002Fprofiler-plugin\n\n### Testing Checklist\n\n- [ ] Unit tests cover all public functions\n- [ ] Edge cases tested (zero amounts, max values, empty state)\n- [ ] Authorization tested (correct signers required)\n- [ ] Error conditions tested (invalid inputs, unauthorized)\n- [ ] Events emission verified\n- [ ] Storage TTL behavior validated\n- [ ] Cross-contract interactions tested\n- [ ] Fuzz tests for critical paths (deposits, withdrawals, swaps)\n- [ ] Property-based tests for invariants\n- [ ] Mutation testing confirms test quality\n- [ ] Differential test snapshots committed to source control\n- [ ] Integration tests against local network\n- [ ] Testnet deployment verified before mainnet\n\n---\n\n# Part 3: Security\n\n\n## Core Principle\n\nAssume the attacker controls:\n- All arguments passed to contract functions\n- Transaction ordering and timing\n- All accounts except those requiring signatures\n- The ability to create contracts that mimic your interface\n\n## Soroban Security Advantages\n\nSoroban's architecture prevents certain vulnerability classes by design:\n\n### No Delegate Call\nUnlike Ethereum, Soroban has no `delegatecall` equivalent. Contracts cannot execute arbitrary bytecode in their context, eliminating proxy-based attacks.\n\n### No Classical Reentrancy\nSoroban's synchronous execution model prevents the cross-contract reentrancy that plagues Ethereum. Self-reentrancy is possible but rarely exploitable.\n\n### Explicit Authorization\nAuthorization is opt-in via `require_auth()`, making it explicit which operations need signatures.\n\n---\n\n## Vulnerability Categories\n\n### 1. Missing Authorization Checks\n\n**Risk**: Anyone can call privileged functions without proper verification.\n\n**Attack**: Attacker calls admin-only functions, drains funds, or modifies critical state.\n\n**Vulnerable Code**:\n```rust\n\u002F\u002F BAD: No authorization check\npub fn withdraw(env: Env, to: Address, amount: i128) {\n    transfer_tokens(&env, &to, amount);\n}\n```\n\n**Secure Code**:\n```rust\n\u002F\u002F GOOD: Requires authorization from admin\npub fn withdraw(env: Env, to: Address, amount: i128) {\n    let admin: Address = env.storage().instance().get(&DataKey::Admin).unwrap();\n    admin.require_auth();\n    transfer_tokens(&env, &to, amount);\n}\n```\n\n**Prevention**: Always use `require_auth()` on the caller or an admin address. See Part 1: Contract Development above for full authorization patterns (direct auth, admin helpers, `require_auth_for_args`).\n\n---\n\n### 2. Reinitialization Attacks\n\n**Risk**: Initialization function can be called multiple times, allowing attacker to overwrite admin or critical state.\n\n**Attack**: Attacker reinitializes contract to become the admin, then drains assets.\n\n**Vulnerable Code**:\n```rust\n\u002F\u002F BAD: Can be called multiple times\npub fn initialize(env: Env, admin: Address) {\n    env.storage().instance().set(&DataKey::Admin, &admin);\n}\n```\n\n**Secure Code**:\n```rust\n\u002F\u002F GOOD: Prevents reinitialization\npub fn initialize(env: Env, admin: Address) {\n    if env.storage().instance().has(&DataKey::Initialized) {\n        panic!(\"already initialized\");\n    }\n    env.storage().instance().set(&DataKey::Admin, &admin);\n    env.storage().instance().set(&DataKey::Initialized, &true);\n}\n\n\u002F\u002F Alternative: Check for admin existence\npub fn initialize(env: Env, admin: Address) {\n    if env.storage().instance().has(&DataKey::Admin) {\n        panic!(\"already initialized\");\n    }\n    env.storage().instance().set(&DataKey::Admin, &admin);\n}\n```\n\n---\n\n### 3. Arbitrary Contract Calls\n\n**Risk**: Contract calls whatever address is passed as parameter without validation.\n\n**Attack**: Attacker passes malicious contract that mimics expected interface but behaves differently.\n\n**Vulnerable Code**:\n```rust\n\u002F\u002F BAD: Calls any contract passed as parameter\npub fn swap(env: Env, token: Address, amount: i128) {\n    let client = token::Client::new(&env, &token);\n    client.transfer(...); \u002F\u002F Could be malicious contract\n}\n```\n\n**Secure Code**:\n```rust\n\u002F\u002F GOOD: Validate against known allowlist\npub fn swap(env: Env, token: Address, amount: i128) {\n    let allowed_tokens: Vec\u003CAddress> = env.storage()\n        .instance()\n        .get(&DataKey::AllowedTokens)\n        .unwrap();\n\n    if !allowed_tokens.contains(&token) {\n        panic!(\"token not allowed\");\n    }\n\n    let client = token::Client::new(&env, &token);\n    client.transfer(...);\n}\n\n\u002F\u002F Or validate against Stellar Asset Contract\npub fn swap_sac(env: Env, asset: Address, amount: i128) {\n    \u002F\u002F SACs have known, predictable addresses\n    \u002F\u002F Verify it's a legitimate SAC if needed\n}\n```\n\n---\n\n### 4. Integer Overflow\u002FUnderflow\n\n**Risk**: Arithmetic operations overflow or underflow, causing unexpected values.\n\n**Attack**: Attacker manipulates amounts to cause overflow, bypassing balance checks.\n\n**Vulnerable Code**:\n```rust\n\u002F\u002F BAD: Unchecked arithmetic\npub fn deposit(env: Env, user: Address, amount: i128) {\n    let balance: i128 = get_balance(&env, &user);\n    set_balance(&env, &user, balance + amount); \u002F\u002F Can overflow\n}\n```\n\n**Secure Code**:\n```rust\n\u002F\u002F GOOD: Use checked arithmetic\npub fn deposit(env: Env, user: Address, amount: i128) {\n    let balance: i128 = get_balance(&env, &user);\n    let new_balance = balance.checked_add(amount)\n        .expect(\"overflow\");\n    set_balance(&env, &user, new_balance);\n}\n\n\u002F\u002F Also validate inputs\npub fn deposit(env: Env, user: Address, amount: i128) {\n    if amount \u003C= 0 {\n        panic!(\"invalid amount\");\n    }\n    \u002F\u002F ... rest of logic\n}\n```\n\n---\n\n### 5. Storage Key Collisions\n\n**Risk**: Different data types share the same storage key, causing data corruption.\n\n**Attack**: Attacker manipulates one type of data to corrupt another.\n\n**Vulnerable Code**:\n```rust\n\u002F\u002F BAD: Same prefix for different data\nenv.storage().persistent().set(&symbol_short!(\"data\"), &user_balance);\nenv.storage().persistent().set(&symbol_short!(\"data\"), &config); \u002F\u002F Overwrites!\n```\n\n**Secure Code**:\n```rust\n\u002F\u002F GOOD: Use typed enum for keys\n#[contracttype]\n#[derive(Clone)]\npub enum DataKey {\n    Admin,\n    Balance(Address),\n    Config,\n    Allowance(Address, Address),\n}\n\nenv.storage().persistent().set(&DataKey::Balance(user), &balance);\nenv.storage().instance().set(&DataKey::Config, &config);\n```\n\n---\n\n### 6. Timing\u002FState Race Conditions\n\n**Risk**: Contract state changes between check and use.\n\n**Attack**: In multi-transaction scenarios, attacker exploits gap between validation and action.\n\n**Prevention**:\n```rust\n\u002F\u002F Use atomic operations where possible\npub fn swap(env: Env, user: Address, amount_in: i128, min_out: i128) {\n    user.require_auth();\n\n    \u002F\u002F Perform all checks and state changes atomically\n    let balance = get_balance(&env, &user);\n    if balance \u003C amount_in {\n        panic!(\"insufficient balance\");\n    }\n\n    let amount_out = calculate_output(amount_in);\n    if amount_out \u003C min_out {\n        panic!(\"slippage exceeded\");\n    }\n\n    \u002F\u002F Update all state together\n    set_balance(&env, &user, balance - amount_in);\n    transfer_output(&env, &user, amount_out);\n}\n```\n\n---\n\n### 7. TTL\u002FArchival Vulnerabilities\n\n**Risk**: Critical contract data gets archived, breaking functionality.\n\n**Attack**: Attacker waits for data to be archived, then exploits the missing state.\n\n**Prevention**:\n```rust\n\u002F\u002F Extend TTL for critical data\npub fn critical_operation(env: Env) {\n    \u002F\u002F Always extend instance storage\n    env.storage().instance().extend_ttl(\n        100,      \u002F\u002F threshold\n        518400,   \u002F\u002F extend_to (~30 days)\n    );\n\n    \u002F\u002F Extend specific persistent keys\n    env.storage().persistent().extend_ttl(\n        &DataKey::CriticalData,\n        100,\n        518400,\n    );\n}\n\n\u002F\u002F Consider restoration costs in design\n\u002F\u002F Archived data can be restored, but requires transaction\n```\n\n---\n\n### 8. Cross-Contract Call Validation\n\n**Risk**: Trusting return values from untrusted contracts.\n\n**Attack**: Malicious contract returns false data, causing incorrect state updates.\n\n**Prevention**:\n```rust\n\u002F\u002F Validate all external data\npub fn process_oracle_price(env: Env, oracle: Address, asset: Address) -> i128 {\n    \u002F\u002F Validate oracle is trusted\n    let trusted_oracles: Vec\u003CAddress> = env.storage()\n        .instance()\n        .get(&DataKey::TrustedOracles)\n        .unwrap();\n\n    if !trusted_oracles.contains(&oracle) {\n        panic!(\"untrusted oracle\");\n    }\n\n    let price: i128 = oracle_client.get_price(&asset);\n\n    \u002F\u002F Sanity check the value\n    if price \u003C= 0 || price > MAX_REASONABLE_PRICE {\n        panic!(\"invalid price\");\n    }\n\n    price\n}\n```\n\n---\n\n## Classic Stellar Security\n\n### Trustline Attacks\n\n**Risk**: Users create trustlines to malicious assets that look legitimate.\n\n**Prevention**:\n- Verify asset issuer before creating trustlines\n- Use well-known asset lists (stellar.toml)\n- Display full asset code + issuer in UIs\n\n### Clawback Awareness\n\n**Risk**: Assets with clawback enabled can be seized by issuer.\n\n**Prevention**:\n```typescript\n\u002F\u002F Check if clawback is enabled\nconst issuerAccount = await server.loadAccount(asset.issuer);\nconst clawbackEnabled = issuerAccount.flags.auth_clawback_enabled;\n\nif (clawbackEnabled) {\n  \u002F\u002F Warn user or reject asset\n}\n```\n\n### Account Merge Attacks\n\n**Risk**: Merged accounts can be recreated with different configuration.\n\n**Prevention**:\n- Validate account state before critical operations\n- Don't cache account data long-term\n\n---\n\n## Soroban-Specific Checklist\n\n### Contract Development\n- [ ] All privileged functions require appropriate authorization\n- [ ] Initialization can only happen once\n- [ ] External contract calls are validated against allowlists\n- [ ] All arithmetic uses checked operations\n- [ ] Storage keys are typed and collision-free\n- [ ] Critical data TTLs are extended proactively\n- [ ] Input validation on all public functions\n- [ ] Events emitted for auditable state changes\n\n### Storage Security\n- [ ] Sensitive data uses appropriate storage type\n- [ ] Instance storage for shared\u002Fadmin data\n- [ ] Persistent storage for user-specific data\n- [ ] Temporary storage only for truly temporary data\n- [ ] TTL management strategy documented\n\n### Cross-Contract Calls\n- [ ] Called contracts are validated or allowlisted\n- [ ] Return values are sanity-checked\n- [ ] Failure cases handled gracefully\n- [ ] No excessive trust in external state\n\n---\n\n## Client-Side Checklist\n\n- [ ] Network passphrase validated before signing\n- [ ] Transaction simulation before submission\n- [ ] Clear display of all operation details\n- [ ] Confirmation for high-value transactions\n- [ ] Handle all error states gracefully\n- [ ] Don't trust client-side validation alone\n- [ ] Verify contract addresses against known deployments\n- [ ] Check asset trustline status before transfers\n\n---\n\n## Security Review Questions\n\n1. Can anyone call admin functions without authorization?\n2. Can the contract be reinitialized?\n3. Are all external contract calls validated?\n4. Is arithmetic safe from overflow\u002Funderflow?\n5. Can storage keys collide?\n6. Will critical data survive archival?\n7. Are cross-contract return values validated?\n8. Can timing attacks exploit state changes?\n\n---\n\n## Bug Bounty Programs\n\n### Immunefi - Stellar Core (up to $250K)\n- **URL**: https:\u002F\u002Fimmunefi.com\u002Fbug-bounty\u002Fstellar\u002F\n- **Scope**: stellar-core, rs-soroban-sdk, rs-soroban-env, soroban-tools (CLI + RPC), js-soroban-client, rs-stellar-xdr, wasmi fork\n- **Rewards**: Critical $50K–$250K, High $10K–$50K, Medium $5K, Low $1K\n- **Payment**: USD-denominated, paid in XLM. KYC required.\n- **Rules**: PoC required. Test on local forks only (no mainnet\u002Ftestnet).\n\n### Immunefi - OpenZeppelin on Stellar (up to $25K)\n- **URL**: https:\u002F\u002Fimmunefi.com\u002Fbug-bounty\u002Fopenzeppelin-stellar\u002F\n- **Scope**: OpenZeppelin Stellar Contracts library\n- **Max payout**: $25K per bug, $250K total program cap\n\n### HackerOne - Web Applications\n- **URL**: https:\u002F\u002Fstellar.org\u002Fgrants-and-funding\u002Fbug-bounty\n- **Scope**: SDF web applications, production servers, domains\n- **Disclosure**: 90-day remediation window before public disclosure\n\n## Soroban Audit Bank\n\nSDF's proactive security program with **$3M+ deployed across 43+ audits**.\n\n- **URL**: https:\u002F\u002Fstellar.org\u002Fgrants-and-funding\u002Fsoroban-audit-bank\n- **Projects list**: https:\u002F\u002Fstellar.org\u002Faudit-bank\u002Fprojects\n- **Eligibility**: SCF-funded projects (financial protocols, infrastructure, high-traction dApps)\n- **Co-payment**: 5% upfront (refundable if Critical\u002FHigh\u002FMedium issues remediated within 20 business days)\n- **Follow-up audits**: Triggered at $10M and $100M TVL milestones (includes formal verification and competitive audits)\n- **Preparation**: STRIDE threat modeling framework + Audit Readiness Checklist\n\n### Partner Audit Firms\n\n| Firm | Specialty |\n|------|-----------|\n| **OtterSec** | Smart contract audits |\n| **Veridise** | Tool-assisted audits, [security checklist](https:\u002F\u002Fveridise.com\u002Fblog\u002Faudit-insights\u002Fbuilding-on-stellar-soroban-grab-this-security-checklist-to-avoid-vulnerabilities\u002F) |\n| **Runtime Verification** | Formal methods, [Komet tool](https:\u002F\u002Fruntimeverification.com\u002Fblog\u002Fintroducing-komet-smart-contract-testing-and-verification-tool-for-soroban-created-by-runtime-verification) |\n| **CoinFabrik** | Static analysis (Scout), manual audits |\n| **QuarksLab** | Security research |\n| **Coinspect** | Security audits |\n| **Certora** | Formal verification ([Sunbeam Prover](https:\u002F\u002Fdocs.certora.com\u002Fen\u002Flatest\u002Fdocs\u002Fsunbeam\u002Findex.html)) |\n| **Halborn** | Security assessments |\n| **Zellic** | Blockchain + cryptography research |\n| **Code4rena** | Competitive audit platform |\n\n## Security Tooling\n\n### Static Analysis\n\n#### Scout Soroban (CoinFabrik)\nOpen-source vulnerability detector with 23 detectors (critical through enhancement severity).\n- **GitHub**: https:\u002F\u002Fgithub.com\u002FCoinFabrik\u002Fscout-soroban\n- **Install**: `cargo install cargo-scout-audit` → `cargo scout-audit`\n- **Output formats**: HTML, Markdown, JSON, PDF, SARIF (CI\u002FCD integration)\n- **VSCode extension**: [Scout Audit](https:\u002F\u002Fmarketplace.visualstudio.com\u002Fitems?itemName=CoinFabrik.scout-audit)\n- **Key detectors**: `overflow-check`, `unprotected-update-current-contract-wasm`, `set-contract-storage`, `unrestricted-transfer-from`, `divide-before-multiply`, `dos-unbounded-operation`, `unsafe-unwrap`\n\n#### OpenZeppelin Security Detectors SDK\nFramework for building custom security detectors for Soroban.\n- **GitHub**: https:\u002F\u002Fgithub.com\u002FOpenZeppelin\u002Fsoroban-security-detectors-sdk\n- **Architecture**: `sdk` (core), `detectors` (pre-built), `soroban-scanner` (CLI)\n- **Pre-built detectors**: `auth_missing`, `unchecked_ft_transfer`, improper TTL extension, contract panics, unsafe temporary storage\n- **Extensible**: Load external detector libraries as shared objects\n\n### Formal Verification\n\n#### Certora Sunbeam Prover\nPurpose-built formal verification for Soroban - first WASM platform supported by Certora.\n- **Docs**: https:\u002F\u002Fdocs.certora.com\u002Fen\u002Flatest\u002Fdocs\u002Fsunbeam\u002Findex.html\n- **Spec language**: CVLR (Certora Verification Language for Rust) - Rust macros (`cvlr_assert!`, `cvlr_assume!`, `cvlr_satisfy!`)\n- **Operates at**: WASM bytecode level (eliminates compiler trust assumptions)\n- **Reports**: https:\u002F\u002Fgithub.com\u002FCertora\u002FSecurityReports\n- **Example**: [Blend V1 verification report](https:\u002F\u002Fwww.certora.com\u002Freports\u002Fblend-smart-contract-verification-report)\n\n#### Runtime Verification - Komet\nFormal verification and testing tool built specifically for Soroban (SCF-funded).\n- **Docs**: https:\u002F\u002Fdocs.runtimeverification.com\u002Fkomet\n- **Repo**: https:\u002F\u002Fgithub.com\u002Fruntimeverification\u002Fkomet\n- **Spec language**: Rust - property-based tests written in the same language as Soroban contracts\n- **Operates at**: WASM bytecode level via [KWasm semantics](https:\u002F\u002Fgithub.com\u002Fruntimeverification\u002Fwasm-semantics) (eliminates compiler trust assumptions)\n- **Features**: Fuzzing, testing, formal verification\n- **Reports**: [RV publications](https:\u002F\u002Fgithub.com\u002Fruntimeverification\u002Fpublications)\n- **Example**: [TokenOps audit and verification report](https:\u002F\u002Fgithub.com\u002Fruntimeverification\u002Fpublications\u002Fblob\u002Fmain\u002Freports\u002Fsmart-contracts\u002FTokenOps.pdf)\n- **Blog**: [Introducing Komet](https:\u002F\u002Fruntimeverification.com\u002Fblog\u002Fintroducing-komet-smart-contract-testing-and-verification-tool-for-soroban-created-by-runtime-verification)\n\n### Security Knowledge Base\n\n#### Soroban Security Portal\nCommunity security knowledge base by Inferara (SCF-funded).\n- **URL**: https:\u002F\u002Fsorobansecurity.com\n- **Features**: Searchable audit reports, vulnerability database, best practices\n\n### Security Monitoring (Post-Deployment)\n\n#### OpenZeppelin Monitor (Stellar alpha)\nOpen-source contract monitoring with Stellar support.\n- **Features**: Self-hosted via Docker, Prometheus + Grafana observability\n- **Source**: https:\u002F\u002Fwww.openzeppelin.com\u002Fnews\u002Fmonitor-and-relayers-are-now-open-source\n\n## OpenZeppelin Partnership Overview\n\nStrategic partnership highlights include:\n- **40 Auditor Weeks** of dedicated security audits\n- **Stellar Contracts library** (audited, production-ready)\n- **Relayer** (fee-sponsored transactions, Stellar-native)\n- **Monitor** (contract monitoring, Stellar alpha)\n- **Security Detectors SDK** (static analysis framework)\n- **SEP authorship**: SEP-0049 (Upgradeable Contracts), SEP-0050 (NFTs)\n- **Blog**: https:\u002F\u002Fstellar.org\u002Fblog\u002Ffoundation-news\u002Fsdf-partners-with-openzeppelin-to-enhance-stellar-smart-contract-development\n\n---\n\n# Part 4: Advanced Patterns\n\n\n## When to use this guide\nUse this guide for higher-complexity contract architecture:\n- Upgrades and migrations\n- Factory\u002Fdeployer systems\n- Governance and timelocks\n- DeFi primitives (vaults, pools, oracles)\n- Regulated token\u002Fcompliance workflows\n- Resource and storage optimization\n\nFor core contract syntax and day-to-day patterns, refer to the earlier sections in this guide covering contract structure, storage, authorization, cross-contract calls, events, error handling, and testing.\n\n## Design principles\n- Prefer simple state machines over implicit behavior.\n- Minimize privileged entrypoints and protect all privileged actions with explicit auth.\n- Keep upgrades predictable: version metadata + migration plan + rollback strategy.\n- Use idempotent migrations and fail fast on incompatible versions.\n- Separate protocol\u002Fbusiness logic from governance\u002Fadmin logic when possible.\n\n## Upgradeability patterns\n\n### 1) Explicit upgrade policy\n- Decide early whether the contract is mutable or immutable.\n- If mutable, implement an `upgrade` entrypoint guarded by admin or governance.\n- If immutable, do not expose upgrade capability.\n\n### 2) Version tracking\nTrack both runtime and code version:\n- Contract metadata (`contractmeta!`) for binary version\n- Storage key for migration\u002Fapplication version\n\n```rust\n#![no_std]\nuse soroban_sdk::{contract, contractimpl, contractmeta, contracttype, Address, BytesN, Env};\n\ncontractmeta!(key = \"binver\", val = \"1.0.0\");\n\n#[contracttype]\n#[derive(Clone)]\npub enum DataKey {\n    Admin,\n    AppVersion,\n}\n\n#[contract]\npub struct Upgradeable;\n\n#[contractimpl]\nimpl Upgradeable {\n    pub fn __constructor(env: Env, admin: Address) {\n        env.storage().instance().set(&DataKey::Admin, &admin);\n        env.storage().instance().set(&DataKey::AppVersion, &1u32);\n    }\n\n    pub fn upgrade(env: Env, new_wasm_hash: BytesN\u003C32>) {\n        let admin: Address = env.storage().instance().get(&DataKey::Admin).unwrap();\n        admin.require_auth();\n        env.deployer().update_current_contract_wasm(new_wasm_hash);\n    }\n}\n```\n\n### 3) Migration entrypoint\n- Add a dedicated `migrate` function after upgrades.\n- Ensure migration is monotonic (`new_version > current_version`).\n- Treat migrations as one-way and idempotent.\n\n## Factory and deployment patterns\n\n### Factory contract responsibilities\n- Authorize who can deploy instances.\n- Derive deterministic addresses with salts when needed.\n- Emit events for deployments (indexing\u002Fops observability).\n- Keep deployment logic separate from instance business logic.\n\n```rust\n#![no_std]\nuse soroban_sdk::{contract, contractimpl, Address, BytesN, Env, Val, Vec};\n\n#[contract]\npub struct Factory;\n\n#[contractimpl]\nimpl Factory {\n    pub fn deploy(\n        env: Env,\n        owner: Address,\n        wasm_hash: BytesN\u003C32>,\n        salt: BytesN\u003C32>,\n        constructor_args: Vec\u003CVal>,\n    ) -> Address {\n        owner.require_auth();\n        env.deployer()\n            .with_address(env.current_contract_address(), salt)\n            .deploy_v2(wasm_hash, constructor_args)\n    }\n}\n```\n\nOperational note:\n- Keep a registry (or emit canonical deployment events) to avoid orphaned instances.\n\n## Governance patterns\n\n### Timelock for sensitive actions\nUse a timelock for upgrades and major config changes:\n- `propose_*` stores pending action + execute ledger\n- `execute_*` enforces delay\n- `cancel_*` allows governance abort\n\n### Multisig and role separation\n- Separate roles: proposer, approver, executor.\n- Define threshold and signer rotation process.\n- Record proposal state in persistent storage and prevent replay.\n\nChecklist:\n- Proposal uniqueness and replay protection\n- Expiry semantics\n- Clear cancellation path\n- Explicit event emission\n\n## DeFi primitives\n\n### Vaults\n- Track `total_assets` and `total_shares` with careful rounding rules.\n- Use conservative math for mint\u002Fredeem conversions.\n- Enforce pause\u002Femergency controls for admin-level intervention.\n\n### Pools\u002FAMMs\n- Define invariant and fee accounting precisely.\n- Protect against stale pricing and manipulation.\n- Include slippage checks on all user-facing swaps.\n\n### Oracle integration\n- Require freshness constraints (ledger\u002Ftime bounds).\n- Prefer median\u002Fmulti-source feeds for critical operations.\n- Add circuit breakers for extreme price movement.\n\n## Compliance-oriented token design\n\nCommon regulated features:\n- Allowlist\u002Fdenylist checks before transfer\n- Jurisdiction or investor-class restrictions\n- Forced transfer\u002Ffreeze authority with auditable governance\n- Off-chain identity references (never store sensitive PII directly)\n\nImplementation guidance:\n- Keep compliance policy in dedicated modules\u002Fentrypoints.\n- Emit policy decision events for traceability.\n- Treat privileged compliance actions as high-risk operations requiring strong auth.\n\n## Resource optimization\n\n### Storage\n- Use `instance` for global config.\n- Use `persistent` for critical user state.\n- Use `temporary` only for disposable data.\n- Extend TTL strategically, not on every call.\n\n### Compute\n- Avoid unbounded loops over user-controlled collections.\n- Prefer bounded batch operations.\n- Reduce cross-contract calls in hot paths.\n\n### Contract size\n- Keep release profile optimized (`opt-level = \"z\"`, `lto = true`, `panic = \"abort\"`).\n- Split concerns across contracts when near Wasm size limits.\n\n## Security review checklist for advanced architectures\n- Access control is explicit on every privileged path.\n- Upgrade and migration are both tested (happy path + failure path).\n- Timelock and governance logic is replay-safe.\n- External dependency assumptions are documented.\n- Emergency controls and incident runbooks are defined.\n- Events cover operationally important transitions.\n\n## Testing strategy for advanced patterns\n- Unit tests for role checks, invariants, and edge-case math.\n- Integration tests for multi-step governance flows.\n- Upgrade tests from old state snapshots to new versions.\n- Negative tests for unauthorized and malformed calls.\n\n---\n\n# Part 5: Common Pitfalls\n\n\n## Soroban Contract Issues\n\n### 1. Contract Size Exceeds 64KB Limit\n\n**Problem**: Contract won't deploy because WASM exceeds size limit.\n\n**Symptoms**:\n```\nError: contract exceeds maximum size\n```\n\n**Solutions**:\n\n```toml\n# Cargo.toml - Use aggressive optimization\n[profile.release]\nopt-level = \"z\"           # Optimize for size\nlto = true                # Link-time optimization\ncodegen-units = 1         # Single codegen unit\npanic = \"abort\"           # Smaller panic handling\nstrip = \"symbols\"         # Remove symbols\n```\n\nAdditional strategies:\n- Split large contracts into multiple smaller contracts\n- Use `symbol_short!()` for symbols under 9 chars\n- Avoid large static data in contract\n- Remove debug code and unused functions\n- Use `cargo bloat` to identify large dependencies\n\n```bash\n# Check contract size\nls -la target\u002Fwasm32-unknown-unknown\u002Frelease\u002F*.wasm\n\n# Analyze what's taking space\ncargo install cargo-bloat\ncargo bloat --release --target wasm32-unknown-unknown\n```\n\n---\n\n### 2. `#![no_std]` Missing\n\n**Problem**: Compilation fails with std library errors.\n\n**Symptoms**:\n```\nerror: cannot find macro `println` in this scope\nerror[E0433]: failed to resolve: use of undeclared crate or module `std`\n```\n\n**Solution**:\n```rust\n\u002F\u002F MUST be first line of lib.rs\n#![no_std]\n\nuse soroban_sdk::{contract, contractimpl, Env};\n\n\u002F\u002F Use soroban_sdk equivalents instead of std:\n\u002F\u002F - soroban_sdk::String instead of std::string::String\n\u002F\u002F - soroban_sdk::Vec instead of std::vec::Vec\n\u002F\u002F - soroban_sdk::Map instead of std::collections::HashMap\n```\n\n---\n\n### 3. Storage TTL Not Extended\n\n**Problem**: Contract data gets archived and becomes inaccessible.\n\n**Symptoms**:\n- Contract calls fail after period of inactivity\n- Data appears missing but contract still exists\n\n**Solution**:\n```rust\n\u002F\u002F Proactively extend TTL in operations that use data\npub fn use_data(env: Env) {\n    \u002F\u002F Extend instance storage\n    env.storage().instance().extend_ttl(\n        50,      \u002F\u002F If TTL \u003C 50, extend\n        518400,  \u002F\u002F Extend to ~30 days\n    );\n\n    \u002F\u002F Extend specific persistent keys\n    env.storage().persistent().extend_ttl(\n        &DataKey::ImportantData,\n        50,\n        518400,\n    );\n\n    \u002F\u002F Now use the data...\n}\n```\n\n> See Part 1: Contract Development above for full TTL management patterns and storage type guidance.\n\n---\n\n### 4. Wrong Storage Type\n\n**Problem**: Data unexpectedly deleted or costs too high.\n\n**Symptoms**:\n- Temporary data deleted before expected\n- Unexpectedly high fees for storage\n\n**Solution**:\n```rust\n\u002F\u002F Instance: Shared config, survives with contract\nenv.storage().instance().set(&DataKey::Admin, &admin);\n\n\u002F\u002F Persistent: User data, can be archived but restored\nenv.storage().persistent().set(&DataKey::Balance(user), &balance);\n\n\u002F\u002F Temporary: Truly temporary, auto-deleted, cheapest\nenv.storage().temporary().set(&DataKey::Cache(key), &value);\n```\n\n---\n\n### 5. Authorization Not Working\n\n**Problem**: `require_auth()` not enforcing signatures in tests.\n\n**Symptoms**:\n- Tests pass but transactions fail on network\n- Anyone can call protected functions\n\n**Solution**:\n```rust\n#[test]\nfn test_auth() {\n    let env = Env::default();\n\n    \u002F\u002F DON'T just mock all auths blindly\n    \u002F\u002F env.mock_all_auths();  \u002F\u002F Be careful with this!\n\n    \u002F\u002F DO test specific auth requirements with mock_auths()\n    env.mock_auths(&[MockAuth {\n        address: &user,\n        invoke: &MockAuthInvoke {\n            contract: &contract_id,\n            fn_name: \"transfer\",\n            args: (&user, &other, &100i128).into_val(&env),\n            sub_invokes: &[],\n        },\n    }]);\n\n    client.transfer(&user, &other, &100);\n    assert!(!env.auths().is_empty());\n}\n```\n\n> See Part 2: Testing Strategy above for comprehensive auth testing patterns including `mock_all_auths()`, specific auth mocking, and cross-contract auth.\n\n---\n\n## SDK Issues\n\n### 6. Network Passphrase Mismatch\n\n**Problem**: Transactions fail with signature errors.\n\n**Symptoms**:\n```\nError: tx_bad_auth\n```\n\n**Solution**:\n```typescript\nimport * as StellarSdk from \"@stellar\u002Fstellar-sdk\";\n\n\u002F\u002F ALWAYS use correct passphrase for network\nconst PASSPHRASES = {\n  mainnet: StellarSdk.Networks.PUBLIC,\n  \u002F\u002F \"Public Global Stellar Network ; September 2015\"\n\n  testnet: StellarSdk.Networks.TESTNET,\n  \u002F\u002F \"Test SDF Network ; September 2015\"\n\n  local: \"Standalone Network ; February 2017\",\n};\n\n\u002F\u002F When building transactions\nconst tx = new StellarSdk.TransactionBuilder(account, {\n  fee: StellarSdk.BASE_FEE,\n  networkPassphrase: PASSPHRASES.testnet, \u002F\u002F Match your network!\n});\n```\n\n---\n\n### 7. Account Not Funded\n\n**Problem**: Operations fail because account doesn't exist.\n\n**Symptoms**:\n```\nError: Account not found\nStatus: 404\n```\n\n**Solution**:\n```typescript\n\u002F\u002F Testnet - use Friendbot\nawait fetch(`https:\u002F\u002Ffriendbot.stellar.org?addr=${publicKey}`);\n\n\u002F\u002F Mainnet - must receive XLM from existing account\nconst tx = new StellarSdk.TransactionBuilder(funderAccount, {\n  fee: StellarSdk.BASE_FEE,\n  networkPassphrase: StellarSdk.Networks.PUBLIC,\n})\n  .addOperation(\n    StellarSdk.Operation.createAccount({\n      destination: newAccountPublicKey,\n      startingBalance: \"2\", \u002F\u002F Minimum ~1 XLM for base reserve\n    })\n  )\n  .setTimeout(180)\n  .build();\n```\n\n---\n\n### 8. Missing Trustline\n\n**Problem**: Payment fails for non-native assets.\n\n**Symptoms**:\n```\nError: op_no_trust\n```\n\n**Solution**:\n```typescript\n\u002F\u002F Check if trustline exists\nconst account = await server.loadAccount(destination);\nconst hasTrustline = account.balances.some(\n  (b) =>\n    b.asset_type !== \"native\" &&\n    b.asset_code === asset.code &&\n    b.asset_issuer === asset.issuer\n);\n\nif (!hasTrustline) {\n  \u002F\u002F Create trustline first\n  const trustTx = new StellarSdk.TransactionBuilder(destAccount, {\n    fee: StellarSdk.BASE_FEE,\n    networkPassphrase,\n  })\n    .addOperation(StellarSdk.Operation.changeTrust({ asset }))\n    .setTimeout(180)\n    .build();\n  \u002F\u002F Sign and submit...\n}\n```\n\n---\n\n### 9. Sequence Number Issues\n\n**Problem**: Transaction rejected for sequence number.\n\n**Symptoms**:\n```\nError: tx_bad_seq\n```\n\n**Causes & Solutions**:\n\n```typescript\n\u002F\u002F Cause 1: Stale account data\n\u002F\u002F Solution: Always load fresh account before building tx\nconst account = await server.loadAccount(publicKey);\n\n\u002F\u002F Cause 2: Parallel transactions\n\u002F\u002F Solution: Use sequence number management\nclass SequenceManager {\n  private sequence: bigint;\n\n  async getNext(server: Horizon.Server, publicKey: string) {\n    if (!this.sequence) {\n      const account = await server.loadAccount(publicKey);\n      this.sequence = BigInt(account.sequence);\n    }\n    this.sequence++;\n    return this.sequence.toString();\n  }\n}\n\n\u002F\u002F Cause 3: Transaction timeout without resubmit\n\u002F\u002F Solution: Rebuild with fresh sequence on timeout\n```\n\n---\n\n### 10. Soroban Transaction Not Simulated\n\n**Problem**: Soroban transaction fails with resource errors.\n\n**Symptoms**:\n```\nError: transaction simulation failed\nError: insufficient resources\n```\n\n**Solution**:\n```typescript\n\u002F\u002F ALWAYS simulate before submitting Soroban transactions\nconst simulation = await rpc.simulateTransaction(transaction);\n\nif (StellarSdk.rpc.Api.isSimulationError(simulation)) {\n  throw new Error(`Simulation failed: ${simulation.error}`);\n}\n\n\u002F\u002F Use assembleTransaction to add correct resources\nconst preparedTx = StellarSdk.rpc.assembleTransaction(\n  transaction,\n  simulation\n).build();\n\n\u002F\u002F Now sign and submit preparedTx, not original transaction\n```\n\n---\n\n## Frontend Issues\n\n### 11. Freighter Not Detected\n\n**Problem**: Wallet connection fails silently.\n\n**Symptoms**:\n- `isConnected()` returns false\n- No wallet prompt appears\n\n**Solution**:\n```typescript\nimport { isConnected, isAllowed, requestAccess } from \"@stellar\u002Ffreighter-api\";\n\nasync function checkFreighter() {\n  \u002F\u002F Check if extension is installed\n  const { isConnected: installed, error } = await isConnected();\n  if (error || !installed) {\n    \u002F\u002F Prompt user to install\n    window.open(\"https:\u002F\u002Ffreighter.app\", \"_blank\");\n    return;\n  }\n\n  \u002F\u002F Check if this app is already authorized\n  const { isAllowed: granted } = await isAllowed();\n  if (!granted) {\n    \u002F\u002F requestAccess prompts the user and returns { address, error }\n    const { error: accessError } = await requestAccess();\n    if (accessError) throw new Error(accessError.message);\n  }\n}\n```\n\n---\n\n### 12. Network Mismatch with Wallet\n\n**Problem**: Wallet on different network than app.\n\n**Symptoms**:\n- Transactions fail unexpectedly\n- Wrong balances displayed\n\n**Solution**:\n```typescript\nimport { getNetwork } from \"@stellar\u002Ffreighter-api\";\n\nasync function validateNetwork() {\n  const { network: walletNetwork, error } = await getNetwork();\n  if (error) throw new Error(error.message);\n  const appNetwork = process.env.NEXT_PUBLIC_STELLAR_NETWORK;\n\n  if (walletNetwork !== appNetwork) {\n    throw new Error(\n      `Please switch Freighter to ${appNetwork}. Currently on ${walletNetwork}`\n    );\n  }\n}\n```\n\n---\n\n### 13. Transaction Timeout\n\n**Problem**: Transaction expires before confirmation.\n\n**Symptoms**:\n```\nError: tx_too_late\n```\n\n**Solution**:\n```typescript\n\u002F\u002F Set appropriate timeout based on expected confirmation time\nconst tx = new StellarSdk.TransactionBuilder(account, {\n  fee: StellarSdk.BASE_FEE,\n  networkPassphrase,\n})\n  .addOperation(\u002F* ... *\u002F)\n  .setTimeout(180) \u002F\u002F 3 minutes - adjust as needed\n  .build();\n\n\u002F\u002F Handle timeout gracefully\nasync function submitWithRetry(signedXdr: string) {\n  try {\n    return await submitTransaction(signedXdr);\n  } catch (error) {\n    if (error.response?.data?.extras?.result_codes?.transaction === \"tx_too_late\") {\n      \u002F\u002F Rebuild with fresh blockhash and retry\n      const newTx = await rebuildTransaction(signedXdr);\n      return await submitTransaction(newTx);\n    }\n    throw error;\n  }\n}\n```\n\n---\n\n## CLI Issues\n\n### 14. Identity Not Found\n\n**Problem**: Stellar CLI can't find saved identity.\n\n**Symptoms**:\n```\nError: identity \"alice\" not found\n```\n\n**Solution**:\n```bash\n# List existing identities\nstellar keys list\n\n# Generate new identity\nstellar keys generate --global alice\n\n# For testnet with funding\nstellar keys generate --global alice --network testnet --fund\n\n# Specify identity location\nstellar keys generate alice --config-dir \u002Fcustom\u002Fpath\n```\n\n---\n\n### 15. Contract Invoke Parsing Errors\n\n**Problem**: CLI can't parse function arguments.\n\n**Symptoms**:\n```\nError: invalid argument format\n```\n\n**Solution**:\n```bash\n# Use correct argument syntax\n# Addresses: just the G... or C... string\nstellar contract invoke \\\n  --id CONTRACT_ID \\\n  --source alice \\\n  --network testnet \\\n  -- \\\n  transfer \\\n  --from GABC... \\\n  --to GDEF... \\\n  --amount 1000\n\n# Complex types: use JSON\nstellar contract invoke \\\n  --id CONTRACT_ID \\\n  -- \\\n  complex_fn \\\n  --data '{\"field1\": \"value\", \"field2\": 123}'\n```\n\n---\n\n## General Best Practices\n\n### Debugging Checklist\n\n1. **Check network**: Is wallet\u002FCLI on correct network?\n2. **Check account**: Is source account funded?\n3. **Check sequence**: Is sequence number current?\n4. **Check simulation**: Did Soroban tx simulate successfully?\n5. **Check trustlines**: For asset transfers, do trustlines exist?\n6. **Check TTL**: For contract data, is TTL sufficient?\n7. **Check authorization**: Is correct account signing?\n8. **Check logs**: What does the error message actually say?\n\n### Error Code Reference\n\n| Code | Meaning | Common Fix |\n|------|---------|------------|\n| `tx_bad_auth` | Signature invalid | Check network passphrase |\n| `tx_bad_seq` | Wrong sequence | Reload account |\n| `tx_too_late` | Transaction expired | Rebuild and resubmit |\n| `op_no_trust` | Missing trustline | Create trustline first |\n| `op_underfunded` | Insufficient balance | Add funds |\n| `op_low_reserve` | Below minimum balance | Maintain reserve |\n","# Soroban Smart Contracts\n\nEnd-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.\n\n## When to use this skill\n- Writing a Soroban contract in Rust\n- Setting up unit, integration, fuzz, or property tests\n- Reviewing a contract for security issues (authorization, reentrancy-adjacent bugs, storage hygiene, TTL, overflow)\n- Architecting upgradeable contracts, factories, governance, or DeFi primitives\n- Debugging a Soroban-specific error (auth, storage, archival, resource limits)\n\n## Related skills\n- Assets, trustlines, and SAC bridge → `..\u002Fassets\u002FSKILL.md`\n- Frontend\u002Fwallets that call your contract → `..\u002Fdapp\u002FSKILL.md`\n- Chain data queries (RPC\u002FHorizon) → `..\u002Fdata\u002FSKILL.md`\n- ZK cryptography (BLS12-381, BN254, Poseidon) → `..\u002Fzk-proofs\u002FSKILL.md`\n- SEP\u002FCAP standards and ecosystem links → `..\u002Fstandards\u002FSKILL.md`\n\n---\n\n# Part 1: Contract Development\n\n\n## When to use Soroban\nUse Soroban when you need:\n- Custom on-chain logic beyond Stellar's built-in operations\n- Programmable escrow, lending, or DeFi primitives\n- Complex authorization rules\n- State management beyond account balances\n- Interoperability with Stellar Assets via SAC\n\n## Quick Navigation\n- Initialization and constructors: [Project Setup](#project-setup), [Contract Constructors (Protocol 22+)](#contract-constructors-protocol-22)\n- Core implementation patterns: [Core Contract Structure](#core-contract-structure), [Storage Types](#storage-types), [Authorization](#authorization)\n- Advanced interactions: [Cross-Contract Calls](#cross-contract-calls), [Events](#events), [Error Handling](#error-handling)\n- Delivery workflow: [Building and Deploying](#building-and-deploying), [Unit Testing](#unit-testing), [Best Practices](#best-practices)\n- ZK status guidance: [Zero-Knowledge Cryptography (Status-Sensitive)](#zero-knowledge-cryptography-status-sensitive)\n\n## Alternative Languages\n\nRust is the primary and recommended language for Soroban contracts. Community-maintained alternatives exist but are not recommended for production:\n- **AssemblyScript**: [`as-soroban-sdk`](https:\u002F\u002Fgithub.com\u002FSoneso\u002Fas-soroban-sdk) by Soneso - allows TypeScript-like syntax, officially listed on Stellar docs, but may lag behind the latest protocol version\n- **Solidity**: [Hyperledger Solang](https:\u002F\u002Fgithub.com\u002Fhyperledger-solang\u002Fsolang) - SDF-funded, compiles Solidity to Soroban WASM, currently **pre-alpha** ([docs](https:\u002F\u002Fdevelopers.stellar.org\u002Fdocs\u002Flearn\u002Fmigrate\u002Fevm\u002Fsolidity-support-via-solang))\n\n## Architecture Overview\n\n### Host-Guest Model\nSoroban uses a WebAssembly sandbox with strict separation:\n- **Host Environment**: Provides storage, crypto, cross-contract calls\n- **Guest Contract**: Your Rust code compiled to WASM\n- Contracts reference host objects via handles (not direct memory)\n\n### Key Constraints\n- `#![no_std]` required - no Rust standard library\n- 64KB contract size limit (use release optimizations)\n- Limited heap allocation\n- No string type (use `String` from soroban-sdk or `Symbol` for short strings)\n- `Symbol` limited to 32 characters (was 10 in earlier versions)\n\n## Project Setup\n\n### Initialize a new contract\n```bash\nstellar contract init my-contract\ncd my-contract\n```\n\nThis creates:\n```\nmy-contract\u002F\n├── Cargo.toml\n├── src\u002F\n│   └── lib.rs\n└── contracts\u002F\n    └── hello_world\u002F\n        ├── Cargo.toml\n        └── src\u002F\n            └── lib.rs\n```\n\n### Cargo.toml configuration\n```toml\n[package]\nname = \"my-contract\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[lib]\ncrate-type = [\"cdylib\"]\n\n[dependencies]\nsoroban-sdk = \"25.0.1\"  # check https:\u002F\u002Fcrates.io\u002Fcrates\u002Fsoroban-sdk for latest\n\n[dev-dependencies]\nsoroban-sdk = { version = \"25.0.1\", features = [\"testutils\"] }  # match above\n\n[profile.release]\nopt-level = \"z\"\noverflow-checks = true\ndebug = 0\nstrip = \"symbols\"\ndebug-assertions = false\npanic = \"abort\"\ncodegen-units = 1\nlto = true\n\n[profile.release-with-logs]\ninherits = \"release\"\ndebug-assertions = true\n```\n\n## Contract Constructors (Protocol 22+)\n\nUse constructors for atomic initialization when protocol support is available. This avoids a separate `initialize` transaction and reduces front-running risk.\n\n### Constructor pattern\n```rust\n#![no_std]\nuse soroban_sdk::{contract, contractimpl, contracttype, Address, Env};\n\n#[contracttype]\n#[derive(Clone)]\npub enum DataKey {\n    Admin,\n    Value,\n}\n\n#[contract]\npub struct MyContract;\n\n#[contractimpl]\nimpl MyContract {\n    \u002F\u002F Runs once at deployment time.\n    pub fn __constructor(env: Env, admin: Address, initial_value: u32) {\n        env.storage().instance().set(&DataKey::Admin, &admin);\n        env.storage().instance().set(&DataKey::Value, &initial_value);\n    }\n}\n```\n\n### Deploy with constructor args (CLI)\n```bash\nstellar contract deploy \\\n  --wasm target\u002Fwasm32-unknown-unknown\u002Frelease\u002Fmy_contract.wasm \\\n  --source alice \\\n  --network testnet \\\n  -- \\\n  --admin alice \\\n  --initial_value 100\n```\n\n### Rules\n1. Name must be `__constructor` exactly.\n2. Constructor returns `()` (no return value).\n3. Runs only at creation time and does not run on upgrade.\n4. If constructor fails, deployment fails atomically.\n\n### Backwards compatibility\nIf targeting older protocol environments, use guarded `initialize` patterns and prevent re-initialization explicitly.\n\n## Core Contract Structure\n\n### Basic Contract\n```rust\n#![no_std]\nuse soroban_sdk::{contract, contractimpl, symbol_short, vec, Env, Symbol, Vec};\n\n#[contract]\npub struct HelloContract;\n\n#[contractimpl]\nimpl HelloContract {\n    pub fn hello(env: Env, to: Symbol) -> Vec\u003CSymbol> {\n        vec![&env, symbol_short!(\"Hello\"), to]\n    }\n}\n```\n\n### Contract with State\n```rust\n#![no_std]\nuse soroban_sdk::{contract, contractimpl, contracttype, Address, Env};\n\n#[contracttype]\n#[derive(Clone)]\npub enum DataKey {\n    Counter,\n    Admin,\n    UserBalance(Address),\n}\n\n#[contract]\npub struct CounterContract;\n\n#[contractimpl]\nimpl CounterContract {\n    pub fn initialize(env: Env, admin: Address) {\n        if env.storage().instance().has(&DataKey::Admin) {\n            panic!(\"already initialized\");\n        }\n        env.storage().instance().set(&DataKey::Admin, &admin);\n        env.storage().instance().set(&DataKey::Counter, &0u32);\n    }\n\n    pub fn increment(env: Env) -> u32 {\n        let mut count: u32 = env.storage().instance().get(&DataKey::Counter).unwrap_or(0);\n        count += 1;\n        env.storage().instance().set(&DataKey::Counter, &count);\n\n        \u002F\u002F Extend TTL to prevent archival\n        env.storage().instance().extend_ttl(100, 518400); \u002F\u002F threshold, ~30 days\n\n        count\n    }\n\n    pub fn get_count(env: Env) -> u32 {\n        env.storage().instance().get(&DataKey::Counter).unwrap_or(0)\n    }\n}\n```\n\n## Storage Types\n\nSoroban has three storage types with different costs and lifetimes:\n\n### Instance Storage\n- Tied to contract instance lifetime\n- Shared across all users\n- Best for: admin addresses, global config, counters\n```rust\nenv.storage().instance().set(&key, &value);\nenv.storage().instance().get(&key);\nenv.storage().instance().extend_ttl(min_ttl, extend_to);\n```\n\n### Persistent Storage\n- Survives archival (can be restored)\n- Per-key TTL management\n- Best for: user balances, important state\n```rust\nenv.storage().persistent().set(&key, &value);\nenv.storage().persistent().get(&key);\nenv.storage().persistent().extend_ttl(&key, min_ttl, extend_to);\n```\n\n### Temporary Storage\n- Cheapest, automatically deleted when TTL expires\n- Cannot be restored after archival\n- Best for: caches, temporary flags, session data\n```rust\nenv.storage().temporary().set(&key, &value);\nenv.storage().temporary().get(&key);\nenv.storage().temporary().extend_ttl(&key, min_ttl, extend_to);\n```\n\n### TTL Management\n```rust\n\u002F\u002F Check remaining TTL\nlet ttl = env.storage().persistent().get_ttl(&key);\n\n\u002F\u002F Extend if below threshold\nconst MIN_TTL: u32 = 17280;  \u002F\u002F ~1 day at 5s ledgers\nconst EXTEND_TO: u32 = 518400;  \u002F\u002F ~30 days\n\nif ttl \u003C MIN_TTL {\n    env.storage().persistent().extend_ttl(&key, MIN_TTL, EXTEND_TO);\n}\n```\n\n## Data Types\n\n### Primitive Types\n```rust\nuse soroban_sdk::{Address, Bytes, BytesN, Map, String, Symbol, Vec, I128, U256};\n\n\u002F\u002F Address - account or contract identifier\nlet addr: Address = env.current_contract_address();\n\n\u002F\u002F Symbol - short strings (max 32 chars)\nlet sym: Symbol = symbol_short!(\"transfer\");\n\n\u002F\u002F String - longer strings\nlet s: String = String::from_str(&env, \"Hello, Stellar!\");\n\n\u002F\u002F Fixed-size bytes\nlet hash: BytesN\u003C32> = env.crypto().sha256(&bytes);\n\n\u002F\u002F Collections\nlet v: Vec\u003Cu32> = vec![&env, 1, 2, 3];\nlet m: Map\u003CSymbol, u32> = Map::new(&env);\n```\n\n### Custom Types\n```rust\n#[contracttype]\n#[derive(Clone, Debug, Eq, PartialEq)]\npub struct TokenMetadata {\n    pub name: String,\n    pub symbol: Symbol,\n    pub decimals: u32,\n}\n\n#[contracttype]\n#[derive(Clone)]\npub enum DataKey {\n    Admin,\n    Balance(Address),\n    Allowance(Address, Address),  \u002F\u002F (owner, spender)\n}\n```\n\n## Authorization\n\n### Requiring Authorization\n```rust\n#[contractimpl]\nimpl TokenContract {\n    pub fn transfer(env: Env, from: Address, to: Address, amount: i128) {\n        \u002F\u002F Require 'from' to authorize this call\n        from.require_auth();\n\n        \u002F\u002F Or require auth for specific arguments\n        from.require_auth_for_args((&to, amount).into_val(&env));\n\n        \u002F\u002F Transfer logic...\n    }\n}\n```\n\n### Admin Patterns\n```rust\nfn require_admin(env: &Env) {\n    let admin: Address = env.storage().instance().get(&DataKey::Admin).unwrap();\n    admin.require_auth();\n}\n\npub fn set_admin(env: Env, new_admin: Address) {\n    require_admin(&env);\n    env.storage().instance().set(&DataKey::Admin, &new_admin);\n}\n```\n\n## Cross-Contract Calls\n\n### Calling Another Contract\n```rust\nuse soroban_sdk::{contract, contractimpl, Address, Env};\n\nmod token_contract {\n    soroban_sdk::contractimport!(\n        file = \"..\u002Ftoken\u002Ftarget\u002Fwasm32-unknown-unknown\u002Frelease\u002Ftoken.wasm\"\n    );\n}\n\n#[contract]\npub struct VaultContract;\n\n#[contractimpl]\nimpl VaultContract {\n    pub fn deposit(env: Env, user: Address, token: Address, amount: i128) {\n        user.require_auth();\n\n        \u002F\u002F Create client for token contract\n        let token_client = token_contract::Client::new(&env, &token);\n\n        \u002F\u002F Call transfer on token contract\n        token_client.transfer(&user, &env.current_contract_address(), &amount);\n\n        \u002F\u002F Update vault state...\n    }\n}\n```\n\n### Using Stellar Asset Contract (SAC)\n```rust\nuse soroban_sdk::token::Client as TokenClient;\n\npub fn transfer_asset(env: Env, from: Address, to: Address, asset: Address, amount: i128) {\n    from.require_auth();\n\n    let token = TokenClient::new(&env, &asset);\n    token.transfer(&from, &to, &amount);\n}\n```\n\n## Events\n\n### Emitting Events\n```rust\nuse soroban_sdk::{contract, contractevent, contractimpl, Address, Env};\n\n#[contractevent(topics = [\"transfer\"])]\npub struct TransferEvent {\n    pub from: Address,\n    pub to: Address,\n    pub amount: i128,\n}\n\n#[contract]\npub struct TokenContract;\n\n#[contractimpl]\nimpl TokenContract {\n    pub fn transfer(env: Env, from: Address, to: Address, amount: i128) {\n        \u002F\u002F ... transfer logic ...\n\n        \u002F\u002F Emit event\n        TransferEvent { from, to, amount }.publish(&env);\n    }\n}\n```\n\n## Error Handling\n\n### Custom Errors\n```rust\nuse soroban_sdk::contracterror;\n\n#[contracterror]\n#[derive(Copy, Clone, Debug, Eq, PartialEq)]\n#[repr(u32)]\npub enum ContractError {\n    AlreadyInitialized = 1,\n    NotInitialized = 2,\n    InsufficientBalance = 3,\n    Unauthorized = 4,\n    InvalidAmount = 5,\n}\n\n\u002F\u002F Usage\npub fn transfer(env: Env, from: Address, to: Address, amount: i128) -> Result\u003C(), ContractError> {\n    if amount \u003C= 0 {\n        return Err(ContractError::InvalidAmount);\n    }\n\n    let balance: i128 = get_balance(&env, &from);\n    if balance \u003C amount {\n        return Err(ContractError::InsufficientBalance);\n    }\n\n    \u002F\u002F ... transfer logic ...\n    Ok(())\n}\n```\n\n## Building and Deploying\n\n### Build Contract\n```bash\n# Build optimized WASM\nstellar contract build\n\n# Output: target\u002Fwasm32-unknown-unknown\u002Frelease\u002Fmy_contract.wasm\n```\n\n### Deploy to Testnet\n```bash\n# Generate and fund a new identity\nstellar keys generate --global alice --network testnet --fund\n\n# Deploy contract\nstellar contract deploy \\\n  --wasm target\u002Fwasm32-unknown-unknown\u002Frelease\u002Fmy_contract.wasm \\\n  --source alice \\\n  --network testnet\n\n# Returns: CONTRACT_ID (starts with 'C')\n```\n\n### Initialize Contract\n```bash\nstellar contract invoke \\\n  --id CONTRACT_ID \\\n  --source alice \\\n  --network testnet \\\n  -- \\\n  initialize \\\n  --admin alice\n```\n\n### Invoke Functions\n```bash\nstellar contract invoke \\\n  --id CONTRACT_ID \\\n  --source alice \\\n  --network testnet \\\n  -- \\\n  increment\n```\n\n## Unit Testing\n\n```rust\n#![cfg(test)]\n\nuse super::*;\nuse soroban_sdk::testutils::Address as _;\nuse soroban_sdk::Env;\n\n#[test]\nfn test_increment() {\n    let env = Env::default();\n    let contract_id = env.register(CounterContract, ());\n    let client = CounterContractClient::new(&env, &contract_id);\n\n    let admin = Address::generate(&env);\n    client.initialize(&admin);\n\n    assert_eq!(client.get_count(), 0);\n    assert_eq!(client.increment(), 1);\n    assert_eq!(client.increment(), 2);\n    assert_eq!(client.get_count(), 2);\n}\n\n#[test]\nfn test_transfer_with_auth() {\n    let env = Env::default();\n    env.mock_all_auths();  \u002F\u002F Auto-approve all auth requests\n\n    let contract_id = env.register(TokenContract, ());\n    let client = TokenContractClient::new(&env, &contract_id);\n\n    let alice = Address::generate(&env);\n    let bob = Address::generate(&env);\n\n    \u002F\u002F Mint tokens to alice\n    client.mint(&alice, &1000);\n\n    \u002F\u002F Transfer from alice to bob\n    client.transfer(&alice, &bob, &100);\n\n    assert_eq!(client.balance(&alice), 900);\n    assert_eq!(client.balance(&bob), 100);\n}\n```\n\n## Best Practices\n\n### Contract Size Optimization\n- Use `symbol_short!()` for symbols under 9 chars (more efficient)\n- Avoid unnecessary string operations\n- Use appropriate storage type for data lifetime\n- Consider splitting large contracts\n\n### Storage Efficiency\n- Use compact data structures\n- Clean up temporary storage\n- Batch storage operations when possible\n- Manage TTLs proactively to avoid archival\n\n### Security\n- Always validate inputs\n- Use `require_auth()` for sensitive operations\n- Check contract ownership in initialization\n- Prevent reinitialization attacks\n- Validate cross-contract call targets\n\n### Gas\u002FResource Optimization\n- Minimize storage reads\u002Fwrites\n- Use events for data that doesn't need on-chain queries\n- Batch operations where possible\n- Profile resource usage with `stellar contract invoke --sim`\n\n## Zero-Knowledge Cryptography (Status-Sensitive)\n\nStellar's ZK cryptography capabilities are evolving. Treat availability as protocol- and network-dependent.\n\n- [CAP-0059](https:\u002F\u002Fgithub.com\u002Fstellar\u002Fstellar-protocol\u002Fblob\u002Fmaster\u002Fcore\u002Fcap-0059.md): BLS12-381 primitives\n- [CAP-0074](https:\u002F\u002Fgithub.com\u002Fstellar\u002Fstellar-protocol\u002Fblob\u002Fmaster\u002Fcore\u002Fcap-0074.md): BN254 host functions (proposed)\n- [CAP-0075](https:\u002F\u002Fgithub.com\u002Fstellar\u002Fstellar-protocol\u002Fblob\u002Fmaster\u002Fcore\u002Fcap-0075.md): Poseidon\u002FPoseidon2 host functions (proposed)\n\nBefore implementation, always verify:\n1. CAP status in the CAP preamble (`Accepted`\u002F`Implemented` vs draft\u002Fawaiting decision)\n2. Target network software version and protocol support\n3. `soroban-sdk` release support for the target host functions\n\n### Practical guidance\n- Use BLS12-381 features where supported and documented in your target SDK\u002Fnetwork.\n- For BN254\u002FPoseidon plans, design feature flags and graceful fallbacks until support is active.\n- Keep cryptographic assumptions explicit in audits and deployment notes.\n\n### Example references\n- [Groth16 Verifier](https:\u002F\u002Fgithub.com\u002Fstellar\u002Fsoroban-examples\u002Ftree\u002Fmain\u002Fgroth16_verifier)\n- [Soroban examples repository](https:\u002F\u002Fgithub.com\u002Fstellar\u002Fsoroban-examples)\n\n> See [zk-proofs.md](..\u002Fzk-proofs\u002FSKILL.md) for Groth16 verification patterns, Poseidon usage, Noir\u002FRISC Zero integration, and implementation guidance.\n\n---\n\n# Part 2: Testing Strategy\n\n\n## Quick Navigation\n- Strategy overview: [Testing Pyramid](#testing-pyramid)\n- Core test layers: [Unit Testing with Soroban SDK](#unit-testing-with-soroban-sdk), [Local Testing with Stellar Quickstart](#local-testing-with-stellar-quickstart), [Testnet Testing](#testnet-testing)\n- Integration and CI: [Integration Testing Patterns](#integration-testing-patterns), [Test Configuration](#test-configuration), [CI\u002FCD Configuration](#cicd-configuration)\n- Advanced testing: [Fuzz Testing](#fuzz-testing), [Property-Based Testing](#property-based-testing), [Differential Testing with Test Snapshots](#differential-testing-with-test-snapshots), [Fork Testing](#fork-testing), [Mutation Testing](#mutation-testing)\n- Performance and readiness: [Resource Profiling](#resource-profiling), [Best Practices](#best-practices)\n\n## Testing Pyramid\n\n1. **Unit tests (fast)**: Native Rust tests with `soroban-sdk` testutils\n2. **Local integration tests**: Stellar Quickstart Docker\n3. **Testnet tests**: Deploy and test on public testnet\n4. **Mainnet smoke tests**: Final validation before production\n\n## Unit Testing with Soroban SDK\n\nThe Soroban SDK provides comprehensive testing utilities that run natively (not in WASM), enabling fast iteration with full debugging support.\n\n### Basic Test Setup\n\n```rust\n#![cfg(test)]\n\nuse soroban_sdk::{testutils::Address as _, Address, Env};\n\n\u002F\u002F Import your contract\nuse crate::{Contract, ContractClient};\n\n#[test]\nfn test_basic_functionality() {\n    \u002F\u002F Create test environment\n    let env = Env::default();\n\n    \u002F\u002F Register contract\n    let contract_id = env.register(Contract, ());\n\n    \u002F\u002F Create typed client\n    let client = ContractClient::new(&env, &contract_id);\n\n    \u002F\u002F Generate test addresses\n    let user = Address::generate(&env);\n\n    \u002F\u002F Call contract functions\n    client.initialize(&user);\n\n    \u002F\u002F Assert results\n    assert_eq!(client.get_value(), 0);\n}\n```\n\n### Testing Authorization\n\n```rust\n#[test]\nfn test_with_auth() {\n    let env = Env::default();\n\n    \u002F\u002F Mock all authorizations automatically\n    env.mock_all_auths();\n\n    let contract_id = env.register(TokenContract, ());\n    let client = TokenContractClient::new(&env, &contract_id);\n\n    let admin = Address::generate(&env);\n    let user1 = Address::generate(&env);\n    let user2 = Address::generate(&env);\n\n    \u002F\u002F Initialize and mint\n    client.initialize(&admin);\n    client.mint(&user1, &1000);\n\n    \u002F\u002F Transfer (requires auth from user1)\n    client.transfer(&user1, &user2, &100);\n\n    assert_eq!(client.balance(&user1), 900);\n    assert_eq!(client.balance(&user2), 100);\n\n    \u002F\u002F Verify which auths were required\n    let auths = env.auths();\n    assert_eq!(auths.len(), 1);\n    \u002F\u002F auths[0] contains (address, contract_id, function, args)\n}\n```\n\n### Testing with Specific Auth Requirements\n\n```rust\n#[test]\nfn test_specific_auth() {\n    let env = Env::default();\n    let contract_id = env.register(Contract, ());\n    let client = ContractClient::new(&env, &contract_id);\n\n    let user = Address::generate(&env);\n\n    \u002F\u002F Mock auth only for specific address\n    env.mock_auths(&[MockAuth {\n        address: &user,\n        invoke: &MockAuthInvoke {\n            contract: &contract_id,\n            fn_name: \"transfer\",\n            args: (&user, &other, &100i128).into_val(&env),\n            sub_invokes: &[],\n        },\n    }]);\n\n    client.transfer(&user, &other, &100);\n}\n```\n\n### Testing Time-Dependent Logic\n\n```rust\n#[test]\nfn test_time_based() {\n    let env = Env::default();\n    let contract_id = env.register(VestingContract, ());\n    let client = VestingContractClient::new(&env, &contract_id);\n\n    let beneficiary = Address::generate(&env);\n\n    \u002F\u002F Set initial timestamp\n    env.ledger().set_timestamp(1000);\n\n    client.create_vesting(&beneficiary, &1000, &2000); \u002F\u002F unlock at t=2000\n\n    \u002F\u002F Try to claim before unlock\n    assert!(client.try_claim(&beneficiary).is_err());\n\n    \u002F\u002F Advance time past unlock\n    env.ledger().set_timestamp(2500);\n\n    \u002F\u002F Now claim succeeds\n    client.claim(&beneficiary);\n}\n```\n\n### Testing Ledger State\n\n```rust\n#[test]\nfn test_ledger_manipulation() {\n    let env = Env::default();\n\n    \u002F\u002F Set ledger sequence\n    env.ledger().set_sequence_number(1000);\n\n    \u002F\u002F Set timestamp\n    env.ledger().set_timestamp(1704067200); \u002F\u002F Jan 1, 2024\n\n    \u002F\u002F Set network passphrase\n    env.ledger().set_network_id([0u8; 32]); \u002F\u002F Custom network ID\n\n    \u002F\u002F Get current values\n    let seq = env.ledger().sequence();\n    let ts = env.ledger().timestamp();\n}\n```\n\n### Testing Events\n\n```rust\n#[test]\nfn test_events() {\n    let env = Env::default();\n    let contract_id = env.register(Contract, ());\n    let client = ContractClient::new(&env, &contract_id);\n\n    client.do_something();\n\n    \u002F\u002F Get all events\n    let events = env.events().all();\n\n    \u002F\u002F Check specific event\n    assert_eq!(events.len(), 1);\n\n    let event = &events[0];\n    \u002F\u002F event.0 = contract_id\n    \u002F\u002F event.1 = topics (Vec\u003CVal>)\n    \u002F\u002F event.2 = data (Val)\n}\n```\n\n### Testing Storage\n\n```rust\n#[test]\nfn test_storage_ttl() {\n    let env = Env::default();\n    let contract_id = env.register(Contract, ());\n    let client = ContractClient::new(&env, &contract_id);\n\n    client.store_data();\n\n    \u002F\u002F Check TTL\n    let key = DataKey::MyData;\n    let ttl = env.as_contract(&contract_id, || {\n        env.storage().persistent().get_ttl(&key)\n    });\n\n    assert!(ttl > 0);\n}\n```\n\n### Testing Cross-Contract Calls\n\n```rust\n#[test]\nfn test_cross_contract() {\n    let env = Env::default();\n\n    \u002F\u002F Register both contracts\n    let token_id = env.register(token::WASM, ());\n    let vault_id = env.register(VaultContract, ());\n\n    let token_client = token::Client::new(&env, &token_id);\n    let vault_client = VaultContractClient::new(&env, &vault_id);\n\n    env.mock_all_auths();\n\n    let user = Address::generate(&env);\n\n    \u002F\u002F Setup: mint tokens to user\n    token_client.mint(&user, &1000);\n\n    \u002F\u002F Test: deposit tokens into vault\n    vault_client.deposit(&user, &token_id, &500);\n\n    assert_eq!(token_client.balance(&user), 500);\n    assert_eq!(vault_client.balance(&user), 500);\n}\n```\n\n## Local Testing with Stellar Quickstart\n\n### Start Local Network\n\n```bash\n# Pull and run Stellar Quickstart\ndocker run --rm -it -p 8000:8000 \\\n  --name stellar \\\n  stellar\u002Fquickstart:latest \\\n  --local \\\n  --enable-soroban-rpc\n\n# Or use Stellar CLI\nstellar container start local\n```\n\n### Configure for Local Network\n\n```typescript\nimport * as StellarSdk from \"@stellar\u002Fstellar-sdk\";\n\nconst LOCAL_RPC = \"http:\u002F\u002Flocalhost:8000\u002Fsoroban\u002Frpc\";\nconst LOCAL_HORIZON = \"http:\u002F\u002Flocalhost:8000\";\nconst LOCAL_PASSPHRASE = \"Standalone Network ; February 2017\";\n\nconst rpc = new StellarSdk.rpc.Server(LOCAL_RPC);\nconst horizon = new StellarSdk.Horizon.Server(LOCAL_HORIZON);\n```\n\n### Fund Test Accounts (Local)\n\n```bash\n# Using Stellar CLI\nstellar keys generate --global test-account --network local --fund\n\n# Or via friendbot endpoint\ncurl \"http:\u002F\u002Flocalhost:8000\u002Ffriendbot?addr=G...\"\n```\n\n### Deploy and Test Locally\n\n```bash\n# Deploy contract to local network\nstellar contract deploy \\\n  --wasm target\u002Fwasm32-unknown-unknown\u002Frelease\u002Fcontract.wasm \\\n  --source test-account \\\n  --network local\n\n# Invoke contract\nstellar contract invoke \\\n  --id CONTRACT_ID \\\n  --source test-account \\\n  --network local \\\n  -- \\\n  function_name \\\n  --arg value\n```\n\n## Testnet Testing\n\n### Network Configuration\n\n```bash\n# Testnet RPC: https:\u002F\u002Fsoroban-testnet.stellar.org\n# Testnet Horizon: https:\u002F\u002Fhorizon-testnet.stellar.org\n# Network Passphrase: \"Test SDF Network ; September 2015\"\n# Friendbot: https:\u002F\u002Ffriendbot.stellar.org\n```\n\n### Create and Fund Testnet Account\n\n```bash\n# Generate new identity\nstellar keys generate --global my-testnet-key --network testnet\n\n# Fund via Friendbot\nstellar keys fund my-testnet-key --network testnet\n\n# Or manually\ncurl \"https:\u002F\u002Ffriendbot.stellar.org?addr=G...\"\n```\n\n### Deploy to Testnet\n\n```bash\n# Deploy contract\nstellar contract deploy \\\n  --wasm target\u002Fwasm32-unknown-unknown\u002Frelease\u002Fcontract.wasm \\\n  --source my-testnet-key \\\n  --network testnet\n\n# Upload contract code (separate from deployment)\nstellar contract upload \\\n  --wasm target\u002Fwasm32-unknown-unknown\u002Frelease\u002Fcontract.wasm \\\n  --source my-testnet-key \\\n  --network testnet\n```\n\n### Testnet Reset Awareness\n\n**Important**: Testnet resets approximately quarterly:\n- All accounts and contracts are deleted\n- Plan for re-deployment after resets\n- Don't rely on persistent state for test data\n\nCheck reset schedule: https:\u002F\u002Fstellar.org\u002Fdevelopers\u002Fblog\n\n## Integration Testing Patterns\n\n### TypeScript Integration Tests\n\n```typescript\n\u002F\u002F tests\u002Fintegration\u002Fcontract.test.ts\nimport * as StellarSdk from \"@stellar\u002Fstellar-sdk\";\n\nconst RPC_URL = process.env.RPC_URL || \"http:\u002F\u002Flocalhost:8000\u002Fsoroban\u002Frpc\";\nconst NETWORK_PASSPHRASE = process.env.NETWORK_PASSPHRASE || \"Standalone Network ; February 2017\";\n\ndescribe(\"Contract Integration Tests\", () => {\n  let rpc: StellarSdk.rpc.Server;\n  let keypair: StellarSdk.Keypair;\n  let contractId: string;\n\n  beforeAll(async () => {\n    rpc = new StellarSdk.rpc.Server(RPC_URL);\n    keypair = StellarSdk.Keypair.random();\n\n    \u002F\u002F Fund account\n    await fundAccount(keypair.publicKey());\n\n    \u002F\u002F Deploy contract\n    contractId = await deployContract(keypair);\n  });\n\n  test(\"should initialize contract\", async () => {\n    const account = await rpc.getAccount(keypair.publicKey());\n    const contract = new StellarSdk.Contract(contractId);\n\n    const tx = new StellarSdk.TransactionBuilder(account, {\n      fee: \"100\",\n      networkPassphrase: NETWORK_PASSPHRASE,\n    })\n      .addOperation(\n        contract.call(\n          \"initialize\",\n          StellarSdk.Address.fromString(keypair.publicKey()).toScVal()\n        )\n      )\n      .setTimeout(30)\n      .build();\n\n    const simResult = await rpc.simulateTransaction(tx);\n    const preparedTx = StellarSdk.rpc.assembleTransaction(tx, simResult);\n\n    preparedTx.sign(keypair);\n    const result = await rpc.sendTransaction(preparedTx.build());\n\n    expect(result.status).not.toBe(\"ERROR\");\n  });\n});\n```\n\n### Rust Integration Tests\n\n```rust\n\u002F\u002F tests\u002Fintegration_test.rs\nuse soroban_sdk::{Env, Address};\nuse std::process::Command;\n\n#[test]\n#[ignore] \u002F\u002F Run with: cargo test -- --ignored\nfn integration_test_with_local_network() {\n    \u002F\u002F Requires local network running\n    let output = Command::new(\"stellar\")\n        .args([\n            \"contract\", \"invoke\",\n            \"--id\", \"CONTRACT_ID\",\n            \"--source\", \"test-account\",\n            \"--network\", \"local\",\n            \"--\",\n            \"get_count\"\n        ])\n        .output()\n        .expect(\"Failed to invoke contract\");\n\n    assert!(output.status.success());\n}\n```\n\n## Test Configuration\n\n### Cargo.toml for Tests\n\n```toml\n[dev-dependencies]\nsoroban-sdk = { version = \"25.0.1\", features = [\"testutils\"] }  # match [dependencies] version\n\n[profile.test]\nopt-level = 0\ndebug = true\n```\n\n### Running Tests\n\n```bash\n# Run unit tests\ncargo test\n\n# Run with output\ncargo test -- --nocapture\n\n# Run specific test\ncargo test test_transfer\n\n# Run ignored (integration) tests\ncargo test -- --ignored\n```\n\n## CI\u002FCD Configuration\n\n### GitHub Actions Example\n\n```yaml\nname: Test Soroban Contract\n\non: [push, pull_request]\n\njobs:\n  unit-tests:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions\u002Fcheckout@v4\n\n      - name: Install Rust\n        uses: dtolnay\u002Frust-toolchain@stable\n\n      - name: Add WASM target\n        run: rustup target add wasm32-unknown-unknown\n\n      - name: Run unit tests\n        run: cargo test\n\n      - name: Build contract\n        run: cargo build --release --target wasm32-unknown-unknown\n\n  integration-tests:\n    runs-on: ubuntu-latest\n    needs: unit-tests\n    services:\n      stellar:\n        image: stellar\u002Fquickstart:latest\n        ports:\n          - 8000:8000\n        options: >-\n          --health-cmd \"curl -f http:\u002F\u002Flocalhost:8000 || exit 1\"\n          --health-interval 10s\n          --health-timeout 5s\n          --health-retries 10\n\n    steps:\n      - uses: actions\u002Fcheckout@v4\n\n      - name: Install Stellar CLI\n        run: |\n          cargo install stellar-cli --locked\n\n      - name: Deploy and test\n        run: |\n          stellar keys generate --global ci-test --network local --fund\n          stellar contract deploy \\\n            --wasm target\u002Fwasm32-unknown-unknown\u002Frelease\u002Fcontract.wasm \\\n            --source ci-test \\\n            --network local\n```\n\n## Best Practices\n\n### Test Organization\n```\nproject\u002F\n├── src\u002F\n│   └── lib.rs\n├── tests\u002F\n│   ├── common\u002F\n│   │   └── mod.rs      # Shared test utilities\n│   ├── unit\u002F\n│   │   ├── mod.rs\n│   │   └── transfer.rs\n│   └── integration\u002F\n│       └── full_flow.rs\n└── Cargo.toml\n```\n\n### Test Utilities Module\n\n```rust\n\u002F\u002F tests\u002Fcommon\u002Fmod.rs\nuse soroban_sdk::{testutils::Address as _, Address, Env};\nuse crate::{Contract, ContractClient};\n\npub fn setup_contract(env: &Env) -> (Address, ContractClient) {\n    let contract_id = env.register(Contract, ());\n    let client = ContractClient::new(env, &contract_id);\n    let admin = Address::generate(env);\n\n    env.mock_all_auths();\n    client.initialize(&admin);\n\n    (contract_id, client)\n}\n\npub fn create_funded_user(env: &Env, client: &ContractClient, amount: i128) -> Address {\n    let user = Address::generate(env);\n    client.mint(&user, &amount);\n    user\n}\n```\n\n## Fuzz Testing\n\nSoroban has first-class fuzz testing via `cargo-fuzz` and the built-in `SorobanArbitrary` trait. All `#[contracttype]` types automatically derive `SorobanArbitrary` when the `\"testutils\"` feature is active.\n\n### Setup\n\n```bash\n# Install nightly Rust + cargo-fuzz\nrustup install nightly\ncargo install --locked cargo-fuzz\n\n# Initialize fuzz targets\ncargo fuzz init\n```\n\nUpdate `Cargo.toml` to include both crate types:\n```toml\n[lib]\ncrate-type = [\"lib\", \"cdylib\"]\n```\n\nAdd to `fuzz\u002FCargo.toml`:\n```toml\n[dependencies]\nsoroban-sdk = { version = \"25.0.1\", features = [\"testutils\"] }\n```\n\n### Writing a Fuzz Target\n\n```rust\n\u002F\u002F fuzz\u002Ffuzz_targets\u002Ffuzz_deposit.rs\n#![no_main]\n\nuse libfuzzer_sys::fuzz_target;\nuse soroban_sdk::{testutils::Address as _, Address, Env};\nuse my_contract::{Contract, ContractClient};\n\nfuzz_target!(|input: (u64, i128)| {\n    let (seed, amount) = input;\n    let env = Env::default();\n    env.mock_all_auths();\n\n    let contract_id = env.register(Contract, ());\n    let client = ContractClient::new(&env, &contract_id);\n    let user = Address::generate(&env);\n\n    \u002F\u002F Initialize\n    client.initialize(&user);\n\n    \u002F\u002F Fuzz deposit - should never panic unexpectedly\n    let _ = client.try_deposit(&user, &amount);\n});\n```\n\n### Running Fuzz Tests\n\n```bash\n# Run (use --sanitizer=thread on macOS)\ncargo +nightly fuzz run fuzz_deposit\n\n# Generate code coverage\ncargo +nightly fuzz coverage fuzz_deposit\n```\n\n### Soroban Token Fuzzer\n\nReusable library for fuzzing token contracts:\n- **GitHub**: https:\u002F\u002Fgithub.com\u002Fbrson\u002Fsoroban-token-fuzzer\n\n### Documentation\n\n- [Stellar Fuzzing Guide](https:\u002F\u002Fdevelopers.stellar.org\u002Fdocs\u002Fbuild\u002Fguides\u002Ftesting\u002Ffuzzing)\n- [Fuzzing Example Contract](https:\u002F\u002Fdevelopers.stellar.org\u002Fdocs\u002Fbuild\u002Fsmart-contracts\u002Fexample-contracts\u002Ffuzzing)\n\n## Property-Based Testing\n\nUse `proptest` with `SorobanArbitrary` for QuickCheck-style property testing that runs in standard `cargo test`.\n\n```rust\n#[cfg(test)]\nmod prop_tests {\n    use super::*;\n    use proptest::prelude::*;\n    use soroban_sdk::{testutils::Address as _, Env};\n\n    proptest! {\n        #[test]\n        fn deposit_then_withdraw_preserves_balance(amount in 1i128..=i128::MAX) {\n            let env = Env::default();\n            env.mock_all_auths();\n            let contract_id = env.register(Contract, ());\n            let client = ContractClient::new(&env, &contract_id);\n            let user = Address::generate(&env);\n\n            client.initialize(&user);\n            client.deposit(&user, &amount);\n            client.withdraw(&user, &amount);\n\n            prop_assert_eq!(client.balance(&user), 0);\n        }\n    }\n}\n```\n\n**Recommended workflow**: Use `cargo-fuzz` interactively to find deep bugs, then convert to `proptest` for regression prevention in CI.\n\n## Differential Testing with Test Snapshots\n\nSoroban automatically writes JSON snapshots at the end of every test to `test_snapshots\u002F`, capturing events and final ledger state. Commit these to source control - diffs reveal unintended behavioral changes.\n\n### Comparing Against Deployed Contracts\n\n```rust\n\u002F\u002F Fetch deployed contract for comparison\n\u002F\u002F $ stellar contract fetch --id C... --out-file deployed.wasm\n\nmod deployed {\n    soroban_sdk::contractimport!(file = \"deployed.wasm\");\n}\n\n#[test]\nfn test_upgrade_compatibility() {\n    let env = Env::default();\n    env.mock_all_auths();\n\n    \u002F\u002F Register both versions\n    let old_id = env.register(deployed::WASM, ());\n    let new_id = env.register(NewContract, ());\n\n    let old_client = deployed::Client::new(&env, &old_id);\n    let new_client = NewContractClient::new(&env, &new_id);\n\n    let user = Address::generate(&env);\n\n    \u002F\u002F Run identical operations and compare\n    old_client.initialize(&user);\n    new_client.initialize(&user);\n\n    assert_eq!(old_client.get_value(), new_client.get_value());\n}\n```\n\n- **Docs**: [Differential Tests with Test Snapshots](https:\u002F\u002Fdevelopers.stellar.org\u002Fdocs\u002Fbuild\u002Fguides\u002Ftesting\u002Fdifferential-tests-with-test-snapshots)\n\n## Fork Testing\n\nTest against real production state using ledger snapshots:\n\n```bash\n# Create snapshot of deployed contract\nstellar snapshot create --address C... --output json --out snapshot.json\n\n# Optionally at a specific ledger\nstellar snapshot create --address C... --ledger 12345678 --output json --out snapshot.json\n```\n\n```rust\n#[test]\nfn test_against_mainnet_state() {\n    let env = Env::from_ledger_snapshot_file(\"snapshot.json\");\n    env.mock_all_auths();\n\n    let contract_id = \u002F* contract address from snapshot *\u002F;\n    let client = ContractClient::new(&env, &contract_id);\n\n    \u002F\u002F Test operations against real state\n    let result = client.get_value();\n    assert!(result > 0);\n}\n```\n\n- **Docs**: [Fork Testing](https:\u002F\u002Fdevelopers.stellar.org\u002Fdocs\u002Fbuild\u002Fguides\u002Ftesting\u002Ffork-testing)\n\n## Mutation Testing\n\nUse `cargo-mutants` to verify test quality - modifies source code and checks that tests catch the changes.\n\n```bash\ncargo install --locked cargo-mutants\ncargo mutants\n```\n\n**Output interpretation**:\n- **CAUGHT**: Tests detected the mutation (good coverage)\n- **MISSED**: Tests passed despite mutation (test gap - review `mutants.out\u002Fdiff\u002F`)\n\n- **Docs**: [Mutation Testing](https:\u002F\u002Fdevelopers.stellar.org\u002Fdocs\u002Fbuild\u002Fguides\u002Ftesting\u002Fmutation-testing)\n\n## Resource Profiling\n\nSoroban uses a multidimensional resource model (CPU instructions, ledger reads\u002Fwrites, bytes, events, rent).\n\n### CLI Simulation\n\n```bash\n# Simulate contract invocation to see resource costs\nstellar contract invoke \\\n  --id CONTRACT_ID \\\n  --source alice \\\n  --network testnet \\\n  --sim-only \\\n  -- \\\n  function_name --arg value\n```\n\n### Stellar Plus Profiler (Cheesecake Labs)\n\n```typescript\nimport { StellarPlus } from 'stellar-plus';\n\nconst profilerPlugin = new StellarPlus.Utils.Plugins.sorobanTransaction.profiler();\n\u002F\u002F Collects CPU instructions, RAM, ledger reads\u002Fwrites\n\u002F\u002F Aggregation: sum, average, standard deviation\n\u002F\u002F Output: CSV, formatted text tables\n```\n\n- **Docs**: https:\u002F\u002Fdocs.cheesecakelabs.com\u002Fstellar-plus\u002Freference\u002Futils\u002Fplugins\u002Fprofiler-plugin\n\n### Testing Checklist\n\n- [ ] Unit tests cover all public functions\n- [ ] Edge cases tested (zero amounts, max values, empty state)\n- [ ] Authorization tested (correct signers required)\n- [ ] Error conditions tested (invalid inputs, unauthorized)\n- [ ] Events emission verified\n- [ ] Storage TTL behavior validated\n- [ ] Cross-contract interactions tested\n- [ ] Fuzz tests for critical paths (deposits, withdrawals, swaps)\n- [ ] Property-based tests for invariants\n- [ ] Mutation testing confirms test quality\n- [ ] Differential test snapshots committed to source control\n- [ ] Integration tests against local network\n- [ ] Testnet deployment verified before mainnet\n\n---\n\n# Part 3: Security\n\n\n## Core Principle\n\nAssume the attacker controls:\n- All arguments passed to contract functions\n- Transaction ordering and timing\n- All accounts except those requiring signatures\n- The ability to create contracts that mimic your interface\n\n## Soroban Security Advantages\n\nSoroban's architecture prevents certain vulnerability classes by design:\n\n### No Delegate Call\nUnlike Ethereum, Soroban has no `delegatecall` equivalent. Contracts cannot execute arbitrary bytecode in their context, eliminating proxy-based attacks.\n\n### No Classical Reentrancy\nSoroban's synchronous execution model prevents the cross-contract reentrancy that plagues Ethereum. Self-reentrancy is possible but rarely exploitable.\n\n### Explicit Authorization\nAuthorization is opt-in via `require_auth()`, making it explicit which operations need signatures.\n\n---\n\n## Vulnerability Categories\n\n### 1. Missing Authorization Checks\n\n**Risk**: Anyone can call privileged functions without proper verification.\n\n**Attack**: Attacker calls admin-only functions, drains funds, or modifies critical state.\n\n**Vulnerable Code**:\n```rust\n\u002F\u002F BAD: No authorization check\npub fn withdraw(env: Env, to: Address, amount: i128) {\n    transfer_tokens(&env, &to, amount);\n}\n```\n\n**Secure Code**:\n```rust\n\u002F\u002F GOOD: Requires authorization from admin\npub fn withdraw(env: Env, to: Address, amount: i128) {\n    let admin: Address = env.storage().instance().get(&DataKey::Admin).unwrap();\n    admin.require_auth();\n    transfer_tokens(&env, &to, amount);\n}\n```\n\n**Prevention**: Always use `require_auth()` on the caller or an admin address. See Part 1: Contract Development above for full authorization patterns (direct auth, admin helpers, `require_auth_for_args`).\n\n---\n\n### 2. Reinitialization Attacks\n\n**Risk**: Initialization function can be called multiple times, allowing attacker to overwrite admin or critical state.\n\n**Attack**: Attacker reinitializes contract to become the admin, then drains assets.\n\n**Vulnerable Code**:\n```rust\n\u002F\u002F BAD: Can be called multiple times\npub fn initialize(env: Env, admin: Address) {\n    env.storage().instance().set(&DataKey::Admin, &admin);\n}\n```\n\n**Secure Code**:\n```rust\n\u002F\u002F GOOD: Prevents reinitialization\npub fn initialize(env: Env, admin: Address) {\n    if env.storage().instance().has(&DataKey::Initialized) {\n        panic!(\"already initialized\");\n    }\n    env.storage().instance().set(&DataKey::Admin, &admin);\n    env.storage().instance().set(&DataKey::Initialized, &true);\n}\n\n\u002F\u002F Alternative: Check for admin existence\npub fn initialize(env: Env, admin: Address) {\n    if env.storage().instance().has(&DataKey::Admin) {\n        panic!(\"already initialized\");\n    }\n    env.storage().instance().set(&DataKey::Admin, &admin);\n}\n```\n\n---\n\n### 3. Arbitrary Contract Calls\n\n**Risk**: Contract calls whatever address is passed as parameter without validation.\n\n**Attack**: Attacker passes malicious contract that mimics expected interface but behaves differently.\n\n**Vulnerable Code**:\n```rust\n\u002F\u002F BAD: Calls any contract passed as parameter\npub fn swap(env: Env, token: Address, amount: i128) {\n    let client = token::Client::new(&env, &token);\n    client.transfer(...); \u002F\u002F Could be malicious contract\n}\n```\n\n**Secure Code**:\n```rust\n\u002F\u002F GOOD: Validate against known allowlist\npub fn swap(env: Env, token: Address, amount: i128) {\n    let allowed_tokens: Vec\u003CAddress> = env.storage()\n        .instance()\n        .get(&DataKey::AllowedTokens)\n        .unwrap();\n\n    if !allowed_tokens.contains(&token) {\n        panic!(\"token not allowed\");\n    }\n\n    let client = token::Client::new(&env, &token);\n    client.transfer(...);\n}\n\n\u002F\u002F Or validate against Stellar Asset Contract\npub fn swap_sac(env: Env, asset: Address, amount: i128) {\n    \u002F\u002F SACs have known, predictable addresses\n    \u002F\u002F Verify it's a legitimate SAC if needed\n}\n```\n\n---\n\n### 4. Integer Overflow\u002FUnderflow\n\n**Risk**: Arithmetic operations overflow or underflow, causing unexpected values.\n\n**Attack**: Attacker manipulates amounts to cause overflow, bypassing balance checks.\n\n**Vulnerable Code**:\n```rust\n\u002F\u002F BAD: Unchecked arithmetic\npub fn deposit(env: Env, user: Address, amount: i128) {\n    let balance: i128 = get_balance(&env, &user);\n    set_balance(&env, &user, balance + amount); \u002F\u002F Can overflow\n}\n```\n\n**Secure Code**:\n```rust\n\u002F\u002F GOOD: Use checked arithmetic\npub fn deposit(env: Env, user: Address, amount: i128) {\n    let balance: i128 = get_balance(&env, &user);\n    let new_balance = balance.checked_add(amount)\n        .expect(\"overflow\");\n    set_balance(&env, &user, new_balance);\n}\n\n\u002F\u002F Also validate inputs\npub fn deposit(env: Env, user: Address, amount: i128) {\n    if amount \u003C= 0 {\n        panic!(\"invalid amount\");\n    }\n    \u002F\u002F ... rest of logic\n}\n```\n\n---\n\n### 5. Storage Key Collisions\n\n**Risk**: Different data types share the same storage key, causing data corruption.\n\n**Attack**: Attacker manipulates one type of data to corrupt another.\n\n**Vulnerable Code**:\n```rust\n\u002F\u002F BAD: Same prefix for different data\nenv.storage().persistent().set(&symbol_short!(\"data\"), &user_balance);\nenv.storage().persistent().set(&symbol_short!(\"data\"), &config); \u002F\u002F Overwrites!\n```\n\n**Secure Code**:\n```rust\n\u002F\u002F GOOD: Use typed enum for keys\n#[contracttype]\n#[derive(Clone)]\npub enum DataKey {\n    Admin,\n    Balance(Address),\n    Config,\n    Allowance(Address, Address),\n}\n\nenv.storage().persistent().set(&DataKey::Balance(user), &balance);\nenv.storage().instance().set(&DataKey::Config, &config);\n```\n\n---\n\n### 6. Timing\u002FState Race Conditions\n\n**Risk**: Contract state changes between check and use.\n\n**Attack**: In multi-transaction scenarios, attacker exploits gap between validation and action.\n\n**Prevention**:\n```rust\n\u002F\u002F Use atomic operations where possible\npub fn swap(env: Env, user: Address, amount_in: i128, min_out: i128) {\n    user.require_auth();\n\n    \u002F\u002F Perform all checks and state changes atomically\n    let balance = get_balance(&env, &user);\n    if balance \u003C amount_in {\n        panic!(\"insufficient balance\");\n    }\n\n    let amount_out = calculate_output(amount_in);\n    if amount_out \u003C min_out {\n        panic!(\"slippage exceeded\");\n    }\n\n    \u002F\u002F Update all state together\n    set_balance(&env, &user, balance - amount_in);\n    transfer_output(&env, &user, amount_out);\n}\n```\n\n---\n\n### 7. TTL\u002FArchival Vulnerabilities\n\n**Risk**: Critical contract data gets archived, breaking functionality.\n\n**Attack**: Attacker waits for data to be archived, then exploits the missing state.\n\n**Prevention**:\n```rust\n\u002F\u002F Extend TTL for critical data\npub fn critical_operation(env: Env) {\n    \u002F\u002F Always extend instance storage\n    env.storage().instance().extend_ttl(\n        100,      \u002F\u002F threshold\n        518400,   \u002F\u002F extend_to (~30 days)\n    );\n\n    \u002F\u002F Extend specific persistent keys\n    env.storage().persistent().extend_ttl(\n        &DataKey::CriticalData,\n        100,\n        518400,\n    );\n}\n\n\u002F\u002F Consider restoration costs in design\n\u002F\u002F Archived data can be restored, but requires transaction\n```\n\n---\n\n### 8. Cross-Contract Call Validation\n\n**Risk**: Trusting return values from untrusted contracts.\n\n**Attack**: Malicious contract returns false data, causing incorrect state updates.\n\n**Prevention**:\n```rust\n\u002F\u002F Validate all external data\npub fn process_oracle_price(env: Env, oracle: Address, asset: Address) -> i128 {\n    \u002F\u002F Validate oracle is trusted\n    let trusted_oracles: Vec\u003CAddress> = env.storage()\n        .instance()\n        .get(&DataKey::TrustedOracles)\n        .unwrap();\n\n    if !trusted_oracles.contains(&oracle) {\n        panic!(\"untrusted oracle\");\n    }\n\n    let price: i128 = oracle_client.get_price(&asset);\n\n    \u002F\u002F Sanity check the value\n    if price \u003C= 0 || price > MAX_REASONABLE_PRICE {\n        panic!(\"invalid price\");\n    }\n\n    price\n}\n```\n\n---\n\n## Classic Stellar Security\n\n### Trustline Attacks\n\n**Risk**: Users create trustlines to malicious assets that look legitimate.\n\n**Prevention**:\n- Verify asset issuer before creating trustlines\n- Use well-known asset lists (stellar.toml)\n- Display full asset code + issuer in UIs\n\n### Clawback Awareness\n\n**Risk**: Assets with clawback enabled can be seized by issuer.\n\n**Prevention**:\n```typescript\n\u002F\u002F Check if clawback is enabled\nconst issuerAccount = await server.loadAccount(asset.issuer);\nconst clawbackEnabled = issuerAccount.flags.auth_clawback_enabled;\n\nif (clawbackEnabled) {\n  \u002F\u002F Warn user or reject asset\n}\n```\n\n### Account Merge Attacks\n\n**Risk**: Merged accounts can be recreated with different configuration.\n\n**Prevention**:\n- Validate account state before critical operations\n- Don't cache account data long-term\n\n---\n\n## Soroban-Specific Checklist\n\n### Contract Development\n- [ ] All privileged functions require appropriate authorization\n- [ ] Initialization can only happen once\n- [ ] External contract calls are validated against allowlists\n- [ ] All arithmetic uses checked operations\n- [ ] Storage keys are typed and collision-free\n- [ ] Critical data TTLs are extended proactively\n- [ ] Input validation on all public functions\n- [ ] Events emitted for auditable state changes\n\n### Storage Security\n- [ ] Sensitive data uses appropriate storage type\n- [ ] Instance storage for shared\u002Fadmin data\n- [ ] Persistent storage for user-specific data\n- [ ] Temporary storage only for truly temporary data\n- [ ] TTL management strategy documented\n\n### Cross-Contract Calls\n- [ ] Called contracts are validated or allowlisted\n- [ ] Return values are sanity-checked\n- [ ] Failure cases handled gracefully\n- [ ] No excessive trust in external state\n\n---\n\n## Client-Side Checklist\n\n- [ ] Network passphrase validated before signing\n- [ ] Transaction simulation before submission\n- [ ] Clear display of all operation details\n- [ ] Confirmation for high-value transactions\n- [ ] Handle all error states gracefully\n- [ ] Don't trust client-side validation alone\n- [ ] Verify contract addresses against known deployments\n- [ ] Check asset trustline status before transfers\n\n---\n\n## Security Review Questions\n\n1. Can anyone call admin functions without authorization?\n2. Can the contract be reinitialized?\n3. Are all external contract calls validated?\n4. Is arithmetic safe from overflow\u002Funderflow?\n5. Can storage keys collide?\n6. Will critical data survive archival?\n7. Are cross-contract return values validated?\n8. Can timing attacks exploit state changes?\n\n---\n\n## Bug Bounty Programs\n\n### Immunefi - Stellar Core (up to $250K)\n- **URL**: https:\u002F\u002Fimmunefi.com\u002Fbug-bounty\u002Fstellar\u002F\n- **Scope**: stellar-core, rs-soroban-sdk, rs-soroban-env, soroban-tools (CLI + RPC), js-soroban-client, rs-stellar-xdr, wasmi fork\n- **Rewards**: Critical $50K–$250K, High $10K–$50K, Medium $5K, Low $1K\n- **Payment**: USD-denominated, paid in XLM. KYC required.\n- **Rules**: PoC required. Test on local forks only (no mainnet\u002Ftestnet).\n\n### Immunefi - OpenZeppelin on Stellar (up to $25K)\n- **URL**: https:\u002F\u002Fimmunefi.com\u002Fbug-bounty\u002Fopenzeppelin-stellar\u002F\n- **Scope**: OpenZeppelin Stellar Contracts library\n- **Max payout**: $25K per bug, $250K total program cap\n\n### HackerOne - Web Applications\n- **URL**: https:\u002F\u002Fstellar.org\u002Fgrants-and-funding\u002Fbug-bounty\n- **Scope**: SDF web applications, production servers, domains\n- **Disclosure**: 90-day remediation window before public disclosure\n\n## Soroban Audit Bank\n\nSDF's proactive security program with **$3M+ deployed across 43+ audits**.\n\n- **URL**: https:\u002F\u002Fstellar.org\u002Fgrants-and-funding\u002Fsoroban-audit-bank\n- **Projects list**: https:\u002F\u002Fstellar.org\u002Faudit-bank\u002Fprojects\n- **Eligibility**: SCF-funded projects (financial protocols, infrastructure, high-traction dApps)\n- **Co-payment**: 5% upfront (refundable if Critical\u002FHigh\u002FMedium issues remediated within 20 business days)\n- **Follow-up audits**: Triggered at $10M and $100M TVL milestones (includes formal verification and competitive audits)\n- **Preparation**: STRIDE threat modeling framework + Audit Readiness Checklist\n\n### Partner Audit Firms\n\n| Firm | Specialty |\n|------|-----------|\n| **OtterSec** | Smart contract audits |\n| **Veridise** | Tool-assisted audits, [security checklist](https:\u002F\u002Fveridise.com\u002Fblog\u002Faudit-insights\u002Fbuilding-on-stellar-soroban-grab-this-security-checklist-to-avoid-vulnerabilities\u002F) |\n| **Runtime Verification** | Formal methods, [Komet tool](https:\u002F\u002Fruntimeverification.com\u002Fblog\u002Fintroducing-komet-smart-contract-testing-and-verification-tool-for-soroban-created-by-runtime-verification) |\n| **CoinFabrik** | Static analysis (Scout), manual audits |\n| **QuarksLab** | Security research |\n| **Coinspect** | Security audits |\n| **Certora** | Formal verification ([Sunbeam Prover](https:\u002F\u002Fdocs.certora.com\u002Fen\u002Flatest\u002Fdocs\u002Fsunbeam\u002Findex.html)) |\n| **Halborn** | Security assessments |\n| **Zellic** | Blockchain + cryptography research |\n| **Code4rena** | Competitive audit platform |\n\n## Security Tooling\n\n### Static Analysis\n\n#### Scout Soroban (CoinFabrik)\nOpen-source vulnerability detector with 23 detectors (critical through enhancement severity).\n- **GitHub**: https:\u002F\u002Fgithub.com\u002FCoinFabrik\u002Fscout-soroban\n- **Install**: `cargo install cargo-scout-audit` → `cargo scout-audit`\n- **Output formats**: HTML, Markdown, JSON, PDF, SARIF (CI\u002FCD integration)\n- **VSCode extension**: [Scout Audit](https:\u002F\u002Fmarketplace.visualstudio.com\u002Fitems?itemName=CoinFabrik.scout-audit)\n- **Key detectors**: `overflow-check`, `unprotected-update-current-contract-wasm`, `set-contract-storage`, `unrestricted-transfer-from`, `divide-before-multiply`, `dos-unbounded-operation`, `unsafe-unwrap`\n\n#### OpenZeppelin Security Detectors SDK\nFramework for building custom security detectors for Soroban.\n- **GitHub**: https:\u002F\u002Fgithub.com\u002FOpenZeppelin\u002Fsoroban-security-detectors-sdk\n- **Architecture**: `sdk` (core), `detectors` (pre-built), `soroban-scanner` (CLI)\n- **Pre-built detectors**: `auth_missing`, `unchecked_ft_transfer`, improper TTL extension, contract panics, unsafe temporary storage\n- **Extensible**: Load external detector libraries as shared objects\n\n### Formal Verification\n\n#### Certora Sunbeam Prover\nPurpose-built formal verification for Soroban - first WASM platform supported by Certora.\n- **Docs**: https:\u002F\u002Fdocs.certora.com\u002Fen\u002Flatest\u002Fdocs\u002Fsunbeam\u002Findex.html\n- **Spec language**: CVLR (Certora Verification Language for Rust) - Rust macros (`cvlr_assert!`, `cvlr_assume!`, `cvlr_satisfy!`)\n- **Operates at**: WASM bytecode level (eliminates compiler trust assumptions)\n- **Reports**: https:\u002F\u002Fgithub.com\u002FCertora\u002FSecurityReports\n- **Example**: [Blend V1 verification report](https:\u002F\u002Fwww.certora.com\u002Freports\u002Fblend-smart-contract-verification-report)\n\n#### Runtime Verification - Komet\nFormal verification and testing tool built specifically for Soroban (SCF-funded).\n- **Docs**: https:\u002F\u002Fdocs.runtimeverification.com\u002Fkomet\n- **Repo**: https:\u002F\u002Fgithub.com\u002Fruntimeverification\u002Fkomet\n- **Spec language**: Rust - property-based tests written in the same language as Soroban contracts\n- **Operates at**: WASM bytecode level via [KWasm semantics](https:\u002F\u002Fgithub.com\u002Fruntimeverification\u002Fwasm-semantics) (eliminates compiler trust assumptions)\n- **Features**: Fuzzing, testing, formal verification\n- **Reports**: [RV publications](https:\u002F\u002Fgithub.com\u002Fruntimeverification\u002Fpublications)\n- **Example**: [TokenOps audit and verification report](https:\u002F\u002Fgithub.com\u002Fruntimeverification\u002Fpublications\u002Fblob\u002Fmain\u002Freports\u002Fsmart-contracts\u002FTokenOps.pdf)\n- **Blog**: [Introducing Komet](https:\u002F\u002Fruntimeverification.com\u002Fblog\u002Fintroducing-komet-smart-contract-testing-and-verification-tool-for-soroban-created-by-runtime-verification)\n\n### Security Knowledge Base\n\n#### Soroban Security Portal\nCommunity security knowledge base by Inferara (SCF-funded).\n- **URL**: https:\u002F\u002Fsorobansecurity.com\n- **Features**: Searchable audit reports, vulnerability database, best practices\n\n### Security Monitoring (Post-Deployment)\n\n#### OpenZeppelin Monitor (Stellar alpha)\nOpen-source contract monitoring with Stellar support.\n- **Features**: Self-hosted via Docker, Prometheus + Grafana observability\n- **Source**: https:\u002F\u002Fwww.openzeppelin.com\u002Fnews\u002Fmonitor-and-relayers-are-now-open-source\n\n## OpenZeppelin Partnership Overview\n\nStrategic partnership highlights include:\n- **40 Auditor Weeks** of dedicated security audits\n- **Stellar Contracts library** (audited, production-ready)\n- **Relayer** (fee-sponsored transactions, Stellar-native)\n- **Monitor** (contract monitoring, Stellar alpha)\n- **Security Detectors SDK** (static analysis framework)\n- **SEP authorship**: SEP-0049 (Upgradeable Contracts), SEP-0050 (NFTs)\n- **Blog**: https:\u002F\u002Fstellar.org\u002Fblog\u002Ffoundation-news\u002Fsdf-partners-with-openzeppelin-to-enhance-stellar-smart-contract-development\n\n---\n\n# Part 4: Advanced Patterns\n\n\n## When to use this guide\nUse this guide for higher-complexity contract architecture:\n- Upgrades and migrations\n- Factory\u002Fdeployer systems\n- Governance and timelocks\n- DeFi primitives (vaults, pools, oracles)\n- Regulated token\u002Fcompliance workflows\n- Resource and storage optimization\n\nFor core contract syntax and day-to-day patterns, refer to the earlier sections in this guide covering contract structure, storage, authorization, cross-contract calls, events, error handling, and testing.\n\n## Design principles\n- Prefer simple state machines over implicit behavior.\n- Minimize privileged entrypoints and protect all privileged actions with explicit auth.\n- Keep upgrades predictable: version metadata + migration plan + rollback strategy.\n- Use idempotent migrations and fail fast on incompatible versions.\n- Separate protocol\u002Fbusiness logic from governance\u002Fadmin logic when possible.\n\n## Upgradeability patterns\n\n### 1) Explicit upgrade policy\n- Decide early whether the contract is mutable or immutable.\n- If mutable, implement an `upgrade` entrypoint guarded by admin or governance.\n- If immutable, do not expose upgrade capability.\n\n### 2) Version tracking\nTrack both runtime and code version:\n- Contract metadata (`contractmeta!`) for binary version\n- Storage key for migration\u002Fapplication version\n\n```rust\n#![no_std]\nuse soroban_sdk::{contract, contractimpl, contractmeta, contracttype, Address, BytesN, Env};\n\ncontractmeta!(key = \"binver\", val = \"1.0.0\");\n\n#[contracttype]\n#[derive(Clone)]\npub enum DataKey {\n    Admin,\n    AppVersion,\n}\n\n#[contract]\npub struct Upgradeable;\n\n#[contractimpl]\nimpl Upgradeable {\n    pub fn __constructor(env: Env, admin: Address) {\n        env.storage().instance().set(&DataKey::Admin, &admin);\n        env.storage().instance().set(&DataKey::AppVersion, &1u32);\n    }\n\n    pub fn upgrade(env: Env, new_wasm_hash: BytesN\u003C32>) {\n        let admin: Address = env.storage().instance().get(&DataKey::Admin).unwrap();\n        admin.require_auth();\n        env.deployer().update_current_contract_wasm(new_wasm_hash);\n    }\n}\n```\n\n### 3) Migration entrypoint\n- Add a dedicated `migrate` function after upgrades.\n- Ensure migration is monotonic (`new_version > current_version`).\n- Treat migrations as one-way and idempotent.\n\n## Factory and deployment patterns\n\n### Factory contract responsibilities\n- Authorize who can deploy instances.\n- Derive deterministic addresses with salts when needed.\n- Emit events for deployments (indexing\u002Fops observability).\n- Keep deployment logic separate from instance business logic.\n\n```rust\n#![no_std]\nuse soroban_sdk::{contract, contractimpl, Address, BytesN, Env, Val, Vec};\n\n#[contract]\npub struct Factory;\n\n#[contractimpl]\nimpl Factory {\n    pub fn deploy(\n        env: Env,\n        owner: Address,\n        wasm_hash: BytesN\u003C32>,\n        salt: BytesN\u003C32>,\n        constructor_args: Vec\u003CVal>,\n    ) -> Address {\n        owner.require_auth();\n        env.deployer()\n            .with_address(env.current_contract_address(), salt)\n            .deploy_v2(wasm_hash, constructor_args)\n    }\n}\n```\n\nOperational note:\n- Keep a registry (or emit canonical deployment events) to avoid orphaned instances.\n\n## Governance patterns\n\n### Timelock for sensitive actions\nUse a timelock for upgrades and major config changes:\n- `propose_*` stores pending action + execute ledger\n- `execute_*` enforces delay\n- `cancel_*` allows governance abort\n\n### Multisig and role separation\n- Separate roles: proposer, approver, executor.\n- Define threshold and signer rotation process.\n- Record proposal state in persistent storage and prevent replay.\n\nChecklist:\n- Proposal uniqueness and replay protection\n- Expiry semantics\n- Clear cancellation path\n- Explicit event emission\n\n## DeFi primitives\n\n### Vaults\n- Track `total_assets` and `total_shares` with careful rounding rules.\n- Use conservative math for mint\u002Fredeem conversions.\n- Enforce pause\u002Femergency controls for admin-level intervention.\n\n### Pools\u002FAMMs\n- Define invariant and fee accounting precisely.\n- Protect against stale pricing and manipulation.\n- Include slippage checks on all user-facing swaps.\n\n### Oracle integration\n- Require freshness constraints (ledger\u002Ftime bounds).\n- Prefer median\u002Fmulti-source feeds for critical operations.\n- Add circuit breakers for extreme price movement.\n\n## Compliance-oriented token design\n\nCommon regulated features:\n- Allowlist\u002Fdenylist checks before transfer\n- Jurisdiction or investor-class restrictions\n- Forced transfer\u002Ffreeze authority with auditable governance\n- Off-chain identity references (never store sensitive PII directly)\n\nImplementation guidance:\n- Keep compliance policy in dedicated modules\u002Fentrypoints.\n- Emit policy decision events for traceability.\n- Treat privileged compliance actions as high-risk operations requiring strong auth.\n\n## Resource optimization\n\n### Storage\n- Use `instance` for global config.\n- Use `persistent` for critical user state.\n- Use `temporary` only for disposable data.\n- Extend TTL strategically, not on every call.\n\n### Compute\n- Avoid unbounded loops over user-controlled collections.\n- Prefer bounded batch operations.\n- Reduce cross-contract calls in hot paths.\n\n### Contract size\n- Keep release profile optimized (`opt-level = \"z\"`, `lto = true`, `panic = \"abort\"`).\n- Split concerns across contracts when near Wasm size limits.\n\n## Security review checklist for advanced architectures\n- Access control is explicit on every privileged path.\n- Upgrade and migration are both tested (happy path + failure path).\n- Timelock and governance logic is replay-safe.\n- External dependency assumptions are documented.\n- Emergency controls and incident runbooks are defined.\n- Events cover operationally important transitions.\n\n## Testing strategy for advanced patterns\n- Unit tests for role checks, invariants, and edge-case math.\n- Integration tests for multi-step governance flows.\n- Upgrade tests from old state snapshots to new versions.\n- Negative tests for unauthorized and malformed calls.\n\n---\n\n# Part 5: Common Pitfalls\n\n\n## Soroban Contract Issues\n\n### 1. Contract Size Exceeds 64KB Limit\n\n**Problem**: Contract won't deploy because WASM exceeds size limit.\n\n**Symptoms**:\n```\nError: contract exceeds maximum size\n```\n\n**Solutions**:\n\n```toml\n# Cargo.toml - Use aggressive optimization\n[profile.release]\nopt-level = \"z\"           # Optimize for size\nlto = true                # Link-time optimization\ncodegen-units = 1         # Single codegen unit\npanic = \"abort\"           # Smaller panic handling\nstrip = \"symbols\"         # Remove symbols\n```\n\nAdditional strategies:\n- Split large contracts into multiple smaller contracts\n- Use `symbol_short!()` for symbols under 9 chars\n- Avoid large static data in contract\n- Remove debug code and unused functions\n- Use `cargo bloat` to identify large dependencies\n\n```bash\n# Check contract size\nls -la target\u002Fwasm32-unknown-unknown\u002Frelease\u002F*.wasm\n\n# Analyze what's taking space\ncargo install cargo-bloat\ncargo bloat --release --target wasm32-unknown-unknown\n```\n\n---\n\n### 2. `#![no_std]` Missing\n\n**Problem**: Compilation fails with std library errors.\n\n**Symptoms**:\n```\nerror: cannot find macro `println` in this scope\nerror[E0433]: failed to resolve: use of undeclared crate or module `std`\n```\n\n**Solution**:\n```rust\n\u002F\u002F MUST be first line of lib.rs\n#![no_std]\n\nuse soroban_sdk::{contract, contractimpl, Env};\n\n\u002F\u002F Use soroban_sdk equivalents instead of std:\n\u002F\u002F - soroban_sdk::String instead of std::string::String\n\u002F\u002F - soroban_sdk::Vec instead of std::vec::Vec\n\u002F\u002F - soroban_sdk::Map instead of std::collections::HashMap\n```\n\n---\n\n### 3. Storage TTL Not Extended\n\n**Problem**: Contract data gets archived and becomes inaccessible.\n\n**Symptoms**:\n- Contract calls fail after period of inactivity\n- Data appears missing but contract still exists\n\n**Solution**:\n```rust\n\u002F\u002F Proactively extend TTL in operations that use data\npub fn use_data(env: Env) {\n    \u002F\u002F Extend instance storage\n    env.storage().instance().extend_ttl(\n        50,      \u002F\u002F If TTL \u003C 50, extend\n        518400,  \u002F\u002F Extend to ~30 days\n    );\n\n    \u002F\u002F Extend specific persistent keys\n    env.storage().persistent().extend_ttl(\n        &DataKey::ImportantData,\n        50,\n        518400,\n    );\n\n    \u002F\u002F Now use the data...\n}\n```\n\n> See Part 1: Contract Development above for full TTL management patterns and storage type guidance.\n\n---\n\n### 4. Wrong Storage Type\n\n**Problem**: Data unexpectedly deleted or costs too high.\n\n**Symptoms**:\n- Temporary data deleted before expected\n- Unexpectedly high fees for storage\n\n**Solution**:\n```rust\n\u002F\u002F Instance: Shared config, survives with contract\nenv.storage().instance().set(&DataKey::Admin, &admin);\n\n\u002F\u002F Persistent: User data, can be archived but restored\nenv.storage().persistent().set(&DataKey::Balance(user), &balance);\n\n\u002F\u002F Temporary: Truly temporary, auto-deleted, cheapest\nenv.storage().temporary().set(&DataKey::Cache(key), &value);\n```\n\n---\n\n### 5. Authorization Not Working\n\n**Problem**: `require_auth()` not enforcing signatures in tests.\n\n**Symptoms**:\n- Tests pass but transactions fail on network\n- Anyone can call protected functions\n\n**Solution**:\n```rust\n#[test]\nfn test_auth() {\n    let env = Env::default();\n\n    \u002F\u002F DON'T just mock all auths blindly\n    \u002F\u002F env.mock_all_auths();  \u002F\u002F Be careful with this!\n\n    \u002F\u002F DO test specific auth requirements with mock_auths()\n    env.mock_auths(&[MockAuth {\n        address: &user,\n        invoke: &MockAuthInvoke {\n            contract: &contract_id,\n            fn_name: \"transfer\",\n            args: (&user, &other, &100i128).into_val(&env),\n            sub_invokes: &[],\n        },\n    }]);\n\n    client.transfer(&user, &other, &100);\n    assert!(!env.auths().is_empty());\n}\n```\n\n> See Part 2: Testing Strategy above for comprehensive auth testing patterns including `mock_all_auths()`, specific auth mocking, and cross-contract auth.\n\n---\n\n## SDK Issues\n\n### 6. Network Passphrase Mismatch\n\n**Problem**: Transactions fail with signature errors.\n\n**Symptoms**:\n```\nError: tx_bad_auth\n```\n\n**Solution**:\n```typescript\nimport * as StellarSdk from \"@stellar\u002Fstellar-sdk\";\n\n\u002F\u002F ALWAYS use correct passphrase for network\nconst PASSPHRASES = {\n  mainnet: StellarSdk.Networks.PUBLIC,\n  \u002F\u002F \"Public Global Stellar Network ; September 2015\"\n\n  testnet: StellarSdk.Networks.TESTNET,\n  \u002F\u002F \"Test SDF Network ; September 2015\"\n\n  local: \"Standalone Network ; February 2017\",\n};\n\n\u002F\u002F When building transactions\nconst tx = new StellarSdk.TransactionBuilder(account, {\n  fee: StellarSdk.BASE_FEE,\n  networkPassphrase: PASSPHRASES.testnet, \u002F\u002F Match your network!\n});\n```\n\n---\n\n### 7. Account Not Funded\n\n**Problem**: Operations fail because account doesn't exist.\n\n**Symptoms**:\n```\nError: Account not found\nStatus: 404\n```\n\n**Solution**:\n```typescript\n\u002F\u002F Testnet - use Friendbot\nawait fetch(`https:\u002F\u002Ffriendbot.stellar.org?addr=${publicKey}`);\n\n\u002F\u002F Mainnet - must receive XLM from existing account\nconst tx = new StellarSdk.TransactionBuilder(funderAccount, {\n  fee: StellarSdk.BASE_FEE,\n  networkPassphrase: StellarSdk.Networks.PUBLIC,\n})\n  .addOperation(\n    StellarSdk.Operation.createAccount({\n      destination: newAccountPublicKey,\n      startingBalance: \"2\", \u002F\u002F Minimum ~1 XLM for base reserve\n    })\n  )\n  .setTimeout(180)\n  .build();\n```\n\n---\n\n### 8. Missing Trustline\n\n**Problem**: Payment fails for non-native assets.\n\n**Symptoms**:\n```\nError: op_no_trust\n```\n\n**Solution**:\n```typescript\n\u002F\u002F Check if trustline exists\nconst account = await server.loadAccount(destination);\nconst hasTrustline = account.balances.some(\n  (b) =>\n    b.asset_type !== \"native\" &&\n    b.asset_code === asset.code &&\n    b.asset_issuer === asset.issuer\n);\n\nif (!hasTrustline) {\n  \u002F\u002F Create trustline first\n  const trustTx = new StellarSdk.TransactionBuilder(destAccount, {\n    fee: StellarSdk.BASE_FEE,\n    networkPassphrase,\n  })\n    .addOperation(StellarSdk.Operation.changeTrust({ asset }))\n    .setTimeout(180)\n    .build();\n  \u002F\u002F Sign and submit...\n}\n```\n\n---\n\n### 9. Sequence Number Issues\n\n**Problem**: Transaction rejected for sequence number.\n\n**Symptoms**:\n```\nError: tx_bad_seq\n```\n\n**Causes & Solutions**:\n\n```typescript\n\u002F\u002F Cause 1: Stale account data\n\u002F\u002F Solution: Always load fresh account before building tx\nconst account = await server.loadAccount(publicKey);\n\n\u002F\u002F Cause 2: Parallel transactions\n\u002F\u002F Solution: Use sequence number management\nclass SequenceManager {\n  private sequence: bigint;\n\n  async getNext(server: Horizon.Server, publicKey: string) {\n    if (!this.sequence) {\n      const account = await server.loadAccount(publicKey);\n      this.sequence = BigInt(account.sequence);\n    }\n    this.sequence++;\n    return this.sequence.toString();\n  }\n}\n\n\u002F\u002F Cause 3: Transaction timeout without resubmit\n\u002F\u002F Solution: Rebuild with fresh sequence on timeout\n```\n\n---\n\n### 10. Soroban Transaction Not Simulated\n\n**Problem**: Soroban transaction fails with resource errors.\n\n**Symptoms**:\n```\nError: transaction simulation failed\nError: insufficient resources\n```\n\n**Solution**:\n```typescript\n\u002F\u002F ALWAYS simulate before submitting Soroban transactions\nconst simulation = await rpc.simulateTransaction(transaction);\n\nif (StellarSdk.rpc.Api.isSimulationError(simulation)) {\n  throw new Error(`Simulation failed: ${simulation.error}`);\n}\n\n\u002F\u002F Use assembleTransaction to add correct resources\nconst preparedTx = StellarSdk.rpc.assembleTransaction(\n  transaction,\n  simulation\n).build();\n\n\u002F\u002F Now sign and submit preparedTx, not original transaction\n```\n\n---\n\n## Frontend Issues\n\n### 11. Freighter Not Detected\n\n**Problem**: Wallet connection fails silently.\n\n**Symptoms**:\n- `isConnected()` returns false\n- No wallet prompt appears\n\n**Solution**:\n```typescript\nimport { isConnected, isAllowed, requestAccess } from \"@stellar\u002Ffreighter-api\";\n\nasync function checkFreighter() {\n  \u002F\u002F Check if extension is installed\n  const { isConnected: installed, error } = await isConnected();\n  if (error || !installed) {\n    \u002F\u002F Prompt user to install\n    window.open(\"https:\u002F\u002Ffreighter.app\", \"_blank\");\n    return;\n  }\n\n  \u002F\u002F Check if this app is already authorized\n  const { isAllowed: granted } = await isAllowed();\n  if (!granted) {\n    \u002F\u002F requestAccess prompts the user and returns { address, error }\n    const { error: accessError } = await requestAccess();\n    if (accessError) throw new Error(accessError.message);\n  }\n}\n```\n\n---\n\n### 12. Network Mismatch with Wallet\n\n**Problem**: Wallet on different network than app.\n\n**Symptoms**:\n- Transactions fail unexpectedly\n- Wrong balances displayed\n\n**Solution**:\n```typescript\nimport { getNetwork } from \"@stellar\u002Ffreighter-api\";\n\nasync function validateNetwork() {\n  const { network: walletNetwork, error } = await getNetwork();\n  if (error) throw new Error(error.message);\n  const appNetwork = process.env.NEXT_PUBLIC_STELLAR_NETWORK;\n\n  if (walletNetwork !== appNetwork) {\n    throw new Error(\n      `Please switch Freighter to ${appNetwork}. Currently on ${walletNetwork}`\n    );\n  }\n}\n```\n\n---\n\n### 13. Transaction Timeout\n\n**Problem**: Transaction expires before confirmation.\n\n**Symptoms**:\n```\nError: tx_too_late\n```\n\n**Solution**:\n```typescript\n\u002F\u002F Set appropriate timeout based on expected confirmation time\nconst tx = new StellarSdk.TransactionBuilder(account, {\n  fee: StellarSdk.BASE_FEE,\n  networkPassphrase,\n})\n  .addOperation(\u002F* ... *\u002F)\n  .setTimeout(180) \u002F\u002F 3 minutes - adjust as needed\n  .build();\n\n\u002F\u002F Handle timeout gracefully\nasync function submitWithRetry(signedXdr: string) {\n  try {\n    return await submitTransaction(signedXdr);\n  } catch (error) {\n    if (error.response?.data?.extras?.result_codes?.transaction === \"tx_too_late\") {\n      \u002F\u002F Rebuild with fresh blockhash and retry\n      const newTx = await rebuildTransaction(signedXdr);\n      return await submitTransaction(newTx);\n    }\n    throw error;\n  }\n}\n```\n\n---\n\n## CLI Issues\n\n### 14. Identity Not Found\n\n**Problem**: Stellar CLI can't find saved identity.\n\n**Symptoms**:\n```\nError: identity \"alice\" not found\n```\n\n**Solution**:\n```bash\n# List existing identities\nstellar keys list\n\n# Generate new identity\nstellar keys generate --global alice\n\n# For testnet with funding\nstellar keys generate --global alice --network testnet --fund\n\n# Specify identity location\nstellar keys generate alice --config-dir \u002Fcustom\u002Fpath\n```\n\n---\n\n### 15. Contract Invoke Parsing Errors\n\n**Problem**: CLI can't parse function arguments.\n\n**Symptoms**:\n```\nError: invalid argument format\n```\n\n**Solution**:\n```bash\n# Use correct argument syntax\n# Addresses: just the G... or C... string\nstellar contract invoke \\\n  --id CONTRACT_ID \\\n  --source alice \\\n  --network testnet \\\n  -- \\\n  transfer \\\n  --from GABC... \\\n  --to GDEF... \\\n  --amount 1000\n\n# Complex types: use JSON\nstellar contract invoke \\\n  --id CONTRACT_ID \\\n  -- \\\n  complex_fn \\\n  --data '{\"field1\": \"value\", \"field2\": 123}'\n```\n\n---\n\n## General Best Practices\n\n### Debugging Checklist\n\n1. **Check network**: Is wallet\u002FCLI on correct network?\n2. **Check account**: Is source account funded?\n3. **Check sequence**: Is sequence number current?\n4. **Check simulation**: Did Soroban tx simulate successfully?\n5. **Check trustlines**: For asset transfers, do trustlines exist?\n6. **Check TTL**: For contract data, is TTL sufficient?\n7. **Check authorization**: Is correct account signing?\n8. **Check logs**: What does the error message actually say?\n\n### Error Code Reference\n\n| Code | Meaning | Common Fix |\n|------|---------|------------|\n| `tx_bad_auth` | Signature invalid | Check network passphrase |\n| `tx_bad_seq` | Wrong sequence | Reload account |\n| `tx_too_late` | Transaction expired | Rebuild and resubmit |\n| `op_no_trust` | Missing trustline | Create trustline first |\n| `op_underfunded` | Insufficient balance | Add funds |\n| `op_low_reserve` | Below minimum balance | Maintain reserve |\n",{"name":5,"metadata":24,"description":7},{"argument-hint":25,"user-invocable":26},"[contract task]","true","main","db2f47e2b79822ad3d8dd0f17489d5d15bcba96d",".agents\u002Fskills\u002Fsoroban",3,"https:\u002F\u002Fgithub.com\u002FWritzProtocol\u002Fwritz","https:\u002F\u002Fwritz.xyz","https:\u002F\u002Fgithub.com\u002FWritzProtocol","https:\u002F\u002Fwritz.xyz\u002F","Native Bitcoin lending on Stellar. No bridge, no custodian.","2026-11-14 18:13:11",{"source":8,"skillName":5,"commands":38,"prompt":48,"zipAvailable":49},[39,42,45],{"tool":40,"command":41},"npx","npx skills add WritzProtocol\u002Fwritz --skill soroban",{"tool":43,"command":44},"bunx","bunx skills add WritzProtocol\u002Fwritz --skill soroban",{"tool":46,"command":47},"pnpm","pnpm dlx skills add WritzProtocol\u002Fwritz --skill soroban","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FWritzProtocol\u002Fwritz\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fsoroban\u002FSKILL.md",true,[],[52,59,66,73,80,87],{"skillNo":53,"name":54,"nameZh":6,"description":55,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":56,"categories":57,"keywords":58,"publishedAt":19},"01M77KKJ6DYZP10BJ74CW4H0AE","zk-proofs","Zero-knowledge proofs and privacy patterns on Stellar. Covers Groth16 verification in smart contracts via BLS12-381 host functions (CAP-0059, available), the BN254 + Poseidon proposals (CAP-0074\u002F0075, status-sensitive), and concrete toolchain walkthroughs for Circom (on-chain verifiable today), Noir, and RISC Zero (attestation pattern until BN254 lands). Use when building privacy-preserving applications, ZK-verifier contracts, or wiring a proving toolchain to Stellar.","https:\u002F\u002Fgithub.com\u002FWritzProtocol\u002Fwritz\u002Fblob\u002Fmain\u002F.codex\u002Fskills\u002Fzk-proofs\u002FSKILL.md",[],[],{"skillNo":60,"name":61,"nameZh":6,"description":62,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":63,"categories":64,"keywords":65,"publishedAt":19},"01M77KKF3SK8JVBGRY4A89HYQC","tyler-architect","System architect and technical design leader. Use when the user asks to talk to Tyler or requests the architect.","https:\u002F\u002Fgithub.com\u002FWritzProtocol\u002Fwritz\u002Fblob\u002Fmain\u002F.codex\u002Fskills\u002Ftyler-architect\u002FSKILL.md",[],[],{"skillNo":67,"name":68,"nameZh":6,"description":69,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":70,"categories":71,"keywords":72,"publishedAt":19},"01M77KKCD584VQA1TM1F9Q8JBH","stellar-help","Analyzes current state and user query to answer BMad questions or recommend the next skill(s) to use. Use when user asks for help, bmad help, what to do next, or what to start with in BMad.","https:\u002F\u002Fgithub.com\u002FWritzProtocol\u002Fwritz\u002Fblob\u002Fmain\u002F.codex\u002Fskills\u002Fstellar-help\u002FSKILL.md",[],[],{"skillNo":74,"name":75,"nameZh":6,"description":76,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":19},"01M77KK7W2HKQ3QMAG0KJY1BHH","stellar-competitive-landscape","Map the competitive landscape for a Stellar project idea. Use when a user says \"who are my competitors on Stellar\", \"competitive analysis Stellar\", \"what already exists in this space on Stellar\", \"show me similar Stellar projects\", \"is anyone else building this on Stellar\", or \"map the Stellar landscape for X\". Queries the 728-project LumenLoop ecosystem database and Electric Capital developer activity to rank competitors by SCF funding history and repo activity.","https:\u002F\u002Fgithub.com\u002FWritzProtocol\u002Fwritz\u002Fblob\u002Fmain\u002F.codex\u002Fskills\u002Fstellar-competitive-landscape\u002FSKILL.md",[],[],{"skillNo":81,"name":82,"nameZh":6,"description":83,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":84,"categories":85,"keywords":86,"publishedAt":19},"01M77KK1ACXYN5AZTWR8B5CKTX","standards","Stellar standards, ecosystem, and reference. Covers SEPs (Stellar Ecosystem Proposals), CAPs (Core Advancement Proposals), and a quick map for picking the right standard for wallets, anchors, payments, deposits\u002Fwithdrawals, federation, deep links, and KYC. Also bundles ecosystem references (DeFi protocols, dev tools, wallets, infra, community projects), curated documentation links, and MCP servers (live tools such as Raven). Use when you need to know which SEP applies, or want a starting point for ecosystem integrations, official docs, or live MCP tooling.","https:\u002F\u002Fgithub.com\u002FWritzProtocol\u002Fwritz\u002Fblob\u002Fmain\u002F.codex\u002Fskills\u002Fstandards\u002FSKILL.md",[],[],{"skillNo":88,"name":89,"nameZh":6,"description":90,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":91,"categories":92,"keywords":93,"publishedAt":19},"01M77KJV8VW46WC58DHJR2296C","smart-contracts","Stellar smart contract development (Rust, soroban-sdk). Entry point with project setup, contract anatomy, and build\u002Fdeploy workflow, routing to three companion files in this directory - development.md (storage\u002FTTL, authorization, cross-contract calls, tokens, events, errors, upgrades, fees, troubleshooting), testing.md (unit, fuzz, property, fork, mutation, integration), and security.md (vulnerability classes, checklists, tooling, audits). Use when writing, testing, reviewing, securing, debugging, or shipping Stellar smart contracts, including anything the user calls \"Soroban\" - Soroban contracts, soroban-sdk, Soroban auth\u002Fstorage\u002FTTL errors, SEP-41 tokens, or SAC integration from contract code.","https:\u002F\u002Fgithub.com\u002FWritzProtocol\u002Fwritz\u002Fblob\u002Fmain\u002F.codex\u002Fskills\u002Fsmart-contracts\u002FSKILL.md",[],[]]