x402-engineer 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/AGENT.md +102 -0
  2. package/README.md +43 -0
  3. package/dist/cli.cjs +137 -0
  4. package/package.json +51 -0
  5. package/skills/stellar-dev/SKILL.md +146 -0
  6. package/skills/stellar-dev/advanced-patterns.md +188 -0
  7. package/skills/stellar-dev/api-rpc-horizon.md +521 -0
  8. package/skills/stellar-dev/common-pitfalls.md +510 -0
  9. package/skills/stellar-dev/contracts-soroban.md +565 -0
  10. package/skills/stellar-dev/ecosystem.md +430 -0
  11. package/skills/stellar-dev/frontend-stellar-sdk.md +651 -0
  12. package/skills/stellar-dev/resources.md +306 -0
  13. package/skills/stellar-dev/security.md +491 -0
  14. package/skills/stellar-dev/standards-reference.md +94 -0
  15. package/skills/stellar-dev/stellar-assets.md +419 -0
  16. package/skills/stellar-dev/testing.md +786 -0
  17. package/skills/stellar-dev/zk-proofs.md +136 -0
  18. package/skills/x402-add-paywall/SKILL.md +208 -0
  19. package/skills/x402-add-paywall/references/patterns.md +132 -0
  20. package/skills/x402-debug/SKILL.md +92 -0
  21. package/skills/x402-debug/references/checklist.md +146 -0
  22. package/skills/x402-explain/SKILL.md +136 -0
  23. package/skills/x402-init/SKILL.md +129 -0
  24. package/skills/x402-init/templates/env-example.md +17 -0
  25. package/skills/x402-init/templates/express/config.ts.md +29 -0
  26. package/skills/x402-init/templates/express/server.ts.md +30 -0
  27. package/skills/x402-init/templates/fastify/adapter.ts.md +66 -0
  28. package/skills/x402-init/templates/fastify/config.ts.md +29 -0
  29. package/skills/x402-init/templates/fastify/server.ts.md +90 -0
  30. package/skills/x402-init/templates/hono/config.ts.md +29 -0
  31. package/skills/x402-init/templates/hono/server.ts.md +31 -0
  32. package/skills/x402-init/templates/next-app-router/config.ts.md +29 -0
  33. package/skills/x402-init/templates/next-app-router/server.ts.md +31 -0
  34. package/skills/x402-stellar/SKILL.md +139 -0
  35. package/skills/x402-stellar/references/api.md +237 -0
  36. package/skills/x402-stellar/references/patterns.md +276 -0
  37. package/skills/x402-stellar/references/setup.md +138 -0
  38. package/skills/x402-stellar/scripts/check-deps.js +218 -0
