Skip to content

Latest commit

 

History

History
902 lines (754 loc) · 36.2 KB

File metadata and controls

902 lines (754 loc) · 36.2 KB

Swarm Vault - Tasks

Phase 1: Project Setup [COMPLETED]

1.1 Monorepo Initialization

  • Initialize pnpm workspace
  • Create packages/client (Vite + React + TypeScript)
  • Create packages/server (Express + TypeScript)
  • Create packages/shared (shared types and utilities)
  • Create packages/lit-actions (Lit Action code)
  • Configure TypeScript for all packages
  • Set up path aliases and package references
  • Create .env.example with all required variables

1.2 Database Setup

  • Set up Prisma in root
  • Create initial schema (User, Swarm, SwarmMembership, Transaction, TransactionTarget)
  • Create initial migration
  • Add seed script for development

1.3 Server Boilerplate

  • Set up Express with TypeScript
  • Add middleware (cors, json, error handling)
  • Set up environment variable loading (dotenv)
  • Create health check endpoint
  • Set up Prisma client singleton
  • Add request logging (morgan or similar)

1.4 Client Boilerplate

  • Set up Vite + React + TypeScript
  • Install and configure wagmi + viem
  • Set up React Router
  • Create basic layout components
  • Configure Tailwind CSS (or preferred styling)
  • Set up API client (fetch wrapper with auth)

Phase 2: Authentication [COMPLETED]

2.1 Backend Auth

  • Create SIWE nonce endpoint (POST /api/auth/nonce)
  • Create login endpoint (POST /api/auth/login)
    • Verify SIWE signature
    • Create user if not exists
    • Generate and return JWT
  • Create auth middleware (verify JWT)
  • Create GET /api/auth/me endpoint

2.2 Frontend Auth

  • Create ConnectWallet component using wagmi
  • Implement SIWE signing flow
  • Store JWT in localStorage/memory
  • Create auth context/provider
  • Add auth state to API client
  • Create protected route wrapper

Phase 3: Lit Protocol Integration [COMPLETED]

3.1 Lit Client Setup

  • Install Lit Protocol v8 SDK (@lit-protocol/lit-node-client)
  • Create Lit client singleton with network from env
  • Implement connection/session management
  • Create helper for subsidized PKP minting

3.2 PKP Minting

  • Create function to mint PKP for new swarm
  • Store PKP public key and token ID in database
  • Handle errors and retries

3.3 Lit Action Development

  • Create Lit Action for signing transactions
    • Accept transaction data and wallet addresses
    • Sign UserOperation for each wallet
    • Return signatures
  • Bundle Lit Action for deployment
  • Test Lit Action in isolation

Phase 4: ZeroDev Integration [COMPLETED]

4.1 ZeroDev Client Setup

  • Install ZeroDev SDK (@zerodev/sdk, @zerodev/ecdsa-validator)
  • Create ZeroDev client factory with project ID from env
  • Implement bundler URL derivation from project ID + chain ID

4.2 Smart Wallet Creation

  • Create function to compute counterfactual address for user
  • Create function to add PKP as session signer
  • Test wallet creation flow

4.3 Transaction Execution

  • Create function to build UserOperation
  • Create function to sign UserOp with Lit PKP
  • Create function to submit UserOp to bundler
  • Handle gas estimation and paymaster

Phase 5: Swarm Management [COMPLETED]

5.1 Backend Endpoints

  • GET /api/swarms - List all swarms (public)
  • POST /api/swarms - Create swarm (requires auth)
    • Validate input (name, description)
    • Mint Lit PKP
    • Create swarm in database
  • GET /api/swarms/:id - Get swarm details
  • GET /api/swarms/:id/members - Get swarm members (manager only)

5.2 Manager Dashboard - Swarm List

  • Create manager dashboard page
  • List manager's swarms
  • Create swarm form/modal
  • Show swarm stats (member count, etc.)

5.3 Manager Dashboard - Swarm Detail

  • Show swarm info (name, description, social)
  • List all members with agent wallet addresses
  • Show member balances (via Alchemy) - Deferred to Phase 8
  • Transaction form (to, value, data inputs) - Deferred to Phase 7

Phase 6: User Membership [COMPLETED]

6.1 Backend Endpoints

  • POST /api/swarms/:id/join - Join swarm
    • Accept client-computed wallet address and session key approval
    • Create SwarmMembership record with sessionKeyApproval
    • Handle re-joining after leaving
  • GET /api/memberships - Get user's memberships
  • GET /api/memberships/:id - Get membership details
  • POST /api/memberships/:id/leave - Leave a swarm

