From 3674852e21ea0fd876a4c6fd1dc092ca7fe08fd4 Mon Sep 17 00:00:00 2001 From: oceans404 Date: Mon, 6 Jul 2026 12:13:45 -0700 Subject: [PATCH 1/3] Fix example code bugs, stale link labels, and duplicated reference content across six skills --- skills/assets/SKILL.md | 19 +---- skills/dapp/SKILL.md | 40 ++++++---- skills/data/SKILL.md | 22 +++--- skills/smart-contracts/development.md | 2 +- skills/smart-contracts/testing.md | 2 +- skills/standards/SKILL.md | 105 ++++---------------------- 6 files changed, 60 insertions(+), 130 deletions(-) diff --git a/skills/assets/SKILL.md b/skills/assets/SKILL.md index a130ddb..c16eb64 100644 --- a/skills/assets/SKILL.md +++ b/skills/assets/SKILL.md @@ -406,30 +406,19 @@ image = "https://example.com/token-logo.png" ### SEP-0010 (Web Authentication) -Authenticate users with their Stellar accounts: - -```typescript -// Server generates challenge -// Client signs with wallet -// Server verifies signature -``` +Authenticate users with their Stellar accounts. Flow: the server generates a challenge transaction, the client signs it with their wallet, and the server verifies the signature. See [SEP-0010](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0010.md). ### SEP-0024 (Hosted Deposit/Withdrawal) -For fiat on/off ramps: - -```typescript -// Interactive flow for deposits/withdrawals -// Anchor handles KYC and fiat transfer -``` +For fiat on/off ramps: an interactive webview flow where the anchor handles KYC and the fiat transfer. See [SEP-0024](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0024.md). ### SEP-0045 (Web Auth for Contract Accounts) -Extends SEP-10 to support contract accounts (`C...` addresses) for web authentication. Required for smart wallet / passkey-based anchor integrations. See [SEP-0045](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0045.md). +Extends SEP-10 to support contract accounts (`C...` addresses) for web authentication. Required for smart wallet / passkey-based anchor integrations. Draft status; verify current status in [SEP-0045](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0045.md). ### SEP-0050 (Non-Fungible Tokens) -Standard contract interface for NFTs on Stellar. Reference implementations available in [OpenZeppelin Stellar Contracts](https://github.com/OpenZeppelin/stellar-contracts) with Base, Consecutive, and Enumerable variants. See [SEP-0050](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0050.md). +Standard contract interface for NFTs on Stellar. Reference implementations available in [OpenZeppelin Stellar Contracts](https://github.com/OpenZeppelin/stellar-contracts) with Base, Consecutive, and Enumerable variants. Draft status; verify current status in [SEP-0050](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0050.md). ## Best Practices diff --git a/skills/dapp/SKILL.md b/skills/dapp/SKILL.md index 0de7ec2..f6c0eed 100644 --- a/skills/dapp/SKILL.md +++ b/skills/dapp/SKILL.md @@ -52,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](../data/SKILL.md). +> For the full API reference (RPC methods, Horizon endpoints, migration guide), see the [data skill](../data/SKILL.md). ### Basic Setup ```typescript @@ -86,20 +86,29 @@ const requireEnv = (name: string): string => { return value; }; -export const config = { - testnet: { - horizonUrl: "https://horizon-testnet.stellar.org", - rpcUrl: "https://soroban-testnet.stellar.org", - networkPassphrase: StellarSdk.Networks.TESTNET, - friendbotUrl: "https://friendbot.stellar.org", - }, - mainnet: { - horizonUrl: "https://horizon.stellar.org", - rpcUrl: requireEnv("NEXT_PUBLIC_STELLAR_MAINNET_RPC_URL"), - networkPassphrase: StellarSdk.Networks.PUBLIC, - friendbotUrl: null, - }, -}[NETWORK]!; +function getConfig(network: string) { + switch (network) { + case "testnet": + return { + horizonUrl: "https://horizon-testnet.stellar.org", + rpcUrl: "https://soroban-testnet.stellar.org", + networkPassphrase: StellarSdk.Networks.TESTNET, + friendbotUrl: "https://friendbot.stellar.org" as string | null, + }; + case "mainnet": + return { + horizonUrl: "https://horizon.stellar.org", + // Resolved lazily so testnet runs don't require the mainnet env var + rpcUrl: requireEnv("NEXT_PUBLIC_STELLAR_MAINNET_RPC_URL"), + networkPassphrase: StellarSdk.Networks.PUBLIC, + friendbotUrl: null, + }; + default: + throw new Error(`Unknown network: ${network}`); + } +} + +export const config = getConfig(NETWORK); export const horizon = new StellarSdk.Horizon.Server(config.horizonUrl); export const rpc = new StellarSdk.rpc.Server(config.rpcUrl); @@ -441,6 +450,7 @@ export function ConnectButton() { import { useState } from "react"; import { useFreighter } from "@/hooks/useFreighter"; import { buildPaymentTx, submitTransaction } from "@/lib/transactions"; +import { config } from "@/lib/stellar"; export function SendPayment() { const { address, sign } = useFreighter(); diff --git a/skills/data/SKILL.md b/skills/data/SKILL.md index 1fb81b5..3d5c08d 100644 --- a/skills/data/SKILL.md +++ b/skills/data/SKILL.md @@ -427,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](../dapp/SKILL.md). +> For a React/Next.js-specific setup, see the [dapp skill](../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 @@ -449,29 +449,33 @@ const requireEnv = (name: string): string => { return value; }; -const configs: Record = { - mainnet: { +// Lazy per-network factories: requireEnv only runs for the selected network, +// so testnet/local work without the mainnet env var set. +const configs: Record NetworkConfig> = { + mainnet: () => ({ rpcUrl: requireEnv("STELLAR_MAINNET_RPC_URL"), horizonUrl: "https://horizon.stellar.org", networkPassphrase: StellarSdk.Networks.PUBLIC, friendbotUrl: null, - }, - testnet: { + }), + testnet: () => ({ rpcUrl: "https://soroban-testnet.stellar.org", horizonUrl: "https://horizon-testnet.stellar.org", networkPassphrase: StellarSdk.Networks.TESTNET, friendbotUrl: "https://friendbot.stellar.org", - }, - local: { + }), + local: () => ({ rpcUrl: "http://localhost:8000/soroban/rpc", horizonUrl: "http://localhost:8000", networkPassphrase: "Standalone Network ; February 2017", friendbotUrl: "http://localhost:8000/friendbot", - }, + }), }; const network = process.env.STELLAR_NETWORK || "testnet"; -export const config = configs[network]; +const makeConfig = configs[network]; +if (!makeConfig) throw new Error(`Unknown network: ${network}`); +export const config = makeConfig(); export const rpc = new StellarSdk.rpc.Server(config.rpcUrl); export const horizon = new StellarSdk.Horizon.Server(config.horizonUrl); diff --git a/skills/smart-contracts/development.md b/skills/smart-contracts/development.md index 9863553..30923a2 100644 --- a/skills/smart-contracts/development.md +++ b/skills/smart-contracts/development.md @@ -58,7 +58,7 @@ pub enum DataKey { ## Data types ```rust -use soroban_sdk::{Address, Bytes, BytesN, Map, String, Symbol, Vec}; +use soroban_sdk::{symbol_short, vec, Address, Bytes, BytesN, Map, String, Symbol, Vec}; let addr: Address = env.current_contract_address(); let sym: Symbol = symbol_short!("transfer"); // ≤9 chars; Symbol max is 32 diff --git a/skills/smart-contracts/testing.md b/skills/smart-contracts/testing.md index a11f832..f11e9a8 100644 --- a/skills/smart-contracts/testing.md +++ b/skills/smart-contracts/testing.md @@ -15,7 +15,7 @@ Layers, fastest first: #![cfg(test)] use soroban_sdk::{ testutils::{Address as _, MockAuth, MockAuthInvoke}, - Address, Env, + Address, Env, IntoVal, }; use crate::{Contract, ContractClient}; diff --git a/skills/standards/SKILL.md b/skills/standards/SKILL.md index 133de57..e60929f 100644 --- a/skills/standards/SKILL.md +++ b/skills/standards/SKILL.md @@ -315,41 +315,13 @@ Audited smart contract library for Stellar (track latest release tags before pin ### Security Tools -#### Scout Soroban (CoinFabrik) -Open-source vulnerability detector with 23 detectors for Stellar smart 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 Stellar contracts. -- **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 Stellar smart contracts — 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 Stellar smart contracts (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 the 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 +Usage details, detector lists, and workflow guidance live in [the smart contract security guide](../smart-contracts/security.md#tooling). Catalog: + +- [Scout Soroban](https://github.com/CoinFabrik/scout-soroban) (CoinFabrik) - static analysis, 23 detectors, VSCode extension, SARIF output ([examples](https://github.com/CoinFabrik/scout-soroban-examples)) +- [Security Detectors SDK](https://github.com/OpenZeppelin/soroban-security-detectors-sdk) (OpenZeppelin) - pre-built detectors plus a framework for custom ones +- [Certora Sunbeam Prover](https://docs.certora.com/en/latest/docs/sunbeam/index.html) - formal verification at WASM level, CVLR spec language ([Blend V1 report](https://www.certora.com/reports/blend-smart-contract-verification-report)) +- [Komet](https://docs.runtimeverification.com/komet) (Runtime Verification) - property testing and formal verification via KWasm semantics ([reports](https://github.com/runtimeverification/publications)) +- [Soroban Security Portal](https://sorobansecurity.com) (Inferara) - searchable audit reports and vulnerability database ### CLI & SDKs @@ -622,54 +594,26 @@ Major companies building on Stellar: ## 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 +Official and community example repos are cataloged in Part 2: Example Repositories above. See also [Stellar Repositories](https://github.com/orgs/stellar/repositories) for everything under the stellar org. ## Ecosystem Projects -For DeFi protocols, wallets, oracles, gaming/NFTs, cross-chain bridges, and builder teams, see Part 2: Stellar Ecosystem below. +For DeFi protocols, wallets, oracles, gaming/NFTs, cross-chain bridges, and builder teams, see Part 2: Stellar Ecosystem above. ## Security -For vulnerability patterns, checklists, and detailed tooling guides, see [the smart contract security guide](../smart-contracts/security.md). +Vulnerability patterns, checklists, tooling (static analysis, formal verification, monitoring), the Audit Bank, and the Immunefi bounty programs are covered in [the smart contract security guide](../smart-contracts/security.md). The Security Tools catalog in Part 2 above lists the tool links. -### Bug Bounty Programs -- [Stellar Bug Bounty (Immunefi)](https://immunefi.com/bug-bounty/stellar/) - Up to $250K, covers core + smart contract stack -- [OpenZeppelin Stellar Bounty (Immunefi)](https://immunefi.com/bug-bounty/openzeppelin-stellar/) - Up to $25K +Additional resources not covered there: - [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) - contract verification tool - -### Security Resources - [Veridise Security Checklist](https://veridise.com/blog/audit-insights/building-on-stellar-soroban-grab-this-security-checklist-to-avoid-vulnerabilities/) - smart-contract security checklist -- [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). +For comprehensive ZK development guidance, see the [zk-proofs skill](../zk-proofs/SKILL.md). Always verify CAP status and network support before treating any ZK primitive as production-available. @@ -721,10 +665,8 @@ Always verify CAP status and network support before treating any ZK primitive as - [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 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 + +Mercury, SubQuery, Goldsky, and Zephyr VM are cataloged with docs links in Part 2: Data Indexing above. Full directory: [Indexer Directory](https://developers.stellar.org/docs/data/indexers). ### Historical Data & Analytics - [Hubble](https://developers.stellar.org/docs/data/analytics/hubble) - BigQuery dataset (updated every 30 min) @@ -733,15 +675,7 @@ Always verify CAP status and network support before treating any ZK primitive as ## 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) +Anchors, on/off ramps, and the Stellar Disbursement Platform are cataloged in Part 2: Infrastructure above. See also the [Anchor Platform docs](https://developers.stellar.org/docs/category/anchor-platform). ### RPC Providers - [RPC Provider Directory](https://developers.stellar.org/docs/data/apis/rpc/providers) - Full list of providers @@ -779,14 +713,7 @@ Always verify CAP status and network support before treating any ZK primitive as ## 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) +Directories (Stellar Ecosystem, SCF Project Tracker) and funding programs (SCF, Audit Bank) are cataloged in Part 2: Project Directories above. See also the [$100M Soroban Adoption Fund](https://stellar.org/soroban). ## Learning Resources From 6f2df4c33df0f61bc180094b6ad8789d6ff08934 Mon Sep 17 00:00:00 2001 From: oceans404 Date: Mon, 6 Jul 2026 12:21:41 -0700 Subject: [PATCH 2/3] Remove time-sensitive phrasing and align Scout detector count with security.md --- skills/agentic-payments/SKILL.md | 2 +- skills/standards/SKILL.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/skills/agentic-payments/SKILL.md b/skills/agentic-payments/SKILL.md index 2a90150..5c2c8cc 100644 --- a/skills/agentic-payments/SKILL.md +++ b/skills/agentic-payments/SKILL.md @@ -347,7 +347,7 @@ Always test on testnet first. To switch a working setup to mainnet, change only **OZ Channels 401 on testnet or mainnet** - Symptom: facilitator rejects with 401, server logs `Failed to initialize: no supported payment kinds loaded from any facilitator` -- Fix: an API key is required on **both** networks (this is a recent change). Generate one at [channels.openzeppelin.com/testnet/gen](https://channels.openzeppelin.com/testnet/gen) (testnet) or [channels.openzeppelin.com/gen](https://channels.openzeppelin.com/gen) (mainnet), then set `OZ_API_KEY` and pass it via `createAuthHeaders` (see the Seller example). +- Fix: an API key is required on **both** networks. Generate one at [channels.openzeppelin.com/testnet/gen](https://channels.openzeppelin.com/testnet/gen) (testnet) or [channels.openzeppelin.com/gen](https://channels.openzeppelin.com/gen) (mainnet), then set `OZ_API_KEY` and pass it via `createAuthHeaders` (see the Seller example). **Trustline missing on the recipient** - Symptom: `op_no_trust` during settlement, even though the client has USDC diff --git a/skills/standards/SKILL.md b/skills/standards/SKILL.md index e60929f..c5f6b26 100644 --- a/skills/standards/SKILL.md +++ b/skills/standards/SKILL.md @@ -317,7 +317,7 @@ Audited smart contract library for Stellar (track latest release tags before pin Usage details, detector lists, and workflow guidance live in [the smart contract security guide](../smart-contracts/security.md#tooling). Catalog: -- [Scout Soroban](https://github.com/CoinFabrik/scout-soroban) (CoinFabrik) - static analysis, 23 detectors, VSCode extension, SARIF output ([examples](https://github.com/CoinFabrik/scout-soroban-examples)) +- [Scout Soroban](https://github.com/CoinFabrik/scout-soroban) (CoinFabrik) - static analysis, 20+ detectors, VSCode extension, SARIF output ([examples](https://github.com/CoinFabrik/scout-soroban-examples)) - [Security Detectors SDK](https://github.com/OpenZeppelin/soroban-security-detectors-sdk) (OpenZeppelin) - pre-built detectors plus a framework for custom ones - [Certora Sunbeam Prover](https://docs.certora.com/en/latest/docs/sunbeam/index.html) - formal verification at WASM level, CVLR spec language ([Blend V1 report](https://www.certora.com/reports/blend-smart-contract-verification-report)) - [Komet](https://docs.runtimeverification.com/komet) (Runtime Verification) - property testing and formal verification via KWasm semantics ([reports](https://github.com/runtimeverification/publications)) From 503eb3217ea9b524a39d24f36dddce9bb71ca05b Mon Sep 17 00:00:00 2001 From: oceans404 Date: Mon, 6 Jul 2026 12:44:45 -0700 Subject: [PATCH 3/3] Update dapp skill to JS SDK v16 and lead contract calls with contract.Client Re-grounds the SDK-mechanics sections against the official JS SDK docs (stellar.github.io/js-stellar-sdk): - Node 20+ -> Node 22+; note stellar-base folded into stellar-sdk, ESM-first, native fetch (v16 migration). - Lead smart contract invocation with the typed contract.Client (Client.from -> method() -> signAndSend); demote the low-level Contract.call path to an advanced note using prepareTransaction. - Replace the unbounded getTransaction poll loop with rpc.pollTransaction. - Add rpc.queryContract / getContractMethods one-liners for reading contract state; keep manual getLedgerEntries as advanced. - Use the typed NotFoundError in the balance example and point to result codes for submission failures. - Add a sourcing note: SDK mechanics track the JS SDK docs; wallet, passkey, and relayer sections are separate packages verified against their own docs. --- skills/dapp/SKILL.md | 136 +++++++++++++++++++++++++++++++++---------- 1 file changed, 105 insertions(+), 31 deletions(-) diff --git a/skills/dapp/SKILL.md b/skills/dapp/SKILL.md index f6c0eed..7fa1999 100644 --- a/skills/dapp/SKILL.md +++ b/skills/dapp/SKILL.md @@ -42,7 +42,7 @@ Client-side development with `@stellar/stellar-sdk`, wallet connection, signing, ## Recommended Dependencies -> **Requires Node.js 20+** — the Stellar SDK dropped Node 18 support. +> **Requires Node.js 22+.** As of SDK v16, Node 22 is the minimum (older Node produces an `EBADENGINE` warning). v16 also folded `@stellar/stellar-base` into `@stellar/stellar-sdk`, is ESM-first, and uses native `fetch` instead of axios. If you still import `@stellar/stellar-base` directly, switch the import to `@stellar/stellar-sdk` and uninstall the base package (keeping both breaks `instanceof` checks). See the [migration guide](https://stellar.github.io/js-stellar-sdk/guides/00-migration). ```bash npm install @stellar/stellar-sdk @stellar/freighter-api @@ -50,6 +50,8 @@ npm install @stellar/stellar-sdk @stellar/freighter-api npm install @stellar/stellar-sdk @creit.tech/stellar-wallets-kit ``` +> **Sourcing:** SDK mechanics below (init, transaction building, contract invocation, submission, data fetching, error handling) track the official [JS SDK docs](https://stellar.github.io/js-stellar-sdk/) (which also publish [`llms.txt`](https://stellar.github.io/js-stellar-sdk/llms.txt) / [`llms-full.txt`](https://stellar.github.io/js-stellar-sdk/llms-full.txt) bundles for agents). Wallet integrations (Freighter, Stellar Wallets Kit), passkey smart accounts, and the OpenZeppelin relayer are separate packages, not part of the JS SDK — verify those against their own upstream docs. + ## SDK Initialization > For the full API reference (RPC methods, Horizon endpoints, migration guide), see the [data skill](../data/SKILL.md). @@ -272,7 +274,56 @@ export async function buildPaymentTx( } ``` -### Smart Contract Invocation +### Smart Contract Invocation (`contract.Client`) + +The canonical way to call a Soroban contract from JS is the `contract.Client`, not hand-built `Contract.call` + `assembleTransaction`. The client reads the contract's interface from the network, so each method is callable by name and returns an `AssembledTransaction`. You get a native JS result and don't build ScVals by hand. + +```typescript +import { contract, rpc, Networks } from "@stellar/stellar-sdk"; + +// Describe just the methods you call. `Client.from()` uses this to type +// the returned client, so calls are checked and autocompleted — no codegen. +// For a contract with many methods, generate this interface from its spec +// with the SDK's binding CLI instead of writing it by hand. +interface CounterContract { + increment: ( + options?: contract.MethodOptions, + ) => Promise>; +} + +// `signTransaction` comes from the wallet (e.g. Freighter/Wallets Kit in the +// browser). `contract.basicNodeSigner(keypair, networkPassphrase)` is the +// Node equivalent for scripts and tests. +export async function getCounterClient( + contractId: string, + publicKey: string, + signTransaction: contract.ClientOptions["signTransaction"], +) { + return contract.Client.from({ + contractId, + rpcUrl: "https://soroban-testnet.stellar.org", + networkPassphrase: Networks.TESTNET, + publicKey, + signTransaction, + }); +} + +// Preview (free simulation) then sign + send to apply on-chain. +export async function increment(client: contract.Client & CounterContract) { + const tx = await client.increment(); + console.log("preview:", tx.result); // predicted return value, no signature + const sent = await tx.signAndSend(); // submits and polls to completion + return sent.result; +} +``` + +`AssembledTransaction` also supports fine-grained control (`{ fee, simulate, timeoutInSeconds }` as a second arg) and multi-party auth via `tx.needsNonInvokerSigningBy()` / `tx.signAuthEntries()`. See [Invoke a Contract](https://stellar.github.io/js-stellar-sdk/guides/06-invoke-a-contract) and [Authorize a Contract Call](https://stellar.github.io/js-stellar-sdk/guides/07-contract-auth). + +
+Advanced: low-level invocation without a client + +Use this only when you need direct control over the transaction (e.g. batching a contract call with classic operations). Otherwise prefer `contract.Client` above. + ```typescript import * as StellarSdk from "@stellar/stellar-sdk"; import { rpc, config } from "@/lib/stellar"; @@ -284,10 +335,9 @@ export async function invokeContract( args: StellarSdk.xdr.ScVal[] ) { const account = await rpc.getAccount(sourceAddress); - const contract = new StellarSdk.Contract(contractId); - let transaction = new StellarSdk.TransactionBuilder(account, { + const transaction = new StellarSdk.TransactionBuilder(account, { fee: StellarSdk.BASE_FEE, networkPassphrase: config.networkPassphrase, }) @@ -295,28 +345,18 @@ export async function invokeContract( .setTimeout(180) .build(); - // Simulate to get resource estimates - const simulation = await rpc.simulateTransaction(transaction); - - if (StellarSdk.rpc.Api.isSimulationError(simulation)) { - throw new Error(`Simulation failed: ${simulation.error}`); - } - - // Assemble with proper resources - transaction = StellarSdk.rpc.assembleTransaction( - transaction, - simulation - ).build(); - - return transaction.toXDR(); + // `prepareTransaction` simulates and applies footprint/auth/fees in one step. + // (Equivalent to simulateTransaction + rpc.assembleTransaction.) + const prepared = await rpc.prepareTransaction(transaction); + return prepared.toXDR(); } ``` -### Building ScVal Arguments +**Building ScVal arguments by hand** (only needed for the low-level path — `contract.Client` converts native JS args for you): + ```typescript import * as StellarSdk from "@stellar/stellar-sdk"; -// Common conversions const addressVal = StellarSdk.Address.fromString(address).toScVal(); const i128Val = StellarSdk.nativeToScVal(BigInt(amount), { type: "i128" }); const u32Val = StellarSdk.nativeToScVal(42, { type: "u32" }); @@ -334,10 +374,15 @@ const structVal = StellarSdk.nativeToScVal( } ); -// Vec -const vecVal = StellarSdk.nativeToScVal([1, 2, 3], { type: "i128" }); +// Vec of i128 — the element type is applied to each item +const vecVal = StellarSdk.nativeToScVal( + [1, 2, 3].map((n) => BigInt(n)), + { type: "i128" } +); ``` +
+ ## Transaction Submission ### Submit and Wait for Confirmation @@ -369,15 +414,13 @@ async function submitSorobanTransaction(signedXdr: string) { const response = await rpc.sendTransaction(transaction); if (response.status === "ERROR") { - throw new Error(`Transaction failed: ${response.errorResult}`); + throw new Error(`Send failed: ${response.errorResult}`); } - // Poll for completion - let getResponse = await rpc.getTransaction(response.hash); - while (getResponse.status === "NOT_FOUND") { - await new Promise((resolve) => setTimeout(resolve, 1000)); - getResponse = await rpc.getTransaction(response.hash); - } + // Poll for completion. pollTransaction handles the retry loop (default 5 + // attempts, 1s apart — tune with { attempts, sleepStrategy }) instead of a + // hand-rolled while loop that can spin forever. + const getResponse = await rpc.pollTransaction(response.hash); if (getResponse.status === "SUCCESS") { return { @@ -551,6 +594,7 @@ export default function RootLayout({ ### Account Balance ```typescript +import { NotFoundError } from "@stellar/stellar-sdk"; import { horizon } from "@/lib/stellar"; export async function getBalance(address: string) { @@ -561,15 +605,43 @@ export async function getBalance(address: string) { ); return nativeBalance?.balance || "0"; } catch (error) { - if (error.response?.status === 404) { - return "0"; // Account not funded + // loadAccount rejects with the typed NotFoundError for an unfunded account. + if (error instanceof NotFoundError) { + return "0"; // Account not funded yet } throw error; } } ``` +> For submission failures, Horizon returns result codes under `error.response?.data?.extras?.result_codes` (`transaction` + per-`operation`). See [Handle Errors](https://stellar.github.io/js-stellar-sdk/guides/05-handle-errors). + ### Contract State + +For a read-only contract call, `rpc.Server` has one-line shortcuts that build the contract interface for you (including the built-in spec for Stellar Asset Contracts), so no client setup or manual ScVal work is needed: + +```typescript +import { rpc } from "@/lib/stellar"; + +// Run a read-only method and get the decoded result directly. +const { result: balance, isReadCall } = await rpc.queryContract( + tokenId, + "balance", + { id: "G..." } // named args, keyed by parameter name; omit for no-arg methods +); + +// Discover a contract's callable methods from just its ID. +const methods = await rpc.getContractMethods(tokenId); +// [{ name: "balance", inputs: [{ name: "id", type: "Address" }], outputs: ["I128"] }, ...] +``` + +`isReadCall` is per-call: `false` means the `result` is only a simulation preview of a call that would change state (apply it by signing a transaction via `contract.Client`). + +
+Advanced: read a raw ledger entry + +Reach for `getLedgerEntries` only when you need a specific storage key that isn't exposed as a contract method. + ```typescript import * as StellarSdk from "@stellar/stellar-sdk"; import { rpc } from "@/lib/stellar"; @@ -598,6 +670,8 @@ export async function getContractData( } ``` +
+ ## Smart Accounts (Passkey Wallets) For passwordless authentication using WebAuthn passkeys, use Smart Account Kit.