TradeRouter
Solana swap builder and limit-order engine.
Base URL: https://api.traderouter.ai
WebSocket: wss://api.traderouter.ai/ws
Website: https://traderouter.ai
Auth: None. No API key. Wallet address is the only identity.
Content-Type: All REST requests require Content-Type: application/json.
Before you use this skill
Maintaining the WebSocket connection: Limit orders, trailing orders, and order management (cancel, extend, list) require an open WebSocket connection to wss://api.traderouter.ai/ws. The server delivers order_filled only over that connection — if the client disconnects, it will not receive fills until it reconnects and re-registers. Keep the WS connection alive for the lifetime of any active limit/trailing orders so you can receive and execute fills. On disconnect, reconnect and re-register (see Reconnection); active orders persist server-side.
Authentication for order management: WebSocket order placement and cancellation are gated by a challenge–response flow: the server sends a challenge with a nonce; the client must sign the nonce with the wallet’s private key (Ed25519) and send register with wallet_address and the base58 signature. Only after the server responds with registered and authenticated: true can the client place or cancel orders. Authorization is proof-of-control of the wallet via the signed challenge — no separate API key.
Service origin: This skill documents the API only. The service website is https://traderouter.ai (API at api.traderouter.ai).
MEV protection: The POST /protect endpoint accepts signed transactions and uses Jito and a staked connection lane to process your transaction.
Risk: No API key is requested; identity is the wallet address (and for WebSocket orders, proof via the signed challenge).
When to use which endpoint
| User intent |
Endpoint |
Method |
| Instant buy or sell of a token |
POST /swap → sign → POST /protect |
REST |
| Check wallet token balances |
POST /holdings |
REST |
| Submit an already-signed transaction with MEV protection |
POST /protect |
REST |
| Market cap / price for token(s) |
GET /mcap?tokens=MINT1,MINT2 |
REST |
| Flex trade card image for wallet + token |
GET /flex?wallet_address=…&token_address=… |
REST |
| Limit order (take-profit, stop-loss, dip buy, breakout) |
WebSocket sell or buy action |
WS |
| Trailing stop (auto-adjust with market) |
WebSocket trailing_sell or trailing_buy |
WS |
| TWAP (time-weighted buy/sell over duration) |
WebSocket twap_buy or twap_sell |
WS |
| Manage orders (check, list, cancel, extend) |
WebSocket actions |
WS |
| DCA (recurring small buys) |
WebSocket buy orders — see DCA section below |
WS |
POST /swap — Build unsigned swap transaction
Returns an unsigned transaction (base58). Client must sign it, then submit via POST /protect.
Sell uses holdings_percentage (bps). Buy uses amount (lamports). Never mix them.
Request
{
"wallet_address": "SOLANA_PUBKEY",
"token_address": "SPL_TOKEN_MINT",
"action": "buy",
"amount": 100000000,
"slippage": 1500
}
| Field |
Type |
Required |
Notes |
| wallet_address |
string |
yes |
Solana pubkey |
| token_address |
string |
yes |
SPL token mint address |
| action |
string |
yes |
"buy" or "sell" |
| amount |
integer |
buy only |
Lamports. Only for buy. |
| holdings_percentage |
integer |
sell only |
Bps (10000 = 100%). Only for sell. |
| slippage |
integer |
no |
Bps, default 500 (5%). For low-liquidity or newly launched tokens, use 1500-2500 bps. 500 bps will often fail on memecoins. |
If both amount and holdings_percentage are sent, treat the request as invalid. The reference client blocks this locally via schema validation before network calls, and the API should return 422 for malformed payloads.
Success response
{
"status": "success",
"data": {
"swap_tx": "<base58_unsigned_transaction>",
"token_address": "SPL_TOKEN_MINT",
"pool_type": "raydium",
"pool_address": "POOL_PUBKEY",
"amount_in": 100000000,
"min_amount_out": 950000,
"price_impact": 0.5,
"slippage": 1500,
"decimals": 6
}
}
pool_type tells you which DEX the swap routes through (e.g. raydium, pumpswap, orca, meteora). Treat this field as an open enum and handle unknown values gracefully.
Error response
{
"status": "error",
"error": "Insufficient balance",
"code": 400
}
code is optional. Common: 422 (validation), 400 (bad request).
"Error running simulation" is usually an unsellable route at that moment (dead/rugged pool, zero effective balance, or no valid route). Do not loop retries — place the token on cooldown and retry later only if strategy requires.
POST /protect — Submit signed transaction (MEV protected)
Submit a signed transaction (base64). Blocks until confirmed on-chain. Returns signature and balance changes. Under the hood, the service uses Jito and a staked connection lane for MEV protection and submission.
⚠️ Set a 30-second timeout on /protect calls. This endpoint blocks until on-chain confirmation and can hang during network congestion.
⚠️ Encoding mismatch: /swap returns swap_tx as base58. /protect expects base64. You must convert — see the workflow section.
Request
{
"signed_tx_base64": "<base64_signed_transaction>"
}
Success response
{
"status": "success",
"signature": "5kyc5dMF1tybDcj8sVMZz3fCLbHYDczZ7A4mMu5JMPz1...",
"sol_balance_pre": 10399668919,
"sol_balance_post": 10399538835,
"token_balances": [
{
"mint": "FFKwi6dzaDmkGhtMDGKbt3HAyEYWk2BgwN4AwcWbbonk",
"balance": 25952334242,
"decimals": 6,
"balance_change": 2032594114,
"ui_amount_string": "25952.334242"
}
]
}
Use sol_balance_post and token_balances to update holdings after the swap.
Error handling
{"status":"error","error":"message"} — general error.
- 503 — protect endpoint not configured on server.
submitTx() handles this automatically — falls back to direct RPC. You lose MEV protection but the transaction still goes through.
- Timeout — the tx may have landed on-chain. Check tx status via RPC before retrying.
POST /holdings — Scan wallet token balances
Returns token holdings with liquid DEX pool info. Set HTTP timeout to at least 100 seconds — this endpoint scans all token accounts and can be slow.
Request
{
"wallet_address": "SOLANA_PUBKEY"
}
Response
Empty wallet: {}
Wallet with holdings:
{
"data": [
{
"address": "SPL_TOKEN_MINT",
"valueNative": 1500000000,
"amount": 25952334242,
"decimals": 6
}
]
}
/holdings is intended to return sellable tokens, but keep a defensive valueNative > MIN_VALUE_NATIVE filter (default 0, i.e. valueNative > 0) in case stale or edge-case entries appear. The reference client's getHoldings() applies this filter automatically.
GET /mcap — Market cap data
Return market cap (and optional price/pool) for given token addresses.
Request: GET https://api.traderouter.ai/mcap?tokens=MINT1,MINT2 (comma-delimited Solana mint addresses).
Response: Object keyed by token address. Each value can include marketCap, pair_address, pool_type, priceUsd. Empty object if no tokens provided or none found.
GET /flex — Flex trade card PNG
Generate a flex trade card image for a wallet and token mint.
Request: GET https://api.traderouter.ai/flex?wallet_address=WALLET&token_address=MINT.
Response: image/png. 400 on invalid params; 501 if flex_card_image deps not available; 500 on server error.
Instant swap workflow (step by step)
The encoding changes: /swap returns base58, /protect expects base64. Do not send base58 to /protect.
POST /swap with wallet_address, token_address, action, amount or holdings_percentage, slippage
- Read
data.swap_tx from response — this is base58 encoded
- Decode from base58 into raw bytes
- Deserialize as VersionedTransaction
- Sign with wallet private key
- Re-serialize the signed transaction into bytes
- Encode as base64
- Submit via
submitTx(signedBase64) — this calls /protect first (30s timeout), auto-falls back to RPC on 503
- On success:
signature = tx hash, use sol_balance_post and token_balances to update state
- On timeout:
submitTx checks if tx landed via RPC before falling back — no manual handling needed
WebSocket — Limit and trailing orders
URL: wss://api.traderouter.ai/ws
You must keep the WebSocket connection open for limit and trailing orders to work: the server sends order_filled only over this connection. If the connection drops, you will not receive fills until you reconnect and re-register. Maintain the connection for as long as you have active orders that you want to receive and execute.
Server monitors market cap every ~5 seconds. When target is crossed, server pushes order_filled with an unsigned swap transaction to sign and submit.
Reference implementation: Follow the flow below (challenge → register with signature, verification of order_filled and order_created). Use the canonical payloads, params_hash encoding, and Ed25519 verification rules in this skill as the source of truth.
Connection sequence (MUST follow this exact order)
The server sends a challenge on connect (not subscribed). Registration is challenge–response only; there is no unauthenticated path for placing orders.
- Connect to
wss://api.traderouter.ai/ws
- Server sends:
{"type": "challenge", "nonce": "<nonce>", "message": "..."}. The current protocol always sends challenge as the first message.
- Client: Sign the nonce (UTF-8 bytes) with the wallet's private key (Ed25519). You must have the wallet private key to use the WebSocket for orders; without it you cannot register successfully.
- Client sends:
{"action": "register", "wallet_address": "<SOLANA_PUBKEY>", "signature": "<base58>"}. The signature is the base58-encoded result of signing the nonce. If you omit signature after a challenge, the server responds with {"type": "error", "message": "Missing signature. Sign the challenge nonce and send register with wallet_address and signature."} and you will not be authenticated.
- Server sends:
{"type": "registered", "wallet_address": "<pubkey>", "authenticated": true}.
- Only after receiving
registered with authenticated: true may you send order actions. Sending order actions before that returns {"type": "error", "message": "Not authenticated. Register with a valid signature to place or manage orders."}.
Do NOT send any order actions before receiving {"type": "registered", "authenticated": true}. Plain {"action": "register", "wallet_address": "..."} without a signature will fail when the server has sent a challenge.
Reconnection
On WebSocket disconnect:
- Reconnect to
wss://api.traderouter.ai/ws
- Server sends a new challenge (new nonce). Send
{"action": "register", "wallet_address": "...", "signature": "<base58 of nonce signed with wallet>"}.
- Wait for
{"type": "registered", "authenticated": true}
- Check for any pending
order_filled messages
- Use the staleness check (
triggered_mcap / filled_mcap < 0.85) to skip stale fills
Active orders persist server-side — you do not need to re-place them after reconnect.
Limit sell (take-profit or stop-loss)
{
"action": "sell",
"token_address": "SPL_TOKEN_MINT",
"holdings_percentage": 10000,
"target": 20000,
"slippage": 1500,
"expiry_hours": 144
}
target (often named targetMcapBps in client code) is bps vs current mcap at order placement time (not your wallet entry price). Any value > 0. Sell target > 10000 = take-profit (e.g. 20000 = mcap doubles). Sell target < 10000 = stop-loss (e.g. 5000 = mcap halves).
Limit buy (dip buy or breakout entry)
{
"action": "buy",
"token_address": "SPL_TOKEN_MINT",
"amount": 100000000,
"target": 5000,
"slippage": 1500,
"expiry_hours": 144
}
target (often named targetMcapBps in client code) is bps vs current mcap at order placement time (not your wallet entry price). Any value > 0. Buy target < 10000** = dip buy (e.g. 5000 = mcap halves). **Buy target > 10000 = breakout entry (e.g. 20000 = mcap doubles).
Trailing sell / Trailing buy
{
"action": "trailing_sell",
"token_address": "SPL_TOKEN_MINT",
"holdings_percentage": 10000,
"trail": 1000,
"slippage": 1500,
"expiry_hours": 144
}
trail is bps — percentage callback from peak before triggering.
Example: trail: 1000 (10%). Token mcap peaks at $100k. Sell triggers when mcap drops to $90k (10% below peak). If mcap later peaks at $150k, the trigger moves up to $135k.
Replace trailing_sell with trailing_buy and holdings_percentage with amount for trailing buy. For trailing buy, the trigger works in reverse: if mcap bottoms at $50k, a 10% trail triggers when mcap rises to $55k.
Order management actions
{"action": "check_order", "order_id": "ORDER_ID"}
{"action": "list_orders"}
{"action": "cancel_order", "order_id": "ORDER_ID"}
{"action": "extend_order", "order_id": "ORDER_ID", "expiry_hours": 336}
TWAP (time-weighted average price)
twap_buy and twap_sell split a total quantity into frequency equal slices executed every duration / frequency seconds. duration is in seconds (min 60, max 30 days). There is no separate expiry — the order lives exactly duration seconds.
twap_sell: Either quantity (raw token units) or holdings_percentage (bps, e.g. 5000 = 50%). If using holdings_percentage, the server resolves it once at order creation to a fixed token amount, then divides by frequency per slice.
{
"action": "twap_sell",
"token_address": "SPL_TOKEN_MINT",
"frequency": 5,
"duration": 3600,
"holdings_percentage": 5000,
"slippage": 500
}
twap_buy: Use quantity (SOL lamports) as total to spend over the duration.
{
"action": "twap_buy",
"token_address": "SPL_TOKEN_MINT",
"frequency": 5,
"duration": 3600,
"quantity": 1000000000,
"slippage": 500
}
Server messages: twap_order_created when accepted; twap_execution for each slice (includes execution_num, executions_total, executions_remaining, next_execution_at; when status is success, data.swap_tx and server_signature — verify signature then sign and submit like order_filled); twap_order_completed when all slices are done. On cancel_order for a TWAP order, server responds with twap_order_cancelled. Verify twap_execution.server_signature (same trust anchor as order_filled; MCP may use a dedicated signer for the twap slice payload) before signing/submitting each slice.
Order expiry
Orders silently expire when expiry_hours is reached — the server does not send an expiry event. To detect expired orders, periodically call check_order or list_orders. Expired orders will no longer appear in results.
All WebSocket actions reference
| Action |
Required fields |
Optional |
| register |
wallet_address |
signature (required when server sent challenge; base58 of nonce signed with wallet) |
| sell |
token_address, holdings_percentage (bps), target, slippage |
expiry_hours (default 144), wallet_address |
| buy |
token_address, amount (lamports), target, slippage |
expiry_hours, wallet_address |
| trailing_sell |
token_address, holdings_percentage, trail (bps), slippage |
expiry_hours |
| trailing_buy |
token_address, amount, trail (bps), slippage |
expiry_hours |
| check_order |
order_id |
— |
| list_orders |
— |
wallet_address |
| cancel_order |
order_id |
— |
| extend_order |
order_id, expiry_hours (max 336) |
— |
| twap_sell |
token_address, frequency, duration, quantity or holdings_percentage (bps) |
slippage (default 500) |
| twap_buy |
token_address, frequency, duration, quantity (SOL lamports) |
slippage (default 500) |
expiry_hours: default 144, max 336.
Server → client message types
| type |
Payload fields |
Description |
| challenge |
nonce, message |
Sent on connect; client must sign nonce and send register with wallet_address + signature |
| registered |
wallet_address, authenticated |
Registration confirmed; only when authenticated true can client send order actions |
| order_created |
order_id, order_type, token_address, entry_mcap, target_mcap, target_bps (limit), trail_bps (trailing), slippage, expiry_hours, amount, holdings_percentage, params_hash, server_signature |
Order accepted; when params_hash and server_signature are present, verify server_signature over params_hash (Rec 2) — see Verifying server signatures |
| order_filled |
order_id, order_type, status, token_address, entry_mcap, triggered_mcap, filled_mcap, target_mcap, triggered_at, filled_at, server_signature, already_dispatched, data (optional; when already_dispatched false: data.swap_tx base58) |
Target hit — verify server_signature, then sign data.swap_tx and submit; when already_dispatched true, data/swap_tx may be omitted (idempotent ack) |
| twap_order_created |
order_id, order_type, token_address, frequency, duration, interval_seconds, amount_per_execution, original_quantity, expires_at, slippage, holdings_percentage (optional) |
TWAP order accepted |
| twap_execution |
order_id, order_type, status, token_address, execution_num, executions_total, executions_remaining, next_execution_at, server_signature, data (optional), error (optional) |
One TWAP slice — verify server_signature, then sign data.swap_tx and submit when status success |
| twap_order_completed |
order_id, order_type, token_address, executions_completed, status |
All TWAP slices done |
| twap_order_cancelled |
order_id, status |
TWAP order cancelled (response to cancel_order) |
| order_status |
order_id, status |
Response to check_order |
| order_list |
orders[] |
Response to list_orders |
| order_cancelled |
order_id |
Order cancelled |
| order_extended |
order_id |
TTL extended |
| error |
message |
Error description |
| heartbeat |
— |
Keepalive, ignore |
WebSocket authentication (required for orders)
The server sends a challenge with a nonce on connect. To place or manage orders you must:
- Sign the nonce (as UTF-8 bytes) with the wallet's private key (Ed25519).
- Send one message:
{"action": "register", "wallet_address": "<pubkey>", "signature": "<base58 signature>"}. There is no separate auth action — the signature is sent in the same register message.
- Wait for
{"type": "registered", "authenticated": true}. Only then send order actions.
If you send register without signature after a challenge, the server responds with an error and does not set authenticated: true. Unauthenticated sessions cannot place or manage orders.
Verifying server signatures (order_filled and order_created)
Trust anchor — do not fetch from the server. The server public key must be a hardcoded or preconfigured trust anchor. Never fetch it from the same server at runtime (e.g. GET /security) to verify that server's messages; that is a TOCTOU vulnerability. Use a hardcoded default and allow override via TRADEROUTER_SERVER_PUBKEY (base58). Use this key to verify all server signatures (Ed25519, base58 decode key and signature).
Key rotation: Support a second key via TRADEROUTER_SERVER_PUBKEY_NEXT. On verification failure with the current key, try the next key; if the next key succeeds, the server has rotated — update your primary key and treat the order as valid. Document rotation at https://api.traderouter.ai/security.
Rejection when signature is required: The server may require a valid server_signature on every order_filled (TRADEROUTER_REQUIRE_SERVER_SIGNATURE, default true). For order_created, clients can require a params commitment (TRADEROUTER_REQUIRE_ORDER_CREATED_SIGNATURE, default true); if required and the server omits params_hash/server_signature, reject the order. If signature is present but verification fails, reject the fill or order.
order_filled.server_signature: The server signs a canonical JSON payload. Build the payload from the message using only these keys (include a key only if present and not null): order_id, order_type, status, token_address, entry_mcap, triggered_mcap, filled_mcap, target_mcap, triggered_at, filled_at, data. Serialize with sorted keys (recursive for nested objects) and no extra whitespace, and ensure_ascii (escape non-ASCII as \uXXXX); e.g. Python: json.dumps(payload, sort_keys=True, separators=(",", ":"), ensure_ascii=True); then SHA-256 of the UTF-8 bytes. The server's Ed25519 signature (base58) is over this digest. Verify with the server public key (base58 decode key and signature, verify digest with Ed25519). Always verify before signing or submitting the fill. If verification fails or server_signature is missing when the server is expected to send it, do not sign/submit. If already_dispatched is true, skip sign/submit (idempotent ack).
order_created.server_signature (Rec 2): When the server includes params_hash and server_signature in order_created, it is committing to the order parameters. The params_hash is the SHA-256 hex of a pipe-delimited canonical string: for limit orders order_id|token_address|order_type|target_bps|slippage|expiry_hours|amount|holdings_percentage; for trailing orders the same but trail_bps instead of target_bps. The server signs the digest SHA-256(params_hash_hex.encode("utf-8")). Verify with the server public key (base58 decode key and signature, verify digest with Ed25519). If present and verification fails, treat the order as untrusted.
Handling order_filled
When order_filled arrives:
- Idempotency: If
already_dispatched is true, skip sign/submit; treat as idempotent ack (fill was already sent). Log and exit.
- Verify: Verify
server_signature using the configured trust anchor (see "Verifying server signatures" above). On failure or if signature is missing when required, log and do not sign/submit.
- Read
order_id from the message — use for logging and correlation throughout
- Read
data.swap_tx — this is base58 unsigned (when already_dispatched is false; when true, data or data.swap_tx may be omitted)
- Decode from base58 into raw bytes
- Deserialize as VersionedTransaction
- Sign with client wallet
- Re-serialize signed transaction into bytes
- Encode as base64
- Submit via
submitTx(signedBase64) — handles /protect + fallback internally
- Log
order_id + signature together for audit trail
- Use response to update holdings
Idempotency: Duplicate or late order_filled messages may have already_dispatched: true and no data.swap_tx; skip sign/submit and update local state only.
Logging: For each order_filled, log at least: received (order_id, order_type, token); if skipped (already_dispatched or verify failed) log reason; on submit log order_id + signature for audit.
⚠️ filled_mcap can be 0 or null. If triggered_mcap exists but filled_mcap is 0/null, the fill is still valid — the transaction will work, but mcap data at fill time is unreliable. Don't reject fills based on filled_mcap alone.
Staleness check: Apply to every order_filled, not only after reconnect. If triggered_mcap and filled_mcap are both present and filled_mcap > 0, and triggered_mcap / filled_mcap < 0.85, treat the fill as stale and consider skipping (do not sign/submit). Divide-by-zero: If filled_mcap is 0 or null, do not apply the ratio; the fill is not stale by this check. Proceed with verification and sign/submit as normal.
holdings_percentage resolves at execution time
For limit sell and trailing sell orders, holdings_percentage is calculated when the order triggers, not when placed. If you sell 50% of a token via instant swap, a pending order with holdings_percentage: 10000 (100%) will sell 100% of the remaining balance, not the original amount. This is a feature — it accounts for partial sells between placement and execution.
DCA (Dollar-Cost Averaging)
DCA is implemented as repeated limit buy orders. It is not automatic chaining — each fill requires agent action:
- Place a
buy order via WebSocket with the desired amount and target
- When
order_filled arrives, sign the swap_tx and submit via submitTx() (follow the base58→base64 steps above)
- After successful submission, place the next
buy order
- Repeat for as many intervals as desired
The server does not auto-chain orders. Each fill triggers order_filled, the agent must sign + submit, then explicitly place the next order.
Troubleshooting
| Issue |
Fix |
| /holdings times out |
Set HTTP timeout to at least 100 seconds. |
| /protect hangs |
Set a 30s timeout. On timeout, check tx status via RPC before retrying — tx may have landed. |
| /protect returns 503 |
submitTx() auto-falls back to RPC. No manual action needed. |
| 422 from /swap |
Invalid payload (missing fields or mixed buy/sell params). Sell needs: wallet_address, token_address, action, holdings_percentage. Buy needs: wallet_address, token_address, action, amount. |
| "Error running simulation" from /swap |
Route is unsellable now (dead/rugged pool, zero effective balance, or route failure). Put token on cooldown; avoid tight retry loops. |
| Swap fails on-chain |
Increase slippage (1500-2500 bps for memecoins), check SOL balance for fees, verify token/pool exists. |
| No order_filled received |
Verify register was sent, {"type":"registered"} received, and authenticated: true is set. A session that registered without a valid signature will receive registered with authenticated: false and will not receive fills — check this field first. Wallet must match. |
| WebSocket disconnects |
Reconnect, re-register with signature, check for pending fills. Active orders persist server-side. |
| Sell fails on token from /holdings |
Keep defensive filter valueNative > MIN_VALUE_NATIVE (> 0 by default) and verify balance/pool just before sell. |
| filled_mcap is 0 or null |
Fill is still valid. Execute normally — mcap data is unreliable but tx works. |
| Order seems to have disappeared |
Orders silently expire at expiry_hours. Use list_orders to check. |
Request pacing / rate limits
No hard limits are documented in this skill. Use conservative client pacing defaults unless the API owner gives stricter numbers:
- REST (
/swap, /protect, /holdings): target <= 2 requests/sec sustained per wallet (short bursts <= 5).
- WebSocket mutating actions (
buy, sell, trailing_*, cancel_order, extend_order): target <= 5 messages/sec per wallet.
- On 429 or repeated 5xx: exponential backoff with jitter (1s, 2s, 4s, cap 30s).
- Never tight-loop retries on the same token after
"Error running simulation"; honor cooldown first.
Important rules
- No API key needed. Wallet address is the only identity.
- Never expose private keys. Sign only in a secure client environment.
- Keep WebSocket connection open for limit/trailing orders. Fills are delivered only over the open WS; disconnect means you miss fills until you reconnect and re-register.
- Register with signature on WebSocket. Server sends challenge; sign nonce and send register with wallet_address + signature. No orders before
{"type":"registered","authenticated":true}.
- Sell = holdings_percentage. Buy = amount. Do not mix these parameters.
- Target basis: WS
target is relative to current mcap at order placement, not to your wallet entry price.
- Encoding: /swap returns base58, /protect expects base64. Decode → deserialize → sign → serialize → encode base64.
- Slippage: Default 500 (5%). Use 1500-2500 bps for low-liquidity or newly launched tokens. 500 bps will fail on most memecoins.
- Set timeouts: 30s on /protect, 100s on /holdings.
- All transactions from the API are unsigned. Client always signs.
- Always submit via
submitTx(). This function enforces /protect first for MEV protection. RPC fallback is internal and only fires on 503 or timeout. Never call connection.sendRawTransaction() directly.
- Unsellable routes: "Error running simulation" should trigger cooldown, not spam retries.
- Holdings filtering: Keep
valueNative > MIN_VALUE_NATIVE (> 0 by default) as a defensive guard before sells. The reference client's getHoldings() does this automatically.
- Order expiry is silent. Server does not notify. Poll
list_orders to detect.
Definition of Done
An agent is production-ready only when it can execute all of the following with zero manual steps:
Canonical Stack
Reference implementation: The skill text above is the source of truth for WebSocket challenge–response, verification, and params_hash. Python clients can use: solders (Keypair, VersionedTransaction), websockets, httpx, cryptography (Ed25519), base58.
Node.js (skill examples): Pin these versions unless explicitly tested.
Runtime: Node.js 20 LTS
crypto: built-in (createHash for SHA-256; no npm install)
web3.js: @solana/web3.js@1.95.8
bs58: bs58@6.0.0
ws: ws@8.18.0
ajv: ajv@8.17.1
tweetnacl: tweetnacl@1.0.3
npm init -y
npm pkg set type=module
npm install @solana/web3.js@1.95.8 bs58@6.0.0 ws@8.18.0 ajv@8.17.1 tweetnacl@1.0.3
The type=module line is required. All code below uses ESM imports and top-level await, which fail under CommonJS.
Python: solders, websockets, httpx, cryptography, base58. Encoding and verification logic are identical across runtimes; only library names differ.
Reference Client
Minimal copy-paste implementation. Everything is in this one code block — safety guards, logging, kill switch, dry-run gating. There are no separate code blocks to wire in. The reference client uses ajv to validate requests before sending them. The inline schemas enforce the minimum required fields for each call; the Request/Response Schemas section below has the full payload definitions.
One submission function: All transactions go through submitTx(). This function tries /protect first (MEV-protected), and only falls back to direct RPC on 503 or timeout. There is no separate RPC submission function — the fallback is internal. Never call connection.sendRawTransaction() directly.
import { Connection, Keypair, VersionedTransaction } from '@solana/web3.js';
import bs58 from 'bs58';
import WebSocket from 'ws';
import Ajv from 'ajv';
import nacl from 'tweetnacl';
import { createHash } from 'crypto';
const API = 'https://api.traderouter.ai';
const WS_URL = 'wss://api.traderouter.ai/ws';
const RPC_URL = process.env.RPC_URL || 'https://api.mainnet-beta.solana.com';
const connection = new Connection(RPC_URL, 'confirmed');
// SAFE-BY-DEFAULT: DRY_RUN is true unless you explicitly set DRY_RUN=false to go live.
const DRY_RUN = process.env.DRY_RUN !== 'false';
// Trust anchor: hardcoded or loaded from env. NEVER fetch from the server at runtime.
const SERVER_PUBKEY_BYTES = bs58.decode(
process.env.TRADEROUTER_SERVER_PUBKEY || 'EXX3nRzfDUvbjZSmxFzHDdiSYeGVP1EGr77iziFZ4Jd4'
);
const SERVER_PUBKEY_NEXT_BYTES = process.env.TRADEROUTER_SERVER_PUBKEY_NEXT
? bs58.decode(process.env.TRADEROUTER_SERVER_PUBKEY_NEXT)
: null;
const REQUIRE_SERVER_SIGNATURE = process.env.TRADEROUTER_REQUIRE_SERVER_SIGNATURE !== 'false';
// ---------- Schema Validation (AJV, enforced at runtime) ----------
const ajv = new Ajv({ allErrors: true, strict: false });
const swapRequestSchema = {
type: 'object',
required: ['wallet_address', 'token_address', 'action'],
properties: {
wallet_address: { type: 'string', minLength: 32, maxLength: 44 },
token_address: { type: 'string', minLength: 32, maxLength: 44 },
action: { type: 'string', enum: ['buy', 'sell'] },
amount: { type: 'integer', minimum: 1 },
holdings_percentage: { type: 'integer', minimum: 1, maximum: 10000 },
slippage: { type: 'integer', minimum: 100, maximum: 2500 },
},
if: { properties: { action: { const: 'buy' } } },
then: { required: ['amount'], not: { required: ['holdings_percentage'] } },
else: { required: ['holdings_percentage'], not: { required: ['amount'] } },
};
const protectRequestSchema = {
type: 'object',
required: ['signed_tx_base64'],
properties: {
signed_tx_base64: { type: 'string', minLength: 100, pattern: '^[A-Za-z0-9+/]+=*$' },
},
};
// When already_dispatched is true, server omits data or data.swap_tx; schema must allow that.
const orderFilledSchema = {
type: 'object',
required: ['type', 'order_id', 'order_type', 'status'],
properties: {
type: { const: 'order_filled' },
order_id: { type: 'string' },
order_type: { type: 'string', enum: ['sell', 'buy', 'trailing_sell', 'trailing_buy'] },
status: { type: 'string', enum: ['success'] },
already_dispatched: { type: 'boolean' },
data: {
type: 'object',
properties: {
swap_tx: { type: 'string', minLength: 100 },
token_address: { type: 'string' },
pool_type: { type: 'string' },
},
},
},
};
const validateSwapRequest = ajv.compile(swapRequestSchema);
const validateProtectRequest = ajv.compile(protectRequestSchema);
const validateOrderFilled = ajv.compile(orderFilledSchema);
function assertSchema(validateFn, payload, label) {
if (validateFn(payload)) return;
const detail = ajv.errorsText(validateFn.errors || [], { separator: '; ' });
throw new Error(`${label} validation failed: ${detail}`);
}
// ---------- Logging (JSON lines, one line per event) ----------
function log(fields) {
console.log(JSON.stringify({ ts: new Date().toISOString(), wallet: _wallet?.publicKey?.toBase58() || 'unknown', ...fields }));
}
// ---------- Safety Guards (enforced in buildSwap + submitTx) ----------
const SAFETY = {
MAX_BUY_LAMPORTS: 500_000_000, // 0.5 SOL max per buy (conservative starter)
MAX_SLIPPAGE_BPS: 2500, // 25% absolute ceiling
MIN_SLIPPAGE_BPS: 100, // 1% floor
MIN_VALUE_NATIVE: 0, // defensive min valueNative to attempt sell (> 0)
MAX_RETRIES_PER_TOKEN: 2, // don't hammer unsellable routes
UNSWAPPABLE_COOLDOWN_MS: 15 * 60 * 1000, // 15m cooldown for transient unsellable routes
MAX_DAILY_LOSS_LAMPORTS: 2_000_000_000, // 2 SOL daily loss limit
DENYLIST: new Map(), // token mint -> retry_after_epoch_ms (session-scoped)
dailyLoss: 0, // tracked across swaps
};
let KILL_SWITCH = false; // set true to halt all execution immediately
function isTokenOnCooldown(tokenAddress) {
const retryAfter = SAFETY.DENYLIST.get(tokenAddress);
if (!retryAfter) return false;
if (Date.now() >= retryAfter) {
SAFETY.DENYLIST.delete(tokenAddress);
return false;
}
return true;
}
function enforceSafety(action, tokenAddress, amount, slippage) {
if (KILL_SWITCH) throw new Error('KILL_SWITCH is active — all execution halted');
if (isTokenOnCooldown(tokenAddress)) {
const retryAfter = SAFETY.DENYLIST.get(tokenAddress);
log({ step: 'safety_blocked', token: tokenAddress, reason: 'cooldown_active', retry_after_ms: retryAfter });
throw new Error(`${tokenAddress} is on cooldown until ${new Date(retryAfter).toISOString()}`);
}
if (slippage > SAFETY.MAX_SLIPPAGE_BPS) throw new Error(`slippage ${slippage} exceeds max ${SAFETY.MAX_SLIPPAGE_BPS}`);
if (slippage < SAFETY.MIN_SLIPPAGE_BPS) throw new Error(`slippage ${slippage} below min ${SAFETY.MIN_SLIPPAGE_BPS}`);
if (action === 'buy' && amount > SAFETY.MAX_BUY_LAMPORTS) throw new Error(`amount ${amount} exceeds max ${SAFETY.MAX_BUY_LAMPORTS}`);
if (SAFETY.dailyLoss > SAFETY.MAX_DAILY_LOSS_LAMPORTS) {
KILL_SWITCH = true;
throw new Error('daily loss limit reached — KILL_SWITCH activated');
}
}
function markUnswappable(tokenAddress, errorMessage) {
const retryAfter = Date.now() + SAFETY.UNSWAPPABLE_COOLDOWN_MS;
SAFETY.DENYLIST.set(tokenAddress, retryAfter);
log({ step: 'safety_blocked', token: tokenAddress, reason: 'cooldown_set', retry_after_ms: retryAfter, source_error: errorMessage });
}
// ---------- Wallet (lazy init) ----------
let _wallet = null;
function getWallet() {
if (!_wallet) {
if (!process.env.PRIVATE_KEY) throw new Error('PRIVATE_KEY env var not set');
try {
_wallet = Keypair.fromSecretKey(bs58.decode(process.env.PRIVATE_KEY));
} catch (e) {
throw new Error(`Invalid PRIVATE_KEY: ${e.message}`);
}
}
return _wallet;
}
// ---------- Server Signature Verification ----------
// Canonical JSON for server signature: recursive sort_keys + ensure_ascii.
function canonicalizeForSigning(value) {
if (Array.isArray(value)) return value.map(canonicalizeForSigning);
if (value && typeof value === 'object') {
const out = {};
for (const key of Object.keys(value).sort()) out[key] = canonicalizeForSigning(value[key]);
return out;
}
return value;
}
function canonicalJsonPythonStyle(obj) {
const canonicalObj = canonicalizeForSigning(obj);
const json = JSON.stringify(canonicalObj);
return json.replace
…(truncated)
1---
2name: traderouter
3description: >
4 Solana swap execution, MEV-protected transaction submission, wallet scanning, and market-cap-based
5 limit/trailing orders via the TradeRouter API. Use when the user wants to: swap SPL tokens on Solana
6 (buy or sell), check wallet token holdings, submit signed transactions through an MEV-protected
7 priority lane, place limit orders (buy/sell at a target market cap), set trailing stop orders
8 (trailing_sell/trailing_buy), manage existing orders (check, list, cancel, extend), or implement
9 DCA strategies. No API key required — wallet address is the only identity. Supports REST endpoints
10 POST /swap, POST /holdings, POST /protect, and WebSocket wss://api.traderouter.ai/ws for limit orders.
11metadata:
12 source: https://skillmd.com/skills/modbender/traderouter
13---
14
15# TradeRouter
16
17Solana swap builder and limit-order engine.
18
19**Base URL:** `https://api.traderouter.ai`
20**WebSocket:** `wss://api.traderouter.ai/ws`
21**Website:** https://traderouter.ai
22**Auth:** None. No API key. Wallet address is the only identity.
23**Content-Type:** All REST requests require `Content-Type: application/json`.
24
25---
26
27## Before you use this skill
28
29**Maintaining the WebSocket connection:** Limit orders, trailing orders, and order management (cancel, extend, list) require an **open WebSocket connection** to `wss://api.traderouter.ai/ws`. The server delivers `order_filled` only over that connection — if the client disconnects, it will not receive fills until it reconnects and re-registers. Keep the WS connection alive for the lifetime of any active limit/trailing orders so you can receive and execute fills. On disconnect, reconnect and re-register (see Reconnection); active orders persist server-side.
30
31**Authentication for order management:** WebSocket order placement and cancellation are gated by a **challenge–response flow**: the server sends a challenge with a nonce; the client must **sign the nonce** with the wallet’s private key (Ed25519) and send `register` with `wallet_address` and the base58 signature. Only after the server responds with `registered` and `authenticated: true` can the client place or cancel orders. Authorization is **proof-of-control** of the wallet via the signed challenge — no separate API key.
32
33**Service origin:** This skill documents the API only. The service website is **https://traderouter.ai** (API at api.traderouter.ai).
34
35**MEV protection:** The `POST /protect` endpoint accepts signed transactions and uses **Jito** and a **staked connection lane** to process your transaction.
36
37**Risk:** No API key is requested; identity is the wallet address (and for WebSocket orders, proof via the signed challenge).
38
39---
40
41## When to use which endpoint
42
43| User intent | Endpoint | Method |
44|-------------|----------|--------|
45| Instant buy or sell of a token | `POST /swap` → sign → `POST /protect` | REST |
46| Check wallet token balances | `POST /holdings` | REST |
47| Submit an already-signed transaction with MEV protection | `POST /protect` | REST |
48| Market cap / price for token(s) | `GET /mcap?tokens=MINT1,MINT2` | REST |
49| Flex trade card image for wallet + token | `GET /flex?wallet_address=…&token_address=…` | REST |
50| Limit order (take-profit, stop-loss, dip buy, breakout) | WebSocket `sell` or `buy` action | WS |
51| Trailing stop (auto-adjust with market) | WebSocket `trailing_sell` or `trailing_buy` | WS |
52| TWAP (time-weighted buy/sell over duration) | WebSocket `twap_buy` or `twap_sell` | WS |
53| Manage orders (check, list, cancel, extend) | WebSocket actions | WS |
54| DCA (recurring small buys) | WebSocket `buy` orders — see DCA section below | WS |
55
56---
57
58## POST /swap — Build unsigned swap transaction
59
60Returns an **unsigned** transaction (base58). Client must sign it, then submit via `POST /protect`.
61
62**Sell uses `holdings_percentage` (bps). Buy uses `amount` (lamports). Never mix them.**
63
64### Request
65
66```json
67{
68 "wallet_address": "SOLANA_PUBKEY",
69 "token_address": "SPL_TOKEN_MINT",
70 "action": "buy",
71 "amount": 100000000,
72 "slippage": 1500
73}
74```
75
76| Field | Type | Required | Notes |
77|-------|------|----------|-------|
78| wallet_address | string | yes | Solana pubkey |
79| token_address | string | yes | SPL token mint address |
80| action | string | yes | `"buy"` or `"sell"` |
81| amount | integer | buy only | Lamports. **Only for buy.** |
82| holdings_percentage | integer | sell only | Bps (10000 = 100%). **Only for sell.** |
83| slippage | integer | no | Bps, default 500 (5%). **For low-liquidity or newly launched tokens, use 1500-2500 bps.** 500 bps will often fail on memecoins. |
84
85If both `amount` and `holdings_percentage` are sent, treat the request as invalid. The reference client blocks this locally via schema validation before network calls, and the API should return 422 for malformed payloads.
86
87### Success response
88
89```json
90{
91 "status": "success",
92 "data": {
93 "swap_tx": "<base58_unsigned_transaction>",
94 "token_address": "SPL_TOKEN_MINT",
95 "pool_type": "raydium",
96 "pool_address": "POOL_PUBKEY",
97 "amount_in": 100000000,
98 "min_amount_out": 950000,
99 "price_impact": 0.5,
100 "slippage": 1500,
101 "decimals": 6
102 }
103}
104```
105
106`pool_type` tells you which DEX the swap routes through (e.g. `raydium`, `pumpswap`, `orca`, `meteora`). Treat this field as an open enum and handle unknown values gracefully.
107
108### Error response
109
110```json
111{
112 "status": "error",
113 "error": "Insufficient balance",
114 "code": 400
115}
116```
117
118`code` is optional. Common: 422 (validation), 400 (bad request).
119
120**"Error running simulation"** is usually an unsellable route at that moment (dead/rugged pool, zero effective balance, or no valid route). Do not loop retries — place the token on cooldown and retry later only if strategy requires.
121
122---
123
124## POST /protect — Submit signed transaction (MEV protected)
125
126Submit a **signed** transaction (**base64**). Blocks until confirmed on-chain. Returns signature and balance changes. Under the hood, the service uses **Jito** and a **staked connection lane** for MEV protection and submission.
127
128**⚠️ Set a 30-second timeout on /protect calls.** This endpoint blocks until on-chain confirmation and can hang during network congestion.
129
130**⚠️ Encoding mismatch:** `/swap` returns `swap_tx` as **base58**. `/protect` expects **base64**. You must convert — see the workflow section.
131
132### Request
133
134```json
135{
136 "signed_tx_base64": "<base64_signed_transaction>"
137}
138```
139
140### Success response
141
142```json
143{
144 "status": "success",
145 "signature": "5kyc5dMF1tybDcj8sVMZz3fCLbHYDczZ7A4mMu5JMPz1...",
146 "sol_balance_pre": 10399668919,
147 "sol_balance_post": 10399538835,
148 "token_balances": [
149 {
150 "mint": "FFKwi6dzaDmkGhtMDGKbt3HAyEYWk2BgwN4AwcWbbonk",
151 "balance": 25952334242,
152 "decimals": 6,
153 "balance_change": 2032594114,
154 "ui_amount_string": "25952.334242"
155 }
156 ]
157}
158```
159
160Use `sol_balance_post` and `token_balances` to update holdings after the swap.
161
162### Error handling
163
164- `{"status":"error","error":"message"}` — general error.
165- **503** — protect endpoint not configured on server. `submitTx()` handles this automatically — falls back to direct RPC. You lose MEV protection but the transaction still goes through.
166- **Timeout** — the tx may have landed on-chain. Check tx status via RPC before retrying.
167
168---
169
170## POST /holdings — Scan wallet token balances
171
172Returns token holdings with liquid DEX pool info. **Set HTTP timeout to at least 100 seconds** — this endpoint scans all token accounts and can be slow.
173
174### Request
175
176```json
177{
178 "wallet_address": "SOLANA_PUBKEY"
179}
180```
181
182### Response
183
184Empty wallet: `{}`
185
186Wallet with holdings:
187
188```json
189{
190 "data": [
191 {
192 "address": "SPL_TOKEN_MINT",
193 "valueNative": 1500000000,
194 "amount": 25952334242,
195 "decimals": 6
196 }
197 ]
198}
199```
200
201`/holdings` is intended to return sellable tokens, but keep a defensive `valueNative > MIN_VALUE_NATIVE` filter (default `0`, i.e. `valueNative > 0`) in case stale or edge-case entries appear. The reference client's `getHoldings()` applies this filter automatically.
202
203---
204
205## GET /mcap — Market cap data
206
207Return market cap (and optional price/pool) for given token addresses.
208
209**Request:** `GET https://api.traderouter.ai/mcap?tokens=MINT1,MINT2` (comma-delimited Solana mint addresses).
210
211**Response:** Object keyed by token address. Each value can include `marketCap`, `pair_address`, `pool_type`, `priceUsd`. Empty object if no tokens provided or none found.
212
213---
214
215## GET /flex — Flex trade card PNG
216
217Generate a flex trade card image for a wallet and token mint.
218
219**Request:** `GET https://api.traderouter.ai/flex?wallet_address=WALLET&token_address=MINT`.
220
221**Response:** `image/png`. 400 on invalid params; 501 if flex_card_image deps not available; 500 on server error.
222
223---
224
225## Instant swap workflow (step by step)
226
227**The encoding changes: /swap returns base58, /protect expects base64.** Do not send base58 to /protect.
228
2291. `POST /swap` with wallet_address, token_address, action, amount or holdings_percentage, slippage
2302. Read `data.swap_tx` from response — this is **base58** encoded
2313. **Decode** from base58 into raw bytes
2324. **Deserialize** as VersionedTransaction
2335. **Sign** with wallet private key
2346. **Re-serialize** the signed transaction into bytes
2357. **Encode** as **base64**
2368. Submit via `submitTx(signedBase64)` — this calls `/protect` first (30s timeout), auto-falls back to RPC on 503
2379. On success: `signature` = tx hash, use `sol_balance_post` and `token_balances` to update state
23810. On timeout: `submitTx` checks if tx landed via RPC before falling back — no manual handling needed
239
240---
241
242## WebSocket — Limit and trailing orders
243
244**URL:** `wss://api.traderouter.ai/ws`
245
246**You must keep the WebSocket connection open** for limit and trailing orders to work: the server sends `order_filled` only over this connection. If the connection drops, you will not receive fills until you reconnect and re-register. Maintain the connection for as long as you have active orders that you want to receive and execute.
247
248Server monitors market cap every ~5 seconds. When target is crossed, server pushes `order_filled` with an unsigned swap transaction to sign and submit.
249
250**Reference implementation:** Follow the flow below (challenge → register with signature, verification of `order_filled` and `order_created`). Use the canonical payloads, params_hash encoding, and Ed25519 verification rules in this skill as the source of truth.
251
252### Connection sequence (MUST follow this exact order)
253
254The server sends a **challenge** on connect (not `subscribed`). Registration is **challenge–response only**; there is no unauthenticated path for placing orders.
255
2561. Connect to `wss://api.traderouter.ai/ws`
2572. **Server sends:** `{"type": "challenge", "nonce": "<nonce>", "message": "..."}`. The current protocol always sends `challenge` as the first message.
2583. **Client:** Sign the **nonce** (UTF-8 bytes) with the **wallet's private key** (Ed25519). You **must** have the wallet private key to use the WebSocket for orders; without it you cannot register successfully.
2594. **Client sends:** `{"action": "register", "wallet_address": "<SOLANA_PUBKEY>", "signature": "<base58>"}`. The signature is the base58-encoded result of signing the nonce. If you omit signature after a challenge, the server responds with `{"type": "error", "message": "Missing signature. Sign the challenge nonce and send register with wallet_address and signature."}` and you will not be authenticated.
2605. **Server sends:** `{"type": "registered", "wallet_address": "<pubkey>", "authenticated": true}`.
2616. **Only after** receiving `registered` with `authenticated: true` may you send order actions. Sending order actions before that returns `{"type": "error", "message": "Not authenticated. Register with a valid signature to place or manage orders."}`.
262
263**Do NOT send any order actions before receiving `{"type": "registered", "authenticated": true}`.** Plain `{"action": "register", "wallet_address": "..."}` without a signature will **fail** when the server has sent a challenge.
264
265### Reconnection
266
267On WebSocket disconnect:
2681. Reconnect to `wss://api.traderouter.ai/ws`
2692. Server sends a new **challenge** (new nonce). Send `{"action": "register", "wallet_address": "...", "signature": "<base58 of nonce signed with wallet>"}`.
2703. Wait for `{"type": "registered", "authenticated": true}`
2714. Check for any pending `order_filled` messages
2725. Use the staleness check (`triggered_mcap / filled_mcap < 0.85`) to skip stale fills
273
274Active orders persist server-side — you do **not** need to re-place them after reconnect.
275
276### Limit sell (take-profit or stop-loss)
277
278```json
279{
280 "action": "sell",
281 "token_address": "SPL_TOKEN_MINT",
282 "holdings_percentage": 10000,
283 "target": 20000,
284 "slippage": 1500,
285 "expiry_hours": 144
286}
287```
288
289`target` (often named `targetMcapBps` in client code) is bps vs **current mcap at order placement time** (not your wallet entry price). Any value > 0. **Sell target > 10000** = take-profit (e.g. 20000 = mcap doubles). **Sell target < 10000** = stop-loss (e.g. 5000 = mcap halves).
290
291### Limit buy (dip buy or breakout entry)
292
293```json
294{
295 "action": "buy",
296 "token_address": "SPL_TOKEN_MINT",
297 "amount": 100000000,
298 "target": 5000,
299 "slippage": 1500,
300 "expiry_hours": 144
301}
302```
303
304`target` (often named `targetMcapBps` in client code) is bps vs **current mcap at order placement time** (not your wallet entry price). Any value > 0. **Buy target < 10000** = dip buy (e.g. 5000 = mcap halves). **Buy target > 10000** = breakout entry (e.g. 20000 = mcap doubles).
305
306### Trailing sell / Trailing buy
307
308```json
309{
310 "action": "trailing_sell",
311 "token_address": "SPL_TOKEN_MINT",
312 "holdings_percentage": 10000,
313 "trail": 1000,
314 "slippage": 1500,
315 "expiry_hours": 144
316}
317```
318
319`trail` is bps — percentage callback from peak before triggering.
320
321**Example:** `trail: 1000` (10%). Token mcap peaks at $100k. Sell triggers when mcap drops to $90k (10% below peak). If mcap later peaks at $150k, the trigger moves up to $135k.
322
323Replace `trailing_sell` with `trailing_buy` and `holdings_percentage` with `amount` for trailing buy. For trailing buy, the trigger works in reverse: if mcap bottoms at $50k, a 10% trail triggers when mcap rises to $55k.
324
325### Order management actions
326
327```json
328{"action": "check_order", "order_id": "ORDER_ID"}
329{"action": "list_orders"}
330{"action": "cancel_order", "order_id": "ORDER_ID"}
331{"action": "extend_order", "order_id": "ORDER_ID", "expiry_hours": 336}
332```
333
334### TWAP (time-weighted average price)
335
336`twap_buy` and `twap_sell` split a total quantity into `frequency` equal slices executed every `duration / frequency` seconds. `duration` is in seconds (min 60, max 30 days). There is no separate expiry — the order lives exactly `duration` seconds.
337
338**twap_sell:** Either `quantity` (raw token units) or `holdings_percentage` (bps, e.g. 5000 = 50%). If using `holdings_percentage`, the server resolves it once at order creation to a fixed token amount, then divides by `frequency` per slice.
339
340```json
341{
342 "action": "twap_sell",
343 "token_address": "SPL_TOKEN_MINT",
344 "frequency": 5,
345 "duration": 3600,
346 "holdings_percentage": 5000,
347 "slippage": 500
348}
349```
350
351**twap_buy:** Use `quantity` (SOL lamports) as total to spend over the duration.
352
353```json
354{
355 "action": "twap_buy",
356 "token_address": "SPL_TOKEN_MINT",
357 "frequency": 5,
358 "duration": 3600,
359 "quantity": 1000000000,
360 "slippage": 500
361}
362```
363
364**Server messages:** `twap_order_created` when accepted; `twap_execution` for each slice (includes `execution_num`, `executions_total`, `executions_remaining`, `next_execution_at`; when `status` is `success`, `data.swap_tx` and `server_signature` — verify signature then sign and submit like `order_filled`); `twap_order_completed` when all slices are done. On `cancel_order` for a TWAP order, server responds with `twap_order_cancelled`. Verify `twap_execution.server_signature` (same trust anchor as `order_filled`; MCP may use a dedicated signer for the twap slice payload) before signing/submitting each slice.
365
366### Order expiry
367
368Orders silently expire when `expiry_hours` is reached — **the server does not send an expiry event.** To detect expired orders, periodically call `check_order` or `list_orders`. Expired orders will no longer appear in results.
369
370### All WebSocket actions reference
371
372| Action | Required fields | Optional |
373|--------|----------------|----------|
374| register | wallet_address | signature (required when server sent challenge; base58 of nonce signed with wallet) |
375| sell | token_address, holdings_percentage (bps), target, slippage | expiry_hours (default 144), wallet_address |
376| buy | token_address, amount (lamports), target, slippage | expiry_hours, wallet_address |
377| trailing_sell | token_address, holdings_percentage, trail (bps), slippage | expiry_hours |
378| trailing_buy | token_address, amount, trail (bps), slippage | expiry_hours |
379| check_order | order_id | — |
380| list_orders | — | wallet_address |
381| cancel_order | order_id | — |
382| extend_order | order_id, expiry_hours (max 336) | — |
383| twap_sell | token_address, frequency, duration, quantity or holdings_percentage (bps) | slippage (default 500) |
384| twap_buy | token_address, frequency, duration, quantity (SOL lamports) | slippage (default 500) |
385
386**expiry_hours:** default 144, max 336.
387
388### Server → client message types
389
390| type | Payload fields | Description |
391|------|----------------|-------------|
392| challenge | nonce, message | Sent on connect; client must sign nonce and send register with wallet_address + signature |
393| registered | wallet_address, authenticated | Registration confirmed; only when authenticated true can client send order actions |
394| order_created | order_id, order_type, token_address, entry_mcap, target_mcap, target_bps (limit), trail_bps (trailing), slippage, expiry_hours, amount, holdings_percentage, params_hash, server_signature | Order accepted; when params_hash and server_signature are present, verify server_signature over params_hash (Rec 2) — see Verifying server signatures |
395| order_filled | order_id, order_type, status, token_address, entry_mcap, triggered_mcap, filled_mcap, target_mcap, triggered_at, filled_at, server_signature, already_dispatched, data (optional; when already_dispatched false: data.swap_tx base58) | Target hit — verify server_signature, then sign data.swap_tx and submit; when already_dispatched true, data/swap_tx may be omitted (idempotent ack) |
396| twap_order_created | order_id, order_type, token_address, frequency, duration, interval_seconds, amount_per_execution, original_quantity, expires_at, slippage, holdings_percentage (optional) | TWAP order accepted |
397| twap_execution | order_id, order_type, status, token_address, execution_num, executions_total, executions_remaining, next_execution_at, server_signature, data (optional), error (optional) | One TWAP slice — verify server_signature, then sign data.swap_tx and submit when status success |
398| twap_order_completed | order_id, order_type, token_address, executions_completed, status | All TWAP slices done |
399| twap_order_cancelled | order_id, status | TWAP order cancelled (response to cancel_order) |
400| order_status | order_id, status | Response to check_order |
401| order_list | orders[] | Response to list_orders |
402| order_cancelled | order_id | Order cancelled |
403| order_extended | order_id | TTL extended |
404| error | message | Error description |
405| heartbeat | — | Keepalive, ignore |
406
407### WebSocket authentication (required for orders)
408
409The server sends a **challenge** with a **nonce** on connect. To place or manage orders you must:
410
4111. Sign the **nonce** (as UTF-8 bytes) with the wallet's private key (Ed25519).
4122. Send **one** message: `{"action": "register", "wallet_address": "<pubkey>", "signature": "<base58 signature>"}`. There is no separate `auth` action — the signature is sent in the same `register` message.
4133. Wait for `{"type": "registered", "authenticated": true}`. Only then send order actions.
414
415If you send `register` without `signature` after a challenge, the server responds with an error and does not set `authenticated: true`. Unauthenticated sessions cannot place or manage orders.
416
417### Verifying server signatures (order_filled and order_created)
418
419**Trust anchor — do not fetch from the server.** The server public key must be a **hardcoded or preconfigured** trust anchor. **Never** fetch it from the same server at runtime (e.g. GET /security) to verify that server's messages; that is a TOCTOU vulnerability. Use a hardcoded default and allow override via `TRADEROUTER_SERVER_PUBKEY` (base58). Use this key to verify all server signatures (Ed25519, base58 decode key and signature).
420
421**Key rotation:** Support a second key via `TRADEROUTER_SERVER_PUBKEY_NEXT`. On verification failure with the current key, try the next key; if the next key succeeds, the server has rotated — update your primary key and treat the order as valid. Document rotation at https://api.traderouter.ai/security.
422
423**Rejection when signature is required:** The server may require a valid `server_signature` on every `order_filled` (`TRADEROUTER_REQUIRE_SERVER_SIGNATURE`, default true). For `order_created`, clients can require a params commitment (`TRADEROUTER_REQUIRE_ORDER_CREATED_SIGNATURE`, default true); if required and the server omits `params_hash`/`server_signature`, reject the order. If signature is present but verification fails, reject the fill or order.
424
425**order_filled.server_signature:** The server signs a **canonical JSON** payload. Build the payload from the message using only these keys (include a key only if present and not null): `order_id`, `order_type`, `status`, `token_address`, `entry_mcap`, `triggered_mcap`, `filled_mcap`, `target_mcap`, `triggered_at`, `filled_at`, `data`. Serialize with **sorted keys (recursive for nested objects)** and no extra whitespace, and **ensure_ascii** (escape non-ASCII as `\uXXXX`); e.g. Python: `json.dumps(payload, sort_keys=True, separators=(",", ":"), ensure_ascii=True)`; then SHA-256 of the UTF-8 bytes. The server's Ed25519 signature (base58) is over this digest. Verify with the server public key (base58 decode key and signature, verify digest with Ed25519). **Always verify before signing or submitting the fill.** If verification fails or `server_signature` is missing when the server is expected to send it, do not sign/submit. If `already_dispatched` is true, skip sign/submit (idempotent ack).
426
427**order_created.server_signature (Rec 2):** When the server includes `params_hash` and `server_signature` in `order_created`, it is committing to the order parameters. The **params_hash** is the SHA-256 hex of a pipe-delimited canonical string: for limit orders `order_id|token_address|order_type|target_bps|slippage|expiry_hours|amount|holdings_percentage`; for trailing orders the same but `trail_bps` instead of `target_bps`. The server signs the digest SHA-256(params_hash_hex.encode("utf-8")). Verify with the server public key (base58 decode key and signature, verify digest with Ed25519). If present and verification fails, treat the order as untrusted.
428### Handling order_filled
429
430When `order_filled` arrives:
4311. **Idempotency:** If `already_dispatched` is true, skip sign/submit; treat as idempotent ack (fill was already sent). Log and exit.
4322. **Verify:** Verify `server_signature` using the configured trust anchor (see "Verifying server signatures" above). On failure or if signature is missing when required, log and do not sign/submit.
4333. Read `order_id` from the message — use for logging and correlation throughout
4344. Read `data.swap_tx` — this is **base58** unsigned (when `already_dispatched` is false; when true, `data` or `data.swap_tx` may be omitted)
4355. **Decode** from base58 into raw bytes
4366. **Deserialize** as VersionedTransaction
4377. **Sign** with client wallet
4388. **Re-serialize** signed transaction into bytes
4399. **Encode** as **base64**
44010. Submit via `submitTx(signedBase64)` — handles /protect + fallback internally
44111. Log `order_id` + `signature` together for audit trail
44212. Use response to update holdings
443
444**Idempotency:** Duplicate or late `order_filled` messages may have `already_dispatched: true` and no `data.swap_tx`; skip sign/submit and update local state only.
445
446**Logging:** For each `order_filled`, log at least: received (order_id, order_type, token); if skipped (already_dispatched or verify failed) log reason; on submit log order_id + signature for audit.
447
448**⚠️ `filled_mcap` can be 0 or null.** If `triggered_mcap` exists but `filled_mcap` is 0/null, the fill is still valid — the transaction will work, but mcap data at fill time is unreliable. Don't reject fills based on `filled_mcap` alone.
449
450**Staleness check:** Apply to **every** `order_filled`, not only after reconnect. If `triggered_mcap` and `filled_mcap` are both present and **filled_mcap > 0**, and `triggered_mcap / filled_mcap < 0.85`, treat the fill as stale and consider skipping (do not sign/submit). **Divide-by-zero:** If `filled_mcap` is 0 or null, do not apply the ratio; the fill is not stale by this check. Proceed with verification and sign/submit as normal.
451
452### `holdings_percentage` resolves at execution time
453
454For limit sell and trailing sell orders, `holdings_percentage` is calculated **when the order triggers**, not when placed. If you sell 50% of a token via instant swap, a pending order with `holdings_percentage: 10000` (100%) will sell 100% of the *remaining* balance, not the original amount. This is a feature — it accounts for partial sells between placement and execution.
455
456---
457
458## DCA (Dollar-Cost Averaging)
459
460DCA is implemented as repeated limit buy orders. It is **not automatic chaining** — each fill requires agent action:
461
4621. Place a `buy` order via WebSocket with the desired `amount` and `target`
4632. When `order_filled` arrives, sign the `swap_tx` and submit via `submitTx()` (follow the base58→base64 steps above)
4643. After successful submission, place the **next** `buy` order
4654. Repeat for as many intervals as desired
466
467The server does not auto-chain orders. Each fill triggers `order_filled`, the agent must sign + submit, then explicitly place the next order.
468
469---
470
471## Troubleshooting
472
473| Issue | Fix |
474|-------|-----|
475| /holdings times out | Set HTTP timeout to at least 100 seconds. |
476| /protect hangs | Set a 30s timeout. On timeout, check tx status via RPC before retrying — tx may have landed. |
477| /protect returns 503 | `submitTx()` auto-falls back to RPC. No manual action needed. |
478| 422 from /swap | Invalid payload (missing fields or mixed buy/sell params). Sell needs: wallet_address, token_address, action, holdings_percentage. Buy needs: wallet_address, token_address, action, amount. |
479| "Error running simulation" from /swap | Route is unsellable now (dead/rugged pool, zero effective balance, or route failure). Put token on cooldown; avoid tight retry loops. |
480| Swap fails on-chain | Increase slippage (1500-2500 bps for memecoins), check SOL balance for fees, verify token/pool exists. |
481| No order_filled received | Verify register was sent, `{"type":"registered"}` received, and `authenticated: true` is set. A session that registered without a valid signature will receive `registered` with `authenticated: false` and will not receive fills — check this field first. Wallet must match. |
482| WebSocket disconnects | Reconnect, re-register with signature, check for pending fills. Active orders persist server-side. |
483| Sell fails on token from /holdings | Keep defensive filter `valueNative > MIN_VALUE_NATIVE` (`> 0` by default) and verify balance/pool just before sell. |
484| filled_mcap is 0 or null | Fill is still valid. Execute normally — mcap data is unreliable but tx works. |
485| Order seems to have disappeared | Orders silently expire at `expiry_hours`. Use `list_orders` to check. |
486
487---
488
489## Request pacing / rate limits
490
491No hard limits are documented in this skill. Use conservative client pacing defaults unless the API owner gives stricter numbers:
492
493- REST (`/swap`, `/protect`, `/holdings`): target <= 2 requests/sec sustained per wallet (short bursts <= 5).
494- WebSocket mutating actions (`buy`, `sell`, `trailing_*`, `cancel_order`, `extend_order`): target <= 5 messages/sec per wallet.
495- On 429 or repeated 5xx: exponential backoff with jitter (1s, 2s, 4s, cap 30s).
496- Never tight-loop retries on the same token after `"Error running simulation"`; honor cooldown first.
497
498---
499
500## Important rules
501
502- **No API key needed.** Wallet address is the only identity.
503- **Never expose private keys.** Sign only in a secure client environment.
504- **Keep WebSocket connection open for limit/trailing orders.** Fills are delivered only over the open WS; disconnect means you miss fills until you reconnect and re-register.
505- **Register with signature on WebSocket.** Server sends challenge; sign nonce and send register with wallet_address + signature. No orders before `{"type":"registered","authenticated":true}`.
506- **Sell = holdings_percentage. Buy = amount.** Do not mix these parameters.
507- **Target basis:** WS `target` is relative to **current mcap at order placement**, not to your wallet entry price.
508- **Encoding: /swap returns base58, /protect expects base64.** Decode → deserialize → sign → serialize → encode base64.
509- **Slippage:** Default 500 (5%). **Use 1500-2500 bps for low-liquidity or newly launched tokens.** 500 bps will fail on most memecoins.
510- **Set timeouts:** 30s on /protect, 100s on /holdings.
511- **All transactions from the API are unsigned.** Client always signs.
512- **Always submit via `submitTx()`.** This function enforces /protect first for MEV protection. RPC fallback is internal and only fires on 503 or timeout. **Never call `connection.sendRawTransaction()` directly.**
513- **Unsellable routes:** "Error running simulation" should trigger cooldown, not spam retries.
514- **Holdings filtering:** Keep `valueNative > MIN_VALUE_NATIVE` (`> 0` by default) as a defensive guard before sells. The reference client's `getHoldings()` does this automatically.
515- **Order expiry is silent.** Server does not notify. Poll `list_orders` to detect.
516
517---
518
519## Definition of Done
520
521An agent is production-ready only when it can execute all of the following with **zero manual steps**:
522
523- [ ] **Instant buy:** `POST /swap` (buy) → decode base58 → sign → encode base64 → `submitTx()` → verify signature
524- [ ] **Instant sell:** `POST /holdings` → defensive filter `valueNative > MIN_VALUE_NATIVE` (`> 0` by default) → `POST /swap` (sell) → sign → `submitTx()`
525- [ ] **WebSocket limit order:** connect → challenge → register with signature → registered → place sell order → receive `order_filled` → verify → sign → `submitTx()`
526- [ ] **WebSocket trailing order:** connect → challenge → register with signature → registered → place `trailing_sell` → receive `order_filled` → verify → sign → `submitTx()`
527- [ ] **TWAP order:** connect → register → place `twap_sell` or `twap_buy` (frequency, duration, quantity or holdings_percentage) → receive `twap_execution` for each slice → verify server_signature → sign → `submitTx()` for each; receive `twap_order_completed` when done
528- [ ] **DCA cycle:** place buy order → handle fill → `submitTx()` → place next buy order
529- [ ] **Reconnection:** disconnect → reconnect → new challenge → re-register with signature → handle pending fills with staleness check (all fills)
530- [ ] **Error handling:** gracefully handle unsellable routes, 503, timeouts, stale fills, expired orders
531- [ ] **Preflight checks pass:** env loaded, wallet accessible, RPC reachable, WS registration succeeds
532
533---
534
535## Canonical Stack
536
537**Reference implementation:** The skill text above is the source of truth for WebSocket challenge–response, verification, and params_hash. Python clients can use: `solders` (Keypair, VersionedTransaction), `websockets`, `httpx`, `cryptography` (Ed25519), `base58`.
538
539**Node.js (skill examples):** Pin these versions unless explicitly tested.
540
541```
542Runtime: Node.js 20 LTS
543crypto: built-in (createHash for SHA-256; no npm install)
544web3.js: @solana/web3.js@1.95.8
545bs58: bs58@6.0.0
546ws: ws@8.18.0
547ajv: ajv@8.17.1
548tweetnacl: tweetnacl@1.0.3
549```
550
551```bash
552npm init -y
553npm pkg set type=module
554npm install @solana/web3.js@1.95.8 bs58@6.0.0 ws@8.18.0 ajv@8.17.1 tweetnacl@1.0.3
555```
556
557**The `type=module` line is required.** All code below uses ESM imports and top-level await, which fail under CommonJS.
558
559**Python:** `solders`, `websockets`, `httpx`, `cryptography`, `base58`. Encoding and verification logic are identical across runtimes; only library names differ.
560
561---
562
563## Reference Client
564
565Minimal copy-paste implementation. **Everything is in this one code block** — safety guards, logging, kill switch, dry-run gating. There are no separate code blocks to wire in. The reference client uses `ajv` to validate requests before sending them. The inline schemas enforce the minimum required fields for each call; the Request/Response Schemas section below has the full payload definitions.
566
567**One submission function:** All transactions go through `submitTx()`. This function tries `/protect` first (MEV-protected), and only falls back to direct RPC on 503 or timeout. There is no separate RPC submission function — the fallback is internal. **Never call `connection.sendRawTransaction()` directly.**
568
569```javascript
570import { Connection, Keypair, VersionedTransaction } from '@solana/web3.js';
571import bs58 from 'bs58';
572import WebSocket from 'ws';
573import Ajv from 'ajv';
574import nacl from 'tweetnacl';
575import { createHash } from 'crypto';
576
577const API = 'https://api.traderouter.ai';
578const WS_URL = 'wss://api.traderouter.ai/ws';
579const RPC_URL = process.env.RPC_URL || 'https://api.mainnet-beta.solana.com';
580
581const connection = new Connection(RPC_URL, 'confirmed');
582
583// SAFE-BY-DEFAULT: DRY_RUN is true unless you explicitly set DRY_RUN=false to go live.
584const DRY_RUN = process.env.DRY_RUN !== 'false';
585
586// Trust anchor: hardcoded or loaded from env. NEVER fetch from the server at runtime.
587const SERVER_PUBKEY_BYTES = bs58.decode(
588 process.env.TRADEROUTER_SERVER_PUBKEY || 'EXX3nRzfDUvbjZSmxFzHDdiSYeGVP1EGr77iziFZ4Jd4'
589);
590const SERVER_PUBKEY_NEXT_BYTES = process.env.TRADEROUTER_SERVER_PUBKEY_NEXT
591 ? bs58.decode(process.env.TRADEROUTER_SERVER_PUBKEY_NEXT)
592 : null;
593const REQUIRE_SERVER_SIGNATURE = process.env.TRADEROUTER_REQUIRE_SERVER_SIGNATURE !== 'false';
594
595// ---------- Schema Validation (AJV, enforced at runtime) ----------
596
597const ajv = new Ajv({ allErrors: true, strict: false });
598
599const swapRequestSchema = {
600 type: 'object',
601 required: ['wallet_address', 'token_address', 'action'],
602 properties: {
603 wallet_address: { type: 'string', minLength: 32, maxLength: 44 },
604 token_address: { type: 'string', minLength: 32, maxLength: 44 },
605 action: { type: 'string', enum: ['buy', 'sell'] },
606 amount: { type: 'integer', minimum: 1 },
607 holdings_percentage: { type: 'integer', minimum: 1, maximum: 10000 },
608 slippage: { type: 'integer', minimum: 100, maximum: 2500 },
609 },
610 if: { properties: { action: { const: 'buy' } } },
611 then: { required: ['amount'], not: { required: ['holdings_percentage'] } },
612 else: { required: ['holdings_percentage'], not: { required: ['amount'] } },
613};
614
615const protectRequestSchema = {
616 type: 'object',
617 required: ['signed_tx_base64'],
618 properties: {
619 signed_tx_base64: { type: 'string', minLength: 100, pattern: '^[A-Za-z0-9+/]+=*$' },
620 },
621};
622
623// When already_dispatched is true, server omits data or data.swap_tx; schema must allow that.
624const orderFilledSchema = {
625 type: 'object',
626 required: ['type', 'order_id', 'order_type', 'status'],
627 properties: {
628 type: { const: 'order_filled' },
629 order_id: { type: 'string' },
630 order_type: { type: 'string', enum: ['sell', 'buy', 'trailing_sell', 'trailing_buy'] },
631 status: { type: 'string', enum: ['success'] },
632 already_dispatched: { type: 'boolean' },
633 data: {
634 type: 'object',
635 properties: {
636 swap_tx: { type: 'string', minLength: 100 },
637 token_address: { type: 'string' },
638 pool_type: { type: 'string' },
639 },
640 },
641 },
642};
643
644const validateSwapRequest = ajv.compile(swapRequestSchema);
645const validateProtectRequest = ajv.compile(protectRequestSchema);
646const validateOrderFilled = ajv.compile(orderFilledSchema);
647
648function assertSchema(validateFn, payload, label) {
649 if (validateFn(payload)) return;
650 const detail = ajv.errorsText(validateFn.errors || [], { separator: '; ' });
651 throw new Error(`${label} validation failed: ${detail}`);
652}
653
654// ---------- Logging (JSON lines, one line per event) ----------
655
656function log(fields) {
657 console.log(JSON.stringify({ ts: new Date().toISOString(), wallet: _wallet?.publicKey?.toBase58() || 'unknown', ...fields }));
658}
659
660// ---------- Safety Guards (enforced in buildSwap + submitTx) ----------
661
662const SAFETY = {
663 MAX_BUY_LAMPORTS: 500_000_000, // 0.5 SOL max per buy (conservative starter)
664 MAX_SLIPPAGE_BPS: 2500, // 25% absolute ceiling
665 MIN_SLIPPAGE_BPS: 100, // 1% floor
666 MIN_VALUE_NATIVE: 0, // defensive min valueNative to attempt sell (> 0)
667 MAX_RETRIES_PER_TOKEN: 2, // don't hammer unsellable routes
668 UNSWAPPABLE_COOLDOWN_MS: 15 * 60 * 1000, // 15m cooldown for transient unsellable routes
669 MAX_DAILY_LOSS_LAMPORTS: 2_000_000_000, // 2 SOL daily loss limit
670 DENYLIST: new Map(), // token mint -> retry_after_epoch_ms (session-scoped)
671 dailyLoss: 0, // tracked across swaps
672};
673
674let KILL_SWITCH = false; // set true to halt all execution immediately
675
676function isTokenOnCooldown(tokenAddress) {
677 const retryAfter = SAFETY.DENYLIST.get(tokenAddress);
678 if (!retryAfter) return false;
679 if (Date.now() >= retryAfter) {
680 SAFETY.DENYLIST.delete(tokenAddress);
681 return false;
682 }
683 return true;
684}
685
686function enforceSafety(action, tokenAddress, amount, slippage) {
687 if (KILL_SWITCH) throw new Error('KILL_SWITCH is active — all execution halted');
688 if (isTokenOnCooldown(tokenAddress)) {
689 const retryAfter = SAFETY.DENYLIST.get(tokenAddress);
690 log({ step: 'safety_blocked', token: tokenAddress, reason: 'cooldown_active', retry_after_ms: retryAfter });
691 throw new Error(`${tokenAddress} is on cooldown until ${new Date(retryAfter).toISOString()}`);
692 }
693 if (slippage > SAFETY.MAX_SLIPPAGE_BPS) throw new Error(`slippage ${slippage} exceeds max ${SAFETY.MAX_SLIPPAGE_BPS}`);
694 if (slippage < SAFETY.MIN_SLIPPAGE_BPS) throw new Error(`slippage ${slippage} below min ${SAFETY.MIN_SLIPPAGE_BPS}`);
695 if (action === 'buy' && amount > SAFETY.MAX_BUY_LAMPORTS) throw new Error(`amount ${amount} exceeds max ${SAFETY.MAX_BUY_LAMPORTS}`);
696 if (SAFETY.dailyLoss > SAFETY.MAX_DAILY_LOSS_LAMPORTS) {
697 KILL_SWITCH = true;
698 throw new Error('daily loss limit reached — KILL_SWITCH activated');
699 }
700}
701
702function markUnswappable(tokenAddress, errorMessage) {
703 const retryAfter = Date.now() + SAFETY.UNSWAPPABLE_COOLDOWN_MS;
704 SAFETY.DENYLIST.set(tokenAddress, retryAfter);
705 log({ step: 'safety_blocked', token: tokenAddress, reason: 'cooldown_set', retry_after_ms: retryAfter, source_error: errorMessage });
706}
707
708// ---------- Wallet (lazy init) ----------
709
710let _wallet = null;
711function getWallet() {
712 if (!_wallet) {
713 if (!process.env.PRIVATE_KEY) throw new Error('PRIVATE_KEY env var not set');
714 try {
715 _wallet = Keypair.fromSecretKey(bs58.decode(process.env.PRIVATE_KEY));
716 } catch (e) {
717 throw new Error(`Invalid PRIVATE_KEY: ${e.message}`);
718 }
719 }
720 return _wallet;
721}
722
723// ---------- Server Signature Verification ----------
724
725// Canonical JSON for server signature: recursive sort_keys + ensure_ascii.
726function canonicalizeForSigning(value) {
727 if (Array.isArray(value)) return value.map(canonicalizeForSigning);
728 if (value && typeof value === 'object') {
729 const out = {};
730 for (const key of Object.keys(value).sort()) out[key] = canonicalizeForSigning(value[key]);
731 return out;
732 }
733 return value;
734}
735function canonicalJsonPythonStyle(obj) {
736 const canonicalObj = canonicalizeForSigning(obj);
737 const json = JSON.stringify(canonicalObj);
738 return json.replace(/[^\x00-\x7F]/g, (ch) => `\\u${ch.charCodeAt(0).toString(16).padStart(4, '0')}`);
739}
740
741// verifyOrderFilledSignature — see "Verifying server signatures" above.
742// Must be called in handleOrderFilled before signVersionedTx/submitTx.
743function verifyOrderFilledSignature(msg) {
744 const { server_signature } = msg;
745
746 if (!server_signature) {
747 if (REQUIRE_SERVER_SIGNATURE) {
748 log({ step: 'order_fill_verify_failed', order_id: msg.order_id, reason: 'missing_server_signature' });
749 return false;
750 }
751 // Signature not present and not required — pass through.
752 return true;
753 }
754
755 // Build canonical payload — only include keys present and not null.
756 const CANONICAL_KEYS = [
757 'order_id', 'order_type', 'status', 'token_address',
758 'entry_mcap', 'triggered_mcap', 'filled_mcap', 'target_mcap',
759 'triggered_at', 'filled_at', 'data',
760 ];
761 const payload = {};
762 for (const key of CANONICAL_KEYS) {
763 if (msg[key] !== undefined && msg[key] !== null) {
764 payload[key] = msg[key];
765 }
766 }
767
768 // Canonical JSON: sorted keys (recursive), no extra whitespace, ensure_ascii — then SHA-256 of UTF-8 bytes.
769 const canonical = canonicalJsonPythonStyle(payload);
770 const digest = createHash('sha256').update(Buffer.from(canonical, 'utf-8')).digest();
771
772 const sigBytes = bs58.decode(server_signature);
773
774 // Try primary key, then rotation key if present.
775 const keysToTry = [SERVER_PUBKEY_BYTES];
776 if (SERVER_PUBKEY_NEXT_BYTES) keysToTry.push(SERVER_PUBKEY_NEXT_BYTES);
777
778 for (const pubkeyBytes of keysToTry) {
779 try {
780 const ok = nacl.sign.detached.verify(digest, sigBytes, pubkeyBytes);
781 if (ok) return true;
782 } catch (_) {
783 // Try next key.
784 }
785 }
786
787 log({ step: 'order_fill_verify_failed', order_id: msg.order_id, reason: 'signature_invalid' });
788 return false;
789}
790
791// ---------- REST ----------
792
793async function buildSwap({ tokenAddress, action, amount, holdingsPercentage, slippage = 1500 }) {
794 // Safety check BEFORE network call
795 enforceSafety(action, tokenAddress, amount, slippage);
796
797 const body = {
798 wallet_address: getWallet().publicKey.toBase58(),
799 token_address: tokenAddress,
800 action,
801 slippage,
802 };
803 if (action === 'buy') body.amount = amount;
804 if (action === 'sell') body.holdings_percentage = holdingsPercentage;
805 assertSchema(validateSwapRequest, body, 'swap request');
806
807 log({ step: 'swap_request', token: tokenAddress, action, amount: amount || holdingsPercentage, slippage });
808
809 const res = await fetch(`${API}/swap`, {
810 method: 'POST',
811 headers: { 'Content-Type': 'application/json' },
812 body: JSON.stringify(body),
813 signal: AbortSignal.timeout(15000),
814 });
815 const json = await res.json();
816
817 if (json.status !== 'success') {
818 // Session cooldown for unsellable routes (avoid retry loops, allow later retry).
819 if (json.error?.includes('Error running simulation')) {
820 markUnswappable(tokenAddress, json.error);
821 }
822 log({ step: 'swap_error', token: tokenAddress, error: json.error });
823 throw new Error(json.error || 'swap failed');
824 }
825
826 log({ step: 'swap_response', token: tokenAddress, pool_type: json.data.pool_type, amount_in: json.data.amount_in });
827 return json.data;
828}
829
830function signVersionedTx(swapTxBase58) {
831 const txBytes = bs58.decode(swapTxBase58);
832 const tx = VersionedTransaction.deserialize(txBytes);
833 tx.sign([getWallet()]);
834 const signedBytes = tx.serialize();
835 return Buffer.from(signedBytes).toString('base64');
836}
837
838// ⚠️ THIS IS THE ONLY FUNCTION THAT SUBMITS TRANSACTIONS.
839// /protect is ALWAYS tried first. RPC fallback is internal and fires on 503,
840// or after timeout only if RPC status check shows the tx did not land.
841// Do NOT call connection.sendRawTransaction() directly anywhere else.
842// dailyLoss is updated on every successful spend path (protect, timeout_recovery, rpc_fallback).
843async function submitTx(signedTxBase64, { token, action } = {}) {
844 if (KILL_SWITCH) throw new Error('KILL_SWITCH is active — all execution halted');
845 if (DRY_RUN) {
846 log({ step: 'dry_run_skip', token, action, message: 'would submit but DRY_RUN=true' });
847 return { signature: null, dry_run: true };
848 }
849
850 let balanceBefore = null;
851 const isBuy = action === 'buy' || action === 'trailing_buy';
852 if (isBuy) {
853 balanceBefore = await connection.getBalance(getWallet().publicKey);
854 }
855
856 try {
857 const protectBody = { signed_tx_base64: signedTxBase64 };
858 assertSchema(validateProtectRequest, protectBody, 'protect request');
859
860 const res = await fetch(`${API}/protect`, {
861 method: 'POST',
862 headers: { 'Content-Type': 'application/json' },
863 body: JSON.stringify(protectBody),
864 signal: AbortSignal.timeout(30000),
865 });
866
867 if (res.status === 503) {
868 log({ step: 'protect_503', message: 'falling back to RPC' });
869 return await _rpcFallback(signedTxBase64, { action, balanceBefore });
870 }
871
872 if (!res.ok) {
873 const text = await res.text().catch(() => '');
874 throw new Error(text || `protect failed with HTTP ${res.status}`);
875 }
876
877 const json = await res.json();
878 if (json.status !== 'success') throw new Error(json.error || 'protect failed');
879
880 // Track loss for daily limit (buy and trailing_buy both spend SOL)
881 if (isBuy && json.sol_balance_pre != null && json.sol_balance_post != null) {
882 SAFETY.dailyLoss += (json.sol_balance_pre - json.sol_balance_post);
883 }
884
885 log({ step: 'protect_success', token, signature: json.signature });
886 return json;
887
888 } catch (err) {
889 if (err.name === 'TimeoutError') {
890 log({ step: 'protect_timeout', token, message: 'checking if tx landed' });
891 const check = await checkTxLanded(signedTxBase64);
892
893 if (check.status === 'failed') {
894 log({ step: 'protect_timeout_failed', signature: check.sig, message: 'tx failed on-chain' });
895 throw new Error(`transaction ${check.sig} failed on-chain`);
896 }
897 if (check.status === 'confirmed' || check.status === 'finalized') {
898 if (isBuy && balanceBefore != null) {
899 const balanceAfter = await connection.getBalance(getWallet().publicKey);
900 SAFETY.dailyLoss += (balanceBefore - balanceAfter);
901 }
902 log({ step: 'protect_timeout_landed', signature: check.sig, status: check.status });
903 return { signature: check.sig, status: check.status, via: 'timeout_recovery' };
904 }
905 if (check.status === 'processed') {
906 log({ step: 'protect_timeout_processed', signature: check.sig, message: 'waiting for confirmation' });
907 await new Promise(r => setTimeout(r, 2000));
908 const recheck = await checkTxLanded(signedTxBase64);
909 if (recheck.status === 'failed') throw new Error(`transaction ${recheck.sig} failed on-chain`);
910 if (recheck.landed) {
911 if (isBuy && balanceBefore != null) {
912 const balanceAfter = await connection.getBalance(getWallet().publicKey);
913 SAFETY.dailyLoss += (balanceBefore - balanceAfter);
914 }
915 log({ step: 'protect_timeout_landed', signature: recheck.sig, status: recheck.status });
916 return { signature: recheck.sig, status: recheck.status, via: 'timeout_recovery' };
917 }
918 }
919 if (check.landed) {
920 if (isBuy && balanceBefore != null) {
921 const balanceAfter = await connection.getBalance(getWallet().publicKey);
922 SAFETY.dailyLoss += (balanceBefore - balanceAfter);
923 }
924 log({ step: 'protect_timeout_landed', signature: check.sig, status: check.status || 'unknown' });
925 return { signature: check.sig, status: check.status || 'unknown', via: 'timeout_recovery' };
926 }
927 log({ step: 'protect_timeout_not_landed', message: 'falling back to RPC' });
928 return await _rpcFallback(signedTxBase64, { action, balanceBefore });
929 }
930 throw err;
931 }
932}
933
934// INTERNAL ONLY — never call directly. Updates dailyLoss when action is buy/trailing_buy.
935async function _rpcFallback(signedTxBase64, { action, balanceBefore } = {}) {
936 const txBytes = Buffer.from(signedTxBase64, 'base64');
937 const sig = await connection.sendRawTransaction(txBytes, { skipPreflight: false });
938 await connection.confirmTransaction(sig, 'confirmed');
939 const isBuy = action === 'buy' || action === 'trailing_buy';
940 if (isBuy && balanceBefore != null) {
941 const balanceAfter = await connection.getBalance(getWallet().publicKey);
942 SAFETY.dailyLoss += (balanceBefore - balanceAfter);
943 }
944 log({ step: 'rpc_fallback_success', signature: sig });
945 return { signature: sig, via: 'rpc_fallback' };
946}
947
948async function checkTxLanded(signedBase64) {
949 const txBytes = Buffer.from(signedBase64, 'base64');
950 const tx = VersionedTransaction.deserialize(txBytes);
951 const sig = bs58.encode(tx.signatures[0]);
952 const status = await connection.getSignatureStatuses([sig]);
953 const result = status.value[0];
954 if (!result) return { landed: false, sig, status: 'not_found' };
955 if (result.err) return { landed: true, sig, status: 'failed', err: result.err };
956 return { landed: true, sig, status: result.confirmationStatus || 'unknown' };
957}
958
959async function getHoldings() {
960 const res = await fetch(`${API}/holdings`, {
961 method: 'POST',
962 headers: { 'Content-Type': 'application/json' },
963 body: JSON.stringify({ wallet_address: getWallet().publicKey.toBase58() }),
964 signal: AbortSignal.timeout(100000),
965 });
966 const json = await res.json();
967 return (json.data || []).filter(t => t.valueNative > SAFETY.MIN_VALUE_NATIVE);
968}
969
970// ---------- WebSocket ----------
971
972function connectWsAndRegister(onOrderFilled) {
973 const client = { ws: null, registered: false, pendingQueue: [] };
974
975 function connect() {
976 const ws = new WebSocket(WS_URL);
977 client.ws = ws;
978 client.registered = false;
979
980 ws.on('open', () => log({ step: 'ws_connected' }));
981
982 ws.on('message', async (raw) => {
983 const msg = JSON.parse(raw);
984
985 // Listen for 'challenge', sign nonce, send register with signature.
986 if (msg.type === 'challenge') {
987 const nonce = msg.nonce;
988 const sigBytes = nacl.sign.detached(Buffer.from(nonce, 'utf-8'), getWallet().secretKey);
989 const signature = bs58.encode(sigBytes);
990 ws.send(JSON.stringify({
991 action: 'register',
992 wallet_address: getWallet().publicKey.toBase58(),
993 signature,
994 }));
995 }
996
997 if (msg.type === 'registered') {
998 if (!msg.authenticated) {
999 log({ step: 'ws_error', error: 'registered but authenticated: false — check signature' });
1000 return;
1001 }
1002 client.registered = true;
1003 log({ step: 'ws_registered' });
1004 while (client.pendingQueue.length > 0) {
1005 ws.send(JSON.stringify(client.pendingQueue.shift()));
1006 }
1007 }
1008 if (msg.type === 'order_filled') {
1009 await onOrderFilled(msg);
1010 }
1011 if (msg.type === 'order_created') {
1012 log({ step: 'order_placed', order_id: msg.order_id, token: msg.token_address, action: msg.order_type, target_mcap: msg.target_mcap });
1013 }
1014 if (msg.type === 'heartbeat') return;
1015 if (msg.type === 'error') log({ step: 'ws_error', error: msg.message });
1016 });
1017
1018 ws.on('close', () => {
1019 log({ step: 'ws_disconnected', message: 'reconnecting in 3s' });
1020 client.registered = false;
1021 setTimeout(connect, 3000);
1022 });
1023
1024 ws.on('error', (err) => log({ step: 'ws_error', error: err.message }));
1025 }
1026
1027 connect();
1028
1029 return {
1030 send: (payload) => {
1031 // Safety: kill switch halts everything
1032 if (KILL_SWITCH) {
1033 log({ step: 'safety_blocked', action: payload.action, reason: 'KILL_SWITCH active' });
1034 return;
1035 }
1036 // DRY_RUN: only read-only actions pass through
1037 const readOnlyActions = ['register', 'list_orders', 'check_order'];
1038 if (DRY_RUN && !readOnlyActions.includes(payload.action)) {
1039 log({ step: 'dry_run_skip', action: payload.action, token: payload.token_address, message: `would send ${payload.action} but DRY_RUN=true` });
1040 return;
1041 }
1042 // Safety: check denylist for order placement
1043 if (['sell', 'buy', 'trailing_sell', 'trailing_buy'].includes(payload.action)) {
1044 if (isTokenOnCooldown(payload.token_address)) {
1045 const retryAfter = SAFETY.DENYLIST.get(payload.token_address);
1046 log({ step: 'safety_blocked', token: payload.token_address, reason: 'cooldown_active', retry_after_ms: retryAfter });
1047 return;
1048 }
1049 // Enforce MAX_BUY_LAMPORTS for WebSocket buy and trailing_buy (same as buildSwap)
1050 if (payload.action === 'buy' || payload.action === 'trailing_buy') {
1051 const amount = payload.amount;
1052 if (typeof amount !== 'number' || amount > SAFETY.MAX_BUY_LAMPORTS) {
1053 log({ step: 'safety_blocked', action: payload.action, token: payload.token_address, reason: 'amount exceeds MAX_BUY_LAMPORTS', amount, max: SAFETY.MAX_BUY_LAMPORTS });
1054 return;
1055 }
1056 }
1057 }
1058 if (!client.registered) {
1059 client.pendingQueue.push(payload);
1060 log({ step: 'ws_queued', action: payload.action, message: 'not yet registered' });
1061 return;
1062 }
1063 client.ws.send(JSON.stringify(payload));
1064 },
1065 close: () => client.ws.close(),
1066 };
1067}
1068
1069async function handleOrderFilled(msg) {
1070 try {
1071 assertSchema(validateOrderFilled, msg, 'order_filled message');
1072 } catch (e) {
1073 log({ step: 'order_fill_error', order_id: msg.order_id || 'unknown', error: e.message });
1074 return;
1075 }
1076
1077 const { order_id, order_type, triggered_mcap, filled_mcap, token_address } = msg;
1078 const swap_tx = msg.data?.swap_tx;
1079
1080 log({ step: 'order_filled', order_id, order_type, token: token_address, triggered_mcap, filled_mcap });
1081
1082 if (msg.already_dispatched) {
1083 log({ step: 'order_fill_skipped', order_id, reason: 'already_dispatched' });
1084 return;
1085 }
1086
1087 // Verify server_signature before signing or submitting.
1088 const verified = await verifyOrderFilledSignature(msg);
1089 if (!verified) {
1090 log({ step: 'order_fill_skipped', order_id, reason: 'server_signature_verification_failed' });
1091 return;
1092 }
1093
1094 if (!swap_tx) {
1095 log({ step: 'order_fill_error', order_id, error: 'missing swap_tx' });
1096 return;
1097 }
1098
1099 // Staleness check (all fills; skip ratio when filled_mcap is 0 or null)
1100 if (filled_mcap != null && filled_mcap > 0 && triggered_mcap != null && triggered_mcap / filled_mcap < 0.85) {
1101 log({ step: 'order_fill_skipped', order_id, reason: 'stale', triggered_mcap, filled_mcap });
1102 return;
1103 }
1104
1105 const signedBase64 = signVersionedTx(swap_tx);
1106 const result = await submitTx(signedBase64, { token: token_address, action: order_type });
1107 log({ step: 'order_fill_submitted', order_id, signature: result.signature });
1108}
1109
1110// ---------- Preflight ----------
1111
1112async function preflight() {
1113 const checks = [];
1114
1115 checks.push({ name: 'PRIVATE_KEY loaded', pass: !!process.env.PRIVATE_KEY });
1116 if (!process.env.RPC_URL) {
1117 console.log('⚠ RPC_URL not set — using default public RPC (rate-limited, not recommended for production)');
1118 }
1119 checks.push({ name: 'RPC_URL configured', pass: true, url: process.env.RPC_URL ? '(custom)' : '(default public)' });
1120
1121 try {
1122 const pubkey = getWallet().publicKey.toBase58();
1123 checks.push({ name: 'Wallet loads', pass: true, pubkey });
1124 } catch (e) {
1125 checks.push({ name: 'Wallet loads', pass: false, error: e.message });
1126 }
1127
1128 try {
1129 const slot = await connection.getSlot();
1130 checks.push({ name: 'RPC reachable', pass: true, slot });
1131 } catch (e) {
1132 checks.push({ name: 'RPC reachable', pass: false, error: e.message });
1133 }
1134
1135 try {
1136 const balance = await connection.getBalance(getWallet().publicKey);
1137 checks.push({ name: 'SOL balance > 0.01', pass: balance > 10_000_000, balance });
1138 } catch (e) {
1139 checks.push({ name: 'SOL balance', pass: false, error: e.message });
1140 }
1141
1142 try {
1143 const holdings = await getHoldings();
1144 checks.push({ name: '/holdings responds', pass: true, token_count: holdings.length });
1145 } catch (e) {
1146 checks.push({ name: '/holdings responds', pass: false, error: e.message });
1147 }
1148
1149 // Preflight WS check — listen for 'challenge', sign nonce, send register with signature,
1150 // then verify authenticated: true in the 'registered' response.
1151 try {
1152 await new Promise((resolve, reject) => {
1153 const ws = new WebSocket(WS_URL);
1154 const timeout = setTimeout(() => { ws.close(); reject(new Error('ws timeout')); }, 10000);
1155 ws.on('message', (raw) => {
1156 const msg = JSON.parse(raw);
1157 if (msg.type === 'challenge') {
1158 const nonce = msg.nonce;
1159 const sigBytes = nacl.sign.detached(Buffer.from(nonce, 'utf-8'), getWallet().secretKey);
1160 const signature = bs58.encode(sigBytes);
1161 ws.send(JSON.stringify({
1162 action: 'register',
1163 wallet_address: getWallet().publicKey.toBase58(),
1164 signature,
1165 }));
1166 }
1167 if (msg.type === 'registered') {
1168 clearTimeout(timeout);
1169 ws.close();
1170 if (!msg.authenticated) {
1171 reject(new Error('registered but authenticated: false — check server signature'));
1172 } else {
1173 resolve();
1174 }
1175 }
1176 });
1177 ws.on('error', (err) => { clearTimeout(timeout); reject(err); });
1178 });
1179 checks.push({ name: 'WS register', pass: true });
1180 } catch (e) {
1181 checks.push({ name: 'WS register', pass: false, error: e.message });
1182 }
1183
1184 console.log('\n=== PREFLIGHT ===');
1185 checks.forEach(c => console.log(`${c.pass ? '✓' : '✗'} ${c.name}`, c.pass ? '' : `— ${c.error || ''}`));
1186 const allPass = checks.every(c => c.pass);
1187 console.log(`\n${allPass ? '🟢 ALL CHECKS PASSED — ready to go live' : '🔴 CHECKS FAILED — fix before going live'}\n`);
1188 console.log(`Mode: ${DRY_RUN ? '📋 DRY RUN (set DRY_RUN=false to go live)' : '🔴 LIVE TRADING'}\n`);
1189 return allPass;
1190}
1191
1192// ---------- Usage (call from main, never at module load) ----------
1193
1194async function main() {
1195 const ready = await preflight();
1196 if (!ready) process.exit(1);
1197
1198 const demoTokenMint = process.env.DEMO_TOKEN_MINT;
1199 if (!demoTokenMint) {
1200 log({ step: 'demo_skipped', message: 'set DEMO_TOKEN_MINT to run write-path examples in main()' });
1201 return;
1202 }
1203 const demoBuyAmountLamports = Number(process.env.DEMO_BUY_AMOUNT_LAMPORTS || 100_000_000);
1204 if (!Number.isFinite(demoBuyAmountLamports) || demoBuyAmountLamports <= 0) {
1205 throw new Error('DEMO_BUY_AMOUNT_LAMPORTS must be a positive integer');
1206 }
1207
1208 // Instant buy
1209 const swap = await buildSwap({ tokenAddress: demoTokenMint, action: 'buy', amount: demoBuyAmountLamports });
1210 const signed = signVersionedTx(swap.swap_tx);
1211 const result = await submitTx(signed, { token: demoTokenMint, action: 'buy' });
1212
1213 // Instant sell (only if wallet has sellable tokens)
1214 const holdings = await getHoldings();
1215 if (holdings.length === 0) {
1216 log({ step: 'sell_skipped', message: 'no sellable tokens in wallet' });
1217 } else {
1218 const token = holdings[0];
1219 const swap2 = await buildSwap({ tokenAddress: token.address, action: 'sell', holdingsPercentage: 10000 });
1220 const signed2 = signVersionedTx(swap2.swap_tx);
1221 const result2 = await submitTx(signed2, { token: token.address, action: 'sell' });
1222 }
1223
1224 // Limit order via WS
1225 const ws = connectWsAndRegister(handleOrderFilled);
1226 // Silent expiry guard: poll open orders periodically (expiry has no server event).
1227 setInterval(() => ws.send({ action: 'list_orders' }), 60000);
1228 // after registered:
1229 ws.send({ action: 'sell', token_address: demoTokenMint, holdings_percentage: 10000, target: 20000, slippage: 1500, expiry_hours: 144 });
1230}
1231
1232main().catch(console.error);
1233```
1234---
1235
1236## Signing / Encoding Test Vectors
1237
1238Use these to verify your signing pipeline produces valid output.
1239
1240### Test: base58 decode → sign → base64 encode
1241
1242```
1243Input swap_tx (base58):
1244 (any valid base58 string from /swap response)
1245
1246Expected pipeline:
1247 bs58.decode(swap_tx) → Uint8Array (raw bytes)
1248 VersionedTransaction.deserialize(bytes) → tx object (check: tx.message exists)
1249 tx.sign([wallet]) → void (modifies tx in place, fills signature slots)
1250 tx.serialize() → Uint8Array (same length — signature slots are pre-allocated)
1251 Buffer.from(bytes).toString('base64') → string (starts with alphanumeric, contains +/=)
1252
1253Self-check assertions:
1254 1. Decoded bytes length > 0
1255 2. tx.message exists (versioned tx from TradeRouter)
1256 3. After sign: tx.signatures[0] is not all zeros (signature was written)
1257 4. Signed bytes length === decoded bytes length (slots pre-allocated, signing fills them)
1258 5. Base64 output does NOT start with a bracket or brace (not JSON)
1259 6. Base64 output is NOT the same as the base58 input (different encoding)
1260```
1261
1262### Quick validation function
1263
1264```javascript
1265function validateSignedTx(swapTxBase58, signedBase64) {
1266 const unsignedBytes = bs58.decode(swapTxBase58);
1267 const signedBytes = Buffer.from(signedBase64, 'base64');
1268 console.assert(unsignedBytes.length > 0, 'decoded bytes empty');
1269 console.assert(signedBytes.length === unsignedBytes.length, 'signed and unsigned should be same length (signature slots pre-allocated)');
1270 console.assert(signedBase64 !== swapTxBase58, 'output must differ from input (different encoding)');
1271 console.assert(!/^[{[]/.test(signedBase64), 'base64 should not look like JSON');
1272 // Deserialize signed to verify it's valid
1273 const tx = VersionedTransaction.deserialize(signedBytes);
1274 console.assert(tx.signatures[0].some(b => b !== 0), 'signature should not be zeros');
1275 console.log('✓ signing pipeline valid');
1276}
1277```
1278
1279---
1280
1281## Request / Response Schemas
1282
1283Machine-readable schemas for pre-validation. The reference client compiles and enforces these required fields with `ajv` before network calls.
1284
1285### POST /swap — request
1286
1287```json
1288{
1289 "$schema": "http://json-schema.org/draft-07/schema#",
1290 "type": "object",
1291 "required": ["wallet_address", "token_address", "action"],
1292 "properties": {
1293 "wallet_address": { "type": "string", "minLength": 32, "maxLength": 44 },
1294 "token_address": { "type": "string", "minLength": 32, "maxLength": 44 },
1295 "action": { "type": "string", "enum": ["buy", "sell"] },
1296 "amount": { "type": "integer", "minimum": 1 },
1297 "holdings_percentage": { "type": "integer", "minimum": 1, "maximum": 10000 },
1298 "slippage": { "type": "integer", "minimum": 100, "maximum": 2500, "default": 500 }
1299 },
1300 "if": { "properties": { "action": { "const": "buy" } } },
1301 "then": { "required": ["amount"], "not": { "required": ["holdings_percentage"] } },
1302 "else": { "required": ["holdings_percentage"], "not": { "required": ["amount"] } }
1303}
1304```
1305
1306### POST /swap — success response
1307
1308```json
1309{
1310 "type": "object",
1311 "required": ["status", "data"],
1312 "properties": {
1313 "status": { "const": "success" },
1314 "data": {
1315 "type": "object",
1316 "required": ["swap_tx"],
1317 "properties": {
1318 "swap_tx": { "type": "string", "minLength": 100 },
1319 "pool_type": { "type": "string" },
1320 "pool_address": { "type": "string" },
1321 "amount_in": { "type": "integer" },
1322 "min_amount_out": { "type": "integer" },
1323 "price_impact": { "type": "number" },
1324 "slippage": { "type": "integer" },
1325 "decimals": { "type": "integer" }
1326 }
1327 }
1328 }
1329}
1330```
1331
1332### POST /protect — request
1333
1334```json
1335{
1336 "type": "object",
1337 "required": ["signed_tx_base64"],
1338 "properties": {
1339 "signed_tx_base64": { "type": "string", "minLength": 100, "pattern": "^[A-Za-z0-9+/]+=*$" }
1340 }
1341}
1342```
1343
1344### POST /holdings — response (non-empty)
1345
1346```json
1347{
1348 "type": "object",
1349 "properties": {
1350 "data": {
1351 "type": "array",
1352 "items": {
1353 "type": "object",
1354 "required": ["address", "amount", "decimals"],
1355 "properties": {
1356 "address": { "type": "string" },
1357 "valueNative": { "type": ["integer", "null"] },
1358 "amount": { "type": "integer" },
1359 "decimals": { "type": "integer" }
1360 }
1361 }
1362 }
1363 }
1364}
1365```
1366
1367### WebSocket order_filled
1368
1369When `already_dispatched` is true, the server may omit `data` or `data.swap_tx` (idempotent ack). Schema must not require them.
1370
1371```json
1372{
1373 "type": "object",
1374 "required": ["type", "order_id", "order_type", "status"],
1375 "properties": {
1376 "type": { "const": "order_filled" },
1377 "order_id": { "type": "string", "format": "uuid" },
1378 "order_type": { "type": "string", "enum": ["sell", "buy", "trailing_sell", "trailing_buy"] },
1379 "status": { "type": "string", "enum": ["success"] },
1380 "already_dispatched": { "type": "boolean" },
1381 "entry_mcap": { "type": "number" },
1382 "triggered_mcap": { "type": "number" },
1383 "filled_mcap": { "type": ["number", "null"] },
1384 "target_mcap": { "type": "number" },
1385 "triggered_at": { "type": "number" },
1386 "filled_at": { "type": "number" },
1387 "token_address": { "type": "string" },
1388 "server_signature": { "type": "string" },
1389 "data": {
1390 "type": "object",
1391 "properties": {
1392 "swap_tx": { "type": "string", "minLength": 100 },
1393 "token_address": { "type": "string" },
1394 "pool_type": { "type": "string" },
1395 "pool_address": { "type": "string" },
1396 "amount_in": { "type": "integer" },
1397 "min_amount_out": { "type": "integer" },
1398 "price_impact": { "type": "number" },
1399 "slippage": { "type": "integer" },
1400 "decimals": { "type": "integer" }
1401 }
1402 }
1403 }
1404}
1405```
1406
1407---
1408
1409## Retry / Idempotency Policy
1410
1411| Error class | Retry? | Max attempts | Backoff | Notes |
1412|-------------|--------|-------------|---------|-------|
1413| 400 from /swap | **No** | 0 | — | Bad request. Fix payload. |
1414| 422 from /swap | **No** | 0 | — | Missing fields. Fix payload. |
1415| "Error running simulation" | **Cooldown** | 0 immediate | 15m | Mark token unswappable for the session and retry later only if needed. |
1416| 503 from /protect | **Auto-fallback** | 1 | — | `submitTx()` falls back to RPC internally. No manual action. |
1417| /protect timeout (30s) | **Check first** | 1 | — | Check tx status via `connection.getSignatureStatuses([sig])`. Only retry if `value[0]` is null (not found). |
1418| /holdings timeout | **Yes** | 2 | 5s | Endpoint is slow, not broken. |
1419| /swap 5xx | **Yes** | 2 | 3s | Server issue, may resolve. |
1420| WS disconnect | **Reconnect** | ∞ | 3s fixed | Re-register. Orders persist. |
1421| WS error message | **No** | 0 | — | Log and surface to user. |
1422| On-chain swap failure | **Maybe** | 1 | — | Increase slippage to 2500, retry once. If fails again, skip. |
1423
1424**Idempotency:** Solana transactions include a recent blockhash. A signed tx can only land once. If /protect times out, the tx may have landed — always check via RPC before re-signing a new tx.
1425
1426---
1427
1428## Timeout and Confirmation Contracts
1429
1430| Endpoint | Timeout | On timeout |
1431|----------|---------|------------|
1432| `POST /swap` | 15s | Retry once with 3s backoff |
1433| `POST /protect` | 30s | Call `connection.getSignatureStatuses([sig])`. If `value[0]` is null → tx didn't land, safe to retry. If `value[0].err` → tx failed on-chain, do not retry. If `confirmationStatus` is `'processed'` → transitional, wait 2s and re-check. If `'confirmed'` or `'finalized'` → landed, do not retry. `submitTx()` handles all this internally. |
1434| `POST /holdings` | 100s | Retry once with 5s backoff |
1435| WebSocket connect | 10s | Retry with 3s backoff |
1436
1437### Post-timeout /protect check
1438
1439`checkTxLanded()` is defined in the Reference Client above. Returns `{ landed, sig, status }`:
1440- `{ landed: false, sig, status: 'not_found' }` — safe to retry via RPC fallback
1441- `{ landed: true, sig, status: 'failed', err }` — tx errored on-chain, do not retry
1442- `{ landed: true, sig, status: 'processed' }` — transitional, wait 2s and re-check
1443- `{ landed: true, sig, status: 'confirmed' }` — tx landed, do not retry
1444- `{ landed: true, sig, status: 'finalized' }` — tx landed and finalized, do not retry
1445
1446`sig` is the real base58 transaction signature for reconciliation. `submitTx()` handles all of this internally.
1447
1448---
1449
1450## WebSocket Lifecycle State Machine
1451
1452```
1453 ┌──────────────┐
1454 │ DISCONNECTED │ ←── ws.close / error / timeout
1455 └──────┬───────┘
1456 │ connect
1457 ▼
1458 ┌──────────────┐
1459 │ CHALLENGE │ ←── server sends {"type":"challenge","nonce":"..."}
1460 └──────┬───────┘
1461 │ sign nonce; send register with wallet_address + signature
1462 ▼
1463 ┌──────────────┐
1464 │ REGISTERED │ ←── server sends {"type":"registered","authenticated":true}
1465 └──────┬───────┘
1466 │ (can now send orders)
1467 ▼
1468 ┌──────────────┐
1469 │ ACTIVE │ ←── orders placed, listening for fills
1470 └──────────────┘
1471```
1472
1473**Rules:**
1474- **DISCONNECTED:** no sends allowed. Reconnect immediately.
1475- **CHALLENGE:** sign nonce and send `register` with wallet_address + signature only. All other sends rejected until REGISTERED.
1476- **REGISTERED / ACTIVE:** all actions allowed. Only enter REGISTERED state when `authenticated: true` is confirmed.
1477- On any disconnect, state resets to DISCONNECTED. Orders persist server-side.
1478- Queue any order sends that arrive during DISCONNECTED/CHALLENGE and flush after REGISTERED.
1479
1480---
1481
1482
1483## Execution Safety Guards
1484
1485All safety enforcement is **built into the reference client** — `enforceSafety()` is called inside `buildSwap()`, `KILL_SWITCH` is checked in `submitTx()` and `ws.send()`, `markUnswappable()` is called on "Error running simulation" responses, token cooldown is checked before WS order placement, and **dailyLoss** is updated on every successful spend path (protect success, timeout recovery, RPC fallback) for both `buy` and `trailing_buy`. **MAX_BUY_LAMPORTS** is enforced in `ws.send()` for `buy` and `trailing_buy` orders so WebSocket orders cannot bypass the per-trade limit.
1486
1487**Defaults (adjust per deployment):**
1488
1489`MAX_BUY_LAMPORTS = 0.5 SOL` is intentionally conservative for first deploys. Increase only after risk limits, kill switch, and monitoring are verified.
1490
1491| Guard | Default | Enforced in |
1492|-------|---------|-------------|
1493| MAX_BUY_LAMPORTS | 500,000,000 (0.5 SOL, conservative starter value) | `buildSwap()` via `enforceSafety()`, `ws.send()` for buy/trailing_buy |
1494| MAX_SLIPPAGE_BPS | 2500 (25%) | `buildSwap()` via `enforceSafety()` |
1495| MIN_SLIPPAGE_BPS | 100 (1%) | `buildSwap()` via `enforceSafety()` |
1496| MIN_VALUE_NATIVE | 0 (`valueNative > 0`, defensive) | `getHoldings()` filter |
1497| UNSWAPPABLE_COOLDOWN_MS | 900,000 (15 minutes) | `markUnswappable()` |
1498| MAX_DAILY_LOSS_LAMPORTS | 2,000,000,000 (2 SOL) | Updated on every spend path: `/protect` success, timeout_recovery, `_rpcFallback()`; `enforceSafety()` → activates KILL_SWITCH |
1499| DENYLIST | empty Map (session-scoped cooldown) | `buildSwap()`, `ws.send()`, auto-populated by `markUnswappable()` |
1500| KILL_SWITCH | false | `submitTx()`, `ws.send()`, auto-activated on daily loss limit |
1501
1502**Unswappable token cooldown:** When `/swap` returns "Error running simulation", `buildSwap()` calls `markUnswappable(tokenAddress)`, placing that token on a 15-minute session cooldown. This avoids retry loops while allowing future retries later.
1503
1504**Emergency kill:** Set `KILL_SWITCH = true` to halt all execution. Also auto-activates when `dailyLoss > MAX_DAILY_LOSS_LAMPORTS`.
1505
1506---
1507
1508## Logging Format
1509
1510All logging is through the `log()` function in the reference client, which outputs JSON lines with automatic timestamp and wallet fields.
1511
1512**Every step emitted by the reference client:**
1513
1514| Step | Emitted by | Required fields |
1515|------|-----------|----------------|
1516| swap_request | `buildSwap()` | token, action, amount/holdings_percentage, slippage |
1517| swap_response | `buildSwap()` | token, pool_type, amount_in |
1518| swap_error | `buildSwap()` | token, error |
1519| safety_blocked | `enforceSafety()`, `markUnswappable()`, `ws.send()` | token, reason |
1520| dry_run_skip | `submitTx()`, `ws.send()` | token, action, message |
1521| protect_success | `submitTx()` | token, signature |
1522| protect_503 | `submitTx()` | message |
1523| protect_timeout | `submitTx()` | token, message |
1524| protect_timeout_landed | `submitTx()` | signature, status |
1525| protect_timeout_processed | `submitTx()` | signature, message |
1526| protect_timeout_failed | `submitTx()` | signature, message |
1527| protect_timeout_not_landed | `submitTx()` | message |
1528| rpc_fallback_success | `_rpcFallback()` | signature |
1529| sell_skipped | `main()` | message |
1530| ws_connected | WS `open` handler | — |
1531| ws_registered | WS `registered` handler | — |
1532| ws_disconnected | WS `close` handler | message |
1533| ws_error | WS `error` handler | error |
1534| ws_queued | `ws.send()` | action, message |
1535| order_placed | WS `order_created` handler | order_id, token, action, target_mcap |
1536| order_filled | `handleOrderFilled()` | order_id, order_type, token, triggered_mcap, filled_mcap |
1537| order_fill_error | `handleOrderFilled()` | order_id, error |
1538| order_fill_skipped | `handleOrderFilled()` | order_id, reason, triggered_mcap, filled_mcap |
1539| order_fill_submitted | `handleOrderFilled()` | order_id, signature |
1540| order_fill_verify_failed | `verifyOrderFilledSignature()` | order_id, reason |
1541
1542---
1543
1544## Dry-Run / Paper Mode
1545
1546**Safe-by-default:** `DRY_RUN` is **true** unless you explicitly set `DRY_RUN=false`. A fresh agent runs paper mode automatically — no accidental live trades on first run.
1547
1548Dry-run is enforced at the two chokepoints in the reference client — `submitTx()` and `ws.send()`. The agent runs the full pipeline (fetches swap quotes, enforces safety guards, logs everything) but:
1549
1550- **`submitTx()`** short-circuits before submission and returns `{ signature: null, dry_run: true }`
1551- **`ws.send()`** blocks all mutating actions (`sell`, `buy`, `trailing_sell`, `trailing_buy`, `cancel_order`, `extend_order`) and logs intent
1552- Only read-only operations pass through: `register`, `list_orders`, `check_order`
1553
1554There is no separate "paper mode function." The same `main()` code path runs in both modes — `DRY_RUN` just gates the irreversible actions.
1555
1556```bash
1557# Paper mode (default — no DRY_RUN env needed)
1558PRIVATE_KEY=... node agent.js
1559
1560# Live mode — must explicitly opt in
1561DRY_RUN=false PRIVATE_KEY=... node agent.js
1562```
1563
1564---
1565
1566## Preflight Startup Checklist
1567
1568The `preflight()` function is built into the reference client. It runs automatically at the start of `main()` and exits the process if any check fails.
1569
1570**Checks performed:**
1571
1572| Check | Fails if |
1573|-------|----------|
1574| PRIVATE_KEY loaded | env var missing |
1575| RPC_URL configured | always passes (warns if using default public RPC) |
1576| Wallet loads | key is invalid/undecodable |
1577| RPC reachable | `getSlot()` fails |
1578| SOL balance > 0.01 | balance < 10,000,000 lamports |
1579| /holdings responds | endpoint unreachable or times out |
1580| WS register | WebSocket connect, challenge–response, or `authenticated: true` confirmation fails within 10s |
1581
1582After all checks, preflight reports mode (`DRY RUN` or `LIVE TRADING`).