Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions be/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ PORT=
# Optional overrides. Leave EMPTY to use the addresses recorded in docs/deployments.md;
# an override shows up in /config as source "env" with recorded: false.
STELLAR_RPC_URL=
HORIZON_URL=
RECLAIM_VERIFIER_ID=
USDC_SAC_ID=
ADVANCE_CONTRACT_ID=
136 changes: 132 additions & 4 deletions be/src/api/app.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,13 @@
import assert from "node:assert/strict";
import { test } from "node:test";

import { readFileSync } from "node:fs";
import { join } from "node:path";

import type { AdvanceRecord } from "../chain/advance.js";
import type { HorizonOperation } from "../chain/history.js";
import { RECORDED } from "../network.js";
import { createApp, type RpcLike } from "./app.js";
import { createApp, type ChainLike, type RpcLike } from "./app.js";
import { loadConfig, parseOrigin } from "./config.js";

const FRONT_END = "https://app.forepay.example";
Expand All @@ -15,8 +20,41 @@ const OTHER_CONTRACT = "CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABSC4

const healthy: RpcLike = { getHealth: async () => ({ status: "healthy", latestLedger: 123 }) };

function app(env: Record<string, string> = {}, rpc: RpcLike = healthy, readyTimeoutMs?: number) {
return createApp({ loaded: loadConfig({ CORS_ORIGINS: FRONT_END, ...env }), rpc, readyTimeoutMs });
// Real Horizon records for the rehearsal account; its advances went to the dev contract.
const OPS = (
JSON.parse(readFileSync(join(import.meta.dirname, "../chain/fixtures/horizon-ops.json"), "utf8")) as {
records: HorizonOperation[];
}
).records;
const BORROWER = "GA2CD6PMHMBTCFAQDO3R22BSZN5ZSVTAKVNOKXL2SONZBLGRAYIOWWH2";
const DEV = "CD25Q4TDGDY6CI3LUIWUOH6SXCH6ETIUCI6FUOBI322GCJL5G3EIHQN4";

/** The contract's record for an advance, as `advance(nullifier)` returned it on the dev contract. */
function record(pubId: string, openedAt: bigint, repaid = 10_000_000n): AdvanceRecord {
return {
borrower: BORROWER,
pubId,
windowStart: "2026-07-01",
windowEnd: "2026-09-30",
revenueCents: 400n,
principal: 10_000_000n,
repaid,
openedAt,
};
}

const RECORDS: Record<string, AdvanceRecord> = {
"1d124817f351c4a88ed2fe92a2f79812f2bfa41e0610a5bbb84f7a5e892e68f5": record("pub-h1792261997", 1792262007n),
d0cd01df330362b23508edf7e386950549da634b756d1c29aa242cfc9c88c839: record("pub-h1792084434", 1792084442n, 2_500_000n),
};

const fixtureChain: ChainLike = {
operations: async () => OPS,
readAdvance: async (_contract, nullifier) => RECORDS[nullifier] ?? null,
};

function app(env: Record<string, string> = {}, rpc: RpcLike = healthy, readyTimeoutMs?: number, chain = fixtureChain) {
return createApp({ loaded: loadConfig({ CORS_ORIGINS: FRONT_END, ...env }), rpc, chain, readyTimeoutMs });
}

test("with no overrides, /config reports exactly the recorded addresses", async () => {
Expand All @@ -26,8 +64,15 @@ test("with no overrides, /config reports exactly the recorded addresses", async
network: "testnet",
networkPassphrase: RECORDED.networkPassphrase,
rpcUrl: RECORDED.rpcUrl,
horizonUrl: RECORDED.horizonUrl,
contracts: RECORDED.contracts,
sources: { rpcUrl: "recorded", reclaimVerifier: "recorded", usdcSac: "recorded", advance: "recorded" },
sources: {
rpcUrl: "recorded",
horizonUrl: "recorded",
reclaimVerifier: "recorded",
usdcSac: "recorded",
advance: "recorded",
},
recorded: true,
});
});
Expand All @@ -46,6 +91,7 @@ test("a stale override is visible: source env, recorded false", async () => {
test("bad configuration is refused at load, not discovered later", () => {
assert.throws(() => loadConfig({ USDC_SAC_ID: "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF" }), /not a contract address/);
assert.throws(() => loadConfig({ STELLAR_RPC_URL: "http://soroban-testnet.stellar.org" }), /https/);
assert.throws(() => loadConfig({ HORIZON_URL: "http://horizon-testnet.stellar.org" }), /https/);
assert.throws(() => loadConfig({ STELLAR_NETWORK_PASSPHRASE: "Public Global Stellar Network ; September 2015" }), /only testnet/);
assert.throws(() => loadConfig({ PORT: "99999" }), /PORT/);
});
Expand Down Expand Up @@ -109,3 +155,85 @@ test("unknown routes are JSON 404s", async () => {
assert.equal(res.status, 404);
assert.deepEqual(await res.json(), { error: "not found" });
});

test("/advances: the contract's record of each advance, newest first, amounts as strings", async () => {
const res = await app({ ADVANCE_CONTRACT_ID: DEV }).request(`/advances?borrower=${BORROWER}`);
assert.equal(res.status, 200);
assert.equal(res.headers.get("cache-control"), "no-store");
// Only the two advances the contract has a record for are listed; the other calls in
// the fixture have none in this stub, and an advance without a record is not shown.
assert.deepEqual(await res.json(), [
{
nullifier: "1d124817f351c4a88ed2fe92a2f79812f2bfa41e0610a5bbb84f7a5e892e68f5",
borrower: BORROWER,
windowStart: "2026-07-01",
windowEnd: "2026-09-30",
revenueCents: "400",
principal: "10000000",
repaid: "10000000",
openedAt: "1792262007",
txHash: "1e066220909da8dfdfc92d1926a377a4dc2a08b12adaca2c88cef8f394a60f25",
},
{
nullifier: "d0cd01df330362b23508edf7e386950549da634b756d1c29aa242cfc9c88c839",
borrower: BORROWER,
windowStart: "2026-07-01",
windowEnd: "2026-09-30",
revenueCents: "400",
principal: "10000000",
repaid: "2500000",
openedAt: "1792084442",
txHash: "9a94cf083543b58d79b60431de305f3912099ca9337ada4793ef1e38546f8ad0",
},
]);
});

test("/advances only lists records the contract holds for this borrower", async () => {
const someoneElse: ChainLike = {
operations: async () => OPS,
readAdvance: async (_c, n) => (RECORDS[n] ? { ...RECORDS[n], borrower: "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF" } : null),
};
const res = await app({ ADVANCE_CONTRACT_ID: DEV }, healthy, undefined, someoneElse).request(`/advances?borrower=${BORROWER}`);
assert.deepEqual(await res.json(), []);
});

test("/transactions: every kind, as strings, newest first", async () => {
const res = await app({ ADVANCE_CONTRACT_ID: DEV }).request(`/transactions?borrower=${BORROWER}`);
assert.equal(res.status, 200);
const rows = (await res.json()) as { kind: string; amount: string; at: string; status: string; nullifier: string }[];
assert.deepEqual([...new Set(rows.map((r) => r.kind))].sort(), ["advance", "repayment", "trustline"]);
for (const r of rows) {
assert.match(r.amount, /^\d+$/);
assert.match(r.at, /^\d+$/);
}
assert.ok(rows.every((r, i) => i === 0 || BigInt(rows[i - 1].at) >= BigInt(r.at)));
});

test("history routes refuse a borrower that is not a G… address", async () => {
for (const q of ["", "?borrower=", `?borrower=${DEV}`, "?borrower=GABC"]) {
for (const route of ["/advances", "/transactions"]) {
const res = await app().request(`${route}${q}`);
assert.equal(res.status, 400, `${route}${q}`);
}
}
});

test("history routes answer 502 when the chain cannot be read, without leaking why", async () => {
const down: ChainLike = {
operations: async () => {
throw new Error("Horizon answered 503 for GA2C…");
},
readAdvance: async () => null,
};
const original = console.error;
console.error = () => {};
try {
for (const route of ["/advances", "/transactions"]) {
const res = await app({}, healthy, undefined, down).request(`${route}?borrower=${BORROWER}`);
assert.equal(res.status, 502);
assert.deepEqual(await res.json(), { error: "the chain could not be read; try again" });
}
} finally {
console.error = original;
}
});
97 changes: 91 additions & 6 deletions be/src/api/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,32 +5,46 @@
* GET /ready readiness: the Stellar RPC answers. 503 when it does not.
* GET /config the network and contract addresses this API is actually pointed
* at, where each came from, and whether they match the record.
* GET /advances?borrower=G… every advance the wallet took, newest first, with
* the contract's current record of each (principal, repaid, window).
* GET /transactions?borrower=G… advances, repayments and the USDC trustline,
* newest first, failed ones included.
*
* The chain-state routes (an advance's status, a repayment position, whether a
* nullifier is spent) are added once #6 freezes the contract interface: building them
* against a moving interface is how the API and the contract drift apart.
* Amounts are stroops and times are seconds, both as decimal strings: JSON numbers
* lose precision past 2^53 and an i128 can exceed that.
*
* The app is built from injected config and RPC so tests run without a network.
* The app is built from injected config and chain access so tests run without a network.
*/
import { Hono } from "hono";
import { Hono, type Context } from "hono";
import { cors } from "hono/cors";
import { secureHeaders } from "hono/secure-headers";

import { StrKey } from "@stellar/stellar-sdk";

import type { AdvanceRecord } from "../chain/advance.js";
import { advanceCalls, ledgerTransactions, type HorizonOperation } from "../chain/history.js";
import type { LoadedConfig } from "./config.js";

/** The slice of the Stellar RPC client the API uses. */
export interface RpcLike {
getHealth(): Promise<{ status: string; latestLedger?: number }>;
}

/** Chain reads the history routes need: Horizon's operations, the contract's records. */
export interface ChainLike {
operations(account: string): Promise<HorizonOperation[]>;
readAdvance(contract: string, nullifierHex: string): Promise<AdvanceRecord | null>;
}

export interface AppDeps {
loaded: LoadedConfig;
rpc: RpcLike;
chain: ChainLike;
/** Readiness check timeout. */
readyTimeoutMs?: number;
}

export function createApp({ loaded, rpc, readyTimeoutMs = 5000 }: AppDeps) {
export function createApp({ loaded, rpc, chain, readyTimeoutMs = 5000 }: AppDeps) {
const { config, sources, recorded } = loaded;
const allowed = new Set(config.corsOrigins);
const app = new Hono();
Expand Down Expand Up @@ -67,17 +81,88 @@ export function createApp({ loaded, rpc, readyTimeoutMs = 5000 }: AppDeps) {
network: config.network,
networkPassphrase: config.networkPassphrase,
rpcUrl: config.rpcUrl,
horizonUrl: config.horizonUrl,
contracts: config.contracts,
sources,
recorded,
}),
);

/** The borrower and the advance contract a history route needs, or the error response. */
function historyScope(c: Context): { borrower: string; contract: string } | Response {
const borrower = c.req.query("borrower") ?? "";
if (!StrKey.isValidEd25519PublicKey(borrower)) {
return c.json({ error: "borrower must be a Stellar account address (G…)" }, 400);
}
const contract = config.contracts.advance;
if (!contract) return c.json({ error: "no advance contract is configured" }, 503);
c.header("Cache-Control", "no-store");
return { borrower, contract };
}

app.get("/advances", async (c) => {
const scope = historyScope(c);
if (scope instanceof Response) return scope;
const { borrower, contract } = scope;
const ops = await upstream(() => chain.operations(borrower));
// Newest first, so the first call per nullifier is the one that funded it.
const funded = new Map<string, string>();
for (const call of advanceCalls(ops, borrower, contract)) {
if (call.successful && !funded.has(call.nullifier)) funded.set(call.nullifier, call.hash);
}
const records = await upstream(() =>
Promise.all([...funded.keys()].map((n) => chain.readAdvance(contract, n))),
);
const rows = [...funded.entries()]
.map(([nullifier, txHash], i) => ({ nullifier, txHash, record: records[i] }))
// The contract's record is the authority: no record, or someone else's, is not listed.
.filter((r): r is { nullifier: string; txHash: string; record: AdvanceRecord } => r.record?.borrower === borrower)
.sort((a, b) => (a.record.openedAt === b.record.openedAt ? 0 : a.record.openedAt > b.record.openedAt ? -1 : 1));
return c.json(
rows.map(({ nullifier, txHash, record }) => ({
nullifier,
borrower: record.borrower,
windowStart: record.windowStart,
windowEnd: record.windowEnd,
revenueCents: String(record.revenueCents),
principal: String(record.principal),
repaid: String(record.repaid),
openedAt: String(record.openedAt),
txHash,
})),
);
});

app.get("/transactions", async (c) => {
const scope = historyScope(c);
if (scope instanceof Response) return scope;
const ops = await upstream(() => chain.operations(scope.borrower));
return c.json(
ledgerTransactions(ops, scope.borrower, scope.contract).map((t) => ({
...t,
amount: String(t.amount),
at: String(t.at),
})),
);
});

app.notFound((c) => c.json({ error: "not found" }, 404));
app.onError((err, c) => {
console.error(err);
if (err instanceof UpstreamError) return c.json({ error: "the chain could not be read; try again" }, 502);
return c.json({ error: "internal error" }, 500);
});

return app;
}

/** Horizon or the RPC failed: a 502 the front end can retry, not a 500 bug. */
class UpstreamError extends Error {}

async function upstream<T>(read: () => Promise<T>): Promise<T> {
try {
return await read();
} catch (e) {
throw new UpstreamError((e as Error).message, { cause: e });
}
}
12 changes: 10 additions & 2 deletions be/src/api/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ export interface ApiConfig {
network: "testnet";
networkPassphrase: string;
rpcUrl: string;
horizonUrl: string;
contracts: Record<ContractName, string | null>;
/** Exact origins allowed by CORS. Never a wildcard. */
corsOrigins: string[];
Expand All @@ -25,7 +26,7 @@ export type Source = "recorded" | "env";

export interface LoadedConfig {
config: ApiConfig;
sources: Record<"rpcUrl" | ContractName, Source>;
sources: Record<"rpcUrl" | "horizonUrl" | ContractName, Source>;
/** True when every contract in use equals docs/deployments.md. */
recorded: boolean;
}
Expand Down Expand Up @@ -63,8 +64,14 @@ export function loadConfig(env: Record<string, string | undefined> = process.env
const rpcUrl = get("STELLAR_RPC_URL") ?? RECORDED.rpcUrl;
if (!/^https:\/\//.test(rpcUrl)) throw new Error(`STELLAR_RPC_URL must be https: ${rpcUrl}`);

const horizonUrl = get("HORIZON_URL") ?? RECORDED.horizonUrl;
if (!/^https:\/\//.test(horizonUrl)) throw new Error(`HORIZON_URL must be https: ${horizonUrl}`);

const contracts = {} as Record<ContractName, string | null>;
const sources = { rpcUrl: get("STELLAR_RPC_URL") ? "env" : "recorded" } as LoadedConfig["sources"];
const sources = {
rpcUrl: get("STELLAR_RPC_URL") ? "env" : "recorded",
horizonUrl: get("HORIZON_URL") ? "env" : "recorded",
} as LoadedConfig["sources"];
for (const name of Object.keys(CONTRACT_ENV) as ContractName[]) {
const fromEnv = get(CONTRACT_ENV[name]);
if (fromEnv !== undefined && !StrKey.isValidContract(fromEnv)) {
Expand All @@ -90,6 +97,7 @@ export function loadConfig(env: Record<string, string | undefined> = process.env
network: "testnet",
networkPassphrase: RECORDED.networkPassphrase,
rpcUrl,
horizonUrl,
contracts,
corsOrigins,
port,
Expand Down
13 changes: 12 additions & 1 deletion be/src/api/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import { serve } from "@hono/node-server";
import { rpc } from "@stellar/stellar-sdk";

import { die, loadEnv } from "../cli/env.js";
import { readAdvance } from "../chain/advance.js";
import { fetchOperations } from "../chain/history.js";
import { createApp } from "./app.js";
import { loadConfig } from "./config.js";

Expand All @@ -32,7 +34,16 @@ if (!loaded.recorded) {
);
}

const app = createApp({ loaded, rpc: new rpc.Server(loaded.config.rpcUrl) });
const server = new rpc.Server(loaded.config.rpcUrl);
const { horizonUrl, networkPassphrase } = loaded.config;
const app = createApp({
loaded,
rpc: server,
chain: {
operations: (account) => fetchOperations(account, { horizonUrl }),
readAdvance: (contract, nullifier) => readAdvance(server, networkPassphrase, contract, nullifier),
},
});
serve({ fetch: app.fetch, port: loaded.config.port }, (info) => {
console.log(`Forepay API on :${info.port} (${loaded.config.network}, CORS: ${loaded.config.corsOrigins.join(", ") || "none"})`);
});
Loading