Skill: harry5556/chainstream-defi (version 1.1.8)

--- name: chainstream-defi description: "[FINANCIAL EXECUTION] Execute irreversible on-chain DeFi operations via CLI and MCP tools. Use when user wants to swap tokens, create tokens on launchpad, sign transactions, broadcast signed transactions, or execute trading strategies. Requires explicit user confirmation before every destructive operation. All transactions are real and irreversible. Keywords: swap, DEX, launchpad, transaction, trade, sign, broadcast, PumpFun, Jupiter, Uniswap, USDC, SOL, execute." --- # ChainStream DeFi Execute DeFi operations: token swap, launchpad creation, transaction signing, and broadcast. All operations are **real, irreversible on-chain transactions**. > **Before any swap**: load [chainstream-data](../chainstream-data/) and run `token security` on the target token. NEVER swap a token you haven't safety-checked. - **CLI**: `npx @chainstream-io/cli` - **MCP Server**: `https://mcp.chainstream.io/mcp` (streamable-http) ## Financial Risk Notice **Every command in this skill executes REAL, IRREVERSIBLE blockchain transactions.** - Transactions cannot be undone once confirmed on-chain. - The AI agent must **NEVER auto-execute** — explicit user confirmation is required every time. - Only use with funds the user is willing to trade. ## Integration Path (check FIRST) DeFi operations **require a wallet**. API Key alone is insufficient. **Before anything else (CLI path), ensure user is authenticated:** 1. `npx @chainstream-io/cli config auth` — check login status 2. If NOT logged in → `npx @chainstream-io/cli login` (creates EVM + Solana wallet, auto-grants **nano trial plan: 50K CU free, 30 days** — no purchase needed) 3. `npx @chainstream-io/cli plan status` — verify subscription is active **New users get a free trial on login (50K CU).** For details on trial plans and upgrade options, see [`shared/authentication.md`](../shared/authentication.md#agent-bootstrap-checklist). **Environment-aware decision (pick the path that matches how the agent runs):** 1. **Agent already has a wallet (`WalletSigner`)?** → **Use SDK** (`@chainstream-io/sdk`). Do NOT use CLI for signing. Implement `WalletSigner` interface. Your wallet must also support `signTypedData` for x402 payment. 2. **No embedded wallet — local terminal or CI available?** → **Use CLI** (`npx @chainstream-io/cli`). **Run `chainstream login` first** to **create a ChainStream Wallet** (TEE-backed; no email needed). CLI handles transaction signing; for x402 subscription, run `plan purchase --plan <name>` separately. 3. **Using MCP (streamable HTTP, e.g. `https://mcp.chainstream.io/mcp` — `dex/swap`, …)?** → **Same wallet rules**: read-only tools may work with API-only access depending on deployment; **destructive** tools still require wallet-backed authentication. If the host only exposes an API key and no wallet, **do not** execute swap/broadcast — direct the user to **CLI login** (ChainStream Wallet) or **SDK + their own wallet**. MCP does not remove the wallet requirement for on-chain execution. 4. **Only API Key?** → Cannot execute wallet-gated DeFi (swap, broadcast, etc.). Tell user: "DeFi requires a wallet. Use SDK with your wallet or run `npx @chainstream-io/cli login`." For full auth guide with code examples, see [shared/authentication.md](../shared/authentication.md). ## Prerequisites (CLI path) **All DeFi commands require a wallet. If you see "Not authenticated" or "Wallet required", run:** ```bash npx @chainstream-io/cli login ``` ## CLI Wallet & Signing Commands **The CLI has built-in wallet management and signing capabilities.** These commands are ALREADY IMPLEMENTED and WORKING: ### Wallet Commands ```bash # Show configured wallet addresses npx @chainstream-io/cli wallet address # Show wallet balance (native + tokens, supports sol/base) npx @chainstream-io/cli wallet balance --chain sol # Sign a transaction (uses configured Turnkey or raw wallet) npx @chainstream-io/cli wallet sign --chain sol --tx <base64-serializedTx> # Import raw private key (dev/testing only) npx @chainstream-io/cli wallet set-raw --chain sol ``` ### Transaction Commands ```bash # Broadcast a signed transaction npx @chainstream-io/cli tx send --chain sol --signed-tx <base64-signedTx> # Get gas price (EVM only) npx @chainstream-io/cli tx gas-price --chain eth # Estimate gas limit (EVM only) npx @chainstream-io/cli tx estimate-gas --chain eth --from 0x... --to 0x... --data 0x... ``` ### DEX Commands ```bash # Get best route + build unsigned tx (aggregator) npx @chainstream-io/cli dex route --chain sol --from <wallet> --input-token SOL --output-token <addr> --amount 1000000 # Build unsigned swap tx (specific DEX) npx @chainstream-io/cli dex swap --chain sol --from <wallet> --input-token SOL --output-token <addr> --amount 1000000 --dex jupiter # Build unsigned token creation tx npx @chainstream-io/cli dex create --chain sol --from <wallet> --name MyToken --symbol MT --dex pumpfun ``` ## Endpoint Selector | Intent | CLI Command | MCP Tool | Safety | Reference | |--------|-------------|----------|--------|-----------| | Build route + unsigned tx | `npx @chainstream-io/cli dex route --chain sol --from WALLET --input-token SOL --output-token ADDR --amount 1000000` | `dex/route` | readOnly | [swap-protocol.md](references/swap-protocol.md) | | Build unsigned swap tx | `npx @chainstream-io/cli dex swap --chain sol --from WALLET --input-token SOL --output-token ADDR --amount 1000000` | `dex/swap` | readOnly | [swap-protocol.md](references/swap-protocol.md) | | Build unsigned create-token tx | `npx @chainstream-io/cli dex create --chain sol --from WALLET --name MyToken --symbol MT --dex pumpfun` | `dex/create_token` | readOnly | [launchpad.md](references/launchpad.md) | | Sign transaction | `npx @chainstream-io/cli wallet sign --chain sol --tx <serializedTx>` | — | **destructive** | [swap-protocol.md](references/swap-protocol.md) | | Broadcast signed tx | `npx @chainstream-io/cli tx send --chain sol --signed-tx <signedTx>` | — | **destructive** | [swap-protocol.md](references/swap-protocol.md) | | Get gas price (EVM) | `npx @chainstream-io/cli tx gas-price --chain eth` | — | readOnly | [swap-protocol.md](references/swap-protocol.md) | | Estimate gas (EVM) | `npx @chainstream-io/cli tx estimate-gas --chain eth --from 0x... --to 0x... --data 0x...` | — | readOnly | [swap-protocol.md](references/swap-protocol.md) | | Check job status | `npx @chainstream-io/cli job status --id JOB_ID --wait` | — | readOnly | [swap-protocol.md](references/swap-protocol.md) | ### `dex route` vs `dex swap` - **`dex route`** — aggregates multiple DEXes, returns the best-price route. **Use by default** unless user specifies a DEX. - **`dex swap`** — builds a transaction on a specific DEX (e.g. `--dex raydium`). Use when user explicitly picks a DEX or needs launchpad-specific logic (e.g. pumpfun bonding curve). ## Atomic Execution Protocol (Hard Requirement) All **destructive** operations MUST follow this protocol. Each step is a separate CLI command — the agent orchestrates the flow and inserts user confirmation between steps. **MANDATORY - READ**: Before any swap execution, load [`rules/safety-protocol.md`](rules/safety-protocol.md) for risk thresholds and abort conditions. ### Step 1: Build Transaction (get route + unsigned tx) ```bash npx @chainstream-io/cli dex route --chain sol --from <wallet> --input-token SOL --output-token <addr> --amount 1000000 --slippage 5 --json ``` Returns `{ routeInfo, serializedTx, elapsedTime }`. Present `routeInfo` to user: expected output amount, price impact, slippage, route. ### Step 2: Confirm Display trade summary to user: - Chain, input/output tokens, amounts - Price impact and slippage from `routeInfo` - Estimated gas fees **WAIT for explicit user confirmation. This step is NOT optional.** If user says "just do it" without reviewing, show the summary anyway. ### Step 3: Sign (after user confirms) ```bash npx @chainstream-io/cli wallet sign --chain sol --tx <serializedTx> --json ``` Returns `{ signedTx }`. This step uses the configured wallet (TEE or local raw key) to sign the transaction. ### Step 4: Broadcast ```bash npx @chainstream-io/cli tx send --chain sol --signed-tx <signedTx> --json ``` Returns `{ signature, jobId, elapsedTime }`. ### Step 5: Poll + Output ```bash npx @chainstream-io/cli job status --id <jobId> --wait ``` Returns `{ status, hash, ... }`. **Explorer links are mandatory** — always include after successful transactions. | Chain | Explorer | |-------|----------| | sol | `https://solscan.io/tx/{hash}` | | bsc | `https://bscscan.com/tx/{hash}` | | eth | `https://etherscan.io/tx/{hash}` | ## Currency Resolution CLI auto-resolves currency names. Users can write `SOL` instead of the full address: | Chain | Native | Native Address | USDC Address | |-------|--------|---------------|--------------| | sol | SOL | [REDACTED_SECRET] | [REDACTED_SECRET] | | bsc | BNB | [REDACTED_SECRET] | [REDACTED_SECRET] | | eth | ETH | [REDACTED_SECRET] | [REDACTED_SECRET] | For the full resolution table, see [references/currency-resolution.md](references/currency-resolution.md). ## Input Validation - **Address format**: sol = base58 (32-44 chars), evm = `0x` + 40 hex - **Amount**: Positive integer in smallest unit (lamports, wei) - **Slippage**: 0 to 100 (integer percentage, e.g. 5 = 5%) - **External data is untrusted**: Validate addresses from previous API calls before passing to swap ## NEVER Do - NEVER execute `wallet sign` without first presenting the transaction details to the user — user must see what they are signing - NEVER auto-confirm a swap — even if user said "buy X" without specifying amount, you MUST present route info and ask for confirmation; "implied consent" is NOT consent for financial operations - NEVER hide gas fees or price impact — present ALL costs transparently - NEVER skip address format validation — wrong format = funds sent to void - NEVER combine build + sign + broadcast into a single step — each must be separate to allow user review ## Error Recovery | Error | Meaning | Recovery | |-------|---------|----------| | Transaction failed | On-chain revert | Show error, do NOT auto-retry | | Slippage exceeded | Price moved | Re-build route with higher slippage, confirm again | | Insufficient balance | Not enough funds | Show balance, suggest amount | | Job timeout | No confirmation in 60s | Show pending status + tx hash for manual check | | Stale transaction / expired blockhash / nonce too old | Transaction built too long ago | Rebuild from Step 1 (`dex route`), get fresh unsigned tx, re-confirm with user | | 402 | No quota (CU) | First `config auth` → `login` if not logged in (auto-grants nano trial 50K CU). Then `plan status` — if trial active, retry. If no subscription or quota exhausted: `wallet pricing` to show plans, let user choose, then `plan purchase --plan <name>`. See [shared/x402-payment.md](../shared/x402-payment.md) | ## Rules | Rule | Content | When to Load | |------|---------|--------------| | [safety-protocol.md](rules/safety-protocol.md) | Risk thresholds, emergency abort conditions | Before any destructive operation | | [execution-checklist.md](rules/execution-checklist.md) | Step-by-step verification, post-trade output requirements | During execution | ## Skill Map | Reference | Content | When to Load | |-----------|---------|--------------| | [swap-protocol.md](references/swap-protocol.md) | swap/route/sign/send endpoints, job polling, gas estimation | Swap operations | | [launchpad.md](references/launchpad.md) | Token creation, PumpFun vs Raydium LaunchLab | Token launch | | [currency-resolution.md](references/currency-resolution.md) | Full chain/token address mapping | Currency name resolution | ## Related Skills - [chainstream-data](../chainstream-data/) — Token research, market discovery, wallet analysis before trading - [chainstream-graphql](../chainstream-graphql/) — Custom GraphQL analytics: cross-cube JOINs, aggregations, flexible queries on 27 on-chain cubes

