From 51cf40e5d8c9bd3258cd4987acbe864a97998305 Mon Sep 17 00:00:00 2001 From: kalepail Date: Fri, 6 Feb 2026 11:58:28 -0500 Subject: [PATCH 1/3] Refine Stellar dev skill docs and integrate PR #3 content Integrates and hardens the intent of stellar/stellar-dev-skill#3 with maintainability and freshness improvements. Reference: https://github.com/stellar/stellar-dev-skill/pull/3 --- README.md | 4 +- skill/SKILL.md | 14 ++- skill/advanced-patterns.md | 188 ++++++++++++++++++++++++++++++++++ skill/api-rpc-horizon.md | 6 +- skill/contracts-soroban.md | 101 +++++++++++------- skill/ecosystem.md | 2 +- skill/frontend-stellar-sdk.md | 4 +- skill/security.md | 4 +- skill/standards-reference.md | 94 +++++++++++++++++ 9 files changed, 370 insertions(+), 47 deletions(-) create mode 100644 skill/advanced-patterns.md create mode 100644 skill/standards-reference.md diff --git a/README.md b/README.md index 5319164..ce369d8 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Stellar Development Skill -A comprehensive AI skill for modern Stellar development (January 2026 best practices). +A comprehensive AI skill for modern Stellar development with current best practices. Inspired by [solana-foundation/solana-dev-skill](https://github.com/solana-foundation/solana-dev-skill) and [cloudflare/skills](https://github.com/cloudflare/skills). @@ -67,6 +67,8 @@ skill/ ├── 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 ``` diff --git a/skill/SKILL.md b/skill/SKILL.md index a5040c3..ece0c8c 100644 --- a/skill/SKILL.md +++ b/skill/SKILL.md @@ -1,6 +1,6 @@ --- name: stellar-dev -description: End-to-end Stellar development playbook (Jan 2026). 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, zero-knowledge proofs (Protocol 25 X-Ray, BN254, Poseidon), testing strategies, security patterns, and common pitfalls. Optimized for payments, asset tokenization, DeFi, privacy-preserving applications, and financial applications. Use when building on Stellar, Soroban, or working with XLM, Stellar Assets, trustlines, anchors, SEPs, ZK proofs, privacy pools, or the Stellar RPC/Horizon APIs. +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, 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]" --- @@ -64,6 +64,9 @@ Use this Skill when the user asks for: - 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 @@ -83,6 +86,8 @@ Use this Skill when the user asks for: - 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) ### 2. Pick the right building blocks - Contracts: Soroban Rust SDK + Stellar CLI @@ -122,12 +127,13 @@ When you implement changes, provide: - 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) ## 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, -zero-knowledge, zk, zk-snark, groth16, bn254, poseidon, pairing, privacy, confidential, -x-ray, protocol 25, noir, risc zero, privacy pool, merkle tree +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 diff --git a/skill/advanced-patterns.md b/skill/advanced-patterns.md new file mode 100644 index 0000000..d8e10c7 --- /dev/null +++ b/skill/advanced-patterns.md @@ -0,0 +1,188 @@ +# 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/api-rpc-horizon.md b/skill/api-rpc-horizon.md index eb93730..bf6831a 100644 --- a/skill/api-rpc-horizon.md +++ b/skill/api-rpc-horizon.md @@ -15,9 +15,11 @@ Stellar provides two API paradigms: ### Endpoints +> Note: SDF directly provides Futurenet public RPC. For Mainnet RPC, select a provider from the RPC providers directory. + | Network | RPC URL | |---------|---------| -| Mainnet | `https://soroban.stellar.org` | +| Mainnet | Provider-specific endpoint (see RPC providers doc) | | Testnet | `https://soroban-testnet.stellar.org` | | Futurenet | `https://rpc-futurenet.stellar.org` | | Local | `http://localhost:8000/soroban/rpc` | @@ -410,7 +412,7 @@ type NetworkConfig = { const configs: Record = { mainnet: { - rpcUrl: "https://soroban.stellar.org", + rpcUrl: process.env.STELLAR_MAINNET_RPC_URL || "https://mainnet.sorobanrpc.com", horizonUrl: "https://horizon.stellar.org", networkPassphrase: StellarSdk.Networks.PUBLIC, friendbotUrl: null, diff --git a/skill/contracts-soroban.md b/skill/contracts-soroban.md index a386cec..6d0e635 100644 --- a/skill/contracts-soroban.md +++ b/skill/contracts-soroban.md @@ -81,6 +81,55 @@ 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 @@ -484,44 +533,26 @@ fn test_transfer_with_auth() { - Batch operations where possible - Profile resource usage with `stellar contract invoke --sim` -## Zero-Knowledge Cryptography (Protocol 25 "X-Ray") - -Protocol 25 (mainnet January 22, 2026) added native ZK cryptographic primitives via [CAP-0074](https://github.com/stellar/stellar-protocol/blob/master/core/cap-0074.md) and [CAP-0075](https://github.com/stellar/stellar-protocol/blob/master/core/cap-0075.md). - -### BN254 Elliptic Curve (CAP-0074) - -Provides feature parity with Ethereum's EIP-196/EIP-197 precompiles: - -```rust -use soroban_sdk::crypto::bn254::{Bn254, Bn254G1Affine, Fr}; - -let bn254 = env.crypto().bn254(); - -// G1 point addition -let result: Bn254G1Affine = bn254.g1_add(&p0, &p1); - -// G1 scalar multiplication -let result: Bn254G1Affine = bn254.g1_mul(&p0, &scalar); - -// Multi-pairing check (Groth16 verification) -let valid: bool = bn254.pairing_check(g1_points, g2_points); -``` +## Zero-Knowledge Cryptography (Status-Sensitive) -### Poseidon Hash Functions (CAP-0075) +Stellar's ZK cryptography capabilities are evolving. Treat availability as protocol- and network-dependent. -ZK-friendly hash functions (two orders of magnitude fewer ZK constraints than SHA-256). Exposed as raw permutation primitives via `env.crypto_hazmat()` (requires `hazmat` feature flag). +- [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) -### Use Cases Unlocked -- **zk-SNARK verification** (Groth16, PlonK) — on-chain proof verification -- **Privacy pools** — prove lawful source of funds without revealing details -- **Confidential tokens** — hidden balances with validity proofs -- **Merkle trees** with Poseidon hashes for efficient ZK circuits -- **Cross-chain ZK proofs** via Wormhole + RISC Zero integration +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 -### Examples -- [Groth16 Verifier](https://github.com/stellar/soroban-examples/tree/main/groth16_verifier) — zk-SNARK verifier example (uses BLS12-381; BN254 follows the same pattern) -- [BLS Signature](https://github.com/stellar/soroban-examples) — BLS12-381 signature verification +### 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. -> **Note**: BLS12-381 curve operations were added in Protocol 22 via CAP-0059. Protocol 25 adds BN254 as a complement, matching Ethereum's curve for easier migration of EVM ZK applications. +### 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 complete implementation guidance. +> 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 index 683cd33..704a1f0 100644 --- a/skill/ecosystem.md +++ b/skill/ecosystem.md @@ -180,7 +180,7 @@ Cloud execution environment for blockchain data processing. ### Contract Libraries #### OpenZeppelin Stellar Contracts -Audited smart contract library for Soroban (v0.6.0, Jan 2026). +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 diff --git a/skill/frontend-stellar-sdk.md b/skill/frontend-stellar-sdk.md index 4fa5c40..047330e 100644 --- a/skill/frontend-stellar-sdk.md +++ b/skill/frontend-stellar-sdk.md @@ -31,7 +31,7 @@ const networkPassphrase = StellarSdk.Networks.TESTNET; // For Mainnet const server = new StellarSdk.Horizon.Server("https://horizon.stellar.org"); -const rpc = new StellarSdk.rpc.Server("https://soroban.stellar.org"); +const rpc = new StellarSdk.rpc.Server(process.env.NEXT_PUBLIC_STELLAR_MAINNET_RPC_URL || "https://mainnet.sorobanrpc.com"); const networkPassphrase = StellarSdk.Networks.PUBLIC; ``` @@ -51,7 +51,7 @@ export const config = { }, mainnet: { horizonUrl: "https://horizon.stellar.org", - rpcUrl: "https://soroban.stellar.org", + rpcUrl: process.env.NEXT_PUBLIC_STELLAR_MAINNET_RPC_URL || "https://mainnet.sorobanrpc.com", networkPassphrase: StellarSdk.Networks.PUBLIC, friendbotUrl: null, }, diff --git a/skill/security.md b/skill/security.md index ce5ff97..1aa7cac 100644 --- a/skill/security.md +++ b/skill/security.md @@ -472,9 +472,9 @@ 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 (Jan 2025 – Dec 2026) +## OpenZeppelin Partnership Overview -Two-year strategic partnership covering: +Strategic partnership highlights include: - **40 Auditor Weeks** of dedicated security audits - **Stellar Contracts library** (audited, production-ready) - **Relayer** (fee-sponsored transactions, Stellar-native) diff --git a/skill/standards-reference.md b/skill/standards-reference.md new file mode 100644 index 0000000..518cdca --- /dev/null +++ b/skill/standards-reference.md @@ -0,0 +1,94 @@ +# 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` From 935619a0b64e172ae615d52ea1d9108d943d6a99 Mon Sep 17 00:00:00 2001 From: kalepail Date: Fri, 6 Feb 2026 13:20:06 -0500 Subject: [PATCH 2/3] Audit and harden skill docs for long-term maintenance Follow-up integration for #3 (https://github.com/stellar/stellar-dev-skill/pull/3). Adds status-safe ZK guidance, removes brittle endpoint/date assumptions, improves quick navigation in long docs, and keeps routing references aligned. --- README.md | 1 + skill/SKILL.md | 8 +- skill/api-rpc-horizon.md | 22 +- skill/contracts-soroban.md | 7 + skill/ecosystem.md | 8 +- skill/frontend-stellar-sdk.md | 22 +- skill/resources.md | 20 +- skill/testing.md | 7 + skill/zk-proofs.md | 648 +++++++--------------------------- 9 files changed, 209 insertions(+), 534 deletions(-) diff --git a/README.md b/README.md index ce369d8..ea8fab9 100644 --- a/README.md +++ b/README.md @@ -64,6 +64,7 @@ skill/ ├── 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 diff --git a/skill/SKILL.md b/skill/SKILL.md index ece0c8c..3e3728c 100644 --- a/skill/SKILL.md +++ b/skill/SKILL.md @@ -1,6 +1,6 @@ --- 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, 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. +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]" --- @@ -15,7 +15,7 @@ Use this Skill when the user asks for: - Transaction building / sending / confirmation - Stellar Asset issuance and management - Client SDK usage (JavaScript, Python, Go, Rust) -- Zero-knowledge proof verification (BN254, Poseidon, Groth16) +- 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 @@ -41,9 +41,9 @@ Use this Skill when the user asks for: - Full transaction building, signing, and submission - Soroban contract deployment and invocation -### 3. API Access: Stellar RPC first (Horizon deprecated) +### 3. API Access: Stellar RPC first (Horizon legacy-focused) - **Prefer Stellar RPC** for new projects (JSON-RPC, real-time state) -- **Horizon API** is deprecated but maintained for legacy compatibility +- **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 diff --git a/skill/api-rpc-horizon.md b/skill/api-rpc-horizon.md index bf6831a..91acac7 100644 --- a/skill/api-rpc-horizon.md +++ b/skill/api-rpc-horizon.md @@ -7,9 +7,16 @@ Stellar provides two API paradigms: | API | Status | Use Case | |-----|--------|----------| | **Stellar RPC** | Preferred | Soroban, real-time state, new projects | -| **Horizon** | Deprecated (maintained) | Historical data, legacy applications | +| **Horizon** | Legacy-focused | Historical data, legacy applications | -**Recommendation**: Use Stellar RPC for all new projects. Use Horizon only for historical queries or legacy compatibility. +**Recommendation**: Use Stellar RPC for all new projects. Use Horizon mainly for historical queries and legacy compatibility paths. + +## Quick Navigation +- RPC methods and usage: [Stellar RPC](#stellar-rpc) +- Horizon endpoints and streaming: [Horizon API (Legacy)](#horizon-api-legacy) +- Migration strategy: [Migration: Horizon to RPC](#migration-horizon-to-rpc) +- Data history/indexing options: [Historical Data Access](#historical-data-access) +- Environment setup and endpoints: [Network Configuration](#network-configuration) ## Stellar RPC @@ -146,7 +153,7 @@ for (const event of events.events) { - **No streaming**: Poll for updates (no WebSocket) - **Contract-focused**: Limited classic Stellar data -## Horizon API (Deprecated) +## Horizon API (Legacy) ### Endpoints @@ -396,6 +403,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 mainnet RPC, set `STELLAR_MAINNET_RPC_URL` from a provider in the RPC providers directory. ### Environment-Based Setup @@ -410,9 +418,15 @@ type NetworkConfig = { friendbotUrl: string | null; }; +const requireEnv = (name: string): string => { + const value = process.env[name]; + if (!value) throw new Error(`Missing required env var: ${name}`); + return value; +}; + const configs: Record = { mainnet: { - rpcUrl: process.env.STELLAR_MAINNET_RPC_URL || "https://mainnet.sorobanrpc.com", + rpcUrl: requireEnv("STELLAR_MAINNET_RPC_URL"), horizonUrl: "https://horizon.stellar.org", networkPassphrase: StellarSdk.Networks.PUBLIC, friendbotUrl: null, diff --git a/skill/contracts-soroban.md b/skill/contracts-soroban.md index 6d0e635..28272ee 100644 --- a/skill/contracts-soroban.md +++ b/skill/contracts-soroban.md @@ -8,6 +8,13 @@ Use Soroban when you need: - 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: diff --git a/skill/ecosystem.md b/skill/ecosystem.md index 704a1f0..6637244 100644 --- a/skill/ecosystem.md +++ b/skill/ecosystem.md @@ -6,6 +6,8 @@ This guide catalogs the major projects, protocols, and tools in the Stellar ecos > - [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 @@ -341,7 +343,7 @@ Simple NFT using OpenZeppelin. 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 (last commit Nov 2025) +- **Status**: Active development (verify latest activity before integrating) #### Allbridge Core Cross-chain stable swap bridge (Stellar is 10th supported chain). @@ -349,7 +351,7 @@ Cross-chain stable swap bridge (Stellar is 10th supported chain). - **Features**: Automatic Stellar account activation, liquidity pools #### LayerZero -Omnichain interoperability protocol connecting Stellar to 150+ blockchains (launched Nov 2025). +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 @@ -408,7 +410,7 @@ Security audit funding for SCF projects. ### Stablecoins - **USDC** (Circle): Primary USD stablecoin - **EURC** (Circle): EUR stablecoin -- **PYUSD** (PayPal): PayPal USD on Stellar (Q3 2025) +- **PYUSD** (PayPal): Verify current issuance and distribution details before launch planning ## Enterprise Integrations diff --git a/skill/frontend-stellar-sdk.md b/skill/frontend-stellar-sdk.md index 047330e..665e69e 100644 --- a/skill/frontend-stellar-sdk.md +++ b/skill/frontend-stellar-sdk.md @@ -6,6 +6,14 @@ - Clean separation of client/server in Next.js - Transaction sending with proper confirmation handling +## Quick Navigation +- SDK setup and env config: [SDK Initialization](#sdk-initialization) +- Wallet integrations: [Wallet Integration](#wallet-integration) +- Tx build/send patterns: [Transaction Building](#transaction-building), [Transaction Submission](#transaction-submission) +- React + Next.js patterns: [React Components](#react-components), [Next.js App Router Setup](#nextjs-app-router-setup) +- Smart wallets/passkeys: [Smart Accounts (Passkey Wallets)](#smart-accounts-passkey-wallets) +- Production UX checklist: [Transaction UX Checklist](#transaction-ux-checklist) + ## Recommended Dependencies > **Requires Node.js 20+** — the Stellar SDK dropped Node 18 support. @@ -31,17 +39,27 @@ const networkPassphrase = StellarSdk.Networks.TESTNET; // For Mainnet const server = new StellarSdk.Horizon.Server("https://horizon.stellar.org"); -const rpc = new StellarSdk.rpc.Server(process.env.NEXT_PUBLIC_STELLAR_MAINNET_RPC_URL || "https://mainnet.sorobanrpc.com"); +const mainnetRpcUrl = process.env.NEXT_PUBLIC_STELLAR_MAINNET_RPC_URL; +if (!mainnetRpcUrl) throw new Error("Missing NEXT_PUBLIC_STELLAR_MAINNET_RPC_URL"); +const rpc = new StellarSdk.rpc.Server(mainnetRpcUrl); // set from your chosen RPC provider const networkPassphrase = StellarSdk.Networks.PUBLIC; ``` ### Environment Configuration +> Use a provider-specific mainnet RPC URL (see: https://developers.stellar.org/docs/data/apis/rpc/providers). + ```typescript // lib/stellar.ts import * as StellarSdk from "@stellar/stellar-sdk"; const NETWORK = process.env.NEXT_PUBLIC_STELLAR_NETWORK || "testnet"; +const requireEnv = (name: string): string => { + const value = process.env[name]; + if (!value) throw new Error(`Missing required env var: ${name}`); + return value; +}; + export const config = { testnet: { horizonUrl: "https://horizon-testnet.stellar.org", @@ -51,7 +69,7 @@ export const config = { }, mainnet: { horizonUrl: "https://horizon.stellar.org", - rpcUrl: process.env.NEXT_PUBLIC_STELLAR_MAINNET_RPC_URL || "https://mainnet.sorobanrpc.com", + rpcUrl: requireEnv("NEXT_PUBLIC_STELLAR_MAINNET_RPC_URL"), networkPassphrase: StellarSdk.Networks.PUBLIC, friendbotUrl: null, }, diff --git a/skill/resources.md b/skill/resources.md index cfbb428..7287c90 100644 --- a/skill/resources.md +++ b/skill/resources.md @@ -13,7 +13,7 @@ ### 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 (deprecated) +- [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 @@ -22,7 +22,7 @@ - [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 (migrated from `stellar/go` Dec 2025) +- [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) @@ -109,17 +109,19 @@ For vulnerability patterns, checklists, and detailed tooling guides, see [securi - [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 (Protocol 25 X-Ray) +## 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 -- [X-Ray Announcement](https://stellar.org/blog/developers/announcing-stellar-x-ray-protocol-25) - Protocol 25 overview -- [CAP-0074](https://github.com/stellar/stellar-protocol/blob/master/core/cap-0074.md) - BN254 elliptic curve specification -- [CAP-0075](https://github.com/stellar/stellar-protocol/blob/master/core/cap-0075.md) - Poseidon hash function specification +- [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](https://docs.rs/soroban-sdk/latest/soroban_sdk/crypto/bn254/) - BN254 types and functions +- [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 @@ -261,7 +263,7 @@ For comprehensive ZK development guidance, see [zk-proofs.md](zk-proofs.md). ### Major Stablecoins - [USDC on Stellar](https://www.circle.com/usdc/stellar) - Circle - [EURC on Stellar](https://www.circle.com/en/eurc) - Circle -- PYUSD (PayPal) - Launched Q3 2025 +- PYUSD (PayPal) - Verify current issuer/distribution details before integration ### Asset Discovery - [StellarExpert Asset Directory](https://stellar.expert/explorer/public/asset) @@ -301,4 +303,4 @@ See [ecosystem.md](ecosystem.md) for a table of teams shipping production code o ### Foundation - [Stellar Development Foundation](https://stellar.org/foundation) - [Foundation Roadmap](https://stellar.org/foundation/roadmap) -- [2025 Year in Review](https://stellar.org/blog/ecosystem/stellar-2025-year-in-review) +- [Ecosystem Blog](https://stellar.org/blog/ecosystem) diff --git a/skill/testing.md b/skill/testing.md index ccbb606..e35175d 100644 --- a/skill/testing.md +++ b/skill/testing.md @@ -1,5 +1,12 @@ # 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 diff --git a/skill/zk-proofs.md b/skill/zk-proofs.md index 74807a3..11fde63 100644 --- a/skill/zk-proofs.md +++ b/skill/zk-proofs.md @@ -1,512 +1,136 @@ -# Zero-Knowledge Proofs on Stellar (Protocol 25 X-Ray) - -Protocol 25 "X-Ray" (Mainnet January 22, 2026) introduced native ZK cryptographic primitives, enabling privacy-preserving applications on Stellar. - -## When to Use ZK on Stellar - -- **On-chain proof verification** — Verify zk-SNARK proofs (Groth16, PLONK, UltraHonk) -- **Privacy pools** — Prove lawful source of funds without revealing transaction history -- **Confidential tokens** — Hidden balances with validity proofs -- **ZK Merkle trees** — Efficient membership proofs using Poseidon hashes -- **Cross-chain bridges** — Verify state proofs from other chains -- **Compliance-forward privacy** — KYC/AML compliance with minimal data exposure - -## Prerequisites - -```toml -# Cargo.toml -[dependencies] -soroban-sdk = "25.0.1" -``` - -Ensure your Stellar CLI and network target Protocol 25+. - ---- - -## Core Primitives - -### BN254 Elliptic Curve (CAP-0074) - -BN254 (alt_bn128) is a pairing-friendly curve matching Ethereum's EIP-196/EIP-197 precompiles. This enables migration of existing EVM ZK applications. - -#### Types - -```rust -use soroban_sdk::crypto::bn254::{Fr, G1Affine, G2Affine}; -``` - -| Type | Size | Description | -|------|------|-------------| -| `Fr` | 32 bytes | Scalar field element (converts to/from U256) | -| `G1Affine` | 64 bytes | G1 point (x, y coordinates) | -| `G2Affine` | 128 bytes | G2 point (extension field coordinates) | - -#### Operations - -BN254 uses **operator overloading** for point arithmetic: - -```rust -use soroban_sdk::{contract, contractimpl, Env, BytesN, U256, Vec}; -use soroban_sdk::crypto::bn254::{Fr, G1Affine, G2Affine}; - -#[contract] -pub struct Bn254Example; - -#[contractimpl] -impl Bn254Example { - /// Add two G1 points - pub fn g1_add(a: BytesN<64>, b: BytesN<64>) -> BytesN<64> { - let a = G1Affine::from_bytes(a); - let b = G1Affine::from_bytes(b); - (a + b).to_bytes() // Use + operator - } - - /// Scalar multiplication - pub fn g1_mul(p: BytesN<64>, s: U256) -> BytesN<64> { - let p = G1Affine::from_bytes(p); - let s = Fr::from(s); - (p * s).to_bytes() // Use * operator - } - - /// Multi-pairing check (core of zk-SNARK verification) - /// Returns true if: e(g1[0], g2[0]) × e(g1[1], g2[1]) × ... = 1 - pub fn verify_pairing(env: Env, g1_bytes: Vec>, g2_bytes: Vec>) -> bool { - let mut g1_points = Vec::new(&env); - for bytes in g1_bytes.iter() { - g1_points.push_back(G1Affine::from_bytes(bytes)); - } - - let mut g2_points = Vec::new(&env); - for bytes in g2_bytes.iter() { - g2_points.push_back(G2Affine::from_bytes(bytes)); - } - - env.crypto().bn254().pairing_check(g1_points, g2_points) - } -} -``` - -#### Encoding Format - -Points use **uncompressed big-endian** encoding (no flag bits): - -- **G1**: 64 bytes — `be_encode(X) || be_encode(Y)` -- **G2**: 128 bytes — `be_encode(X_c1) || be_encode(X_c0) || be_encode(Y_c1) || be_encode(Y_c0)` -- **Point at infinity**: All zeros -- **Fr (scalar)**: U256 / 32 bytes - ---- - -### Poseidon Hash Functions (CAP-0075) - -Poseidon is optimized for ZK circuits — ~300 constraints vs ~27,000 for SHA-256. Essential for efficient Merkle trees and commitments in ZK applications. - -#### API - -```rust -use soroban_sdk::{contract, contractimpl, Env, Symbol, U256, Vec}; - -#[contract] -pub struct PoseidonExample; - -#[contractimpl] -impl PoseidonExample { - /// Poseidon hash over BN254 scalar field - pub fn poseidon(env: Env, inputs: Vec) -> U256 { - let field = Symbol::new(&env, "BN254"); - env.crypto().poseidon_hash(&inputs, field) - } - - /// Poseidon2 hash (optimized variant) - pub fn poseidon2(env: Env, inputs: Vec) -> U256 { - let field = Symbol::new(&env, "BN254"); - env.crypto().poseidon2_hash(&inputs, field) - } -} -``` - -#### Supported Fields - -| Field Symbol | Curve | -|--------------|-------| -| `"BN254"` | BN254 scalar field | -| `"BLS12_381"` | BLS12-381 scalar field | - -#### CLI Example - -```bash -# Hash two field elements [3, 4] -stellar contract invoke --id poseidon --network futurenet -- poseidon \ - --inputs '["3", "4"]' - -# Output: "14763215145315200506921711489642608356394854266165572616578112107564877678998" -``` - ---- - -## Groth16 Verification Pattern - -Groth16 is the most common zk-SNARK proof system. Verification uses the pairing equation: - -``` -e(A, B) = e(α, β) × e(L, γ) × e(C, δ) -``` - -Where: -- `(A, B, C)` = proof elements -- `(α, β, γ, δ)` = verification key -- `L` = linear combination of public inputs - -### Verification Contract Structure - -```rust -use soroban_sdk::{contract, contractimpl, contracttype, contracterror, Env, Vec, BytesN, U256}; -use soroban_sdk::crypto::bn254::{Fr, G1Affine, G2Affine}; - -#[contracterror] -#[derive(Copy, Clone, Debug, Eq, PartialEq)] -#[repr(u32)] -pub enum ZkError { - InvalidVerifyingKey = 1, - InvalidPublicInputs = 2, -} - -#[derive(Clone)] -#[contracttype] -pub struct VerifyingKey { - pub alpha_g1: BytesN<64>, - pub beta_g2: BytesN<128>, - pub gamma_g2: BytesN<128>, - pub delta_g2: BytesN<128>, - pub ic: Vec>, // Input commitments -} - -#[derive(Clone)] -#[contracttype] -pub struct Proof { - pub a: BytesN<64>, - pub b: BytesN<128>, - pub c: BytesN<64>, -} - -#[contract] -pub struct Groth16Verifier; - -#[contractimpl] -impl Groth16Verifier { - /// Verify a Groth16 proof with public inputs - pub fn verify( - env: Env, - vk: VerifyingKey, - proof: Proof, - public_inputs: Vec, - ) -> Result { - // Compute vk_x = ic[0] + sum(public_inputs[i] * ic[i+1]) - let mut vk_x = G1Affine::from_bytes( - vk.ic.get(0).ok_or(ZkError::InvalidVerifyingKey)? - ); - - for i in 0..public_inputs.len() { - let ic_i = G1Affine::from_bytes( - vk.ic.get(i + 1).ok_or(ZkError::InvalidVerifyingKey)? - ); - let input_i = Fr::from( - public_inputs.get(i).ok_or(ZkError::InvalidPublicInputs)? - ); - let term = ic_i * input_i; - vk_x = vk_x + term; - } - - // Negate proof.a for the pairing equation - let proof_a = G1Affine::from_bytes(proof.a); - let neg_a = -proof_a; - - // Build point vectors for pairing check - let g1_points = Vec::from_array(&env, [ - neg_a, - G1Affine::from_bytes(vk.alpha_g1), - vk_x, - G1Affine::from_bytes(proof.c), - ]); - - let g2_points = Vec::from_array(&env, [ - G2Affine::from_bytes(proof.b), - G2Affine::from_bytes(vk.beta_g2), - G2Affine::from_bytes(vk.gamma_g2), - G2Affine::from_bytes(vk.delta_g2), - ]); - - // Pairing check: e(-A, B) * e(alpha, beta) * e(vk_x, gamma) * e(C, delta) = 1 - Ok(env.crypto().bn254().pairing_check(g1_points, g2_points)) - } -} -``` - -> **Note**: The official `groth16_verifier` example in soroban-examples uses BLS12-381. The pattern above adapts it for BN254 (Ethereum-compatible). - ---- - -## ZK Development Workflow - -### 1. Write the Circuit (Off-chain) - -Choose a proving system and write your circuit logic: - -**Noir (Aztec)** — Domain-specific language for ZK: -```noir -// circuit.nr -fn main(x: Field, y: pub Field) { - assert(x * x == y); -} -``` - -**RISC Zero** — Write in Rust, prove any computation: -```rust -// guest/src/main.rs -#![no_main] -risc0_zkvm::guest::entry!(main); - -fn main() { - let input: u64 = risc0_zkvm::guest::env::read(); - let result = expensive_computation(input); - risc0_zkvm::guest::env::commit(&result); -} -``` - -### 2. Generate Proofs (Off-chain) - -Compile the circuit and generate proofs using the respective toolchain: - -```bash -# Noir -nargo compile -nargo prove - -# RISC Zero -cargo risczero build -cargo run --release -``` - -### 3. Deploy Verifier Contract (On-chain) - -Deploy a Soroban contract that verifies the proofs using BN254 primitives. - -### 4. Verify Proofs (On-chain) - -Submit proofs to your verifier contract for on-chain verification. - ---- - -## Multi-Scalar Multiplication (MSM) - -Soroban doesn't provide native MSM. Implement using operator overloading: - -```rust -use soroban_sdk::{Vec, BytesN, U256}; -use soroban_sdk::crypto::bn254::{Fr, G1Affine}; - -#[derive(Copy, Clone, Debug, Eq, PartialEq)] -pub enum MsmError { EmptyInput, LengthMismatch } - -/// Compute sum of scalar[i] * point[i] -pub fn g1_msm( - scalars: &Vec, - points: &Vec>, -) -> Result { - if scalars.len() != points.len() { return Err(MsmError::LengthMismatch); } - if scalars.is_empty() { return Err(MsmError::EmptyInput); } - - // Start with first term - let first_point = points.get(0).ok_or(MsmError::LengthMismatch)?; - let first_scalar = scalars.get(0).ok_or(MsmError::LengthMismatch)?; - let mut result = G1Affine::from_bytes(first_point) * Fr::from(first_scalar); - - for i in 1..scalars.len() { - let scalar_u256 = scalars.get(i).ok_or(MsmError::LengthMismatch)?; - let point_bytes = points.get(i).ok_or(MsmError::LengthMismatch)?; - let scalar = Fr::from(scalar_u256); - let point = G1Affine::from_bytes(point_bytes); - let term = point * scalar; - result = result + term; - } - - Ok(result) -} -``` - ---- - -## ZK Merkle Tree with Poseidon - -```rust -use soroban_sdk::{Env, Vec, U256, Symbol}; - -#[derive(Copy, Clone, Debug, Eq, PartialEq)] -pub enum MerkleError { LengthMismatch, InvalidProof } - -/// Verify a Merkle proof using Poseidon hash -pub fn verify_merkle_proof( - env: &Env, - leaf: U256, - proof: Vec, - path_indices: Vec, // true = right, false = left - root: U256, -) -> Result { - if proof.len() != path_indices.len() { return Err(MerkleError::LengthMismatch); } - - let field = Symbol::new(env, "BN254"); - let mut current = leaf; - - for i in 0..proof.len() { - let sibling = proof.get(i).ok_or(MerkleError::InvalidProof)?; - let is_right = path_indices.get(i).ok_or(MerkleError::InvalidProof)?; - - // Hash pair in correct order - let inputs = if is_right { - Vec::from_array(env, [sibling, current]) - } else { - Vec::from_array(env, [current, sibling]) - }; - - current = env.crypto().poseidon_hash(&inputs, field.clone()); - } - - Ok(current == root) -} -``` - ---- - -## Security Considerations - -### Proof Verification - -- **Validate all inputs** — Malformed G1/G2 points will cause host function traps -- **Check proof freshness** — Prevent replay attacks with nullifiers or nonces -- **Verify public inputs** — Don't trust client-provided public input commitments - -### Encoding Errors - -Host functions trap on: -- G1 point byte length ≠ 64 -- G2 point byte length ≠ 128 -- Point not on curve -- G2 point not in correct subgroup -- Mismatched vector lengths in pairing_check - -### Privacy Pool Patterns - -```rust -use soroban_sdk::{contracttype, Env, U256}; - -#[contracttype] -pub enum DataKey { - Nullifier(U256), -} - -// Use nullifiers to prevent double-spending -pub fn withdraw( - env: Env, - proof: Proof, - nullifier_hash: U256, - // ... other params -) { - // Check nullifier hasn't been used - if env.storage().persistent().has(&DataKey::Nullifier(nullifier_hash)) { - panic!("nullifier already used"); - } - - // Verify the ZK proof - if !verify_proof(&env, &proof) { - panic!("invalid proof"); - } - - // Mark nullifier as used - env.storage().persistent().set(&DataKey::Nullifier(nullifier_hash), &true); - - // Process withdrawal... -} -``` - ---- - -## Testing ZK Contracts - -### Unit Tests - -```rust -#[cfg(test)] -mod tests { - use super::*; - use soroban_sdk::Env; - - #[test] - fn test_poseidon_hash() { - let env = Env::default(); - let field = Symbol::new(&env, "BN254"); - - let inputs = Vec::from_array(&env, [U256::from_u32(&env, 1), U256::from_u32(&env, 2)]); - let hash = env.crypto().poseidon_hash(&inputs, field); - - // Expected: 7853200120776062878684798364095072458815029376092732009249414926327459813530 - assert!(hash != U256::from_u32(&env, 0)); - } - - #[test] - fn test_pairing_check() { - let env = Env::default(); - - // TODO: Add test vectors from your proving system - // let g1_points = Vec::from_array(&env, [/* G1 points */]); - // let g2_points = Vec::from_array(&env, [/* G2 points */]); - // let result = env.crypto().bn254().pairing_check(g1_points, g2_points); - // assert!(result); - } -} -``` - -### Integration Tests - -1. Generate real proofs using your off-chain prover -2. Deploy verifier to Futurenet or Testnet -3. Submit proofs via Stellar CLI or SDK -4. Verify correct acceptance/rejection - -```bash -# Deploy verifier -stellar contract deploy \ - --wasm target/wasm32v1-none/release/verifier.optimized.wasm \ - --alias verifier \ - --network futurenet - -# Invoke with proof data -stellar contract invoke --id verifier --network futurenet \ - -- verify --proof --public_inputs -``` - ---- - -## Examples & Resources - -### Official Resources -- [X-Ray Announcement](https://stellar.org/blog/developers/announcing-stellar-x-ray-protocol-25) — Protocol 25 overview -- [CAP-0074](https://github.com/stellar/stellar-protocol/blob/master/core/cap-0074.md) — BN254 specification -- [CAP-0075](https://github.com/stellar/stellar-protocol/blob/master/core/cap-0075.md) — Poseidon specification -- [Soroban SDK BN254 Source](https://github.com/stellar/rs-soroban-sdk/blob/v25.0.1/soroban-sdk/src/crypto/bn254.rs) — Implementation reference - -### Example Contracts -- [P25 Preview Examples](https://github.com/jayz22/soroban-examples/tree/p25-preview/p25-preview) — BN254 and Poseidon examples -- [Groth16 Verifier (BLS12-381)](https://github.com/stellar/soroban-examples/tree/main/groth16_verifier) — Official verifier example -- [Import Ark BN254](https://github.com/jayz22/soroban-examples/tree/p25-preview/import_ark_bn254) — Using ark-bn254 crate - -### Proving Systems -- [Noir Documentation](https://noir-lang.org/docs/) — Aztec's ZK DSL -- [RISC Zero](https://dev.risczero.com/) — General-purpose zkVM - -> **Note**: Protocol 25 launched January 22, 2026. Always verify SDK version compatibility (soroban-sdk v25+) when using examples. - ---- - -## Keywords -zero-knowledge, zk, zk-snark, groth16, plonk, bn254, alt_bn128, poseidon, poseidon2, pairing, elliptic curve, -privacy, confidential, merkle tree, nullifier, proof verification, noir, risc zero, x-ray, protocol 25 +# Zero-Knowledge Proofs on Stellar (Status-Sensitive) + +## When to use this guide +Use this guide when the user asks for: +- On-chain ZK proof verification patterns +- Privacy-preserving smart contract architecture +- BN254/Poseidon readiness planning +- Groth16 or PLONK integration strategy +- Cross-chain proof verification design + +This guide is intentionally status-aware. ZK capabilities on Stellar evolve with protocol and SDK releases. + +## Source-of-truth checks (required) +Before implementation, always verify: +1. CAP status in `stellar/stellar-protocol` (`Accepted`/`Implemented` vs draft/awaiting decision) +2. Target network protocol/software version +3. `soroban-sdk` support for required cryptographic host functions +4. Availability of production examples matching your proving system + +Primary references: +- [CAP-0059](https://github.com/stellar/stellar-protocol/blob/master/core/cap-0059.md) (BLS12-381) +- [CAP-0074](https://github.com/stellar/stellar-protocol/blob/master/core/cap-0074.md) (BN254 proposal) +- [CAP-0075](https://github.com/stellar/stellar-protocol/blob/master/core/cap-0075.md) (Poseidon/Poseidon2 proposal) +- [Stellar protocol/software versions](https://developers.stellar.org/docs/networks/software-versions) +- [RPC providers](https://developers.stellar.org/docs/data/apis/rpc/providers) + +## Capability model +Treat advanced cryptography as capability-gated: +- Capability A: proof verification primitive support +- Capability B: hash primitive support +- Capability C: SDK ergonomics and bindings +- Capability D: operational cost envelope + +Do not assume all capabilities are present on all networks/environments. + +## Architecture patterns + +### 1) Verification gateway +Use a dedicated verifier contract (or module) for cryptographic checks: +- Normalize and validate inputs +- Enforce domain separation for statements +- Verify proof +- Emit explicit success/failure events + +Benefits: +- Smaller audit surface +- Easier upgrades/migrations +- Cleaner operational telemetry + +### 2) Policy-and-proof split +Separate concerns: +- `Verifier`: cryptographic validity only +- `Policy`: business/risk/compliance logic +- `Application`: state transition after verifier + policy pass + +Benefits: +- Better testability +- Safer upgrades +- Clearer incident response + +### 3) Feature flags and graceful fallback +Gate advanced paths by environment support: +- Enable ZK flows only where required primitives are verified available +- Keep deterministic fallback behavior for unsupported environments +- Document supported network/protocol matrix in deployment notes + +## Integration checklist +- [ ] Target network supports required primitives +- [ ] SDK pin supports required APIs +- [ ] Proof statement includes anti-replay binding (nonce/context) +- [ ] Full simulation path is covered (proof + policy + state transition) +- [ ] Negative-path tests exist for malformed/tampered inputs +- [ ] Resource budget checks are documented for realistic proof sizes +- [ ] Security review documents all cryptographic assumptions + +## Common pitfalls + +### Over-trusting proof payload shape +A payload that parses is not equivalent to a valid statement for your application. + +Mitigation: +- Validate public-input semantics and statement domain explicitly. + +### Missing anti-replay controls +Valid proofs can be replayed without context binding. + +Mitigation: +- Bind proofs to session/nonce/action scope and persist replay guards. + +### Monolithic contract design +Combining verifier, policy, and state logic increases audit complexity. + +Mitigation: +- Keep verifier logic isolated and narrow. + +### Hardcoded protocol assumptions +Assuming primitive availability across all networks causes runtime failures. + +Mitigation: +- Capability-gate and verify at deployment time. + +## Testing strategy + +### Unit tests +- Input domain validation +- Replay protection behavior +- Event correctness + +### Integration tests +- End-to-end proof submission flow +- Negative cases: tampered input, stale nonce, unsupported feature path +- Network-configuration differences (local/testnet/mainnet) + +### Operational tests +- Cost/resource envelope under realistic proof sizes +- Load behavior on verifier hot paths +- Upgrade/migration safety tests for verifier changes + +## Security review focus +- Authorization and anti-replay guarantees +- Statement domain separation +- Upgrade controls around verifier/policy modules +- Denial-of-service resistance and bounded workloads +- Event/log coverage for forensic traceability + +## 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) + +## What not to do +- Do not claim specific primitives are production-ready without checking CAP status and network support. +- Do not hardcode draft-spec behavior as guaranteed runtime behavior. +- Do not skip simulation and negative-path testing for verifier flows. From cac8ceece67313297b550cf0bd2b7cf55da5ec23 Mon Sep 17 00:00:00 2001 From: kalepail Date: Fri, 6 Feb 2026 14:03:42 -0500 Subject: [PATCH 3/3] Address PR #4 review comments on RPC docs/examples Implements valid Copilot feedback: (1) fix duplicate const declarations in frontend basic setup snippet, (2) add explicit linked RPC providers directory references in API docs. Retains prior status-safe provider policy and env-var requirement for mainnet RPC. --- skill/api-rpc-horizon.md | 6 +++--- skill/frontend-stellar-sdk.md | 12 ++++++------ 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/skill/api-rpc-horizon.md b/skill/api-rpc-horizon.md index 91acac7..b4d72bf 100644 --- a/skill/api-rpc-horizon.md +++ b/skill/api-rpc-horizon.md @@ -22,11 +22,11 @@ Stellar provides two API paradigms: ### Endpoints -> Note: SDF directly provides Futurenet public RPC. For Mainnet RPC, select a provider from the RPC providers directory. +> Note: SDF directly provides Futurenet public RPC. For Mainnet RPC, select a provider from the [RPC providers directory](https://developers.stellar.org/docs/data/apis/rpc/providers). | Network | RPC URL | |---------|---------| -| Mainnet | Provider-specific endpoint (see RPC providers doc) | +| Mainnet | Provider-specific endpoint (see [RPC providers directory](https://developers.stellar.org/docs/data/apis/rpc/providers)) | | Testnet | `https://soroban-testnet.stellar.org` | | Futurenet | `https://rpc-futurenet.stellar.org` | | Local | `http://localhost:8000/soroban/rpc` | @@ -403,7 +403,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 mainnet RPC, set `STELLAR_MAINNET_RPC_URL` from a provider in the RPC providers directory. +> 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/skill/frontend-stellar-sdk.md b/skill/frontend-stellar-sdk.md index 665e69e..a112fca 100644 --- a/skill/frontend-stellar-sdk.md +++ b/skill/frontend-stellar-sdk.md @@ -33,16 +33,16 @@ npm install @stellar/stellar-sdk @creit.tech/stellar-wallets-kit import * as StellarSdk from "@stellar/stellar-sdk"; // For Testnet -const server = new StellarSdk.Horizon.Server("https://horizon-testnet.stellar.org"); -const rpc = new StellarSdk.rpc.Server("https://soroban-testnet.stellar.org"); -const networkPassphrase = StellarSdk.Networks.TESTNET; +const testnetServer = new StellarSdk.Horizon.Server("https://horizon-testnet.stellar.org"); +const testnetRpc = new StellarSdk.rpc.Server("https://soroban-testnet.stellar.org"); +const testnetNetworkPassphrase = StellarSdk.Networks.TESTNET; // For Mainnet -const server = new StellarSdk.Horizon.Server("https://horizon.stellar.org"); +const mainnetServer = new StellarSdk.Horizon.Server("https://horizon.stellar.org"); const mainnetRpcUrl = process.env.NEXT_PUBLIC_STELLAR_MAINNET_RPC_URL; if (!mainnetRpcUrl) throw new Error("Missing NEXT_PUBLIC_STELLAR_MAINNET_RPC_URL"); -const rpc = new StellarSdk.rpc.Server(mainnetRpcUrl); // set from your chosen RPC provider -const networkPassphrase = StellarSdk.Networks.PUBLIC; +const mainnetRpc = new StellarSdk.rpc.Server(mainnetRpcUrl); // set from your chosen RPC provider +const mainnetNetworkPassphrase = StellarSdk.Networks.PUBLIC; ``` ### Environment Configuration