feat(phase1): wallet scanner — scan API, classifier, token fetch, web UI
- @pyre/core: conservative classifier (classifyTokenAccount) + types + risk constants. EMPTY only when truly empty + classic-SPL + not frozen/delegated; Token-2022/unknown → UNSUPPORTED; frozen/delegated/NFT/valuable/over-threshold → PROTECTED_SKIP; TRANSMUTABLE only via explicit route hook (none in MVP). 43 unit tests incl. a "never says safe" assertion. - @pyre/solana: parseTokenAccounts (SPL + Token-2022 detection, NFT heuristic, rent, defensive owner cross-check) + tests. Tx builders remain Phase-2 stubs. - @pyre/config: loadConfig() from env. - @pyre/api: POST /api/scan — validates pubkey, recomputes classification server-side, CORS + rate-limit; DB persistence deferred. Live-RPC smoke OK. - @pyre/web: wallet-connect (Wallet Standard) + grouped scan UI, ember theme, trust wording (no "safe"); next.config transpiles @pyre/core; prod build OK. Built by 4 agents on a locked core contract; 2 audit agents (security: SOUND; build: 1 blocker → fixed). Stripped .js import extensions in @pyre/core so Turbopack resolves the source package. All typecheck + tests + build green. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -12,10 +12,13 @@
|
||||
"test": "echo \"TODO: tests\""
|
||||
},
|
||||
"dependencies": {
|
||||
"@fastify/cors": "^10.0.1",
|
||||
"@fastify/rate-limit": "^10.2.1",
|
||||
"@pyre/config": "workspace:*",
|
||||
"@pyre/core": "workspace:*",
|
||||
"@pyre/db": "workspace:*",
|
||||
"@pyre/solana": "workspace:*",
|
||||
"@solana/web3.js": "^1.98.0",
|
||||
"bullmq": "^5.34.0",
|
||||
"fastify": "^5.2.0",
|
||||
"ioredis": "^5.4.2"
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
// PYRE backend API — SKELETON ONLY.
|
||||
// PYRE backend API — Phase 1 (READ-ONLY).
|
||||
//
|
||||
// Minimal Fastify bootstrap. Only `/health` is wired up. The §14 endpoints
|
||||
// below are intentionally NOT implemented — no scan/classify/build logic here.
|
||||
// Fastify bootstrap wiring `/health` and `POST /api/scan`. The scan endpoint is
|
||||
// read-only: it parses a wallet's SPL token accounts via RPC, classifies each
|
||||
// account server-side, and returns the results live. No transaction building or
|
||||
// signing happens here.
|
||||
//
|
||||
// DB persistence is DEFERRED in Phase 1 — scan results (wallet_scans /
|
||||
// token_accounts) are returned live and NOT written to @pyre/db yet. The
|
||||
// `scanId` is a freshly generated UUID with no persisted row behind it.
|
||||
//
|
||||
// Trust rules (§16): never request private keys, never sign custodially,
|
||||
// always build an unsigned tx the client decodes + previews before signing,
|
||||
@@ -9,45 +15,174 @@
|
||||
// client-submitted classifications (recompute server-side), log all tx-build
|
||||
// requests, rate-limit scan endpoints, protect admin endpoints.
|
||||
|
||||
import { randomUUID } from "node:crypto";
|
||||
import Fastify from "fastify";
|
||||
import cors from "@fastify/cors";
|
||||
import rateLimit from "@fastify/rate-limit";
|
||||
import { Connection, PublicKey } from "@solana/web3.js";
|
||||
import { loadConfig } from "@pyre/config";
|
||||
import {
|
||||
classifyTokenAccount,
|
||||
TokenClassification,
|
||||
RENT_EXEMPT_TOKEN_ACCOUNT_LAMPORTS,
|
||||
} from "@pyre/core";
|
||||
import type {
|
||||
ScanResponse,
|
||||
ScanSummary,
|
||||
TokenAccountDto,
|
||||
ParsedTokenAccount,
|
||||
} from "@pyre/core";
|
||||
import { parseTokenAccounts } from "@pyre/solana";
|
||||
|
||||
const config = loadConfig();
|
||||
|
||||
// External RPC provider only — never run a validator/RPC node on the MVP VPS.
|
||||
const connection = new Connection(config.solanaRpcUrl, "confirmed");
|
||||
|
||||
const app = Fastify({ logger: true });
|
||||
|
||||
// CORS restricted to the web app origin.
|
||||
await app.register(cors, { origin: config.webPublicUrl });
|
||||
|
||||
// Rate limiting is registered globally but disabled by default; routes opt in
|
||||
// via their per-route `config.rateLimit` (see /api/scan below).
|
||||
await app.register(rateLimit, {
|
||||
global: false,
|
||||
max: config.rateLimitScanPerMin,
|
||||
timeWindow: "1 minute",
|
||||
});
|
||||
|
||||
app.get("/health", async () => {
|
||||
return { status: "ok", service: "@pyre/api" };
|
||||
});
|
||||
|
||||
// TODO (§14): implement the following routes as real, validated handlers.
|
||||
// POST /api/scan
|
||||
// in: { wallet }
|
||||
// out: { scanId, wallet, summary, accounts[] }
|
||||
//
|
||||
// POST /api/build/close-empty
|
||||
// in: { wallet, accountAddresses[] }
|
||||
// out: { transactionBase64, preview: { accountsToClose,
|
||||
// estimatedRentReturnedLamports, rentDestination } }
|
||||
//
|
||||
// POST /api/build/burn
|
||||
// in: { wallet, items[] }
|
||||
// out: { transactionBase64, preview: { tokensToBurn, accountsPotentiallyClosable } }
|
||||
//
|
||||
// POST /api/receipt
|
||||
// in: { wallet, txSignature, scanId }
|
||||
// out: { receiptId, txSignature, rentReturnedLamports, closedAccounts,
|
||||
// burnedTokens, skippedTokens }
|
||||
//
|
||||
// POST /api/prometheus/generate (enqueue BullMQ job for @pyre/worker)
|
||||
// in: { receiptId, chaos, operatorSeed? }
|
||||
// out: { generationId, spawnName, ticker, lore, imagePrompt, metadata, riskFlags }
|
||||
//
|
||||
// Admin endpoints — review/approve/reject Spawn generations (protected).
|
||||
/** Request body schema for POST /api/scan — only `wallet` is accepted. */
|
||||
const scanBodySchema = {
|
||||
type: "object",
|
||||
required: ["wallet"],
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
wallet: { type: "string", minLength: 32, maxLength: 44 },
|
||||
},
|
||||
} as const;
|
||||
|
||||
const port = Number(process.env.PORT ?? 3001);
|
||||
const host = process.env.HOST ?? "0.0.0.0";
|
||||
interface ScanBody {
|
||||
wallet: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/scan — read-only wallet scan.
|
||||
*
|
||||
* in: { wallet }
|
||||
* out: { scanId, wallet, summary, accounts[] }
|
||||
*
|
||||
* Validates the wallet is a valid base58 PublicKey, parses its SPL token
|
||||
* accounts, and classifies each account server-side. Client-submitted
|
||||
* classifications are never accepted (the schema forbids extra properties).
|
||||
*/
|
||||
app.post<{ Body: ScanBody }>(
|
||||
"/api/scan",
|
||||
{
|
||||
schema: { body: scanBodySchema },
|
||||
config: { rateLimit: { max: config.rateLimitScanPerMin, timeWindow: "1 minute" } },
|
||||
},
|
||||
async (request, reply) => {
|
||||
const { wallet } = request.body;
|
||||
|
||||
// Validate wallet pubkey (base58) — never trust client input.
|
||||
let walletPk: PublicKey;
|
||||
try {
|
||||
walletPk = new PublicKey(wallet);
|
||||
} catch {
|
||||
return reply.code(400).send({ error: "invalid wallet address" });
|
||||
}
|
||||
|
||||
let accounts: ParsedTokenAccount[];
|
||||
try {
|
||||
accounts = await parseTokenAccounts(connection, walletPk);
|
||||
} catch (err) {
|
||||
request.log.error({ err, wallet }, "parseTokenAccounts failed");
|
||||
return reply.code(502).send({ error: "scan failed" });
|
||||
}
|
||||
|
||||
const dtos: TokenAccountDto[] = [];
|
||||
const summary: ScanSummary = {
|
||||
totalAccounts: accounts.length,
|
||||
emptyCloseOnly: 0,
|
||||
incinerateOnly: 0,
|
||||
transmutable: 0,
|
||||
protectedSkip: 0,
|
||||
unsupported: 0,
|
||||
estimatedRentLamports: "0",
|
||||
};
|
||||
|
||||
// Sum reclaimable rent across EMPTY_CLOSE_ONLY accounts using BigInt to
|
||||
// avoid precision loss on large lamport totals.
|
||||
let rentSum = 0n;
|
||||
|
||||
for (const acct of accounts) {
|
||||
// Recompute classification server-side; never trust the client.
|
||||
// Forward the operator-tunable USD threshold from config.
|
||||
const { classification, warnings } = classifyTokenAccount(acct, {
|
||||
usdThreshold: config.protectedUsdThreshold,
|
||||
});
|
||||
|
||||
const lamports =
|
||||
acct.lamports || RENT_EXEMPT_TOKEN_ACCOUNT_LAMPORTS;
|
||||
|
||||
const dto: TokenAccountDto = {
|
||||
ata: acct.ata,
|
||||
owner: acct.owner,
|
||||
mint: acct.mint,
|
||||
tokenProgram: acct.tokenProgram,
|
||||
rawBalance: acct.rawAmount,
|
||||
uiBalance: acct.uiAmount,
|
||||
decimals: acct.decimals,
|
||||
symbol: acct.symbol,
|
||||
name: acct.name,
|
||||
classification,
|
||||
warnings,
|
||||
estimatedRentLamports: String(lamports),
|
||||
frozen: acct.isFrozen,
|
||||
delegated: acct.isDelegated,
|
||||
};
|
||||
dtos.push(dto);
|
||||
|
||||
switch (classification) {
|
||||
case TokenClassification.EMPTY_CLOSE_ONLY:
|
||||
summary.emptyCloseOnly += 1;
|
||||
rentSum += BigInt(lamports);
|
||||
break;
|
||||
case TokenClassification.INCINERATE_ONLY:
|
||||
summary.incinerateOnly += 1;
|
||||
break;
|
||||
case TokenClassification.TRANSMUTABLE:
|
||||
summary.transmutable += 1;
|
||||
break;
|
||||
case TokenClassification.PROTECTED_SKIP:
|
||||
summary.protectedSkip += 1;
|
||||
break;
|
||||
case TokenClassification.UNSUPPORTED:
|
||||
summary.unsupported += 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
summary.estimatedRentLamports = rentSum.toString();
|
||||
|
||||
const response: ScanResponse = {
|
||||
scanId: randomUUID(),
|
||||
wallet: walletPk.toBase58(),
|
||||
summary,
|
||||
accounts: dtos,
|
||||
};
|
||||
|
||||
return response;
|
||||
},
|
||||
);
|
||||
|
||||
// TODO: load + validate config via @pyre/config instead of reading process.env here.
|
||||
app
|
||||
.listen({ port, host })
|
||||
.listen({ port: config.apiPort, host: process.env.HOST ?? "0.0.0.0" })
|
||||
.then((address) => {
|
||||
app.log.info(`@pyre/api listening on ${address}`);
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user