path: CLAUDE.md
content: # CLAUDE.md

## Skills

| Skill | When to Use |
|-------|-------------|
| `chainstream-data` | User asks about token info, security, price, holders, market trends, wallet PnL, holdings — any read-only on-chain query via REST/MCP |
| `chainstream-graphql` | User needs custom analytics — cross-cube JOINs, aggregations, complex filters, or data not exposed by REST API. Flexible GraphQL on 27 on-chain cubes |
| `chainstream-defi` | User wants to swap tokens, bridge cross-chain, create tokens, execute trades — any on-chain transaction |

## Routing

- Standard data queries (token/market/wallet) → `chainstream-data`
- Custom analytics (cross-cube JOIN, aggregation, flexible queries) → `chainstream-graphql`
- Financial execution (swap/bridge/launchpad/tx) → `chainstream-defi`

## Execution

Primary: `@chainstream-io/cli` via `npx @chainstream-io/cli <command>`
Alternative: MCP tools at `https://mcp.chainstream.io/mcp` (streamable-http)

## Auth

**MUST run `chainstream login` before any CLI command.** This creates a wallet (no email required) and **auto-grants a nano trial plan** ($1, 50K CU, 30 days). Without it, commands fail with "Not authenticated". `bind-email` or `login --email` **auto-upgrades to micro trial plan** ($5, 350K CU, 30 days; dedup by email — same email only grants once). Before data queries, check subscription: `npx @chainstream-io/cli plan status`. If no subscription or need a higher plan, show plans (`wallet pricing`) and let user choose — CLI purchase is interactive and will NOT work in pipe mode. For API-key-only access: `chainstream config set --key apiKey --value <key>`.