package/AGENT.md ADDED
@@ -0,0 +1,102 @@
1
+ # x402 Engineer
2
+
3
+ > A helpful guide for adding HTTP 402 micropayments to any API using the x402 protocol on Stellar.
4
+
5
+ ## What I Do
6
+
7
+ I help you add pay-per-request billing to API endpoints using the x402 protocol and USDC on Stellar testnet. I explain what I'm doing and why at each step -- think of me as a senior dev pairing with you on your first x402 integration.
8
+
9
+ ## Commands
10
+
11
+ ### `/x402:init` -- Bootstrap x402
12
+
13
+ Sets up x402 payment protection in your project. Detects your framework (Next.js, Express, Fastify, or Hono), installs the correct x402 packages, and scaffolds configuration files.
14
+
15
+ **Creates:**
16
+ - Route config file (`lib/x402/config.ts`) with `routesConfig` and env var exports
17
+ - Server/middleware file (`lib/x402/server.ts`) with framework-specific adapter
18
+ - `.env.example` with required variables (SERVER_STELLAR_ADDRESS, FACILITATOR_URL, FACILITATOR_API_KEY)
19
+ - For Fastify: custom `FastifyAdapter` (because `@x402/fastify` is not published on npm)
20
+
21
+ **Idempotent:** Detects existing setup and skips what already exists.
22
+
23
+ ### `/x402:add-paywall` -- Protect an endpoint
24
+
25
+ Wraps an API endpoint with x402 payment middleware. Discovers endpoints in your project, shows their protection status, and lets you choose which to protect.
26
+
27
+ **How it works:**
28
+ - Next.js: wraps the route handler inline with `withPayment()` or `withX402()`
29
+ - Express/Fastify/Hono: adds the route to `routesConfig` (middleware handles the rest)
30
+
31
+ **Idempotent:** Detects `// x402: payment-protected endpoint` markers and routesConfig entries. Already-protected endpoints are skipped.
32
+
33
+ ### `/x402:debug` -- Diagnose issues
34
+
35
+ Runs a comprehensive static analysis checklist covering:
36
+ 1. Environment variables (set, format-valid)
37
+ 2. Dependencies (installed, correct versions)
38
+ 3. Code structure (config file, server file, import paths, price format)
39
+ 4. Framework detection (correct adapter for detected framework)
40
+
41
+ **Output:** `[PASS]` / `[FAIL]` / `[WARN]` for each check with actionable fix instructions.
42
+
43
+ ### `/x402:explain` -- Understand your setup
44
+
45
+ Generates a live overview of how x402 is wired in your project:
46
+ - Protected endpoints table (method, path, price, asset, network)
47
+ - 6-step payment flow diagram
48
+ - Framework and adapter details
49
+ - Configuration file locations
50
+
51
+ **Dynamic:** Reads your codebase fresh on every invocation. Always reflects current state.
52
+
53
+ ### Recommended progression
54
+
55
+ ```
56
+ /x402:init -> /x402:add-paywall -> /x402:explain -> /x402:debug
57
+ ```
58
+
59
+ Start with `init` for new projects, or `add-paywall` if already set up.
60
+
61
+ ## Protocol Flow
62
+
63
+ Every x402 payment follows this lifecycle:
64
+
65
+ ```
66
+ Client Request -> 402 Response -> Sign Payment -> Retry with X-Payment -> Verify via Facilitator -> Settle -> Return Resource
67
+ ```
68
+
69
+ 1. **Client sends request** to a protected endpoint (no payment header)
70
+ 2. **Server returns HTTP 402** with payment requirements in response headers
71
+ 3. **Client signs a payment** using their Stellar wallet (USDC amount specified by server)
72
+ 4. **Client retries** the same request with `X-Payment` header containing the signed payment
73
+ 5. **Facilitator verifies** the payment signature and settles the transaction on Stellar
74
+ 6. **Server returns the resource** after facilitator confirms payment
75
+
76
+ ## What I Know
77
+
78
+ - **x402 protocol**: Payment header format, facilitator API, middleware patterns
79
+ - **Stellar testnet**: Account creation, USDC trustlines, transaction signing, Friendbot funding
80
+ - **Frameworks**: Next.js (App Router), Express, Fastify, Hono -- server middleware patterns
81
+ - **Skills**: x402-stellar (protocol reference), stellar-dev (blockchain reference)
82
+
83
+ ## What I Defer
84
+
85
+ - **Mainnet deployment**: Use Stellar documentation for production network configuration
86
+ - **Custom pricing models**: Beyond simple per-request pricing, consult x402 protocol spec
87
+ - **Unsupported frameworks**: For frameworks not listed above, I'll adapt patterns but recommend checking framework docs
88
+ - **Token economics**: For complex payment models, see tokenomics resources
89
+
90
+ ## Skills
91
+
92
+ This agent ships with six skill packs:
93
+
94
+ **Reference skills:**
95
+ - **x402-stellar** -- Protocol patterns, API reference, setup guides for Stellar micropayments
96
+ - **stellar-dev** -- Stellar/Soroban development: SDK usage, assets, contracts, testing, security
97
+
98
+ **Command skills:**
99
+ - **x402-init** -- `/x402:init` slash command
100
+ - **x402-add-paywall** -- `/x402:add-paywall` slash command
101
+ - **x402-debug** -- `/x402:debug` slash command
102
+ - **x402-explain** -- `/x402:explain` slash command
package/README.md ADDED
@@ -0,0 +1,43 @@
1
+ # @x402/engineer
2
+
3
+ Claude Code skill pack for adding x402 micropayments to any API endpoint in seconds.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npx @x402/engineer install
9
+ ```
10
+
11
+ This registers x402 skills and slash commands into your Claude Code environment (`~/.claude/`).
12
+
13
+ ## Commands
14
+
15
+ | Command | Description |
16
+ |---------|-------------|
17
+ | `/x402:init` | Bootstrap x402 in your project (deps, env template, route config) |
18
+ | `/x402:add-paywall` | Wrap an endpoint with payment middleware (idempotent) |
19
+ | `/x402:debug` | Diagnose payment flow issues (headers, facilitator, wallet) |
20
+ | `/x402:explain` | Generate explanation of how x402 is wired in your codebase |
21
+
22
+ ## Supported Frameworks
23
+
24
+ - Next.js (App Router)
25
+ - Express
26
+ - Fastify
27
+ - Hono
28
+
29
+ ## Prerequisites
30
+
31
+ - [Claude Code](https://claude.ai/code) installed and configured
32
+ - Node.js >= 18
33
+ - A Stellar wallet and OZ Channels facilitator credentials (see `/x402:init` for guided setup)
34
+
35
+ ## Uninstall
36
+
37
+ ```bash
38
+ npx @x402/engineer uninstall
39
+ ```
40
+
41
+ ## License
42
+
43
+ MIT
package/dist/cli.cjs ADDED
@@ -0,0 +1,137 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
18
+ // If the importer is in node compatibility mode or this is not an ESM
19
+ // file that has been converted to a CommonJS file using a Babel-
20
+ // compatible transform (i.e. "__esModule" has not been set), then set
21
+ // "default" to the CommonJS "module.exports" for node compatibility.
22
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
23
+ mod
24
+ ));
25
+
26
+ // src/install.ts
27
+ var import_node_fs2 = __toESM(require("fs"), 1);
28
+ var import_node_path2 = __toESM(require("path"), 1);
29
+
30
+ // src/paths.ts
31
+ var import_node_path = __toESM(require("path"), 1);
32
+ var import_node_os = __toESM(require("os"), 1);
33
+ var PACKAGE_ROOT = import_node_path.default.resolve(__dirname, "..");
34
+ var PATHS = {
35
+ packageRoot: PACKAGE_ROOT,
36
+ packageSkills: import_node_path.default.join(PACKAGE_ROOT, "skills"),
37
+ packageCommands: import_node_path.default.join(PACKAGE_ROOT, "commands"),
38
+ packageAgent: import_node_path.default.join(PACKAGE_ROOT, "AGENT.md"),
39
+ claudeDir: import_node_path.default.join(import_node_os.default.homedir(), ".claude"),
40
+ skillsDir: import_node_path.default.join(import_node_os.default.homedir(), ".claude", "skills"),
41
+ commandsDir: import_node_path.default.join(import_node_os.default.homedir(), ".claude", "commands"),
42
+ manifest: import_node_path.default.join(import_node_os.default.homedir(), ".claude", "skills", "x402-manifest.json")
43
+ };
44
+
45
+ // src/manifest.ts
46
+ var import_node_fs = __toESM(require("fs"), 1);
47
+ function readManifest(manifestPath) {
48
+ try {
49
+ const raw = import_node_fs.default.readFileSync(manifestPath, "utf-8");
50
+ return JSON.parse(raw);
51
+ } catch {
52
+ return null;
53
+ }
54
+ }
55
+ function writeManifest(manifestPath, manifest) {
56
+ import_node_fs.default.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2) + "\n");
57
+ }
58
+
59
+ // src/install.ts
60
+ function install(pathsOverride) {
61
+ const p = pathsOverride ?? PATHS;
62
+ const existing = readManifest(p.manifest);
63
+ const isUpdate = existing !== null;
64
+ const version = JSON.parse(
65
+ import_node_fs2.default.readFileSync(import_node_path2.default.join(p.packageRoot, "package.json"), "utf-8")
66
+ ).version;
67
+ import_node_fs2.default.mkdirSync(p.skillsDir, { recursive: true });
68
+ import_node_fs2.default.mkdirSync(p.commandsDir, { recursive: true });
69
+ const installedSkills = [];
70
+ const installedCommands = [];
71
+ const skillDirs = import_node_fs2.default.readdirSync(p.packageSkills, { withFileTypes: true }).filter((d) => d.isDirectory());
72
+ for (const dir of skillDirs) {
73
+ const src = import_node_path2.default.join(p.packageSkills, dir.name);
74
+ const dest = import_node_path2.default.join(p.skillsDir, dir.name);
75
+ import_node_fs2.default.cpSync(src, dest, { recursive: true, force: true });
76
+ installedSkills.push(dest);
77
+ const verb = isUpdate ? "Updated" : "Installed";
78
+ console.log(` \u2713 ${verb} ${dir.name} skill`);
79
+ }
80
+ if (import_node_fs2.default.existsSync(import_node_path2.default.join(p.packageCommands, "x402"))) {
81
+ const src = import_node_path2.default.join(p.packageCommands, "x402");
82
+ const dest = import_node_path2.default.join(p.commandsDir, "x402");
83
+ import_node_fs2.default.cpSync(src, dest, { recursive: true, force: true });
84
+ installedCommands.push(dest);
85
+ const verb = isUpdate ? "Updated" : "Installed";
86
+ console.log(` \u2713 ${verb} x402 commands`);
87
+ }
88
+ writeManifest(p.manifest, {
89
+ version,
90
+ installedAt: existing?.installedAt ?? (/* @__PURE__ */ new Date()).toISOString(),
91
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
92
+ paths: { skills: installedSkills, commands: installedCommands }
93
+ });
94
+ console.log("");
95
+ console.log(" Run /x402:init to get started");
96
+ }
97
+
98
+ // src/uninstall.ts
99
+ var import_node_fs3 = __toESM(require("fs"), 1);
100
+ var import_node_path3 = __toESM(require("path"), 1);
101
+ function uninstall(pathsOverride) {
102
+ const p = pathsOverride ?? PATHS;
103
+ const manifest = readManifest(p.manifest);
104
+ if (!manifest) {
105
+ console.log(" x402 engineer is not installed");
106
+ return;
107
+ }
108
+ for (const skillPath of manifest.paths.skills) {
109
+ if (import_node_fs3.default.existsSync(skillPath)) {
110
+ import_node_fs3.default.rmSync(skillPath, { recursive: true, force: true });
111
+ console.log(` \u2713 Removed ${import_node_path3.default.basename(skillPath)} skill`);
112
+ }
113
+ }
114
+ for (const cmdPath of manifest.paths.commands) {
115
+ if (import_node_fs3.default.existsSync(cmdPath)) {
116
+ import_node_fs3.default.rmSync(cmdPath, { recursive: true, force: true });
117
+ console.log(` \u2713 Removed ${import_node_path3.default.basename(cmdPath)} commands`);
118
+ }
119
+ }
120
+ import_node_fs3.default.rmSync(p.manifest, { force: true });
121
+ console.log("");
122
+ console.log(" x402 engineer uninstalled");
123
+ }
124
+
125
+ // src/cli.ts
126
+ var command = process.argv[2];
127
+ switch (command) {
128
+ case "install":
129
+ install();
130
+ break;
131
+ case "uninstall":
132
+ uninstall();
133
+ break;
134
+ default:
135
+ console.log("Usage: npx @x402/engineer <install|uninstall>");
136
+ process.exit(1);
137
+ }
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "x402-engineer",
3
+ "version": "0.1.0",
4
+ "description": "Claude Code skill pack for adding x402 micropayments to any API endpoint",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "bin": "dist/cli.cjs",
8
+ "exports": {
9
+ ".": "./src/index.ts",
10
+ "./types": "./src/types/index.ts"
11
+ },
12
+ "types": "./src/index.ts",
13
+ "files": [
14
+ "dist/",
15
+ "skills/",
16
+ "commands/",
17
+ "AGENT.md",
18
+ "README.md"
19
+ ],
20
+ "publishConfig": {
21
+ "access": "public"
22
+ },
23
+ "scripts": {
24
+ "build": "tsup",
25
+ "dev": "tsx src/cli.ts",
26
+ "prepublishOnly": "npm run build"
27
+ },
28
+ "engines": {
29
+ "node": ">=18.0.0"
30
+ },
31
+ "keywords": [
32
+ "x402",
33
+ "micropayments",
34
+ "stellar",
35
+ "claude-code",
36
+ "skill-pack",
37
+ "api-monetization"
38
+ ],
39
+ "repository": {
40
+ "type": "git",
41
+ "url": "https://github.com/x402/engineer",
42
+ "directory": "packages/engineer"
43
+ },
44
+ "devDependencies": {
45
+ "@x402/tsconfig": "*",
46
+ "tsup": "^8.5.1",
47
+ "tsx": "^4.21.0",
48
+ "typescript": "^6.0.0",
49
+ "vitest": "^3.2.4"
50
+ }
51
+ }
@@ -0,0 +1,146 @@
1
+ ---
2
+ name: stellar-dev
3
+ 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.
4
+ user-invocable: true
5
+ argument-hint: "[task-description]"
6
+ triggers:
7
+ - /x402:init
8
+ - /x402:debug
9
+ - stellar
10
+ - soroban
11
+ - xlm
12
+ - trustline
13
+ ---
14
+
15
+ # Stellar Development Skill (Soroban-first)
16
+
17
+ ## What this Skill is for
18
+ Use this Skill when the user asks for:
19
+ - Soroban smart contract development (Rust)
20
+ - Stellar dApp frontend work (React / Next.js / Node.js)
21
+ - Wallet connection + signing flows (Freighter, etc.)
22
+ - Transaction building / sending / confirmation
23
+ - Stellar Asset issuance and management
24
+ - Client SDK usage (JavaScript, Python, Go, Rust)
25
+ - Zero-knowledge proof verification (where supported by target network/protocol)
26
+ - Privacy-preserving applications (privacy pools, confidential tokens)
27
+ - Local testing and deployment
28
+ - Security hardening and audit-style reviews
29
+
30
+ ## What this Skill is NOT for
31
+ - Bitcoin, Ethereum, Solana, or other non-Stellar blockchain development
32
+ - Stellar node/validator operation (see [validators docs](https://developers.stellar.org/docs/validators))
33
+ - General Rust programming unrelated to Soroban
34
+ - Stellar protocol governance or CAP authoring
35
+
36
+ ## Default stack decisions (opinionated)
37
+
38
+ ### 1. Smart Contracts: Soroban (Rust)
39
+ - Use Soroban SDK (`soroban-sdk` crate) for all smart contract development
40
+ - Contracts compile to WebAssembly (WASM)
41
+ - Use `#![no_std]` - standard library not available
42
+ - 64KB contract size limit - use release optimizations
43
+ - Prefer Stellar Assets over custom token contracts when possible
44
+
45
+ ### 2. Client SDK: stellar-sdk (JavaScript) first
46
+ - Use `@stellar/stellar-sdk` for browser and Node.js applications
47
+ - Supports both Stellar RPC and legacy Horizon API
48
+ - Full transaction building, signing, and submission
49
+ - Soroban contract deployment and invocation
50
+
51
+ ### 3. API Access: Stellar RPC first (Horizon legacy-focused)
52
+ - **Prefer Stellar RPC** for new projects (JSON-RPC, real-time state)
53
+ - **Horizon API** remains available for legacy compatibility and historical-query workflows
54
+ - RPC: 7-day history for most methods; `getLedgers` queries back to genesis (Infinite Scroll)
55
+ - Use Hubble/Galexie for comprehensive historical data beyond RPC
56
+
57
+ ### 4. Token Strategy: Stellar Assets first
58
+ - **Prefer Stellar Assets** (classic issuance + trustlines) for fungible tokens
59
+ - Built-in ecosystem support (wallets, exchanges, anchors)
60
+ - Stellar Asset Contracts (SAC) provide Soroban interoperability
61
+ - Use custom Soroban tokens only for complex logic requirements
62
+
63
+ ### 5. Testing
64
+ - **Local**: Use Stellar Quickstart Docker for local network
65
+ - **Testnet**: Use Testnet with Friendbot for funding
66
+ - **Unit tests**: Compile to native for fast iteration
67
+ - **Integration tests**: Deploy to local/testnet
68
+
69
+ ### 6. Wallet Integration
70
+ - **Freighter** is the primary browser wallet
71
+ - Use Stellar Wallets Kit for multi-wallet support
72
+ - Wallet Standard for consistent connection patterns
73
+
74
+ ### 7. Freshness policy
75
+ - Verify volatile facts (protocol support, RPC endpoints, CAP/SEP status, SDK API changes) against official docs before asserting them as current.
76
+
77
+ ## Operating procedure (how to execute tasks)
78
+
79
+ ### 1. Classify the task layer
80
+ - Smart contract layer (Soroban/Rust)
81
+ - Client SDK/scripts layer (JS/Python/Go)
82
+ - Frontend/wallet layer
83
+ - Asset management layer (issuance, trustlines)
84
+ - Testing/CI layer
85
+ - Infrastructure (RPC/Horizon/indexing)
86
+
87
+ ### Quick routing
88
+ - Need custom on-chain logic? → [contracts-soroban.md](contracts-soroban.md)
89
+ - Building a frontend/dApp? → [frontend-stellar-sdk.md](frontend-stellar-sdk.md)
90
+ - Issuing or managing tokens? → [stellar-assets.md](stellar-assets.md)
91
+ - Zero-knowledge proofs or privacy? → [zk-proofs.md](zk-proofs.md)
92
+ - Setting up tests/CI? → [testing.md](testing.md)
93
+ - Querying chain data or indexing? → [api-rpc-horizon.md](api-rpc-horizon.md) (also see [Data Docs](https://developers.stellar.org/docs/data))
94
+ - Security review? → [security.md](security.md)
95
+ - Hit an error? → [common-pitfalls.md](common-pitfalls.md)
96
+ - Need upgrade/factory/governance/DeFi architecture patterns? → [advanced-patterns.md](advanced-patterns.md)
97
+ - Need SEP/CAP guidance and standards links? → [standards-reference.md](standards-reference.md)
98
+
99
+ ### 2. Pick the right building blocks
100
+ - Contracts: Soroban Rust SDK + Stellar CLI
101
+ - Frontend: stellar-sdk (JS) + Freighter/Wallets Kit
102
+ - Backend: stellar-sdk (JS/Python/Go) + RPC
103
+ - Assets: Classic operations or SAC for Soroban interop
104
+ - Testing: Quickstart (local) or Testnet
105
+
106
+ ### 3. Implement with Stellar-specific correctness
107
+ Always be explicit about:
108
+ - Network passphrase (Mainnet vs Testnet vs local)
109
+ - Source account + sequence number
110
+ - Fee + resource limits (for Soroban)
111
+ - Authorization requirements
112
+ - Trustline status for assets
113
+ - Contract storage types (temporary vs persistent vs instance)
114
+
115
+ ### 4. Add tests
116
+ - Unit tests: Native compilation with `#[test]`
117
+ - Integration tests: Local Quickstart or Testnet
118
+ - Contract tests: Use `Env` from soroban-sdk
119
+ - Frontend tests: Mock wallet/RPC interactions
120
+
121
+ ### 5. Deliverables expectations
122
+ When you implement changes, provide:
123
+ - Exact files changed + diffs
124
+ - Commands to install/build/test/deploy
125
+ - Network configuration (passphrase, RPC endpoint)
126
+ - Risk notes for signing/fees/storage/authorization
127
+
128
+ ## Progressive disclosure (read when needed)
129
+ - Smart contracts: [contracts-soroban.md](contracts-soroban.md)
130
+ - Frontend + wallets: [frontend-stellar-sdk.md](frontend-stellar-sdk.md)
131
+ - Testing strategy: [testing.md](testing.md)
132
+ - Stellar Assets: [stellar-assets.md](stellar-assets.md)
133
+ - Zero-knowledge proofs: [zk-proofs.md](zk-proofs.md)
134
+ - API access (RPC/Horizon): [api-rpc-horizon.md](api-rpc-horizon.md)
135
+ - Security checklist: [security.md](security.md)
136
+ - Common pitfalls: [common-pitfalls.md](common-pitfalls.md)
137
+ - Advanced architecture patterns: [advanced-patterns.md](advanced-patterns.md)
138
+ - SEP/CAP standards map: [standards-reference.md](standards-reference.md)
139
+ - Ecosystem projects: [ecosystem.md](ecosystem.md)
140
+ - Reference links: [resources.md](resources.md)
141
+
142
+ ## Keywords
143
+ stellar, soroban, xlm, smart contracts, rust, wasm, webassembly, rpc, horizon,
144
+ freighter, stellar-sdk, soroban-sdk, stellar-cli, trustline, anchor, sep, passkey,
145
+ smart wallet, sac, stellar asset contract, defi, token, nft, scaffold stellar, constructor, upgrade, factory, governance, standards,
146
+ zero-knowledge, zk, zk-snark, groth16, bn254, poseidon, pairing, privacy, confidential, noir, risc zero, privacy pool, merkle tree
@@ -0,0 +1,188 @@
1
+ # Advanced Soroban Patterns
2
+
3
+ ## When to use this guide
4
+ Use this guide for higher-complexity contract architecture:
5
+ - Upgrades and migrations
6
+ - Factory/deployer systems
7
+ - Governance and timelocks
8
+ - DeFi primitives (vaults, pools, oracles)
9
+ - Regulated token/compliance workflows
10
+ - Resource and storage optimization
11
+
12
+ Use `contracts-soroban.md` for core contract syntax and day-to-day patterns.
13
+
14
+ ## Design principles
15
+ - Prefer simple state machines over implicit behavior.
16
+ - Minimize privileged entrypoints and protect all privileged actions with explicit auth.
17
+ - Keep upgrades predictable: version metadata + migration plan + rollback strategy.
18
+ - Use idempotent migrations and fail fast on incompatible versions.
19
+ - Separate protocol/business logic from governance/admin logic when possible.
20
+
21
+ ## Upgradeability patterns
22
+
23
+ ### 1) Explicit upgrade policy
24
+ - Decide early whether the contract is mutable or immutable.
25
+ - If mutable, implement an `upgrade` entrypoint guarded by admin or governance.
26
+ - If immutable, do not expose upgrade capability.
27
+
28
+ ### 2) Version tracking
29
+ Track both runtime and code version:
30
+ - Contract metadata (`contractmeta!`) for binary version
31
+ - Storage key for migration/application version
32
+
33
+ ```rust
34
+ #![no_std]
35
+ use soroban_sdk::{contract, contractimpl, contractmeta, contracttype, Address, BytesN, Env};
36
+
37
+ contractmeta!(key = "binver", val = "1.0.0");
38
+
39
+ #[contracttype]
40
+ #[derive(Clone)]
41
+ pub enum DataKey {
42
+ Admin,
43
+ AppVersion,
44
+ }
45
+
46
+ #[contract]
47
+ pub struct Upgradeable;
48
+
49
+ #[contractimpl]
50
+ impl Upgradeable {
51
+ pub fn __constructor(env: Env, admin: Address) {
52
+ env.storage().instance().set(&DataKey::Admin, &admin);
53
+ env.storage().instance().set(&DataKey::AppVersion, &1u32);
54
+ }
55
+
56
+ pub fn upgrade(env: Env, new_wasm_hash: BytesN<32>) {
57
+ let admin: Address = env.storage().instance().get(&DataKey::Admin).unwrap();
58
+ admin.require_auth();
59
+ env.deployer().update_current_contract_wasm(new_wasm_hash);
60
+ }
61
+ }
62
+ ```
63
+
64
+ ### 3) Migration entrypoint
65
+ - Add a dedicated `migrate` function after upgrades.
66
+ - Ensure migration is monotonic (`new_version > current_version`).
67
+ - Treat migrations as one-way and idempotent.
68
+
69
+ ## Factory and deployment patterns
70
+
71
+ ### Factory contract responsibilities
72
+ - Authorize who can deploy instances.
73
+ - Derive deterministic addresses with salts when needed.
74
+ - Emit events for deployments (indexing/ops observability).
75
+ - Keep deployment logic separate from instance business logic.
76
+
77
+ ```rust
78
+ #![no_std]
79
+ use soroban_sdk::{contract, contractimpl, Address, BytesN, Env, Val, Vec};
80
+
81
+ #[contract]
82
+ pub struct Factory;
83
+
84
+ #[contractimpl]
85
+ impl Factory {
86
+ pub fn deploy(
87
+ env: Env,
88
+ owner: Address,
89
+ wasm_hash: BytesN<32>,
90
+ salt: BytesN<32>,
91
+ constructor_args: Vec<Val>,
92
+ ) -> Address {
93
+ owner.require_auth();
94
+ env.deployer()
95
+ .with_address(env.current_contract_address(), salt)
96
+ .deploy_v2(wasm_hash, constructor_args)
97
+ }
98
+ }
99
+ ```
100
+
101
+ Operational note:
102
+ - Keep a registry (or emit canonical deployment events) to avoid orphaned instances.
103
+
104
+ ## Governance patterns
105
+
106
+ ### Timelock for sensitive actions
107
+ Use a timelock for upgrades and major config changes:
108
+ - `propose_*` stores pending action + execute ledger
109
+ - `execute_*` enforces delay
110
+ - `cancel_*` allows governance abort
111
+
112
+ ### Multisig and role separation
113
+ - Separate roles: proposer, approver, executor.
114
+ - Define threshold and signer rotation process.
115
+ - Record proposal state in persistent storage and prevent replay.
116
+
117
+ Checklist:
118
+ - Proposal uniqueness and replay protection
119
+ - Expiry semantics
120
+ - Clear cancellation path
121
+ - Explicit event emission
122
+
123
+ ## DeFi primitives
124
+
125
+ ### Vaults
126
+ - Track `total_assets` and `total_shares` with careful rounding rules.
127
+ - Use conservative math for mint/redeem conversions.
128
+ - Enforce pause/emergency controls for admin-level intervention.
129
+
130
+ ### Pools/AMMs
131
+ - Define invariant and fee accounting precisely.
132
+ - Protect against stale pricing and manipulation.
133
+ - Include slippage checks on all user-facing swaps.
134
+
135
+ ### Oracle integration
136
+ - Require freshness constraints (ledger/time bounds).
137
+ - Prefer median/multi-source feeds for critical operations.
138
+ - Add circuit breakers for extreme price movement.
139
+
140
+ ## Compliance-oriented token design
141
+
142
+ Common regulated features:
143
+ - Allowlist/denylist checks before transfer
144
+ - Jurisdiction or investor-class restrictions
145
+ - Forced transfer/freeze authority with auditable governance
146
+ - Off-chain identity references (never store sensitive PII directly)
147
+
148
+ Implementation guidance:
149
+ - Keep compliance policy in dedicated modules/entrypoints.
150
+ - Emit policy decision events for traceability.
151
+ - Treat privileged compliance actions as high-risk operations requiring strong auth.
152
+
153
+ ## Resource optimization
154
+
155
+ ### Storage
156
+ - Use `instance` for global config.
157
+ - Use `persistent` for critical user state.
158
+ - Use `temporary` only for disposable data.
159
+ - Extend TTL strategically, not on every call.
160
+
161
+ ### Compute
162
+ - Avoid unbounded loops over user-controlled collections.
163
+ - Prefer bounded batch operations.
164
+ - Reduce cross-contract calls in hot paths.
165
+
166
+ ### Contract size
167
+ - Keep release profile optimized (`opt-level = "z"`, `lto = true`, `panic = "abort"`).
168
+ - Split concerns across contracts when near Wasm size limits.
169
+
170
+ ## Security review checklist for advanced architectures
171
+ - Access control is explicit on every privileged path.
172
+ - Upgrade and migration are both tested (happy path + failure path).
173
+ - Timelock and governance logic is replay-safe.
174
+ - External dependency assumptions are documented.
175
+ - Emergency controls and incident runbooks are defined.
176
+ - Events cover operationally important transitions.
177
+
178
+ ## Testing strategy for advanced patterns
179
+ - Unit tests for role checks, invariants, and edge-case math.
180
+ - Integration tests for multi-step governance flows.
181
+ - Upgrade tests from old state snapshots to new versions.
182
+ - Negative tests for unauthorized and malformed calls.
183
+
184
+ ## Related docs
185
+ - Core contract development: `contracts-soroban.md`
186
+ - Security checks: `security.md`
187
+ - Testing approach: `testing.md`
188
+ - Standards references: `standards-reference.md`