From 55fbaf7dd94f423d6bac7eb5643d2391d6679faf Mon Sep 17 00:00:00 2001 From: kadi Date: Thu, 18 Jun 2026 20:28:05 +1000 Subject: [PATCH 1/7] Add StockWaves skill: China & global market data + quant signals + tokenized-stock safety gate (x402) China-market intelligence (Weibo/Baidu/Douyin pulse, structured CN news/events, sector-theme momentum), quant signals across A-share/HK/US equities + crypto + macro, and an on-chain tokenized-stock pre-trade safety gate (real token vs copycat, depeg, liquidity, market-hours, freeze-authority). All x402 pay-per-call, USDC on Base + Solana, no signup or API key. Co-Authored-By: Claude Opus 4.8 (1M context) --- stockwaves/catalog.json | 24 ++++++++++++++ stockwaves/skill.md | 72 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 96 insertions(+) create mode 100644 stockwaves/catalog.json create mode 100644 stockwaves/skill.md diff --git a/stockwaves/catalog.json b/stockwaves/catalog.json new file mode 100644 index 0000000000..90f66c5adf --- /dev/null +++ b/stockwaves/catalog.json @@ -0,0 +1,24 @@ +{ + "schemaVersion": 1, + "slug": "stockwaves", + "provider": "StockWaves", + "providerUrl": "https://stockwaves.net", + "logo": null, + "demo": { + "title": "stockwaves-x402.ts", + "language": "typescript", + "code": "import { x402Client, wrapFetchWithPayment } from \"@x402/fetch\";\nimport { ExactEvmScheme } from \"@x402/evm/exact/client\";\nimport { privateKeyToAccount } from \"viem/accounts\";\n\nconst BASE_URL = \"https://stockwaves.net\";\nconst signer = privateKeyToAccount(process.env.EVM_PRIVATE_KEY as `0x${string}`);\n\n// No API key, no signup — every endpoint is x402 pay-per-call (USDC on Base or Solana).\nconst client = new x402Client();\nclient.register(\"eip155:*\", new ExactEvmScheme(signer));\nconst pay = wrapFetchWithPayment(fetch, client);\n\n// China social pulse — Weibo + Baidu + Douyin hot-search, structured (~$0.03)\nconst pulse = await (await pay(`${BASE_URL}/api/cn/trending?platform=all&limit=20`)).json();\n\n// Pre-trade safety on a tokenized US stock: is this the REAL issuer token vs a copycat? (~$0.03)\nconst gate = await (await pay(`${BASE_URL}/api/xstock/health?symbol=AAPLx`)).json();\n\n// FREE — no payment: proof-before-you-buy backtest, and a free safety preview\nconst track = await (await fetch(`${BASE_URL}/api/track-record`)).json();\nconst preview = await (await fetch(`${BASE_URL}/api/xstock/health/preview?symbol=NVDAx`)).json();" + }, + "setup": [ + "No signup and no API key — every paid endpoint speaks x402 directly.", + "Pay with any standard x402 client: the 402 challenge offers Base (eip155:8453) AND Solana — pick either, asset is USDC.", + "Prefer Bankr wallet signing (`/agent/sign`) when available — set `BANKR_API_KEY` (Agent API + signing enabled).", + "Otherwise set `EVM_PRIVATE_KEY` (a USDC-funded Base wallet) and install `@x402/fetch` + `@x402/evm`.", + "Discover everything zero-config: GET https://stockwaves.net/.well-known/x402 , /openapi.json , /llms.txt" + ], + "install": { + "type": "bankr", + "repoPath": "stockwaves", + "command": "install the stockwaves skill from https://github.com/BankrBot/skills/tree/main/stockwaves" + } +} diff --git a/stockwaves/skill.md b/stockwaves/skill.md new file mode 100644 index 0000000000..0800069c17 --- /dev/null +++ b/stockwaves/skill.md @@ -0,0 +1,72 @@ +--- +name: stockwaves-api +description: Pay-per-call China & global market data, quant signals, and a tokenized-stock pre-trade safety gate over x402. Use when an agent needs Chinese-market intelligence (Weibo/Baidu/Douyin pulse, structured CN news/events, sector momentum), cross-asset quant signals (A-share/HK/US equities, crypto, macro), or a pre-buy safety check on an on-chain tokenized US stock (real token vs copycat, depeg, liquidity, market-hours). +--- + +# StockWaves API Skill + +Use this skill when an agent needs market data Western APIs can't reach (real-time Chinese internet pulse + structured CN market intelligence), quant trading signals across China/HK/US equities, crypto and cross-asset macro, OR a pre-trade safety verdict on a tokenized US stock before buying it on-chain. + +Every endpoint is **x402 pay-per-call** — no signup, no API key. The skill's job is to execute the x402 flow correctly and pick the right endpoint. + +## Base URL + +- `STOCKWAVES_BASE_URL`: `https://stockwaves.net` +- Single origin for runtime requests AND discovery docs (`/.well-known/x402`, `/openapi.json`, `/llms.txt`). + +## Access Model + +- **x402 only** — there is no API-key path. Unpaid requests return HTTP `402`. +- The 402 challenge offers **two rails — Base (`eip155:8453`) and Solana (`solana:…`)**. Pay on either; asset is USDC; scheme is standard x402 `exact` (EIP-3009 on Base / signed tx on Solana), settled via the Coinbase/CDP facilitator. +- Prefer **Bankr wallet signing** (`/agent/sign`) when available — set a Bankr API key via `X-API-Key` with Agent API access + signing permissions (not read-only). +- Otherwise use any vanilla x402 client (SIWE/SIWX) with a USDC-funded wallet. + +## x402 API Call Checklist + +1. Send the request to the StockWaves endpoint without payment headers. +2. If the response is `402`, parse the base64 `PAYMENT-REQUIRED` header (it carries scheme, both networks, USDC asset, amount, payTo). +3. Sign the payment and retry with the `PAYMENT-SIGNATURE` header. +4. On success, read the data and the `PAYMENT-RESPONSE` settle receipt. +5. Apply retry/backoff for `402` re-challenges and transient `5xx`; a `4xx` from the handler means you were NOT charged (settlement only occurs on status < 400). + +## Required Preflight (Deterministic) + +Before the first call in a session, fetch the discovery docs (all free, no payment): + +- `GET /.well-known/x402` — the list of paid resources. +- `GET /openapi.json` — canonical route + query-param metadata (treat as authoritative for invocation). +- `GET /llms.txt` — human/agent-readable catalog with prices and how-to-pay. +- Treat the runtime `402` challenge as authoritative for price/network/payTo. + +## Core Endpoints (price = USDC per call) + +China-market intelligence (data Western agents can't reach): +- `GET /api/cn/trending` — $0.03 — live Weibo + Baidu + Douyin hot-search, structured (per-platform rank, heat, category). Query: `?platform=all|weibo|baidu|douyin&limit=1-50&category=` +- `GET /api/cn/news` — $0.04 — structured CN market news & risk feed: per-event-type sentiment, mention counts, ticker mapping, risk keywords + severity (English labels; derived structure, no article text). Query: `?limit=1-50&ticker=` +- `GET /api/cn/themes` — $0.06 — China industrial-theme momentum (AI compute / semis / robotics / defense / new energy): per-theme rotation-strength + per-board rank/trend/lifecycle. +- `GET /api/cn/brief` — $0.08 — ONE-call synthesized China daily brief: social pulse + market events + risk alerts + hot themes + top sector rotation. Query: `?top=5` + +Quant signals (A-share / HK / US equities, crypto, macro): +- `GET /api/recommend` — $0.50 — Top-N stock picks (4-factor resonance) with take-profit / stop-loss. Query: `?market=A|US&limit=1-100` +- `GET /api/dealer` — $0.08 — dealer (smart-money) 6-signal scan across A-shares. Query: `?top_n=1-1000&limit=1-500` +- `GET /api/rotation` — $0.05 — sector rotation forecast (strength + momentum + catalyst). Query: `?limit=1-100` +- `GET /api/anomalies/insight` — $0.05 — blind-spot / anomaly insight: setups the system keeps missing. Query: `?days=1-90` +- `GET /api/btc/signal` — $0.03 — real-time BTC/USDT directional signal (RL model): position lean [-1,1], direction, conviction, risk flags. +- `GET /api/macro/allocation` — $0.10 — cross-asset ETF tactical allocation (QQQ/IWM/SPY/TLT/DBC/GLD): per-ETF signal, position, confidence, regime. +- `GET /api/crypto/microstructure` — $0.01 — live crypto perp microstructure (Binance public): funding, premium/basis, OI (+USD), taker buy/sell ratio, 24h realized vol. Query: `?symbol=BTCUSDT` + +Compute (bring your own signals): +- `POST /api/portfolio/optimize` — $0.05 — stateless portfolio optimizer. POST `{assets:[{symbol,target,confidence?,vol?,regime?}], config?}` → risk-constrained weights (inverse-vol, conviction scaling, correlation penalty, gross/net + per-symbol caps, regime haircut). + +Tokenized US stocks — pre-trade safety gate (any issuer, multi-chain): +- `GET /api/xstock/health` — $0.03 — before an agent BUYS an on-chain US stock, check it's the REAL token and safe right now. Multi-issuer (Backed/xStocks, Ondo, Remora/rStocks, Backpack Securities), multi-chain (Solana + EVM incl. BNB). `?symbol=AAPLx|AAPLon|TSLAr|SPCX` OR `?address=` → `decision` (ok/review/avoid) + signals: **authenticity** (verified vs the issuer's own registry — a token claiming a ticker but not on the allowlist is flagged a COPYCAT), **depeg_bps** (DEX price vs Pyth equity oracle), **market_status**, **liquidity_usd**, **trading_halted**, **freeze_authority**, supply. Diligence support — NOT investment/legal advice. + +Free (no payment): +- `GET /api/track-record` — FREE — walk-forward backtest performance (Sharpe, return, max drawdown) of the systematic strategy behind the paid signals. Proof before you buy. +- `GET /api/xstock/health/preview` — FREE (rate-limited) — the safety verdict + authenticity for one token at zero cost (the full numeric signals stay behind the paid `/api/xstock/health`). `?symbol=` or `?address=`. + +## Notes + +- All endpoints return English fields (`event_en`, `board_en`, `signals_en`, …) alongside the originals; stocks are identified by language-neutral `symbol` (ticker). +- Derived structured output only — no third-party article text (copyright-safe). +- Informational data, NOT investment advice. Terms: `https://stockwaves.net/terms`. From 2bdaeea2a98a641fdffd55cfa13485e9842471c9 Mon Sep 17 00:00:00 2001 From: kadi Date: Thu, 18 Jun 2026 20:28:40 +1000 Subject: [PATCH 2/7] Add StockWaves to the Available Skills table Co-Authored-By: Claude Opus 4.8 (1M context) --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index bc5b17c034..79d850f132 100644 --- a/README.md +++ b/README.md @@ -57,6 +57,7 @@ Bankr Skills equip builders with plug-and-play tools to build more powerful agen | [qrcoin](https://qrcoin.fun) | [qrcoin](qrcoin/) | QR code auction game. Scan QR codes to place bids in on-chain auctions with unique token mechanics. | | [Quicknode](https://www.quicknode.com) | [quicknode](quicknode/) | Blockchain RPC and data access for all supported chains. Native/token balances, gas estimation, transaction status, and onchain queries for Base, Ethereum, Polygon, Solana, and Unichain. Supports API key and x402 pay-per-request access. | | [Quotient](https://quotient.social) | [quotient](quotient/) | Market intelligence API with x402 micropayment and API key auth. Access onchain/social analytics, OpenAPI discovery, and pricing data via `q-api.quotient.social`. | +| [StockWaves](https://stockwaves.net) | [stockwaves](stockwaves/) | China & global market data + quant signals + a tokenized-stock pre-trade safety gate — all x402 pay-per-call (USDC on Base + Solana, no signup, no API key). Real-time Weibo/Baidu/Douyin hot-search pulse, structured CN news/events + sector-theme momentum; quant signals across A-share/HK/US equities, crypto, and cross-asset macro; and an "is this the REAL token vs a copycat?" gate (depeg / liquidity / market-hours / freeze-authority) across Backed/Ondo/Remora/Backpack on Solana + EVM. Free preview + walk-forward track-record. | | [SIGNA](https://www.signaagent.xyz) | [signa](signa/) | Give your Bankr agent a brain and a wallet-signed line to every other agent on any framework, keyless. Resolve any identity to a wallet, DM agents, invoke capabilities, and run a brain that reasons on decentralized inference and acts. No API key. | | [Axiom](https://clawbots.org) | [signals](signals/) | Transaction-verified trading signals on Base. Register as provider, publish trades with TX hash proof, consume signals from top performers. | | [Builder's Garden](https://builders.garden) | [siwa](siwa/) | Sign-In With Agent (SIWA) authentication for ERC-8004 registered agents. Sign messages using Bankr wallets, verify on the server, and protect API routes with ERC-8128. | From 5a63dc9106998cea816eb440bd50ee63e5c952ea Mon Sep 17 00:00:00 2001 From: kadi Date: Thu, 18 Jun 2026 20:36:37 +1000 Subject: [PATCH 3/7] Polish stockwaves demo: use the verified createPaymentPayload + PAYMENT-SIGNATURE recipe (the working x402 flow), align setup deps Co-Authored-By: Claude Opus 4.8 (1M context) --- stockwaves/catalog.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/stockwaves/catalog.json b/stockwaves/catalog.json index 90f66c5adf..581a0aceeb 100644 --- a/stockwaves/catalog.json +++ b/stockwaves/catalog.json @@ -7,13 +7,13 @@ "demo": { "title": "stockwaves-x402.ts", "language": "typescript", - "code": "import { x402Client, wrapFetchWithPayment } from \"@x402/fetch\";\nimport { ExactEvmScheme } from \"@x402/evm/exact/client\";\nimport { privateKeyToAccount } from \"viem/accounts\";\n\nconst BASE_URL = \"https://stockwaves.net\";\nconst signer = privateKeyToAccount(process.env.EVM_PRIVATE_KEY as `0x${string}`);\n\n// No API key, no signup — every endpoint is x402 pay-per-call (USDC on Base or Solana).\nconst client = new x402Client();\nclient.register(\"eip155:*\", new ExactEvmScheme(signer));\nconst pay = wrapFetchWithPayment(fetch, client);\n\n// China social pulse — Weibo + Baidu + Douyin hot-search, structured (~$0.03)\nconst pulse = await (await pay(`${BASE_URL}/api/cn/trending?platform=all&limit=20`)).json();\n\n// Pre-trade safety on a tokenized US stock: is this the REAL issuer token vs a copycat? (~$0.03)\nconst gate = await (await pay(`${BASE_URL}/api/xstock/health?symbol=AAPLx`)).json();\n\n// FREE — no payment: proof-before-you-buy backtest, and a free safety preview\nconst track = await (await fetch(`${BASE_URL}/api/track-record`)).json();\nconst preview = await (await fetch(`${BASE_URL}/api/xstock/health/preview?symbol=NVDAx`)).json();" + "code": "import { x402Client, x402HTTPClient } from \"@x402/core/client\";\nimport { encodePaymentSignatureHeader } from \"@x402/core/http\";\nimport { registerExactEvmScheme } from \"@x402/evm/exact/client\";\nimport { privateKeyToAccount } from \"viem/accounts\";\n\nconst signer = privateKeyToAccount(process.env.EVM_PRIVATE_KEY as `0x${string}`);\nconst client = new x402Client();\nregisterExactEvmScheme(client, { signer });\nconst http = new x402HTTPClient(client);\n\n// Standard x402: 402 -> decode PAYMENT-REQUIRED -> sign -> retry with PAYMENT-SIGNATURE.\n// (Bankr agents can use Bankr wallet signing instead -- see setup.)\nasync function pay(url: string, init: RequestInit = {}) {\n let res = await fetch(url, init);\n if (res.status === 402) {\n const challenge = JSON.parse(Buffer.from(res.headers.get(\"PAYMENT-REQUIRED\")!, \"base64\").toString());\n const sig = encodePaymentSignatureHeader(await http.createPaymentPayload(challenge));\n res = await fetch(url, { ...init, headers: { ...init.headers, \"PAYMENT-SIGNATURE\": sig } });\n }\n return res.json();\n}\n\nconst BASE_URL = \"https://stockwaves.net\";\nconst pulse = await pay(`${BASE_URL}/api/cn/trending?platform=all&limit=20`); // ~$0.03 USDC -- China hot-search pulse\nconst gate = await pay(`${BASE_URL}/api/xstock/health?symbol=AAPLx`); // ~$0.03 -- REAL token vs copycat\nconst free = await (await fetch(`${BASE_URL}/api/xstock/health/preview?symbol=NVDAx`)).json(); // FREE preview" }, "setup": [ "No signup and no API key — every paid endpoint speaks x402 directly.", "Pay with any standard x402 client: the 402 challenge offers Base (eip155:8453) AND Solana — pick either, asset is USDC.", "Prefer Bankr wallet signing (`/agent/sign`) when available — set `BANKR_API_KEY` (Agent API + signing enabled).", - "Otherwise set `EVM_PRIVATE_KEY` (a USDC-funded Base wallet) and install `@x402/fetch` + `@x402/evm`.", + "Otherwise set `EVM_PRIVATE_KEY` (a USDC-funded Base wallet) and install `@x402/core` + `@x402/evm` + `viem`.", "Discover everything zero-config: GET https://stockwaves.net/.well-known/x402 , /openapi.json , /llms.txt" ], "install": { @@ -21,4 +21,4 @@ "repoPath": "stockwaves", "command": "install the stockwaves skill from https://github.com/BankrBot/skills/tree/main/stockwaves" } -} +} \ No newline at end of file From 291a5723290027c1d9c0371df1d89116d33442c7 Mon Sep 17 00:00:00 2001 From: kadi Date: Thu, 18 Jun 2026 20:43:15 +1000 Subject: [PATCH 4/7] Add stockwaves references/api-reference.md Co-Authored-By: Claude Opus 4.8 (1M context) --- stockwaves/references/api-reference.md | 40 ++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 stockwaves/references/api-reference.md diff --git a/stockwaves/references/api-reference.md b/stockwaves/references/api-reference.md new file mode 100644 index 0000000000..0c01202238 --- /dev/null +++ b/stockwaves/references/api-reference.md @@ -0,0 +1,40 @@ +# StockWaves API Reference + +Base URL `https://stockwaves.net`. All endpoints return English fields alongside originals; stocks are identified by language-neutral `symbol` (ticker). Prices are USDC per call. Canonical machine spec: `/openapi.json`. + +## China-market intelligence +| Endpoint | Price | Query | Returns | +|---|---|---|---| +| `GET /api/cn/trending` | $0.03 | `platform=all\|weibo\|baidu\|douyin`, `limit=1-50`, `category=` | per-platform hot-search rows: `rank`, `term`, `category`, `heat` (native scale, NOT cross-platform comparable), `marker`/`is_rising` (Weibo). | +| `GET /api/cn/news` | $0.04 | `limit=1-50`, `ticker=` | events `{ticker, event, event_en, sentiment, count, sources}`; risks `{detected_at, ticker, severity, kind, keywords}`. Derived structure only — no article text. | +| `GET /api/cn/themes` | $0.06 | — | per industrial theme (AI compute/semis/robotics/defense/new energy): agg rotation-strength; per board: rot_score, rank, trend, lifecycle. | +| `GET /api/cn/brief` | $0.08 | `top=1-10` | one-call synthesized China daily: social_pulse + market_events + risk_alerts + industrial_themes + sector_rotation_top. | + +## Quant signals +| Endpoint | Price | Query | Returns | +|---|---|---|---| +| `GET /api/recommend` | $0.50 | `market=A\|US`, `limit=1-100` | Top-N picks (4-factor resonance) + take-profit / stop-loss. | +| `GET /api/dealer` | $0.08 | `top_n=1-1000`, `limit=1-500` | dealer (smart-money) 6-signal scan across A-shares. | +| `GET /api/rotation` | $0.05 | `limit=1-100` | sector rotation forecast: strength + momentum + catalyst. | +| `GET /api/anomalies/insight` | $0.05 | `days=1-90` | blind-spot / anomaly setups the system keeps missing. | +| `GET /api/btc/signal` | $0.03 | — | BTC/USDT RL signal: position lean [-1,1], direction, conviction, risk flags. | +| `GET /api/macro/allocation` | $0.10 | `symbols=` (CSV) | cross-asset ETF allocation (QQQ/IWM/SPY/TLT/DBC/GLD): signal, position, confidence, regime. | +| `GET /api/crypto/microstructure` | $0.01 | `symbol=BTCUSDT` ({BTC,ETH,SOL,BNB,XRP,DOGE}USDT) | live perp microstructure: funding, premium/basis, OI (+USD), taker buy/sell ratio, 24h realized vol. | + +## Compute +| Endpoint | Price | Body | Returns | +|---|---|---|---| +| `POST /api/portfolio/optimize` | $0.05 | `{assets:[{symbol,target,confidence?,vol?,regime?}], config?}` | risk-constrained weights (inverse-vol, conviction scaling, correlation penalty, gross/net + per-symbol caps, regime haircut). | + +## Tokenized US stocks — pre-trade safety gate +| Endpoint | Price | Query | Returns | +|---|---|---|---| +| `GET /api/xstock/health` | $0.03 | `symbol=AAPLx\|AAPLon\|TSLAr\|SPCX` OR `address=` | `decision` (ok/review/avoid) + signals: `authenticity` (verified vs issuer registry — Backed/Ondo/Remora/Backpack; off-allowlist = COPYCAT), `depeg_bps` (DEX vs Pyth equity oracle), `market_status`, `liquidity_usd`, `trading_halted`, `freeze_authority`, `onchain_supply`. Multi-chain (Solana + EVM incl. BNB). | + +## Free (no payment) +| Endpoint | Query | Returns | +|---|---|---| +| `GET /api/track-record` | — | walk-forward backtest (Sharpe, return, max drawdown, WF score). Proof before you buy. | +| `GET /api/xstock/health/preview` | `symbol=` or `address=` | rate-limited: the safety `decision` + `authenticity` only (full numeric signals stay behind the paid gate). | + +Informational data, NOT investment advice. Terms: `https://stockwaves.net/terms`. From 4ba9ab5ca25c197e4094d6b44bc473b71d009fb9 Mon Sep 17 00:00:00 2001 From: kadi Date: Thu, 18 Jun 2026 20:43:16 +1000 Subject: [PATCH 5/7] Add stockwaves references/x402-flow.md Co-Authored-By: Claude Opus 4.8 (1M context) --- stockwaves/references/x402-flow.md | 45 ++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 stockwaves/references/x402-flow.md diff --git a/stockwaves/references/x402-flow.md b/stockwaves/references/x402-flow.md new file mode 100644 index 0000000000..047c51b31d --- /dev/null +++ b/stockwaves/references/x402-flow.md @@ -0,0 +1,45 @@ +# x402 Payment Flow + +Two ways to pay, in order of preference. + +## 1. Bankr wallet signing (preferred) +If running inside Bankr, let Bankr sign: call `/agent/sign` with a Bankr API key (`X-API-Key`, Agent API + signing enabled, not read-only). Bankr handles the 402 challenge/settle for you — you just issue the request. + +## 2. Vanilla x402 (any agent) +For non-Bankr agents, do the standard challenge → sign → retry. This is the recipe verified end-to-end against these endpoints (the load-bearing detail is the `PAYMENT-SIGNATURE` request header — not `X-PAYMENT`). + +### Protocol +1. Send the request (GET, or POST with a JSON body) without payment headers. +2. If status is `402`, base64-decode the `PAYMENT-REQUIRED` response header → the challenge JSON (`accepts` offers Base `eip155:8453` AND Solana; asset USDC; scheme `exact`). +3. Build a payment payload from the challenge and encode it as the `PAYMENT-SIGNATURE` header. +4. Retry the SAME request (do not mutate path/query/body) with that header. +5. On success, read the data and the `PAYMENT-RESPONSE` settle receipt. + +### Reference implementation (TypeScript) +```ts +import { x402Client, x402HTTPClient } from "@x402/core/client"; +import { encodePaymentSignatureHeader } from "@x402/core/http"; +import { registerExactEvmScheme } from "@x402/evm/exact/client"; +import { privateKeyToAccount } from "viem/accounts"; + +const signer = privateKeyToAccount(process.env.EVM_PRIVATE_KEY as `0x${string}`); +const client = new x402Client(); +registerExactEvmScheme(client, { signer }); +const http = new x402HTTPClient(client); + +export async function pay(url: string, init: RequestInit = {}) { + let res = await fetch(url, init); + if (res.status === 402) { + const challenge = JSON.parse(Buffer.from(res.headers.get("PAYMENT-REQUIRED")!, "base64").toString()); + const sig = encodePaymentSignatureHeader(await http.createPaymentPayload(challenge)); + res = await fetch(url, { ...init, headers: { ...init.headers, "PAYMENT-SIGNATURE": sig } }); + } + return res.json(); +} +``` + +### Reliability rules +- Do NOT change path/query/body between the challenge and the paid retry. +- One nonce settles once: a duplicate/replayed `PAYMENT-SIGNATURE` is rejected (the facilitator dedups in-flight). Build a fresh payment per logical call. +- Settlement happens only when the handler returns status < 400 — a `4xx` (bad params) means you were NOT charged. +- Pay on EITHER rail; pick Solana if your wallet is SPL-funded, Base if EVM-funded. From e0ec94b64b4ea4ed4b8fc5cce0438c10852c7248 Mon Sep 17 00:00:00 2001 From: kadi Date: Thu, 18 Jun 2026 20:43:17 +1000 Subject: [PATCH 6/7] Add stockwaves references/error-handling.md Co-Authored-By: Claude Opus 4.8 (1M context) --- stockwaves/references/error-handling.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 stockwaves/references/error-handling.md diff --git a/stockwaves/references/error-handling.md b/stockwaves/references/error-handling.md new file mode 100644 index 0000000000..09742e1742 --- /dev/null +++ b/stockwaves/references/error-handling.md @@ -0,0 +1,16 @@ +# Error Handling + +| Status | Meaning | Action | +|---|---|---| +| `402` | Payment required (first leg of every paid call). | Read `PAYMENT-REQUIRED`, sign, retry with `PAYMENT-SIGNATURE`. Not an error. | +| `200` | Success. | Read the body and the `PAYMENT-RESPONSE` settle receipt. | +| `400` | Bad params / body. | Fix the request. You were NOT charged (settlement only on status < 400) — do not retry blindly. | +| `402` after paying | Stale/duplicate payment, or a re-challenge. | Fetch a FRESH challenge and rebuild the payment payload (one nonce settles once). | +| `429` | Rate limited (mainly the FREE preview tiers, per-IP daily quota). | Back off; switch to the paid endpoint, or retry later. Paid calls are not quota-limited. | +| `5xx` | Transient upstream/server error. | Bounded retry with exponential backoff (e.g. 3 tries). You were NOT charged. | + +## Rules +- Settlement is server-response-based: it occurs only when the handler returns status < 400, so a `4xx` never costs USDC. +- Do not mutate path/query/body between the challenge and the paid retry — it invalidates the signature. +- Treat the runtime `402` challenge (price/network/payTo) as authoritative over any cached pricing. +- Never log or echo the raw `PAYMENT-SIGNATURE` or the signer key. From b5f502fa0b3ceb1f35d201e5c4fcf736e35821b3 Mon Sep 17 00:00:00 2001 From: kadi Date: Thu, 18 Jun 2026 20:43:19 +1000 Subject: [PATCH 7/7] Link references from stockwaves skill.md Co-Authored-By: Claude Opus 4.8 (1M context) --- stockwaves/skill.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/stockwaves/skill.md b/stockwaves/skill.md index 0800069c17..80b7150d71 100644 --- a/stockwaves/skill.md +++ b/stockwaves/skill.md @@ -70,3 +70,8 @@ Free (no payment): - All endpoints return English fields (`event_en`, `board_en`, `signals_en`, …) alongside the originals; stocks are identified by language-neutral `symbol` (ticker). - Derived structured output only — no third-party article text (copyright-safe). - Informational data, NOT investment advice. Terms: `https://stockwaves.net/terms`. + +## References +- API reference (all endpoints, params, response fields): `/skill/references/api-reference.md` +- x402 payment flow (Bankr signing + verified vanilla recipe): `/skill/references/x402-flow.md` +- Error handling (402 / 429 / 4xx / 5xx, retry rules): `/skill/references/error-handling.md`