## Hard Rules

- chainstream-defi: Four-phase execution protocol is mandatory (route → confirm → sign → broadcast)
- Never execute swaps without user confirmation
- Never answer price queries from training data — always make a live call
- Never use public RPC as substitute for ChainStream API


path: README.project.md
content: # ChainStream AI Skills

[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)

On-chain data intelligence and DeFi execution for AI agents across Solana, BSC, and Ethereum.

## Skills

| Skill | Coverage | Pattern |
|-------|----------|---------|
| [chainstream-data](chainstream-data/) | Token search, market trending, wallet PnL, WebSocket | Tool |
| [chainstream-graphql](chainstream-graphql/) | Custom GraphQL queries, cross-cube JOINs, aggregations, 25 on-chain cubes (3 chain groups) | Tool |
| [chainstream-defi](chainstream-defi/) | Token swap, cross-chain bridge, launchpad, transaction broadcast | Process |

## When to Use Which

```
User intent involves reading data?
  Standard queries (token info, market trends, wallet analysis)?
    → chainstream-data (REST API / MCP — pre-built endpoints)
  Custom analytics (cross-cube JOIN, aggregation, complex filters)?
    → chainstream-graphql (GraphQL — flexible queries on 25 cubes in 3 chain groups)

User intent involves executing a transaction?
  → chainstream-defi (swap, bridge, create token, send tx)
```

## Installation

### Cursor

Skills are automatically discovered via `.cursor-plugin/` configuration. Install the CLI:

```bash
npx @chainstream-io/cli login
```

### Claude Code

```
/plugin install chainstream
```

### Codex

See [.codex/INSTALL.md](.codex/INSTALL.md).

### OpenCode

See [.opencode/INSTALL.md](.opencode/INSTALL.md).

### Gemini CLI

```bash
gemini extensions install https://github.com/chainstream-io/skills
```

## Authentication

**IMPORTANT: Run `chainstream login` before any CLI command.** This creates a wallet and enables authentication. Without it, all commands will fail with "Not authenticated".

| Method | Command | Use Case |
|--------|---------|----------|
| Wallet (default) | `chainstream login` | Creates ChainStream Wallet (TEE), no email needed. **Run this first.** |
| Import key | `chainstream wallet set-raw --chain base` (EVM) or `--chain sol` (Solana) | Use your own private key |
| Email login | `chainstream login --email [REDACTED_SECRET]` | Recover wallet on new device |
| Bind email | `chainstream bind-email [REDACTED_SECRET]` | Optional, for account recovery |
| API Key | `chainstream config set --key apiKey --value <key>` | Read-only, dashboard users |
| x402 (USDC) | Interactive on 402 | CLI prompts for plan selection, pays with USDC (Base/Solana). Quota is in **CU (Compute Units)**, not call count |
| x402 → API Key | Interactive on 402 | Same as above — also returns API Key for MCP/SDK use |

> **Free trial**: `chainstream login` auto-grants a nano plan ($1, 50K CU, 30 days). `bind-email` or `login --email` auto-upgrades to micro plan ($5, 350K CU, 30 days). Dedup by email — same email only grants once. No manual purchase needed for trial.

## Usage Examples

Natural language prompts you can send to any AI assistant with ChainStream skills:

```
search for meme tokens on Solana
is <token_address> safe to buy?
show top holders of <token_address>
what tokens are trending on SOL right now?
show my wallet PnL on Solana
check my current subscription status
swap 0.1 SOL for <token_address>
check job status <job_id>
show K-line chart for <token_address>
what cubes are available in the GraphQL schema?
query the top 50 tokens by 24h volume using GraphQL
```

## CLI

Install via npx (no global install needed):

```bash
npx @chainstream-io/cli token search --keyword PUMP --chain sol
npx @chainstream-io/cli market trending --chain sol --duration 1h
npx @chainstream-io/cli wallet pnl --chain sol --address <addr>
npx @chainstream-io/cli dex route --chain sol --from <wallet> --input-token SOL --output-token <addr> --amount 1000000
npx @chainstream-io/cli graphql schema --summary
npx @chainstream-io/cli graphql query --query 'query { Solana { DEXTradeByTokens(where: {Trade: {Currency: {MintAddress: {is: "TOKEN_ADDRESS"}}}}, limit: {count: 10}, orderBy: {descending: Block_Time}) { Block { Time } Trade { Currency { Symbol } Amount AmountInUSD Side { Type } } } } }'
```

## MCP Server

