cred402/sdk/index.ts
caelum0x 7fdc321d79 feat: live-wire Casper writes, add marketing homepage, fix cold-start UX
Round 1 against STRATEGY-2026-10-23.md's backlog:

- Wire register_agent/stake/set_credit_score/deposit_liquidity to the real
  Casper Testnet contracts (lib/casper/live_bridge.ts), verified live against
  the real RPC node with a freshly generated (unfunded) keypair
  (npm run casper:keygen). Honesty flags built in for the Odra payable
  calling convention and the admin-gated set_credit_score call.
- Unblock NEAR's paid x402 route (npm run near:keygen generates a real
  implicit account id); QIE stays correctly flagged as blocked on unconfirmed
  external facts (asset contract, facilitator), not env plumbing.
- New public Home tab: live-stats hero, how-it-works, a real competitor
  comparison table, and a "90-second proof" that calls the real API live in
  the browser (verified end-to-end with gstack browse).
- Cold-start UX: visible retry state in X402Playground + the TS SDK, plus a
  keep-warm self-ping (lib/services/keepalive.ts) so the free Render dyno
  rarely idles out from under a real first-time caller.
- New GET /v1/credit-score/:agentId alias + docs/integrations/ samples for
  Skyfire/Nevermined/Coinbase x402.
- Self-hosting quickstart: root docker-compose.yml + scripts/bootstrap.sh,
  both run for real; fixed a real EACCES crash-loop bug in infra/Dockerfile
  (non-root user never owned the /data volume mount) found while verifying.

450/450 tests pass, typecheck clean, frontend build clean.
2026-10-23 19:57:40 +03:00

127 lines
5.6 KiB
TypeScript

/**
* @cred402/sdk — a thin TypeScript client for the Cred402 protocol.
*
* Wraps the REST API, the x402 paid-evidence flow, and the SSE event stream so an
* external agent (TS/Node) can integrate in a few lines:
*
* const c = new Cred402Client("http://localhost:4021");
* const passport = await c.getPassport("EvidenceSellerAgent");
* const report = await c.buyEvidence("energy_output"); // full x402 dance
*/
import { generateAgentKeypair, signPayment, type AgentKeypair, type PaymentChallenge } from "../lib/x402/index.js";
export interface Cred402ClientOptions {
baseUrl?: string;
/** Identity used to sign x402 payment authorizations. A fresh one is generated if omitted. */
keypair?: AgentKeypair;
agentId?: string;
}
export class Cred402Client {
readonly baseUrl: string;
readonly keypair: AgentKeypair;
readonly agentId: string;
constructor(opts: Cred402ClientOptions | string = {}) {
const o = typeof opts === "string" ? { baseUrl: opts } : opts;
this.baseUrl = (o.baseUrl ?? "http://localhost:4021").replace(/\/$/, "");
this.keypair = o.keypair ?? generateAgentKeypair();
this.agentId = o.agentId ?? "sdk.agent";
}
// ---- reads ----
getState() { return this.get("/api/state"); }
getAgents() { return this.get("/api/agents"); }
getPassports() { return this.get("/api/passports"); }
getPassport(agentId: string) { return this.get(`/api/passport/${encodeURIComponent(agentId)}`); }
getReceipts() { return this.get("/api/receipts"); }
getCreditLine(agentId: string) { return this.get("/api/pool").then((p: any) => p.creditLines.find((l: any) => l.agent_id === agentId)); }
getDisputes() { return this.get("/api/disputes"); }
getGovernance() { return this.get("/api/governance"); }
getAssets() { return this.get("/api/assets"); }
getRiskPolicy() { return this.get("/api/health"); }
// ---- actions ----
runDemo(dispute = false) { return this.post(dispute ? "/api/demo/dispute" : "/api/demo/run"); }
openDispute(body: { dispute_type: string; respondent_agent: string; note?: string; receipt_id?: string }) {
return this.post("/api/disputes/open", body);
}
setGovernanceParam(key: string, value: unknown) { return this.post("/api/governance/param", { key, value }); }
upgradePolicy(version: string) { return this.post("/api/policy/upgrade", { version }); }
/**
* The full x402 flow: GET the paid endpoint, sign the challenge, retry, return
* the signed report. Mirrors `scripts/x402_client.ts` as a reusable method.
*/
async buyEvidence(evidenceType: string, rwaId = "SOLAR-A17"): Promise<unknown> {
const url = `${this.baseUrl}/verify/${evidenceType}?rwa_id=${rwaId}&buyer=${encodeURIComponent(this.agentId)}`;
const challengeRes = await fetch(url);
if (challengeRes.status !== 402) throw new Error(`expected 402, got ${challengeRes.status}`);
const { challenge } = (await challengeRes.json()) as { challenge: PaymentChallenge };
const { header } = signPayment({
challenge,
payer_agent: this.agentId,
payer_public_key: this.keypair.publicKeyHex,
payer_private_pem: this.keypair.privatePem,
});
const paid = await fetch(url, { headers: { "X-Payment": header } });
if (!paid.ok) throw new Error(`payment failed: ${paid.status}`);
return paid.json();
}
/** Subscribe to the SSE event stream (browser or Node 18+ with EventSource). */
watchEvents(onEvent: (e: unknown) => void): () => void {
const ES = (globalThis as { EventSource?: typeof EventSource }).EventSource;
if (!ES) throw new Error("EventSource not available in this runtime");
const es = new ES(`${this.baseUrl}/api/events/stream`);
es.addEventListener("chain", (ev) => onEvent(JSON.parse((ev as MessageEvent).data)));
return () => es.close();
}
/**
* Cold-start-aware request: the hosted reference deployment (Render free tier)
* can take 30-60s to wake from idle. Retries transient network failures and
* 502/503 "still booting" responses with backoff for ~60s before giving up,
* so a real first-time integrator's call survives the wake-up instead of
* reading as a dead API. Resolves on the first try once the backend is warm.
*/
private async requestWithRetry(path: string, init: RequestInit): Promise<Response> {
const delays = [1500, 3000, 6000, 10000, 15000, 20000];
let lastErr: unknown;
for (let attempt = 0; attempt <= delays.length; attempt++) {
try {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 12_000);
const res = await fetch(`${this.baseUrl}${path}`, { ...init, signal: controller.signal });
clearTimeout(timeout);
if ((res.status === 502 || res.status === 503) && attempt < delays.length) {
throw new Error(`${path} -> ${res.status} (cold start?)`);
}
return res;
} catch (err) {
lastErr = err;
if (attempt >= delays.length) break;
await new Promise((r) => setTimeout(r, delays[attempt]));
}
}
throw lastErr instanceof Error ? lastErr : new Error(`${path} failed`);
}
private async get(path: string): Promise<any> {
const res = await this.requestWithRetry(path, { method: "GET" });
if (!res.ok) throw new Error(`${path} -> ${res.status}`);
return res.json();
}
private async post(path: string, body?: unknown): Promise<any> {
const res = await this.requestWithRetry(path, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: body ? JSON.stringify(body) : undefined,
});
if (!res.ok) throw new Error(`${path} -> ${res.status}`);
return res.json();
}
}
export { generateAgentKeypair } from "../lib/x402/index.js";