From cc9b71531d1ab4b6df990bf8a45fd541bba1ebb7 Mon Sep 17 00:00:00 2001 From: stellar-dev-skill Date: Mon, 11 May 2026 20:58:39 +0000 Subject: [PATCH 1/6] refactor: restructure skill into 7 thematic sub-skills Replace flat skill/ directory (one SKILL.md + 14 sibling .md files) with skills//SKILL.md layout where each sub-skill is a self-contained Agent Skill with its own frontmatter and routing. Pattern matches the coreyhaines31/marketingskills repo. Themes: - soroban: contract dev + testing + security + advanced patterns + pitfalls - dapp: frontend + wallets (Freighter, Wallets Kit) + signing + smart accounts - assets: Stellar Assets + trustlines + SAC bridge - data: Stellar RPC + Horizon + indexing - agentic-payments: x402 (paid APIs) + MPP (Charge + Channel) - zk-proofs: ZK verification, BLS12-381, BN254/Poseidon (status-sensitive) - standards: SEPs + CAPs + ecosystem + curated resources Cross-references between sub-skills use relative ..//SKILL.md paths; in-file self-references (within merged skills like soroban) rewritten to "Part N" descriptions to avoid redundant self-links. Updated plugin.json to point at ./skills/ (plural) and refreshed README to document the new structure. --- .claude-plugin/plugin.json | 2 +- README.md | 26 +- skill/SKILL.md | 162 -- skill/advanced-patterns.md | 188 -- skill/common-pitfalls.md | 510 ---- skill/contracts-soroban.md | 565 ---- skill/ecosystem.md | 430 --- skill/mpp.md | 254 -- skill/resources.md | 306 -- skill/security.md | 491 ---- skill/standards-reference.md | 94 - skill/testing.md | 786 ----- skill/x402.md | 203 -- skills/agentic-payments/SKILL.md | 500 ++++ .../assets/SKILL.md | 27 +- .../dapp/SKILL.md | 30 +- .../data/SKILL.md | 29 +- skills/soroban/SKILL.md | 2584 +++++++++++++++++ skills/standards/SKILL.md | 864 ++++++ .../zk-proofs.md => skills/zk-proofs/SKILL.md | 39 +- 20 files changed, 4075 insertions(+), 4015 deletions(-) delete mode 100644 skill/SKILL.md delete mode 100644 skill/advanced-patterns.md delete mode 100644 skill/common-pitfalls.md delete mode 100644 skill/contracts-soroban.md delete mode 100644 skill/ecosystem.md delete mode 100644 skill/mpp.md delete mode 100644 skill/resources.md delete mode 100644 skill/security.md delete mode 100644 skill/standards-reference.md delete mode 100644 skill/testing.md delete mode 100644 skill/x402.md create mode 100644 skills/agentic-payments/SKILL.md rename skill/stellar-assets.md => skills/assets/SKILL.md (88%) rename skill/frontend-stellar-sdk.md => skills/dapp/SKILL.md (92%) rename skill/api-rpc-horizon.md => skills/data/SKILL.md (90%) create mode 100644 skills/soroban/SKILL.md create mode 100644 skills/standards/SKILL.md rename skill/zk-proofs.md => skills/zk-proofs/SKILL.md (73%) diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 673bac2..a57bf08 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -5,5 +5,5 @@ "author": { "name": "Stellar Development Foundation" }, - "skills": "./skill/" + "skills": "./skills/" } diff --git a/README.md b/README.md index 2a706dc..a6d2cf6 100644 --- a/README.md +++ b/README.md @@ -46,7 +46,7 @@ npx skills add https://github.com/stellar/stellar-dev-skill git clone https://github.com/stellar/stellar-dev-skill ``` -Copy the `skill/` directory contents to your assistant's skills location. +Copy the `skills/` directory contents to your assistant's skills location. | Agent | Skill Directory | Docs | |-------|-----------------|------| @@ -58,23 +58,17 @@ Copy the `skill/` directory contents to your assistant's skills location. ## Skill Structure ``` -skill/ -├── SKILL.md # Main skill definition (required) -├── contracts-soroban.md # Soroban smart contract development -├── frontend-stellar-sdk.md # Frontend integration patterns -├── testing.md # Testing strategies -├── stellar-assets.md # Asset issuance and management -├── zk-proofs.md # ZK proof architecture and verification patterns -├── api-rpc-horizon.md # API access (RPC/Horizon) -├── security.md # Security checklist -├── common-pitfalls.md # Common issues and solutions -├── advanced-patterns.md # Advanced Soroban architecture patterns -├── standards-reference.md # SEP/CAP standards quick reference -├── ecosystem.md # DeFi protocols, wallets, tools, projects -└── resources.md # Curated reference links +skills/ +├── soroban/SKILL.md # Soroban contracts + testing + security + patterns + pitfalls +├── dapp/SKILL.md # Frontend, wallets (Freighter, Wallets Kit), signing, smart accounts +├── assets/SKILL.md # Stellar Assets, trustlines, SAC bridge +├── data/SKILL.md # Stellar RPC (preferred) + Horizon (legacy), indexing +├── agentic-payments/SKILL.md # x402 + MPP (Charge + Channel) for AI/machine payments +├── zk-proofs/SKILL.md # ZK verification, BLS12-381, BN254/Poseidon (status-sensitive) +└── standards/SKILL.md # SEPs, CAPs, ecosystem projects, curated reference links ``` -The skill uses a progressive disclosure pattern. The main `SKILL.md` provides core guidance, and the AI reads the specialized markdown files only when needed for specific tasks. +Each sub-skill is a self-contained Agent Skill with its own frontmatter. Cross-references link related skills (e.g., the `agentic-payments` skill points to `soroban` for the Soroban SACs the protocols call, and to `assets` for USDC). The AI reads only the sub-skills relevant to the task at hand. ## Example Prompts diff --git a/skill/SKILL.md b/skill/SKILL.md deleted file mode 100644 index 384d5ff..0000000 --- a/skill/SKILL.md +++ /dev/null @@ -1,162 +0,0 @@ ---- -name: stellar-dev -description: End-to-end Stellar development playbook. Covers Soroban smart contracts (Rust SDK), Stellar CLI, JavaScript/Python/Go SDKs for client apps, Stellar RPC (preferred) and Horizon API (legacy), Stellar Assets vs Soroban tokens (SAC bridge), wallet integration (Freighter, Stellar Wallets Kit), smart accounts with passkeys, status-sensitive zero-knowledge proof patterns, testing strategies, security patterns, and common pitfalls. Optimized for payments, asset tokenization, DeFi, privacy-aware applications, and financial applications. Use when building on Stellar, Soroban, or working with XLM, Stellar Assets, trustlines, anchors, SEPs, ZK proofs, or the Stellar RPC/Horizon APIs. -user-invocable: true -argument-hint: "[task-description]" ---- - -# Stellar Development Skill (Soroban-first) - -## What this Skill is for -Use this Skill when the user asks for: -- Soroban smart contract development (Rust) -- Stellar dApp frontend work (React / Next.js / Node.js) -- Wallet connection + signing flows (Freighter, etc.) -- Transaction building / sending / confirmation -- Stellar Asset issuance and management -- Client SDK usage (JavaScript, Python, Go, Rust) -- Zero-knowledge proof verification (where supported by target network/protocol) -- Privacy-preserving applications (privacy pools, confidential tokens) -- Local testing and deployment -- Security hardening and audit-style reviews -- Agentic payments: paid APIs (x402) and AI agent payment clients (x402, MPP charge, MPP channel) - -## What this Skill is NOT for -- Bitcoin, Ethereum, Solana, or other non-Stellar blockchain development -- Stellar node/validator operation (see [validators docs](https://developers.stellar.org/docs/validators)) -- General Rust programming unrelated to Soroban -- Stellar protocol governance or CAP authoring - -## Default stack decisions (opinionated) - -### 1. Smart Contracts: Soroban (Rust) -- Use Soroban SDK (`soroban-sdk` crate) for all smart contract development -- Contracts compile to WebAssembly (WASM) -- Use `#![no_std]` - standard library not available -- 64KB contract size limit - use release optimizations -- Prefer Stellar Assets over custom token contracts when possible - -### 2. Client SDK: stellar-sdk (JavaScript) first -- Use `@stellar/stellar-sdk` for browser and Node.js applications -- Supports both Stellar RPC and legacy Horizon API -- Full transaction building, signing, and submission -- Soroban contract deployment and invocation - -### 3. API Access: Stellar RPC first (Horizon legacy-focused) -- **Prefer Stellar RPC** for new projects (JSON-RPC, real-time state) -- **Horizon API** remains available for legacy compatibility and historical-query workflows -- RPC: 7-day history for most methods; `getLedgers` queries back to genesis (Infinite Scroll) -- Use Hubble/Galexie for comprehensive historical data beyond RPC - -### 4. Token Strategy: Stellar Assets first -- **Prefer Stellar Assets** (classic issuance + trustlines) for fungible tokens -- Built-in ecosystem support (wallets, exchanges, anchors) -- Stellar Asset Contracts (SAC) provide Soroban interoperability -- Use custom Soroban tokens only for complex logic requirements - -### 5. Testing -- **Local**: Use Stellar Quickstart Docker for local network -- **Testnet**: Use Testnet with Friendbot for funding -- **Unit tests**: Compile to native for fast iteration -- **Integration tests**: Deploy to local/testnet - -### 6. Wallet Integration -- **Freighter** is the primary browser wallet -- Use Stellar Wallets Kit for multi-wallet support -- Wallet Standard for consistent connection patterns - -### 7. Freshness policy -- Verify volatile facts (protocol support, RPC endpoints, CAP/SEP status, SDK API changes) against official docs before asserting them as current. - -## Operating procedure (how to execute tasks) - -### 1. Classify the task layer -- Smart contract layer (Soroban/Rust) -- Client SDK/scripts layer (JS/Python/Go) -- Frontend/wallet layer -- Asset management layer (issuance, trustlines) -- Testing/CI layer -- Infrastructure (RPC/Horizon/indexing) - -### Quick routing -- Need custom on-chain logic? → [contracts-soroban.md](contracts-soroban.md) -- Building a frontend/dApp? → [frontend-stellar-sdk.md](frontend-stellar-sdk.md) -- Issuing or managing tokens? → [stellar-assets.md](stellar-assets.md) -- Zero-knowledge proofs or privacy? → [zk-proofs.md](zk-proofs.md) -- Setting up tests/CI? → [testing.md](testing.md) -- Querying chain data or indexing? → [api-rpc-horizon.md](api-rpc-horizon.md) (also see [Data Docs](https://developers.stellar.org/docs/data)) -- Security review? → [security.md](security.md) -- Hit an error? → [common-pitfalls.md](common-pitfalls.md) -- Need upgrade/factory/governance/DeFi architecture patterns? → [advanced-patterns.md](advanced-patterns.md) -- Need SEP/CAP guidance and standards links? → [standards-reference.md](standards-reference.md) -- Building a paid API or AI agent payment client? → [x402.md](x402.md) or [mpp.md](mpp.md) (see comparison below) - -### Agentic payments: x402 vs MPP - -| | x402 | MPP Charge | MPP Channel | -|--|------|------------|-------------| -| Per-request on-chain tx? | Yes (via facilitator) | Yes (Soroban SAC) | No (off-chain commits) | -| Needs facilitator? | Yes (OZ Channels) | No | No | -| Client needs XLM? | No (fees sponsored) | Optional (`feePayer`) | Yes | -| Setup complexity | Low | Low | Medium (deploy contract first) | -| Best for | Quickest setup, fee-free clients | No third-party dep | High-frequency agents | - -- Selling an API, want zero-XLM clients → [x402.md](x402.md) Seller -- Calling an x402 API from an agent → [x402.md](x402.md) Buyer -- Selling an API, no facilitator dependency → [mpp.md](mpp.md) Charge mode -- Agent making many requests per session → [mpp.md](mpp.md) Channel mode -- Unsure → x402 (lowest friction to get started) - -All protocols use USDC (SEP-41 SAC) by default; `stellar:testnet` / `stellar:pubnet` CAIP-2 network IDs. - -### 2. Pick the right building blocks -- Contracts: Soroban Rust SDK + Stellar CLI -- Frontend: stellar-sdk (JS) + Freighter/Wallets Kit -- Backend: stellar-sdk (JS/Python/Go) + RPC -- Assets: Classic operations or SAC for Soroban interop -- Testing: Quickstart (local) or Testnet - -### 3. Implement with Stellar-specific correctness -Always be explicit about: -- Network passphrase (Mainnet vs Testnet vs local) -- Source account + sequence number -- Fee + resource limits (for Soroban) -- Authorization requirements -- Trustline status for assets -- Contract storage types (temporary vs persistent vs instance) - -### 4. Add tests -- Unit tests: Native compilation with `#[test]` -- Integration tests: Local Quickstart or Testnet -- Contract tests: Use `Env` from soroban-sdk -- Frontend tests: Mock wallet/RPC interactions - -### 5. Deliverables expectations -When you implement changes, provide: -- Exact files changed + diffs -- Commands to install/build/test/deploy -- Network configuration (passphrase, RPC endpoint) -- Risk notes for signing/fees/storage/authorization - -## Progressive disclosure (read when needed) -- Smart contracts: [contracts-soroban.md](contracts-soroban.md) -- Frontend + wallets: [frontend-stellar-sdk.md](frontend-stellar-sdk.md) -- Testing strategy: [testing.md](testing.md) -- Stellar Assets: [stellar-assets.md](stellar-assets.md) -- Zero-knowledge proofs: [zk-proofs.md](zk-proofs.md) -- API access (RPC/Horizon): [api-rpc-horizon.md](api-rpc-horizon.md) -- Security checklist: [security.md](security.md) -- Common pitfalls: [common-pitfalls.md](common-pitfalls.md) -- Advanced architecture patterns: [advanced-patterns.md](advanced-patterns.md) -- SEP/CAP standards map: [standards-reference.md](standards-reference.md) -- Ecosystem projects: [ecosystem.md](ecosystem.md) -- Reference links: [resources.md](resources.md) -- x402 paid APIs + agent clients: [x402.md](x402.md) -- MPP agentic payments (charge + channel): [mpp.md](mpp.md) - -## Keywords -stellar, soroban, xlm, smart contracts, rust, wasm, webassembly, rpc, horizon, -freighter, stellar-sdk, soroban-sdk, stellar-cli, trustline, anchor, sep, passkey, -smart wallet, sac, stellar asset contract, defi, token, nft, scaffold stellar, constructor, upgrade, factory, governance, standards, -zero-knowledge, zk, zk-snark, groth16, bn254, poseidon, pairing, privacy, confidential, noir, risc zero, privacy pool, merkle tree, -x402, mpp, machine payments protocol, agentic payments, paid api, payment channel, ai agent payments, usdc, sep-41, oz channels, openzeppelin relayer, http 402, per-request payments, soroban auth entries, fee sponsorship, payment middleware diff --git a/skill/advanced-patterns.md b/skill/advanced-patterns.md deleted file mode 100644 index d8e10c7..0000000 --- a/skill/advanced-patterns.md +++ /dev/null @@ -1,188 +0,0 @@ -# Advanced Soroban Patterns - -## When to use this guide -Use this guide for higher-complexity contract architecture: -- Upgrades and migrations -- Factory/deployer systems -- Governance and timelocks -- DeFi primitives (vaults, pools, oracles) -- Regulated token/compliance workflows -- Resource and storage optimization - -Use `contracts-soroban.md` for core contract syntax and day-to-day patterns. - -## Design principles -- Prefer simple state machines over implicit behavior. -- Minimize privileged entrypoints and protect all privileged actions with explicit auth. -- Keep upgrades predictable: version metadata + migration plan + rollback strategy. -- Use idempotent migrations and fail fast on incompatible versions. -- Separate protocol/business logic from governance/admin logic when possible. - -## Upgradeability patterns - -### 1) Explicit upgrade policy -- Decide early whether the contract is mutable or immutable. -- If mutable, implement an `upgrade` entrypoint guarded by admin or governance. -- If immutable, do not expose upgrade capability. - -### 2) Version tracking -Track both runtime and code version: -- Contract metadata (`contractmeta!`) for binary version -- Storage key for migration/application version - -```rust -#![no_std] -use soroban_sdk::{contract, contractimpl, contractmeta, contracttype, Address, BytesN, Env}; - -contractmeta!(key = "binver", val = "1.0.0"); - -#[contracttype] -#[derive(Clone)] -pub enum DataKey { - Admin, - AppVersion, -} - -#[contract] -pub struct Upgradeable; - -#[contractimpl] -impl Upgradeable { - pub fn __constructor(env: Env, admin: Address) { - env.storage().instance().set(&DataKey::Admin, &admin); - env.storage().instance().set(&DataKey::AppVersion, &1u32); - } - - pub fn upgrade(env: Env, new_wasm_hash: BytesN<32>) { - let admin: Address = env.storage().instance().get(&DataKey::Admin).unwrap(); - admin.require_auth(); - env.deployer().update_current_contract_wasm(new_wasm_hash); - } -} -``` - -### 3) Migration entrypoint -- Add a dedicated `migrate` function after upgrades. -- Ensure migration is monotonic (`new_version > current_version`). -- Treat migrations as one-way and idempotent. - -## Factory and deployment patterns - -### Factory contract responsibilities -- Authorize who can deploy instances. -- Derive deterministic addresses with salts when needed. -- Emit events for deployments (indexing/ops observability). -- Keep deployment logic separate from instance business logic. - -```rust -#![no_std] -use soroban_sdk::{contract, contractimpl, Address, BytesN, Env, Val, Vec}; - -#[contract] -pub struct Factory; - -#[contractimpl] -impl Factory { - pub fn deploy( - env: Env, - owner: Address, - wasm_hash: BytesN<32>, - salt: BytesN<32>, - constructor_args: Vec, - ) -> Address { - owner.require_auth(); - env.deployer() - .with_address(env.current_contract_address(), salt) - .deploy_v2(wasm_hash, constructor_args) - } -} -``` - -Operational note: -- Keep a registry (or emit canonical deployment events) to avoid orphaned instances. - -## Governance patterns - -### Timelock for sensitive actions -Use a timelock for upgrades and major config changes: -- `propose_*` stores pending action + execute ledger -- `execute_*` enforces delay -- `cancel_*` allows governance abort - -### Multisig and role separation -- Separate roles: proposer, approver, executor. -- Define threshold and signer rotation process. -- Record proposal state in persistent storage and prevent replay. - -Checklist: -- Proposal uniqueness and replay protection -- Expiry semantics -- Clear cancellation path -- Explicit event emission - -## DeFi primitives - -### Vaults -- Track `total_assets` and `total_shares` with careful rounding rules. -- Use conservative math for mint/redeem conversions. -- Enforce pause/emergency controls for admin-level intervention. - -### Pools/AMMs -- Define invariant and fee accounting precisely. -- Protect against stale pricing and manipulation. -- Include slippage checks on all user-facing swaps. - -### Oracle integration -- Require freshness constraints (ledger/time bounds). -- Prefer median/multi-source feeds for critical operations. -- Add circuit breakers for extreme price movement. - -## Compliance-oriented token design - -Common regulated features: -- Allowlist/denylist checks before transfer -- Jurisdiction or investor-class restrictions -- Forced transfer/freeze authority with auditable governance -- Off-chain identity references (never store sensitive PII directly) - -Implementation guidance: -- Keep compliance policy in dedicated modules/entrypoints. -- Emit policy decision events for traceability. -- Treat privileged compliance actions as high-risk operations requiring strong auth. - -## Resource optimization - -### Storage -- Use `instance` for global config. -- Use `persistent` for critical user state. -- Use `temporary` only for disposable data. -- Extend TTL strategically, not on every call. - -### Compute -- Avoid unbounded loops over user-controlled collections. -- Prefer bounded batch operations. -- Reduce cross-contract calls in hot paths. - -### Contract size -- Keep release profile optimized (`opt-level = "z"`, `lto = true`, `panic = "abort"`). -- Split concerns across contracts when near Wasm size limits. - -## Security review checklist for advanced architectures -- Access control is explicit on every privileged path. -- Upgrade and migration are both tested (happy path + failure path). -- Timelock and governance logic is replay-safe. -- External dependency assumptions are documented. -- Emergency controls and incident runbooks are defined. -- Events cover operationally important transitions. - -## Testing strategy for advanced patterns -- Unit tests for role checks, invariants, and edge-case math. -- Integration tests for multi-step governance flows. -- Upgrade tests from old state snapshots to new versions. -- Negative tests for unauthorized and malformed calls. - -## Related docs -- Core contract development: `contracts-soroban.md` -- Security checks: `security.md` -- Testing approach: `testing.md` -- Standards references: `standards-reference.md` diff --git a/skill/common-pitfalls.md b/skill/common-pitfalls.md deleted file mode 100644 index 52a1bf1..0000000 --- a/skill/common-pitfalls.md +++ /dev/null @@ -1,510 +0,0 @@ -# Common Pitfalls and Solutions - -## Soroban Contract Issues - -### 1. Contract Size Exceeds 64KB Limit - -**Problem**: Contract won't deploy because WASM exceeds size limit. - -**Symptoms**: -``` -Error: contract exceeds maximum size -``` - -**Solutions**: - -```toml -# Cargo.toml - Use aggressive optimization -[profile.release] -opt-level = "z" # Optimize for size -lto = true # Link-time optimization -codegen-units = 1 # Single codegen unit -panic = "abort" # Smaller panic handling -strip = "symbols" # Remove symbols -``` - -Additional strategies: -- Split large contracts into multiple smaller contracts -- Use `symbol_short!()` for symbols under 9 chars -- Avoid large static data in contract -- Remove debug code and unused functions -- Use `cargo bloat` to identify large dependencies - -```bash -# Check contract size -ls -la target/wasm32-unknown-unknown/release/*.wasm - -# Analyze what's taking space -cargo install cargo-bloat -cargo bloat --release --target wasm32-unknown-unknown -``` - ---- - -### 2. `#![no_std]` Missing - -**Problem**: Compilation fails with std library errors. - -**Symptoms**: -``` -error: cannot find macro `println` in this scope -error[E0433]: failed to resolve: use of undeclared crate or module `std` -``` - -**Solution**: -```rust -// MUST be first line of lib.rs -#![no_std] - -use soroban_sdk::{contract, contractimpl, Env}; - -// Use soroban_sdk equivalents instead of std: -// - soroban_sdk::String instead of std::string::String -// - soroban_sdk::Vec instead of std::vec::Vec -// - soroban_sdk::Map instead of std::collections::HashMap -``` - ---- - -### 3. Storage TTL Not Extended - -**Problem**: Contract data gets archived and becomes inaccessible. - -**Symptoms**: -- Contract calls fail after period of inactivity -- Data appears missing but contract still exists - -**Solution**: -```rust -// Proactively extend TTL in operations that use data -pub fn use_data(env: Env) { - // Extend instance storage - env.storage().instance().extend_ttl( - 50, // If TTL < 50, extend - 518400, // Extend to ~30 days - ); - - // Extend specific persistent keys - env.storage().persistent().extend_ttl( - &DataKey::ImportantData, - 50, - 518400, - ); - - // Now use the data... -} -``` - -> See [contracts-soroban.md](contracts-soroban.md) for full TTL management patterns and storage type guidance. - ---- - -### 4. Wrong Storage Type - -**Problem**: Data unexpectedly deleted or costs too high. - -**Symptoms**: -- Temporary data deleted before expected -- Unexpectedly high fees for storage - -**Solution**: -```rust -// Instance: Shared config, survives with contract -env.storage().instance().set(&DataKey::Admin, &admin); - -// Persistent: User data, can be archived but restored -env.storage().persistent().set(&DataKey::Balance(user), &balance); - -// Temporary: Truly temporary, auto-deleted, cheapest -env.storage().temporary().set(&DataKey::Cache(key), &value); -``` - ---- - -### 5. Authorization Not Working - -**Problem**: `require_auth()` not enforcing signatures in tests. - -**Symptoms**: -- Tests pass but transactions fail on network -- Anyone can call protected functions - -**Solution**: -```rust -#[test] -fn test_auth() { - let env = Env::default(); - - // DON'T just mock all auths blindly - // env.mock_all_auths(); // Be careful with this! - - // DO test specific auth requirements with mock_auths() - env.mock_auths(&[MockAuth { - address: &user, - invoke: &MockAuthInvoke { - contract: &contract_id, - fn_name: "transfer", - args: (&user, &other, &100i128).into_val(&env), - sub_invokes: &[], - }, - }]); - - client.transfer(&user, &other, &100); - assert!(!env.auths().is_empty()); -} -``` - -> See [testing.md](testing.md) for comprehensive auth testing patterns including `mock_all_auths()`, specific auth mocking, and cross-contract auth. - ---- - -## SDK Issues - -### 6. Network Passphrase Mismatch - -**Problem**: Transactions fail with signature errors. - -**Symptoms**: -``` -Error: tx_bad_auth -``` - -**Solution**: -```typescript -import * as StellarSdk from "@stellar/stellar-sdk"; - -// ALWAYS use correct passphrase for network -const PASSPHRASES = { - mainnet: StellarSdk.Networks.PUBLIC, - // "Public Global Stellar Network ; September 2015" - - testnet: StellarSdk.Networks.TESTNET, - // "Test SDF Network ; September 2015" - - local: "Standalone Network ; February 2017", -}; - -// When building transactions -const tx = new StellarSdk.TransactionBuilder(account, { - fee: StellarSdk.BASE_FEE, - networkPassphrase: PASSPHRASES.testnet, // Match your network! -}); -``` - ---- - -### 7. Account Not Funded - -**Problem**: Operations fail because account doesn't exist. - -**Symptoms**: -``` -Error: Account not found -Status: 404 -``` - -**Solution**: -```typescript -// Testnet - use Friendbot -await fetch(`https://friendbot.stellar.org?addr=${publicKey}`); - -// Mainnet - must receive XLM from existing account -const tx = new StellarSdk.TransactionBuilder(funderAccount, { - fee: StellarSdk.BASE_FEE, - networkPassphrase: StellarSdk.Networks.PUBLIC, -}) - .addOperation( - StellarSdk.Operation.createAccount({ - destination: newAccountPublicKey, - startingBalance: "2", // Minimum ~1 XLM for base reserve - }) - ) - .setTimeout(180) - .build(); -``` - ---- - -### 8. Missing Trustline - -**Problem**: Payment fails for non-native assets. - -**Symptoms**: -``` -Error: op_no_trust -``` - -**Solution**: -```typescript -// Check if trustline exists -const account = await server.loadAccount(destination); -const hasTrustline = account.balances.some( - (b) => - b.asset_type !== "native" && - b.asset_code === asset.code && - b.asset_issuer === asset.issuer -); - -if (!hasTrustline) { - // Create trustline first - const trustTx = new StellarSdk.TransactionBuilder(destAccount, { - fee: StellarSdk.BASE_FEE, - networkPassphrase, - }) - .addOperation(StellarSdk.Operation.changeTrust({ asset })) - .setTimeout(180) - .build(); - // Sign and submit... -} -``` - ---- - -### 9. Sequence Number Issues - -**Problem**: Transaction rejected for sequence number. - -**Symptoms**: -``` -Error: tx_bad_seq -``` - -**Causes & Solutions**: - -```typescript -// Cause 1: Stale account data -// Solution: Always load fresh account before building tx -const account = await server.loadAccount(publicKey); - -// Cause 2: Parallel transactions -// Solution: Use sequence number management -class SequenceManager { - private sequence: bigint; - - async getNext(server: Horizon.Server, publicKey: string) { - if (!this.sequence) { - const account = await server.loadAccount(publicKey); - this.sequence = BigInt(account.sequence); - } - this.sequence++; - return this.sequence.toString(); - } -} - -// Cause 3: Transaction timeout without resubmit -// Solution: Rebuild with fresh sequence on timeout -``` - ---- - -### 10. Soroban Transaction Not Simulated - -**Problem**: Soroban transaction fails with resource errors. - -**Symptoms**: -``` -Error: transaction simulation failed -Error: insufficient resources -``` - -**Solution**: -```typescript -// ALWAYS simulate before submitting Soroban transactions -const simulation = await rpc.simulateTransaction(transaction); - -if (StellarSdk.rpc.Api.isSimulationError(simulation)) { - throw new Error(`Simulation failed: ${simulation.error}`); -} - -// Use assembleTransaction to add correct resources -const preparedTx = StellarSdk.rpc.assembleTransaction( - transaction, - simulation -).build(); - -// Now sign and submit preparedTx, not original transaction -``` - ---- - -## Frontend Issues - -### 11. Freighter Not Detected - -**Problem**: Wallet connection fails silently. - -**Symptoms**: -- `isConnected()` returns false -- No wallet prompt appears - -**Solution**: -```typescript -import { isConnected, isAllowed } from "@stellar/freighter-api"; - -async function checkFreighter() { - // Check if extension is installed - const connected = await isConnected(); - if (!connected) { - // Prompt user to install - window.open("https://freighter.app", "_blank"); - return; - } - - // Check if app is allowed - const allowed = await isAllowed(); - if (!allowed) { - // Need to request permission - await setAllowed(); - } -} -``` - ---- - -### 12. Network Mismatch with Wallet - -**Problem**: Wallet on different network than app. - -**Symptoms**: -- Transactions fail unexpectedly -- Wrong balances displayed - -**Solution**: -```typescript -import { getNetwork } from "@stellar/freighter-api"; - -async function validateNetwork() { - const walletNetwork = await getNetwork(); - const appNetwork = process.env.NEXT_PUBLIC_STELLAR_NETWORK; - - if (walletNetwork !== appNetwork) { - throw new Error( - `Please switch Freighter to ${appNetwork}. Currently on ${walletNetwork}` - ); - } -} -``` - ---- - -### 13. Transaction Timeout - -**Problem**: Transaction expires before confirmation. - -**Symptoms**: -``` -Error: tx_too_late -``` - -**Solution**: -```typescript -// Set appropriate timeout based on expected confirmation time -const tx = new StellarSdk.TransactionBuilder(account, { - fee: StellarSdk.BASE_FEE, - networkPassphrase, -}) - .addOperation(/* ... */) - .setTimeout(180) // 3 minutes - adjust as needed - .build(); - -// Handle timeout gracefully -async function submitWithRetry(signedXdr: string) { - try { - return await submitTransaction(signedXdr); - } catch (error) { - if (error.response?.data?.extras?.result_codes?.transaction === "tx_too_late") { - // Rebuild with fresh blockhash and retry - const newTx = await rebuildTransaction(signedXdr); - return await submitTransaction(newTx); - } - throw error; - } -} -``` - ---- - -## CLI Issues - -### 14. Identity Not Found - -**Problem**: Stellar CLI can't find saved identity. - -**Symptoms**: -``` -Error: identity "alice" not found -``` - -**Solution**: -```bash -# List existing identities -stellar keys list - -# Generate new identity -stellar keys generate --global alice - -# For testnet with funding -stellar keys generate --global alice --network testnet --fund - -# Specify identity location -stellar keys generate alice --config-dir /custom/path -``` - ---- - -### 15. Contract Invoke Parsing Errors - -**Problem**: CLI can't parse function arguments. - -**Symptoms**: -``` -Error: invalid argument format -``` - -**Solution**: -```bash -# Use correct argument syntax -# Addresses: just the G... or C... string -stellar contract invoke \ - --id CONTRACT_ID \ - --source alice \ - --network testnet \ - -- \ - transfer \ - --from GABC... \ - --to GDEF... \ - --amount 1000 - -# Complex types: use JSON -stellar contract invoke \ - --id CONTRACT_ID \ - -- \ - complex_fn \ - --data '{"field1": "value", "field2": 123}' -``` - ---- - -## General Best Practices - -### Debugging Checklist - -1. **Check network**: Is wallet/CLI on correct network? -2. **Check account**: Is source account funded? -3. **Check sequence**: Is sequence number current? -4. **Check simulation**: Did Soroban tx simulate successfully? -5. **Check trustlines**: For asset transfers, do trustlines exist? -6. **Check TTL**: For contract data, is TTL sufficient? -7. **Check authorization**: Is correct account signing? -8. **Check logs**: What does the error message actually say? - -### Error Code Reference - -| Code | Meaning | Common Fix | -|------|---------|------------| -| `tx_bad_auth` | Signature invalid | Check network passphrase | -| `tx_bad_seq` | Wrong sequence | Reload account | -| `tx_too_late` | Transaction expired | Rebuild and resubmit | -| `op_no_trust` | Missing trustline | Create trustline first | -| `op_underfunded` | Insufficient balance | Add funds | -| `op_low_reserve` | Below minimum balance | Maintain reserve | diff --git a/skill/contracts-soroban.md b/skill/contracts-soroban.md deleted file mode 100644 index 28272ee..0000000 --- a/skill/contracts-soroban.md +++ /dev/null @@ -1,565 +0,0 @@ -# Soroban Smart Contract Development - -## When to use Soroban -Use Soroban when you need: -- Custom on-chain logic beyond Stellar's built-in operations -- Programmable escrow, lending, or DeFi primitives -- Complex authorization rules -- State management beyond account balances -- Interoperability with Stellar Assets via SAC - -## Quick Navigation -- Initialization and constructors: [Project Setup](#project-setup), [Contract Constructors (Protocol 22+)](#contract-constructors-protocol-22) -- Core implementation patterns: [Core Contract Structure](#core-contract-structure), [Storage Types](#storage-types), [Authorization](#authorization) -- Advanced interactions: [Cross-Contract Calls](#cross-contract-calls), [Events](#events), [Error Handling](#error-handling) -- Delivery workflow: [Building and Deploying](#building-and-deploying), [Unit Testing](#unit-testing), [Best Practices](#best-practices) -- ZK status guidance: [Zero-Knowledge Cryptography (Status-Sensitive)](#zero-knowledge-cryptography-status-sensitive) - -## Alternative Languages - -Rust is the primary and recommended language for Soroban contracts. Community-maintained alternatives exist but are not recommended for production: -- **AssemblyScript**: [`as-soroban-sdk`](https://github.com/Soneso/as-soroban-sdk) by Soneso — allows TypeScript-like syntax, officially listed on Stellar docs, but may lag behind the latest protocol version -- **Solidity**: [Hyperledger Solang](https://github.com/hyperledger-solang/solang) — SDF-funded, compiles Solidity to Soroban WASM, currently **pre-alpha** ([docs](https://developers.stellar.org/docs/learn/migrate/evm/solidity-support-via-solang)) - -## Architecture Overview - -### Host-Guest Model -Soroban uses a WebAssembly sandbox with strict separation: -- **Host Environment**: Provides storage, crypto, cross-contract calls -- **Guest Contract**: Your Rust code compiled to WASM -- Contracts reference host objects via handles (not direct memory) - -### Key Constraints -- `#![no_std]` required - no Rust standard library -- 64KB contract size limit (use release optimizations) -- Limited heap allocation -- No string type (use `String` from soroban-sdk or `Symbol` for short strings) -- `Symbol` limited to 32 characters (was 10 in earlier versions) - -## Project Setup - -### Initialize a new contract -```bash -stellar contract init my-contract -cd my-contract -``` - -This creates: -``` -my-contract/ -├── Cargo.toml -├── src/ -│ └── lib.rs -└── contracts/ - └── hello_world/ - ├── Cargo.toml - └── src/ - └── lib.rs -``` - -### Cargo.toml configuration -```toml -[package] -name = "my-contract" -version = "0.1.0" -edition = "2021" - -[lib] -crate-type = ["cdylib"] - -[dependencies] -soroban-sdk = "25.0.1" # check https://crates.io/crates/soroban-sdk for latest - -[dev-dependencies] -soroban-sdk = { version = "25.0.1", features = ["testutils"] } # match above - -[profile.release] -opt-level = "z" -overflow-checks = true -debug = 0 -strip = "symbols" -debug-assertions = false -panic = "abort" -codegen-units = 1 -lto = true - -[profile.release-with-logs] -inherits = "release" -debug-assertions = true -``` - -## Contract Constructors (Protocol 22+) - -Use constructors for atomic initialization when protocol support is available. This avoids a separate `initialize` transaction and reduces front-running risk. - -### Constructor pattern -```rust -#![no_std] -use soroban_sdk::{contract, contractimpl, contracttype, Address, Env}; - -#[contracttype] -#[derive(Clone)] -pub enum DataKey { - Admin, - Value, -} - -#[contract] -pub struct MyContract; - -#[contractimpl] -impl MyContract { - // Runs once at deployment time. - pub fn __constructor(env: Env, admin: Address, initial_value: u32) { - env.storage().instance().set(&DataKey::Admin, &admin); - env.storage().instance().set(&DataKey::Value, &initial_value); - } -} -``` - -### Deploy with constructor args (CLI) -```bash -stellar contract deploy \ - --wasm target/wasm32-unknown-unknown/release/my_contract.wasm \ - --source alice \ - --network testnet \ - -- \ - --admin alice \ - --initial_value 100 -``` - -### Rules -1. Name must be `__constructor` exactly. -2. Constructor returns `()` (no return value). -3. Runs only at creation time and does not run on upgrade. -4. If constructor fails, deployment fails atomically. - -### Backwards compatibility -If targeting older protocol environments, use guarded `initialize` patterns and prevent re-initialization explicitly. - -## Core Contract Structure - -### Basic Contract -```rust -#![no_std] -use soroban_sdk::{contract, contractimpl, symbol_short, vec, Env, Symbol, Vec}; - -#[contract] -pub struct HelloContract; - -#[contractimpl] -impl HelloContract { - pub fn hello(env: Env, to: Symbol) -> Vec { - vec![&env, symbol_short!("Hello"), to] - } -} -``` - -### Contract with State -```rust -#![no_std] -use soroban_sdk::{contract, contractimpl, contracttype, Address, Env}; - -#[contracttype] -#[derive(Clone)] -pub enum DataKey { - Counter, - Admin, - UserBalance(Address), -} - -#[contract] -pub struct CounterContract; - -#[contractimpl] -impl CounterContract { - pub fn initialize(env: Env, admin: Address) { - if env.storage().instance().has(&DataKey::Admin) { - panic!("already initialized"); - } - env.storage().instance().set(&DataKey::Admin, &admin); - env.storage().instance().set(&DataKey::Counter, &0u32); - } - - pub fn increment(env: Env) -> u32 { - let mut count: u32 = env.storage().instance().get(&DataKey::Counter).unwrap_or(0); - count += 1; - env.storage().instance().set(&DataKey::Counter, &count); - - // Extend TTL to prevent archival - env.storage().instance().extend_ttl(100, 518400); // threshold, ~30 days - - count - } - - pub fn get_count(env: Env) -> u32 { - env.storage().instance().get(&DataKey::Counter).unwrap_or(0) - } -} -``` - -## Storage Types - -Soroban has three storage types with different costs and lifetimes: - -### Instance Storage -- Tied to contract instance lifetime -- Shared across all users -- Best for: admin addresses, global config, counters -```rust -env.storage().instance().set(&key, &value); -env.storage().instance().get(&key); -env.storage().instance().extend_ttl(min_ttl, extend_to); -``` - -### Persistent Storage -- Survives archival (can be restored) -- Per-key TTL management -- Best for: user balances, important state -```rust -env.storage().persistent().set(&key, &value); -env.storage().persistent().get(&key); -env.storage().persistent().extend_ttl(&key, min_ttl, extend_to); -``` - -### Temporary Storage -- Cheapest, automatically deleted when TTL expires -- Cannot be restored after archival -- Best for: caches, temporary flags, session data -```rust -env.storage().temporary().set(&key, &value); -env.storage().temporary().get(&key); -env.storage().temporary().extend_ttl(&key, min_ttl, extend_to); -``` - -### TTL Management -```rust -// Check remaining TTL -let ttl = env.storage().persistent().get_ttl(&key); - -// Extend if below threshold -const MIN_TTL: u32 = 17280; // ~1 day at 5s ledgers -const EXTEND_TO: u32 = 518400; // ~30 days - -if ttl < MIN_TTL { - env.storage().persistent().extend_ttl(&key, MIN_TTL, EXTEND_TO); -} -``` - -## Data Types - -### Primitive Types -```rust -use soroban_sdk::{Address, Bytes, BytesN, Map, String, Symbol, Vec, I128, U256}; - -// Address - account or contract identifier -let addr: Address = env.current_contract_address(); - -// Symbol - short strings (max 32 chars) -let sym: Symbol = symbol_short!("transfer"); - -// String - longer strings -let s: String = String::from_str(&env, "Hello, Stellar!"); - -// Fixed-size bytes -let hash: BytesN<32> = env.crypto().sha256(&bytes); - -// Collections -let v: Vec = vec![&env, 1, 2, 3]; -let m: Map = Map::new(&env); -``` - -### Custom Types -```rust -#[contracttype] -#[derive(Clone, Debug, Eq, PartialEq)] -pub struct TokenMetadata { - pub name: String, - pub symbol: Symbol, - pub decimals: u32, -} - -#[contracttype] -#[derive(Clone)] -pub enum DataKey { - Admin, - Balance(Address), - Allowance(Address, Address), // (owner, spender) -} -``` - -## Authorization - -### Requiring Authorization -```rust -#[contractimpl] -impl TokenContract { - pub fn transfer(env: Env, from: Address, to: Address, amount: i128) { - // Require 'from' to authorize this call - from.require_auth(); - - // Or require auth for specific arguments - from.require_auth_for_args((&to, amount).into_val(&env)); - - // Transfer logic... - } -} -``` - -### Admin Patterns -```rust -fn require_admin(env: &Env) { - let admin: Address = env.storage().instance().get(&DataKey::Admin).unwrap(); - admin.require_auth(); -} - -pub fn set_admin(env: Env, new_admin: Address) { - require_admin(&env); - env.storage().instance().set(&DataKey::Admin, &new_admin); -} -``` - -## Cross-Contract Calls - -### Calling Another Contract -```rust -use soroban_sdk::{contract, contractimpl, Address, Env}; - -mod token_contract { - soroban_sdk::contractimport!( - file = "../token/target/wasm32-unknown-unknown/release/token.wasm" - ); -} - -#[contract] -pub struct VaultContract; - -#[contractimpl] -impl VaultContract { - pub fn deposit(env: Env, user: Address, token: Address, amount: i128) { - user.require_auth(); - - // Create client for token contract - let token_client = token_contract::Client::new(&env, &token); - - // Call transfer on token contract - token_client.transfer(&user, &env.current_contract_address(), &amount); - - // Update vault state... - } -} -``` - -### Using Stellar Asset Contract (SAC) -```rust -use soroban_sdk::token::Client as TokenClient; - -pub fn transfer_asset(env: Env, from: Address, to: Address, asset: Address, amount: i128) { - from.require_auth(); - - let token = TokenClient::new(&env, &asset); - token.transfer(&from, &to, &amount); -} -``` - -## Events - -### Emitting Events -```rust -use soroban_sdk::{contract, contractevent, contractimpl, Address, Env}; - -#[contractevent(topics = ["transfer"])] -pub struct TransferEvent { - pub from: Address, - pub to: Address, - pub amount: i128, -} - -#[contract] -pub struct TokenContract; - -#[contractimpl] -impl TokenContract { - pub fn transfer(env: Env, from: Address, to: Address, amount: i128) { - // ... transfer logic ... - - // Emit event - TransferEvent { from, to, amount }.publish(&env); - } -} -``` - -## Error Handling - -### Custom Errors -```rust -use soroban_sdk::contracterror; - -#[contracterror] -#[derive(Copy, Clone, Debug, Eq, PartialEq)] -#[repr(u32)] -pub enum ContractError { - AlreadyInitialized = 1, - NotInitialized = 2, - InsufficientBalance = 3, - Unauthorized = 4, - InvalidAmount = 5, -} - -// Usage -pub fn transfer(env: Env, from: Address, to: Address, amount: i128) -> Result<(), ContractError> { - if amount <= 0 { - return Err(ContractError::InvalidAmount); - } - - let balance: i128 = get_balance(&env, &from); - if balance < amount { - return Err(ContractError::InsufficientBalance); - } - - // ... transfer logic ... - Ok(()) -} -``` - -## Building and Deploying - -### Build Contract -```bash -# Build optimized WASM -stellar contract build - -# Output: target/wasm32-unknown-unknown/release/my_contract.wasm -``` - -### Deploy to Testnet -```bash -# Generate and fund a new identity -stellar keys generate --global alice --network testnet --fund - -# Deploy contract -stellar contract deploy \ - --wasm target/wasm32-unknown-unknown/release/my_contract.wasm \ - --source alice \ - --network testnet - -# Returns: CONTRACT_ID (starts with 'C') -``` - -### Initialize Contract -```bash -stellar contract invoke \ - --id CONTRACT_ID \ - --source alice \ - --network testnet \ - -- \ - initialize \ - --admin alice -``` - -### Invoke Functions -```bash -stellar contract invoke \ - --id CONTRACT_ID \ - --source alice \ - --network testnet \ - -- \ - increment -``` - -## Unit Testing - -```rust -#![cfg(test)] - -use super::*; -use soroban_sdk::testutils::Address as _; -use soroban_sdk::Env; - -#[test] -fn test_increment() { - let env = Env::default(); - let contract_id = env.register_contract(None, CounterContract); - let client = CounterContractClient::new(&env, &contract_id); - - let admin = Address::generate(&env); - client.initialize(&admin); - - assert_eq!(client.get_count(), 0); - assert_eq!(client.increment(), 1); - assert_eq!(client.increment(), 2); - assert_eq!(client.get_count(), 2); -} - -#[test] -fn test_transfer_with_auth() { - let env = Env::default(); - env.mock_all_auths(); // Auto-approve all auth requests - - let contract_id = env.register_contract(None, TokenContract); - let client = TokenContractClient::new(&env, &contract_id); - - let alice = Address::generate(&env); - let bob = Address::generate(&env); - - // Mint tokens to alice - client.mint(&alice, &1000); - - // Transfer from alice to bob - client.transfer(&alice, &bob, &100); - - assert_eq!(client.balance(&alice), 900); - assert_eq!(client.balance(&bob), 100); -} -``` - -## Best Practices - -### Contract Size Optimization -- Use `symbol_short!()` for symbols under 9 chars (more efficient) -- Avoid unnecessary string operations -- Use appropriate storage type for data lifetime -- Consider splitting large contracts - -### Storage Efficiency -- Use compact data structures -- Clean up temporary storage -- Batch storage operations when possible -- Manage TTLs proactively to avoid archival - -### Security -- Always validate inputs -- Use `require_auth()` for sensitive operations -- Check contract ownership in initialization -- Prevent reinitialization attacks -- Validate cross-contract call targets - -### Gas/Resource Optimization -- Minimize storage reads/writes -- Use events for data that doesn't need on-chain queries -- Batch operations where possible -- Profile resource usage with `stellar contract invoke --sim` - -## Zero-Knowledge Cryptography (Status-Sensitive) - -Stellar's ZK cryptography capabilities are evolving. Treat availability as protocol- and network-dependent. - -- [CAP-0059](https://github.com/stellar/stellar-protocol/blob/master/core/cap-0059.md): BLS12-381 primitives -- [CAP-0074](https://github.com/stellar/stellar-protocol/blob/master/core/cap-0074.md): BN254 host functions (proposed) -- [CAP-0075](https://github.com/stellar/stellar-protocol/blob/master/core/cap-0075.md): Poseidon/Poseidon2 host functions (proposed) - -Before implementation, always verify: -1. CAP status in the CAP preamble (`Accepted`/`Implemented` vs draft/awaiting decision) -2. Target network software version and protocol support -3. `soroban-sdk` release support for the target host functions - -### Practical guidance -- Use BLS12-381 features where supported and documented in your target SDK/network. -- For BN254/Poseidon plans, design feature flags and graceful fallbacks until support is active. -- Keep cryptographic assumptions explicit in audits and deployment notes. - -### Example references -- [Groth16 Verifier](https://github.com/stellar/soroban-examples/tree/main/groth16_verifier) -- [Soroban examples repository](https://github.com/stellar/soroban-examples) - -> See [zk-proofs.md](zk-proofs.md) for Groth16 verification patterns, Poseidon usage, Noir/RISC Zero integration, and implementation guidance. diff --git a/skill/ecosystem.md b/skill/ecosystem.md deleted file mode 100644 index 3346810..0000000 --- a/skill/ecosystem.md +++ /dev/null @@ -1,430 +0,0 @@ -# Stellar Ecosystem Projects and Protocols - -This guide catalogs the major projects, protocols, and tools in the Stellar ecosystem. Use this as a reference when building on Stellar to find relevant integrations, examples, and community projects. - -> **Canonical directories** — For the most up-to-date project lists, check: -> - [Stellar Ecosystem](https://stellar.org/ecosystem) — Official directory (searchable by country, asset, category) -> - [SCF Projects](https://communityfund.stellar.org/projects) — Funded projects with status tracking -> - [Stellar on DefiLlama](https://defillama.com/chain/stellar) — Live DeFi TVL data -> -> Treat project metrics/status as volatile. Validate latest activity and production readiness before taking dependencies. - -## DeFi Protocols - -### Lending & Borrowing - -#### Blend Protocol -Universal liquidity protocol enabling permissionless lending pools. -- **Use Case**: Lending, borrowing, yield generation -- **GitHub**: https://github.com/blend-capital/blend-contracts -- **GitHub (v2)**: https://github.com/blend-capital/blend-contracts-v2 -- **Integrations**: Meru, Airtm, Lobstr, DeFindex, Beans - -#### Slender -First non-custodial lending protocol on Soroban with flash loan support. -- **Use Case**: Lending, borrowing, flash loans -- **Features**: Pool-based strategy, sTokens, dTokens, utilization caps -- **Oracle**: SEP-40 compatible (Reflector) - -### DEXs & AMMs - -#### Soroswap -First DEX and aggregator on Stellar/Soroban. -- **Use Case**: Token swaps, liquidity provision, aggregation -- **Website**: https://soroswap.finance -- **GitHub (Core)**: https://github.com/soroswap/core -- **GitHub (Frontend)**: https://github.com/soroswap/frontend -- **GitHub (Aggregator)**: https://github.com/soroswap/aggregator -- **Docs**: https://docs.soroswap.finance -- **Features**: AMM + DEX aggregator across Aqua, Phoenix, Stellar Classic DEX - -#### Aquarius / AQUA Network -Governance-driven liquidity layer with AMM functionality. -- **Use Case**: Liquidity incentives, AMM, governance -- **Website**: https://aqua.network -- **GitHub**: https://github.com/AquaToken/soroban-amm -- **GitHub (Org)**: https://github.com/AquaToken -- **Token**: AQUA (governance + rewards) -- **Docs**: https://docs.aqua.network - -#### Phoenix Protocol -AMM protocol on Soroban. -- **GitHub**: https://github.com/Phoenix-Protocol-Group -- **Use Case**: Token swaps, liquidity pools - -### Yield & Vaults - -#### DeFindex -Yield aggregation and vault infrastructure by PaltaLabs. -- **Use Case**: Tokenized vaults, yield strategies, DeFi abstraction -- **Docs**: https://docs.defindex.io -- **Features**: Automated rebalancing, vault management, Blend integration - -### Stablecoins & CDPs - -#### Orbit CDP Protocol -Collateralized stablecoin issuance (USD, EUR, MXN). -- **Use Case**: Mint stablecoins against XLM/bond collateral -- **Docs**: https://docs.orbitcdp.finance -- **Features**: Multi-currency stablecoins, Pegkeeper automation, Blend integration - -## Wallets - -### Browser Extensions - -#### Freighter -SDF's flagship non-custodial browser wallet. -- **Website**: https://freighter.app -- **Docs**: https://docs.freighter.app -- **GitHub**: https://github.com/stellar/freighter -- **GitHub (Mobile)**: https://github.com/stellar/freighter-mobile -- **API**: https://github.com/stellar/freighter/tree/master/library/freighter-api -- **Features**: Soroban support, mobile apps (iOS/Android), Discover browser - -#### xBull -Feature-rich browser wallet with advanced capabilities. -- **Website**: https://xbull.app -- **Features**: Multi-account, hardware wallet support - -#### Albedo -Lightweight web-based wallet and signing provider. -- **Website**: https://albedo.link -- **Use Case**: Web authentication, transaction signing - -#### Rabet -Browser extension wallet for Stellar. -- **Website**: https://rabet.io - -#### Hana Wallet -Modern Stellar wallet with DeFi features. -- **Website**: https://hana.network - -### Mobile Wallets - -#### LOBSTR -Most popular Stellar mobile wallet. -- **Website**: https://lobstr.co -- **Platforms**: iOS, Android, Web -- **Features**: DEX trading, multisig, 2FA, asset discovery - -#### Beans -Payments platform with yield features. -- **Use Case**: Payments, earning (via DeFindex/Blend) -- **Features**: Non-custodial yield generation - -### Multi-Wallet Integration - -#### Stellar Wallets Kit -SDK for integrating multiple Stellar wallets. -- **GitHub**: https://github.com/Creit-Tech/Stellar-Wallets-Kit -- **Supports**: Freighter, LOBSTR, xBull, Albedo, Rabet, Hana, Ledger, Trezor, WalletConnect - -## Developer Tools - -### Smart Account & Authentication - -#### Smart Account Kit (Recommended) -Comprehensive TypeScript SDK for OpenZeppelin Smart Accounts on Stellar/Soroban. -- **GitHub**: https://github.com/kalepail/smart-account-kit -- **Use Case**: Production smart wallets with passkeys -- **Built On**: [OpenZeppelin stellar-contracts](https://github.com/OpenZeppelin/stellar-contracts) -- **Features**: - - Context rules with fine-grained authorization scopes - - Policy support (threshold multisig, spending limits, custom policies) - - Session management with automatic credential persistence - - External wallet adapter support (Freighter, LOBSTR, etc.) - - Built-in indexer for contract discovery - - Multiple signer types (passkeys, Ed25519, policies) - -#### Passkey Kit (Legacy) -Original TypeScript SDK for passkey-based smart wallets. -- **GitHub**: https://github.com/kalepail/passkey-kit -- **Status**: Legacy - use Smart Account Kit for new projects -- **Use Case**: Simple passkey wallet integration -- **Integration**: OpenZeppelin Relayer (gasless tx), Mercury (indexing) -- **Demo**: [passkey-kit-demo.pages.dev](https://passkey-kit-demo.pages.dev) -- **Example**: [Super Peach](https://github.com/kalepail/superpeach) - -#### OpenZeppelin Relayer -Service for fee-sponsored transaction submission. -- **Docs**: https://docs.openzeppelin.com/relayer -- **Use Case**: Gasless transactions, fee sponsoring - -### Data Indexing - -For a full directory of indexing options, see [Stellar Indexer Docs](https://developers.stellar.org/docs/data/indexers). - -#### Mercury -Stellar-native data indexing platform with Retroshades technology. -- **Website**: https://mercurydata.app -- **Docs**: https://docs.mercurydata.app -- **Use Case**: Event indexing, data queries, automation -- **Features**: Zephyr VM (serverless Rust execution at ledger close), GraphQL API - -#### SubQuery -Multi-chain indexer supporting Stellar and Soroban. -- **Website**: https://subquery.network -- **Quick Start**: https://subquery.network/doc/indexer/quickstart/quickstart_chains/stellar.html -- **Features**: Block/transaction/operation/event handlers, multi-threading, 300+ chains - -#### Goldsky -Real-time data replication and subgraph platform. -- **Website**: https://goldsky.com -- **Docs**: https://docs.goldsky.com/chains/stellar -- **Features**: Mirror (real-time pipelines), subgraphs, on-chain + off-chain data - -#### Zephyr VM -Cloud execution environment for blockchain data processing. -- **GitHub**: https://github.com/xycloo/zephyr-vm -- **Use Case**: Indexing, monitoring, automation -- **Features**: Self-hostable, ledger-close execution - -### Contract Libraries - -#### OpenZeppelin Stellar Contracts -Audited smart contract library for Soroban (track latest release tags before pinning versions). -- **GitHub**: https://github.com/OpenZeppelin/stellar-contracts -- **Docs**: https://developers.stellar.org/docs/tools/openzeppelin-contracts -- **Contract Wizard**: https://wizard.openzeppelin.com/stellar -- **Includes**: Tokens (fungible/NFT), governance (timelock), vaults (SEP-56), access control, fee forwarder -- **Crates**: `stellar-tokens`, `stellar-access`, `stellar-contract-utils` - -### Security Tools - -#### Scout Soroban (CoinFabrik) -Open-source vulnerability detector with 23 detectors for Soroban contracts. -- **GitHub**: https://github.com/CoinFabrik/scout-soroban -- **Install**: `cargo install cargo-scout-audit` -- **Features**: CLI tool, VSCode extension, SARIF output for CI/CD -- **Examples**: https://github.com/CoinFabrik/scout-soroban-examples - -#### OpenZeppelin Security Detectors SDK -Framework for building custom security detectors for Soroban. -- **GitHub**: https://github.com/OpenZeppelin/soroban-security-detectors-sdk -- **Detectors**: `auth_missing`, `unchecked_ft_transfer`, improper TTL, contract panics -- **Extensible**: Load external detector libraries, CI/CD ready - -#### Certora Sunbeam Prover -Formal verification for Soroban — first WASM platform supported by Certora. -- **Docs**: https://docs.certora.com/en/latest/docs/sunbeam/index.html -- **Spec Language**: CVLR (Rust macros) — https://github.com/Certora/cvlr -- **Reports**: [Blend V1 verification](https://www.certora.com/reports/blend-smart-contract-verification-report) -- **Verifies at**: WASM bytecode level, eliminating compiler trust assumptions - -#### Runtime Verification — Komet -Formal verification and testing tool designed for Soroban (SCF-funded). -- **Docs**: https://docs.runtimeverification.com/komet -- **Repo**: https://github.com/runtimeverification/komet -- **Spec Language**: Rust — property-based tests written in the same language as Soroban contracts -- **Operates at**: WASM bytecode level via [KWasm semantics](https://github.com/runtimeverification/wasm-semantics) (eliminates compiler trust assumptions) -- **Features**: Fuzzing, testing, formal verification -- **Reports**: https://github.com/runtimeverification/publications -- **Example**: [TokenOps audit and verification report](https://github.com/runtimeverification/publications/blob/main/reports/smart-contracts/TokenOps.pdf) -- **Blog**: [Introducing Komet](https://runtimeverification.com/blog/introducing-komet-smart-contract-testing-and-verification-tool-for-soroban-created-by-runtime-verification) - -#### Soroban Security Portal (Inferara) -Community security knowledge base (SCF-funded). -- **Website**: https://sorobansecurity.com -- **Features**: Searchable audit reports, vulnerability database, best practices - -### CLI & SDKs - -#### Stellar CLI -Official command-line interface for Stellar/Soroban. -- **Docs**: https://developers.stellar.org/docs/tools/stellar-cli -- **Features**: Contract build, deploy, invoke, bindings generation - -#### Stellar SDK (JavaScript) -Official JavaScript/TypeScript SDK. -- **GitHub**: https://github.com/stellar/js-stellar-sdk -- **npm**: `@stellar/stellar-sdk` - -#### Soroban Rust SDK -Rust SDK for Soroban contract development. -- **GitHub**: https://github.com/stellar/rs-soroban-sdk -- **Crate**: `soroban-sdk` - -## Oracles - -#### Reflector Network -Community-powered price oracle for Stellar. -- **Website**: https://reflector.network -- **Docs**: https://developers.stellar.org/docs/data/oracles/oracle-providers -- **Features**: SEP-40 compatible, on-chain/off-chain prices, webhooks -- **Integrations**: Blend, OrbitCDP, DeFindex, EquitX, Slender - -#### DIA Oracle -Cross-chain oracle with 20,000+ asset support. -- **Website**: https://diadata.org -- **Blog**: https://www.diadata.org/blog/post/soroban-stellar-oracle-dia/ -- **Features**: VWAPIR methodology, custom feeds - -#### Band Protocol -Cross-chain data oracle on BandChain. -- **Website**: https://bandprotocol.com -- **Architecture**: Cosmos SDK-based, cross-chain - -## Gaming & NFTs - -#### Litemint -NFT marketplace and gaming platform. -- **GitHub**: https://github.com/litemint/litemint-soroban-contracts -- **Contracts**: Timed auctions, royalty payments -- **Features**: Open/sealed bids, ascending/descending price, buy-now - -## Infrastructure - -### Anchors & On/Off Ramps - -#### Stellar Ramps -Suite of open standards for fiat-crypto bridges. -- **Docs**: https://stellar.org/use-cases/ramps -- **SEPs**: SEP-6, SEP-24, SEP-31 (deposits/withdrawals/cross-border) - -#### Anchor Platform -SDF-maintained platform for building SEP-compliant anchors. -- **Docs**: https://developers.stellar.org/docs/learn/fundamentals/anchors -- **GitHub**: https://github.com/stellar/java-stellar-anchor-sdk - -### Block Explorers - -#### StellarExpert -Comprehensive network explorer with analytics. -- **Website**: https://stellar.expert -- **Features**: Transactions, accounts, assets, contracts - -#### Stellar Lab -Developer tools and transaction builder. -- **Website**: https://lab.stellar.org - -#### StellarChain -Alternative explorer with contract support. -- **Website**: https://stellarchain.io - -### Disbursements - -#### Stellar Disbursement Platform (SDP) -Bulk payment infrastructure for enterprises. -- **Docs**: https://developers.stellar.org/docs/category/use-the-stellar-disbursement-platform -- **GitHub**: https://github.com/stellar/stellar-disbursement-platform -- **Use Case**: Mass payments, aid distribution, payroll - -## Example Repositories - -### Official Examples - -#### Soroban Examples -Official educational smart contract examples. -- **GitHub**: https://github.com/stellar/soroban-examples -- **Includes**: Tokens, atomic swaps, auth, events, liquidity pools, timelock, deployer, merkle distribution - -#### Soroban Example dApp -Crowdfunding dApp with Next.js frontend. -- **GitHub**: https://github.com/stellar/soroban-example-dapp -- **Learning**: Full-stack Soroban development, Freighter integration - -### Community Examples - -#### Soroban Guide (Xycloo) -Learning resources and example contracts. -- **GitHub**: https://github.com/xycloo/soroban-guide -- **Includes**: Events, rock-paper-scissors, vaults, Dutch auctions - -#### Soroban Contracts (icolomina) -Governance and investment contract examples. -- **GitHub**: https://github.com/icolomina/soroban-contracts -- **Includes**: Ballot voting, investment contracts, multisig - -#### Oracle Example -Publisher-subscriber oracle pattern. -- **GitHub**: https://github.com/FredericRezeau/soroban-oracle-example -- **Uses**: soroban-kit oracle module - -#### OZ Stellar NFT -Simple NFT using OpenZeppelin. -- **GitHub**: https://github.com/jamesbachini/OZ-Stellar-NFT - -## Cross-Chain - -#### Axelar -Cross-chain gateway and Interchain Token Service for Soroban. -- **GitHub**: https://github.com/axelarnetwork/axelar-amplifier-stellar -- **Use Case**: Cross-chain messaging, token bridging, interoperability -- **Status**: Active development (verify latest activity before integrating) - -#### Allbridge Core -Cross-chain stable swap bridge (Stellar is 10th supported chain). -- **Use Case**: Cross-chain stablecoin transfers (USDC between Stellar, Base, Arbitrum, etc.) -- **Features**: Automatic Stellar account activation, liquidity pools - -#### LayerZero -Omnichain interoperability protocol with Stellar support. -- **Use Case**: Cross-chain messaging, token bridging (OFT/ONFT), dApp interoperability -- **Features**: OApp standard, Omni-Chain Fungible Tokens, native issuer minting/burning control - -## Builder Teams & Companies - -Notable teams shipping production-level code on Stellar/Soroban. For a broader directory, see [Stellar Ecosystem](https://stellar.org/ecosystem). - -| Team | Website | GitHub | X/Twitter | Notable Projects | -|------|---------|--------|-----------|-----------------| -| **Lightsail Network** | [lightsail.network](https://lightsail.network) | [lightsail-network](https://github.com/lightsail-network) | [@overcat_me](https://x.com/overcat_me) | Quasar RPC, Java/Python SDKs, Ledger app, validators | -| **PaltaLabs** | [paltalabs.io](https://paltalabs.io) | [paltalabs](https://github.com/paltalabs) | [@PaltaLabs](https://x.com/PaltaLabs) | Soroswap, DeFindex | -| **Aha Labs** | [ahalabs.dev](https://ahalabs.dev) | [AhaLabs](https://github.com/AhaLabs) | [@AhaLabsDev](https://x.com/AhaLabsDev) | Scaffold Stellar, Soroban CLI contributions | -| **OpenZeppelin** | [openzeppelin.com](https://www.openzeppelin.com/networks/stellar) | [OpenZeppelin](https://github.com/OpenZeppelin/stellar-contracts) | [@OpenZeppelin](https://x.com/OpenZeppelin) | Contracts library, Relayer, Monitor, Security Detectors SDK | -| **Cheesecake Labs** | [cheesecakelabs.com](https://cheesecakelabs.com) | [CheesecakeLabs](https://github.com/CheesecakeLabs) | [@CheesecakeLabs](https://x.com/CheesecakeLabs) | Stellar Plus library | -| **Script3 / Blend Capital** | [script3.io](https://script3.io) | [script3](https://github.com/script3), [blend-capital](https://github.com/blend-capital) | [@script3official](https://x.com/script3official) | Blend Protocol | -| **Xycloo Labs** | [xycloo.com](https://xycloo.com) | [Xycloo](https://github.com/Xycloo) | [@heytdep](https://x.com/heytdep) | Mercury indexer, Zephyr VM | -| **CoinFabrik** | [coinfabrik.com](https://www.coinfabrik.com) | [CoinFabrik](https://github.com/CoinFabrik) | [@coinfabrik](https://x.com/coinfabrik) | Scout Soroban (static analysis) | -| **Creit Tech** | [creit.tech](https://creit.tech) | [Creit-Tech](https://github.com/Creit-Tech) | [@CreitTech_](https://x.com/CreitTech_) | Stellar Wallets Kit, xBull, SorobanHub | -| **Ultra Stellar** | [ultrastellar.com](https://ultrastellar.com) | [lobstrco](https://github.com/lobstrco) | [@Lobstrco](https://x.com/Lobstrco) | LOBSTR wallet, StellarExpert | - -## Project Directories - -### Official Directories - -#### Stellar Ecosystem Directory -The canonical, up-to-date project directory maintained by SDF. -- **Website**: https://stellar.org/ecosystem -- **Features**: Search by country, asset, category -- **Includes**: DeFi, wallets, anchors, on/off ramps, exchanges, infrastructure - -#### SCF Project Tracker -All Stellar Community Fund–funded projects with status and milestones. -- **Website**: https://communityfund.stellar.org/projects - -### Funding Programs - -#### Stellar Community Fund (SCF) -Grants up to $150K per funding round. -- **Website**: https://communityfund.stellar.org -- **Funded**: 100+ projects across DeFi, NFT, GameFi, Web3 - -#### Soroban Audit Bank -Security audit funding for SCF projects. -- **Website**: https://stellar.org/grants-and-funding/soroban-audit-bank -- **Features**: Pre-negotiated audit rates, readiness checklist - -## Real-World Assets - -### Major Issuers on Stellar -- **Franklin Templeton**: Regulated fund tokens -- **Ondo**: Tokenized real estate -- **RedSwan**: $100M commercial real estate -- **Centrifuge**: Yield-generating tokens -- **WisdomTree**: Asset-backed tokens - -### Stablecoins -- **USDC** (Circle): Primary USD stablecoin -- **EURC** (Circle): EUR stablecoin -- **PYUSD** (PayPal): Verify current issuance and distribution details before launch planning - -## Enterprise Integrations - -Major companies building on Stellar: -- **PayPal**: PYUSD stablecoin -- **Visa**: Settlement infrastructure -- **Mastercard**: Payment rails -- **Wirex**: USDC/EURC settlement -- **U.S. Bank**: Custom stablecoin testing -- **PwC**: Stablecoin exploration diff --git a/skill/mpp.md b/skill/mpp.md deleted file mode 100644 index 6ccd66d..0000000 --- a/skill/mpp.md +++ /dev/null @@ -1,254 +0,0 @@ -# MPP (Machine Payments Protocol) on Stellar - -## When to use MPP -MPP is the right choice when: -- You want **no facilitator dependency** — payments settle directly on Stellar via Soroban SAC transfers -- Your AI agent makes **many requests per session** — use channel mode to pay off-chain and settle once -- You're building a Stellar-native payment stack without relying on third-party infrastructure - -Two modes: - -| Mode | On-chain txs | Best for | -|------|-------------|----------| -| **Charge** | One per request | Per-request payments, no pre-funding required | -| **Channel** | One deposit + one close | High-frequency agents (100s of requests/session) | - -If you need zero-XLM clients or the simplest possible setup, use [x402](x402.md) instead. - -## Charge mode: per-request payments - -Each request triggers a Soroban SAC token transfer settled on-chain. No facilitator. Server can optionally sponsor fees so clients don't need XLM. - -```bash -npm install express @stellar/mpp mppx @stellar/stellar-sdk dotenv -npm pkg set type=module -``` - -**Server:** - -```js -// charge-server.js -import express from "express"; -import { Mppx } from "mppx"; -import * as stellar from "@stellar/mpp/charge/server"; -import * as StellarSdk from "@stellar/stellar-sdk"; - -const USDC_SAC_TESTNET = "CBIELTK6YBZJU5UP2WWQEUCYKLPU6AUNZ2BQ4WWFEIE3USCIHMXQDAMA"; -const RECIPIENT = process.env.STELLAR_RECIPIENT; // G... address - -const mppx = Mppx.create({ - secretKey: process.env.MPP_SECRET_KEY, // shared secret for credential verification - methods: [ - stellar.charge({ - recipient: RECIPIENT, - currency: USDC_SAC_TESTNET, - network: "stellar:testnet", - // optional: server pays network fees so clients don't need XLM - feePayer: process.env.FEE_PAYER_SECRET - ? { envelopeSigner: StellarSdk.Keypair.fromSecret(process.env.FEE_PAYER_SECRET) } - : undefined, - }), - ], -}); - -const app = express(); -app.use(express.json()); - -// mppx middleware: returns 402 with challenge, then validates payment on retry -app.use(mppx.middleware()); - -app.get("/data", (req, res) => { - res.json({ result: "paid content", price: "$0.001 USDC" }); -}); - -app.listen(3002, () => console.log("MPP charge server on http://localhost:3002")); -``` - -**Client:** - -```js -// charge-client.js -import { Mppx } from "mppx"; -import * as stellar from "@stellar/mpp/charge/client"; -import * as StellarSdk from "@stellar/stellar-sdk"; - -const keypair = StellarSdk.Keypair.fromSecret(process.env.STELLAR_SECRET_KEY); - -const mppx = Mppx.create({ - methods: [ - stellar.charge({ - keypair, - mode: "pull", // server assembles and broadcasts the transaction - onProgress(event) { - // event.type: "challenge" | "signed" | "settled" - if (event.type === "settled") console.log("Settled:", event.txHash); - }, - }), - ], -}); - -// mppx wraps fetch — 402 handling is transparent -const res = await mppx.fetch("http://localhost:3002/data"); -console.log(await res.json()); -``` - -**Env vars (server):** `STELLAR_RECIPIENT`, `MPP_SECRET_KEY`, `FEE_PAYER_SECRET` (optional) -**Env vars (client):** `STELLAR_SECRET_KEY` - -**`mode: "pull"` vs `"push"`:** -- `"pull"` — client signs auth entries, server assembles + broadcasts (default; use with `feePayer`) -- `"push"` — client builds and broadcasts the transaction directly (client must have XLM for fees) - -## Channel mode: high-frequency off-chain payments - -The client deploys a one-way payment channel contract, deposits USDC once, then signs **cumulative commitments** off-chain for each request. No transaction per request — only two on-chain txs total (deposit + close). Ideal for AI agents making hundreds of calls in a session. - -### Channel lifecycle - -``` -1. Deploy channel contract (one-time) → C... contract address -2. Client deposits USDC into channel → on-chain tx -3. Per request: client signs commitment → off-chain (just a signature) - Amount is cumulative: each sig covers all previous payments + this one -4. Server closes channel when done → on-chain tx, settles total -``` - -### Prerequisites - -- Deploy a one-way-channel Soroban contract to get a `C...` contract address -- Generate an ed25519 keypair for commitment signing (see [stellar-mpp SDK](https://github.com/stellar/stellar-mpp-sdk)) -- Fund the channel with USDC before making requests - -### Server: - -```js -// channel-server.js -import express from "express"; -import { Mppx, Store } from "mppx"; -import * as stellar from "@stellar/mpp/channel/server"; - -const mppx = Mppx.create({ - secretKey: process.env.MPP_SECRET_KEY, - methods: [ - stellar.channel({ - channel: process.env.CHANNEL_CONTRACT, // C... contract address - commitmentKey: process.env.COMMITMENT_PUBKEY, // 64-char hex ed25519 public key - store: Store.memory(), // dev only — use persistent store in production - network: "stellar:testnet", - }), - ], -}); - -const app = express(); -app.use(express.json()); -app.use(mppx.middleware()); - -app.get("/data", (req, res) => { - res.json({ result: "paid content" }); -}); - -app.listen(3003); -``` - -### Client: - -```js -// channel-client.js -import { Mppx } from "mppx"; -import * as stellar from "@stellar/mpp/channel/client"; -import * as StellarSdk from "@stellar/stellar-sdk"; - -// commitment key must be a raw ed25519 seed — NOT a standard Stellar secret key -const commitmentKey = StellarSdk.Keypair.fromRawEd25519Seed( - Buffer.from(process.env.COMMITMENT_SECRET, "hex") // 64-char hex secret -); - -const mppx = Mppx.create({ - methods: [ - stellar.channel({ - commitmentKey, - onProgress(event) { - // event.type: "challenge" | "signed" - }, - }), - ], -}); - -// Make many requests — each signs a cumulative off-chain commitment -for (let i = 0; i < 100; i++) { - const res = await mppx.fetch("http://localhost:3003/data"); - console.log(i, await res.json()); -} -``` - -### Closing the channel (server-initiated): - -```js -import { close } from "@stellar/mpp/channel/server"; -import * as StellarSdk from "@stellar/stellar-sdk"; - -const txHash = await close({ - channel: process.env.CHANNEL_CONTRACT, - amount: lastCumulativeAmount, // bigint, total USDC owed in base units - signature: lastCommitmentSignature, // hex string from final commitment - feePayer: { envelopeSigner: StellarSdk.Keypair.fromSecret(process.env.FEE_PAYER_SECRET) }, - network: "stellar:testnet", -}); -// Single on-chain transaction settles the full session -console.log("Channel closed:", txHash); -``` - -**Env vars (server):** `CHANNEL_CONTRACT`, `COMMITMENT_PUBKEY`, `MPP_SECRET_KEY`, `FEE_PAYER_SECRET` -**Env vars (client):** `COMMITMENT_SECRET` - -## Packages and subpath imports - -```bash -npm install @stellar/mpp mppx @stellar/stellar-sdk -``` - -| Import path | Recommended import pattern | -|-------------|----------------------------| -| `@stellar/mpp/charge/server` | `import * as stellar from "@stellar/mpp/charge/server"` — use `stellar.charge(...)` | -| `@stellar/mpp/charge/client` | `import * as stellar from "@stellar/mpp/charge/client"` — use `stellar.charge(...)` | -| `@stellar/mpp/channel/server` | `import * as stellar from "@stellar/mpp/channel/server"` — use `stellar.channel(...)`, `stellar.close(...)`, `stellar.getChannelState(...)`, `stellar.watchChannel(...)` | -| `@stellar/mpp/channel/client` | `import * as stellar from "@stellar/mpp/channel/client"` — use `stellar.channel(...)` | -| `@stellar/mpp/channel` | Zod schema definitions for channel types | -| `mppx` | `import { Mppx, Store } from "mppx"` | - -## Testnet runbook - -**Steps shared with all protocols:** -1. Generate keypair + fund with Friendbot (see [x402.md testnet runbook](x402.md)) -2. Add USDC trustline -3. Get testnet USDC from [Circle faucet](https://faucet.circle.com/) - -**Channel mode only:** -4. Deploy the one-way-channel contract (see [stellar-mpp-sdk](https://github.com/stellar/stellar-mpp-sdk) for deploy script) -5. Generate a 64-char hex ed25519 seed for the commitment key: - ```bash - node -e "console.log(require('crypto').randomBytes(32).toString('hex'))" - ``` -6. Derive the public key and fund the channel with USDC before making requests - -## Common pitfalls - -**Channel: wrong commitment key format** -- Symptom: `Keypair.fromRawEd25519Seed` throws or signatures fail to verify -- Fix: the commitment key is a raw ed25519 seed as a 64-char hex string — not a Stellar `S...` secret key. Generate with `crypto.randomBytes(32).toString('hex')`. - -**Channel: non-cumulative amounts** -- Symptom: server rejects commitments after the first request -- Fix: each commitment's `amount` must be the **running total** of all payments so far, not just the price of the current request. The server tracks the highest-seen commitment. - -**Channel: deposit TTL expired** -- Symptom: `close()` fails or channel appears drained -- Fix: Soroban contract storage has a TTL. Close the channel before it expires, or extend storage TTL via `bumpContractInstance`. Don't leave channels open indefinitely. - -**Charge: client has no XLM for fees** -- Symptom: `op_insufficient_balance` or fee errors on client-submitted transactions -- Fix: set `mode: "pull"` on the client and configure `feePayer` on the server so the server pays fees. The client only signs auth entries. - -**`Store.memory()` in production** -- Symptom: server loses track of channel state on restart, enables double-spend -- Fix: replace `Store.memory()` with a persistent store (database-backed) before going to production. diff --git a/skill/resources.md b/skill/resources.md deleted file mode 100644 index 7287c90..0000000 --- a/skill/resources.md +++ /dev/null @@ -1,306 +0,0 @@ -# Curated Resources (Source-of-Truth First) - -## Official Documentation - -### Stellar Developer Docs -- [Stellar Documentation](https://developers.stellar.org/docs) - Primary documentation -- [Build Smart Contracts](https://developers.stellar.org/docs/build/smart-contracts) - Soroban guides -- [Build Apps](https://developers.stellar.org/docs/build/apps) - Client application guides -- [Tools & SDKs](https://developers.stellar.org/docs/tools) - Available tooling -- [Networks](https://developers.stellar.org/docs/networks) - Network configuration -- [Learn Fundamentals](https://developers.stellar.org/docs/learn/fundamentals) - Core concepts -- [Security Best Practices](https://developers.stellar.org/docs/build/security-docs) - -### API References -- [Stellar RPC Methods](https://developers.stellar.org/docs/data/apis/rpc/api-reference/methods) - RPC API -- [Horizon API](https://developers.stellar.org/docs/data/apis/horizon/api-reference) - REST API (legacy-focused) -- [Oracle Providers](https://developers.stellar.org/docs/data/oracles/oracle-providers) - -## SDKs - -### Client SDKs (Application Development) -- [JavaScript SDK](https://github.com/stellar/js-stellar-sdk) - `@stellar/stellar-sdk` -- [Python SDK](https://github.com/StellarCN/py-stellar-base) - `stellar-sdk` -- [Java SDK](https://github.com/lightsail-network/java-stellar-sdk) - `network.lightsail:stellar-sdk` (Lightsail Network) -- [Go SDK](https://github.com/stellar/go-stellar-sdk) - `txnbuild`, Horizon & RPC clients -- [Rust SDK (RPC Client)](https://github.com/stellar/rs-stellar-rpc-client) -- [SDK Documentation](https://developers.stellar.org/docs/tools/sdks/client-sdks) - -### Contract SDK (Soroban Development) -- [Soroban Rust SDK](https://github.com/stellar/rs-soroban-sdk) - `soroban-sdk` -- [Soroban SDK Docs](https://docs.rs/soroban-sdk/latest/soroban_sdk/) - Rust docs - -## CLI Tools - -### Stellar CLI -- [Stellar CLI Repository](https://github.com/stellar/stellar-cli) -- [CLI Installation](https://developers.stellar.org/docs/tools/stellar-cli) -- [CLI Commands Reference](https://developers.stellar.org/docs/tools/stellar-cli/stellar-cli-commands) - -### Scaffold Stellar -- [Scaffold Stellar](https://scaffoldstellar.org) - Full-stack dApp scaffolding (contracts + React/Vite/TS frontend) -- [Scaffold Docs](https://developers.stellar.org/docs/tools/scaffold-stellar) - Official documentation -- [GitHub](https://github.com/theahaco/scaffold-stellar) - Open source (Apache 2.0) - -### Quickstart (Local Development) -- [Quickstart Docker](https://github.com/stellar/quickstart) -- [Quickstart Guide](https://developers.stellar.org/docs/tools/quickstart) - -## Contract Libraries & Tools - -### OpenZeppelin Stellar Contracts -- [OpenZeppelin Contracts](https://github.com/OpenZeppelin/stellar-contracts) -- [Documentation](https://developers.stellar.org/docs/tools/openzeppelin-contracts) -- [Contract Wizard](https://wizard.openzeppelin.com/stellar) - Generate contracts - -### Smart Account SDKs -- [Smart Account Kit](https://github.com/kalepail/smart-account-kit) - Production smart wallet SDK (recommended) -- [Passkey Kit](https://github.com/kalepail/passkey-kit) - Legacy passkey wallet SDK -- [Super Peach](https://github.com/kalepail/superpeach) - Smart wallet implementation example - -### Developer Tools -- [Stellar Wallets Kit](https://github.com/Creit-Tech/Stellar-Wallets-Kit) - Multi-wallet integration -- [OpenZeppelin Relayer](https://docs.openzeppelin.com/relayer) - Fee-sponsored transactions - -## Example Repositories - -### Official Examples -- [Soroban Examples](https://github.com/stellar/soroban-examples) - Core contract patterns -- [Soroban Example dApp](https://github.com/stellar/soroban-example-dapp) - Crowdfunding Next.js app -- [Stellar Repositories](https://github.com/orgs/stellar/repositories) - -### Community Examples -- [Scout Soroban Examples](https://github.com/CoinFabrik/scout-soroban-examples) - Security-audited examples -- [Soroban Guide (Xycloo)](https://github.com/xycloo/soroban-guide) - Learning resources -- [Soroban Contracts (icolomina)](https://github.com/icolomina/soroban-contracts) - Governance examples -- [Oracle Example](https://github.com/FredericRezeau/soroban-oracle-example) - Pub-sub oracle pattern -- [OZ Stellar NFT](https://github.com/jamesbachini/OZ-Stellar-NFT) - Simple NFT with OpenZeppelin - -## Ecosystem Projects - -For DeFi protocols, wallets, oracles, gaming/NFTs, cross-chain bridges, and builder teams, see [ecosystem.md](ecosystem.md). - -## Security - -For vulnerability patterns, checklists, and detailed tooling guides, see [security.md](security.md). - -### Bug Bounty Programs -- [Stellar Bug Bounty (Immunefi)](https://immunefi.com/bug-bounty/stellar/) - Up to $250K, covers core + Soroban -- [OpenZeppelin Stellar Bounty (Immunefi)](https://immunefi.com/bug-bounty/openzeppelin-stellar/) - Up to $25K -- [HackerOne VDP](https://stellar.org/grants-and-funding/bug-bounty) - Web application vulnerabilities - -### Audit Bank & Audit Firms -- [Soroban Audit Bank](https://stellar.org/grants-and-funding/soroban-audit-bank) - $3M+ deployed, 43+ audits -- [Audited Projects List](https://stellar.org/audit-bank/projects) - Public audit registry -- Partners: OtterSec, Veridise, Runtime Verification, CoinFabrik, QuarksLab, Coinspect, Certora, Halborn, Zellic, Code4rena - -### Static Analysis -- [Scout Soroban](https://github.com/CoinFabrik/scout-soroban) - 23 vulnerability detectors, VSCode extension -- [OZ Security Detectors SDK](https://github.com/OpenZeppelin/soroban-security-detectors-sdk) - Custom detector framework - -### Formal Verification -- [Certora Sunbeam Prover](https://docs.certora.com/en/latest/docs/sunbeam/index.html) - WASM-level formal verification -- [CVLR Spec Language](https://github.com/Certora/cvlr) - Certora Verification Language for Rust -- [Runtime Verification Komet](https://runtimeverification.com/blog/introducing-komet-smart-contract-testing-and-verification-tool-for-soroban-created-by-runtime-verification) - Soroban verification tool - -### Security Resources -- [Veridise Security Checklist](https://veridise.com/blog/audit-insights/building-on-stellar-soroban-grab-this-security-checklist-to-avoid-vulnerabilities/) - Soroban-specific -- [Soroban Security Portal](https://sorobansecurity.com) - Community vulnerability database -- [CoinFabrik Audit Reports](https://www.coinfabrik.com/smart-contract-audit-reports/) -- [Certora Security Reports](https://github.com/Certora/SecurityReports) - Includes Stellar verifications - -## Zero-Knowledge Proofs (Status-Sensitive) - -For comprehensive ZK development guidance, see [zk-proofs.md](zk-proofs.md). - -Always verify CAP status and network support before treating any ZK primitive as production-available. - -### Protocol & Specifications -- [Protocol upgrades](https://stellar.org/protocol-upgrades) - Upgrade timeline and network context -- [CAP-0074](https://github.com/stellar/stellar-protocol/blob/master/core/cap-0074.md) - BN254 host functions proposal -- [CAP-0075](https://github.com/stellar/stellar-protocol/blob/master/core/cap-0075.md) - Poseidon/Poseidon2 host functions proposal - -### SDK Documentation -- [Soroban SDK BN254 module](https://docs.rs/soroban-sdk/latest/soroban_sdk/crypto/bn254/) - Verify availability in your pinned SDK version -- [Soroban SDK Crypto](https://docs.rs/soroban-sdk/latest/soroban_sdk/crypto/) - Full crypto module reference - -### Proving Systems & Tooling -- [Noir Documentation](https://noir-lang.org/docs/) - Aztec's ZK domain-specific language -- [RISC Zero](https://dev.risczero.com/) - General-purpose zkVM for Rust programs - -### Example Contracts -- [Soroban Examples](https://github.com/stellar/soroban-examples) - Official examples (includes `groth16_verifier`, `privacy-pools`, `import_ark_bn254`) - -## Testing - -### Testing Guides -- [Definitive Guide to Testing Smart Contracts](https://stellar.org/blog/developers/the-definitive-guide-to-testing-smart-contracts-on-stellar) - Comprehensive overview -- [Fuzzing Guide](https://developers.stellar.org/docs/build/guides/testing/fuzzing) - cargo-fuzz + SorobanArbitrary -- [Fuzzing Example Contract](https://developers.stellar.org/docs/build/smart-contracts/example-contracts/fuzzing) -- [Differential Testing](https://developers.stellar.org/docs/build/guides/testing/differential-tests-with-test-snapshots) - Automatic test snapshots -- [Fork Testing](https://developers.stellar.org/docs/build/guides/testing/fork-testing) - Test against production state -- [Mutation Testing](https://developers.stellar.org/docs/build/guides/testing/mutation-testing) - cargo-mutants - -### Local Development -- [Stellar Quickstart](https://github.com/stellar/quickstart) -- [Docker Setup](https://developers.stellar.org/docs/tools/quickstart) - -### Test Networks -- [Testnet Info](https://developers.stellar.org/docs/networks/testnet) -- [Friendbot](https://friendbot.stellar.org) - Testnet faucet - -## Data & Analytics - -### Data Documentation Hub -- [Stellar Data Overview](https://developers.stellar.org/docs/data) - Choose the right tool (APIs, indexers, analytics, oracles) -- [Indexer Directory](https://developers.stellar.org/docs/data/indexers) - All supported indexers -- [RPC Provider Directory](https://developers.stellar.org/docs/data/apis/rpc/providers) - All RPC infrastructure providers - -### Block Explorers -- [StellarExpert](https://stellar.expert) - Network explorer & analytics -- [StellarExpert API](https://stellar.expert/openapi.html) - Free REST API (no auth, CORS-enabled) -- [Stellar Lab](https://lab.stellar.org) - Developer tools -- [StellarChain](https://stellarchain.io) - Alternative explorer - -### Data Indexers -- [Mercury](https://mercurydata.app) - Stellar-native indexer with Retroshades + GraphQL ([docs](https://docs.mercurydata.app)) -- [SubQuery](https://subquery.network) - Multi-chain indexer with Stellar/Soroban support ([quick start](https://subquery.network/doc/indexer/quickstart/quickstart_chains/stellar.html)) -- [Goldsky](https://goldsky.com) - Real-time data replication pipelines + subgraphs ([Stellar docs](https://docs.goldsky.com/chains/stellar)) -- [Zephyr VM](https://github.com/xycloo/zephyr-vm) - Serverless Rust execution at ledger close - -### Historical Data & Analytics -- [Hubble](https://developers.stellar.org/docs/data/analytics/hubble) - BigQuery dataset (updated every 30 min) -- [Galexie](https://developers.stellar.org/docs/data/indexers/build-your-own/galexie) - Data pipeline for building data lakes -- [Data Lake](https://developers.stellar.org/docs/data/apis/rpc/admin-guide/data-lake-integration) - Powers RPC Infinite Scroll (public via AWS Open Data) - -## Infrastructure - -### Anchors & On/Off Ramps -- [Anchor Platform](https://github.com/stellar/java-stellar-anchor-sdk) -- [Anchor Docs](https://developers.stellar.org/docs/category/anchor-platform) -- [Anchor Fundamentals](https://developers.stellar.org/docs/learn/fundamentals/anchors) -- [Stellar Ramps](https://stellar.org/use-cases/ramps) - -### Disbursements -- [Stellar Disbursement Platform](https://github.com/stellar/stellar-disbursement-platform) -- [SDP Documentation](https://developers.stellar.org/docs/category/use-the-stellar-disbursement-platform) - -### RPC Providers -- [RPC Provider Directory](https://developers.stellar.org/docs/data/apis/rpc/providers) - Full list of providers -- [Quasar (Lightsail Network)](https://quasar.lightsail.network) - Stellar-native RPC, Archive RPC, hosted Galexie Data Lake -- [Blockdaemon](https://www.blockdaemon.com/soroban) - Enterprise RPC -- [Validation Cloud](https://www.validationcloud.io) - Testnet & Mainnet -- [QuickNode](https://www.quicknode.com) - Testnet, Mainnet & Dedicated -- [Ankr](https://www.ankr.com) - Testnet & Mainnet -- [NOWNodes](https://nownodes.io) - All networks incl. Futurenet -- [GetBlock](https://getblock.io) - Testnet & Mainnet - -## Protocol & Governance - -### Stellar Protocol -- [Stellar Protocol Repo](https://github.com/stellar/stellar-protocol) -- [CAPs](https://github.com/stellar/stellar-protocol/tree/master/core) - Core Advancement Proposals -- [SEPs](https://github.com/stellar/stellar-protocol/tree/master/ecosystem) - Stellar Ecosystem Proposals - -### Key SEP Standards -- [SEP-0001](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0001.md) - stellar.toml -- [SEP-0010](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0010.md) - Web Authentication -- [SEP-0024](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0024.md) - Hosted Deposit/Withdrawal -- [SEP-0030](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0030.md) - Account Recovery -- [SEP-0031](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0031.md) - Cross-Border Payments -- [SEP-0041](https://developers.stellar.org/docs/tokens/token-interface) - Token Interface -- [SEP-0045](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0045.md) - Web Auth for Contract Accounts (Draft) -- [SEP-0046](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0046.md) - Contract Meta (Active) -- [SEP-0048](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0048.md) - Contract Interface Specification (Active) -- [SEP-0050](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0050.md) - Non-Fungible Tokens (Draft) -- [SEP-0056](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0056.md) - Tokenized Vault Standard (Draft, ERC-4626 equivalent) - -### Network Upgrades -- [Protocol Upgrades](https://stellar.org/protocol-upgrades) -- [SDF Blog](https://stellar.org/blog) - -## Project Directories & Funding - -### Ecosystem Discovery -- [Stellar Ecosystem](https://stellar.org/ecosystem) - Official project directory -- [Stellar Community Fund Projects](https://communityfund.stellar.org/projects) - -### Funding Programs -- [Stellar Community Fund](https://communityfund.stellar.org) - Grants up to $150K -- [Soroban Audit Bank](https://stellar.org/grants-and-funding/soroban-audit-bank) -- [$100M Soroban Adoption Fund](https://stellar.org/soroban) - -## Learning Resources - -### Official Tutorials -- [Getting Started](https://developers.stellar.org/docs/build/smart-contracts/getting-started) -- [Hello World Contract](https://developers.stellar.org/docs/build/smart-contracts/getting-started/hello-world) -- [Deploy to Testnet](https://developers.stellar.org/docs/build/smart-contracts/getting-started/deploy-to-testnet) -- [TypeScript Bindings](https://developers.stellar.org/docs/build/apps/guestbook/bindings) -- [Passkey Prerequisites](https://developers.stellar.org/docs/build/apps/guestbook/passkeys-prerequisites) - -### Video Content -- [Stellar YouTube](https://www.youtube.com/@StellarDevelopmentFoundation) -- [Learn Rust for Smart Contracts (DAO Series)](https://www.youtube.com/watch?v=VeQM5N-0DrI) -- [Call Option Contract Walkthrough](https://www.youtube.com/watch?v=Z8FHVllP_D0) -- [Blend Protocol Tutorial](https://www.youtube.com/watch?v=58j0QkXKiDU) - -### Developer Tools -- [Stella AI Bot](https://developers.stellar.org/docs/tools/developer-tools) - AI assistant for Stellar developer questions -- [Soroban Playground](https://soropg.com) - Browser-based Soroban IDE ([GitHub](https://github.com/jamesbachini/Soroban-Playground)) - -### Blog Posts & Guides -- [Composability on Stellar](https://stellar.org/blog/developers/composability-on-stellar-from-concept-to-reality) -- [Testing Smart Contracts Guide](https://stellar.org/blog/developers/the-definitive-guide-to-testing-smart-contracts-on-stellar) -- [Sorobounty Spectacular Tutorials](https://stellar.org/blog/developers/sorobounty-spectacular-dapp-tutorials) -- [Learn Soroban 1-2-3 (Community Tools)](https://stellar.org/blog/developers/learn-soroban-as-easy-as-1-2-3-with-community-made-tooling) -- [SCF Infrastructure Recap](https://stellar.org/blog/ecosystem/stellar-community-fund-recap-soroban-infrastructure) -- [Native vs Soroban Tokens](https://cheesecakelabs.com/blog/native-tokens-vs-soroban-tokens/) -- [57Blocks Integration Testing](https://57blocks.com/blog/soroban-integration-testing-best-practices) - -## Stablecoins on Stellar - -### Major Stablecoins -- [USDC on Stellar](https://www.circle.com/usdc/stellar) - Circle -- [EURC on Stellar](https://www.circle.com/en/eurc) - Circle -- PYUSD (PayPal) - Verify current issuer/distribution details before integration - -### Asset Discovery -- [StellarExpert Asset Directory](https://stellar.expert/explorer/public/asset) - -## Community - -### Developer Resources -- [Stellar Developers Discord](https://discord.gg/stellar) -- [Stellar Stack Exchange](https://stellar.stackexchange.com) -- [GitHub Discussions](https://github.com/stellar/stellar-protocol/discussions) - -### Key People to Follow - -Builders and contributors actively shaping the Stellar/Soroban ecosystem: - -| Name | GitHub | X/Twitter | Focus | -|------|--------|-----------|-------| -| Tyler van der Hoeven | [kalepail](https://github.com/kalepail) | [@kalepail](https://x.com/kalepail) | SDF DevRel, Smart Account Kit, Passkey Kit, Launchtube | -| Leigh McCulloch | [leighmcculloch](https://github.com/leighmcculloch) | [@___leigh___](https://x.com/___leigh___) | SDF core engineer, Stellar CLI, Soroban SDK | -| James Bachini | [jamesbachini](https://github.com/jamesbachini) | [@james_bachini](https://x.com/james_bachini) | SDF Dev in Residence, Soroban Playground, tutorials | -| Elliot Voris | [ElliotFriend](https://github.com/ElliotFriend) | [@ElliotFriend](https://x.com/ElliotFriend) | SDF DevRel, community education | -| Carsten Jacobsen | [carstenjacobsen](https://github.com/carstenjacobsen) | — | SDF, weekly dev meetings, Soroban examples | -| Esteban Iglesias | [esteblock](https://github.com/esteblock) | [@esteblock_dev](https://x.com/esteblock_dev) | PaltaLabs, Soroswap, DeFindex | -| Markus Paulson-Luna | [markuspluna](https://github.com/markuspluna) | [@script3official](https://x.com/script3official) | Script3, Blend Protocol | -| Alexander Mootz | [mootz12](https://github.com/mootz12) | — | Script3, Blend contracts | -| Tommaso | [heytdep](https://github.com/heytdep) | [@heytdep](https://x.com/heytdep) | Xycloo Labs, Mercury indexer, ZephyrVM | -| OrbitLens | [orbitlens](https://github.com/orbitlens) | [@orbitlens](https://x.com/orbitlens) | Reflector oracle, StellarExpert, Albedo | -| Frederic Rezeau | [FredericRezeau](https://github.com/FredericRezeau) | [@FredericRezeau](https://x.com/FredericRezeau) | Litemint, soroban-kit, gaming | -| Jun Luo (Overcat) | [overcat](https://github.com/overcat) | [@overcat_me](https://x.com/overcat_me) | Lightsail Network, Quasar RPC, Java/Python SDKs, Ledger app | -| Jay Geng | [jayz22](https://github.com/jayz22) | — | SDF, Soroban SDK, confidential tokens | -| Chad Ostrowski | [chadoh](https://github.com/chadoh) | [@chadoh](https://x.com/chadoh) | Aha Labs CEO, Scaffold Stellar, Soroban CLI | -| Willem Wyndham | [willemneal](https://github.com/willemneal) | [@willemneal](https://x.com/willemneal) | Aha Labs co-founder, Scaffold Stellar, JS contract client | - -### Builder Teams & Companies -See [ecosystem.md](ecosystem.md) for a table of teams shipping production code on Stellar/Soroban, with GitHub orgs, websites, and Twitter handles. - -### Foundation -- [Stellar Development Foundation](https://stellar.org/foundation) -- [Foundation Roadmap](https://stellar.org/foundation/roadmap) -- [Ecosystem Blog](https://stellar.org/blog/ecosystem) diff --git a/skill/security.md b/skill/security.md deleted file mode 100644 index bc0004d..0000000 --- a/skill/security.md +++ /dev/null @@ -1,491 +0,0 @@ -# Stellar Security Checklist (Soroban + Classic) - -## Core Principle - -Assume the attacker controls: -- All arguments passed to contract functions -- Transaction ordering and timing -- All accounts except those requiring signatures -- The ability to create contracts that mimic your interface - -## Soroban Security Advantages - -Soroban's architecture prevents certain vulnerability classes by design: - -### No Delegate Call -Unlike Ethereum, Soroban has no `delegatecall` equivalent. Contracts cannot execute arbitrary bytecode in their context, eliminating proxy-based attacks. - -### No Classical Reentrancy -Soroban's synchronous execution model prevents the cross-contract reentrancy that plagues Ethereum. Self-reentrancy is possible but rarely exploitable. - -### Explicit Authorization -Authorization is opt-in via `require_auth()`, making it explicit which operations need signatures. - ---- - -## Vulnerability Categories - -### 1. Missing Authorization Checks - -**Risk**: Anyone can call privileged functions without proper verification. - -**Attack**: Attacker calls admin-only functions, drains funds, or modifies critical state. - -**Vulnerable Code**: -```rust -// BAD: No authorization check -pub fn withdraw(env: Env, to: Address, amount: i128) { - transfer_tokens(&env, &to, amount); -} -``` - -**Secure Code**: -```rust -// GOOD: Requires authorization from admin -pub fn withdraw(env: Env, to: Address, amount: i128) { - let admin: Address = env.storage().instance().get(&DataKey::Admin).unwrap(); - admin.require_auth(); - transfer_tokens(&env, &to, amount); -} -``` - -**Prevention**: Always use `require_auth()` on the caller or an admin address. See [contracts-soroban.md](contracts-soroban.md) for full authorization patterns (direct auth, admin helpers, `require_auth_for_args`). - ---- - -### 2. Reinitialization Attacks - -**Risk**: Initialization function can be called multiple times, allowing attacker to overwrite admin or critical state. - -**Attack**: Attacker reinitializes contract to become the admin, then drains assets. - -**Vulnerable Code**: -```rust -// BAD: Can be called multiple times -pub fn initialize(env: Env, admin: Address) { - env.storage().instance().set(&DataKey::Admin, &admin); -} -``` - -**Secure Code**: -```rust -// GOOD: Prevents reinitialization -pub fn initialize(env: Env, admin: Address) { - if env.storage().instance().has(&DataKey::Initialized) { - panic!("already initialized"); - } - env.storage().instance().set(&DataKey::Admin, &admin); - env.storage().instance().set(&DataKey::Initialized, &true); -} - -// Alternative: Check for admin existence -pub fn initialize(env: Env, admin: Address) { - if env.storage().instance().has(&DataKey::Admin) { - panic!("already initialized"); - } - env.storage().instance().set(&DataKey::Admin, &admin); -} -``` - ---- - -### 3. Arbitrary Contract Calls - -**Risk**: Contract calls whatever address is passed as parameter without validation. - -**Attack**: Attacker passes malicious contract that mimics expected interface but behaves differently. - -**Vulnerable Code**: -```rust -// BAD: Calls any contract passed as parameter -pub fn swap(env: Env, token: Address, amount: i128) { - let client = token::Client::new(&env, &token); - client.transfer(...); // Could be malicious contract -} -``` - -**Secure Code**: -```rust -// GOOD: Validate against known allowlist -pub fn swap(env: Env, token: Address, amount: i128) { - let allowed_tokens: Vec
= env.storage() - .instance() - .get(&DataKey::AllowedTokens) - .unwrap(); - - if !allowed_tokens.contains(&token) { - panic!("token not allowed"); - } - - let client = token::Client::new(&env, &token); - client.transfer(...); -} - -// Or validate against Stellar Asset Contract -pub fn swap_sac(env: Env, asset: Address, amount: i128) { - // SACs have known, predictable addresses - // Verify it's a legitimate SAC if needed -} -``` - ---- - -### 4. Integer Overflow/Underflow - -**Risk**: Arithmetic operations overflow or underflow, causing unexpected values. - -**Attack**: Attacker manipulates amounts to cause overflow, bypassing balance checks. - -**Vulnerable Code**: -```rust -// BAD: Unchecked arithmetic -pub fn deposit(env: Env, user: Address, amount: i128) { - let balance: i128 = get_balance(&env, &user); - set_balance(&env, &user, balance + amount); // Can overflow -} -``` - -**Secure Code**: -```rust -// GOOD: Use checked arithmetic -pub fn deposit(env: Env, user: Address, amount: i128) { - let balance: i128 = get_balance(&env, &user); - let new_balance = balance.checked_add(amount) - .expect("overflow"); - set_balance(&env, &user, new_balance); -} - -// Also validate inputs -pub fn deposit(env: Env, user: Address, amount: i128) { - if amount <= 0 { - panic!("invalid amount"); - } - // ... rest of logic -} -``` - ---- - -### 5. Storage Key Collisions - -**Risk**: Different data types share the same storage key, causing data corruption. - -**Attack**: Attacker manipulates one type of data to corrupt another. - -**Vulnerable Code**: -```rust -// BAD: Same prefix for different data -env.storage().persistent().set(&symbol_short!("data"), &user_balance); -env.storage().persistent().set(&symbol_short!("data"), &config); // Overwrites! -``` - -**Secure Code**: -```rust -// GOOD: Use typed enum for keys -#[contracttype] -#[derive(Clone)] -pub enum DataKey { - Admin, - Balance(Address), - Config, - Allowance(Address, Address), -} - -env.storage().persistent().set(&DataKey::Balance(user), &balance); -env.storage().instance().set(&DataKey::Config, &config); -``` - ---- - -### 6. Timing/State Race Conditions - -**Risk**: Contract state changes between check and use. - -**Attack**: In multi-transaction scenarios, attacker exploits gap between validation and action. - -**Prevention**: -```rust -// Use atomic operations where possible -pub fn swap(env: Env, user: Address, amount_in: i128, min_out: i128) { - user.require_auth(); - - // Perform all checks and state changes atomically - let balance = get_balance(&env, &user); - if balance < amount_in { - panic!("insufficient balance"); - } - - let amount_out = calculate_output(amount_in); - if amount_out < min_out { - panic!("slippage exceeded"); - } - - // Update all state together - set_balance(&env, &user, balance - amount_in); - transfer_output(&env, &user, amount_out); -} -``` - ---- - -### 7. TTL/Archival Vulnerabilities - -**Risk**: Critical contract data gets archived, breaking functionality. - -**Attack**: Attacker waits for data to be archived, then exploits the missing state. - -**Prevention**: -```rust -// Extend TTL for critical data -pub fn critical_operation(env: Env) { - // Always extend instance storage - env.storage().instance().extend_ttl( - 100, // threshold - 518400, // extend_to (~30 days) - ); - - // Extend specific persistent keys - env.storage().persistent().extend_ttl( - &DataKey::CriticalData, - 100, - 518400, - ); -} - -// Consider restoration costs in design -// Archived data can be restored, but requires transaction -``` - ---- - -### 8. Cross-Contract Call Validation - -**Risk**: Trusting return values from untrusted contracts. - -**Attack**: Malicious contract returns false data, causing incorrect state updates. - -**Prevention**: -```rust -// Validate all external data -pub fn process_oracle_price(env: Env, oracle: Address, asset: Address) -> i128 { - // Validate oracle is trusted - let trusted_oracles: Vec
= env.storage() - .instance() - .get(&DataKey::TrustedOracles) - .unwrap(); - - if !trusted_oracles.contains(&oracle) { - panic!("untrusted oracle"); - } - - let price: i128 = oracle_client.get_price(&asset); - - // Sanity check the value - if price <= 0 || price > MAX_REASONABLE_PRICE { - panic!("invalid price"); - } - - price -} -``` - ---- - -## Classic Stellar Security - -### Trustline Attacks - -**Risk**: Users create trustlines to malicious assets that look legitimate. - -**Prevention**: -- Verify asset issuer before creating trustlines -- Use well-known asset lists (stellar.toml) -- Display full asset code + issuer in UIs - -### Clawback Awareness - -**Risk**: Assets with clawback enabled can be seized by issuer. - -**Prevention**: -```typescript -// Check if clawback is enabled -const issuerAccount = await server.loadAccount(asset.issuer); -const clawbackEnabled = issuerAccount.flags.auth_clawback_enabled; - -if (clawbackEnabled) { - // Warn user or reject asset -} -``` - -### Account Merge Attacks - -**Risk**: Merged accounts can be recreated with different configuration. - -**Prevention**: -- Validate account state before critical operations -- Don't cache account data long-term - ---- - -## Soroban-Specific Checklist - -### Contract Development -- [ ] All privileged functions require appropriate authorization -- [ ] Initialization can only happen once -- [ ] External contract calls are validated against allowlists -- [ ] All arithmetic uses checked operations -- [ ] Storage keys are typed and collision-free -- [ ] Critical data TTLs are extended proactively -- [ ] Input validation on all public functions -- [ ] Events emitted for auditable state changes - -### Storage Security -- [ ] Sensitive data uses appropriate storage type -- [ ] Instance storage for shared/admin data -- [ ] Persistent storage for user-specific data -- [ ] Temporary storage only for truly temporary data -- [ ] TTL management strategy documented - -### Cross-Contract Calls -- [ ] Called contracts are validated or allowlisted -- [ ] Return values are sanity-checked -- [ ] Failure cases handled gracefully -- [ ] No excessive trust in external state - ---- - -## Client-Side Checklist - -- [ ] Network passphrase validated before signing -- [ ] Transaction simulation before submission -- [ ] Clear display of all operation details -- [ ] Confirmation for high-value transactions -- [ ] Handle all error states gracefully -- [ ] Don't trust client-side validation alone -- [ ] Verify contract addresses against known deployments -- [ ] Check asset trustline status before transfers - ---- - -## Security Review Questions - -1. Can anyone call admin functions without authorization? -2. Can the contract be reinitialized? -3. Are all external contract calls validated? -4. Is arithmetic safe from overflow/underflow? -5. Can storage keys collide? -6. Will critical data survive archival? -7. Are cross-contract return values validated? -8. Can timing attacks exploit state changes? - ---- - -## Bug Bounty Programs - -### Immunefi — Stellar Core (up to $250K) -- **URL**: https://immunefi.com/bug-bounty/stellar/ -- **Scope**: stellar-core, rs-soroban-sdk, rs-soroban-env, soroban-tools (CLI + RPC), js-soroban-client, rs-stellar-xdr, wasmi fork -- **Rewards**: Critical $50K–$250K, High $10K–$50K, Medium $5K, Low $1K -- **Payment**: USD-denominated, paid in XLM. KYC required. -- **Rules**: PoC required. Test on local forks only (no mainnet/testnet). - -### Immunefi — OpenZeppelin on Stellar (up to $25K) -- **URL**: https://immunefi.com/bug-bounty/openzeppelin-stellar/ -- **Scope**: OpenZeppelin Stellar Contracts library -- **Max payout**: $25K per bug, $250K total program cap - -### HackerOne — Web Applications -- **URL**: https://stellar.org/grants-and-funding/bug-bounty -- **Scope**: SDF web applications, production servers, domains -- **Disclosure**: 90-day remediation window before public disclosure - -## Soroban Audit Bank - -SDF's proactive security program with **$3M+ deployed across 43+ audits**. - -- **URL**: https://stellar.org/grants-and-funding/soroban-audit-bank -- **Projects list**: https://stellar.org/audit-bank/projects -- **Eligibility**: SCF-funded projects (financial protocols, infrastructure, high-traction dApps) -- **Co-payment**: 5% upfront (refundable if Critical/High/Medium issues remediated within 20 business days) -- **Follow-up audits**: Triggered at $10M and $100M TVL milestones (includes formal verification and competitive audits) -- **Preparation**: STRIDE threat modeling framework + Audit Readiness Checklist - -### Partner Audit Firms - -| Firm | Specialty | -|------|-----------| -| **OtterSec** | Smart contract audits | -| **Veridise** | Tool-assisted audits, [security checklist](https://veridise.com/blog/audit-insights/building-on-stellar-soroban-grab-this-security-checklist-to-avoid-vulnerabilities/) | -| **Runtime Verification** | Formal methods, [Komet tool](https://runtimeverification.com/blog/introducing-komet-smart-contract-testing-and-verification-tool-for-soroban-created-by-runtime-verification) | -| **CoinFabrik** | Static analysis (Scout), manual audits | -| **QuarksLab** | Security research | -| **Coinspect** | Security audits | -| **Certora** | Formal verification ([Sunbeam Prover](https://docs.certora.com/en/latest/docs/sunbeam/index.html)) | -| **Halborn** | Security assessments | -| **Zellic** | Blockchain + cryptography research | -| **Code4rena** | Competitive audit platform | - -## Security Tooling - -### Static Analysis - -#### Scout Soroban (CoinFabrik) -Open-source vulnerability detector with 23 detectors (critical through enhancement severity). -- **GitHub**: https://github.com/CoinFabrik/scout-soroban -- **Install**: `cargo install cargo-scout-audit` → `cargo scout-audit` -- **Output formats**: HTML, Markdown, JSON, PDF, SARIF (CI/CD integration) -- **VSCode extension**: [Scout Audit](https://marketplace.visualstudio.com/items?itemName=CoinFabrik.scout-audit) -- **Key detectors**: `overflow-check`, `unprotected-update-current-contract-wasm`, `set-contract-storage`, `unrestricted-transfer-from`, `divide-before-multiply`, `dos-unbounded-operation`, `unsafe-unwrap` - -#### OpenZeppelin Security Detectors SDK -Framework for building custom security detectors for Soroban. -- **GitHub**: https://github.com/OpenZeppelin/soroban-security-detectors-sdk -- **Architecture**: `sdk` (core), `detectors` (pre-built), `soroban-scanner` (CLI) -- **Pre-built detectors**: `auth_missing`, `unchecked_ft_transfer`, improper TTL extension, contract panics, unsafe temporary storage -- **Extensible**: Load external detector libraries as shared objects - -### Formal Verification - -#### Certora Sunbeam Prover -Purpose-built formal verification for Soroban — first WASM platform supported by Certora. -- **Docs**: https://docs.certora.com/en/latest/docs/sunbeam/index.html -- **Spec language**: CVLR (Certora Verification Language for Rust) — Rust macros (`cvlr_assert!`, `cvlr_assume!`, `cvlr_satisfy!`) -- **Operates at**: WASM bytecode level (eliminates compiler trust assumptions) -- **Reports**: https://github.com/Certora/SecurityReports -- **Example**: [Blend V1 verification report](https://www.certora.com/reports/blend-smart-contract-verification-report) - -#### Runtime Verification — Komet -Formal verification and testing tool built specifically for Soroban (SCF-funded). -- **Docs**: https://docs.runtimeverification.com/komet -- **Repo**: https://github.com/runtimeverification/komet -- **Spec language**: Rust — property-based tests written in the same language as Soroban contracts -- **Operates at**: WASM bytecode level via [KWasm semantics](https://github.com/runtimeverification/wasm-semantics) (eliminates compiler trust assumptions) -- **Features**: Fuzzing, testing, formal verification -- **Reports**: [RV publications](https://github.com/runtimeverification/publications) -- **Example**: [TokenOps audit and verification report](https://github.com/runtimeverification/publications/blob/main/reports/smart-contracts/TokenOps.pdf) -- **Blog**: [Introducing Komet](https://runtimeverification.com/blog/introducing-komet-smart-contract-testing-and-verification-tool-for-soroban-created-by-runtime-verification) - -### Security Knowledge Base - -#### Soroban Security Portal -Community security knowledge base by Inferara (SCF-funded). -- **URL**: https://sorobansecurity.com -- **Features**: Searchable audit reports, vulnerability database, best practices - -### Security Monitoring (Post-Deployment) - -#### OpenZeppelin Monitor (Stellar alpha) -Open-source contract monitoring with Stellar support. -- **Features**: Self-hosted via Docker, Prometheus + Grafana observability -- **Source**: https://www.openzeppelin.com/news/monitor-and-relayers-are-now-open-source - -## OpenZeppelin Partnership Overview - -Strategic partnership highlights include: -- **40 Auditor Weeks** of dedicated security audits -- **Stellar Contracts library** (audited, production-ready) -- **Relayer** (fee-sponsored transactions, Stellar-native) -- **Monitor** (contract monitoring, Stellar alpha) -- **Security Detectors SDK** (static analysis framework) -- **SEP authorship**: SEP-0049 (Upgradeable Contracts), SEP-0050 (NFTs) -- **Blog**: https://stellar.org/blog/foundation-news/sdf-partners-with-openzeppelin-to-enhance-stellar-smart-contract-development diff --git a/skill/standards-reference.md b/skill/standards-reference.md deleted file mode 100644 index 518cdca..0000000 --- a/skill/standards-reference.md +++ /dev/null @@ -1,94 +0,0 @@ -# Stellar Standards Reference (SEPs & CAPs) - -## When to use this guide -Use this when you need: -- The right SEP/CAP for a feature or integration -- Interoperability guidance for wallets, anchors, and contracts -- A fast map from use case to official standards docs - -## Maintenance note -Standards status can change quickly. -Before implementation, verify current status in: -- SEPs: [stellar-protocol/ecosystem](https://github.com/stellar/stellar-protocol/tree/master/ecosystem) -- CAPs: [stellar-protocol/core](https://github.com/stellar/stellar-protocol/tree/master/core) - -Treat this file as a routing map, not a source of final governance/status truth. - -## High-value SEPs for app developers - -### Contracts and token interfaces -- [SEP-0041](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0041.md): Soroban token interface -- [SEP-0046](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0046.md): Contract metadata in Wasm -- [SEP-0048](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0048.md): Contract interface specification -- [SEP-0049](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0049.md): Upgradeable-contract guidance -- [SEP-0050](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0050.md): NFT standard work -- [SEP-0055](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0055.md): Contract build verification -- [SEP-0056](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0056.md): Vault-style tokenized products -- [SEP-0057](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0057.md): Regulated token patterns (T-REX) - -### Auth, identity, and metadata -- [SEP-0010](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0010.md): Web authentication -- [SEP-0023](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0023.md): StrKey encoding -- [SEP-0001](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0001.md): `stellar.toml` - -### Anchor and fiat integration -- [SEP-0006](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0006.md): Programmatic deposit/withdrawal API -- [SEP-0024](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0024.md): Hosted interactive anchor flow -- [SEP-0031](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0031.md): Cross-border payment flow -- [SEP-0012](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0012.md): KYC data exchange - -## High-value CAPs for Soroban developers - -### Soroban foundations -- [CAP-0046](https://github.com/stellar/stellar-protocol/blob/master/core/cap-0046.md): Soroban overview -- CAP-0046 subdocuments (`cap-0046-*.md`): runtime, lifecycle, host functions, storage, auth, metering - -### Frequently used contract capabilities -- [CAP-0051](https://github.com/stellar/stellar-protocol/blob/master/core/cap-0051.md): secp256r1 verification (passkey-related cryptography) -- [CAP-0053](https://github.com/stellar/stellar-protocol/blob/master/core/cap-0053.md): TTL extension behavior -- [CAP-0058](https://github.com/stellar/stellar-protocol/blob/master/core/cap-0058.md): constructors (`__constructor`) -- [CAP-0059](https://github.com/stellar/stellar-protocol/blob/master/core/cap-0059.md): BLS12-381 primitives -- [CAP-0067](https://github.com/stellar/stellar-protocol/blob/master/core/cap-0067.md): protocol/runtime improvements including asset/event model changes - -### Newer and draft crypto/features -- [CAP-0074](https://github.com/stellar/stellar-protocol/blob/master/core/cap-0074.md): BN254 host functions proposal -- [CAP-0075](https://github.com/stellar/stellar-protocol/blob/master/core/cap-0075.md): Poseidon/Poseidon2 proposal -- [CAP-0079](https://github.com/stellar/stellar-protocol/blob/master/core/cap-0079.md): muxed-address strkey conversion proposal - -Use the CAP preamble status fields as the source of truth for implementation readiness. - -## Quick mapping by use case - -### I am building a fungible token -1. Start with SEP-0041 interface expectations. -2. Prefer Stellar Assets + SAC interop unless custom logic is required. -3. If regulated, review SEP-0057 patterns. - -### I need upgrade-safe contracts -1. Read SEP-0049 guidance for upgrade process design. -2. Use CAP-0058 constructors for atomic initialization where protocol support exists. -3. Add migration/versioning strategy before deploying upgradeable contracts. - -### I am building a smart-wallet flow -1. Use SEP-0010 for web authentication flows. -2. Review CAP-0051 for passkey-related cryptographic primitives. -3. Align wallet UX and signing payloads with current SDK guidance. - -### I need anchor integration for fiat rails -1. SEP-0006 for API-first flows. -2. SEP-0024 for hosted interactive rails. -3. SEP-0031 when supporting payment corridors. -4. SEP-0012 for KYC data requirements. - -## Practical workflow for AI agents -- Step 1: Identify feature category (token, wallet auth, anchor, upgradeability). -- Step 2: Link user to the 1-3 primary SEP/CAP docs. -- Step 3: Check status/acceptance in the source repo before asserting support. -- Step 4: Implement only what is active on the target network/protocol. -- Step 5: Document dependencies on draft standards explicitly. - -## Related docs -- Contract implementation details: `contracts-soroban.md` -- Advanced architecture guidance: `advanced-patterns.md` -- RPC and data access: `api-rpc-horizon.md` -- Security considerations: `security.md` diff --git a/skill/testing.md b/skill/testing.md deleted file mode 100644 index e35175d..0000000 --- a/skill/testing.md +++ /dev/null @@ -1,786 +0,0 @@ -# Testing Strategy (Local / Testnet / Unit Tests) - -## Quick Navigation -- Strategy overview: [Testing Pyramid](#testing-pyramid) -- 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) -- Integration and CI: [Integration Testing Patterns](#integration-testing-patterns), [Test Configuration](#test-configuration), [CI/CD Configuration](#cicd-configuration) -- 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) -- Performance and readiness: [Resource Profiling](#resource-profiling), [Best Practices](#best-practices) - -## Testing Pyramid - -1. **Unit tests (fast)**: Native Rust tests with `soroban-sdk` testutils -2. **Local integration tests**: Stellar Quickstart Docker -3. **Testnet tests**: Deploy and test on public testnet -4. **Mainnet smoke tests**: Final validation before production - -## Unit Testing with Soroban SDK - -The Soroban SDK provides comprehensive testing utilities that run natively (not in WASM), enabling fast iteration with full debugging support. - -### Basic Test Setup - -```rust -#![cfg(test)] - -use soroban_sdk::{testutils::Address as _, Address, Env}; - -// Import your contract -use crate::{Contract, ContractClient}; - -#[test] -fn test_basic_functionality() { - // Create test environment - let env = Env::default(); - - // Register contract - let contract_id = env.register_contract(None, Contract); - - // Create typed client - let client = ContractClient::new(&env, &contract_id); - - // Generate test addresses - let user = Address::generate(&env); - - // Call contract functions - client.initialize(&user); - - // Assert results - assert_eq!(client.get_value(), 0); -} -``` - -### Testing Authorization - -```rust -#[test] -fn test_with_auth() { - let env = Env::default(); - - // Mock all authorizations automatically - env.mock_all_auths(); - - let contract_id = env.register_contract(None, TokenContract); - let client = TokenContractClient::new(&env, &contract_id); - - let admin = Address::generate(&env); - let user1 = Address::generate(&env); - let user2 = Address::generate(&env); - - // Initialize and mint - client.initialize(&admin); - client.mint(&user1, &1000); - - // Transfer (requires auth from user1) - client.transfer(&user1, &user2, &100); - - assert_eq!(client.balance(&user1), 900); - assert_eq!(client.balance(&user2), 100); - - // Verify which auths were required - let auths = env.auths(); - assert_eq!(auths.len(), 1); - // auths[0] contains (address, contract_id, function, args) -} -``` - -### Testing with Specific Auth Requirements - -```rust -#[test] -fn test_specific_auth() { - let env = Env::default(); - let contract_id = env.register_contract(None, Contract); - let client = ContractClient::new(&env, &contract_id); - - let user = Address::generate(&env); - - // Mock auth only for specific address - env.mock_auths(&[MockAuth { - address: &user, - invoke: &MockAuthInvoke { - contract: &contract_id, - fn_name: "transfer", - args: (&user, &other, &100i128).into_val(&env), - sub_invokes: &[], - }, - }]); - - client.transfer(&user, &other, &100); -} -``` - -### Testing Time-Dependent Logic - -```rust -#[test] -fn test_time_based() { - let env = Env::default(); - let contract_id = env.register_contract(None, VestingContract); - let client = VestingContractClient::new(&env, &contract_id); - - let beneficiary = Address::generate(&env); - - // Set initial timestamp - env.ledger().set_timestamp(1000); - - client.create_vesting(&beneficiary, &1000, &2000); // unlock at t=2000 - - // Try to claim before unlock - assert!(client.try_claim(&beneficiary).is_err()); - - // Advance time past unlock - env.ledger().set_timestamp(2500); - - // Now claim succeeds - client.claim(&beneficiary); -} -``` - -### Testing Ledger State - -```rust -#[test] -fn test_ledger_manipulation() { - let env = Env::default(); - - // Set ledger sequence - env.ledger().set_sequence_number(1000); - - // Set timestamp - env.ledger().set_timestamp(1704067200); // Jan 1, 2024 - - // Set network passphrase - env.ledger().set_network_id([0u8; 32]); // Custom network ID - - // Get current values - let seq = env.ledger().sequence(); - let ts = env.ledger().timestamp(); -} -``` - -### Testing Events - -```rust -#[test] -fn test_events() { - let env = Env::default(); - let contract_id = env.register_contract(None, Contract); - let client = ContractClient::new(&env, &contract_id); - - client.do_something(); - - // Get all events - let events = env.events().all(); - - // Check specific event - assert_eq!(events.len(), 1); - - let event = &events[0]; - // event.0 = contract_id - // event.1 = topics (Vec) - // event.2 = data (Val) -} -``` - -### Testing Storage - -```rust -#[test] -fn test_storage_ttl() { - let env = Env::default(); - let contract_id = env.register_contract(None, Contract); - let client = ContractClient::new(&env, &contract_id); - - client.store_data(); - - // Check TTL - let key = DataKey::MyData; - let ttl = env.as_contract(&contract_id, || { - env.storage().persistent().get_ttl(&key) - }); - - assert!(ttl > 0); -} -``` - -### Testing Cross-Contract Calls - -```rust -#[test] -fn test_cross_contract() { - let env = Env::default(); - - // Register both contracts - let token_id = env.register_contract_wasm(None, token::WASM); - let vault_id = env.register_contract(None, VaultContract); - - let token_client = token::Client::new(&env, &token_id); - let vault_client = VaultContractClient::new(&env, &vault_id); - - env.mock_all_auths(); - - let user = Address::generate(&env); - - // Setup: mint tokens to user - token_client.mint(&user, &1000); - - // Test: deposit tokens into vault - vault_client.deposit(&user, &token_id, &500); - - assert_eq!(token_client.balance(&user), 500); - assert_eq!(vault_client.balance(&user), 500); -} -``` - -## Local Testing with Stellar Quickstart - -### Start Local Network - -```bash -# Pull and run Stellar Quickstart -docker run --rm -it -p 8000:8000 \ - --name stellar \ - stellar/quickstart:latest \ - --local \ - --enable-soroban-rpc - -# Or use Stellar CLI -stellar container start local -``` - -### Configure for Local Network - -```typescript -import * as StellarSdk from "@stellar/stellar-sdk"; - -const LOCAL_RPC = "http://localhost:8000/soroban/rpc"; -const LOCAL_HORIZON = "http://localhost:8000"; -const LOCAL_PASSPHRASE = "Standalone Network ; February 2017"; - -const rpc = new StellarSdk.rpc.Server(LOCAL_RPC); -const horizon = new StellarSdk.Horizon.Server(LOCAL_HORIZON); -``` - -### Fund Test Accounts (Local) - -```bash -# Using Stellar CLI -stellar keys generate --global test-account --network local --fund - -# Or via friendbot endpoint -curl "http://localhost:8000/friendbot?addr=G..." -``` - -### Deploy and Test Locally - -```bash -# Deploy contract to local network -stellar contract deploy \ - --wasm target/wasm32-unknown-unknown/release/contract.wasm \ - --source test-account \ - --network local - -# Invoke contract -stellar contract invoke \ - --id CONTRACT_ID \ - --source test-account \ - --network local \ - -- \ - function_name \ - --arg value -``` - -## Testnet Testing - -### Network Configuration - -```bash -# Testnet RPC: https://soroban-testnet.stellar.org -# Testnet Horizon: https://horizon-testnet.stellar.org -# Network Passphrase: "Test SDF Network ; September 2015" -# Friendbot: https://friendbot.stellar.org -``` - -### Create and Fund Testnet Account - -```bash -# Generate new identity -stellar keys generate --global my-testnet-key --network testnet - -# Fund via Friendbot -stellar keys fund my-testnet-key --network testnet - -# Or manually -curl "https://friendbot.stellar.org?addr=G..." -``` - -### Deploy to Testnet - -```bash -# Deploy contract -stellar contract deploy \ - --wasm target/wasm32-unknown-unknown/release/contract.wasm \ - --source my-testnet-key \ - --network testnet - -# Install contract code (separate from deployment) -stellar contract install \ - --wasm target/wasm32-unknown-unknown/release/contract.wasm \ - --source my-testnet-key \ - --network testnet -``` - -### Testnet Reset Awareness - -**Important**: Testnet resets approximately quarterly: -- All accounts and contracts are deleted -- Plan for re-deployment after resets -- Don't rely on persistent state for test data - -Check reset schedule: https://stellar.org/developers/blog - -## Integration Testing Patterns - -### TypeScript Integration Tests - -```typescript -// tests/integration/contract.test.ts -import * as StellarSdk from "@stellar/stellar-sdk"; - -const RPC_URL = process.env.RPC_URL || "http://localhost:8000/soroban/rpc"; -const NETWORK_PASSPHRASE = process.env.NETWORK_PASSPHRASE || "Standalone Network ; February 2017"; - -describe("Contract Integration Tests", () => { - let rpc: StellarSdk.rpc.Server; - let keypair: StellarSdk.Keypair; - let contractId: string; - - beforeAll(async () => { - rpc = new StellarSdk.rpc.Server(RPC_URL); - keypair = StellarSdk.Keypair.random(); - - // Fund account - await fundAccount(keypair.publicKey()); - - // Deploy contract - contractId = await deployContract(keypair); - }); - - test("should initialize contract", async () => { - const account = await rpc.getAccount(keypair.publicKey()); - const contract = new StellarSdk.Contract(contractId); - - const tx = new StellarSdk.TransactionBuilder(account, { - fee: "100", - networkPassphrase: NETWORK_PASSPHRASE, - }) - .addOperation( - contract.call( - "initialize", - StellarSdk.Address.fromString(keypair.publicKey()).toScVal() - ) - ) - .setTimeout(30) - .build(); - - const simResult = await rpc.simulateTransaction(tx); - const preparedTx = StellarSdk.rpc.assembleTransaction(tx, simResult); - - preparedTx.sign(keypair); - const result = await rpc.sendTransaction(preparedTx.build()); - - expect(result.status).not.toBe("ERROR"); - }); -}); -``` - -### Rust Integration Tests - -```rust -// tests/integration_test.rs -use soroban_sdk::{Env, Address}; -use std::process::Command; - -#[test] -#[ignore] // Run with: cargo test -- --ignored -fn integration_test_with_local_network() { - // Requires local network running - let output = Command::new("stellar") - .args([ - "contract", "invoke", - "--id", "CONTRACT_ID", - "--source", "test-account", - "--network", "local", - "--", - "get_count" - ]) - .output() - .expect("Failed to invoke contract"); - - assert!(output.status.success()); -} -``` - -## Test Configuration - -### Cargo.toml for Tests - -```toml -[dev-dependencies] -soroban-sdk = { version = "25.0.1", features = ["testutils"] } # match [dependencies] version - -[profile.test] -opt-level = 0 -debug = true -``` - -### Running Tests - -```bash -# Run unit tests -cargo test - -# Run with output -cargo test -- --nocapture - -# Run specific test -cargo test test_transfer - -# Run ignored (integration) tests -cargo test -- --ignored -``` - -## CI/CD Configuration - -### GitHub Actions Example - -```yaml -name: Test Soroban Contract - -on: [push, pull_request] - -jobs: - unit-tests: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - - name: Install Rust - uses: dtolnay/rust-toolchain@stable - - - name: Add WASM target - run: rustup target add wasm32-unknown-unknown - - - name: Run unit tests - run: cargo test - - - name: Build contract - run: cargo build --release --target wasm32-unknown-unknown - - integration-tests: - runs-on: ubuntu-latest - needs: unit-tests - services: - stellar: - image: stellar/quickstart:latest - ports: - - 8000:8000 - options: >- - --health-cmd "curl -f http://localhost:8000 || exit 1" - --health-interval 10s - --health-timeout 5s - --health-retries 10 - - steps: - - uses: actions/checkout@v4 - - - name: Install Stellar CLI - run: | - cargo install stellar-cli --locked - - - name: Deploy and test - run: | - stellar keys generate --global ci-test --network local --fund - stellar contract deploy \ - --wasm target/wasm32-unknown-unknown/release/contract.wasm \ - --source ci-test \ - --network local -``` - -## Best Practices - -### Test Organization -``` -project/ -├── src/ -│ └── lib.rs -├── tests/ -│ ├── common/ -│ │ └── mod.rs # Shared test utilities -│ ├── unit/ -│ │ ├── mod.rs -│ │ └── transfer.rs -│ └── integration/ -│ └── full_flow.rs -└── Cargo.toml -``` - -### Test Utilities Module - -```rust -// tests/common/mod.rs -use soroban_sdk::{testutils::Address as _, Address, Env}; -use crate::{Contract, ContractClient}; - -pub fn setup_contract(env: &Env) -> (Address, ContractClient) { - let contract_id = env.register_contract(None, Contract); - let client = ContractClient::new(env, &contract_id); - let admin = Address::generate(env); - - env.mock_all_auths(); - client.initialize(&admin); - - (contract_id, client) -} - -pub fn create_funded_user(env: &Env, client: &ContractClient, amount: i128) -> Address { - let user = Address::generate(env); - client.mint(&user, &amount); - user -} -``` - -## Fuzz Testing - -Soroban 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. - -### Setup - -```bash -# Install nightly Rust + cargo-fuzz -rustup install nightly -cargo install --locked cargo-fuzz - -# Initialize fuzz targets -cargo fuzz init -``` - -Update `Cargo.toml` to include both crate types: -```toml -[lib] -crate-type = ["lib", "cdylib"] -``` - -Add to `fuzz/Cargo.toml`: -```toml -[dependencies] -soroban-sdk = { version = "25.0.1", features = ["testutils"] } -``` - -### Writing a Fuzz Target - -```rust -// fuzz/fuzz_targets/fuzz_deposit.rs -#![no_main] - -use libfuzzer_sys::fuzz_target; -use soroban_sdk::{testutils::Address as _, Address, Env}; -use my_contract::{Contract, ContractClient}; - -fuzz_target!(|input: (u64, i128)| { - let (seed, amount) = input; - let env = Env::default(); - env.mock_all_auths(); - - let contract_id = env.register(Contract, ()); - let client = ContractClient::new(&env, &contract_id); - let user = Address::generate(&env); - - // Initialize - client.initialize(&user); - - // Fuzz deposit — should never panic unexpectedly - let _ = client.try_deposit(&user, &amount); -}); -``` - -### Running Fuzz Tests - -```bash -# Run (use --sanitizer=thread on macOS) -cargo +nightly fuzz run fuzz_deposit - -# Generate code coverage -cargo +nightly fuzz coverage fuzz_deposit -``` - -### Soroban Token Fuzzer - -Reusable library for fuzzing token contracts: -- **GitHub**: https://github.com/brson/soroban-token-fuzzer - -### Documentation - -- [Stellar Fuzzing Guide](https://developers.stellar.org/docs/build/guides/testing/fuzzing) -- [Fuzzing Example Contract](https://developers.stellar.org/docs/build/smart-contracts/example-contracts/fuzzing) - -## Property-Based Testing - -Use `proptest` with `SorobanArbitrary` for QuickCheck-style property testing that runs in standard `cargo test`. - -```rust -#[cfg(test)] -mod prop_tests { - use super::*; - use proptest::prelude::*; - use soroban_sdk::{testutils::Address as _, Env}; - - proptest! { - #[test] - fn deposit_then_withdraw_preserves_balance(amount in 1i128..=i128::MAX) { - let env = Env::default(); - env.mock_all_auths(); - let contract_id = env.register(Contract, ()); - let client = ContractClient::new(&env, &contract_id); - let user = Address::generate(&env); - - client.initialize(&user); - client.deposit(&user, &amount); - client.withdraw(&user, &amount); - - prop_assert_eq!(client.balance(&user), 0); - } - } -} -``` - -**Recommended workflow**: Use `cargo-fuzz` interactively to find deep bugs, then convert to `proptest` for regression prevention in CI. - -## Differential Testing with Test Snapshots - -Soroban automatically writes JSON snapshots at the end of every test to `test_snapshots/`, capturing events and final ledger state. Commit these to source control — diffs reveal unintended behavioral changes. - -### Comparing Against Deployed Contracts - -```rust -// Fetch deployed contract for comparison -// $ stellar contract fetch --id C... --out-file deployed.wasm - -mod deployed { - soroban_sdk::contractimport!(file = "deployed.wasm"); -} - -#[test] -fn test_upgrade_compatibility() { - let env = Env::default(); - env.mock_all_auths(); - - // Register both versions - let old_id = env.register_contract_wasm(None, deployed::WASM); - let new_id = env.register(NewContract, ()); - - let old_client = deployed::Client::new(&env, &old_id); - let new_client = NewContractClient::new(&env, &new_id); - - let user = Address::generate(&env); - - // Run identical operations and compare - old_client.initialize(&user); - new_client.initialize(&user); - - assert_eq!(old_client.get_value(), new_client.get_value()); -} -``` - -- **Docs**: [Differential Tests with Test Snapshots](https://developers.stellar.org/docs/build/guides/testing/differential-tests-with-test-snapshots) - -## Fork Testing - -Test against real production state using ledger snapshots: - -```bash -# Create snapshot of deployed contract -stellar snapshot create --address C... --output json --out snapshot.json - -# Optionally at a specific ledger -stellar snapshot create --address C... --ledger 12345678 --output json --out snapshot.json -``` - -```rust -#[test] -fn test_against_mainnet_state() { - let env = Env::from_ledger_snapshot_file("snapshot.json"); - env.mock_all_auths(); - - let contract_id = /* contract address from snapshot */; - let client = ContractClient::new(&env, &contract_id); - - // Test operations against real state - let result = client.get_value(); - assert!(result > 0); -} -``` - -- **Docs**: [Fork Testing](https://developers.stellar.org/docs/build/guides/testing/fork-testing) - -## Mutation Testing - -Use `cargo-mutants` to verify test quality — modifies source code and checks that tests catch the changes. - -```bash -cargo install --locked cargo-mutants -cargo mutants -``` - -**Output interpretation**: -- **CAUGHT**: Tests detected the mutation (good coverage) -- **MISSED**: Tests passed despite mutation (test gap — review `mutants.out/diff/`) - -- **Docs**: [Mutation Testing](https://developers.stellar.org/docs/build/guides/testing/mutation-testing) - -## Resource Profiling - -Soroban uses a multidimensional resource model (CPU instructions, ledger reads/writes, bytes, events, rent). - -### CLI Simulation - -```bash -# Simulate contract invocation to see resource costs -stellar contract invoke \ - --id CONTRACT_ID \ - --source alice \ - --network testnet \ - --sim-only \ - -- \ - function_name --arg value -``` - -### Stellar Plus Profiler (Cheesecake Labs) - -```typescript -import { StellarPlus } from 'stellar-plus'; - -const profilerPlugin = new StellarPlus.Utils.Plugins.sorobanTransaction.profiler(); -// Collects CPU instructions, RAM, ledger reads/writes -// Aggregation: sum, average, standard deviation -// Output: CSV, formatted text tables -``` - -- **Docs**: https://docs.cheesecakelabs.com/stellar-plus/reference/utils/plugins/profiler-plugin - -### Testing Checklist - -- [ ] Unit tests cover all public functions -- [ ] Edge cases tested (zero amounts, max values, empty state) -- [ ] Authorization tested (correct signers required) -- [ ] Error conditions tested (invalid inputs, unauthorized) -- [ ] Events emission verified -- [ ] Storage TTL behavior validated -- [ ] Cross-contract interactions tested -- [ ] Fuzz tests for critical paths (deposits, withdrawals, swaps) -- [ ] Property-based tests for invariants -- [ ] Mutation testing confirms test quality -- [ ] Differential test snapshots committed to source control -- [ ] Integration tests against local network -- [ ] Testnet deployment verified before mainnet diff --git a/skill/x402.md b/skill/x402.md deleted file mode 100644 index 0ae3492..0000000 --- a/skill/x402.md +++ /dev/null @@ -1,203 +0,0 @@ -# x402 on Stellar - -## When to use x402 -x402 is the right choice when: -- You want the fastest path to a paid API — minimal code, no contract deployment -- You want clients (including AI agents) to pay with **zero XLM** — the OZ Channels facilitator sponsors all network fees -- You're building on top of an existing x402 ecosystem (Coinbase, other chains) - -Trade-off: you depend on OZ Channels (or a self-hosted relayer) for verification and settlement. If you need zero third-party dependency, use [MPP Charge](mpp.md) instead. - -## How x402 works on Stellar - -``` -Client → GET /resource → Server -Client ← 402 Payment Required (payment requirements) ← Server -Client builds Soroban SAC USDC transfer -Client signs auth entries only (not the full tx envelope) -Client → GET /resource + X-PAYMENT header → Server -Server → OZ Channels /verify + /settle → Stellar (~5s) -Client ← 200 OK + resource -``` - -The key Stellar difference: clients sign **auth entries**, not full transaction envelopes. The facilitator assembles the transaction, pays fees, and submits. Clients need zero XLM. - -## Seller: monetize an Express API - -```bash -npm install @x402/express @x402/core @x402/stellar express dotenv -npm pkg set type=module -``` - -```js -// server.js -import express from "express"; -import { paymentMiddlewareFromConfig } from "@x402/express"; -import { HTTPFacilitatorClient } from "@x402/core/server"; -import { ExactStellarScheme } from "@x402/stellar/exact/server"; - -const app = express(); - -const facilitator = new HTTPFacilitatorClient({ - url: process.env.FACILITATOR_URL ?? "https://channels.openzeppelin.com/x402/testnet", - // omit createAuthHeaders on testnet if you don't have an API key yet - createAuthHeaders: process.env.OZ_API_KEY - ? async () => { - const h = { Authorization: `Bearer ${process.env.OZ_API_KEY}` }; - return { verify: h, settle: h, supported: h }; - } - : undefined, -}); - -app.use( - paymentMiddlewareFromConfig( - { - "GET /weather": { - description: "Current weather data", - // human-readable price string — auto-converts to USDC base units - price: "$0.001", - network: "stellar:testnet", - payTo: process.env.STELLAR_RECIPIENT, // your G... address - }, - }, - { facilitator, schemes: [ExactStellarScheme] } - ) -); - -app.get("/weather", (_req, res) => { - res.json({ city: "San Francisco", temp: 18, conditions: "Foggy" }); -}); - -app.listen(3001, () => console.log("x402 server on http://localhost:3001")); -``` - -**Env vars:** -- `STELLAR_RECIPIENT` — your G... address (receives USDC) -- `OZ_API_KEY` — OZ Channels API key (optional on testnet, required on mainnet) -- `FACILITATOR_URL` — defaults to testnet URL above - -**Price format options:** -- `"$0.001"` — human-readable, auto-converts to 7-decimal USDC units -- `{ amount: "1000", asset: "ASSET_SAC_CONTRACT_ID" }` — explicit base units for non-USDC assets - -## Buyer: agent client - -```bash -npm install @x402/fetch @x402/stellar @stellar/stellar-sdk dotenv -npm pkg set type=module -``` - -```js -// client.js -import { x402HTTPClient } from "@x402/fetch"; -import { createEd25519Signer, getNetworkPassphrase } from "@x402/stellar"; -import { ExactStellarScheme } from "@x402/stellar/exact/client"; -import * as StellarSdk from "@stellar/stellar-sdk"; - -const keypair = StellarSdk.Keypair.fromSecret(process.env.STELLAR_SECRET_KEY); -const network = "stellar:testnet"; - -// createEd25519Signer wraps the keypair for auth-entry signing -const signer = createEd25519Signer(keypair, getNetworkPassphrase(network)); - -// x402HTTPClient wraps fetch — handles 402 negotiation transparently -const client = x402HTTPClient({ signer, schemes: [ExactStellarScheme] }); - -const res = await client.fetch("http://localhost:3001/weather"); -console.log(await res.json()); -// Paid automatically: 402 negotiation + auth-entry signing happens under the hood -``` - -**Env vars:** -- `STELLAR_SECRET_KEY` — your S... secret key (needs USDC trustline + balance) - -## Testnet runbook - -1. **Generate a keypair** - ```bash - node -e "const { Keypair } = require('@stellar/stellar-sdk'); const kp = Keypair.random(); console.log('Public:', kp.publicKey()); console.log('Secret:', kp.secret());" - ``` - -2. **Fund with testnet XLM** - ```bash - curl "https://friendbot.stellar.org?addr=YOUR_PUBLIC_KEY" - ``` - -3. **Add USDC trustline** — open [Stellar Lab](https://laboratory.stellar.org/#account-creator?network=test), or via SDK: - ```js - import * as StellarSdk from "@stellar/stellar-sdk"; - - const server = new StellarSdk.Horizon.Server("https://horizon-testnet.stellar.org"); - const keypair = process.env.STELLAR_SECRET_KEY - ? StellarSdk.Keypair.fromSecret(process.env.STELLAR_SECRET_KEY) - : StellarSdk.Keypair.random(); - - const account = await server.loadAccount(keypair.publicKey()); - const tx = new StellarSdk.TransactionBuilder(account, { - fee: "100", - networkPassphrase: StellarSdk.Networks.TESTNET, - }) - .addOperation( - StellarSdk.Operation.changeTrust({ - asset: new StellarSdk.Asset("USDC", "GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5"), - }), - ) - .setTimeout(30) - .build(); - tx.sign(keypair); - await server.submitTransaction(tx); - ``` - -4. **Get testnet USDC** — use the [Circle testnet faucet](https://faucet.circle.com/) (select Stellar testnet) - -5. **Get an OZ Channels testnet API key** (optional for testnet, required for mainnet): - - Testnet: [channels.openzeppelin.com/testnet/gen](https://channels.openzeppelin.com/testnet/gen) - - Mainnet: [channels.openzeppelin.com/gen](https://channels.openzeppelin.com/gen) - -## Mainnet checklist - -| Config | Value | -|--------|-------| -| Network ID | `stellar:pubnet` | -| RPC URL | Provider-specific endpoint (see [Stellar RPC providers directory](https://developers.stellar.org/docs/data/rpc/providers)) | -| Facilitator URL | `https://channels.openzeppelin.com/x402` | -| USDC SAC | `CCW67TSZV3SSS2HXMBQ5JFGCKJNXKZM7UQUWUZPUTHXSTZLEO7SJMI75` | -| Funding | Real USDC on mainnet (CEX, DEX, or bridge) | - -Always test on testnet first. Switch by changing `network` and `FACILITATOR_URL`. - -## Key concepts - -**Auth entry signing** — On Stellar, x402 clients sign Soroban authorization entries, not full transaction envelopes. The facilitator assembles the complete transaction. This is lighter than EVM/Solana signing, and means clients never need to manage sequence numbers or pay fees. - -**Fee sponsorship** — OZ Channels pays all Stellar network fees (~$0.00001/tx). Clients need a funded wallet with USDC but zero XLM. - -**`exact-v2` scheme** — The Stellar x402 scheme version. Server advertises `scheme: "exact"` + `x402Version: 2`. Don't mix v1 and v2 packages. - -**SAC (Stellar Asset Contract)** — USDC on Stellar is a classic asset wrapped in a Soroban contract. x402 payments invoke `transfer` on the SAC. Any SEP-41 token works; USDC is the default. - -**Ledger expiration** — Auth entries include a `max_ledger` bound. Use `latestLedger + 12` (~1 minute at 5s/ledger). Expired entries fail at settlement. - -**CAIP-2 network IDs** — `stellar:testnet` and `stellar:pubnet`. These are the exact strings the protocol expects. - -## Common pitfalls - -**Auth entry expired on settle** -- Symptom: facilitator returns `isValid: false`, error mentions ledger expiration -- Fix: ensure client uses `latestLedger + 12` (or higher) as expiration; don't cache auth entries across requests - -**Wrong USDC decimal precision** -- Symptom: payment amount off by 10x or 100x -- Fix: Stellar USDC uses **7 decimal places** (not 6 like EVM USDC). `$0.001` = `10000` in base units. - -**V1/V2 package mismatch** -- Symptom: TypeScript errors or silent payment failures -- Fix: use all `@x402/*` packages at the same major version. V2 is multi-chain; don't import V1 `@x402/core` alongside V2 `@x402/stellar`. - -**Missing USDC trustline** -- Symptom: `op_no_trust` error during settlement -- Fix: add a USDC `changeTrust` operation before attempting any x402 payment (see testnet runbook above) - -**OZ Channels 401 on mainnet** -- Symptom: facilitator rejects with 401 -- Fix: mainnet requires an API key in the `Authorization: Bearer` header — generate one at channels.openzeppelin.com/gen diff --git a/skills/agentic-payments/SKILL.md b/skills/agentic-payments/SKILL.md new file mode 100644 index 0000000..a2a83eb --- /dev/null +++ b/skills/agentic-payments/SKILL.md @@ -0,0 +1,500 @@ +--- +name: agentic-payments +description: Agentic and machine-to-machine payments on Stellar. Covers x402 (HTTP 402 paid APIs via OZ Channels facilitator, fee-sponsored clients) and MPP (Machine Payments Protocol) in both Charge mode (per-request Soroban SAC) and Channel mode (off-chain commits, high-frequency). Defaults to USDC (SEP-41 SAC) on `stellar:testnet`/`stellar:pubnet` (CAIP-2). Use when selling a paid API to AI agents, building an x402 client, or designing a payment-channel architecture for high-frequency agent traffic. +user-invocable: true +argument-hint: "[payment task]" +--- + +# Agentic Payments: x402 + MPP + +Two complementary protocols for AI-agent and machine-to-machine payments on Stellar. Pick based on who depends on whom and how often the agent pays. + +## Quick decision + +| | x402 | MPP Charge | MPP Channel | +|--|------|------------|-------------| +| Per-request on-chain tx? | Yes (via facilitator) | Yes (Soroban SAC) | No (off-chain commits) | +| Needs facilitator? | Yes (OZ Channels) | No | No | +| Client needs XLM? | No (fees sponsored) | Optional (`feePayer`) | Yes | +| Setup complexity | Low | Low | Medium (deploy contract first) | +| Best for | Quickest setup, fee-free clients | No third-party dep | High-frequency agents | + +- Selling an API, want zero-XLM clients → see **x402 Seller** below +- Calling an x402 API from an agent → see **x402 Buyer** below +- Selling an API, no facilitator dependency → see **MPP Charge** below +- Agent making many requests per session → see **MPP Channel** below +- Unsure → x402 (lowest friction to get started) + +All protocols use USDC (SEP-41 SAC) by default; `stellar:testnet` / `stellar:pubnet` CAIP-2 network IDs. + +## Related skills +- The Soroban SACs the protocols call → `../soroban/SKILL.md` +- USDC and other classic assets → `../assets/SKILL.md` +- Wallets and signing in the buyer client → `../dapp/SKILL.md` +- RPC simulation / submission patterns → `../data/SKILL.md` +- SEP-41 (token interface) and related standards → `../standards/SKILL.md` + +--- + +# Part 1: x402 — Paid APIs + Agent Buyer Clients + + +## When to use x402 +x402 is the right choice when: +- You want the fastest path to a paid API — minimal code, no contract deployment +- You want clients (including AI agents) to pay with **zero XLM** — the OZ Channels facilitator sponsors all network fees +- You're building on top of an existing x402 ecosystem (Coinbase, other chains) + +Trade-off: you depend on OZ Channels (or a self-hosted relayer) for verification and settlement. If you need zero third-party dependency, use MPP Charge (Part 2 below) instead. + +## How x402 works on Stellar + +``` +Client → GET /resource → Server +Client ← 402 Payment Required (payment requirements) ← Server +Client builds Soroban SAC USDC transfer +Client signs auth entries only (not the full tx envelope) +Client → GET /resource + X-PAYMENT header → Server +Server → OZ Channels /verify + /settle → Stellar (~5s) +Client ← 200 OK + resource +``` + +The key Stellar difference: clients sign **auth entries**, not full transaction envelopes. The facilitator assembles the transaction, pays fees, and submits. Clients need zero XLM. + +## Seller: monetize an Express API + +```bash +npm install @x402/express @x402/core @x402/stellar express dotenv +npm pkg set type=module +``` + +```js +// server.js +import express from "express"; +import { paymentMiddlewareFromConfig } from "@x402/express"; +import { HTTPFacilitatorClient } from "@x402/core/server"; +import { ExactStellarScheme } from "@x402/stellar/exact/server"; + +const app = express(); + +const facilitator = new HTTPFacilitatorClient({ + url: process.env.FACILITATOR_URL ?? "https://channels.openzeppelin.com/x402/testnet", + // omit createAuthHeaders on testnet if you don't have an API key yet + createAuthHeaders: process.env.OZ_API_KEY + ? async () => { + const h = { Authorization: `Bearer ${process.env.OZ_API_KEY}` }; + return { verify: h, settle: h, supported: h }; + } + : undefined, +}); + +app.use( + paymentMiddlewareFromConfig( + { + "GET /weather": { + description: "Current weather data", + // human-readable price string — auto-converts to USDC base units + price: "$0.001", + network: "stellar:testnet", + payTo: process.env.STELLAR_RECIPIENT, // your G... address + }, + }, + { facilitator, schemes: [ExactStellarScheme] } + ) +); + +app.get("/weather", (_req, res) => { + res.json({ city: "San Francisco", temp: 18, conditions: "Foggy" }); +}); + +app.listen(3001, () => console.log("x402 server on http://localhost:3001")); +``` + +**Env vars:** +- `STELLAR_RECIPIENT` — your G... address (receives USDC) +- `OZ_API_KEY` — OZ Channels API key (optional on testnet, required on mainnet) +- `FACILITATOR_URL` — defaults to testnet URL above + +**Price format options:** +- `"$0.001"` — human-readable, auto-converts to 7-decimal USDC units +- `{ amount: "1000", asset: "ASSET_SAC_CONTRACT_ID" }` — explicit base units for non-USDC assets + +## Buyer: agent client + +```bash +npm install @x402/fetch @x402/stellar @stellar/stellar-sdk dotenv +npm pkg set type=module +``` + +```js +// client.js +import { x402HTTPClient } from "@x402/fetch"; +import { createEd25519Signer, getNetworkPassphrase } from "@x402/stellar"; +import { ExactStellarScheme } from "@x402/stellar/exact/client"; +import * as StellarSdk from "@stellar/stellar-sdk"; + +const keypair = StellarSdk.Keypair.fromSecret(process.env.STELLAR_SECRET_KEY); +const network = "stellar:testnet"; + +// createEd25519Signer wraps the keypair for auth-entry signing +const signer = createEd25519Signer(keypair, getNetworkPassphrase(network)); + +// x402HTTPClient wraps fetch — handles 402 negotiation transparently +const client = x402HTTPClient({ signer, schemes: [ExactStellarScheme] }); + +const res = await client.fetch("http://localhost:3001/weather"); +console.log(await res.json()); +// Paid automatically: 402 negotiation + auth-entry signing happens under the hood +``` + +**Env vars:** +- `STELLAR_SECRET_KEY` — your S... secret key (needs USDC trustline + balance) + +## Testnet runbook + +1. **Generate a keypair** + ```bash + node -e "const { Keypair } = require('@stellar/stellar-sdk'); const kp = Keypair.random(); console.log('Public:', kp.publicKey()); console.log('Secret:', kp.secret());" + ``` + +2. **Fund with testnet XLM** + ```bash + curl "https://friendbot.stellar.org?addr=YOUR_PUBLIC_KEY" + ``` + +3. **Add USDC trustline** — open [Stellar Lab](https://laboratory.stellar.org/#account-creator?network=test), or via SDK: + ```js + import * as StellarSdk from "@stellar/stellar-sdk"; + + const server = new StellarSdk.Horizon.Server("https://horizon-testnet.stellar.org"); + const keypair = process.env.STELLAR_SECRET_KEY + ? StellarSdk.Keypair.fromSecret(process.env.STELLAR_SECRET_KEY) + : StellarSdk.Keypair.random(); + + const account = await server.loadAccount(keypair.publicKey()); + const tx = new StellarSdk.TransactionBuilder(account, { + fee: "100", + networkPassphrase: StellarSdk.Networks.TESTNET, + }) + .addOperation( + StellarSdk.Operation.changeTrust({ + asset: new StellarSdk.Asset("USDC", "GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5"), + }), + ) + .setTimeout(30) + .build(); + tx.sign(keypair); + await server.submitTransaction(tx); + ``` + +4. **Get testnet USDC** — use the [Circle testnet faucet](https://faucet.circle.com/) (select Stellar testnet) + +5. **Get an OZ Channels testnet API key** (optional for testnet, required for mainnet): + - Testnet: [channels.openzeppelin.com/testnet/gen](https://channels.openzeppelin.com/testnet/gen) + - Mainnet: [channels.openzeppelin.com/gen](https://channels.openzeppelin.com/gen) + +## Mainnet checklist + +| Config | Value | +|--------|-------| +| Network ID | `stellar:pubnet` | +| RPC URL | Provider-specific endpoint (see [Stellar RPC providers directory](https://developers.stellar.org/docs/data/rpc/providers)) | +| Facilitator URL | `https://channels.openzeppelin.com/x402` | +| USDC SAC | `CCW67TSZV3SSS2HXMBQ5JFGCKJNXKZM7UQUWUZPUTHXSTZLEO7SJMI75` | +| Funding | Real USDC on mainnet (CEX, DEX, or bridge) | + +Always test on testnet first. Switch by changing `network` and `FACILITATOR_URL`. + +## Key concepts + +**Auth entry signing** — On Stellar, x402 clients sign Soroban authorization entries, not full transaction envelopes. The facilitator assembles the complete transaction. This is lighter than EVM/Solana signing, and means clients never need to manage sequence numbers or pay fees. + +**Fee sponsorship** — OZ Channels pays all Stellar network fees (~$0.00001/tx). Clients need a funded wallet with USDC but zero XLM. + +**`exact-v2` scheme** — The Stellar x402 scheme version. Server advertises `scheme: "exact"` + `x402Version: 2`. Don't mix v1 and v2 packages. + +**SAC (Stellar Asset Contract)** — USDC on Stellar is a classic asset wrapped in a Soroban contract. x402 payments invoke `transfer` on the SAC. Any SEP-41 token works; USDC is the default. + +**Ledger expiration** — Auth entries include a `max_ledger` bound. Use `latestLedger + 12` (~1 minute at 5s/ledger). Expired entries fail at settlement. + +**CAIP-2 network IDs** — `stellar:testnet` and `stellar:pubnet`. These are the exact strings the protocol expects. + +## Common pitfalls + +**Auth entry expired on settle** +- Symptom: facilitator returns `isValid: false`, error mentions ledger expiration +- Fix: ensure client uses `latestLedger + 12` (or higher) as expiration; don't cache auth entries across requests + +**Wrong USDC decimal precision** +- Symptom: payment amount off by 10x or 100x +- Fix: Stellar USDC uses **7 decimal places** (not 6 like EVM USDC). `$0.001` = `10000` in base units. + +**V1/V2 package mismatch** +- Symptom: TypeScript errors or silent payment failures +- Fix: use all `@x402/*` packages at the same major version. V2 is multi-chain; don't import V1 `@x402/core` alongside V2 `@x402/stellar`. + +**Missing USDC trustline** +- Symptom: `op_no_trust` error during settlement +- Fix: add a USDC `changeTrust` operation before attempting any x402 payment (see testnet runbook above) + +**OZ Channels 401 on mainnet** +- Symptom: facilitator rejects with 401 +- Fix: mainnet requires an API key in the `Authorization: Bearer` header — generate one at channels.openzeppelin.com/gen + +--- + +# Part 2: MPP — Machine Payments Protocol (Charge + Channel) + + +## When to use MPP +MPP is the right choice when: +- You want **no facilitator dependency** — payments settle directly on Stellar via Soroban SAC transfers +- Your AI agent makes **many requests per session** — use channel mode to pay off-chain and settle once +- You're building a Stellar-native payment stack without relying on third-party infrastructure + +Two modes: + +| Mode | On-chain txs | Best for | +|------|-------------|----------| +| **Charge** | One per request | Per-request payments, no pre-funding required | +| **Channel** | One deposit + one close | High-frequency agents (100s of requests/session) | + +If you need zero-XLM clients or the simplest possible setup, use x402 (Part 1 above) instead. + +## Charge mode: per-request payments + +Each request triggers a Soroban SAC token transfer settled on-chain. No facilitator. Server can optionally sponsor fees so clients don't need XLM. + +```bash +npm install express @stellar/mpp mppx @stellar/stellar-sdk dotenv +npm pkg set type=module +``` + +**Server:** + +```js +// charge-server.js +import express from "express"; +import { Mppx } from "mppx"; +import * as stellar from "@stellar/mpp/charge/server"; +import * as StellarSdk from "@stellar/stellar-sdk"; + +const USDC_SAC_TESTNET = "CBIELTK6YBZJU5UP2WWQEUCYKLPU6AUNZ2BQ4WWFEIE3USCIHMXQDAMA"; +const RECIPIENT = process.env.STELLAR_RECIPIENT; // G... address + +const mppx = Mppx.create({ + secretKey: process.env.MPP_SECRET_KEY, // shared secret for credential verification + methods: [ + stellar.charge({ + recipient: RECIPIENT, + currency: USDC_SAC_TESTNET, + network: "stellar:testnet", + // optional: server pays network fees so clients don't need XLM + feePayer: process.env.FEE_PAYER_SECRET + ? { envelopeSigner: StellarSdk.Keypair.fromSecret(process.env.FEE_PAYER_SECRET) } + : undefined, + }), + ], +}); + +const app = express(); +app.use(express.json()); + +// mppx middleware: returns 402 with challenge, then validates payment on retry +app.use(mppx.middleware()); + +app.get("/data", (req, res) => { + res.json({ result: "paid content", price: "$0.001 USDC" }); +}); + +app.listen(3002, () => console.log("MPP charge server on http://localhost:3002")); +``` + +**Client:** + +```js +// charge-client.js +import { Mppx } from "mppx"; +import * as stellar from "@stellar/mpp/charge/client"; +import * as StellarSdk from "@stellar/stellar-sdk"; + +const keypair = StellarSdk.Keypair.fromSecret(process.env.STELLAR_SECRET_KEY); + +const mppx = Mppx.create({ + methods: [ + stellar.charge({ + keypair, + mode: "pull", // server assembles and broadcasts the transaction + onProgress(event) { + // event.type: "challenge" | "signed" | "settled" + if (event.type === "settled") console.log("Settled:", event.txHash); + }, + }), + ], +}); + +// mppx wraps fetch — 402 handling is transparent +const res = await mppx.fetch("http://localhost:3002/data"); +console.log(await res.json()); +``` + +**Env vars (server):** `STELLAR_RECIPIENT`, `MPP_SECRET_KEY`, `FEE_PAYER_SECRET` (optional) +**Env vars (client):** `STELLAR_SECRET_KEY` + +**`mode: "pull"` vs `"push"`:** +- `"pull"` — client signs auth entries, server assembles + broadcasts (default; use with `feePayer`) +- `"push"` — client builds and broadcasts the transaction directly (client must have XLM for fees) + +## Channel mode: high-frequency off-chain payments + +The client deploys a one-way payment channel contract, deposits USDC once, then signs **cumulative commitments** off-chain for each request. No transaction per request — only two on-chain txs total (deposit + close). Ideal for AI agents making hundreds of calls in a session. + +### Channel lifecycle + +``` +1. Deploy channel contract (one-time) → C... contract address +2. Client deposits USDC into channel → on-chain tx +3. Per request: client signs commitment → off-chain (just a signature) + Amount is cumulative: each sig covers all previous payments + this one +4. Server closes channel when done → on-chain tx, settles total +``` + +### Prerequisites + +- Deploy a one-way-channel Soroban contract to get a `C...` contract address +- Generate an ed25519 keypair for commitment signing (see [stellar-mpp SDK](https://github.com/stellar/stellar-mpp-sdk)) +- Fund the channel with USDC before making requests + +### Server: + +```js +// channel-server.js +import express from "express"; +import { Mppx, Store } from "mppx"; +import * as stellar from "@stellar/mpp/channel/server"; + +const mppx = Mppx.create({ + secretKey: process.env.MPP_SECRET_KEY, + methods: [ + stellar.channel({ + channel: process.env.CHANNEL_CONTRACT, // C... contract address + commitmentKey: process.env.COMMITMENT_PUBKEY, // 64-char hex ed25519 public key + store: Store.memory(), // dev only — use persistent store in production + network: "stellar:testnet", + }), + ], +}); + +const app = express(); +app.use(express.json()); +app.use(mppx.middleware()); + +app.get("/data", (req, res) => { + res.json({ result: "paid content" }); +}); + +app.listen(3003); +``` + +### Client: + +```js +// channel-client.js +import { Mppx } from "mppx"; +import * as stellar from "@stellar/mpp/channel/client"; +import * as StellarSdk from "@stellar/stellar-sdk"; + +// commitment key must be a raw ed25519 seed — NOT a standard Stellar secret key +const commitmentKey = StellarSdk.Keypair.fromRawEd25519Seed( + Buffer.from(process.env.COMMITMENT_SECRET, "hex") // 64-char hex secret +); + +const mppx = Mppx.create({ + methods: [ + stellar.channel({ + commitmentKey, + onProgress(event) { + // event.type: "challenge" | "signed" + }, + }), + ], +}); + +// Make many requests — each signs a cumulative off-chain commitment +for (let i = 0; i < 100; i++) { + const res = await mppx.fetch("http://localhost:3003/data"); + console.log(i, await res.json()); +} +``` + +### Closing the channel (server-initiated): + +```js +import { close } from "@stellar/mpp/channel/server"; +import * as StellarSdk from "@stellar/stellar-sdk"; + +const txHash = await close({ + channel: process.env.CHANNEL_CONTRACT, + amount: lastCumulativeAmount, // bigint, total USDC owed in base units + signature: lastCommitmentSignature, // hex string from final commitment + feePayer: { envelopeSigner: StellarSdk.Keypair.fromSecret(process.env.FEE_PAYER_SECRET) }, + network: "stellar:testnet", +}); +// Single on-chain transaction settles the full session +console.log("Channel closed:", txHash); +``` + +**Env vars (server):** `CHANNEL_CONTRACT`, `COMMITMENT_PUBKEY`, `MPP_SECRET_KEY`, `FEE_PAYER_SECRET` +**Env vars (client):** `COMMITMENT_SECRET` + +## Packages and subpath imports + +```bash +npm install @stellar/mpp mppx @stellar/stellar-sdk +``` + +| Import path | Recommended import pattern | +|-------------|----------------------------| +| `@stellar/mpp/charge/server` | `import * as stellar from "@stellar/mpp/charge/server"` — use `stellar.charge(...)` | +| `@stellar/mpp/charge/client` | `import * as stellar from "@stellar/mpp/charge/client"` — use `stellar.charge(...)` | +| `@stellar/mpp/channel/server` | `import * as stellar from "@stellar/mpp/channel/server"` — use `stellar.channel(...)`, `stellar.close(...)`, `stellar.getChannelState(...)`, `stellar.watchChannel(...)` | +| `@stellar/mpp/channel/client` | `import * as stellar from "@stellar/mpp/channel/client"` — use `stellar.channel(...)` | +| `@stellar/mpp/channel` | Zod schema definitions for channel types | +| `mppx` | `import { Mppx, Store } from "mppx"` | + +## Testnet runbook + +**Steps shared with all protocols:** +1. Generate keypair + fund with Friendbot (see x402 testnet runbook in Part 1 above) +2. Add USDC trustline +3. Get testnet USDC from [Circle faucet](https://faucet.circle.com/) + +**Channel mode only:** +4. Deploy the one-way-channel contract (see [stellar-mpp-sdk](https://github.com/stellar/stellar-mpp-sdk) for deploy script) +5. Generate a 64-char hex ed25519 seed for the commitment key: + ```bash + node -e "console.log(require('crypto').randomBytes(32).toString('hex'))" + ``` +6. Derive the public key and fund the channel with USDC before making requests + +## Common pitfalls + +**Channel: wrong commitment key format** +- Symptom: `Keypair.fromRawEd25519Seed` throws or signatures fail to verify +- Fix: the commitment key is a raw ed25519 seed as a 64-char hex string — not a Stellar `S...` secret key. Generate with `crypto.randomBytes(32).toString('hex')`. + +**Channel: non-cumulative amounts** +- Symptom: server rejects commitments after the first request +- Fix: each commitment's `amount` must be the **running total** of all payments so far, not just the price of the current request. The server tracks the highest-seen commitment. + +**Channel: deposit TTL expired** +- Symptom: `close()` fails or channel appears drained +- Fix: Soroban contract storage has a TTL. Close the channel before it expires, or extend storage TTL via `bumpContractInstance`. Don't leave channels open indefinitely. + +**Charge: client has no XLM for fees** +- Symptom: `op_insufficient_balance` or fee errors on client-submitted transactions +- Fix: set `mode: "pull"` on the client and configure `feePayer` on the server so the server pays fees. The client only signs auth entries. + +**`Store.memory()` in production** +- Symptom: server loses track of channel state on restart, enables double-spend +- Fix: replace `Store.memory()` with a persistent store (database-backed) before going to production. diff --git a/skill/stellar-assets.md b/skills/assets/SKILL.md similarity index 88% rename from skill/stellar-assets.md rename to skills/assets/SKILL.md index 6b826c8..7a35d4e 100644 --- a/skill/stellar-assets.md +++ b/skills/assets/SKILL.md @@ -1,4 +1,29 @@ -# Stellar Assets (Classic + Soroban Interop) +--- +name: assets +description: Stellar Assets (classic) + trustlines + Stellar Asset Contract (SAC) bridge to Soroban. Covers asset issuance, distribution, authorization flags, clawback, regulated assets, trustline management, and the SAC interop layer that exposes classic assets as Soroban tokens. Use when tokenizing real-world assets, issuing stablecoins, managing trustlines, or bridging classic assets to Soroban contracts. +user-invocable: true +argument-hint: "[asset task]" +--- + +# Stellar Assets, Trustlines, and SAC + +Stellar's native token mechanism: classic asset issuance, trustlines, and the Stellar Asset Contract (SAC) bridge that makes classic assets usable from Soroban. Default to classic assets over custom Soroban tokens unless you need custom logic. + +## When to use this skill +- Issuing a new asset (stablecoin, security token, utility token) +- Setting up trustlines from a client or contract +- Managing issuer flags (auth required, auth revocable, clawback) +- Bridging a classic asset into a Soroban contract via SAC +- Building regulated-asset flows (compliance, KYC, freeze) + +## Related skills +- Custom token contracts (when classic isn't enough) → `../soroban/SKILL.md` +- UI flows for trustline creation and asset display → `../dapp/SKILL.md` +- Looking up balances and trustline state → `../data/SKILL.md` +- Token-related SEPs (SEP-41, SEP-7, etc.) → `../standards/SKILL.md` + +--- + ## Overview diff --git a/skill/frontend-stellar-sdk.md b/skills/dapp/SKILL.md similarity index 92% rename from skill/frontend-stellar-sdk.md rename to skills/dapp/SKILL.md index a112fca..0e0d105 100644 --- a/skill/frontend-stellar-sdk.md +++ b/skills/dapp/SKILL.md @@ -1,4 +1,30 @@ -# Frontend with Stellar SDK (Next.js / React) +--- +name: dapp +description: Stellar dApp / frontend development. Covers the JavaScript stellar-sdk (browser + Node.js), Freighter wallet, Stellar Wallets Kit (multi-wallet), Wallet Standard, smart accounts with passkeys, transaction building / signing / submission, Soroban contract invocation from the client, simulation, and error handling. Use when building a React/Next.js/Node.js app that talks to Stellar or Soroban. +user-invocable: true +argument-hint: "[dapp task]" +--- + +# Stellar dApp / Frontend + +Client-side development with `@stellar/stellar-sdk`, wallet connection, signing, and submitting transactions. Covers both classic Stellar operations and Soroban contract invocation from the browser or Node.js. + +## When to use this skill +- Connecting Freighter or other wallets via Stellar Wallets Kit +- Building, simulating, signing, and submitting transactions +- Invoking Soroban contracts from a frontend +- Implementing smart accounts with passkeys +- Handling network passphrases (Mainnet / Testnet / local) + +## Related skills +- Writing the contract being invoked → `../soroban/SKILL.md` +- Issuing assets and managing trustlines → `../assets/SKILL.md` +- Querying chain state via RPC / Horizon → `../data/SKILL.md` +- Building paid APIs or agent payment clients → `../agentic-payments/SKILL.md` +- SEPs the wallet/anchor flows depend on → `../standards/SKILL.md` + +--- + ## Goals - Single SDK instance for the app (RPC/Horizon + transaction building) @@ -26,7 +52,7 @@ npm install @stellar/stellar-sdk @creit.tech/stellar-wallets-kit ## SDK Initialization -> For the full API reference (RPC methods, Horizon endpoints, migration guide), see [api-rpc-horizon.md](api-rpc-horizon.md). +> For the full API reference (RPC methods, Horizon endpoints, migration guide), see [api-rpc-horizon.md](../data/SKILL.md). ### Basic Setup ```typescript diff --git a/skill/api-rpc-horizon.md b/skills/data/SKILL.md similarity index 90% rename from skill/api-rpc-horizon.md rename to skills/data/SKILL.md index b4d72bf..84ebcf2 100644 --- a/skill/api-rpc-horizon.md +++ b/skills/data/SKILL.md @@ -1,4 +1,29 @@ -# API Access (Stellar RPC + Horizon) +--- +name: data +description: Querying Stellar chain data via Stellar RPC (preferred) and Horizon (legacy). Covers RPC JSON-RPC methods, Horizon REST endpoints, streaming, pagination, historical queries, Hubble/Galexie for deep history, and the RPC/Horizon migration story. Use when reading balances, transactions, operations, ledgers, contract events, or building any indexer/analytics workflow. +user-invocable: true +argument-hint: "[data task]" +--- + +# Stellar Data: RPC + Horizon + +API access for reading chain state. Stellar RPC is the preferred entry point for new projects; Horizon remains for legacy and historical-query workflows. For deeper history beyond RPC's 7-day window, use Hubble/Galexie. + +## When to use this skill +- Calling Stellar RPC methods (`getLatestLedger`, `getLedgerEntries`, `getEvents`, `simulateTransaction`, `sendTransaction`) +- Querying Horizon endpoints (accounts, transactions, operations, effects, ledgers) +- Streaming live events or operations +- Pulling historical data beyond RPC's 7-day window (Hubble, Galexie) +- Choosing between RPC and Horizon for a given workflow + +## Related skills +- Building transactions to send → `../dapp/SKILL.md` +- Soroban contract simulation and event emission → `../soroban/SKILL.md` +- Asset balance and trustline lookups → `../assets/SKILL.md` +- Standards (SEP-7 deeplinks, SEP-10 auth) → `../standards/SKILL.md` + +--- + ## Overview @@ -402,7 +427,7 @@ See the full indexer directory: https://developers.stellar.org/docs/data/indexer ## Network Configuration -> For a React/Next.js-specific setup, see [frontend-stellar-sdk.md](frontend-stellar-sdk.md). +> For a React/Next.js-specific setup, see [frontend-stellar-sdk.md](../dapp/SKILL.md). > For mainnet RPC, set `STELLAR_MAINNET_RPC_URL` from a provider in the [RPC providers directory](https://developers.stellar.org/docs/data/apis/rpc/providers). ### Environment-Based Setup diff --git a/skills/soroban/SKILL.md b/skills/soroban/SKILL.md new file mode 100644 index 0000000..ea5ced8 --- /dev/null +++ b/skills/soroban/SKILL.md @@ -0,0 +1,2584 @@ +--- +name: soroban +description: 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. +user-invocable: true +argument-hint: "[contract task]" +--- + +# Soroban Smart Contracts + +End-to-end guide for building Soroban contracts: writing them, testing them, securing them, and shipping advanced architectures. This skill bundles five concerns that live and die together — the contract code, the tests, the security posture, the design patterns, and the gotchas. + +## When to use this skill +- Writing a Soroban contract in Rust +- Setting up unit, integration, fuzz, or property tests +- Reviewing a contract for security issues (authorization, reentrancy-adjacent bugs, storage hygiene, TTL, overflow) +- Architecting upgradeable contracts, factories, governance, or DeFi primitives +- Debugging a Soroban-specific error (auth, storage, archival, resource limits) + +## Related skills +- Assets, trustlines, and SAC bridge → `../assets/SKILL.md` +- Frontend/wallets that call your contract → `../dapp/SKILL.md` +- Chain data queries (RPC/Horizon) → `../data/SKILL.md` +- ZK cryptography (BLS12-381, BN254, Poseidon) → `../zk-proofs/SKILL.md` +- SEP/CAP standards and ecosystem links → `../standards/SKILL.md` + +--- + +# Part 1: Contract Development + + +## When to use Soroban +Use Soroban when you need: +- Custom on-chain logic beyond Stellar's built-in operations +- Programmable escrow, lending, or DeFi primitives +- Complex authorization rules +- State management beyond account balances +- Interoperability with Stellar Assets via SAC + +## Quick Navigation +- Initialization and constructors: [Project Setup](#project-setup), [Contract Constructors (Protocol 22+)](#contract-constructors-protocol-22) +- Core implementation patterns: [Core Contract Structure](#core-contract-structure), [Storage Types](#storage-types), [Authorization](#authorization) +- Advanced interactions: [Cross-Contract Calls](#cross-contract-calls), [Events](#events), [Error Handling](#error-handling) +- Delivery workflow: [Building and Deploying](#building-and-deploying), [Unit Testing](#unit-testing), [Best Practices](#best-practices) +- ZK status guidance: [Zero-Knowledge Cryptography (Status-Sensitive)](#zero-knowledge-cryptography-status-sensitive) + +## Alternative Languages + +Rust is the primary and recommended language for Soroban contracts. Community-maintained alternatives exist but are not recommended for production: +- **AssemblyScript**: [`as-soroban-sdk`](https://github.com/Soneso/as-soroban-sdk) by Soneso — allows TypeScript-like syntax, officially listed on Stellar docs, but may lag behind the latest protocol version +- **Solidity**: [Hyperledger Solang](https://github.com/hyperledger-solang/solang) — SDF-funded, compiles Solidity to Soroban WASM, currently **pre-alpha** ([docs](https://developers.stellar.org/docs/learn/migrate/evm/solidity-support-via-solang)) + +## Architecture Overview + +### Host-Guest Model +Soroban uses a WebAssembly sandbox with strict separation: +- **Host Environment**: Provides storage, crypto, cross-contract calls +- **Guest Contract**: Your Rust code compiled to WASM +- Contracts reference host objects via handles (not direct memory) + +### Key Constraints +- `#![no_std]` required - no Rust standard library +- 64KB contract size limit (use release optimizations) +- Limited heap allocation +- No string type (use `String` from soroban-sdk or `Symbol` for short strings) +- `Symbol` limited to 32 characters (was 10 in earlier versions) + +## Project Setup + +### Initialize a new contract +```bash +stellar contract init my-contract +cd my-contract +``` + +This creates: +``` +my-contract/ +├── Cargo.toml +├── src/ +│ └── lib.rs +└── contracts/ + └── hello_world/ + ├── Cargo.toml + └── src/ + └── lib.rs +``` + +### Cargo.toml configuration +```toml +[package] +name = "my-contract" +version = "0.1.0" +edition = "2021" + +[lib] +crate-type = ["cdylib"] + +[dependencies] +soroban-sdk = "25.0.1" # check https://crates.io/crates/soroban-sdk for latest + +[dev-dependencies] +soroban-sdk = { version = "25.0.1", features = ["testutils"] } # match above + +[profile.release] +opt-level = "z" +overflow-checks = true +debug = 0 +strip = "symbols" +debug-assertions = false +panic = "abort" +codegen-units = 1 +lto = true + +[profile.release-with-logs] +inherits = "release" +debug-assertions = true +``` + +## Contract Constructors (Protocol 22+) + +Use constructors for atomic initialization when protocol support is available. This avoids a separate `initialize` transaction and reduces front-running risk. + +### Constructor pattern +```rust +#![no_std] +use soroban_sdk::{contract, contractimpl, contracttype, Address, Env}; + +#[contracttype] +#[derive(Clone)] +pub enum DataKey { + Admin, + Value, +} + +#[contract] +pub struct MyContract; + +#[contractimpl] +impl MyContract { + // Runs once at deployment time. + pub fn __constructor(env: Env, admin: Address, initial_value: u32) { + env.storage().instance().set(&DataKey::Admin, &admin); + env.storage().instance().set(&DataKey::Value, &initial_value); + } +} +``` + +### Deploy with constructor args (CLI) +```bash +stellar contract deploy \ + --wasm target/wasm32-unknown-unknown/release/my_contract.wasm \ + --source alice \ + --network testnet \ + -- \ + --admin alice \ + --initial_value 100 +``` + +### Rules +1. Name must be `__constructor` exactly. +2. Constructor returns `()` (no return value). +3. Runs only at creation time and does not run on upgrade. +4. If constructor fails, deployment fails atomically. + +### Backwards compatibility +If targeting older protocol environments, use guarded `initialize` patterns and prevent re-initialization explicitly. + +## Core Contract Structure + +### Basic Contract +```rust +#![no_std] +use soroban_sdk::{contract, contractimpl, symbol_short, vec, Env, Symbol, Vec}; + +#[contract] +pub struct HelloContract; + +#[contractimpl] +impl HelloContract { + pub fn hello(env: Env, to: Symbol) -> Vec { + vec![&env, symbol_short!("Hello"), to] + } +} +``` + +### Contract with State +```rust +#![no_std] +use soroban_sdk::{contract, contractimpl, contracttype, Address, Env}; + +#[contracttype] +#[derive(Clone)] +pub enum DataKey { + Counter, + Admin, + UserBalance(Address), +} + +#[contract] +pub struct CounterContract; + +#[contractimpl] +impl CounterContract { + pub fn initialize(env: Env, admin: Address) { + if env.storage().instance().has(&DataKey::Admin) { + panic!("already initialized"); + } + env.storage().instance().set(&DataKey::Admin, &admin); + env.storage().instance().set(&DataKey::Counter, &0u32); + } + + pub fn increment(env: Env) -> u32 { + let mut count: u32 = env.storage().instance().get(&DataKey::Counter).unwrap_or(0); + count += 1; + env.storage().instance().set(&DataKey::Counter, &count); + + // Extend TTL to prevent archival + env.storage().instance().extend_ttl(100, 518400); // threshold, ~30 days + + count + } + + pub fn get_count(env: Env) -> u32 { + env.storage().instance().get(&DataKey::Counter).unwrap_or(0) + } +} +``` + +## Storage Types + +Soroban has three storage types with different costs and lifetimes: + +### Instance Storage +- Tied to contract instance lifetime +- Shared across all users +- Best for: admin addresses, global config, counters +```rust +env.storage().instance().set(&key, &value); +env.storage().instance().get(&key); +env.storage().instance().extend_ttl(min_ttl, extend_to); +``` + +### Persistent Storage +- Survives archival (can be restored) +- Per-key TTL management +- Best for: user balances, important state +```rust +env.storage().persistent().set(&key, &value); +env.storage().persistent().get(&key); +env.storage().persistent().extend_ttl(&key, min_ttl, extend_to); +``` + +### Temporary Storage +- Cheapest, automatically deleted when TTL expires +- Cannot be restored after archival +- Best for: caches, temporary flags, session data +```rust +env.storage().temporary().set(&key, &value); +env.storage().temporary().get(&key); +env.storage().temporary().extend_ttl(&key, min_ttl, extend_to); +``` + +### TTL Management +```rust +// Check remaining TTL +let ttl = env.storage().persistent().get_ttl(&key); + +// Extend if below threshold +const MIN_TTL: u32 = 17280; // ~1 day at 5s ledgers +const EXTEND_TO: u32 = 518400; // ~30 days + +if ttl < MIN_TTL { + env.storage().persistent().extend_ttl(&key, MIN_TTL, EXTEND_TO); +} +``` + +## Data Types + +### Primitive Types +```rust +use soroban_sdk::{Address, Bytes, BytesN, Map, String, Symbol, Vec, I128, U256}; + +// Address - account or contract identifier +let addr: Address = env.current_contract_address(); + +// Symbol - short strings (max 32 chars) +let sym: Symbol = symbol_short!("transfer"); + +// String - longer strings +let s: String = String::from_str(&env, "Hello, Stellar!"); + +// Fixed-size bytes +let hash: BytesN<32> = env.crypto().sha256(&bytes); + +// Collections +let v: Vec = vec![&env, 1, 2, 3]; +let m: Map = Map::new(&env); +``` + +### Custom Types +```rust +#[contracttype] +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct TokenMetadata { + pub name: String, + pub symbol: Symbol, + pub decimals: u32, +} + +#[contracttype] +#[derive(Clone)] +pub enum DataKey { + Admin, + Balance(Address), + Allowance(Address, Address), // (owner, spender) +} +``` + +## Authorization + +### Requiring Authorization +```rust +#[contractimpl] +impl TokenContract { + pub fn transfer(env: Env, from: Address, to: Address, amount: i128) { + // Require 'from' to authorize this call + from.require_auth(); + + // Or require auth for specific arguments + from.require_auth_for_args((&to, amount).into_val(&env)); + + // Transfer logic... + } +} +``` + +### Admin Patterns +```rust +fn require_admin(env: &Env) { + let admin: Address = env.storage().instance().get(&DataKey::Admin).unwrap(); + admin.require_auth(); +} + +pub fn set_admin(env: Env, new_admin: Address) { + require_admin(&env); + env.storage().instance().set(&DataKey::Admin, &new_admin); +} +``` + +## Cross-Contract Calls + +### Calling Another Contract +```rust +use soroban_sdk::{contract, contractimpl, Address, Env}; + +mod token_contract { + soroban_sdk::contractimport!( + file = "../token/target/wasm32-unknown-unknown/release/token.wasm" + ); +} + +#[contract] +pub struct VaultContract; + +#[contractimpl] +impl VaultContract { + pub fn deposit(env: Env, user: Address, token: Address, amount: i128) { + user.require_auth(); + + // Create client for token contract + let token_client = token_contract::Client::new(&env, &token); + + // Call transfer on token contract + token_client.transfer(&user, &env.current_contract_address(), &amount); + + // Update vault state... + } +} +``` + +### Using Stellar Asset Contract (SAC) +```rust +use soroban_sdk::token::Client as TokenClient; + +pub fn transfer_asset(env: Env, from: Address, to: Address, asset: Address, amount: i128) { + from.require_auth(); + + let token = TokenClient::new(&env, &asset); + token.transfer(&from, &to, &amount); +} +``` + +## Events + +### Emitting Events +```rust +use soroban_sdk::{contract, contractevent, contractimpl, Address, Env}; + +#[contractevent(topics = ["transfer"])] +pub struct TransferEvent { + pub from: Address, + pub to: Address, + pub amount: i128, +} + +#[contract] +pub struct TokenContract; + +#[contractimpl] +impl TokenContract { + pub fn transfer(env: Env, from: Address, to: Address, amount: i128) { + // ... transfer logic ... + + // Emit event + TransferEvent { from, to, amount }.publish(&env); + } +} +``` + +## Error Handling + +### Custom Errors +```rust +use soroban_sdk::contracterror; + +#[contracterror] +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +#[repr(u32)] +pub enum ContractError { + AlreadyInitialized = 1, + NotInitialized = 2, + InsufficientBalance = 3, + Unauthorized = 4, + InvalidAmount = 5, +} + +// Usage +pub fn transfer(env: Env, from: Address, to: Address, amount: i128) -> Result<(), ContractError> { + if amount <= 0 { + return Err(ContractError::InvalidAmount); + } + + let balance: i128 = get_balance(&env, &from); + if balance < amount { + return Err(ContractError::InsufficientBalance); + } + + // ... transfer logic ... + Ok(()) +} +``` + +## Building and Deploying + +### Build Contract +```bash +# Build optimized WASM +stellar contract build + +# Output: target/wasm32-unknown-unknown/release/my_contract.wasm +``` + +### Deploy to Testnet +```bash +# Generate and fund a new identity +stellar keys generate --global alice --network testnet --fund + +# Deploy contract +stellar contract deploy \ + --wasm target/wasm32-unknown-unknown/release/my_contract.wasm \ + --source alice \ + --network testnet + +# Returns: CONTRACT_ID (starts with 'C') +``` + +### Initialize Contract +```bash +stellar contract invoke \ + --id CONTRACT_ID \ + --source alice \ + --network testnet \ + -- \ + initialize \ + --admin alice +``` + +### Invoke Functions +```bash +stellar contract invoke \ + --id CONTRACT_ID \ + --source alice \ + --network testnet \ + -- \ + increment +``` + +## Unit Testing + +```rust +#![cfg(test)] + +use super::*; +use soroban_sdk::testutils::Address as _; +use soroban_sdk::Env; + +#[test] +fn test_increment() { + let env = Env::default(); + let contract_id = env.register_contract(None, CounterContract); + let client = CounterContractClient::new(&env, &contract_id); + + let admin = Address::generate(&env); + client.initialize(&admin); + + assert_eq!(client.get_count(), 0); + assert_eq!(client.increment(), 1); + assert_eq!(client.increment(), 2); + assert_eq!(client.get_count(), 2); +} + +#[test] +fn test_transfer_with_auth() { + let env = Env::default(); + env.mock_all_auths(); // Auto-approve all auth requests + + let contract_id = env.register_contract(None, TokenContract); + let client = TokenContractClient::new(&env, &contract_id); + + let alice = Address::generate(&env); + let bob = Address::generate(&env); + + // Mint tokens to alice + client.mint(&alice, &1000); + + // Transfer from alice to bob + client.transfer(&alice, &bob, &100); + + assert_eq!(client.balance(&alice), 900); + assert_eq!(client.balance(&bob), 100); +} +``` + +## Best Practices + +### Contract Size Optimization +- Use `symbol_short!()` for symbols under 9 chars (more efficient) +- Avoid unnecessary string operations +- Use appropriate storage type for data lifetime +- Consider splitting large contracts + +### Storage Efficiency +- Use compact data structures +- Clean up temporary storage +- Batch storage operations when possible +- Manage TTLs proactively to avoid archival + +### Security +- Always validate inputs +- Use `require_auth()` for sensitive operations +- Check contract ownership in initialization +- Prevent reinitialization attacks +- Validate cross-contract call targets + +### Gas/Resource Optimization +- Minimize storage reads/writes +- Use events for data that doesn't need on-chain queries +- Batch operations where possible +- Profile resource usage with `stellar contract invoke --sim` + +## Zero-Knowledge Cryptography (Status-Sensitive) + +Stellar's ZK cryptography capabilities are evolving. Treat availability as protocol- and network-dependent. + +- [CAP-0059](https://github.com/stellar/stellar-protocol/blob/master/core/cap-0059.md): BLS12-381 primitives +- [CAP-0074](https://github.com/stellar/stellar-protocol/blob/master/core/cap-0074.md): BN254 host functions (proposed) +- [CAP-0075](https://github.com/stellar/stellar-protocol/blob/master/core/cap-0075.md): Poseidon/Poseidon2 host functions (proposed) + +Before implementation, always verify: +1. CAP status in the CAP preamble (`Accepted`/`Implemented` vs draft/awaiting decision) +2. Target network software version and protocol support +3. `soroban-sdk` release support for the target host functions + +### Practical guidance +- Use BLS12-381 features where supported and documented in your target SDK/network. +- For BN254/Poseidon plans, design feature flags and graceful fallbacks until support is active. +- Keep cryptographic assumptions explicit in audits and deployment notes. + +### Example references +- [Groth16 Verifier](https://github.com/stellar/soroban-examples/tree/main/groth16_verifier) +- [Soroban examples repository](https://github.com/stellar/soroban-examples) + +> See [zk-proofs.md](../zk-proofs/SKILL.md) for Groth16 verification patterns, Poseidon usage, Noir/RISC Zero integration, and implementation guidance. + +--- + +# Part 2: Testing Strategy + + +## Quick Navigation +- Strategy overview: [Testing Pyramid](#testing-pyramid) +- 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) +- Integration and CI: [Integration Testing Patterns](#integration-testing-patterns), [Test Configuration](#test-configuration), [CI/CD Configuration](#cicd-configuration) +- 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) +- Performance and readiness: [Resource Profiling](#resource-profiling), [Best Practices](#best-practices) + +## Testing Pyramid + +1. **Unit tests (fast)**: Native Rust tests with `soroban-sdk` testutils +2. **Local integration tests**: Stellar Quickstart Docker +3. **Testnet tests**: Deploy and test on public testnet +4. **Mainnet smoke tests**: Final validation before production + +## Unit Testing with Soroban SDK + +The Soroban SDK provides comprehensive testing utilities that run natively (not in WASM), enabling fast iteration with full debugging support. + +### Basic Test Setup + +```rust +#![cfg(test)] + +use soroban_sdk::{testutils::Address as _, Address, Env}; + +// Import your contract +use crate::{Contract, ContractClient}; + +#[test] +fn test_basic_functionality() { + // Create test environment + let env = Env::default(); + + // Register contract + let contract_id = env.register_contract(None, Contract); + + // Create typed client + let client = ContractClient::new(&env, &contract_id); + + // Generate test addresses + let user = Address::generate(&env); + + // Call contract functions + client.initialize(&user); + + // Assert results + assert_eq!(client.get_value(), 0); +} +``` + +### Testing Authorization + +```rust +#[test] +fn test_with_auth() { + let env = Env::default(); + + // Mock all authorizations automatically + env.mock_all_auths(); + + let contract_id = env.register_contract(None, TokenContract); + let client = TokenContractClient::new(&env, &contract_id); + + let admin = Address::generate(&env); + let user1 = Address::generate(&env); + let user2 = Address::generate(&env); + + // Initialize and mint + client.initialize(&admin); + client.mint(&user1, &1000); + + // Transfer (requires auth from user1) + client.transfer(&user1, &user2, &100); + + assert_eq!(client.balance(&user1), 900); + assert_eq!(client.balance(&user2), 100); + + // Verify which auths were required + let auths = env.auths(); + assert_eq!(auths.len(), 1); + // auths[0] contains (address, contract_id, function, args) +} +``` + +### Testing with Specific Auth Requirements + +```rust +#[test] +fn test_specific_auth() { + let env = Env::default(); + let contract_id = env.register_contract(None, Contract); + let client = ContractClient::new(&env, &contract_id); + + let user = Address::generate(&env); + + // Mock auth only for specific address + env.mock_auths(&[MockAuth { + address: &user, + invoke: &MockAuthInvoke { + contract: &contract_id, + fn_name: "transfer", + args: (&user, &other, &100i128).into_val(&env), + sub_invokes: &[], + }, + }]); + + client.transfer(&user, &other, &100); +} +``` + +### Testing Time-Dependent Logic + +```rust +#[test] +fn test_time_based() { + let env = Env::default(); + let contract_id = env.register_contract(None, VestingContract); + let client = VestingContractClient::new(&env, &contract_id); + + let beneficiary = Address::generate(&env); + + // Set initial timestamp + env.ledger().set_timestamp(1000); + + client.create_vesting(&beneficiary, &1000, &2000); // unlock at t=2000 + + // Try to claim before unlock + assert!(client.try_claim(&beneficiary).is_err()); + + // Advance time past unlock + env.ledger().set_timestamp(2500); + + // Now claim succeeds + client.claim(&beneficiary); +} +``` + +### Testing Ledger State + +```rust +#[test] +fn test_ledger_manipulation() { + let env = Env::default(); + + // Set ledger sequence + env.ledger().set_sequence_number(1000); + + // Set timestamp + env.ledger().set_timestamp(1704067200); // Jan 1, 2024 + + // Set network passphrase + env.ledger().set_network_id([0u8; 32]); // Custom network ID + + // Get current values + let seq = env.ledger().sequence(); + let ts = env.ledger().timestamp(); +} +``` + +### Testing Events + +```rust +#[test] +fn test_events() { + let env = Env::default(); + let contract_id = env.register_contract(None, Contract); + let client = ContractClient::new(&env, &contract_id); + + client.do_something(); + + // Get all events + let events = env.events().all(); + + // Check specific event + assert_eq!(events.len(), 1); + + let event = &events[0]; + // event.0 = contract_id + // event.1 = topics (Vec) + // event.2 = data (Val) +} +``` + +### Testing Storage + +```rust +#[test] +fn test_storage_ttl() { + let env = Env::default(); + let contract_id = env.register_contract(None, Contract); + let client = ContractClient::new(&env, &contract_id); + + client.store_data(); + + // Check TTL + let key = DataKey::MyData; + let ttl = env.as_contract(&contract_id, || { + env.storage().persistent().get_ttl(&key) + }); + + assert!(ttl > 0); +} +``` + +### Testing Cross-Contract Calls + +```rust +#[test] +fn test_cross_contract() { + let env = Env::default(); + + // Register both contracts + let token_id = env.register_contract_wasm(None, token::WASM); + let vault_id = env.register_contract(None, VaultContract); + + let token_client = token::Client::new(&env, &token_id); + let vault_client = VaultContractClient::new(&env, &vault_id); + + env.mock_all_auths(); + + let user = Address::generate(&env); + + // Setup: mint tokens to user + token_client.mint(&user, &1000); + + // Test: deposit tokens into vault + vault_client.deposit(&user, &token_id, &500); + + assert_eq!(token_client.balance(&user), 500); + assert_eq!(vault_client.balance(&user), 500); +} +``` + +## Local Testing with Stellar Quickstart + +### Start Local Network + +```bash +# Pull and run Stellar Quickstart +docker run --rm -it -p 8000:8000 \ + --name stellar \ + stellar/quickstart:latest \ + --local \ + --enable-soroban-rpc + +# Or use Stellar CLI +stellar container start local +``` + +### Configure for Local Network + +```typescript +import * as StellarSdk from "@stellar/stellar-sdk"; + +const LOCAL_RPC = "http://localhost:8000/soroban/rpc"; +const LOCAL_HORIZON = "http://localhost:8000"; +const LOCAL_PASSPHRASE = "Standalone Network ; February 2017"; + +const rpc = new StellarSdk.rpc.Server(LOCAL_RPC); +const horizon = new StellarSdk.Horizon.Server(LOCAL_HORIZON); +``` + +### Fund Test Accounts (Local) + +```bash +# Using Stellar CLI +stellar keys generate --global test-account --network local --fund + +# Or via friendbot endpoint +curl "http://localhost:8000/friendbot?addr=G..." +``` + +### Deploy and Test Locally + +```bash +# Deploy contract to local network +stellar contract deploy \ + --wasm target/wasm32-unknown-unknown/release/contract.wasm \ + --source test-account \ + --network local + +# Invoke contract +stellar contract invoke \ + --id CONTRACT_ID \ + --source test-account \ + --network local \ + -- \ + function_name \ + --arg value +``` + +## Testnet Testing + +### Network Configuration + +```bash +# Testnet RPC: https://soroban-testnet.stellar.org +# Testnet Horizon: https://horizon-testnet.stellar.org +# Network Passphrase: "Test SDF Network ; September 2015" +# Friendbot: https://friendbot.stellar.org +``` + +### Create and Fund Testnet Account + +```bash +# Generate new identity +stellar keys generate --global my-testnet-key --network testnet + +# Fund via Friendbot +stellar keys fund my-testnet-key --network testnet + +# Or manually +curl "https://friendbot.stellar.org?addr=G..." +``` + +### Deploy to Testnet + +```bash +# Deploy contract +stellar contract deploy \ + --wasm target/wasm32-unknown-unknown/release/contract.wasm \ + --source my-testnet-key \ + --network testnet + +# Install contract code (separate from deployment) +stellar contract install \ + --wasm target/wasm32-unknown-unknown/release/contract.wasm \ + --source my-testnet-key \ + --network testnet +``` + +### Testnet Reset Awareness + +**Important**: Testnet resets approximately quarterly: +- All accounts and contracts are deleted +- Plan for re-deployment after resets +- Don't rely on persistent state for test data + +Check reset schedule: https://stellar.org/developers/blog + +## Integration Testing Patterns + +### TypeScript Integration Tests + +```typescript +// tests/integration/contract.test.ts +import * as StellarSdk from "@stellar/stellar-sdk"; + +const RPC_URL = process.env.RPC_URL || "http://localhost:8000/soroban/rpc"; +const NETWORK_PASSPHRASE = process.env.NETWORK_PASSPHRASE || "Standalone Network ; February 2017"; + +describe("Contract Integration Tests", () => { + let rpc: StellarSdk.rpc.Server; + let keypair: StellarSdk.Keypair; + let contractId: string; + + beforeAll(async () => { + rpc = new StellarSdk.rpc.Server(RPC_URL); + keypair = StellarSdk.Keypair.random(); + + // Fund account + await fundAccount(keypair.publicKey()); + + // Deploy contract + contractId = await deployContract(keypair); + }); + + test("should initialize contract", async () => { + const account = await rpc.getAccount(keypair.publicKey()); + const contract = new StellarSdk.Contract(contractId); + + const tx = new StellarSdk.TransactionBuilder(account, { + fee: "100", + networkPassphrase: NETWORK_PASSPHRASE, + }) + .addOperation( + contract.call( + "initialize", + StellarSdk.Address.fromString(keypair.publicKey()).toScVal() + ) + ) + .setTimeout(30) + .build(); + + const simResult = await rpc.simulateTransaction(tx); + const preparedTx = StellarSdk.rpc.assembleTransaction(tx, simResult); + + preparedTx.sign(keypair); + const result = await rpc.sendTransaction(preparedTx.build()); + + expect(result.status).not.toBe("ERROR"); + }); +}); +``` + +### Rust Integration Tests + +```rust +// tests/integration_test.rs +use soroban_sdk::{Env, Address}; +use std::process::Command; + +#[test] +#[ignore] // Run with: cargo test -- --ignored +fn integration_test_with_local_network() { + // Requires local network running + let output = Command::new("stellar") + .args([ + "contract", "invoke", + "--id", "CONTRACT_ID", + "--source", "test-account", + "--network", "local", + "--", + "get_count" + ]) + .output() + .expect("Failed to invoke contract"); + + assert!(output.status.success()); +} +``` + +## Test Configuration + +### Cargo.toml for Tests + +```toml +[dev-dependencies] +soroban-sdk = { version = "25.0.1", features = ["testutils"] } # match [dependencies] version + +[profile.test] +opt-level = 0 +debug = true +``` + +### Running Tests + +```bash +# Run unit tests +cargo test + +# Run with output +cargo test -- --nocapture + +# Run specific test +cargo test test_transfer + +# Run ignored (integration) tests +cargo test -- --ignored +``` + +## CI/CD Configuration + +### GitHub Actions Example + +```yaml +name: Test Soroban Contract + +on: [push, pull_request] + +jobs: + unit-tests: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Install Rust + uses: dtolnay/rust-toolchain@stable + + - name: Add WASM target + run: rustup target add wasm32-unknown-unknown + + - name: Run unit tests + run: cargo test + + - name: Build contract + run: cargo build --release --target wasm32-unknown-unknown + + integration-tests: + runs-on: ubuntu-latest + needs: unit-tests + services: + stellar: + image: stellar/quickstart:latest + ports: + - 8000:8000 + options: >- + --health-cmd "curl -f http://localhost:8000 || exit 1" + --health-interval 10s + --health-timeout 5s + --health-retries 10 + + steps: + - uses: actions/checkout@v4 + + - name: Install Stellar CLI + run: | + cargo install stellar-cli --locked + + - name: Deploy and test + run: | + stellar keys generate --global ci-test --network local --fund + stellar contract deploy \ + --wasm target/wasm32-unknown-unknown/release/contract.wasm \ + --source ci-test \ + --network local +``` + +## Best Practices + +### Test Organization +``` +project/ +├── src/ +│ └── lib.rs +├── tests/ +│ ├── common/ +│ │ └── mod.rs # Shared test utilities +│ ├── unit/ +│ │ ├── mod.rs +│ │ └── transfer.rs +│ └── integration/ +│ └── full_flow.rs +└── Cargo.toml +``` + +### Test Utilities Module + +```rust +// tests/common/mod.rs +use soroban_sdk::{testutils::Address as _, Address, Env}; +use crate::{Contract, ContractClient}; + +pub fn setup_contract(env: &Env) -> (Address, ContractClient) { + let contract_id = env.register_contract(None, Contract); + let client = ContractClient::new(env, &contract_id); + let admin = Address::generate(env); + + env.mock_all_auths(); + client.initialize(&admin); + + (contract_id, client) +} + +pub fn create_funded_user(env: &Env, client: &ContractClient, amount: i128) -> Address { + let user = Address::generate(env); + client.mint(&user, &amount); + user +} +``` + +## Fuzz Testing + +Soroban 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. + +### Setup + +```bash +# Install nightly Rust + cargo-fuzz +rustup install nightly +cargo install --locked cargo-fuzz + +# Initialize fuzz targets +cargo fuzz init +``` + +Update `Cargo.toml` to include both crate types: +```toml +[lib] +crate-type = ["lib", "cdylib"] +``` + +Add to `fuzz/Cargo.toml`: +```toml +[dependencies] +soroban-sdk = { version = "25.0.1", features = ["testutils"] } +``` + +### Writing a Fuzz Target + +```rust +// fuzz/fuzz_targets/fuzz_deposit.rs +#![no_main] + +use libfuzzer_sys::fuzz_target; +use soroban_sdk::{testutils::Address as _, Address, Env}; +use my_contract::{Contract, ContractClient}; + +fuzz_target!(|input: (u64, i128)| { + let (seed, amount) = input; + let env = Env::default(); + env.mock_all_auths(); + + let contract_id = env.register(Contract, ()); + let client = ContractClient::new(&env, &contract_id); + let user = Address::generate(&env); + + // Initialize + client.initialize(&user); + + // Fuzz deposit — should never panic unexpectedly + let _ = client.try_deposit(&user, &amount); +}); +``` + +### Running Fuzz Tests + +```bash +# Run (use --sanitizer=thread on macOS) +cargo +nightly fuzz run fuzz_deposit + +# Generate code coverage +cargo +nightly fuzz coverage fuzz_deposit +``` + +### Soroban Token Fuzzer + +Reusable library for fuzzing token contracts: +- **GitHub**: https://github.com/brson/soroban-token-fuzzer + +### Documentation + +- [Stellar Fuzzing Guide](https://developers.stellar.org/docs/build/guides/testing/fuzzing) +- [Fuzzing Example Contract](https://developers.stellar.org/docs/build/smart-contracts/example-contracts/fuzzing) + +## Property-Based Testing + +Use `proptest` with `SorobanArbitrary` for QuickCheck-style property testing that runs in standard `cargo test`. + +```rust +#[cfg(test)] +mod prop_tests { + use super::*; + use proptest::prelude::*; + use soroban_sdk::{testutils::Address as _, Env}; + + proptest! { + #[test] + fn deposit_then_withdraw_preserves_balance(amount in 1i128..=i128::MAX) { + let env = Env::default(); + env.mock_all_auths(); + let contract_id = env.register(Contract, ()); + let client = ContractClient::new(&env, &contract_id); + let user = Address::generate(&env); + + client.initialize(&user); + client.deposit(&user, &amount); + client.withdraw(&user, &amount); + + prop_assert_eq!(client.balance(&user), 0); + } + } +} +``` + +**Recommended workflow**: Use `cargo-fuzz` interactively to find deep bugs, then convert to `proptest` for regression prevention in CI. + +## Differential Testing with Test Snapshots + +Soroban automatically writes JSON snapshots at the end of every test to `test_snapshots/`, capturing events and final ledger state. Commit these to source control — diffs reveal unintended behavioral changes. + +### Comparing Against Deployed Contracts + +```rust +// Fetch deployed contract for comparison +// $ stellar contract fetch --id C... --out-file deployed.wasm + +mod deployed { + soroban_sdk::contractimport!(file = "deployed.wasm"); +} + +#[test] +fn test_upgrade_compatibility() { + let env = Env::default(); + env.mock_all_auths(); + + // Register both versions + let old_id = env.register_contract_wasm(None, deployed::WASM); + let new_id = env.register(NewContract, ()); + + let old_client = deployed::Client::new(&env, &old_id); + let new_client = NewContractClient::new(&env, &new_id); + + let user = Address::generate(&env); + + // Run identical operations and compare + old_client.initialize(&user); + new_client.initialize(&user); + + assert_eq!(old_client.get_value(), new_client.get_value()); +} +``` + +- **Docs**: [Differential Tests with Test Snapshots](https://developers.stellar.org/docs/build/guides/testing/differential-tests-with-test-snapshots) + +## Fork Testing + +Test against real production state using ledger snapshots: + +```bash +# Create snapshot of deployed contract +stellar snapshot create --address C... --output json --out snapshot.json + +# Optionally at a specific ledger +stellar snapshot create --address C... --ledger 12345678 --output json --out snapshot.json +``` + +```rust +#[test] +fn test_against_mainnet_state() { + let env = Env::from_ledger_snapshot_file("snapshot.json"); + env.mock_all_auths(); + + let contract_id = /* contract address from snapshot */; + let client = ContractClient::new(&env, &contract_id); + + // Test operations against real state + let result = client.get_value(); + assert!(result > 0); +} +``` + +- **Docs**: [Fork Testing](https://developers.stellar.org/docs/build/guides/testing/fork-testing) + +## Mutation Testing + +Use `cargo-mutants` to verify test quality — modifies source code and checks that tests catch the changes. + +```bash +cargo install --locked cargo-mutants +cargo mutants +``` + +**Output interpretation**: +- **CAUGHT**: Tests detected the mutation (good coverage) +- **MISSED**: Tests passed despite mutation (test gap — review `mutants.out/diff/`) + +- **Docs**: [Mutation Testing](https://developers.stellar.org/docs/build/guides/testing/mutation-testing) + +## Resource Profiling + +Soroban uses a multidimensional resource model (CPU instructions, ledger reads/writes, bytes, events, rent). + +### CLI Simulation + +```bash +# Simulate contract invocation to see resource costs +stellar contract invoke \ + --id CONTRACT_ID \ + --source alice \ + --network testnet \ + --sim-only \ + -- \ + function_name --arg value +``` + +### Stellar Plus Profiler (Cheesecake Labs) + +```typescript +import { StellarPlus } from 'stellar-plus'; + +const profilerPlugin = new StellarPlus.Utils.Plugins.sorobanTransaction.profiler(); +// Collects CPU instructions, RAM, ledger reads/writes +// Aggregation: sum, average, standard deviation +// Output: CSV, formatted text tables +``` + +- **Docs**: https://docs.cheesecakelabs.com/stellar-plus/reference/utils/plugins/profiler-plugin + +### Testing Checklist + +- [ ] Unit tests cover all public functions +- [ ] Edge cases tested (zero amounts, max values, empty state) +- [ ] Authorization tested (correct signers required) +- [ ] Error conditions tested (invalid inputs, unauthorized) +- [ ] Events emission verified +- [ ] Storage TTL behavior validated +- [ ] Cross-contract interactions tested +- [ ] Fuzz tests for critical paths (deposits, withdrawals, swaps) +- [ ] Property-based tests for invariants +- [ ] Mutation testing confirms test quality +- [ ] Differential test snapshots committed to source control +- [ ] Integration tests against local network +- [ ] Testnet deployment verified before mainnet + +--- + +# Part 3: Security + + +## Core Principle + +Assume the attacker controls: +- All arguments passed to contract functions +- Transaction ordering and timing +- All accounts except those requiring signatures +- The ability to create contracts that mimic your interface + +## Soroban Security Advantages + +Soroban's architecture prevents certain vulnerability classes by design: + +### No Delegate Call +Unlike Ethereum, Soroban has no `delegatecall` equivalent. Contracts cannot execute arbitrary bytecode in their context, eliminating proxy-based attacks. + +### No Classical Reentrancy +Soroban's synchronous execution model prevents the cross-contract reentrancy that plagues Ethereum. Self-reentrancy is possible but rarely exploitable. + +### Explicit Authorization +Authorization is opt-in via `require_auth()`, making it explicit which operations need signatures. + +--- + +## Vulnerability Categories + +### 1. Missing Authorization Checks + +**Risk**: Anyone can call privileged functions without proper verification. + +**Attack**: Attacker calls admin-only functions, drains funds, or modifies critical state. + +**Vulnerable Code**: +```rust +// BAD: No authorization check +pub fn withdraw(env: Env, to: Address, amount: i128) { + transfer_tokens(&env, &to, amount); +} +``` + +**Secure Code**: +```rust +// GOOD: Requires authorization from admin +pub fn withdraw(env: Env, to: Address, amount: i128) { + let admin: Address = env.storage().instance().get(&DataKey::Admin).unwrap(); + admin.require_auth(); + transfer_tokens(&env, &to, amount); +} +``` + +**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`). + +--- + +### 2. Reinitialization Attacks + +**Risk**: Initialization function can be called multiple times, allowing attacker to overwrite admin or critical state. + +**Attack**: Attacker reinitializes contract to become the admin, then drains assets. + +**Vulnerable Code**: +```rust +// BAD: Can be called multiple times +pub fn initialize(env: Env, admin: Address) { + env.storage().instance().set(&DataKey::Admin, &admin); +} +``` + +**Secure Code**: +```rust +// GOOD: Prevents reinitialization +pub fn initialize(env: Env, admin: Address) { + if env.storage().instance().has(&DataKey::Initialized) { + panic!("already initialized"); + } + env.storage().instance().set(&DataKey::Admin, &admin); + env.storage().instance().set(&DataKey::Initialized, &true); +} + +// Alternative: Check for admin existence +pub fn initialize(env: Env, admin: Address) { + if env.storage().instance().has(&DataKey::Admin) { + panic!("already initialized"); + } + env.storage().instance().set(&DataKey::Admin, &admin); +} +``` + +--- + +### 3. Arbitrary Contract Calls + +**Risk**: Contract calls whatever address is passed as parameter without validation. + +**Attack**: Attacker passes malicious contract that mimics expected interface but behaves differently. + +**Vulnerable Code**: +```rust +// BAD: Calls any contract passed as parameter +pub fn swap(env: Env, token: Address, amount: i128) { + let client = token::Client::new(&env, &token); + client.transfer(...); // Could be malicious contract +} +``` + +**Secure Code**: +```rust +// GOOD: Validate against known allowlist +pub fn swap(env: Env, token: Address, amount: i128) { + let allowed_tokens: Vec
= env.storage() + .instance() + .get(&DataKey::AllowedTokens) + .unwrap(); + + if !allowed_tokens.contains(&token) { + panic!("token not allowed"); + } + + let client = token::Client::new(&env, &token); + client.transfer(...); +} + +// Or validate against Stellar Asset Contract +pub fn swap_sac(env: Env, asset: Address, amount: i128) { + // SACs have known, predictable addresses + // Verify it's a legitimate SAC if needed +} +``` + +--- + +### 4. Integer Overflow/Underflow + +**Risk**: Arithmetic operations overflow or underflow, causing unexpected values. + +**Attack**: Attacker manipulates amounts to cause overflow, bypassing balance checks. + +**Vulnerable Code**: +```rust +// BAD: Unchecked arithmetic +pub fn deposit(env: Env, user: Address, amount: i128) { + let balance: i128 = get_balance(&env, &user); + set_balance(&env, &user, balance + amount); // Can overflow +} +``` + +**Secure Code**: +```rust +// GOOD: Use checked arithmetic +pub fn deposit(env: Env, user: Address, amount: i128) { + let balance: i128 = get_balance(&env, &user); + let new_balance = balance.checked_add(amount) + .expect("overflow"); + set_balance(&env, &user, new_balance); +} + +// Also validate inputs +pub fn deposit(env: Env, user: Address, amount: i128) { + if amount <= 0 { + panic!("invalid amount"); + } + // ... rest of logic +} +``` + +--- + +### 5. Storage Key Collisions + +**Risk**: Different data types share the same storage key, causing data corruption. + +**Attack**: Attacker manipulates one type of data to corrupt another. + +**Vulnerable Code**: +```rust +// BAD: Same prefix for different data +env.storage().persistent().set(&symbol_short!("data"), &user_balance); +env.storage().persistent().set(&symbol_short!("data"), &config); // Overwrites! +``` + +**Secure Code**: +```rust +// GOOD: Use typed enum for keys +#[contracttype] +#[derive(Clone)] +pub enum DataKey { + Admin, + Balance(Address), + Config, + Allowance(Address, Address), +} + +env.storage().persistent().set(&DataKey::Balance(user), &balance); +env.storage().instance().set(&DataKey::Config, &config); +``` + +--- + +### 6. Timing/State Race Conditions + +**Risk**: Contract state changes between check and use. + +**Attack**: In multi-transaction scenarios, attacker exploits gap between validation and action. + +**Prevention**: +```rust +// Use atomic operations where possible +pub fn swap(env: Env, user: Address, amount_in: i128, min_out: i128) { + user.require_auth(); + + // Perform all checks and state changes atomically + let balance = get_balance(&env, &user); + if balance < amount_in { + panic!("insufficient balance"); + } + + let amount_out = calculate_output(amount_in); + if amount_out < min_out { + panic!("slippage exceeded"); + } + + // Update all state together + set_balance(&env, &user, balance - amount_in); + transfer_output(&env, &user, amount_out); +} +``` + +--- + +### 7. TTL/Archival Vulnerabilities + +**Risk**: Critical contract data gets archived, breaking functionality. + +**Attack**: Attacker waits for data to be archived, then exploits the missing state. + +**Prevention**: +```rust +// Extend TTL for critical data +pub fn critical_operation(env: Env) { + // Always extend instance storage + env.storage().instance().extend_ttl( + 100, // threshold + 518400, // extend_to (~30 days) + ); + + // Extend specific persistent keys + env.storage().persistent().extend_ttl( + &DataKey::CriticalData, + 100, + 518400, + ); +} + +// Consider restoration costs in design +// Archived data can be restored, but requires transaction +``` + +--- + +### 8. Cross-Contract Call Validation + +**Risk**: Trusting return values from untrusted contracts. + +**Attack**: Malicious contract returns false data, causing incorrect state updates. + +**Prevention**: +```rust +// Validate all external data +pub fn process_oracle_price(env: Env, oracle: Address, asset: Address) -> i128 { + // Validate oracle is trusted + let trusted_oracles: Vec
= env.storage() + .instance() + .get(&DataKey::TrustedOracles) + .unwrap(); + + if !trusted_oracles.contains(&oracle) { + panic!("untrusted oracle"); + } + + let price: i128 = oracle_client.get_price(&asset); + + // Sanity check the value + if price <= 0 || price > MAX_REASONABLE_PRICE { + panic!("invalid price"); + } + + price +} +``` + +--- + +## Classic Stellar Security + +### Trustline Attacks + +**Risk**: Users create trustlines to malicious assets that look legitimate. + +**Prevention**: +- Verify asset issuer before creating trustlines +- Use well-known asset lists (stellar.toml) +- Display full asset code + issuer in UIs + +### Clawback Awareness + +**Risk**: Assets with clawback enabled can be seized by issuer. + +**Prevention**: +```typescript +// Check if clawback is enabled +const issuerAccount = await server.loadAccount(asset.issuer); +const clawbackEnabled = issuerAccount.flags.auth_clawback_enabled; + +if (clawbackEnabled) { + // Warn user or reject asset +} +``` + +### Account Merge Attacks + +**Risk**: Merged accounts can be recreated with different configuration. + +**Prevention**: +- Validate account state before critical operations +- Don't cache account data long-term + +--- + +## Soroban-Specific Checklist + +### Contract Development +- [ ] All privileged functions require appropriate authorization +- [ ] Initialization can only happen once +- [ ] External contract calls are validated against allowlists +- [ ] All arithmetic uses checked operations +- [ ] Storage keys are typed and collision-free +- [ ] Critical data TTLs are extended proactively +- [ ] Input validation on all public functions +- [ ] Events emitted for auditable state changes + +### Storage Security +- [ ] Sensitive data uses appropriate storage type +- [ ] Instance storage for shared/admin data +- [ ] Persistent storage for user-specific data +- [ ] Temporary storage only for truly temporary data +- [ ] TTL management strategy documented + +### Cross-Contract Calls +- [ ] Called contracts are validated or allowlisted +- [ ] Return values are sanity-checked +- [ ] Failure cases handled gracefully +- [ ] No excessive trust in external state + +--- + +## Client-Side Checklist + +- [ ] Network passphrase validated before signing +- [ ] Transaction simulation before submission +- [ ] Clear display of all operation details +- [ ] Confirmation for high-value transactions +- [ ] Handle all error states gracefully +- [ ] Don't trust client-side validation alone +- [ ] Verify contract addresses against known deployments +- [ ] Check asset trustline status before transfers + +--- + +## Security Review Questions + +1. Can anyone call admin functions without authorization? +2. Can the contract be reinitialized? +3. Are all external contract calls validated? +4. Is arithmetic safe from overflow/underflow? +5. Can storage keys collide? +6. Will critical data survive archival? +7. Are cross-contract return values validated? +8. Can timing attacks exploit state changes? + +--- + +## Bug Bounty Programs + +### Immunefi — Stellar Core (up to $250K) +- **URL**: https://immunefi.com/bug-bounty/stellar/ +- **Scope**: stellar-core, rs-soroban-sdk, rs-soroban-env, soroban-tools (CLI + RPC), js-soroban-client, rs-stellar-xdr, wasmi fork +- **Rewards**: Critical $50K–$250K, High $10K–$50K, Medium $5K, Low $1K +- **Payment**: USD-denominated, paid in XLM. KYC required. +- **Rules**: PoC required. Test on local forks only (no mainnet/testnet). + +### Immunefi — OpenZeppelin on Stellar (up to $25K) +- **URL**: https://immunefi.com/bug-bounty/openzeppelin-stellar/ +- **Scope**: OpenZeppelin Stellar Contracts library +- **Max payout**: $25K per bug, $250K total program cap + +### HackerOne — Web Applications +- **URL**: https://stellar.org/grants-and-funding/bug-bounty +- **Scope**: SDF web applications, production servers, domains +- **Disclosure**: 90-day remediation window before public disclosure + +## Soroban Audit Bank + +SDF's proactive security program with **$3M+ deployed across 43+ audits**. + +- **URL**: https://stellar.org/grants-and-funding/soroban-audit-bank +- **Projects list**: https://stellar.org/audit-bank/projects +- **Eligibility**: SCF-funded projects (financial protocols, infrastructure, high-traction dApps) +- **Co-payment**: 5% upfront (refundable if Critical/High/Medium issues remediated within 20 business days) +- **Follow-up audits**: Triggered at $10M and $100M TVL milestones (includes formal verification and competitive audits) +- **Preparation**: STRIDE threat modeling framework + Audit Readiness Checklist + +### Partner Audit Firms + +| Firm | Specialty | +|------|-----------| +| **OtterSec** | Smart contract audits | +| **Veridise** | Tool-assisted audits, [security checklist](https://veridise.com/blog/audit-insights/building-on-stellar-soroban-grab-this-security-checklist-to-avoid-vulnerabilities/) | +| **Runtime Verification** | Formal methods, [Komet tool](https://runtimeverification.com/blog/introducing-komet-smart-contract-testing-and-verification-tool-for-soroban-created-by-runtime-verification) | +| **CoinFabrik** | Static analysis (Scout), manual audits | +| **QuarksLab** | Security research | +| **Coinspect** | Security audits | +| **Certora** | Formal verification ([Sunbeam Prover](https://docs.certora.com/en/latest/docs/sunbeam/index.html)) | +| **Halborn** | Security assessments | +| **Zellic** | Blockchain + cryptography research | +| **Code4rena** | Competitive audit platform | + +## Security Tooling + +### Static Analysis + +#### Scout Soroban (CoinFabrik) +Open-source vulnerability detector with 23 detectors (critical through enhancement severity). +- **GitHub**: https://github.com/CoinFabrik/scout-soroban +- **Install**: `cargo install cargo-scout-audit` → `cargo scout-audit` +- **Output formats**: HTML, Markdown, JSON, PDF, SARIF (CI/CD integration) +- **VSCode extension**: [Scout Audit](https://marketplace.visualstudio.com/items?itemName=CoinFabrik.scout-audit) +- **Key detectors**: `overflow-check`, `unprotected-update-current-contract-wasm`, `set-contract-storage`, `unrestricted-transfer-from`, `divide-before-multiply`, `dos-unbounded-operation`, `unsafe-unwrap` + +#### OpenZeppelin Security Detectors SDK +Framework for building custom security detectors for Soroban. +- **GitHub**: https://github.com/OpenZeppelin/soroban-security-detectors-sdk +- **Architecture**: `sdk` (core), `detectors` (pre-built), `soroban-scanner` (CLI) +- **Pre-built detectors**: `auth_missing`, `unchecked_ft_transfer`, improper TTL extension, contract panics, unsafe temporary storage +- **Extensible**: Load external detector libraries as shared objects + +### Formal Verification + +#### Certora Sunbeam Prover +Purpose-built formal verification for Soroban — first WASM platform supported by Certora. +- **Docs**: https://docs.certora.com/en/latest/docs/sunbeam/index.html +- **Spec language**: CVLR (Certora Verification Language for Rust) — Rust macros (`cvlr_assert!`, `cvlr_assume!`, `cvlr_satisfy!`) +- **Operates at**: WASM bytecode level (eliminates compiler trust assumptions) +- **Reports**: https://github.com/Certora/SecurityReports +- **Example**: [Blend V1 verification report](https://www.certora.com/reports/blend-smart-contract-verification-report) + +#### Runtime Verification — Komet +Formal verification and testing tool built specifically for Soroban (SCF-funded). +- **Docs**: https://docs.runtimeverification.com/komet +- **Repo**: https://github.com/runtimeverification/komet +- **Spec language**: Rust — property-based tests written in the same language as Soroban contracts +- **Operates at**: WASM bytecode level via [KWasm semantics](https://github.com/runtimeverification/wasm-semantics) (eliminates compiler trust assumptions) +- **Features**: Fuzzing, testing, formal verification +- **Reports**: [RV publications](https://github.com/runtimeverification/publications) +- **Example**: [TokenOps audit and verification report](https://github.com/runtimeverification/publications/blob/main/reports/smart-contracts/TokenOps.pdf) +- **Blog**: [Introducing Komet](https://runtimeverification.com/blog/introducing-komet-smart-contract-testing-and-verification-tool-for-soroban-created-by-runtime-verification) + +### Security Knowledge Base + +#### Soroban Security Portal +Community security knowledge base by Inferara (SCF-funded). +- **URL**: https://sorobansecurity.com +- **Features**: Searchable audit reports, vulnerability database, best practices + +### Security Monitoring (Post-Deployment) + +#### OpenZeppelin Monitor (Stellar alpha) +Open-source contract monitoring with Stellar support. +- **Features**: Self-hosted via Docker, Prometheus + Grafana observability +- **Source**: https://www.openzeppelin.com/news/monitor-and-relayers-are-now-open-source + +## OpenZeppelin Partnership Overview + +Strategic partnership highlights include: +- **40 Auditor Weeks** of dedicated security audits +- **Stellar Contracts library** (audited, production-ready) +- **Relayer** (fee-sponsored transactions, Stellar-native) +- **Monitor** (contract monitoring, Stellar alpha) +- **Security Detectors SDK** (static analysis framework) +- **SEP authorship**: SEP-0049 (Upgradeable Contracts), SEP-0050 (NFTs) +- **Blog**: https://stellar.org/blog/foundation-news/sdf-partners-with-openzeppelin-to-enhance-stellar-smart-contract-development + +--- + +# Part 4: Advanced Patterns + + +## When to use this guide +Use this guide for higher-complexity contract architecture: +- Upgrades and migrations +- Factory/deployer systems +- Governance and timelocks +- DeFi primitives (vaults, pools, oracles) +- Regulated token/compliance workflows +- Resource and storage optimization + +Use `contracts-soroban.md` for core contract syntax and day-to-day patterns. + +## Design principles +- Prefer simple state machines over implicit behavior. +- Minimize privileged entrypoints and protect all privileged actions with explicit auth. +- Keep upgrades predictable: version metadata + migration plan + rollback strategy. +- Use idempotent migrations and fail fast on incompatible versions. +- Separate protocol/business logic from governance/admin logic when possible. + +## Upgradeability patterns + +### 1) Explicit upgrade policy +- Decide early whether the contract is mutable or immutable. +- If mutable, implement an `upgrade` entrypoint guarded by admin or governance. +- If immutable, do not expose upgrade capability. + +### 2) Version tracking +Track both runtime and code version: +- Contract metadata (`contractmeta!`) for binary version +- Storage key for migration/application version + +```rust +#![no_std] +use soroban_sdk::{contract, contractimpl, contractmeta, contracttype, Address, BytesN, Env}; + +contractmeta!(key = "binver", val = "1.0.0"); + +#[contracttype] +#[derive(Clone)] +pub enum DataKey { + Admin, + AppVersion, +} + +#[contract] +pub struct Upgradeable; + +#[contractimpl] +impl Upgradeable { + pub fn __constructor(env: Env, admin: Address) { + env.storage().instance().set(&DataKey::Admin, &admin); + env.storage().instance().set(&DataKey::AppVersion, &1u32); + } + + pub fn upgrade(env: Env, new_wasm_hash: BytesN<32>) { + let admin: Address = env.storage().instance().get(&DataKey::Admin).unwrap(); + admin.require_auth(); + env.deployer().update_current_contract_wasm(new_wasm_hash); + } +} +``` + +### 3) Migration entrypoint +- Add a dedicated `migrate` function after upgrades. +- Ensure migration is monotonic (`new_version > current_version`). +- Treat migrations as one-way and idempotent. + +## Factory and deployment patterns + +### Factory contract responsibilities +- Authorize who can deploy instances. +- Derive deterministic addresses with salts when needed. +- Emit events for deployments (indexing/ops observability). +- Keep deployment logic separate from instance business logic. + +```rust +#![no_std] +use soroban_sdk::{contract, contractimpl, Address, BytesN, Env, Val, Vec}; + +#[contract] +pub struct Factory; + +#[contractimpl] +impl Factory { + pub fn deploy( + env: Env, + owner: Address, + wasm_hash: BytesN<32>, + salt: BytesN<32>, + constructor_args: Vec, + ) -> Address { + owner.require_auth(); + env.deployer() + .with_address(env.current_contract_address(), salt) + .deploy_v2(wasm_hash, constructor_args) + } +} +``` + +Operational note: +- Keep a registry (or emit canonical deployment events) to avoid orphaned instances. + +## Governance patterns + +### Timelock for sensitive actions +Use a timelock for upgrades and major config changes: +- `propose_*` stores pending action + execute ledger +- `execute_*` enforces delay +- `cancel_*` allows governance abort + +### Multisig and role separation +- Separate roles: proposer, approver, executor. +- Define threshold and signer rotation process. +- Record proposal state in persistent storage and prevent replay. + +Checklist: +- Proposal uniqueness and replay protection +- Expiry semantics +- Clear cancellation path +- Explicit event emission + +## DeFi primitives + +### Vaults +- Track `total_assets` and `total_shares` with careful rounding rules. +- Use conservative math for mint/redeem conversions. +- Enforce pause/emergency controls for admin-level intervention. + +### Pools/AMMs +- Define invariant and fee accounting precisely. +- Protect against stale pricing and manipulation. +- Include slippage checks on all user-facing swaps. + +### Oracle integration +- Require freshness constraints (ledger/time bounds). +- Prefer median/multi-source feeds for critical operations. +- Add circuit breakers for extreme price movement. + +## Compliance-oriented token design + +Common regulated features: +- Allowlist/denylist checks before transfer +- Jurisdiction or investor-class restrictions +- Forced transfer/freeze authority with auditable governance +- Off-chain identity references (never store sensitive PII directly) + +Implementation guidance: +- Keep compliance policy in dedicated modules/entrypoints. +- Emit policy decision events for traceability. +- Treat privileged compliance actions as high-risk operations requiring strong auth. + +## Resource optimization + +### Storage +- Use `instance` for global config. +- Use `persistent` for critical user state. +- Use `temporary` only for disposable data. +- Extend TTL strategically, not on every call. + +### Compute +- Avoid unbounded loops over user-controlled collections. +- Prefer bounded batch operations. +- Reduce cross-contract calls in hot paths. + +### Contract size +- Keep release profile optimized (`opt-level = "z"`, `lto = true`, `panic = "abort"`). +- Split concerns across contracts when near Wasm size limits. + +## Security review checklist for advanced architectures +- Access control is explicit on every privileged path. +- Upgrade and migration are both tested (happy path + failure path). +- Timelock and governance logic is replay-safe. +- External dependency assumptions are documented. +- Emergency controls and incident runbooks are defined. +- Events cover operationally important transitions. + +## Testing strategy for advanced patterns +- Unit tests for role checks, invariants, and edge-case math. +- Integration tests for multi-step governance flows. +- Upgrade tests from old state snapshots to new versions. +- Negative tests for unauthorized and malformed calls. + +## Related docs +- Core contract development: `contracts-soroban.md` +- Security checks: `security.md` +- Testing approach: `testing.md` +- Standards references: `standards-reference.md` + +--- + +# Part 5: Common Pitfalls + + +## Soroban Contract Issues + +### 1. Contract Size Exceeds 64KB Limit + +**Problem**: Contract won't deploy because WASM exceeds size limit. + +**Symptoms**: +``` +Error: contract exceeds maximum size +``` + +**Solutions**: + +```toml +# Cargo.toml - Use aggressive optimization +[profile.release] +opt-level = "z" # Optimize for size +lto = true # Link-time optimization +codegen-units = 1 # Single codegen unit +panic = "abort" # Smaller panic handling +strip = "symbols" # Remove symbols +``` + +Additional strategies: +- Split large contracts into multiple smaller contracts +- Use `symbol_short!()` for symbols under 9 chars +- Avoid large static data in contract +- Remove debug code and unused functions +- Use `cargo bloat` to identify large dependencies + +```bash +# Check contract size +ls -la target/wasm32-unknown-unknown/release/*.wasm + +# Analyze what's taking space +cargo install cargo-bloat +cargo bloat --release --target wasm32-unknown-unknown +``` + +--- + +### 2. `#![no_std]` Missing + +**Problem**: Compilation fails with std library errors. + +**Symptoms**: +``` +error: cannot find macro `println` in this scope +error[E0433]: failed to resolve: use of undeclared crate or module `std` +``` + +**Solution**: +```rust +// MUST be first line of lib.rs +#![no_std] + +use soroban_sdk::{contract, contractimpl, Env}; + +// Use soroban_sdk equivalents instead of std: +// - soroban_sdk::String instead of std::string::String +// - soroban_sdk::Vec instead of std::vec::Vec +// - soroban_sdk::Map instead of std::collections::HashMap +``` + +--- + +### 3. Storage TTL Not Extended + +**Problem**: Contract data gets archived and becomes inaccessible. + +**Symptoms**: +- Contract calls fail after period of inactivity +- Data appears missing but contract still exists + +**Solution**: +```rust +// Proactively extend TTL in operations that use data +pub fn use_data(env: Env) { + // Extend instance storage + env.storage().instance().extend_ttl( + 50, // If TTL < 50, extend + 518400, // Extend to ~30 days + ); + + // Extend specific persistent keys + env.storage().persistent().extend_ttl( + &DataKey::ImportantData, + 50, + 518400, + ); + + // Now use the data... +} +``` + +> See Part 1: Contract Development above for full TTL management patterns and storage type guidance. + +--- + +### 4. Wrong Storage Type + +**Problem**: Data unexpectedly deleted or costs too high. + +**Symptoms**: +- Temporary data deleted before expected +- Unexpectedly high fees for storage + +**Solution**: +```rust +// Instance: Shared config, survives with contract +env.storage().instance().set(&DataKey::Admin, &admin); + +// Persistent: User data, can be archived but restored +env.storage().persistent().set(&DataKey::Balance(user), &balance); + +// Temporary: Truly temporary, auto-deleted, cheapest +env.storage().temporary().set(&DataKey::Cache(key), &value); +``` + +--- + +### 5. Authorization Not Working + +**Problem**: `require_auth()` not enforcing signatures in tests. + +**Symptoms**: +- Tests pass but transactions fail on network +- Anyone can call protected functions + +**Solution**: +```rust +#[test] +fn test_auth() { + let env = Env::default(); + + // DON'T just mock all auths blindly + // env.mock_all_auths(); // Be careful with this! + + // DO test specific auth requirements with mock_auths() + env.mock_auths(&[MockAuth { + address: &user, + invoke: &MockAuthInvoke { + contract: &contract_id, + fn_name: "transfer", + args: (&user, &other, &100i128).into_val(&env), + sub_invokes: &[], + }, + }]); + + client.transfer(&user, &other, &100); + assert!(!env.auths().is_empty()); +} +``` + +> See Part 2: Testing Strategy above for comprehensive auth testing patterns including `mock_all_auths()`, specific auth mocking, and cross-contract auth. + +--- + +## SDK Issues + +### 6. Network Passphrase Mismatch + +**Problem**: Transactions fail with signature errors. + +**Symptoms**: +``` +Error: tx_bad_auth +``` + +**Solution**: +```typescript +import * as StellarSdk from "@stellar/stellar-sdk"; + +// ALWAYS use correct passphrase for network +const PASSPHRASES = { + mainnet: StellarSdk.Networks.PUBLIC, + // "Public Global Stellar Network ; September 2015" + + testnet: StellarSdk.Networks.TESTNET, + // "Test SDF Network ; September 2015" + + local: "Standalone Network ; February 2017", +}; + +// When building transactions +const tx = new StellarSdk.TransactionBuilder(account, { + fee: StellarSdk.BASE_FEE, + networkPassphrase: PASSPHRASES.testnet, // Match your network! +}); +``` + +--- + +### 7. Account Not Funded + +**Problem**: Operations fail because account doesn't exist. + +**Symptoms**: +``` +Error: Account not found +Status: 404 +``` + +**Solution**: +```typescript +// Testnet - use Friendbot +await fetch(`https://friendbot.stellar.org?addr=${publicKey}`); + +// Mainnet - must receive XLM from existing account +const tx = new StellarSdk.TransactionBuilder(funderAccount, { + fee: StellarSdk.BASE_FEE, + networkPassphrase: StellarSdk.Networks.PUBLIC, +}) + .addOperation( + StellarSdk.Operation.createAccount({ + destination: newAccountPublicKey, + startingBalance: "2", // Minimum ~1 XLM for base reserve + }) + ) + .setTimeout(180) + .build(); +``` + +--- + +### 8. Missing Trustline + +**Problem**: Payment fails for non-native assets. + +**Symptoms**: +``` +Error: op_no_trust +``` + +**Solution**: +```typescript +// Check if trustline exists +const account = await server.loadAccount(destination); +const hasTrustline = account.balances.some( + (b) => + b.asset_type !== "native" && + b.asset_code === asset.code && + b.asset_issuer === asset.issuer +); + +if (!hasTrustline) { + // Create trustline first + const trustTx = new StellarSdk.TransactionBuilder(destAccount, { + fee: StellarSdk.BASE_FEE, + networkPassphrase, + }) + .addOperation(StellarSdk.Operation.changeTrust({ asset })) + .setTimeout(180) + .build(); + // Sign and submit... +} +``` + +--- + +### 9. Sequence Number Issues + +**Problem**: Transaction rejected for sequence number. + +**Symptoms**: +``` +Error: tx_bad_seq +``` + +**Causes & Solutions**: + +```typescript +// Cause 1: Stale account data +// Solution: Always load fresh account before building tx +const account = await server.loadAccount(publicKey); + +// Cause 2: Parallel transactions +// Solution: Use sequence number management +class SequenceManager { + private sequence: bigint; + + async getNext(server: Horizon.Server, publicKey: string) { + if (!this.sequence) { + const account = await server.loadAccount(publicKey); + this.sequence = BigInt(account.sequence); + } + this.sequence++; + return this.sequence.toString(); + } +} + +// Cause 3: Transaction timeout without resubmit +// Solution: Rebuild with fresh sequence on timeout +``` + +--- + +### 10. Soroban Transaction Not Simulated + +**Problem**: Soroban transaction fails with resource errors. + +**Symptoms**: +``` +Error: transaction simulation failed +Error: insufficient resources +``` + +**Solution**: +```typescript +// ALWAYS simulate before submitting Soroban transactions +const simulation = await rpc.simulateTransaction(transaction); + +if (StellarSdk.rpc.Api.isSimulationError(simulation)) { + throw new Error(`Simulation failed: ${simulation.error}`); +} + +// Use assembleTransaction to add correct resources +const preparedTx = StellarSdk.rpc.assembleTransaction( + transaction, + simulation +).build(); + +// Now sign and submit preparedTx, not original transaction +``` + +--- + +## Frontend Issues + +### 11. Freighter Not Detected + +**Problem**: Wallet connection fails silently. + +**Symptoms**: +- `isConnected()` returns false +- No wallet prompt appears + +**Solution**: +```typescript +import { isConnected, isAllowed } from "@stellar/freighter-api"; + +async function checkFreighter() { + // Check if extension is installed + const connected = await isConnected(); + if (!connected) { + // Prompt user to install + window.open("https://freighter.app", "_blank"); + return; + } + + // Check if app is allowed + const allowed = await isAllowed(); + if (!allowed) { + // Need to request permission + await setAllowed(); + } +} +``` + +--- + +### 12. Network Mismatch with Wallet + +**Problem**: Wallet on different network than app. + +**Symptoms**: +- Transactions fail unexpectedly +- Wrong balances displayed + +**Solution**: +```typescript +import { getNetwork } from "@stellar/freighter-api"; + +async function validateNetwork() { + const walletNetwork = await getNetwork(); + const appNetwork = process.env.NEXT_PUBLIC_STELLAR_NETWORK; + + if (walletNetwork !== appNetwork) { + throw new Error( + `Please switch Freighter to ${appNetwork}. Currently on ${walletNetwork}` + ); + } +} +``` + +--- + +### 13. Transaction Timeout + +**Problem**: Transaction expires before confirmation. + +**Symptoms**: +``` +Error: tx_too_late +``` + +**Solution**: +```typescript +// Set appropriate timeout based on expected confirmation time +const tx = new StellarSdk.TransactionBuilder(account, { + fee: StellarSdk.BASE_FEE, + networkPassphrase, +}) + .addOperation(/* ... */) + .setTimeout(180) // 3 minutes - adjust as needed + .build(); + +// Handle timeout gracefully +async function submitWithRetry(signedXdr: string) { + try { + return await submitTransaction(signedXdr); + } catch (error) { + if (error.response?.data?.extras?.result_codes?.transaction === "tx_too_late") { + // Rebuild with fresh blockhash and retry + const newTx = await rebuildTransaction(signedXdr); + return await submitTransaction(newTx); + } + throw error; + } +} +``` + +--- + +## CLI Issues + +### 14. Identity Not Found + +**Problem**: Stellar CLI can't find saved identity. + +**Symptoms**: +``` +Error: identity "alice" not found +``` + +**Solution**: +```bash +# List existing identities +stellar keys list + +# Generate new identity +stellar keys generate --global alice + +# For testnet with funding +stellar keys generate --global alice --network testnet --fund + +# Specify identity location +stellar keys generate alice --config-dir /custom/path +``` + +--- + +### 15. Contract Invoke Parsing Errors + +**Problem**: CLI can't parse function arguments. + +**Symptoms**: +``` +Error: invalid argument format +``` + +**Solution**: +```bash +# Use correct argument syntax +# Addresses: just the G... or C... string +stellar contract invoke \ + --id CONTRACT_ID \ + --source alice \ + --network testnet \ + -- \ + transfer \ + --from GABC... \ + --to GDEF... \ + --amount 1000 + +# Complex types: use JSON +stellar contract invoke \ + --id CONTRACT_ID \ + -- \ + complex_fn \ + --data '{"field1": "value", "field2": 123}' +``` + +--- + +## General Best Practices + +### Debugging Checklist + +1. **Check network**: Is wallet/CLI on correct network? +2. **Check account**: Is source account funded? +3. **Check sequence**: Is sequence number current? +4. **Check simulation**: Did Soroban tx simulate successfully? +5. **Check trustlines**: For asset transfers, do trustlines exist? +6. **Check TTL**: For contract data, is TTL sufficient? +7. **Check authorization**: Is correct account signing? +8. **Check logs**: What does the error message actually say? + +### Error Code Reference + +| Code | Meaning | Common Fix | +|------|---------|------------| +| `tx_bad_auth` | Signature invalid | Check network passphrase | +| `tx_bad_seq` | Wrong sequence | Reload account | +| `tx_too_late` | Transaction expired | Rebuild and resubmit | +| `op_no_trust` | Missing trustline | Create trustline first | +| `op_underfunded` | Insufficient balance | Add funds | +| `op_low_reserve` | Below minimum balance | Maintain reserve | diff --git a/skills/standards/SKILL.md b/skills/standards/SKILL.md new file mode 100644 index 0000000..b01c581 --- /dev/null +++ b/skills/standards/SKILL.md @@ -0,0 +1,864 @@ +--- +name: standards +description: 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/withdrawals, federation, deep links, and KYC. Also bundles ecosystem references (DeFi protocols, dev tools, wallets, infra, community projects) and curated documentation links. Use when you need to know which SEP applies, or want a starting point for ecosystem integrations and official docs. +user-invocable: true +argument-hint: "[standards or ecosystem lookup]" +--- + +# Standards, Ecosystem, and Resources + +Three things bundled because they're all reference material you reach for in the same moment: "which standard handles X?", "is there an existing project doing Y?", and "where's the canonical doc for Z?". + +## When to use this skill +- Picking the right SEP for an integration (anchors, deposits, federation, deep links, KYC, paths) +- Checking CAP status for a protocol feature you want to rely on +- Finding existing DeFi protocols, wallets, or infrastructure to integrate with rather than rebuild +- Locating official docs, SDKs, or community resources + +## Related skills +- Implementing a SEP-41 token interface → `../assets/SKILL.md`, `../soroban/SKILL.md` +- Frontend SEP-7 / SEP-10 flows → `../dapp/SKILL.md` +- CAPs for cryptography (BLS, BN254, Poseidon) → `../zk-proofs/SKILL.md` +- x402/MPP protocol context → `../agentic-payments/SKILL.md` + +--- + +# Part 1: SEP / CAP Standards Reference + + +## When to use this guide +Use this when you need: +- The right SEP/CAP for a feature or integration +- Interoperability guidance for wallets, anchors, and contracts +- A fast map from use case to official standards docs + +## Maintenance note +Standards status can change quickly. +Before implementation, verify current status in: +- SEPs: [stellar-protocol/ecosystem](https://github.com/stellar/stellar-protocol/tree/master/ecosystem) +- CAPs: [stellar-protocol/core](https://github.com/stellar/stellar-protocol/tree/master/core) + +Treat this file as a routing map, not a source of final governance/status truth. + +## High-value SEPs for app developers + +### Contracts and token interfaces +- [SEP-0041](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0041.md): Soroban token interface +- [SEP-0046](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0046.md): Contract metadata in Wasm +- [SEP-0048](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0048.md): Contract interface specification +- [SEP-0049](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0049.md): Upgradeable-contract guidance +- [SEP-0050](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0050.md): NFT standard work +- [SEP-0055](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0055.md): Contract build verification +- [SEP-0056](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0056.md): Vault-style tokenized products +- [SEP-0057](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0057.md): Regulated token patterns (T-REX) + +### Auth, identity, and metadata +- [SEP-0010](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0010.md): Web authentication +- [SEP-0023](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0023.md): StrKey encoding +- [SEP-0001](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0001.md): `stellar.toml` + +### Anchor and fiat integration +- [SEP-0006](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0006.md): Programmatic deposit/withdrawal API +- [SEP-0024](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0024.md): Hosted interactive anchor flow +- [SEP-0031](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0031.md): Cross-border payment flow +- [SEP-0012](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0012.md): KYC data exchange + +## High-value CAPs for Soroban developers + +### Soroban foundations +- [CAP-0046](https://github.com/stellar/stellar-protocol/blob/master/core/cap-0046.md): Soroban overview +- CAP-0046 subdocuments (`cap-0046-*.md`): runtime, lifecycle, host functions, storage, auth, metering + +### Frequently used contract capabilities +- [CAP-0051](https://github.com/stellar/stellar-protocol/blob/master/core/cap-0051.md): secp256r1 verification (passkey-related cryptography) +- [CAP-0053](https://github.com/stellar/stellar-protocol/blob/master/core/cap-0053.md): TTL extension behavior +- [CAP-0058](https://github.com/stellar/stellar-protocol/blob/master/core/cap-0058.md): constructors (`__constructor`) +- [CAP-0059](https://github.com/stellar/stellar-protocol/blob/master/core/cap-0059.md): BLS12-381 primitives +- [CAP-0067](https://github.com/stellar/stellar-protocol/blob/master/core/cap-0067.md): protocol/runtime improvements including asset/event model changes + +### Newer and draft crypto/features +- [CAP-0074](https://github.com/stellar/stellar-protocol/blob/master/core/cap-0074.md): BN254 host functions proposal +- [CAP-0075](https://github.com/stellar/stellar-protocol/blob/master/core/cap-0075.md): Poseidon/Poseidon2 proposal +- [CAP-0079](https://github.com/stellar/stellar-protocol/blob/master/core/cap-0079.md): muxed-address strkey conversion proposal + +Use the CAP preamble status fields as the source of truth for implementation readiness. + +## Quick mapping by use case + +### I am building a fungible token +1. Start with SEP-0041 interface expectations. +2. Prefer Stellar Assets + SAC interop unless custom logic is required. +3. If regulated, review SEP-0057 patterns. + +### I need upgrade-safe contracts +1. Read SEP-0049 guidance for upgrade process design. +2. Use CAP-0058 constructors for atomic initialization where protocol support exists. +3. Add migration/versioning strategy before deploying upgradeable contracts. + +### I am building a smart-wallet flow +1. Use SEP-0010 for web authentication flows. +2. Review CAP-0051 for passkey-related cryptographic primitives. +3. Align wallet UX and signing payloads with current SDK guidance. + +### I need anchor integration for fiat rails +1. SEP-0006 for API-first flows. +2. SEP-0024 for hosted interactive rails. +3. SEP-0031 when supporting payment corridors. +4. SEP-0012 for KYC data requirements. + +## Practical workflow for AI agents +- Step 1: Identify feature category (token, wallet auth, anchor, upgradeability). +- Step 2: Link user to the 1-3 primary SEP/CAP docs. +- Step 3: Check status/acceptance in the source repo before asserting support. +- Step 4: Implement only what is active on the target network/protocol. +- Step 5: Document dependencies on draft standards explicitly. + +## Related docs +- Contract implementation details: `contracts-soroban.md` +- Advanced architecture guidance: `advanced-patterns.md` +- RPC and data access: `api-rpc-horizon.md` +- Security considerations: `security.md` + +--- + +# Part 2: Stellar Ecosystem + + +This guide catalogs the major projects, protocols, and tools in the Stellar ecosystem. Use this as a reference when building on Stellar to find relevant integrations, examples, and community projects. + +> **Canonical directories** — For the most up-to-date project lists, check: +> - [Stellar Ecosystem](https://stellar.org/ecosystem) — Official directory (searchable by country, asset, category) +> - [SCF Projects](https://communityfund.stellar.org/projects) — Funded projects with status tracking +> - [Stellar on DefiLlama](https://defillama.com/chain/stellar) — Live DeFi TVL data +> +> Treat project metrics/status as volatile. Validate latest activity and production readiness before taking dependencies. + +## DeFi Protocols + +### Lending & Borrowing + +#### Blend Protocol +Universal liquidity protocol enabling permissionless lending pools. +- **Use Case**: Lending, borrowing, yield generation +- **GitHub**: https://github.com/blend-capital/blend-contracts +- **GitHub (v2)**: https://github.com/blend-capital/blend-contracts-v2 +- **Integrations**: Meru, Airtm, Lobstr, DeFindex, Beans + +#### Slender +First non-custodial lending protocol on Soroban with flash loan support. +- **Use Case**: Lending, borrowing, flash loans +- **Features**: Pool-based strategy, sTokens, dTokens, utilization caps +- **Oracle**: SEP-40 compatible (Reflector) + +### DEXs & AMMs + +#### Soroswap +First DEX and aggregator on Stellar/Soroban. +- **Use Case**: Token swaps, liquidity provision, aggregation +- **Website**: https://soroswap.finance +- **GitHub (Core)**: https://github.com/soroswap/core +- **GitHub (Frontend)**: https://github.com/soroswap/frontend +- **GitHub (Aggregator)**: https://github.com/soroswap/aggregator +- **Docs**: https://docs.soroswap.finance +- **Features**: AMM + DEX aggregator across Aqua, Phoenix, Stellar Classic DEX + +#### Aquarius / AQUA Network +Governance-driven liquidity layer with AMM functionality. +- **Use Case**: Liquidity incentives, AMM, governance +- **Website**: https://aqua.network +- **GitHub**: https://github.com/AquaToken/soroban-amm +- **GitHub (Org)**: https://github.com/AquaToken +- **Token**: AQUA (governance + rewards) +- **Docs**: https://docs.aqua.network + +#### Phoenix Protocol +AMM protocol on Soroban. +- **GitHub**: https://github.com/Phoenix-Protocol-Group +- **Use Case**: Token swaps, liquidity pools + +### Yield & Vaults + +#### DeFindex +Yield aggregation and vault infrastructure by PaltaLabs. +- **Use Case**: Tokenized vaults, yield strategies, DeFi abstraction +- **Docs**: https://docs.defindex.io +- **Features**: Automated rebalancing, vault management, Blend integration + +### Stablecoins & CDPs + +#### Orbit CDP Protocol +Collateralized stablecoin issuance (USD, EUR, MXN). +- **Use Case**: Mint stablecoins against XLM/bond collateral +- **Docs**: https://docs.orbitcdp.finance +- **Features**: Multi-currency stablecoins, Pegkeeper automation, Blend integration + +## Wallets + +### Browser Extensions + +#### Freighter +SDF's flagship non-custodial browser wallet. +- **Website**: https://freighter.app +- **Docs**: https://docs.freighter.app +- **GitHub**: https://github.com/stellar/freighter +- **GitHub (Mobile)**: https://github.com/stellar/freighter-mobile +- **API**: https://github.com/stellar/freighter/tree/master/library/freighter-api +- **Features**: Soroban support, mobile apps (iOS/Android), Discover browser + +#### xBull +Feature-rich browser wallet with advanced capabilities. +- **Website**: https://xbull.app +- **Features**: Multi-account, hardware wallet support + +#### Albedo +Lightweight web-based wallet and signing provider. +- **Website**: https://albedo.link +- **Use Case**: Web authentication, transaction signing + +#### Rabet +Browser extension wallet for Stellar. +- **Website**: https://rabet.io + +#### Hana Wallet +Modern Stellar wallet with DeFi features. +- **Website**: https://hana.network + +### Mobile Wallets + +#### LOBSTR +Most popular Stellar mobile wallet. +- **Website**: https://lobstr.co +- **Platforms**: iOS, Android, Web +- **Features**: DEX trading, multisig, 2FA, asset discovery + +#### Beans +Payments platform with yield features. +- **Use Case**: Payments, earning (via DeFindex/Blend) +- **Features**: Non-custodial yield generation + +### Multi-Wallet Integration + +#### Stellar Wallets Kit +SDK for integrating multiple Stellar wallets. +- **GitHub**: https://github.com/Creit-Tech/Stellar-Wallets-Kit +- **Supports**: Freighter, LOBSTR, xBull, Albedo, Rabet, Hana, Ledger, Trezor, WalletConnect + +## Developer Tools + +### Smart Account & Authentication + +#### Smart Account Kit (Recommended) +Comprehensive TypeScript SDK for OpenZeppelin Smart Accounts on Stellar/Soroban. +- **GitHub**: https://github.com/kalepail/smart-account-kit +- **Use Case**: Production smart wallets with passkeys +- **Built On**: [OpenZeppelin stellar-contracts](https://github.com/OpenZeppelin/stellar-contracts) +- **Features**: + - Context rules with fine-grained authorization scopes + - Policy support (threshold multisig, spending limits, custom policies) + - Session management with automatic credential persistence + - External wallet adapter support (Freighter, LOBSTR, etc.) + - Built-in indexer for contract discovery + - Multiple signer types (passkeys, Ed25519, policies) + +#### Passkey Kit (Legacy) +Original TypeScript SDK for passkey-based smart wallets. +- **GitHub**: https://github.com/kalepail/passkey-kit +- **Status**: Legacy - use Smart Account Kit for new projects +- **Use Case**: Simple passkey wallet integration +- **Integration**: OpenZeppelin Relayer (gasless tx), Mercury (indexing) +- **Demo**: [passkey-kit-demo.pages.dev](https://passkey-kit-demo.pages.dev) +- **Example**: [Super Peach](https://github.com/kalepail/superpeach) + +#### OpenZeppelin Relayer +Service for fee-sponsored transaction submission. +- **Docs**: https://docs.openzeppelin.com/relayer +- **Use Case**: Gasless transactions, fee sponsoring + +### Data Indexing + +For a full directory of indexing options, see [Stellar Indexer Docs](https://developers.stellar.org/docs/data/indexers). + +#### Mercury +Stellar-native data indexing platform with Retroshades technology. +- **Website**: https://mercurydata.app +- **Docs**: https://docs.mercurydata.app +- **Use Case**: Event indexing, data queries, automation +- **Features**: Zephyr VM (serverless Rust execution at ledger close), GraphQL API + +#### SubQuery +Multi-chain indexer supporting Stellar and Soroban. +- **Website**: https://subquery.network +- **Quick Start**: https://subquery.network/doc/indexer/quickstart/quickstart_chains/stellar.html +- **Features**: Block/transaction/operation/event handlers, multi-threading, 300+ chains + +#### Goldsky +Real-time data replication and subgraph platform. +- **Website**: https://goldsky.com +- **Docs**: https://docs.goldsky.com/chains/stellar +- **Features**: Mirror (real-time pipelines), subgraphs, on-chain + off-chain data + +#### Zephyr VM +Cloud execution environment for blockchain data processing. +- **GitHub**: https://github.com/xycloo/zephyr-vm +- **Use Case**: Indexing, monitoring, automation +- **Features**: Self-hostable, ledger-close execution + +### Contract Libraries + +#### OpenZeppelin Stellar Contracts +Audited smart contract library for Soroban (track latest release tags before pinning versions). +- **GitHub**: https://github.com/OpenZeppelin/stellar-contracts +- **Docs**: https://developers.stellar.org/docs/tools/openzeppelin-contracts +- **Contract Wizard**: https://wizard.openzeppelin.com/stellar +- **Includes**: Tokens (fungible/NFT), governance (timelock), vaults (SEP-56), access control, fee forwarder +- **Crates**: `stellar-tokens`, `stellar-access`, `stellar-contract-utils` + +### Security Tools + +#### Scout Soroban (CoinFabrik) +Open-source vulnerability detector with 23 detectors for Soroban contracts. +- **GitHub**: https://github.com/CoinFabrik/scout-soroban +- **Install**: `cargo install cargo-scout-audit` +- **Features**: CLI tool, VSCode extension, SARIF output for CI/CD +- **Examples**: https://github.com/CoinFabrik/scout-soroban-examples + +#### OpenZeppelin Security Detectors SDK +Framework for building custom security detectors for Soroban. +- **GitHub**: https://github.com/OpenZeppelin/soroban-security-detectors-sdk +- **Detectors**: `auth_missing`, `unchecked_ft_transfer`, improper TTL, contract panics +- **Extensible**: Load external detector libraries, CI/CD ready + +#### Certora Sunbeam Prover +Formal verification for Soroban — first WASM platform supported by Certora. +- **Docs**: https://docs.certora.com/en/latest/docs/sunbeam/index.html +- **Spec Language**: CVLR (Rust macros) — https://github.com/Certora/cvlr +- **Reports**: [Blend V1 verification](https://www.certora.com/reports/blend-smart-contract-verification-report) +- **Verifies at**: WASM bytecode level, eliminating compiler trust assumptions + +#### Runtime Verification — Komet +Formal verification and testing tool designed for Soroban (SCF-funded). +- **Docs**: https://docs.runtimeverification.com/komet +- **Repo**: https://github.com/runtimeverification/komet +- **Spec Language**: Rust — property-based tests written in the same language as Soroban contracts +- **Operates at**: WASM bytecode level via [KWasm semantics](https://github.com/runtimeverification/wasm-semantics) (eliminates compiler trust assumptions) +- **Features**: Fuzzing, testing, formal verification +- **Reports**: https://github.com/runtimeverification/publications +- **Example**: [TokenOps audit and verification report](https://github.com/runtimeverification/publications/blob/main/reports/smart-contracts/TokenOps.pdf) +- **Blog**: [Introducing Komet](https://runtimeverification.com/blog/introducing-komet-smart-contract-testing-and-verification-tool-for-soroban-created-by-runtime-verification) + +#### Soroban Security Portal (Inferara) +Community security knowledge base (SCF-funded). +- **Website**: https://sorobansecurity.com +- **Features**: Searchable audit reports, vulnerability database, best practices + +### CLI & SDKs + +#### Stellar CLI +Official command-line interface for Stellar/Soroban. +- **Docs**: https://developers.stellar.org/docs/tools/stellar-cli +- **Features**: Contract build, deploy, invoke, bindings generation + +#### Stellar SDK (JavaScript) +Official JavaScript/TypeScript SDK. +- **GitHub**: https://github.com/stellar/js-stellar-sdk +- **npm**: `@stellar/stellar-sdk` + +#### Soroban Rust SDK +Rust SDK for Soroban contract development. +- **GitHub**: https://github.com/stellar/rs-soroban-sdk +- **Crate**: `soroban-sdk` + +## Oracles + +#### Reflector Network +Community-powered price oracle for Stellar. +- **Website**: https://reflector.network +- **Docs**: https://developers.stellar.org/docs/data/oracles/oracle-providers +- **Features**: SEP-40 compatible, on-chain/off-chain prices, webhooks +- **Integrations**: Blend, OrbitCDP, DeFindex, EquitX, Slender + +#### DIA Oracle +Cross-chain oracle with 20,000+ asset support. +- **Website**: https://diadata.org +- **Blog**: https://www.diadata.org/blog/post/soroban-stellar-oracle-dia/ +- **Features**: VWAPIR methodology, custom feeds + +#### Band Protocol +Cross-chain data oracle on BandChain. +- **Website**: https://bandprotocol.com +- **Architecture**: Cosmos SDK-based, cross-chain + +## Gaming & NFTs + +#### Litemint +NFT marketplace and gaming platform. +- **GitHub**: https://github.com/litemint/litemint-soroban-contracts +- **Contracts**: Timed auctions, royalty payments +- **Features**: Open/sealed bids, ascending/descending price, buy-now + +## Infrastructure + +### Anchors & On/Off Ramps + +#### Stellar Ramps +Suite of open standards for fiat-crypto bridges. +- **Docs**: https://stellar.org/use-cases/ramps +- **SEPs**: SEP-6, SEP-24, SEP-31 (deposits/withdrawals/cross-border) + +#### Anchor Platform +SDF-maintained platform for building SEP-compliant anchors. +- **Docs**: https://developers.stellar.org/docs/learn/fundamentals/anchors +- **GitHub**: https://github.com/stellar/java-stellar-anchor-sdk + +### Block Explorers + +#### StellarExpert +Comprehensive network explorer with analytics. +- **Website**: https://stellar.expert +- **Features**: Transactions, accounts, assets, contracts + +#### Stellar Lab +Developer tools and transaction builder. +- **Website**: https://lab.stellar.org + +#### StellarChain +Alternative explorer with contract support. +- **Website**: https://stellarchain.io + +### Disbursements + +#### Stellar Disbursement Platform (SDP) +Bulk payment infrastructure for enterprises. +- **Docs**: https://developers.stellar.org/docs/category/use-the-stellar-disbursement-platform +- **GitHub**: https://github.com/stellar/stellar-disbursement-platform +- **Use Case**: Mass payments, aid distribution, payroll + +## Example Repositories + +### Official Examples + +#### Soroban Examples +Official educational smart contract examples. +- **GitHub**: https://github.com/stellar/soroban-examples +- **Includes**: Tokens, atomic swaps, auth, events, liquidity pools, timelock, deployer, merkle distribution + +#### Soroban Example dApp +Crowdfunding dApp with Next.js frontend. +- **GitHub**: https://github.com/stellar/soroban-example-dapp +- **Learning**: Full-stack Soroban development, Freighter integration + +### Community Examples + +#### Soroban Guide (Xycloo) +Learning resources and example contracts. +- **GitHub**: https://github.com/xycloo/soroban-guide +- **Includes**: Events, rock-paper-scissors, vaults, Dutch auctions + +#### Soroban Contracts (icolomina) +Governance and investment contract examples. +- **GitHub**: https://github.com/icolomina/soroban-contracts +- **Includes**: Ballot voting, investment contracts, multisig + +#### Oracle Example +Publisher-subscriber oracle pattern. +- **GitHub**: https://github.com/FredericRezeau/soroban-oracle-example +- **Uses**: soroban-kit oracle module + +#### OZ Stellar NFT +Simple NFT using OpenZeppelin. +- **GitHub**: https://github.com/jamesbachini/OZ-Stellar-NFT + +## Cross-Chain + +#### Axelar +Cross-chain gateway and Interchain Token Service for Soroban. +- **GitHub**: https://github.com/axelarnetwork/axelar-amplifier-stellar +- **Use Case**: Cross-chain messaging, token bridging, interoperability +- **Status**: Active development (verify latest activity before integrating) + +#### Allbridge Core +Cross-chain stable swap bridge (Stellar is 10th supported chain). +- **Use Case**: Cross-chain stablecoin transfers (USDC between Stellar, Base, Arbitrum, etc.) +- **Features**: Automatic Stellar account activation, liquidity pools + +#### LayerZero +Omnichain interoperability protocol with Stellar support. +- **Use Case**: Cross-chain messaging, token bridging (OFT/ONFT), dApp interoperability +- **Features**: OApp standard, Omni-Chain Fungible Tokens, native issuer minting/burning control + +## Builder Teams & Companies + +Notable teams shipping production-level code on Stellar/Soroban. For a broader directory, see [Stellar Ecosystem](https://stellar.org/ecosystem). + +| Team | Website | GitHub | X/Twitter | Notable Projects | +|------|---------|--------|-----------|-----------------| +| **Lightsail Network** | [lightsail.network](https://lightsail.network) | [lightsail-network](https://github.com/lightsail-network) | [@overcat_me](https://x.com/overcat_me) | Quasar RPC, Java/Python SDKs, Ledger app, validators | +| **PaltaLabs** | [paltalabs.io](https://paltalabs.io) | [paltalabs](https://github.com/paltalabs) | [@PaltaLabs](https://x.com/PaltaLabs) | Soroswap, DeFindex | +| **Aha Labs** | [ahalabs.dev](https://ahalabs.dev) | [AhaLabs](https://github.com/AhaLabs) | [@AhaLabsDev](https://x.com/AhaLabsDev) | Scaffold Stellar, Soroban CLI contributions | +| **OpenZeppelin** | [openzeppelin.com](https://www.openzeppelin.com/networks/stellar) | [OpenZeppelin](https://github.com/OpenZeppelin/stellar-contracts) | [@OpenZeppelin](https://x.com/OpenZeppelin) | Contracts library, Relayer, Monitor, Security Detectors SDK | +| **Cheesecake Labs** | [cheesecakelabs.com](https://cheesecakelabs.com) | [CheesecakeLabs](https://github.com/CheesecakeLabs) | [@CheesecakeLabs](https://x.com/CheesecakeLabs) | Stellar Plus library | +| **Script3 / Blend Capital** | [script3.io](https://script3.io) | [script3](https://github.com/script3), [blend-capital](https://github.com/blend-capital) | [@script3official](https://x.com/script3official) | Blend Protocol | +| **Xycloo Labs** | [xycloo.com](https://xycloo.com) | [Xycloo](https://github.com/Xycloo) | [@heytdep](https://x.com/heytdep) | Mercury indexer, Zephyr VM | +| **CoinFabrik** | [coinfabrik.com](https://www.coinfabrik.com) | [CoinFabrik](https://github.com/CoinFabrik) | [@coinfabrik](https://x.com/coinfabrik) | Scout Soroban (static analysis) | +| **Creit Tech** | [creit.tech](https://creit.tech) | [Creit-Tech](https://github.com/Creit-Tech) | [@CreitTech_](https://x.com/CreitTech_) | Stellar Wallets Kit, xBull, SorobanHub | +| **Ultra Stellar** | [ultrastellar.com](https://ultrastellar.com) | [lobstrco](https://github.com/lobstrco) | [@Lobstrco](https://x.com/Lobstrco) | LOBSTR wallet, StellarExpert | + +## Project Directories + +### Official Directories + +#### Stellar Ecosystem Directory +The canonical, up-to-date project directory maintained by SDF. +- **Website**: https://stellar.org/ecosystem +- **Features**: Search by country, asset, category +- **Includes**: DeFi, wallets, anchors, on/off ramps, exchanges, infrastructure + +#### SCF Project Tracker +All Stellar Community Fund–funded projects with status and milestones. +- **Website**: https://communityfund.stellar.org/projects + +### Funding Programs + +#### Stellar Community Fund (SCF) +Grants up to $150K per funding round. +- **Website**: https://communityfund.stellar.org +- **Funded**: 100+ projects across DeFi, NFT, GameFi, Web3 + +#### Soroban Audit Bank +Security audit funding for SCF projects. +- **Website**: https://stellar.org/grants-and-funding/soroban-audit-bank +- **Features**: Pre-negotiated audit rates, readiness checklist + +## Real-World Assets + +### Major Issuers on Stellar +- **Franklin Templeton**: Regulated fund tokens +- **Ondo**: Tokenized real estate +- **RedSwan**: $100M commercial real estate +- **Centrifuge**: Yield-generating tokens +- **WisdomTree**: Asset-backed tokens + +### Stablecoins +- **USDC** (Circle): Primary USD stablecoin +- **EURC** (Circle): EUR stablecoin +- **PYUSD** (PayPal): Verify current issuance and distribution details before launch planning + +## Enterprise Integrations + +Major companies building on Stellar: +- **PayPal**: PYUSD stablecoin +- **Visa**: Settlement infrastructure +- **Mastercard**: Payment rails +- **Wirex**: USDC/EURC settlement +- **U.S. Bank**: Custom stablecoin testing +- **PwC**: Stablecoin exploration + +--- + +# Part 3: Curated Resources + + +## Official Documentation + +### Stellar Developer Docs +- [Stellar Documentation](https://developers.stellar.org/docs) - Primary documentation +- [Build Smart Contracts](https://developers.stellar.org/docs/build/smart-contracts) - Soroban guides +- [Build Apps](https://developers.stellar.org/docs/build/apps) - Client application guides +- [Tools & SDKs](https://developers.stellar.org/docs/tools) - Available tooling +- [Networks](https://developers.stellar.org/docs/networks) - Network configuration +- [Learn Fundamentals](https://developers.stellar.org/docs/learn/fundamentals) - Core concepts +- [Security Best Practices](https://developers.stellar.org/docs/build/security-docs) + +### API References +- [Stellar RPC Methods](https://developers.stellar.org/docs/data/apis/rpc/api-reference/methods) - RPC API +- [Horizon API](https://developers.stellar.org/docs/data/apis/horizon/api-reference) - REST API (legacy-focused) +- [Oracle Providers](https://developers.stellar.org/docs/data/oracles/oracle-providers) + +## SDKs + +### Client SDKs (Application Development) +- [JavaScript SDK](https://github.com/stellar/js-stellar-sdk) - `@stellar/stellar-sdk` +- [Python SDK](https://github.com/StellarCN/py-stellar-base) - `stellar-sdk` +- [Java SDK](https://github.com/lightsail-network/java-stellar-sdk) - `network.lightsail:stellar-sdk` (Lightsail Network) +- [Go SDK](https://github.com/stellar/go-stellar-sdk) - `txnbuild`, Horizon & RPC clients +- [Rust SDK (RPC Client)](https://github.com/stellar/rs-stellar-rpc-client) +- [SDK Documentation](https://developers.stellar.org/docs/tools/sdks/client-sdks) + +### Contract SDK (Soroban Development) +- [Soroban Rust SDK](https://github.com/stellar/rs-soroban-sdk) - `soroban-sdk` +- [Soroban SDK Docs](https://docs.rs/soroban-sdk/latest/soroban_sdk/) - Rust docs + +## CLI Tools + +### Stellar CLI +- [Stellar CLI Repository](https://github.com/stellar/stellar-cli) +- [CLI Installation](https://developers.stellar.org/docs/tools/stellar-cli) +- [CLI Commands Reference](https://developers.stellar.org/docs/tools/stellar-cli/stellar-cli-commands) + +### Scaffold Stellar +- [Scaffold Stellar](https://scaffoldstellar.org) - Full-stack dApp scaffolding (contracts + React/Vite/TS frontend) +- [Scaffold Docs](https://developers.stellar.org/docs/tools/scaffold-stellar) - Official documentation +- [GitHub](https://github.com/theahaco/scaffold-stellar) - Open source (Apache 2.0) + +### Quickstart (Local Development) +- [Quickstart Docker](https://github.com/stellar/quickstart) +- [Quickstart Guide](https://developers.stellar.org/docs/tools/quickstart) + +## Contract Libraries & Tools + +### OpenZeppelin Stellar Contracts +- [OpenZeppelin Contracts](https://github.com/OpenZeppelin/stellar-contracts) +- [Documentation](https://developers.stellar.org/docs/tools/openzeppelin-contracts) +- [Contract Wizard](https://wizard.openzeppelin.com/stellar) - Generate contracts + +### Smart Account SDKs +- [Smart Account Kit](https://github.com/kalepail/smart-account-kit) - Production smart wallet SDK (recommended) +- [Passkey Kit](https://github.com/kalepail/passkey-kit) - Legacy passkey wallet SDK +- [Super Peach](https://github.com/kalepail/superpeach) - Smart wallet implementation example + +### Developer Tools +- [Stellar Wallets Kit](https://github.com/Creit-Tech/Stellar-Wallets-Kit) - Multi-wallet integration +- [OpenZeppelin Relayer](https://docs.openzeppelin.com/relayer) - Fee-sponsored transactions + +## Example Repositories + +### Official Examples +- [Soroban Examples](https://github.com/stellar/soroban-examples) - Core contract patterns +- [Soroban Example dApp](https://github.com/stellar/soroban-example-dapp) - Crowdfunding Next.js app +- [Stellar Repositories](https://github.com/orgs/stellar/repositories) + +### Community Examples +- [Scout Soroban Examples](https://github.com/CoinFabrik/scout-soroban-examples) - Security-audited examples +- [Soroban Guide (Xycloo)](https://github.com/xycloo/soroban-guide) - Learning resources +- [Soroban Contracts (icolomina)](https://github.com/icolomina/soroban-contracts) - Governance examples +- [Oracle Example](https://github.com/FredericRezeau/soroban-oracle-example) - Pub-sub oracle pattern +- [OZ Stellar NFT](https://github.com/jamesbachini/OZ-Stellar-NFT) - Simple NFT with OpenZeppelin + +## Ecosystem Projects + +For DeFi protocols, wallets, oracles, gaming/NFTs, cross-chain bridges, and builder teams, see Part 2: Stellar Ecosystem below. + +## Security + +For vulnerability patterns, checklists, and detailed tooling guides, see [security.md](../soroban/SKILL.md). + +### Bug Bounty Programs +- [Stellar Bug Bounty (Immunefi)](https://immunefi.com/bug-bounty/stellar/) - Up to $250K, covers core + Soroban +- [OpenZeppelin Stellar Bounty (Immunefi)](https://immunefi.com/bug-bounty/openzeppelin-stellar/) - Up to $25K +- [HackerOne VDP](https://stellar.org/grants-and-funding/bug-bounty) - Web application vulnerabilities + +### Audit Bank & Audit Firms +- [Soroban Audit Bank](https://stellar.org/grants-and-funding/soroban-audit-bank) - $3M+ deployed, 43+ audits +- [Audited Projects List](https://stellar.org/audit-bank/projects) - Public audit registry +- Partners: OtterSec, Veridise, Runtime Verification, CoinFabrik, QuarksLab, Coinspect, Certora, Halborn, Zellic, Code4rena + +### Static Analysis +- [Scout Soroban](https://github.com/CoinFabrik/scout-soroban) - 23 vulnerability detectors, VSCode extension +- [OZ Security Detectors SDK](https://github.com/OpenZeppelin/soroban-security-detectors-sdk) - Custom detector framework + +### Formal Verification +- [Certora Sunbeam Prover](https://docs.certora.com/en/latest/docs/sunbeam/index.html) - WASM-level formal verification +- [CVLR Spec Language](https://github.com/Certora/cvlr) - Certora Verification Language for Rust +- [Runtime Verification Komet](https://runtimeverification.com/blog/introducing-komet-smart-contract-testing-and-verification-tool-for-soroban-created-by-runtime-verification) - Soroban verification tool + +### Security Resources +- [Veridise Security Checklist](https://veridise.com/blog/audit-insights/building-on-stellar-soroban-grab-this-security-checklist-to-avoid-vulnerabilities/) - Soroban-specific +- [Soroban Security Portal](https://sorobansecurity.com) - Community vulnerability database +- [CoinFabrik Audit Reports](https://www.coinfabrik.com/smart-contract-audit-reports/) +- [Certora Security Reports](https://github.com/Certora/SecurityReports) - Includes Stellar verifications + +## Zero-Knowledge Proofs (Status-Sensitive) + +For comprehensive ZK development guidance, see [zk-proofs.md](../zk-proofs/SKILL.md). + +Always verify CAP status and network support before treating any ZK primitive as production-available. + +### Protocol & Specifications +- [Protocol upgrades](https://stellar.org/protocol-upgrades) - Upgrade timeline and network context +- [CAP-0074](https://github.com/stellar/stellar-protocol/blob/master/core/cap-0074.md) - BN254 host functions proposal +- [CAP-0075](https://github.com/stellar/stellar-protocol/blob/master/core/cap-0075.md) - Poseidon/Poseidon2 host functions proposal + +### SDK Documentation +- [Soroban SDK BN254 module](https://docs.rs/soroban-sdk/latest/soroban_sdk/crypto/bn254/) - Verify availability in your pinned SDK version +- [Soroban SDK Crypto](https://docs.rs/soroban-sdk/latest/soroban_sdk/crypto/) - Full crypto module reference + +### Proving Systems & Tooling +- [Noir Documentation](https://noir-lang.org/docs/) - Aztec's ZK domain-specific language +- [RISC Zero](https://dev.risczero.com/) - General-purpose zkVM for Rust programs + +### Example Contracts +- [Soroban Examples](https://github.com/stellar/soroban-examples) - Official examples (includes `groth16_verifier`, `privacy-pools`, `import_ark_bn254`) + +## Testing + +### Testing Guides +- [Definitive Guide to Testing Smart Contracts](https://stellar.org/blog/developers/the-definitive-guide-to-testing-smart-contracts-on-stellar) - Comprehensive overview +- [Fuzzing Guide](https://developers.stellar.org/docs/build/guides/testing/fuzzing) - cargo-fuzz + SorobanArbitrary +- [Fuzzing Example Contract](https://developers.stellar.org/docs/build/smart-contracts/example-contracts/fuzzing) +- [Differential Testing](https://developers.stellar.org/docs/build/guides/testing/differential-tests-with-test-snapshots) - Automatic test snapshots +- [Fork Testing](https://developers.stellar.org/docs/build/guides/testing/fork-testing) - Test against production state +- [Mutation Testing](https://developers.stellar.org/docs/build/guides/testing/mutation-testing) - cargo-mutants + +### Local Development +- [Stellar Quickstart](https://github.com/stellar/quickstart) +- [Docker Setup](https://developers.stellar.org/docs/tools/quickstart) + +### Test Networks +- [Testnet Info](https://developers.stellar.org/docs/networks/testnet) +- [Friendbot](https://friendbot.stellar.org) - Testnet faucet + +## Data & Analytics + +### Data Documentation Hub +- [Stellar Data Overview](https://developers.stellar.org/docs/data) - Choose the right tool (APIs, indexers, analytics, oracles) +- [Indexer Directory](https://developers.stellar.org/docs/data/indexers) - All supported indexers +- [RPC Provider Directory](https://developers.stellar.org/docs/data/apis/rpc/providers) - All RPC infrastructure providers + +### Block Explorers +- [StellarExpert](https://stellar.expert) - Network explorer & analytics +- [StellarExpert API](https://stellar.expert/openapi.html) - Free REST API (no auth, CORS-enabled) +- [Stellar Lab](https://lab.stellar.org) - Developer tools +- [StellarChain](https://stellarchain.io) - Alternative explorer + +### Data Indexers +- [Mercury](https://mercurydata.app) - Stellar-native indexer with Retroshades + GraphQL ([docs](https://docs.mercurydata.app)) +- [SubQuery](https://subquery.network) - Multi-chain indexer with Stellar/Soroban support ([quick start](https://subquery.network/doc/indexer/quickstart/quickstart_chains/stellar.html)) +- [Goldsky](https://goldsky.com) - Real-time data replication pipelines + subgraphs ([Stellar docs](https://docs.goldsky.com/chains/stellar)) +- [Zephyr VM](https://github.com/xycloo/zephyr-vm) - Serverless Rust execution at ledger close + +### Historical Data & Analytics +- [Hubble](https://developers.stellar.org/docs/data/analytics/hubble) - BigQuery dataset (updated every 30 min) +- [Galexie](https://developers.stellar.org/docs/data/indexers/build-your-own/galexie) - Data pipeline for building data lakes +- [Data Lake](https://developers.stellar.org/docs/data/apis/rpc/admin-guide/data-lake-integration) - Powers RPC Infinite Scroll (public via AWS Open Data) + +## Infrastructure + +### Anchors & On/Off Ramps +- [Anchor Platform](https://github.com/stellar/java-stellar-anchor-sdk) +- [Anchor Docs](https://developers.stellar.org/docs/category/anchor-platform) +- [Anchor Fundamentals](https://developers.stellar.org/docs/learn/fundamentals/anchors) +- [Stellar Ramps](https://stellar.org/use-cases/ramps) + +### Disbursements +- [Stellar Disbursement Platform](https://github.com/stellar/stellar-disbursement-platform) +- [SDP Documentation](https://developers.stellar.org/docs/category/use-the-stellar-disbursement-platform) + +### RPC Providers +- [RPC Provider Directory](https://developers.stellar.org/docs/data/apis/rpc/providers) - Full list of providers +- [Quasar (Lightsail Network)](https://quasar.lightsail.network) - Stellar-native RPC, Archive RPC, hosted Galexie Data Lake +- [Blockdaemon](https://www.blockdaemon.com/soroban) - Enterprise RPC +- [Validation Cloud](https://www.validationcloud.io) - Testnet & Mainnet +- [QuickNode](https://www.quicknode.com) - Testnet, Mainnet & Dedicated +- [Ankr](https://www.ankr.com) - Testnet & Mainnet +- [NOWNodes](https://nownodes.io) - All networks incl. Futurenet +- [GetBlock](https://getblock.io) - Testnet & Mainnet + +## Protocol & Governance + +### Stellar Protocol +- [Stellar Protocol Repo](https://github.com/stellar/stellar-protocol) +- [CAPs](https://github.com/stellar/stellar-protocol/tree/master/core) - Core Advancement Proposals +- [SEPs](https://github.com/stellar/stellar-protocol/tree/master/ecosystem) - Stellar Ecosystem Proposals + +### Key SEP Standards +- [SEP-0001](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0001.md) - stellar.toml +- [SEP-0010](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0010.md) - Web Authentication +- [SEP-0024](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0024.md) - Hosted Deposit/Withdrawal +- [SEP-0030](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0030.md) - Account Recovery +- [SEP-0031](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0031.md) - Cross-Border Payments +- [SEP-0041](https://developers.stellar.org/docs/tokens/token-interface) - Token Interface +- [SEP-0045](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0045.md) - Web Auth for Contract Accounts (Draft) +- [SEP-0046](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0046.md) - Contract Meta (Active) +- [SEP-0048](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0048.md) - Contract Interface Specification (Active) +- [SEP-0050](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0050.md) - Non-Fungible Tokens (Draft) +- [SEP-0056](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0056.md) - Tokenized Vault Standard (Draft, ERC-4626 equivalent) + +### Network Upgrades +- [Protocol Upgrades](https://stellar.org/protocol-upgrades) +- [SDF Blog](https://stellar.org/blog) + +## Project Directories & Funding + +### Ecosystem Discovery +- [Stellar Ecosystem](https://stellar.org/ecosystem) - Official project directory +- [Stellar Community Fund Projects](https://communityfund.stellar.org/projects) + +### Funding Programs +- [Stellar Community Fund](https://communityfund.stellar.org) - Grants up to $150K +- [Soroban Audit Bank](https://stellar.org/grants-and-funding/soroban-audit-bank) +- [$100M Soroban Adoption Fund](https://stellar.org/soroban) + +## Learning Resources + +### Official Tutorials +- [Getting Started](https://developers.stellar.org/docs/build/smart-contracts/getting-started) +- [Hello World Contract](https://developers.stellar.org/docs/build/smart-contracts/getting-started/hello-world) +- [Deploy to Testnet](https://developers.stellar.org/docs/build/smart-contracts/getting-started/deploy-to-testnet) +- [TypeScript Bindings](https://developers.stellar.org/docs/build/apps/guestbook/bindings) +- [Passkey Prerequisites](https://developers.stellar.org/docs/build/apps/guestbook/passkeys-prerequisites) + +### Video Content +- [Stellar YouTube](https://www.youtube.com/@StellarDevelopmentFoundation) +- [Learn Rust for Smart Contracts (DAO Series)](https://www.youtube.com/watch?v=VeQM5N-0DrI) +- [Call Option Contract Walkthrough](https://www.youtube.com/watch?v=Z8FHVllP_D0) +- [Blend Protocol Tutorial](https://www.youtube.com/watch?v=58j0QkXKiDU) + +### Developer Tools +- [Stella AI Bot](https://developers.stellar.org/docs/tools/developer-tools) - AI assistant for Stellar developer questions +- [Soroban Playground](https://soropg.com) - Browser-based Soroban IDE ([GitHub](https://github.com/jamesbachini/Soroban-Playground)) + +### Blog Posts & Guides +- [Composability on Stellar](https://stellar.org/blog/developers/composability-on-stellar-from-concept-to-reality) +- [Testing Smart Contracts Guide](https://stellar.org/blog/developers/the-definitive-guide-to-testing-smart-contracts-on-stellar) +- [Sorobounty Spectacular Tutorials](https://stellar.org/blog/developers/sorobounty-spectacular-dapp-tutorials) +- [Learn Soroban 1-2-3 (Community Tools)](https://stellar.org/blog/developers/learn-soroban-as-easy-as-1-2-3-with-community-made-tooling) +- [SCF Infrastructure Recap](https://stellar.org/blog/ecosystem/stellar-community-fund-recap-soroban-infrastructure) +- [Native vs Soroban Tokens](https://cheesecakelabs.com/blog/native-tokens-vs-soroban-tokens/) +- [57Blocks Integration Testing](https://57blocks.com/blog/soroban-integration-testing-best-practices) + +## Stablecoins on Stellar + +### Major Stablecoins +- [USDC on Stellar](https://www.circle.com/usdc/stellar) - Circle +- [EURC on Stellar](https://www.circle.com/en/eurc) - Circle +- PYUSD (PayPal) - Verify current issuer/distribution details before integration + +### Asset Discovery +- [StellarExpert Asset Directory](https://stellar.expert/explorer/public/asset) + +## Community + +### Developer Resources +- [Stellar Developers Discord](https://discord.gg/stellar) +- [Stellar Stack Exchange](https://stellar.stackexchange.com) +- [GitHub Discussions](https://github.com/stellar/stellar-protocol/discussions) + +### Key People to Follow + +Builders and contributors actively shaping the Stellar/Soroban ecosystem: + +| Name | GitHub | X/Twitter | Focus | +|------|--------|-----------|-------| +| Tyler van der Hoeven | [kalepail](https://github.com/kalepail) | [@kalepail](https://x.com/kalepail) | SDF DevRel, Smart Account Kit, Passkey Kit, Launchtube | +| Leigh McCulloch | [leighmcculloch](https://github.com/leighmcculloch) | [@___leigh___](https://x.com/___leigh___) | SDF core engineer, Stellar CLI, Soroban SDK | +| James Bachini | [jamesbachini](https://github.com/jamesbachini) | [@james_bachini](https://x.com/james_bachini) | SDF Dev in Residence, Soroban Playground, tutorials | +| Elliot Voris | [ElliotFriend](https://github.com/ElliotFriend) | [@ElliotFriend](https://x.com/ElliotFriend) | SDF DevRel, community education | +| Carsten Jacobsen | [carstenjacobsen](https://github.com/carstenjacobsen) | — | SDF, weekly dev meetings, Soroban examples | +| Esteban Iglesias | [esteblock](https://github.com/esteblock) | [@esteblock_dev](https://x.com/esteblock_dev) | PaltaLabs, Soroswap, DeFindex | +| Markus Paulson-Luna | [markuspluna](https://github.com/markuspluna) | [@script3official](https://x.com/script3official) | Script3, Blend Protocol | +| Alexander Mootz | [mootz12](https://github.com/mootz12) | — | Script3, Blend contracts | +| Tommaso | [heytdep](https://github.com/heytdep) | [@heytdep](https://x.com/heytdep) | Xycloo Labs, Mercury indexer, ZephyrVM | +| OrbitLens | [orbitlens](https://github.com/orbitlens) | [@orbitlens](https://x.com/orbitlens) | Reflector oracle, StellarExpert, Albedo | +| Frederic Rezeau | [FredericRezeau](https://github.com/FredericRezeau) | [@FredericRezeau](https://x.com/FredericRezeau) | Litemint, soroban-kit, gaming | +| Jun Luo (Overcat) | [overcat](https://github.com/overcat) | [@overcat_me](https://x.com/overcat_me) | Lightsail Network, Quasar RPC, Java/Python SDKs, Ledger app | +| Jay Geng | [jayz22](https://github.com/jayz22) | — | SDF, Soroban SDK, confidential tokens | +| Chad Ostrowski | [chadoh](https://github.com/chadoh) | [@chadoh](https://x.com/chadoh) | Aha Labs CEO, Scaffold Stellar, Soroban CLI | +| Willem Wyndham | [willemneal](https://github.com/willemneal) | [@willemneal](https://x.com/willemneal) | Aha Labs co-founder, Scaffold Stellar, JS contract client | + +### Builder Teams & Companies +See Part 2: Stellar Ecosystem above for a table of teams shipping production code on Stellar/Soroban, with GitHub orgs, websites, and Twitter handles. + +### Foundation +- [Stellar Development Foundation](https://stellar.org/foundation) +- [Foundation Roadmap](https://stellar.org/foundation/roadmap) +- [Ecosystem Blog](https://stellar.org/blog/ecosystem) diff --git a/skill/zk-proofs.md b/skills/zk-proofs/SKILL.md similarity index 73% rename from skill/zk-proofs.md rename to skills/zk-proofs/SKILL.md index 11fde63..041758b 100644 --- a/skill/zk-proofs.md +++ b/skills/zk-proofs/SKILL.md @@ -1,4 +1,35 @@ -# Zero-Knowledge Proofs on Stellar (Status-Sensitive) +--- +name: zk-proofs +description: Zero-knowledge cryptography and privacy patterns on Stellar/Soroban. Covers Groth16 verification, BLS12-381 (CAP-0059, available), BN254 + Poseidon host functions (CAP-0074/0075, status-sensitive), Noir / RISC Zero integration, privacy pools, confidential tokens, Merkle tree commitments, and status-sensitive guidance for protocol/SDK readiness. Use when building privacy-preserving applications or ZK-verifier contracts on Stellar. +user-invocable: true +argument-hint: "[zk task]" +--- + +# Zero-Knowledge Proofs & Privacy + +Privacy patterns and ZK verification on Stellar/Soroban. Capability is protocol- and SDK-version dependent — always verify CAP status, network version, and `soroban-sdk` host-function support before relying on a primitive. + +## When to use this skill +- Implementing a Groth16 (or other SNARK) verifier as a Soroban contract +- Using BLS12-381 host functions +- Planning for BN254 / Poseidon (currently proposed via CAP-0074/0075) +- Integrating Noir or RISC Zero proofs +- Building privacy pools, confidential tokens, or Merkle-tree-backed commitments + +## Status-sensitive — always verify +1. CAP status (`Accepted`/`Implemented` vs draft) +2. Target network software + protocol version +3. `soroban-sdk` release support for the target host functions +4. Available feature flags + graceful fallback paths + +## Related skills +- Soroban verifier contract patterns + tests → `../soroban/SKILL.md` +- Confidential-token integration with classic assets → `../assets/SKILL.md` +- Off-chain proof verification UI → `../dapp/SKILL.md` +- CAPs referenced here → `../standards/SKILL.md` + +--- + ## When to use this guide Use this guide when the user asks for: @@ -126,9 +157,9 @@ Mitigation: ## Example starting points - [Soroban examples](https://github.com/stellar/soroban-examples) - [Groth16 verifier example](https://github.com/stellar/soroban-examples/tree/main/groth16_verifier) -- [Security guide](security.md) -- [Advanced patterns](advanced-patterns.md) -- [Standards reference](standards-reference.md) +- [Security guide](../soroban/SKILL.md) +- [Advanced patterns](../soroban/SKILL.md) +- [Standards reference](../standards/SKILL.md) ## What not to do - Do not claim specific primitives are production-ready without checking CAP status and network support. From db7333964688664b30dbf5dd25dfd3bdb022cd32 Mon Sep 17 00:00:00 2001 From: Kaan Kacar Date: Tue, 12 May 2026 00:09:58 +0300 Subject: [PATCH 2/6] Potential fix for pull request finding Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- skills/soroban/SKILL.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/skills/soroban/SKILL.md b/skills/soroban/SKILL.md index ea5ced8..f6fa468 100644 --- a/skills/soroban/SKILL.md +++ b/skills/soroban/SKILL.md @@ -1891,7 +1891,7 @@ Use this guide for higher-complexity contract architecture: - Regulated token/compliance workflows - Resource and storage optimization -Use `contracts-soroban.md` for core contract syntax and day-to-day patterns. +For 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. ## Design principles - Prefer simple state machines over implicit behavior. From bca8e70e838555f5161c03160fe70036e3898e28 Mon Sep 17 00:00:00 2001 From: Kaan Kacar Date: Tue, 12 May 2026 00:10:07 +0300 Subject: [PATCH 3/6] Potential fix for pull request finding Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- skills/soroban/SKILL.md | 6 ------ 1 file changed, 6 deletions(-) diff --git a/skills/soroban/SKILL.md b/skills/soroban/SKILL.md index f6fa468..1054217 100644 --- a/skills/soroban/SKILL.md +++ b/skills/soroban/SKILL.md @@ -2063,12 +2063,6 @@ Implementation guidance: - Upgrade tests from old state snapshots to new versions. - Negative tests for unauthorized and malformed calls. -## Related docs -- Core contract development: `contracts-soroban.md` -- Security checks: `security.md` -- Testing approach: `testing.md` -- Standards references: `standards-reference.md` - --- # Part 5: Common Pitfalls From 04a709d5f2ad35b19ac14ba7b5e0403fa4a3a1b2 Mon Sep 17 00:00:00 2001 From: Kaan Kacar Date: Tue, 12 May 2026 00:10:15 +0300 Subject: [PATCH 4/6] Potential fix for pull request finding Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- skills/standards/SKILL.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/skills/standards/SKILL.md b/skills/standards/SKILL.md index b01c581..18bad7d 100644 --- a/skills/standards/SKILL.md +++ b/skills/standards/SKILL.md @@ -114,10 +114,10 @@ Use the CAP preamble status fields as the source of truth for implementation rea - Step 5: Document dependencies on draft standards explicitly. ## Related docs -- Contract implementation details: `contracts-soroban.md` -- Advanced architecture guidance: `advanced-patterns.md` -- RPC and data access: `api-rpc-horizon.md` -- Security considerations: `security.md` +- Contract implementation details: [`../soroban/SKILL.md`](../soroban/SKILL.md) +- Advanced architecture guidance: [`../soroban/SKILL.md`](../soroban/SKILL.md) +- RPC and data access: [`../data/SKILL.md`](../data/SKILL.md) +- Security considerations: [`../security/SKILL.md`](../security/SKILL.md) --- From 69a15dd3458c98d5d4838962fd9df4b4ac77bea0 Mon Sep 17 00:00:00 2001 From: Kaan Kacar Date: Tue, 12 May 2026 00:10:26 +0300 Subject: [PATCH 5/6] Potential fix for pull request finding Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- skills/standards/SKILL.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/skills/standards/SKILL.md b/skills/standards/SKILL.md index 18bad7d..a465360 100644 --- a/skills/standards/SKILL.md +++ b/skills/standards/SKILL.md @@ -640,7 +640,7 @@ For DeFi protocols, wallets, oracles, gaming/NFTs, cross-chain bridges, and buil ## Security -For vulnerability patterns, checklists, and detailed tooling guides, see [security.md](../soroban/SKILL.md). +For vulnerability patterns, checklists, and detailed tooling guides, see [Soroban security section](../soroban/SKILL.md). ### Bug Bounty Programs - [Stellar Bug Bounty (Immunefi)](https://immunefi.com/bug-bounty/stellar/) - Up to $250K, covers core + Soroban From b4f3a3d826fed2268a5449cc943ba0d6a5949b6a Mon Sep 17 00:00:00 2001 From: Kaan Kacar Date: Tue, 12 May 2026 00:10:33 +0300 Subject: [PATCH 6/6] Potential fix for pull request finding Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- skills/agentic-payments/SKILL.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/skills/agentic-payments/SKILL.md b/skills/agentic-payments/SKILL.md index a2a83eb..e842c0b 100644 --- a/skills/agentic-payments/SKILL.md +++ b/skills/agentic-payments/SKILL.md @@ -198,7 +198,7 @@ console.log(await res.json()); | Config | Value | |--------|-------| | Network ID | `stellar:pubnet` | -| RPC URL | Provider-specific endpoint (see [Stellar RPC providers directory](https://developers.stellar.org/docs/data/rpc/providers)) | +| RPC URL | Provider-specific endpoint (see [Stellar RPC providers directory](https://developers.stellar.org/docs/data/apis/rpc/providers)) | | Facilitator URL | `https://channels.openzeppelin.com/x402` | | USDC SAC | `CCW67TSZV3SSS2HXMBQ5JFGCKJNXKZM7UQUWUZPUTHXSTZLEO7SJMI75` | | Funding | Real USDC on mainnet (CEX, DEX, or bridge) |