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
3 changes: 3 additions & 0 deletions fe/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ NEXT_PUBLIC_STELLAR_RPC_URL=

# Contract and asset addresses. Must match docs/deployments.md exactly.
NEXT_PUBLIC_ADVANCE_CONTRACT_ID=
# "1" once that contract runs #94: request_advance and nullifier_for then take the revenue source first.
# Set it when the upgrade executes, not before (fe/README.md).
NEXT_PUBLIC_CONTRACT_TAKES_SOURCE=
NEXT_PUBLIC_USDC_CONTRACT_ID=
# CODE:ISSUER, the classic asset behind the SAC. The USDC trustline check (#19) is keyed by it.
NEXT_PUBLIC_USDC_ASSET=
Expand Down
5 changes: 4 additions & 1 deletion fe/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,11 +63,14 @@ browser. Never put a secret in one.
uses. If they differ from yours, one of you is on an old deployment.
- **`NEXT_PUBLIC_WALLET_CONNECT_PROJECT_ID`** is only needed for mobile wallets. Without it,
desktop browser wallets still work.
- **`NEXT_PUBLIC_CONTRACT_TAKES_SOURCE`** is `1` once the advance contract runs #94, whose
`request_advance` and `nullifier_for` take the revenue source first. Flip it when that upgrade
executes: the contract before it refuses the extra argument, the one after refuses its absence.

## Proving revenue: the relay, or a mock

