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
2 changes: 2 additions & 0 deletions be/src/api/app.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,7 @@ test("/advances: the contract's record of each advance, newest first, amounts as
assert.deepEqual(await res.json(), [
{
nullifier: "1d124817f351c4a88ed2fe92a2f79812f2bfa41e0610a5bbb84f7a5e892e68f5",
source: "AdSense",
borrower: BORROWER,
windowStart: "2026-07-01",
windowEnd: "2026-09-30",
Expand All @@ -180,6 +181,7 @@ test("/advances: the contract's record of each advance, newest first, amounts as
},
{
nullifier: "d0cd01df330362b23508edf7e386950549da634b756d1c29aa242cfc9c88c839",
source: "AdSense",
borrower: BORROWER,
windowStart: "2026-07-01",
windowEnd: "2026-09-30",
Expand Down
13 changes: 7 additions & 6 deletions be/src/api/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import { StrKey } from "@stellar/stellar-sdk";

import { ProveError } from "../adsense/account.js";
import type { AdvanceRecord } from "../chain/advance.js";
import { advanceCalls, ledgerTransactions, type HorizonOperation } from "../chain/history.js";
import { advanceCalls, ledgerTransactions, type HorizonOperation, type Source } from "../chain/history.js";
import { BorrowerBusyError, ProofJobs, QueueFullError } from "../relay/jobs.js";
import type { AdvanceRequestJson, ProveInput, ProveStep } from "../relay/prove.js";
import type { LoadedConfig } from "./config.js";
Expand Down Expand Up @@ -120,21 +120,22 @@ export function createApp({ loaded, rpc, chain, prover, jobs = new ProofJobs(),
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>();
const funded = new Map<string, { txHash: string; source: Source }>();
for (const call of advanceCalls(ops, borrower, contract)) {
if (call.successful && !funded.has(call.nullifier)) funded.set(call.nullifier, call.hash);
if (call.successful && !funded.has(call.nullifier)) funded.set(call.nullifier, { txHash: call.hash, source: call.source });
}
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] }))
.map(([nullifier, { txHash, source }], i) => ({ nullifier, txHash, source, 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)
.filter((r): r is { nullifier: string; txHash: string; source: Source; 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 }) => ({
rows.map(({ nullifier, txHash, source, record }) => ({
nullifier,
source,
borrower: record.borrower,
windowStart: record.windowStart,
windowEnd: record.windowEnd,
Expand Down
49 changes: 49 additions & 0 deletions be/src/chain/history.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import { readFileSync } from "node:fs";
import { join } from "node:path";
import { test } from "node:test";

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

import {
advanceCalls,
fetchOperations,
Expand Down Expand Up @@ -54,6 +56,7 @@ test("request_advance calls are read with their arguments, nullifier and the USD
at: 1792084442n,
successful: true,
nullifier: "d0cd01df330362b23508edf7e386950549da634b756d1c29aa242cfc9c88c839",
source: "AdSense",
borrower: BORROWER,
pubId: "pub-h1792084434",
windowStart: "2026-07-01",
Expand Down Expand Up @@ -140,3 +143,49 @@ test("fetchOperations pages through Horizon, and an unknown account has no histo
const down = (async () => new Response("{}", { status: 503 })) as unknown as typeof fetch;
await assert.rejects(fetchOperations(BORROWER, { horizonUrl: "https://h.example", fetch: down }), /Horizon answered 503/);
});

// #94 puts a `Source` first in `request_advance`. The same real call, rewritten into that
// shape, must read the same, and a call already on chain (the five-argument shape above)
// must keep reading as it does.
function withSource(op: HorizonOperation, source: "AdSense" | "AdMob"): HorizonOperation {
const params = op.parameters ?? [];
const tag = { type: "Vec", value: xdr.ScVal.scvVec([xdr.ScVal.scvSymbol(source)]).toXDR("base64") };
return { ...op, parameters: [params[0], params[1], tag, ...params.slice(2)] };
}

const FUNDED = "9a94cf083543b58d79b60431de305f3912099ca9337ada4793ef1e38546f8ad0";

function funded(): HorizonOperation {
const op = OPS.find((o) => o.transaction_hash === FUNDED);
assert.ok(op, "the fixture holds the funded call");
return op;
}

test("after #94 an AdSense call with its source reads exactly as before, nullifier included", () => {
const op = funded();
const [before] = advanceCalls([op], BORROWER, DEV);
const [after] = advanceCalls([withSource(op, "AdSense")], BORROWER, DEV);
assert.deepEqual(after, before);
assert.equal(ledgerTransactions([withSource(op, "AdSense")], BORROWER, DEV)[0].nullifier, before.nullifier);
});

test("after #94 an AdMob call is the borrower's, with the tagged nullifier", () => {
const op = withSource(funded(), "AdMob");
const [call] = advanceCalls([op], BORROWER, DEV);
assert.equal(call.source, "AdMob");
assert.equal(call.borrower, BORROWER);
assert.equal(call.pubId, "pub-h1792084434");
assert.equal(call.nullifier, nullifierFor("pub-h1792084434", "2026-07-01", "2026-09-30", "AdMob"));
assert.notEqual(call.nullifier, nullifierFor("pub-h1792084434", "2026-07-01", "2026-09-30"));
assert.equal(ledgerTransactions([op], BORROWER, DEV)[0].nullifier, call.nullifier);
});

test("the AdMob nullifier is the one #94's contract computes", () => {
// `nullifier_for(AdMob, …)` on #106's contract for its fixture publisher and window.
assert.equal(nullifierFor("pub-1234567890123456", "2026-07-01", "2026-09-30", "AdMob"), "b4e9944247251fa09409c71406da72d4f03dc9e7a374a708bd92459521d93a58");
// And AdSense is the literal #106 pins as unchanged (`the_adsense_nullifier_bytes_did_not_change`).
assert.equal(
nullifierFor("pub-1234567890123456", "2026-07-01", "2026-09-30"),
"3140b7a01c306d98cfed42ae54092856f38808a69e15ef94ce26d57a734ba31a",
);
});
37 changes: 31 additions & 6 deletions be/src/chain/history.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,8 @@ export interface AdvanceCall {
at: bigint;
successful: boolean;
nullifier: string;
/** The revenue source the advance was proven from (#94). Calls before #94 carry none: AdSense. */
source: Source;
borrower: string;
pubId: string;
windowStart: string;
Expand All @@ -72,13 +74,20 @@ export interface AdvanceCall {
disbursed: bigint;
}

export type Source = "AdSense" | "AdMob";

/**
* `sha256(len ‖ pub_id ‖ len ‖ window_start ‖ len ‖ window_end)`, each length a 4-byte
* big-endian u32. The same derivation as `claim::nullifier_of` in sc/advance.
*
* AdMob appends `len ‖ "admob"` (#94): one Google account's AdSense and AdMob publisher ids
* are the same `pub-` id, so the two need separate nullifier spaces. AdSense appends
* nothing, because advances already on chain are keyed on the untagged hash.
*/
export function nullifierFor(pubId: string, windowStart: string, windowEnd: string): string {
export function nullifierFor(pubId: string, windowStart: string, windowEnd: string, source: Source = "AdSense"): string {
const parts: Buffer[] = [];
for (const field of [pubId, windowStart, windowEnd]) {
const fields = source === "AdMob" ? [pubId, windowStart, windowEnd, "admob"] : [pubId, windowStart, windowEnd];
for (const field of fields) {
const bytes = Buffer.from(field, "utf8");
const len = Buffer.alloc(4);
len.writeUInt32BE(bytes.length);
Expand Down Expand Up @@ -112,6 +121,21 @@ function contractCall(op: HorizonOperation, contract: string): { fn: string; arg
return { fn: String(native[1]), args: native.slice(2) };
}

/**
* `request_advance`'s arguments, before and after #94 put a `Source` first. A call already
* on chain keeps the old five, so both shapes are read. The source decodes as `["AdMob"]`
* (a unit enum variant is a vec holding its symbol), which no `G…` string can be.
*/
function requestArgs(args: unknown[]): { source: Source; borrower: string; pubId: string; windowStart: string; windowEnd: string } {
let source: Source = "AdSense";
if (Array.isArray(args[0])) {
source = args[0][0] === "AdMob" ? "AdMob" : "AdSense";
args = args.slice(1);
}
const [borrower, , pubId, windowStart, windowEnd] = args as string[];
return { source, borrower, pubId, windowStart, windowEnd };
}

/** USDC that moved between `a` and `b`, in either direction, in stroops. */
function usdcMoved(op: HorizonOperation, a: string, b: string): bigint {
let total = 0n;
Expand All @@ -132,13 +156,14 @@ export function advanceCalls(ops: HorizonOperation[], borrower: string, contract
for (const op of ops) {
const call = contractCall(op, contract);
if (!call || call.fn !== "request_advance") continue;
const [callBorrower, , pubId, windowStart, windowEnd] = call.args as string[];
const { source, borrower: callBorrower, pubId, windowStart, windowEnd } = requestArgs(call.args);
if (callBorrower !== borrower) continue;
out.push({
hash: op.transaction_hash,
at: seconds(op.created_at),
successful: op.transaction_successful,
nullifier: nullifierFor(pubId, windowStart, windowEnd),
nullifier: nullifierFor(pubId, windowStart, windowEnd, source),
source,
borrower: callBorrower,
pubId,
windowStart,
Expand Down Expand Up @@ -166,15 +191,15 @@ export function ledgerTransactions(ops: HorizonOperation[], borrower: string, co
const call = contractCall(op, contract);
if (!call) continue;
if (call.fn === "request_advance") {
const [callBorrower, , pubId, windowStart, windowEnd] = call.args as string[];
const { source, borrower: callBorrower, pubId, windowStart, windowEnd } = requestArgs(call.args);
if (callBorrower !== borrower) continue;
out.push({
hash: op.transaction_hash,
kind: "advance",
amount: op.transaction_successful ? usdcMoved(op, contract, borrower) : 0n,
at,
status,
nullifier: nullifierFor(pubId, windowStart, windowEnd),
nullifier: nullifierFor(pubId, windowStart, windowEnd, source),
});
} else if (call.fn === "repay") {
const [from, nullifier, amount] = call.args as [string, Buffer, bigint];
Expand Down
6 changes: 5 additions & 1 deletion docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ Every route returns JSON. All are `GET` except `POST /proofs`.
```json
[{
"nullifier": "1d1248…68f5",
"source": "AdSense",
"borrower": "GA2C…WWH2",
"windowStart": "2026-07-01",
"windowEnd": "2026-09-30",
Expand All @@ -48,7 +49,10 @@ Every route returns JSON. All are `GET` except `POST /proofs`.
rebuild it from history, so the balance shown is always the balance the contract holds.
- `nullifier` is what `repay(from, nullifier, amount)` takes. It is
`sha256(len ‖ pub_id ‖ len ‖ window_start ‖ len ‖ window_end)`, where each length is a 4-byte big-endian
u32. That is the same derivation as the contract's `nullifier_for`.
u32. That is the same derivation as the contract's `nullifier_for`. For AdMob (#94), `len ‖ "admob"` is
appended. AdSense appends nothing, so advances taken before #94 keep their nullifier.
- `source` is `"AdSense"` or `"AdMob"`, read from the `request_advance` call. Calls made before #94 carry no
source, and are AdSense. It is the contract's `advance_source(nullifier)`, without a second read.
- `txHash` is the disbursement transaction.
- Outstanding is `principal − repaid`.

Expand Down