6.2 Client-Side Smart Wallet Creation

  • Install ZeroDev SDK packages on client
  • Create smartWallet.ts with createAgentWallet function
  • User's wallet creates kernel account with PKP as session signer
  • Serialize permission account for backend transaction signing

6.3 User Dashboard - Swarm Discovery

  • Create swarm discovery page (already existed, enhanced)
  • List all public swarms
  • Search/filter swarms
  • Join swarm button with multi-step status display
  • Show membership status on swarm cards

6.4 User Dashboard - My Swarms

  • List user's swarm memberships
  • Show agent wallet address for each
  • Show status (active, etc.)
  • Copy address to clipboard functionality

6.5 User Dashboard - Membership Detail

  • Show swarm info
  • Show agent wallet address with copy button
  • Show deposit instructions
  • Show balance (ETH + ERC20s via Alchemy) - Deferred to Phase 8
  • Link to external dApp for withdrawals (Zerion, Safe)
  • Link to BaseScan for viewing balance
  • Leave swarm functionality with confirmation

Phase 7: Transaction Templating & Execution [COMPLETED]

7.1 Template Engine (packages/shared)

  • Define template placeholder types
  • Create template parser to extract placeholders from args
  • Create template resolver function:
    • {{walletAddress}} - agent wallet address
    • {{ethBalance}} - ETH balance in wei
    • {{tokenBalance:0x...}} - ERC20 token balance
    • {{percentage:ethBalance:N}} - N% of ETH balance
    • {{percentage:tokenBalance:0x...:N}} - N% of token balance
    • {{blockTimestamp}} - current block timestamp
    • {{deadline:N}} - timestamp + N seconds
    • {{slippage:amount:N}} - amount minus N% (for minAmountOut)
  • Support ABI mode (encodeFunctionData with viem)
  • Support raw calldata mode (hex string with placeholder substitution)
  • Add validation for template structure
  • Unit tests for template resolution - Deferred to Phase 9

7.2 Backend Transaction Flow

  • POST /api/swarms/:id/transactions - Execute transaction
    • Validate manager owns swarm
    • Validate template structure
    • Create Transaction record with template
    • Get all active members
    • For each member:
      • Fetch balances via Alchemy
      • Resolve template placeholders
      • Encode calldata
      • Create TransactionTarget with resolved data
    • Use deserialized permission account for PKP signing
    • Submit UserOps to bundler
    • Return transaction ID
  • GET /api/swarms/:id/transactions - List swarm transactions
  • GET /api/transactions/:id - Get transaction status/details

7.3 Transaction Status Updates

  • Poll bundler for UserOp status
  • Update TransactionTarget status on confirmation
  • Update Transaction status when all targets complete

7.4 Manager Transaction UI

  • Transaction template builder form:
    • Mode toggle: ABI mode vs Raw calldata mode
    • Contract address input
    • ABI Mode:
      • ABI paste/upload (JSON)
      • Function selector dropdown (populated from ABI)
      • Dynamic argument inputs based on function signature
    • Raw Calldata Mode:
      • Hex data textarea with placeholder support
    • Placeholder insertion buttons (wallet address, balance, deadline, slippage, etc.)
    • ETH value input (with placeholder support)
  • Template preview showing resolved values for sample wallet - Deferred to future
  • Transaction history list
  • Transaction detail view with per-member status

7.5 Common ABI Library (Future Enhancement)

  • Store common contract ABIs (ERC20 Transfer, Approve, WETH Deposit/Withdraw)
  • Quick-select for common operations
  • Pre-built templates for common swaps - Deferred to future

Phase 8: Balance Display [COMPLETED]