With `NEXT_PUBLIC_RELAY_URL` and `NEXT_PUBLIC_GOOGLE_CLIENT_ID` set, the creator signs in with Google's
own popup (`adsense.readonly` only) and the #17 relay makes the proof, which takes about a minute, more
own popup (`adsense.readonly`, or `admob.readonly` for AdMob) and the #17 relay makes the proof, which takes about a minute, more
behind a queue (`src/lib/reclaim/relay.ts`, `docs/api.md`). No Reclaim SDK runs in the browser. The job
id is kept in `sessionStorage`, so leaving /advance or reloading while it proves comes back to the same
job without a second sign-in.
Expand Down
4 changes: 4 additions & 0 deletions fe/playwright.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ function server(port: number, distDir: string, proving: Record<string, string>)
NEXT_PUBLIC_E2E: "1",
// The Reclaim mock or the stubbed relay, whatever .env.local says.
NEXT_PUBLIC_GOOGLE_CLIENT_ID: "",
// The contract before #94, whatever .env.local says; the relay build sets it.
NEXT_PUBLIC_CONTRACT_TAKES_SOURCE: "",
...proving,
NEXT_PUBLIC_STELLAR_RPC_URL: "https://rpc.e2e.invalid",
NEXT_PUBLIC_API_URL: "https://api.e2e.invalid",
Expand Down Expand Up @@ -63,6 +65,8 @@ export default defineConfig({
server(RELAY_PORT, ".next-e2e-relay", {
NEXT_PUBLIC_RELAY_URL: "https://relay.e2e.invalid",
NEXT_PUBLIC_GOOGLE_CLIENT_ID: "e2e.apps.googleusercontent.com",
// As against #94's contract, whose calls lead with the revenue source; the mock build runs as before it.
NEXT_PUBLIC_CONTRACT_TAKES_SOURCE: "1",
}),
]
: []),
Expand Down
7 changes: 5 additions & 2 deletions fe/src/components/elements/OfferBreakdown.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { formatUsdc } from "@/lib/format";
*/
export function OfferBreakdown({
revenue,
sourceName = "AdSense",
windowShort,
advance,
rate,
Expand All @@ -18,6 +19,8 @@ export function OfferBreakdown({
}: {
/** The proven figure, `$360.00`. */
revenue: string;
/** Where it was earned, `AdSense` or `AdMob` (#97). */
sourceName?: string;
/** `Jul to Sep 2026`. A phone drops the year, unless the window crosses one. */
windowShort: string;
/** What `quote` returned, in stroops. */
Expand All @@ -36,8 +39,8 @@ export function OfferBreakdown({
{
key: (
<>
<span className="hidden md:inline">Your AdSense revenue, {windowShort}</span>
<span className="md:hidden">AdSense revenue, {months}</span>
<span className="hidden md:inline">Your {sourceName} revenue, {windowShort}</span>
<span className="md:hidden">{sourceName} revenue, {months}</span>
</>
),
value: revenue,
Expand Down
12 changes: 11 additions & 1 deletion fe/src/lib/errors.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,14 @@ describe("contractFailureCopy", () => {
}
});

it("names AdMob, not AdSense, for an AdMob proof (#97)", () => {
for (const c of [10, 14, 30]) {
expect(contractFailureCopy(c, "AdMob").body).toMatch(/AdMob/);
expect(contractFailureCopy(c, "AdMob").body).not.toMatch(/AdSense/);
expect(contractFailureCopy(c).body).toMatch(/AdSense/);
}
});

it("uses the Prove and accept board's words for the refusals it names", () => {
expect(contractFailureCopy(20).title).toBe("This proof was already used");
expect(contractFailureCopy(14).title).toBe("We could not confirm this proof");
Expand Down Expand Up @@ -125,6 +133,8 @@ describe("proveFailureCopy", () => {
"relayNotReady",
"googleSignIn",
"noAdsense",
"googleSignInAdmob",
"noAdmob",
"relayFailed",
"relayBusy",
"proofRunning",
Expand All @@ -144,7 +154,7 @@ describe("proveFailureCopy", () => {
it("says nothing was charged only when that is true", () => {
expect(proveFailureCopy("refused").body).toMatch(/Nothing was charged/);
// The relay's failures happen before anything reaches Stellar.
for (const k of ["googleSignIn", "noAdsense", "relayFailed", "proofRunning", "proofGone", "relayUnreachable"] as const) {
for (const k of ["googleSignIn", "noAdsense", "googleSignInAdmob", "noAdmob", "relayFailed", "proofRunning", "proofGone", "relayUnreachable"] as const) {
expect(proveFailureCopy(k).body).toMatch(/Nothing was charged/);
}
for (const k of ["relayBusy", "googleUnavailable", "popupBlocked"] as const) {
Expand Down
24 changes: 19 additions & 5 deletions fe/src/lib/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,17 +139,18 @@ export function isSignatureDeclined(e: unknown): boolean {
/**
* The advance contract's refusals (`docs/interface.md` §7), in the brief's words (§3, rule 4, and the
* "Prove and accept / States and interactions" board, word for word). Shared by #20 and #21. Codes 1 to 6 are admin and upgrade errors a
* creator can never cause, so they fall to the generic sentence.
* creator can never cause, so they fall to the generic sentence. `sourceName` is where the proof came
* from, `AdMob` for an AdMob proof (#97).
*/
export function contractFailureCopy(code: number): FailureCopy {
export function contractFailureCopy(code: number, sourceName = "AdSense"): FailureCopy {
switch (code) {
case 10:
return { title: "Advances are not open yet", body: "Forepay is not taking AdSense proofs yet. Try again later." };
return { title: "Advances are not open yet", body: `Forepay is not taking ${sourceName} proofs yet. Try again later.` };
case 11:
case 14:
return {
title: "We could not confirm this proof",
body: "The revenue could not be matched to Google's data. Try proving again. If it keeps happening, log out of AdSense and back in first.",
body: `The revenue could not be matched to Google's data. Try proving again. If it keeps happening, log out of ${sourceName} and back in first.`,
};
case 12:
return {
Expand All @@ -169,7 +170,7 @@ export function contractFailureCopy(code: number): FailureCopy {
case 30:
return {
title: "We could not read your revenue",
body: "The figure from AdSense was not a plain amount. Nothing was charged.",
body: `The figure from ${sourceName} was not a plain amount. Nothing was charged.`,
};
case 31:
return {
Expand Down Expand Up @@ -212,6 +213,7 @@ export function contractFailureCopy(code: number): FailureCopy {
* - `relayNotReady`: proofs are meant to come from the #17 relay, and this build cannot reach it.
* - `googleSignIn`: Google refused the sign-in the relay was handed, for example an expired one.
* - `noAdsense`: the Google account has no AdSense account, several, or one that is not approved (relay `account`).
* - `googleSignInAdmob`, `noAdmob`: the same two for an AdMob proof (#97).
* - `relayFailed`: the relay could not make the proof, on its side. Nothing was charged.
* - `relayBusy`: the relay is proving for others and its queue is full.
* - `proofRunning`: a proof for this wallet is already running, started from a tab that lost it.
Expand All @@ -237,6 +239,8 @@ export type ProveFailure =
| "relayNotReady"
| "googleSignIn"
| "noAdsense"
| "googleSignInAdmob"
| "noAdmob"
| "relayFailed"
| "relayBusy"
| "proofRunning"
Expand Down Expand Up @@ -331,6 +335,16 @@ export function proveFailureCopy(kind: ProveFailure, walletName = "Freighter"):
title: "We could not use your AdSense account",
body: "We could not find one approved AdSense account on this Google account. Sign in with the account that owns your AdSense, then try again. Nothing was charged.",
};
case "googleSignInAdmob":
return {
title: "Google did not let us read AdMob",
body: "Sign in again and allow Forepay to see your AdMob reports. Nothing was charged.",
};
case "noAdmob":
return {
title: "We could not use your AdMob account",
body: "We could not find one AdMob account on this Google account. Sign in with the account that owns your AdMob, then try again. Nothing was charged.",
};
case "relayFailed":
return {
title: "We could not finish your proof",
Expand Down
4 changes: 2 additions & 2 deletions fe/src/lib/reclaim/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ describe("proveRevenue", () => {
vi.stubEnv("NEXT_PUBLIC_RELAY_URL", "");
const { proveRevenue } = await import("./index");
const stages: string[] = [];
const session = proveRevenue("GA6H", (s) => stages.push(s));
const session = proveRevenue("GA6H", "adsense", (s) => stages.push(s));
expect(stages).toEqual(["waiting"]);
session.abandon();
});
Expand All @@ -19,6 +19,6 @@ describe("proveRevenue", () => {
vi.stubEnv("NEXT_PUBLIC_RELAY_URL", "https://relay.example");
vi.stubEnv("NEXT_PUBLIC_GOOGLE_CLIENT_ID", "");
const { proveRevenue, RelayNotReadyError } = await import("./index");
await expect(proveRevenue("GA6H", () => {}).result).rejects.toBeInstanceOf(RelayNotReadyError);
await expect(proveRevenue("GA6H", "adsense", () => {}).result).rejects.toBeInstanceOf(RelayNotReadyError);
});
});
27 changes: 19 additions & 8 deletions fe/src/lib/reclaim/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/**
* Proving AdSense revenue, and getting back the attested values `request_advance` takes
* Proving AdSense or AdMob revenue (#97), and getting back the attested values `request_advance` takes
* (ARCHITECTURE.md §2, `lib/reclaim/`). The seam between the app and the #17 relay.
*
* With NEXT_PUBLIC_RELAY_URL and NEXT_PUBLIC_GOOGLE_CLIENT_ID set, the creator signs in with Google's
Expand All @@ -9,31 +9,42 @@
*/
import { mockProveRevenue } from "./mock";
import { googleSignIn, preloadGoogleSignIn, relayProveRevenue, sessionJobs } from "./relay";
import { RelayNotReadyError, type ProveSession, type ProveStage } from "./session";
import { RelayNotReadyError, type ProveSession, type ProveStage, type RevenueSource } from "./session";

export {
ReclaimCancelledError,
RelayError,
RelayNotReadyError,
SOURCE_NAME,
type ProveSession,
type ProveStage,
type RelayErrorCode,
type RevenueSource,
} from "./session";

const RELAY_URL = process.env.NEXT_PUBLIC_RELAY_URL ?? "";
const GOOGLE_CLIENT_ID = process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID ?? "";
// The e2e relay answers at once, so its jobs are polled faster than a real one's.
const POLL_MS = process.env.NEXT_PUBLIC_E2E === "1" ? 200 : undefined;

export function proveRevenue(borrower: string, onStage: (stage: ProveStage) => void): ProveSession {
if (!RELAY_URL) return mockProveRevenue(borrower, onStage);
export function proveRevenue(borrower: string, source: RevenueSource, onStage: (stage: ProveStage) => void): ProveSession {
if (!RELAY_URL) return mockProveRevenue(borrower, source, onStage);
if (!GOOGLE_CLIENT_ID) return { result: Promise.reject(new RelayNotReadyError()), reopen: () => {}, abandon: () => {} };
return relayProveRevenue(borrower, onStage, { relayUrl: RELAY_URL, signIn: googleSignIn(GOOGLE_CLIENT_ID), pollMs: POLL_MS });
return relayProveRevenue(borrower, onStage, {
relayUrl: RELAY_URL,
source,
signIn: googleSignIn(GOOGLE_CLIENT_ID),
pollMs: POLL_MS,
});
}

/** A proof the relay is still making for this wallet, started from this tab before the creator left. */
export function proofRunning(borrower: string): boolean {
return !!RELAY_URL && !!GOOGLE_CLIENT_ID && sessionJobs.load(borrower) !== null;
/**
* A proof the relay is still making for this wallet, started from this tab before the creator left: the
* source it proves, or null when there is none.
*/
export function proofRunning(borrower: string): RevenueSource | null {
if (!RELAY_URL || !GOOGLE_CLIENT_ID) return null;
return sessionJobs.load(borrower)?.source ?? null;
}

/** Load Google's sign-in ahead of "Prove my revenue", so the popup opens inside the press. */
Expand Down
15 changes: 11 additions & 4 deletions fe/src/lib/reclaim/mock.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ describe("mockProveRevenue", () => {

it("waits for the login, reads, then returns the arguments request_advance takes", async () => {
const stages: ProveStage[] = [];
const session = mockProveRevenue("GA6H", (s) => stages.push(s));
const session = mockProveRevenue("GA6H", "adsense", (s) => stages.push(s));
expect(stages).toEqual(["waiting"]);
await vi.runAllTimersAsync();
const req = await session.result;
Expand All @@ -23,24 +23,31 @@ describe("mockProveRevenue", () => {

it("returns the figure set for trying the other offer variants", async () => {
window.localStorage.setItem("forepay.mock.revenue", "1240.00");
const session = mockProveRevenue("GA6H", () => {});
const session = mockProveRevenue("GA6H", "adsense", () => {});
await vi.runAllTimersAsync();
expect((await session.result).revenueUsd).toBe("1240.00");
});

it("can close the window instead of finishing", async () => {
window.localStorage.setItem("forepay.mock.reclaim", "cancel");
const session = mockProveRevenue("GA6H", () => {});
const session = mockProveRevenue("GA6H", "adsense", () => {});
const settled = session.result.catch((e) => e);
await vi.runAllTimersAsync();
expect(await settled).toBeInstanceOf(ReclaimCancelledError);
});

it("goes back to waiting when the window is opened again", async () => {
const stages: ProveStage[] = [];
const session = mockProveRevenue("GA6H", (s) => stages.push(s));
const session = mockProveRevenue("GA6H", "adsense", (s) => stages.push(s));
session.reopen();
expect(stages).toEqual(["waiting", "waiting"]);
session.abandon();
});

it("answers AdMob the relay's way, micros beside the exact decimal", async () => {
window.localStorage.setItem("forepay.mock.revenue", "3.20");
const session = mockProveRevenue("GA6H", "admob", () => {});
await vi.runAllTimersAsync();
expect(await session.result).toMatchObject({ source: "admob", revenueMicros: "3200000", revenueUsd: "3.20" });
});
});
15 changes: 12 additions & 3 deletions fe/src/lib/reclaim/mock.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { AdvanceRequest } from "@/lib/stellar/contract";
import { ReclaimCancelledError, type ProveSession, type ProveStage } from "./session";
import { ReclaimCancelledError, type ProveSession, type ProveStage, type RevenueSource } from "./session";

/**
* A stand-in for the Reclaim session and the #17 relay, used while NEXT_PUBLIC_RELAY_URL is unset.
Expand All @@ -11,6 +11,7 @@ import { ReclaimCancelledError, type ProveSession, type ProveStage } from "./ses
*
* Two localStorage keys steer it, for trying each state by hand and in e2e:
* - `forepay.mock.revenue`: the attested figure, `360.00` by default (`1240.00` caps, `3.20` is too small).
* For AdMob it is answered the relay's way: micros as signed, and the exact decimal beside them.
* - `forepay.mock.reclaim`: `cancel` closes the window instead of finishing.
*/
const E2E = process.env.NEXT_PUBLIC_E2E === "1";
Expand All @@ -27,7 +28,13 @@ function setting(key: string): string | null {

export const MOCK_PUB_ID = "pub-4021783466891204";

export function mockProveRevenue(_borrower: string, onStage: (stage: ProveStage) => void): ProveSession {
/** `"12.34"` as AdMob signs it, in millionths of a USD. */
function micros(usd: string): string | undefined {
const m = /^(\d+)(?:\.(\d{1,6}))?$/.exec(usd);
return m ? (BigInt(m[1]) * 1_000_000n + BigInt((m[2] ?? "").padEnd(6, "0"))).toString() : undefined;
}

export function mockProveRevenue(_borrower: string, source: RevenueSource, onStage: (stage: ProveStage) => void): ProveSession {
let timer: ReturnType<typeof setTimeout> | undefined;
let abandoned = false;
let settle: { resolve: (r: AdvanceRequest) => void; reject: (e: unknown) => void } | undefined;
Expand All @@ -44,8 +51,10 @@ export function mockProveRevenue(_borrower: string, onStage: (stage: ProveStage)
onStage("reading");
timer = setTimeout(() => {
if (abandoned) return;
const revenueUsd = setting("forepay.mock.revenue") ?? "360.00";
settle?.resolve({
revenueUsd: setting("forepay.mock.revenue") ?? "360.00",
revenueUsd,
...(source === "admob" ? { source, revenueMicros: micros(revenueUsd) } : {}),
pubId: MOCK_PUB_ID,
windowStart: "2026-07-01",
windowEnd: "2026-09-30",
Expand Down
Loading