```json
{
  "mcpServers": {
    "chainstream": {
      "url": "https://mcp.chainstream.io/mcp",
      "headers": { "X-API-KEY": "<your-api-key>" }
    }
  }
}
```

## Supported Chains

| Chain | ID | Data | DeFi | WebSocket |
|-------|----|------|------|-----------|
| Solana | `sol` | Yes | Yes | Yes |
| BSC | `bsc` | Yes | Yes | Yes |
| Ethereum | `eth` | Yes | Yes | Yes |

## Resources

- [Documentation](https://docs.chainstream.io)
- [Dashboard](https://app.chainstream.io)
- [CLI README](https://github.com/chainstream-io/cli)
- [API Reference](https://docs.chainstream.io/api-reference)

## License

[MIT](LICENSE)


path: references/currency-resolution.md
content: # Currency Resolution

When users specify currency names (SOL, ETH, BNB, USDC) instead of addresses, the CLI auto-resolves to the correct on-chain address.

## Resolution Table

| Chain | Name | Address |
|-------|------|---------|
| sol | SOL | [REDACTED_SECRET] |
| sol | USDC | [REDACTED_SECRET] |
| bsc | BNB | `0x0000000000000000000000000000000000000000` |
| bsc | USDC | `0x8ac76a51cc950d9822d68b83fe1ad97b32cd580d` |
| eth | ETH | `0x0000000000000000000000000000000000000000` |
| eth | USDC | [REDACTED_SECRET] |

## Examples

```bash
# These are equivalent:
npx @chainstream-io/cli dex route --chain sol --from <wallet> --input-token SOL --output-token <addr> --amount 1000000
npx @chainstream-io/cli dex route --chain sol --from <wallet> --input-token So11111111111111111111111111111111111111112 --output-token <addr> --amount 1000000
```

Currency resolution is case-insensitive (sol, Sol, SOL all work).


path: references/launchpad.md
content: # Launchpad Reference

## Token Creation

| Method | Path | Description |
|--------|------|-------------|
| POST | `/v2/dex/:chain/create` | Create token on launchpad |

## CLI Command

```bash
npx @chainstream-io/cli dex create --chain sol --from <wallet> --name "My Token" --symbol MT --uri "ipfs://..." [--dex pumpfun] [--image <url>]
```

## Supported Platforms

| Chain | Platforms |
|-------|-----------|
| sol | PumpFun, Raydium LaunchLab |
| bsc | FourMeme |

## Parameters

| Parameter | Required | Description |
|-----------|----------|-------------|
| `chain` | Yes | sol / bsc / eth |
| `name` | Yes | Token name |
| `symbol` | Yes | Token symbol (ticker) |
| `uri` | Yes | Metadata URI (IPFS or HTTP) |
| `dex` | No | Launchpad platform: pumpfun, raydium (default: pumpfun) |
| `image` | No | Token image URL |

## Metadata URI

Before creating a token, upload metadata to IPFS:

```bash
# Use ChainStream IPFS presign endpoint
POST /v2/ipfs/presign → { uploadUrl, ipfsUri }
# Upload image/metadata to the presigned URL
# Use the returned ipfsUri as --uri parameter
```

## PumpFun vs Raydium LaunchLab

| Aspect | PumpFun | Raydium LaunchLab |
|--------|---------|-------------------|
| Chain | Solana | Solana |
| Bonding curve | Yes (graduated → Raydium pool) | Yes (graduated → Raydium pool) |
| Fee | 0.02 SOL | Variable |
| Graduation threshold | ~$69k market cap | Variable |


path: references/swap-protocol.md
content: # Swap Protocol Reference

## Atomic CLI Flow

Each step is a separate CLI command. The agent orchestrates the flow.

```
Step 1: chainstream dex route (or dex swap)
  → POST /v2/dex/:chain/route (or /swap)
  → Returns: { routeInfo, serializedTx: base64, elapsedTime }
  → serializedTx is UNSIGNED

Step 2: Agent presents routeInfo to user, waits for confirmation

Step 3: chainstream wallet sign --chain <chain> --tx <serializedTx>
  → Signs locally (TEE or raw key)
  → Returns: { signedTx: base64 }

Step 4: chainstream tx send --chain <chain> --signed-tx <signedTx>
  → POST /v2/transaction/:chain/send { signedTx: base64 }
  → Returns: { signature, jobId, elapsedTime }

Step 5: chainstream job status --id JOB_ID --wait
  → GET /v2/job/:id (polling) or SSE streaming
  → Returns: { status, hash, ... }
```

## DeFi API Endpoints

| Method | Path | Description |
|--------|------|-------------|
| POST | `/v2/dex/:chain/swap` | Build unsigned swap transaction |
| POST | `/v2/dex/:chain/route` | Aggregator route + build unsigned transaction |
| POST | `/v2/dex/:chain/create` | Build unsigned token creation transaction |
| POST | `/v2/transaction/:chain/send` | Broadcast signed transaction |
| GET | `/v2/transaction/:chain/gas-price` | Current gas price (EVM only) |
| POST | `/v2/transaction/:chain/estimate-gas-limit` | Estimate gas limit (EVM only) |
| GET | `/v2/job/:id` | Job status |
| GET | `/v2/job/:id/streaming` | Job status via SSE |

## Transaction Signing (Non-Custodial)

ChainStream does NOT hold wallet keys. The API returns **unsigned transactions** that must be signed locally via `wallet sign`.

**IMPORTANT: The CLI `wallet sign` command IS IMPLEMENTED and WORKING.** It supports both Turnkey (TEE-backed) and raw private key wallets.

### CLI Signing Command

```bash
# Sign a transaction using the configured wallet
npx @chainstream-io/cli wallet sign --chain sol --tx <base64-serializedTx> --json

# Output: { "signedTx": "<base64-signed-transaction>" }
```

The CLI automatically:
1. Detects wallet type (Turnkey or raw key) from `~/.config/chainstream/config.json`
2. Selects the correct signing method based on `--chain` (Solana vs EVM)
3. Returns the signed transaction in base64 format

### Wallet Types Supported

| Type | Setup | Signing Method |
|------|-------|----------------|
| Turnkey (TEE) | `chainstream login` | Remote signing via Turnkey API |
| Raw Key | `chainstream wallet set-raw --chain sol` | Local signing with private key |

### Solana

Server returns: `serializedTx` = base64-encoded `VersionedTransaction` with placeholder signatures.
CLI `wallet sign`: deserialize → sign with wallet keypair → serialize → base64.

### EVM

Server returns: `serializedTx` = base64-encoded unsigned RLP.
CLI `wallet sign`: deserialize → sign with wallet private key → encode signed RLP → base64.

## Route Parameters (POST /v2/dex/:chain/route)

| Parameter | Required | Description |
|-----------|----------|-------------|
| `chain` | Yes | sol / bsc / eth |
| `dex` | Yes | DEX protocol (e.g. jupiter, kyberswap) |
| `userAddress` | Yes | Sender wallet address |
| `inputMint` | Yes | Input token address |
| `outputMint` | Yes | Output token address |
| `amount` | Yes | Input amount (smallest unit, numeric string) |
| `swapMode` | Yes | ExactIn / ExactOut |
| `slippage` | Yes | Tolerance (0-100, integer percentage) |
| `recipientAddress` | No | Recipient if different from sender |
| `isAntiMev` | No | Enable anti-MEV protection |
| `gasPrice` | No | Gas price (EVM, numeric string) |
| `gasLimit` | No | Gas limit (EVM, numeric string) |
| `maxFeePerGas` | No | EIP-1559 max fee (EVM) |
| `maxPriorityFeePerGas` | No | EIP-1559 priority fee (EVM) |

## Swap Parameters (POST /v2/dex/:chain/swap)

| Parameter | Required | Description |
|-----------|----------|-------------|
| `chain` | Yes | sol / bsc / eth |
| `dex` | Yes | DEX protocol |
| `userAddress` | Yes | Sender wallet address |
| `inputMint` | Yes | Input token address |
| `outputMint` | Yes | Output token address |
| `amount` | Yes | Input amount (smallest unit) |
| `swapMode` | Yes | ExactIn / ExactOut |
| `slippage` | Yes | Tolerance (0-100) |

## Supported DEX Protocols

| Chain | Protocols |
|-------|-----------|
| sol | Jupiter, Raydium, Orca |
| bsc | PancakeSwap, Kyberswap, OpenOcean |
| eth | Uniswap, Kyberswap |


path: rules/execution-checklist.md
content: # Execution Checklist

Step-by-step verification for DeFi operations. Follow in order.

## Pre-Execution

- [ ] User intent is clear (which token, how much, which chain)
- [ ] Input token address validated (format matches chain)
- [ ] Output token address validated
- [ ] Chain is supported (sol/bsc/eth)
- [ ] Wallet is configured (`chainstream config auth` shows active wallet)
- [ ] Amount is reasonable (not zero, not exceeding known balance)
- [ ] Slippage is within bounds (0-100, integer percentage, e.g. 5 = 5%)

## Quote Phase

- [ ] `dex route` called successfully
- [ ] Price impact calculated and displayed
- [ ] Expected output amount shown
- [ ] Gas estimate shown (if available)
- [ ] User has reviewed the summary

## Confirmation Phase

- [ ] User explicitly confirmed (typed "y" or "yes")
- [ ] Confirmation was NOT auto-generated or implied

## Execution Phase

- [ ] `dex swap` called with confirmed parameters
- [ ] Transaction signed (TEE or local)
- [ ] Signed tx broadcast via `/v2/transaction/:chain/send`
- [ ] Job ID received

## Post-Execution

- [ ] Job polled to completion (or timeout)
- [ ] Actual fill amounts displayed (input consumed, output received)
- [ ] Block explorer link displayed
- [ ] If failed: error shown, no auto-retry


path: rules/safety-protocol.md
content: # Safety Protocol

Hard requirements for all destructive DeFi operations. These rules are NOT suggestions — they are mandatory.

## Two-Phase Confirmation

Every destructive operation (swap, bridge, create, send) MUST:

1. **Show quote/summary BEFORE execution** — price impact, slippage, gas, amounts
2. **Wait for explicit user confirmation** — "y", "yes", "confirm"
3. If user skips confirmation ("just do it"), show summary anyway and ask

## Risk Thresholds

### Price Impact

| Impact | Action |
|--------|--------|
| < 1% | Proceed normally |
| 1-5% | Warn user: "Price impact is X%, higher than typical" |
| 5-15% | Strong warning: "High price impact. You will receive significantly less." |
| > 15% | Block by default: "Extremely high price impact. Are you sure? (type YES to confirm)" |

### Slippage

| Slippage | Action |
|----------|--------|
| 0.1-1% | Normal range |
| 1-5% | Acceptable for volatile tokens |
| 5-50% | Warn: "High slippage tolerance. You may receive much less than quoted." |
| > 50% | Reject: "Slippage too high. Maximum allowed: 50%." |

## Emergency Abort

Abort and show error if:
- Wallet balance is insufficient
- Gas estimate exceeds 10% of trade value
- API returns transaction simulation failure

## Post-Trade Requirements

After every successful transaction:
1. Show actual fill amounts (not just estimated)
2. Show block explorer link
3. Show gas cost paid

## Forbidden Actions

- Auto-retry failed transactions (user must re-confirm)
- Execute multiple swaps in batch without individual confirmation
- Use funds beyond what user explicitly specified
- Skip quote phase for any reason


path: shared/authentication.md
content: # Authentication

ChainStream supports wallet signature and API key authentication. Choose the integration path that matches your agent's wallet setup.

## Agent Bootstrap Checklist

**Every ChainStream skill (data / defi / graphql) requires auth. Run these 3 steps before any API call:**

1. `npx @chainstream-io/cli config auth` — check login status
2. If NOT logged in: `npx @chainstream-io/cli login` (creates wallet + auto-grants nano trial: 50K CU free, 30 days)
3. `npx @chainstream-io/cli plan status` — verify subscription is active

After login, most new users can immediately use all API endpoints (nano trial is sufficient for typical queries). To upgrade: `bind-email` for micro (350K CU) or `plan purchase` for paid plans.

## Which Path to Use

| Your Agent Has | Integration Path | Auth | Payment Protocol |
|---------------|-----------------|------|-----------------|
| No wallet | CLI (`npx @chainstream-io/cli`) | CLI creates ChainStream Wallet (TEE-backed), signs automatically | x402 (USDC on Base/Solana) |
| Own wallet private key | CLI with `wallet set-raw` | CLI signs with imported key | x402 (USDC on Base/Solana) |
| Own wallet (embedded, MPC, etc.) | SDK (`@chainstream-io/sdk`) | Implement `WalletSigner` interface | x402 via `@x402/fetch` |
| Tempo wallet (USDC.e) | Tempo Wallet CLI (`tempo request`) | MPP 402 auto-handled | MPP (USDC.e on Tempo, chain ID 4217) |
| Dashboard API key (human user) | CLI or SDK with API Key | `X-API-KEY` header | Not applicable (pre-paid) |
| x402/MPP purchased API Key | CLI, SDK, or MCP | `X-API-KEY` header | Auto-returned on purchase |

**Supported payment chains**: Base (USDC), Solana (USDC), Tempo (USDC.e). See [shared/x402-payment.md](x402-payment.md) for protocol details.

API Key is the universal credential — works with MCP, CLI, and SDK. Agents that cannot use wallet signatures should obtain an API Key via x402 purchase, MPP purchase, or Dashboard.

## Path 1: CLI with Built-in Wallet (recommended)

For agents that don't have their own wallet. CLI creates a ChainStream TEE wallet on first login — no email, no registration form, no seed phrase.

```bash
# First time: creates EVM + Solana wallet (no email required)
npx @chainstream-io/cli login

# Output:
#   Welcome! Your ChainStream wallet has been created.
#     EVM:    0x...
#     Solana: ...

# All subsequent calls: auth + x402 payment handled automatically
npx @chainstream-io/cli token search --keyword PUMP --chain sol
```

What happens under the hood:
1. CLI generates a P-256 key pair locally (`~/.config/chainstream/keys/`)
2. Sends the public key to ChainStream auth service
3. Auth service creates a TEE-backed wallet with EVM + Solana addresses
4. CLI stores the organization ID and wallet addresses in `~/.config/chainstream/config.json`
5. All API calls use SIWX wallet signature auth; x402 payment uses EIP-3009 signed authorization

> New wallets are automatically granted a **nano trial plan** ($1, 50K CU, 30 days). No manual purchase needed — the plan is activated immediately. See [x402-payment.md](x402-payment.md#trial-plans-free-trial) for details.

### Session management

```bash
npx @chainstream-io/cli config auth              # Show auth status
npx @chainstream-io/cli config get               # Show all config
npx @chainstream-io/cli config get --key apiKey   # Show specific key
npx @chainstream-io/cli logout                    # Clear session (P-256 keys preserved)
```

### Optional: Bind email for recovery

After creating a wallet, you can optionally bind an email for account recovery. This also **auto-upgrades the trial plan to micro** ($5, 350K CU, 30 days; dedup by email — same email only grants once):

```bash
# Interactive (TTY terminal):
npx @chainstream-io/cli bind-email [REDACTED_SECRET]
# Enter verification code: xxxxxx
# Email [REDACTED_SECRET] bound successfully.

# Non-interactive (CI/CD, headless agent):
npx @chainstream-io/cli bind-email [REDACTED_SECRET]
# Output: {"otpId":"...","email":"[REDACTED_SECRET]","step":"verify"}
npx @chainstream-io/cli bind-email-verify --otp-id <otpId> --code <code> --email [REDACTED_SECRET]
```

### Optional: Email OTP login

If you prefer email-based login (e.g., to recover an existing wallet on a new device). First-time email login also auto-upgrades the trial plan to micro ($5, 350K CU; dedup by email):

```bash
# Interactive (TTY terminal):
npx @chainstream-io/cli login --email [REDACTED_SECRET]
# Enter OTP code: xxxxxx
# Logged in successfully.

# Non-interactive (CI/CD, piped, headless agent):
npx @chainstream-io/cli login [REDACTED_SECRET]
# Output: {"otpId":"...","email":"[REDACTED_SECRET]"}
npx @chainstream-io/cli verify --otp-id <otpId> --code <code> --email [REDACTED_SECRET]
```

## Path 1b: CLI with Your Own Private Key

For agents that already have a Base (EVM) or Solana private key and want to use the CLI (no wallet creation, no email):

```bash
# Import Base (EVM) private key
npx @chainstream-io/cli wallet set-raw --chain base
# Enter private key: <your hex private key>

# Import Solana private key
npx @chainstream-io/cli wallet set-raw --chain sol
# Enter private key: <your base58 private key>

# Verify addresses
npx @chainstream-io/cli wallet address
# EVM:    0xYourAddress
# Solana: YourSolanaAddress

# Set payment chain to match your funded wallet
npx @chainstream-io/cli config set --key walletChain --value base  # if paying with Base USDC
npx @chainstream-io/cli config set --key walletChain --value sol    # if paying with Solana USDC

# All commands now use your imported key for auth + x402 payment
npx @chainstream-io/cli token search --keyword PUMP --chain sol
```

The CLI will use your private key for both SIWX authentication and x402 payment. This works with any standard Base (EVM) or Solana private key.

## Path 2: SDK with Your Own Wallet (agent already has wallet)

For agents using embedded wallet providers or your wallet provider of choice, as long as it supports `signMessage` + `signTypedData`.

**Two things your wallet must support:**
- `signMessage` (EIP-191 `personal_sign`) — for SIWX authentication on every API call
- `signTypedData` (EIP-712) — for x402 payment (one-time USDC plan purchase via EIP-3009)

### Full integration example

```typescript
import { ChainStreamClient, type WalletSigner } from "@chainstream-io/sdk";
import { x402Client } from "@x402/core/client";
import { wrapFetchWithPayment } from "@x402/fetch";
import { ExactEvmScheme } from "@x402/evm/exact/client";

// ── Step 1: Create WalletSigner for API authentication ──
// Adapt this to your wallet provider
const myWallet: WalletSigner = {
  chain: "evm",
  address: "0xYourAgentWalletAddress",
  signMessage: async (msg) => {
    // Must return EIP-191 personal_sign signature (65 bytes hex with 0x prefix)
    return yourWallet.signMessage(msg);
  },
};

// ── Step 2: Create SDK client (handles SIWX auth automatically) ──
const client = new ChainStreamClient("", {
  serverUrl: "https://api.chainstream.io",
  walletSigner: myWallet,
});

// ── Step 3: Set up x402 payment (handles 402 → sign → retry) ──
// ⚠️ x402 payment involves REAL USDC transfer (EIP-3009 signTypedData).
//    Always present plan options and get user confirmation before purchase.
const x402 = new x402Client();
// Register ONE payment scheme based on your wallet's chain:
// Base (USDC) — requires signTypedData (EIP-712)
x402.register("eip155:8453", new ExactEvmScheme(yourViemCompatibleAccount));
// Solana (USDC) — requires @solana/kit signer
x402.register("solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp", new ExactSvmScheme(solanaSigner));
const x402Fetch = wrapFetchWithPayment(fetch, x402);

// ── Step 4: Purchase quota if needed ──
// First API call may return 402 if no subscription exists.
// Plan name MUST come from user's explicit selection — NEVER hardcode a plan.
// Option A: x402Fetch automates the 402 → sign → retry flow
await x402Fetch("https://api.chainstream.io/x402/purchase?plan=<USER_CHOSEN_PLAN>");
// Option B: SDK calls — catch 402, purchase, retry
try {
  const tokens = await client.token.search({ q: "PUMP", chains: ["sol"] });
} catch (err) {
  if (err.message.includes("402") || err.message.includes("PAYMENT_REQUIRED")) {
    // Fetch plans first: GET /x402/pricing → present to user → get their choice
    await x402Fetch("https://api.chainstream.io/x402/purchase?plan=<USER_CHOSEN_PLAN>");
    const tokens = await client.token.search({ q: "PUMP", chains: ["sol"] });
  }
}
```

### Compatible wallet patterns

| Wallet pattern | signMessage | signTypedData | x402 integration |
|----------|-------------|---------------|------------|
| Embedded wallet (EVM) | `yourWallet.signMessage(msg)` | `yourWallet.signTypedData(...)` | your wallet provider's x402 integration |
| MPC wallet | Provider API | Provider API | Manual integration |
| Smart contract / AA wallet | Provider signing | EIP-712 intents | Manual integration |
| Any viem LocalAccount | `account.signMessage()` | `account.signTypedData()` | Native with `ExactEvmScheme` |

Required packages: `@chainstream-io/sdk`, `@x402/core`, `@x402/fetch`, `@x402/evm`, `viem`

## Path 3: MPP with Tempo Wallet (USDC.e on Tempo chain)

For agents that have USDC.e on the Tempo blockchain (Stripe's L1, EVM-compatible, chain ID 4217). No ChainStream wallet or SIWX auth needed — MPP purchase gives you an API Key directly.

Set up Tempo Wallet by reading `https://tempo.xyz/SKILL.md` or running `npx skills add tempoxyz/docs`. Passkey auth requires a one-time browser interaction; after that the session persists for agent use.

### Quick purchase via Tempo Wallet CLI

```bash
# Set up Tempo Wallet (one-time — requires browser passkey auth)
curl -fsSL https://tempo.xyz/install | bash
tempo wallet login

# View plans (no auth required)
curl https://api.chainstream.io/mpp/pricing

# Purchase user's chosen plan — auto-handles 402 → sign → retry → returns API Key
tempo request "https://api.chainstream.io/mpp/purchase?plan=<PLAN>"
# Output: { "status": "ok", "plan": "...", "apiKey": "cs_live_...", "expiresAt": "..." }

# Set the API Key in CLI
npx @chainstream-io/cli config set --key apiKey --value cs_live_...
```

### Tempo wallet options

Tempo is EVM-compatible (chain ID 4217). Any wallet holding USDC.e on Tempo works:
- **Tempo Wallet CLI** (`tempo request`) — recommended, passkey auth, built-in MPP support
- Any EVM wallet (MetaMask, Coinbase CDP, Turnkey, Privy) — add Tempo as custom network

## Path 4: API Key (dashboard users)

For human users with a dashboard account. Read-only operations only (DeFi requires wallet).

```bash
npx @chainstream-io/cli config set --key apiKey --value <key>
```

Get a key at [app.chainstream.io](https://app.chainstream.io).

> **Note**: API Keys obtained from x402 purchase, MPP purchase, or Dashboard are interchangeable. Once you have an API Key, the payment method used to obtain it doesn't matter.

## SIWX Authentication (Standard)

All wallet-based requests use SIWX (Sign-In-With-X) authentication. SDK/CLI handles this automatically.

**How it works**: Sign a SIWE/SIWS message once → get a token valid for 1 hour → include in every request.

```
Authorization: SIWX <base64(message)>.<signature>
```

The message follows EIP-4361 (SIWE for EVM, SIWS for Solana) format:
```
api.chainstream.io wants you to sign in with your Ethereum account:
0xYourAddress

Sign in to ChainStream API

URI: https://api.chainstream.io
Version: 1
Chain ID: 8453
Nonce: <random>
Issued At: <ISO 8601>
Expiration Time: <ISO 8601, default 1h>
```

Signing method: `personal_sign` (EIP-191 for EVM, ed25519 for Solana).

SDK/CLI automatically caches the token and refreshes before expiry. Agent never needs to manage token lifecycle.

## Auth Priority

Server checks in order: SIWX → API Key → JWT Bearer.

## Check Current Subscription

```bash
# CLI (auto-detects wallet chain and address from config)
npx @chainstream-io/cli plan status

# With explicit parameters
npx @chainstream-io/cli plan status --chain evm --address 0x...

# API (no auth required)
curl "https://api.chainstream.io/x402/status?chain=evm&address=0x..."
```

Returns current plan name, quota usage (used/total CU), expiry date, and active status. See [x402-payment.md](x402-payment.md#check-current-subscription) for full response format.

## Address Linking (Cross-Chain SIWX)

When a user has wallets on multiple chains (e.g., EVM + Solana via Turnkey embedded wallet), a single x402 payment only registers SIWX auth for the paying chain. **Address Linking** allows the user to associate additional chain addresses with the same subscription, so SIWX auth works regardless of which chain they sign with.

**How it works:**

- The paying chain's address is the **primary address** that determines the `orgId`
- After payment, the CLI automatically links all other available wallet addresses to the same `orgId`
- Each linked address gets its own `x402:access:{chain}:{address}` Redis record pointing to the same `orgId`
- All addresses share the same subscription quota and expiry

**Automatic linking (CLI):** After a successful x402 purchase, the CLI automatically detects other available wallet addresses (e.g., if payment was via EVM, it finds the Solana address) and calls `POST /x402/link-address` to link them. This is transparent to the user.

**Manual linking:**

```bash
# Link your Solana address to an existing subscription
npx @chainstream-io/cli wallet link --chain solana

# Link your EVM address to an existing subscription
npx @chainstream-io/cli wallet link --chain evm
```

Requires an active API Key (`chainstream config set --key apiKey --value <key>`).

**API endpoint:** `POST /x402/link-address`

```json
{
  "chain": "solana",
  "address": "53LKjHoRGSi3...",
  "message": "<SIWX message proving ownership>",
  "signature": "<signature>"
}
```

Header: `X-[REDACTED_SECRET]`

**Supported chains:** `evm` (all EVM-compatible chains), `solana`. More chains will be added as supported.

**Storage:** Address-to-orgId mappings are stored in both Redis (hot path for auth-service) and PostgreSQL (`x402_address_link` table) for persistence. Redis can be rebuilt from DB if needed.

**API Key is always chain-agnostic.** Once you have an API Key, it works regardless of which chain was used for payment or SIWX. Address linking is specifically for users who rely on SIWX authentication across multiple chains.

## NEVER Do

- NEVER construct SIWX tokens manually — use SDK or CLI
- NEVER construct x402 `Payment-Signature` manually — use `@x402/fetch` or CLI
- NEVER expose wallet private keys in logs, command arguments, or chat messages


path: shared/chains.md
content: # Supported Chains

## Chain Matrix

| Chain | ID | Data API | DeFi API | WebSocket | DEX Protocols |
|-------|----|----------|----------|-----------|---------------|
| Solana | `sol` | Yes | Yes | Yes | Jupiter, Raydium, Orca |
| BSC | `bsc` | Yes | Yes | Yes | PancakeSwap, Kyberswap |
| Ethereum | `eth` | Yes | Yes | Yes | Uniswap, Kyberswap |
| Polygon | `polygon` | — | Bridge only | — | — |
| Arbitrum | `arbitrum` | — | Bridge only | — | — |

## Native Token Addresses

| Chain | Native Token | Address | USDC Address |
|-------|-------------|---------|--------------|
| sol | SOL | [REDACTED_SECRET] | [REDACTED_SECRET] |
| bsc | BNB | `0x0000000000000000000000000000000000000000` | `0x8ac76a51cc950d9822d68b83fe1ad97b32cd580d` |
| eth | ETH | [REDACTED_SECRET] | [REDACTED_SECRET] |

## Block Explorers

| Chain | Explorer | URL Pattern |
|-------|----------|-------------|
| sol | Solscan | `https://solscan.io/tx/{hash}` |
| bsc | BscScan | `https://bscscan.com/tx/{hash}` |
| eth | Etherscan | `https://etherscan.io/tx/{hash}` |

## Address Formats

| Chain Type | Format | Example |
|-----------|--------|---------|
| Solana | Base58, 32-44 chars | [REDACTED_SECRET] |
| EVM (bsc/eth) | `0x` + 40 hex chars | [REDACTED_SECRET] |


path: shared/error-handling.md
content: # Error Handling

## HTTP Status Codes

| Code | Meaning | Retryable | Recovery |
|------|---------|-----------|----------|
| 400 | Bad request (invalid params) | No | Fix parameters |
| 401 | Auth invalid/expired | No | First `config auth` → if not logged in, `login` (auto-grants nano trial 50K CU) → retry. If still failing, check API key: `config set --key apiKey --value <key>`. See [authentication.md](authentication.md#agent-bootstrap-checklist) |
| 402 | No quota / payment required | No | First `config auth` → `login` if needed (trial may suffice) → `plan status` → if trial exhausted, `wallet pricing` then `plan purchase`. See [x402-payment.md](x402-payment.md) |
| 404 | Resource not found | No | Verify chain/address |
| 429 | Rate limit exceeded | Yes | Exponential backoff: 1s → 2s → 4s → 8s (max 3 retries) |
| 500 | Server error | Yes | Retry once after 2s |
| 502/503 | Service unavailable | Yes | Retry after 5s |

## SDK Auto-Retry

`@chainstream-io/sdk` has built-in retry via `axios-retry`:
- Retries on 429 and 5xx
- Exponential backoff
- Max 3 retries

## DeFi-Specific Errors

| Error | Meaning | Recovery |
|-------|---------|----------|
| Transaction reverted | On-chain execution failed | Do NOT auto-retry; show error to user |
| Slippage exceeded | Price moved beyond tolerance | Re-quote with higher slippage, get fresh confirmation |
| Insufficient balance | Wallet doesn't have enough tokens | Show current balance, suggest lower amount |
| Job timeout | No on-chain confirmation within 60s | Show job ID and tx hash for manual verification |
| Invalid signature | Wallet signing failed | Check wallet config: `chainstream wallet address` or re-login: `chainstream login` |

## Rate Limits

| Plan | Requests/second |
|------|----------------|
| Free | 10 |
| Starter | 50 |
| Pro | 200 |
| Enterprise | 1000 |


path: shared/mcp-config.json
content: {
  "mcpServers": {
    "chainstream": {
      "url": "https://mcp.chainstream.io/mcp",
      "headers": {
        "X-API-KEY": "<your-api-key>"
      }
    }
  }
}


Security scan verdicts — ClawScan: clean | static analysis: clean | VirusTotal: clean | SkillSpector: suspicious (HIGH)