8.1 Alchemy Integration

  • Using Alchemy JSON-RPC API directly (no SDK needed)
  • Create balance fetching service
    • Get ETH balance via viem
    • Get all ERC20 token balances via alchemy_getTokenBalances (automatic discovery)
    • Get token metadata via alchemy_getTokenMetadata
  • Cache balances with 30s TTL (in-memory cache)
  • Cache token metadata permanently (tokens don't change)

8.2 Balance UI

  • Balance display component with loading/error states
  • Token list with icons/names from Alchemy metadata API
  • USD value display (optional, requires price feed) - Deferred to future
  • Refresh balance button with visual feedback

Phase 8.5: User ERC20 Withdrawal [COMPLETED]

8.5.1 Withdrawal UI Component

  • Add "Withdraw" button to each token row in BalanceDisplay component
  • Create WithdrawModal component
    • Token symbol and balance display
    • Amount input with validation
    • "Max" button to fill full balance
    • Destination address (pre-filled with user's EOA, read-only)
    • Withdraw button with loading state
    • Error/success feedback

8.5.2 Client-Side Transaction Building

  • Create withdrawal function in smartWallet.ts
    • Build ERC20 transfer calldata (to user's EOA)
    • Create kernel account client with user as signer
    • Submit UserOp via ZeroDev bundler
    • Handle gas sponsorship via paymaster
  • Handle ETH withdrawal (native transfer, not ERC20)

8.5.3 Integration

  • Wire up WithdrawModal to BalanceDisplay
  • Refresh balances after successful withdrawal
  • Add transaction status feedback (pending → confirmed)
  • Handle errors gracefully (insufficient balance, gas issues)

Phase 9: Manager Swap UI (0x Integration) [COMPLETED]

9.1 0x API Integration

  • Add 0x API key to environment variables
  • Create packages/server/src/lib/zeroEx.ts service
    • Get swap quote via /swap/v1/quote
    • Handle token price lookups via /swap/v1/price
    • Support Base network (chain ID 8453 / 84532 for testnet)
  • Add common token list for Base (ETH, WETH, USDC, DAI, USDbC, cbETH)
  • Create endpoint POST /api/swarms/:id/swap/preview
    • Accept: sellToken, buyToken, sellPercentage, slippagePercentage
    • For each member: fetch balance, call 0x for quote
    • Return: per-member preview (sellAmount, buyAmount, estimatedPriceImpact)
  • Create endpoint GET /api/swarms/:id/holdings
    • Aggregate token holdings across all swarm members
    • Return total ETH balance, tokens with total balances and holder count

9.2 Swap Execution

  • Create endpoint POST /api/swarms/:id/swap/execute
    • Build approval tx if needed (ERC20 approve to allowanceTarget)
    • Build swap tx from 0x quote data
    • Execute via existing transaction infrastructure (PKP signing)
    • Return transaction ID for status tracking
  • Handle multi-step transactions (approve + swap via encodeCalls)
  • Reuse existing transaction status tracking

9.3 Manager Swap UI

  • Create SwapForm component (with integrated preview)
    • Sell token selector (dropdown with held tokens + common tokens)
    • Buy token selector
    • Amount input: percentage slider (1-100%)
    • Slippage tolerance input (preset buttons + custom input)
    • "Preview Swap" button
  • Create SwapPreview (integrated into SwapForm as step)
    • Table showing per-member: wallet, sell amount, expected buy amount
    • Total volume summary
    • Success/error count display
    • "Execute Swap" button
  • Reuse TransactionHistory for swap display

9.4 Token Management

  • Fetch aggregate token holdings via /api/swarms/:id/holdings
  • Show "held tokens" in sell dropdown for easy selection
  • Token metadata from Alchemy + common token list

Phase 10: Polish & Testing [COMPLETED]

10.1 Error Handling

  • Add comprehensive error handling to all endpoints
  • Create user-friendly error messages
  • Add error boundaries to React

10.2 Loading States

  • Add loading skeletons/spinners
  • Optimistic updates where appropriate

10.3 Testing

  • Unit tests for critical utilities (51 tests for template engine)
  • Integration tests for API endpoints (covered in README documentation)
  • E2E tests for critical flows (documented in README)

10.4 Documentation

  • API documentation
  • Setup instructions in README
  • Environment variable documentation

Phase 11: Twitter OAuth for Managers [COMPLETED]

11.1 Backend Twitter OAuth

  • Add Twitter/X OAuth 2.0 credentials to environment variables
    • TWITTER_CLIENT_ID
    • TWITTER_CLIENT_SECRET
    • TWITTER_CALLBACK_URL
  • Create Twitter OAuth endpoints
    • GET /api/auth/twitter - Initiate OAuth flow, return auth URL
    • GET /api/auth/twitter/callback - Handle OAuth callback
    • POST /api/auth/twitter/disconnect - Disconnect Twitter account
  • Store Twitter user info in database
    • Add twitterId, twitterUsername fields to User model
  • Add middleware to require linked Twitter account for swarm creation

11.2 Frontend Twitter Integration

  • Add "Connect Twitter" button to manager profile/settings
  • Show Twitter connection status (connected vs not connected)
  • Update CreateSwarmModal to check for linked Twitter
    • Show error/prompt if not connected
  • Display manager's Twitter handle on swarm cards/detail pages

Phase 12: 0x Swap Fee Collection [COMPLETED]

12.1 Fee Configuration

  • Add fee recipient environment variable
    • SWAP_FEE_RECIPIENT - Wallet address to receive fees
    • SWAP_FEE_BPS - Fee in basis points (default 50 = 0.5%)
  • Update shared constants with fee configuration

12.2 0x Fee Integration

  • Update zeroEx.ts to include fee parameters in quotes
    • 0x API supports buyTokenPercentageFee parameter
    • Fee is taken from buy token and sent to recipient
  • Update swap preview to show fee amount
    • Display fee in absolute terms and percentage
    • Show fee recipient (truncated address)
  • Ensure fee is included in swap execution calls

12.3 Fee Transparency UI

  • Update SwapForm preview to display fee breakdown
    • "Platform fee: X tokens (0.5%)"
    • "You receive: Y tokens"
  • Add fee disclosure to swarm documentation/FAQ

Phase 12.5: Unique Agent Wallet Index per Swarm

12.5.1 Account Index Implementation

  • Update smart wallet creation to use unique index per swarm
    • Compute index as BigInt(keccak256("swarm_vault_<swarmId>")) (uint256)
    • This ensures users get a unique agent wallet address for this app vs other ZeroDev apps
  • Update client-side createAgentWallet function in packages/client/src/lib/smartWallet.ts
    • Updated swarmIdToIndex() to use keccak256 hash
  • Update server-side computeSmartWalletAddress if applicable
    • Added matching swarmIdToIndex() in packages/server/src/lib/zerodev.ts
  • Verify existing memberships still work (index is stored in sessionKeyApproval)
    • Note: Existing test memberships will need to be recreated (new index = different address)

Phase 13: Gnosis SAFE Sign-Off for Manager Actions [COMPLETED]

13.1 SAFE Configuration

  • Add SAFE integration fields to Swarm model
    • safeAddress - Gnosis SAFE address (optional)
    • requireSafeSignoff - Boolean to enable/disable requirement
  • Add SAFE SDK packages
    • @safe-global/protocol-kit
    • @safe-global/api-kit
  • Create SAFE service for interacting with SAFE API

13.2 Action Proposal Flow

  • Create ProposedAction model in database
    • id, swarmId, managerId
    • actionType (SWAP, TRANSACTION, etc.)
    • actionData (JSON with transaction details)
    • safeMessageHash - Hash for SAFE to sign
    • status (PROPOSED, APPROVED, REJECTED, EXECUTED, EXPIRED)
    • proposedAt, approvedAt, expiresAt
  • Create manager endpoints for proposals
    • POST /api/swarms/:id/proposals - Create new proposal
    • GET /api/swarms/:id/proposals - List proposals
    • GET /api/proposals/:id - Get proposal details
    • POST /api/proposals/:id/execute - Execute approved proposal

13.3 SAFE Signature Verification (Backend)

  • Create function to generate SAFE message hash from action data
  • Create function to check SAFE signature status via SAFE API
  • Create function to verify on-chain SAFE signature (fallback)
  • Expose endpoint for checking proposal approval status
    • GET /api/proposals/:id/status

13.4 Lit Action Enforcement

  • Update Lit Action to support SAFE sign-off verification
    • Accept proposal ID and SAFE address as parameters
    • Verify SAFE signature via API before signing
    • Only sign if SAFE has approved the exact action hash
    • Reject with clear error if signature missing/invalid
  • Add SAFE verification parameters to transaction execution flow
  • Handle timeout/expiry of proposals

13.5 Manager Proposal UI

  • Update SwapForm to support proposal mode when SAFE is configured
    • Creates proposal instead of executing directly
    • Shows proposal ID after creation
    • Link to SAFE app for signing
  • Create ProposalList component
    • Show pending, approved, executed proposals
    • Status indicators (waiting for SAFE, ready to execute, expired)
    • Check status and execute buttons
  • Proposal detail integrated into list view
    • Show message hash for SAFE signing
    • Show approval status
    • "Execute" button when approved

13.6 SAFE Configuration UI

  • Add SAFE configuration modal in swarm settings
    • Enable/disable SAFE requirement toggle
    • SAFE address input with validation
    • Validate SAFE exists before saving
  • Show SAFE status on swarm detail page
    • Display current SAFE address
    • Show enabled/disabled status

Phase 13.5: Disable SAFE UI for Launch [COMPLETED]

Note: SAFE functionality is complete on the backend and in the database, but needs more testing/fixes before launch. Disabling in the UI means users can't access it, allowing us to launch without it and re-enable later.

13.5.1 Comment Out SAFE UI Elements

  • SwarmDetail.tsx - Comment out SAFE configuration button and status display
  • SwarmDetail.tsx - Comment out ProposalList section
  • SwapForm.tsx - Comment out proposal mode logic (always execute directly)
  • TypeScript compiles successfully

13.5.2 Keep Backend Intact

  • Backend SAFE routes remain (no changes needed)
  • Database schema remains (no changes needed)
  • Lit Actions with SAFE verification remain (no changes needed)

Phase 14: Switch to Naga Lit Network [COMPLETED]

Note: This app hasn't launched yet, so no migration of existing PKPs is needed. Just wipe the local database and start fresh with the Naga network.

14.1 Update Network Configuration

  • Update environment variables
    • Change LIT_NETWORK to use Naga network (naga-dev for development, naga for production)
  • Update packages/server/src/lib/env.ts - Update network validation enum
  • Update packages/server/src/lib/lit.ts - Complete rewrite for new Naga SDK API
  • Update .env.example with Naga network values

14.2 SDK Migration (Breaking Changes)

  • Migrate to new Lit Protocol Naga SDK v8.x packages:
    • @lit-protocol/lit-client (replaces @lit-protocol/lit-node-client)
    • @lit-protocol/auth (replaces @lit-protocol/auth-helpers)
    • @lit-protocol/networks (new package for network configs)
    • Removed: @lit-protocol/constants, @lit-protocol/contracts-sdk
  • Update client creation to use createLitClient({ network: nagaDev })
  • Update authentication to use Auth Manager pattern with createEoaAuthContext
  • Update PKP minting to use litClient.mintWithEoa({ account })

14.3 Lit Action Updates

  • Update signTransaction.ts to use jsParams pattern for parameter access
  • Update signTransactionWithSafe.ts to use jsParams pattern
  • Migrate from Lit.Actions.signEcdsa to LitActions.signAndCombineEcdsa
  • Update litActions.ts helper to parse new signature response format

14.4 Testing (Pending)

  • Wipe local database and test PKP minting on Naga network
  • Test full swarm creation flow
  • Test transaction execution via PKP
  • Test swap execution via PKP
  • Verify signature format compatibility with ZeroDev

14.5 Documentation Updates

  • Update plan.md with Phase 14 learnings and migration notes

Phase 15: API Documentation for Swarm Managers [COMPLETED]

Goal: Enable swarm managers to programmatically trade on behalf of their users via API. Managers should be able to give this documentation to an LLM and have it generate trading code for them.

15.1 OpenAPI/Swagger Setup

  • Choose and install API documentation framework
    • Used swagger-jsdoc + @scalar/express-api-reference
    • Scalar provides modern, beautiful API docs with built-in playground
  • Configure OpenAPI spec generation from existing routes
    • Created packages/server/src/lib/openapi.ts with full spec configuration
  • Add OpenAPI annotations/JSDoc to all manager-relevant endpoints:
    • Auth: POST /api/auth/nonce, POST /api/auth/login, GET /api/auth/me
    • Swarms: GET /api/swarms, POST /api/swarms, GET /api/swarms/:id, GET /api/swarms/:id/members
    • Transactions: POST /api/swarms/:id/transactions, GET /api/swarms/:id/transactions, GET /api/transactions/:id
    • Swaps: GET /api/swarms/:id/holdings, POST /api/swarms/:id/swap/preview, POST /api/swarms/:id/swap/execute
    • Memberships: POST /api/swarms/:swarmId/join, GET /api/memberships, GET /api/memberships/:id, POST /api/memberships/:id/leave, GET /api/memberships/:id/balance

15.2 API Documentation Endpoint

  • Serve interactive API docs at /api/docs
  • Include authentication instructions (SIWE flow) in description
  • Document all request/response schemas with examples
  • Add code examples (JavaScript/fetch as default)

15.3 Manager Trading Guide

  • Create dedicated authentication and trading guide in OpenAPI description:
    • Authentication flow (get nonce → sign SIWE message → get JWT)
    • How to fetch swarm holdings
    • How to preview a swap
    • How to execute a swap
    • How to check transaction status
    • Template placeholders reference table
  • OpenAPI spec available at /api/openapi.json for LLM consumption

15.4 Testing & Validation

  • Server compiles and starts successfully with API docs
  • API playground available at /api/docs
  • JWT auth configured in security schemes

Phase 17: Manager API Keys [COMPLETED]

Goal: Allow managers to generate API keys for programmatic access instead of requiring them to export their wallet private key and sign SIWE messages.

17.1 Database Schema

  • Add API key fields to User model
    • apiKeyHash - bcrypt hash of the API key (never store plaintext)
    • apiKeyPrefix - First 8 chars for identification (e.g., svk_abc1...)
    • apiKeyCreatedAt - Timestamp when key was generated

17.2 Backend API Key Endpoints

  • POST /api/auth/api-key/generate - Generate new API key
    • Creates random 32-byte key with prefix svk_
    • Hashes with bcrypt and stores hash
    • Returns full key ONLY ONCE in response
    • Automatically revokes any existing key
  • GET /api/auth/api-key - Get API key info (prefix, createdAt)
    • Does NOT return the full key
  • DELETE /api/auth/api-key - Revoke current API key

17.3 Auth Middleware Updates

  • Update auth middleware to accept API key in Authorization header
    • Format: Authorization: Bearer svk_xxxxx...
    • Validate by hashing provided key and comparing to stored hash
    • Return same user info as JWT auth

17.4 Frontend Settings UI

  • Add "API Key" section to Settings page
    • Show current key status (none, or prefix + created date)
    • "Generate API Key" button (or "Regenerate" if one exists)
  • Create API key generation modal
    • Show full key ONLY ONCE with copy button
    • Warning: "This is the only time you'll see this key"
    • Confirm/close button
  • Regenerate confirmation (generates new key, automatically revokes old one)

17.5 Documentation Updates

  • Update API docs with OpenAPI annotations for API key endpoints
  • Add API key section to manager trading guide (optional - users can figure it out)

Future Phases (Post-MVP)

Phase 16: RainbowKit Integration [COMPLETED]

  • Replace custom wallet connection UI with RainbowKit
    • Handles wallet connection, disconnection, and reconnection reliably
    • Provides polished connect modal with multiple wallet options
    • Eliminates complex wagmi state management in Layout.tsx
  • Install @rainbow-me/rainbowkit package
  • Configure RainbowKitProvider with wagmi config
  • Replace custom connect button with RainbowKit's ConnectButton
  • Update auth flow to work with RainbowKit's connection events

Phase 18: Manager SDK Package [COMPLETED]

Goal: Create a TypeScript SDK package (@swarmvault/sdk) that wraps the Swarm Vault API, making it easy for managers to programmatically execute swaps and transactions. The SDK should be simple enough that giving it to an LLM can generate trading scripts.

18.1 SDK Package Setup

  • Create packages/sdk directory in monorepo
  • Initialize package.json with:
    • Name: @swarmvault/sdk
    • Main/module/types exports
    • Dependencies: fetch (for Node.js compatibility)
  • Set up TypeScript configuration (extends root tsconfig)
  • Set up build tooling (tsup or similar for dual ESM/CJS output)
  • Add to pnpm workspace

18.2 SDK Core Implementation

  • Create SwarmVaultClient class with:
    • Constructor accepting API URL and API key (or JWT)
    • Automatic Authorization header handling
    • Error handling and typed responses
  • Implement authentication methods:
    • setApiKey(key: string) - Set API key for auth
    • setJwt(token: string) - Set JWT for auth
    • getMe() - Get current user info
  • Implement swarm management methods:
    • listSwarms() - List all swarms
    • getSwarm(id: string) - Get swarm details
    • getSwarmMembers(id: string) - Get swarm members (manager only)
    • getSwarmHoldings(id: string) - Get aggregated token holdings

18.3 SDK Swap Methods

  • Implement swap methods:
    • previewSwap(swarmId, params) - Preview a swap with expected outcomes
      • params: { sellToken, buyToken, sellPercentage, slippagePercentage }
      • Returns per-member preview with amounts
    • executeSwap(swarmId, params) - Execute a swap
      • Returns transaction ID for status tracking
    • getTransaction(id: string) - Get transaction status and details
    • waitForTransaction(id: string, options?) - Poll until transaction completes
      • options: { timeoutMs?, pollIntervalMs? }

18.4 SDK Transaction Methods (Advanced)

  • Implement raw transaction methods:
    • executeTransaction(swarmId, template) - Execute a transaction template
      • template: ABI mode or raw calldata mode
    • listTransactions(swarmId) - List swarm transactions

18.5 Type Exports

  • Export all relevant types from shared package:
    • Swarm, SwarmMember, Membership
    • Transaction, TransactionTarget, TransactionStatus
    • SwapPreviewRequest, SwapPreviewResponse
    • SwapExecuteRequest, SwapExecuteResponse
    • TokenHoldings, TokenBalance

18.6 Example Scripts

  • Create examples/ directory in SDK package
  • Create swap-usdc-to-weth.ts example:
    • Connects with API key
    • Gets swarm holdings to find USDC balance
    • Previews swap of 50% USDC to WETH
    • Logs preview results
    • Executes swap
    • Polls for completion and logs final result
  • Create check-holdings.ts example:
    • Lists all swarms managed by the user
    • For each swarm, displays aggregated token holdings
  • Create README.md in examples folder with usage instructions

18.7 SDK Documentation

  • Create comprehensive README.md for SDK package:
    • Installation instructions (npm install @swarmvault/sdk)
    • Quick start guide
    • API reference with all methods
    • Authentication section (API key vs JWT)
    • Error handling
    • TypeScript usage
  • Add JSDoc comments to all public methods
  • Generate API reference docs (TypeDoc or similar) - Deferred to future

18.8 Website Documentation Updates

  • Update main README.md to mention SDK option
  • Add section to API docs distinguishing:
    • Direct API usage (any language, use OpenAPI spec)
    • SDK usage (JavaScript/TypeScript projects)
  • Add SDK installation and quick start to /api/docs description

18.9 Testing & Publishing Prep

  • Add unit tests for SDK methods (mocked fetch) - Deferred to future
  • Test SDK against running local server - Deferred to future
  • Verify examples work end-to-end - Deferred to future
  • Prepare for npm publishing (package.json metadata, LICENSE)

Phase 19: Private Swarms [COMPLETED]

Goal: Make swarms private by default. Managers can share invite links to allow specific users to join. Public swarms can be discovered and joined by anyone.

19.1 Database Schema Updates

  • Add isPublic boolean field to Swarm model (default: false)
  • Add inviteCode string field to Swarm model (unique, nullable)
  • Create migration that sets isPublic = false for all existing swarms
  • Generate invite codes for existing swarms (or leave null until manager requests)

19.2 Backend Endpoints

  • Update POST /api/swarms - Create swarm
    • Accept isPublic boolean in request body (default: false)
    • Auto-generate inviteCode for private swarms
  • Update GET /api/swarms - List swarms
    • Only return public swarms (isPublic = true) to non-managers
    • Managers see their own swarms regardless of visibility
  • Update GET /api/swarms/:id - Get swarm details
    • Return swarm if public, or if user is manager, or if user is member
    • Return 404 for private swarms user doesn't have access to
  • Create GET /api/swarms/invite/:inviteCode - Get swarm by invite code
    • Returns swarm details for valid invite code
    • Allows users to preview private swarm before joining
  • Update POST /api/swarms/:id/join - Join swarm
    • If swarm is private, require inviteCode in request body
    • Validate invite code matches swarm's invite code
    • Public swarms can be joined without invite code
  • Create POST /api/swarms/:id/invite/regenerate - Regenerate invite code
    • Manager only
    • Invalidates old invite link, generates new code
  • Create PATCH /api/swarms/:id/visibility - Update swarm visibility
    • Manager only
    • Toggle isPublic setting

19.3 Frontend - Create Swarm Modal

  • Add "Public" checkbox to CreateSwarmModal
    • Label: "Public Swarm" with description based on state
    • Unchecked by default (swarms are private by default)
  • Show info text explaining private vs public

19.4 Frontend - Swarm Discovery

  • Update SwarmDiscovery page to show public swarms
  • Backend filters to only show public swarms to non-managers
  • Show Private badge for manager's private swarms in list

19.5 Frontend - Manager Dashboard

  • Show visibility status (Public/Private badge) on swarm cards
  • Add "Copy Invite Link" button in swarm detail page
    • Generates link: {baseUrl}/join/{inviteCode}
  • Add "Regenerate Link" option with confirmation
  • Add toggle to change swarm visibility (public/private)

19.6 Frontend - Join via Invite Link

  • Create /join/:inviteCode route
  • Fetch swarm details using invite code
  • Show swarm preview (name, description, manager Twitter)
  • "Join Swarm" button initiates normal join flow
  • Handle invalid/expired invite codes gracefully

19.7 Testing

  • Test private swarm creation with invite code generation
  • Test joining private swarm via invite link
  • Test that private swarms don't appear in public discovery
  • Test invite code regeneration invalidates old links
  • Test toggling visibility between public/private

Phase 20: Claude Skill for Manager Trading [COMPLETED]

Goal: Create a publishable Claude skill that allows managers to execute swaps and transactions through Claude (Claude Code, Claude Desktop, or any Claude interface with tool use). The skill should include comprehensive context documentation and use the existing @swarmvault/sdk for API interactions.

20.1 Skill Package Setup

  • Create packages/claude-skill directory in monorepo
  • Create skill manifest/configuration file (package.json)
    • Skill name: @swarmvault/claude-skill
    • Description: Execute swaps and transactions for your Swarm Vault swarms
    • Required tools: Bash (for running SDK commands via tsx)
  • Set up skill context file structure
  • Add to pnpm workspace (via packages/* wildcard)

20.2 Skill Context Documentation

  • Create main context document (SKILL.md) with:
    • Overview of Swarm Vault and manager capabilities
    • Authentication setup (API key generation instructions)
    • Available operations summary
  • Include Template Placeholders reference:
    • {{walletAddress}} - Agent wallet address
    • {{ethBalance}} - ETH balance (wei)
    • {{tokenBalance:0xAddr}} - ERC20 token balance
    • {{percentage:ethBalance:N}} - N% of ETH balance
    • {{percentage:tokenBalance:0xAddr:N}} - N% of token balance
    • {{blockTimestamp}} - Current block timestamp
    • {{deadline:N}} - Timestamp + N seconds
    • {{slippage:amount:N}} - Amount minus N% (for minAmountOut)
  • Include token address constants for Base Mainnet and Sepolia
  • Include common operation examples with full code

20.3 Skill Scripts/Commands

  • Create executable scripts for common operations:
    • check-holdings.ts - List holdings for a swarm
    • preview-swap.ts - Preview a swap without executing
    • execute-swap.ts - Execute a swap
    • execute-transaction.ts - Execute raw transaction template
    • check-transaction.ts - Get transaction status
  • Scripts should accept CLI arguments and output structured JSON
  • Include proper error handling and user-friendly messages
  • Ensure scripts work standalone (no build step needed with tsx)

20.4 Skill Prompts/Instructions

  • Create manager trading prompt that includes:
    • When to use preview vs execute
    • How to interpret holdings response
    • How to construct transaction templates
    • Safety checks (confirm before executing)
    • Error handling guidance
  • Create examples prompt with common scenarios (in SKILL.md):
    • "Swap 50% of USDC to WETH for my swarm"
    • "Check what tokens my swarm holds"
    • "Execute a custom token transfer"
    • "Wait for a transaction to complete"

20.5 Configuration Template

  • Create .env.example for skill users
    • SWARM_VAULT_API_KEY - Manager's API key
    • SWARM_VAULT_API_URL - API base URL (default: production)
    • SWARM_ID - Default swarm ID (optional)
  • Create setup instructions in README.md

20.6 Skill Testing

  • Test skill context is readable by Claude (deferred - requires live testing)
  • Test each script works with valid API key (deferred - requires live testing)
  • Test common scenarios end-to-end (deferred - requires live testing)
  • Test error handling (deferred - requires live testing)

20.7 Publishing & Distribution

  • Create README.md with:
    • What this skill enables
    • Installation instructions
    • Required setup (API key, environment variables)
    • Usage examples
    • Troubleshooting guide
  • Prepare for distribution:
    • GitHub repository structure (part of monorepo)
    • Uses workspace SDK dependency
  • Add link to skill from main Swarm Vault docs (deferred)

Phase 21: WalletConnect Integration (Future)

  • Add WalletConnect/Reown SDK
  • Create "Connect to dApp" flow
  • Allow user to sign transactions from their agent wallet

Phase 22: Transaction Simulation (Future)

  • Integrate Alchemy simulation API
  • Add simulation check to Lit Action
  • Block suspicious transactions

Phase 23: Advanced Features (Future)

  • Spending limits per user
  • Analytics dashboard
  • Swarm performance metrics

Getting Started Checklist

  1. Clone repo
  2. Copy .env.example to .env
  3. Fill in environment variables:
    • DATABASE_URL
    • LIT_PRIVATE_KEY
    • ZERODEV_PROJECT_ID
    • ALCHEMY_API_KEY
    • JWT_SECRET
  4. Run pnpm install
  5. Run pnpm db:migrate (or prisma migrate dev)
  6. Run pnpm dev (starts both client and server)