From f4eddd57b62efbd09430889de346e5c5a8c9111f Mon Sep 17 00:00:00 2001 From: Nabil-Aufa <181296848+Nabil-Aufa@users.noreply.github.com> Date: Tue, 27 Oct 2026 14:06:46 +0700 Subject: [PATCH 1/6] feat(#97): choose AdSense or AdMob on 2a, and prove the chosen one - 2a asks where the creator earns, AdSense (websites) or AdMob (apps). The Google sign-in asks for that source's read-only scope only, and a token without it counts as the creator stopping. - POST /proofs carries `source: "admob"` for AdMob only, so an AdSense request is what it was before. The kept job records its source, and a resumed job proves what it was started for. - The relay's `token` and `account` failures name AdMob for an AdMob proof (googleSignInAdmob, noAdmob). The waiting, checking and offer copy name the source. - An AdMob figure is sized from its micros truncated to cents (`provenUsd`). `request_advance` gets the signed micros; its AdMob arguments land with #94. - The mock answers AdMob the relay's way, so the flow runs without a relay. Co-Authored-By: Claude Opus 5.5 --- fe/src/components/elements/OfferBreakdown.tsx | 7 +- fe/src/lib/errors.test.ts | 4 +- fe/src/lib/errors.ts | 13 ++++ fe/src/lib/reclaim/index.test.ts | 4 +- fe/src/lib/reclaim/index.ts | 17 ++-- fe/src/lib/reclaim/mock.test.ts | 15 +++- fe/src/lib/reclaim/mock.ts | 15 +++- fe/src/lib/reclaim/relay.test.ts | 77 +++++++++++++++++-- fe/src/lib/reclaim/relay.ts | 69 +++++++++++------ fe/src/lib/reclaim/session.ts | 13 +++- fe/src/lib/stellar/contract.test.ts | 14 +++- fe/src/lib/stellar/contract.ts | 21 ++++- fe/src/modules/advance/Advance.tsx | 38 ++++++--- .../advance/components/FailurePanel.tsx | 2 + .../advance/components/ProveRevenue.tsx | 55 ++++++++++++- .../advance/components/ReviewOffer.tsx | 10 ++- fe/src/modules/advance/failures.test.ts | 4 + fe/src/modules/advance/failures.ts | 4 +- 18 files changed, 312 insertions(+), 70 deletions(-) diff --git a/fe/src/components/elements/OfferBreakdown.tsx b/fe/src/components/elements/OfferBreakdown.tsx index d63833e..2dbdbe8 100644 --- a/fe/src/components/elements/OfferBreakdown.tsx +++ b/fe/src/components/elements/OfferBreakdown.tsx @@ -9,6 +9,7 @@ import { formatUsdc } from "@/lib/format"; */ export function OfferBreakdown({ revenue, + sourceName = "AdSense", windowShort, advance, rate, @@ -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. */ @@ -36,8 +39,8 @@ export function OfferBreakdown({ { key: ( <> - Your AdSense revenue, {windowShort} - AdSense revenue, {months} + Your {sourceName} revenue, {windowShort} + {sourceName} revenue, {months} ), value: revenue, diff --git a/fe/src/lib/errors.test.ts b/fe/src/lib/errors.test.ts index fda9173..8e4578b 100644 --- a/fe/src/lib/errors.test.ts +++ b/fe/src/lib/errors.test.ts @@ -125,6 +125,8 @@ describe("proveFailureCopy", () => { "relayNotReady", "googleSignIn", "noAdsense", + "googleSignInAdmob", + "noAdmob", "relayFailed", "relayBusy", "proofRunning", @@ -144,7 +146,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) { diff --git a/fe/src/lib/errors.ts b/fe/src/lib/errors.ts index 9656763..f364360 100644 --- a/fe/src/lib/errors.ts +++ b/fe/src/lib/errors.ts @@ -212,6 +212,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. @@ -237,6 +238,8 @@ export type ProveFailure = | "relayNotReady" | "googleSignIn" | "noAdsense" + | "googleSignInAdmob" + | "noAdmob" | "relayFailed" | "relayBusy" | "proofRunning" @@ -331,6 +334,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", diff --git a/fe/src/lib/reclaim/index.test.ts b/fe/src/lib/reclaim/index.test.ts index b1ad6e0..1557a66 100644 --- a/fe/src/lib/reclaim/index.test.ts +++ b/fe/src/lib/reclaim/index.test.ts @@ -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(); }); @@ -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); }); }); diff --git a/fe/src/lib/reclaim/index.ts b/fe/src/lib/reclaim/index.ts index 6b0e172..f2cfdc1 100644 --- a/fe/src/lib/reclaim/index.ts +++ b/fe/src/lib/reclaim/index.ts @@ -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 @@ -9,15 +9,17 @@ */ 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 ?? ""; @@ -25,10 +27,15 @@ 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. */ diff --git a/fe/src/lib/reclaim/mock.test.ts b/fe/src/lib/reclaim/mock.test.ts index 0f85e73..d259370 100644 --- a/fe/src/lib/reclaim/mock.test.ts +++ b/fe/src/lib/reclaim/mock.test.ts @@ -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; @@ -23,14 +23,14 @@ 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); @@ -38,9 +38,16 @@ describe("mockProveRevenue", () => { 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" }); + }); }); diff --git a/fe/src/lib/reclaim/mock.ts b/fe/src/lib/reclaim/mock.ts index e868747..2e26533 100644 --- a/fe/src/lib/reclaim/mock.ts +++ b/fe/src/lib/reclaim/mock.ts @@ -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. @@ -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"; @@ -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 | undefined; let abandoned = false; let settle: { resolve: (r: AdvanceRequest) => void; reject: (e: unknown) => void } | undefined; @@ -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", diff --git a/fe/src/lib/reclaim/relay.test.ts b/fe/src/lib/reclaim/relay.test.ts index 92b5be6..44f8d84 100644 --- a/fe/src/lib/reclaim/relay.test.ts +++ b/fe/src/lib/reclaim/relay.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; -import { relayProveRevenue, type JobStore, type SignIn } from "./relay"; -import { ReclaimCancelledError, RelayError, type ProveStage } from "./session"; +import { ADMOB_SCOPE, ADSENSE_SCOPE, googleSignIn, relayProveRevenue, type JobStore, type KeptJob, type SignIn } from "./relay"; +import { ReclaimCancelledError, RelayError, type ProveStage, type RevenueSource } from "./session"; const BORROWER = "GA2CD6PMHMBTCFAQDO3R22BSZN5ZSVTAKVNOKXL2SONZBLGRAYIOWWH2"; const REQUEST = { @@ -29,11 +29,11 @@ function relay(polls: object[], post: { status: number; body: object } = { statu const signedIn: SignIn = async () => "ya29.token"; /** A tab's job store, in memory. */ -function store(kept: { borrower: string; id: string } | null = null) { +function store(kept: { borrower: string; id: string; source?: RevenueSource } | null = null) { const s = { kept }; const jobs: JobStore = { - load: (b) => (s.kept?.borrower === b ? s.kept.id : null), - save: (borrower, id) => (s.kept = { borrower, id }), + load: (b) => (s.kept?.borrower === b ? { id: s.kept.id, source: s.kept.source ?? "adsense" } : null), + save: (borrower, job) => (s.kept = { borrower, ...job }), clear: () => (s.kept = null), }; return Object.assign(s, { jobs }); @@ -110,14 +110,14 @@ describe("relayProveRevenue", () => { it("keeps the job id while proving and forgets it once the job ends", async () => { const t = store(); - let seen: string | null = null; + let seen: KeptJob | null = null; const fetch = (async (_url: string, init?: RequestInit) => { if (init?.method === "POST") return new Response(JSON.stringify({ id: "j1", stage: "queued" }), { status: 202 }); seen = t.jobs.load(BORROWER); return new Response(JSON.stringify({ id: "j1", stage: "done", request: REQUEST })); }) as unknown as typeof globalThis.fetch; await relayProveRevenue(BORROWER, () => {}, { relayUrl: "https://r", signIn: signedIn, fetch, sleep: noSleep, jobs: t.jobs }).result; - expect(seen).toBe("j1"); + expect(seen).toEqual({ id: "j1", source: "adsense" }); expect(t.kept).toBeNull(); }); @@ -259,4 +259,67 @@ describe("relayProveRevenue", () => { expect(polls).toBe(0); expect(settled).toBe(false); }); + + it("proves AdMob when asked: its sign-in, `source` on POST /proofs, and the job kept with its source", async () => { + const ADMOB = { ...REQUEST, revenueUsd: "12.345678", source: "admob", revenueMicros: "12345678" }; + const r = relay([{ id: "j1", stage: "done", request: ADMOB }]); + const asked: RevenueSource[] = []; + const t = store(); + let kept: KeptJob | null = null; + const fetch = (async (url: string, init?: RequestInit) => { + if (init?.method !== "POST") kept = t.jobs.load(BORROWER); + return r.fetch(url, init); + }) as unknown as typeof globalThis.fetch; + const signIn: SignIn = async (source) => (asked.push(source), "ya29.token"); + const req = await relayProveRevenue(BORROWER, () => {}, { relayUrl: "https://r", source: "admob", signIn, fetch, sleep: noSleep, jobs: t.jobs }).result; + expect(asked).toEqual(["admob"]); + expect(JSON.parse(String(r.calls[0].init?.body))).toEqual({ borrower: BORROWER, accessToken: "ya29.token", source: "admob" }); + expect(kept).toEqual({ id: "j1", source: "admob" }); + expect(req).toMatchObject({ source: "admob", revenueMicros: "12345678", revenueUsd: "12.345678" }); + }); + + it("an AdSense proof sends no `source`, so a relay from before #97 reads the same request", async () => { + const r = relay([{ id: "j1", stage: "done", request: REQUEST }]); + await relayProveRevenue(BORROWER, () => {}, { relayUrl: "https://r", source: "adsense", signIn: signedIn, fetch: r.fetch, sleep: noSleep, jobs: store().jobs }).result; + expect(JSON.parse(String(r.calls[0].init?.body))).not.toHaveProperty("source"); + }); + + it("a kept AdMob job resumes as AdMob, and its failures name AdMob", async () => { + const t = store({ borrower: BORROWER, id: "j1", source: "admob" }); + const r = relay([{ id: "j1", stage: "failed", error: { code: "account", message: "This Google account has no AdMob account." } }]); + const e = await relayProveRevenue(BORROWER, () => {}, { relayUrl: "https://r", source: "adsense", signIn: signedIn, fetch: r.fetch, sleep: noSleep, jobs: t.jobs }) + .result.catch((x) => x); + expect(e).toBeInstanceOf(RelayError); + expect((e as RelayError).code).toBe("account"); + expect((e as RelayError).source).toBe("admob"); + }); +}); + +describe("googleSignIn", () => { + /** Google's token client, answering with the scopes the creator allowed. */ + function gis(granted: string) { + const scopes: string[] = []; + window.google = { + accounts: { + oauth2: { + initTokenClient: (c) => { + scopes.push(c.scope); + return { requestAccessToken: () => c.callback({ access_token: "ya29.t", scope: granted }) }; + }, + }, + }, + }; + return scopes; + } + + it("asks for the chosen source's scope only", async () => { + const scopes = gis(ADMOB_SCOPE); + await expect(googleSignIn("id")("admob")).resolves.toBe("ya29.t"); + expect(scopes).toEqual([ADMOB_SCOPE]); + }); + + it("treats a token without the chosen source's scope as the creator stopping", async () => { + gis(ADSENSE_SCOPE); + await expect(googleSignIn("id")("admob")).rejects.toBeInstanceOf(ReclaimCancelledError); + }); }); diff --git a/fe/src/lib/reclaim/relay.ts b/fe/src/lib/reclaim/relay.ts index 63d8028..1dc2828 100644 --- a/fe/src/lib/reclaim/relay.ts +++ b/fe/src/lib/reclaim/relay.ts @@ -16,9 +16,19 @@ * ends the session as `gone`, so the sign-in it needs starts from a press. */ import type { AdvanceRequest } from "@/lib/stellar/contract"; -import { ReclaimCancelledError, RelayError, type ProveSession, type ProveStage, type RelayErrorCode } from "./session"; +import { + ReclaimCancelledError, + RelayError, + type ProveSession, + type ProveStage, + type RelayErrorCode, + type RevenueSource, +} from "./session"; export const ADSENSE_SCOPE = "https://www.googleapis.com/auth/adsense.readonly"; +export const ADMOB_SCOPE = "https://www.googleapis.com/auth/admob.readonly"; +/** One read-only scope per source, never both (#97). */ +const SCOPES: Record = { adsense: ADSENSE_SCOPE, admob: ADMOB_SCOPE }; const GIS_SRC = "https://accounts.google.com/gsi/client"; /** The slice of Google Identity Services' token client used here. */ @@ -73,19 +83,23 @@ export function preloadGoogleSignIn(): void { }); } -/** Opens the popup each time it is called; resolves with the token, or rejects when the popup closes. */ -export type SignIn = () => Promise; +/** + * Opens the popup each time it is called, asking for the source's scope; resolves with the token, or + * rejects when the popup closes. + */ +export type SignIn = (source: RevenueSource) => Promise; export function googleSignIn(clientId: string): SignIn { - return async () => { + return async (source) => { const gis = await loadGis(); + const scope = SCOPES[source]; return new Promise((resolve, reject) => { const client = gis.initTokenClient({ client_id: clientId, - scope: ADSENSE_SCOPE, + scope, callback: (r) => { - if (r.access_token && (r.scope ?? "").split(" ").includes(ADSENSE_SCOPE)) resolve(r.access_token); - // Denied, or allowed without the AdSense box ticked: the creator stopped, nothing was read. + if (r.access_token && (r.scope ?? "").split(" ").includes(scope)) resolve(r.access_token); + // Denied, or allowed without the reports box ticked: the creator stopped, nothing was read. else reject(new ReclaimCancelledError()); }, error_callback: (e) => @@ -108,10 +122,13 @@ type Job = { error?: { code: RelayErrorCode; message: string }; }; +/** A job this tab started, and which source it proves. */ +export type KeptJob = { id: string; source: RevenueSource }; + /** Where the running job's id waits while the creator is away from /advance. */ export type JobStore = { - load: (borrower: string) => string | null; - save: (borrower: string, id: string) => void; + load: (borrower: string) => KeptJob | null; + save: (borrower: string, job: KeptJob) => void; clear: () => void; }; @@ -126,15 +143,18 @@ const JOB_KEY = "forepay.proof.job"; export const sessionJobs: JobStore = { load: (borrower) => { try { - const s = JSON.parse(window.sessionStorage.getItem(JOB_KEY) ?? "null") as { borrower: string; id: string } | null; - return s?.borrower === borrower ? s.id : null; + const s = JSON.parse(window.sessionStorage.getItem(JOB_KEY) ?? "null") as + | { borrower: string; id: string; source?: RevenueSource } + | null; + // Kept before #97 named the source: those were AdSense. + return s?.borrower === borrower ? { id: s.id, source: s.source === "admob" ? "admob" : "adsense" } : null; } catch { return null; } }, - save: (borrower, id) => { + save: (borrower, { id, source }) => { try { - window.sessionStorage.setItem(JOB_KEY, JSON.stringify({ borrower, id })); + window.sessionStorage.setItem(JOB_KEY, JSON.stringify({ borrower, id, source })); } catch { // Storage unavailable: leaving the page while proving loses the job, as before. } @@ -150,6 +170,8 @@ export const sessionJobs: JobStore = { export type RelayOptions = { relayUrl: string; + /** What a new proof proves, AdSense by default. A kept job proves what it was started for. */ + source?: RevenueSource; signIn: SignIn; fetch?: typeof fetch; jobs?: JobStore; @@ -173,6 +195,9 @@ export function relayProveRevenue(borrower: string, onStage: (stage: ProveStage) const pollMs = o.pollMs ?? 5000; const timeoutMs = o.timeoutMs ?? 60 * 60_000; const sleep = o.sleep ?? ((ms: number) => new Promise((r) => setTimeout(r, ms))); + // A kept job proves the source it was started for, whatever this press chose. + const kept = jobs.load(borrower); + const source = kept?.source ?? o.source ?? "adsense"; let abandoned = false; let reading = false; let attempt = 0; @@ -192,7 +217,7 @@ export function relayProveRevenue(borrower: string, onStage: (stage: ProveStage) function signIn() { const mine = ++attempt; onStage("waiting"); - o.signIn().then(settleToken.resolve, (e) => { + o.signIn(source).then(settleToken.resolve, (e) => { if (mine === attempt) settleToken.reject(e); }); } @@ -212,7 +237,7 @@ export function relayProveRevenue(borrower: string, onStage: (stage: ProveStage) const message = typeof body.error === "string" ? body.error : `the relay answered ${res.status}`; // The relay names the refusal in `code` (docs/api.md); the status is the fallback. const code = CODES.find((c) => c === body.code) ?? (res.status === 409 ? "running" : res.status === 503 ? "busy" : "internal"); - throw new RelayError(code, message); + throw new RelayError(code, message, source); } return body; } @@ -234,17 +259,16 @@ export function relayProveRevenue(borrower: string, onStage: (stage: ProveStage) async function prove(): Promise { // A job this tab started before the creator left: wait on it rather than sign in again. - const kept = jobs.load(borrower); if (kept) { reading = true; onStage("reading"); - const job = await follow(kept); + const job = await follow(kept.id); if (job) return job; // The relay no longer has it (it restarted, or the hour passed). Signing in again here would open // Google's popup outside any press, on mount or after an await, and the browser would block it // (review on #75). The creator's next press opens it instead. jobs.clear(); - throw new RelayError("gone", "the relay no longer has this proof job"); + throw new RelayError("gone", "the relay no longer has this proof job", source); } signIn(); const accessToken = await token; @@ -255,12 +279,13 @@ export function relayProveRevenue(borrower: string, onStage: (stage: ProveStage) await call(`${base}/proofs`, { method: "POST", headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ borrower, accessToken }), + // `source` only for AdMob: an AdSense request stays what it was before #97, for relays without it. + body: JSON.stringify(source === "admob" ? { borrower, accessToken, source } : { borrower, accessToken }), }), ); - jobs.save(borrower, started.id); + jobs.save(borrower, { id: started.id, source }); const job = await follow(started.id, started); - if (!job) throw new RelayError("internal", "the relay lost the proof job"); + if (!job) throw new RelayError("internal", "the relay lost the proof job", source); return job; } @@ -271,7 +296,7 @@ export function relayProveRevenue(borrower: string, onStage: (stage: ProveStage) // finds the result. jobs.clear(); if (job.stage === "failed" || !job.request) { - throw new RelayError(job.error?.code ?? "internal", job.error?.message ?? "the proof failed"); + throw new RelayError(job.error?.code ?? "internal", job.error?.message ?? "the proof failed", source); } return { ...job.request, timestampS: BigInt(job.request.timestampS), epoch: BigInt(job.request.epoch) }; } diff --git a/fe/src/lib/reclaim/session.ts b/fe/src/lib/reclaim/session.ts index 159609c..d354b11 100644 --- a/fe/src/lib/reclaim/session.ts +++ b/fe/src/lib/reclaim/session.ts @@ -1,6 +1,15 @@ /** What a Reclaim session reports while it runs, and how it can end. Shared by the real seam and the mock. */ import type { AdvanceRequest } from "@/lib/stellar/contract"; +/** + * Where the revenue comes from (#97): AdSense, ads on websites, or AdMob, ads in apps. The sign-in asks for + * the chosen one's read-only scope only, and the relay proves that one's report (docs/api.md, `source`). + */ +export type RevenueSource = "adsense" | "admob"; + +/** The name each source goes by in the copy. */ +export const SOURCE_NAME: Record = { adsense: "AdSense", admob: "AdMob" }; + export type ProveStage = /** Google's sign-in window is open. The creator signs in to AdSense there, not on our page. */ | "waiting" @@ -35,7 +44,7 @@ export class RelayNotReadyError extends Error { /** * Why the relay could not make the proof, by whose move it is (docs/api.md): * - `token`: Google refused the sign-in, for example an expired one. Signing in again fixes it. - * - `account`: no approved AdSense account behind that Google account. + * - `account`: no approved AdSense account (or no AdMob account) behind that Google account. * - `running`: a proof for this wallet is already running, started from a tab that no longer has it. * - `gone`: the proof this tab was waiting on is no longer on the relay (it restarted, or an hour passed). * - `busy`: the relay is proving for others and its queue is full. @@ -64,6 +73,8 @@ export class RelayError extends Error { constructor( readonly code: RelayErrorCode, message: string, + /** The source being proved, so `token` and `account` name the right one. AdSense when unknown. */ + readonly source: RevenueSource = "adsense", ) { super(message); this.name = "RelayError"; diff --git a/fe/src/lib/stellar/contract.test.ts b/fe/src/lib/stellar/contract.test.ts index dda2beb..be11afd 100644 --- a/fe/src/lib/stellar/contract.test.ts +++ b/fe/src/lib/stellar/contract.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { contractCode } from "./contract"; +import { contractCode, provenUsd } from "./contract"; describe("contractCode", () => { it("reads the contract's error number out of a simulation error", () => { @@ -10,3 +10,15 @@ describe("contractCode", () => { expect(contractCode("HostError: Error(Budget, ExceededLimit)")).toBeNull(); }); }); + +describe("provenUsd", () => { + it("is the AdSense figure as signed", () => { + expect(provenUsd({ revenueUsd: "360.00" })).toBe("360.00"); + }); + + it("truncates AdMob's micros to cents, never rounding up", () => { + expect(provenUsd({ revenueUsd: "12.345678", source: "admob", revenueMicros: "12345678" })).toBe("12.34"); + expect(provenUsd({ revenueUsd: "0.999999", source: "admob", revenueMicros: "999999" })).toBe("0.99"); + expect(provenUsd({ revenueUsd: "4", source: "admob", revenueMicros: "4000000" })).toBe("4.00"); + }); +}); diff --git a/fe/src/lib/stellar/contract.ts b/fe/src/lib/stellar/contract.ts index e4753d5..d2876a9 100644 --- a/fe/src/lib/stellar/contract.ts +++ b/fe/src/lib/stellar/contract.ts @@ -241,12 +241,31 @@ export type AdvanceRequest = { /** 64 bytes, hex. */ signature: string; recoveryId: number; + /** + * An AdMob proof (#97). Its signed figure is `revenueMicros`, millionths of a USD, and `revenueUsd` is + * the same figure as an exact decimal (`"12.345678"`), for display only (docs/api.md). Absent for AdSense. + */ + source?: "admob"; + revenueMicros?: string; }; +/** + * The proven revenue as the contract sizes it: a decimal with at most two places (`quote` refuses more). + * AdMob's micros are truncated to cents, never rounded up, as the contract will (#94). + */ +export function provenUsd(req: Pick): string { + if (req.source !== "admob" || !req.revenueMicros || !/^\d+$/.test(req.revenueMicros)) return req.revenueUsd; + const cents = BigInt(req.revenueMicros) / 10_000n; + return `${cents / 100n}.${(cents % 100n).toString().padStart(2, "0")}`; +} + function advanceArgs(borrower: string, req: AdvanceRequest): xdr.ScVal[] { return [ new Address(borrower).toScVal(), - str(req.revenueUsd), + // The figure the attestor signed. For AdMob that is the micros string; the contract that reads it, + // and whatever else it takes to tell the sources apart, land with #94. The contract deployed before + // it has no AdMob template and refuses an AdMob proof at simulation. + str(req.source === "admob" && req.revenueMicros ? req.revenueMicros : req.revenueUsd), str(req.pubId), str(req.windowStart), str(req.windowEnd), diff --git a/fe/src/modules/advance/Advance.tsx b/fe/src/modules/advance/Advance.tsx index 1994966..d61103d 100644 --- a/fe/src/modules/advance/Advance.tsx +++ b/fe/src/modules/advance/Advance.tsx @@ -7,7 +7,15 @@ import { SkeletonBlock } from "@/components/ui/Skeleton"; import { notify } from "@/components/ui/Toaster"; import { isSignatureDeclined } from "@/lib/errors"; import { formatUsd, formatWindow } from "@/lib/format"; -import { preloadSignIn, proofRunning, proveRevenue, type ProveSession, type ProveStage } from "@/lib/reclaim"; +import { + preloadSignIn, + proofRunning, + proveRevenue, + SOURCE_NAME, + type ProveSession, + type ProveStage, + type RevenueSource, +} from "@/lib/reclaim"; import { TransactionFailedError, awaitAdvance, @@ -15,6 +23,7 @@ import { getAdvance, sizing, nullifierFor, + provenUsd, quote, requestAdvance, type AdvanceRequest, @@ -85,6 +94,8 @@ export function Advance() { const wallet = walletName ?? "your wallet"; const [flow, setFlow] = useState({ at: "start" }); + // The source picked on 2a. A proof resumed from an earlier visit proves what it was started for. + const [source, setSource] = useState("adsense"); const [allowing, setAllowing] = useState(false); // Every attempt gets a number. An answer for an attempt that is no longer the current one (the // creator pressed Cancel, Not now or Back meanwhile) is dropped. @@ -122,8 +133,8 @@ export function Advance() { // The offer on 2b and 2c. Read in `check` before 2b opens, so it is already here. const req = "req" in flow ? flow.req : undefined; const offer = useQuery({ - queryKey: quoteKey(address ?? "", req?.revenueUsd ?? ""), - queryFn: () => quote(address as string, (req as AdvanceRequest).revenueUsd), + queryKey: quoteKey(address ?? "", req ? provenUsd(req) : ""), + queryFn: () => quote(address as string, provenUsd(req as AdvanceRequest)), enabled: !!address && !!req && (flow.at === "offer" || flow.at === "signing"), // `quote` is a pure function of the revenue figure on chain: the same input always sizes the same. staleTime: Infinity, @@ -138,7 +149,7 @@ export function Advance() { enabled: !!address, staleTime: Infinity, }); - const capped = terms.data && req ? isCapped(terms.data, req.revenueUsd) : null; + const capped = terms.data && req ? isCapped(terms.data, provenUsd(req)) : null; // The advance as the contract stored it, for 2d. Keyed by its nullifier (ARCHITECTURE.md §4). const received = flow.at === "received" ? flow : undefined; @@ -183,7 +194,7 @@ export function Advance() { leave(); const id = attempt.current; setFlow({ at: "proving", stage: "waiting" }); - const s = proveRevenue(me, (stage) => { + const s = proveRevenue(me, source, (stage) => { if (id === attempt.current) setFlow({ at: "proving", stage }); }); session.current = s; @@ -207,8 +218,8 @@ export function Advance() { try { const [quoted, checked] = await Promise.allSettled([ queryClient.fetchQuery({ - queryKey: quoteKey(me, r.revenueUsd), - queryFn: () => quote(me, r.revenueUsd), + queryKey: quoteKey(me, provenUsd(r)), + queryFn: () => quote(me, provenUsd(r)), staleTime: Infinity, }), checkAdvance(me, r), @@ -220,7 +231,7 @@ export function Advance() { await queryClient.prefetchQuery({ queryKey: sizingKey(me), queryFn: () => sizing(me), staleTime: Infinity }); if (id === attempt.current) setFlow({ at: "offer", req: r }); } catch (e) { - if (id === attempt.current) setFlow({ at: "failed", failure: proveFailure(e, r.revenueUsd), req: r, during: "prove" }); + if (id === attempt.current) setFlow({ at: "failed", failure: proveFailure(e, provenUsd(r)), req: r, during: "prove" }); } } @@ -426,6 +437,8 @@ export function Advance() { walletName={wallet} terms={terms.isPending ? "loading" : terms.data} usdc={usdc.isError ? "error" : usdc.data} + source={source} + onSource={setSource} onProve={prove} /> @@ -439,12 +452,12 @@ export function Advance() { {flow.at === "checking" ? ( ) : flow.stage === "waiting" ? ( session.current?.reopen()}> Open the window again @@ -463,12 +476,13 @@ export function Advance() { if (flow.at === "offer") { const period = formatWindow(flow.req.windowStart, flow.req.windowEnd); // With the figure, so a quote under 1 USDC reads as "too small" with the creator's own number. - const offerFailure = offer.isError ? proveFailure(offer.error, flow.req.revenueUsd) : null; + const offerFailure = offer.isError ? proveFailure(offer.error, provenUsd(flow.req)) : null; return ( {offer.data !== undefined ? ( void; onProve: () => void; }) { + const name = SOURCE_NAME[source]; return (
@@ -41,8 +49,9 @@ export function ProveRevenue({

See how much you can get

- Sign in with Google in a secure window. We read your AdSense revenue for the last three months and nothing else. + Sign in with Google in a secure window. We read your {name} revenue for the last three months and nothing else.

+ {/* Side by side only where each list keeps its longest item ("Revenue from the last three complete months", about 360 in Body) on one line: two of them and the 24 gap. */}
@@ -50,7 +59,7 @@ export function ProveRevenue({ head="What we read" // Not named months (review S8): the window is not chain data before the advance. It is // what the #17 relay asks AdSense for, so 2a can name it once the relay exists. - items={["Revenue from the last three complete months", "Your AdSense publisher ID"]} + items={["Revenue from the last three complete months", `Your ${name} publisher ID`]} icon={} /> void }) { + return ( +
+ Where you earn +
+ {SOURCES.map((s) => ( + + ))} +
+
+ ); +} + function List({ head, items, icon }: { head: string; items: string[]; icon: ReactNode }) { return (
diff --git a/fe/src/modules/advance/components/ReviewOffer.tsx b/fe/src/modules/advance/components/ReviewOffer.tsx index dda5858..a6f54be 100644 --- a/fe/src/modules/advance/components/ReviewOffer.tsx +++ b/fe/src/modules/advance/components/ReviewOffer.tsx @@ -14,6 +14,7 @@ import { formatUsdc } from "@/lib/format"; */ export function ReviewOffer({ revenue, + sourceName = "AdSense", windowShort, windowLong, advance, @@ -24,6 +25,8 @@ export function ReviewOffer({ }: { /** `$360.00` */ revenue: string; + /** Where it was earned, `AdSense` or `AdMob` (#97). */ + sourceName?: string; /** `Jul to Sep 2026` */ windowShort: string; /** `July to September` */ @@ -71,16 +74,17 @@ export function ReviewOffer({

{capped - ? `The most one advance can be. You earned ${revenue} on AdSense from ${windowLong}.` + ? `The most one advance can be. You earned ${revenue} on ${sourceName} from ${windowLong}.` : capped === null || !terms - ? `You earned ${revenue} on AdSense from ${windowLong}.` - : `${shareWords(terms)} of the ${revenue} you earned on AdSense from ${windowLong}.`} + ? `You earned ${revenue} on ${sourceName} from ${windowLong}.` + : `${shareWords(terms)} of the ${revenue} you earned on ${sourceName} from ${windowLong}.`}

{ expect(proveFailure(new RelayError("googleUnavailable", "x"))).toEqual({ kind: "googleUnavailable" }); expect(proveFailure(new RelayError("popupBlocked", "x"))).toEqual({ kind: "popupBlocked" }); expect(proveFailure(new RelayError("busy", "x"))).toEqual({ kind: "relayBusy" }); + // An AdMob proof names AdMob where the creator has to act on their Google account (#97). + expect(proveFailure(new RelayError("token", "x", "admob"))).toEqual({ kind: "googleSignInAdmob" }); + expect(proveFailure(new RelayError("account", "x", "admob"))).toEqual({ kind: "noAdmob" }); + expect(proveFailure(new RelayError("gone", "x", "admob"))).toEqual({ kind: "proofGone" }); for (const code of ["provider", "prove", "audit", "internal"] as const) { expect(proveFailure(new RelayError(code, "x"))).toEqual({ kind: "relayFailed" }); } diff --git a/fe/src/modules/advance/failures.ts b/fe/src/modules/advance/failures.ts index 2d7b4d0..3323c61 100644 --- a/fe/src/modules/advance/failures.ts +++ b/fe/src/modules/advance/failures.ts @@ -16,8 +16,8 @@ function sorted(e: unknown): AdvanceFailure { if (e instanceof RelayNotReadyError) return { kind: "relayNotReady" }; if (e instanceof RelayError) { const kinds: Partial> = { - token: "googleSignIn", - account: "noAdsense", + token: e.source === "admob" ? "googleSignInAdmob" : "googleSignIn", + account: e.source === "admob" ? "noAdmob" : "noAdsense", running: "proofRunning", gone: "proofGone", busy: "relayBusy", From e3d8aaa1e4731915690d8cec8ad949e1d61e9d66 Mon Sep 17 00:00:00 2001 From: Nabil-Aufa <181296848+Nabil-Aufa@users.noreply.github.com> Date: Tue, 27 Oct 2026 14:17:49 +0700 Subject: [PATCH 2/6] test(#97): e2e for proving AdMob, and stack the source tiles on the narrowest phones - relay.spec: choosing AdMob asks Google for admob.readonly only, sends `source: "admob"`, sizes the offer from the micros truncated to cents and names AdMob on the offer. A Google account with no AdMob gets the AdMob panel, and Prove again stays on AdMob. - The two source tiles sit side by side from about 19rem of card, and stack below it, where "AdSense" spilled out of its tile at 320 (layout.spec). Co-Authored-By: Claude Opus 5.5 --- .../advance/components/ProveRevenue.tsx | 4 +- fe/tests/e2e/relay.spec.ts | 49 +++++++++++++++++-- 2 files changed, 49 insertions(+), 4 deletions(-) diff --git a/fe/src/modules/advance/components/ProveRevenue.tsx b/fe/src/modules/advance/components/ProveRevenue.tsx index 79aefb3..f6468e2 100644 --- a/fe/src/modules/advance/components/ProveRevenue.tsx +++ b/fe/src/modules/advance/components/ProveRevenue.tsx @@ -125,7 +125,9 @@ function SourcePicker({ source, onSource }: { source: RevenueSource; onSource: ( return (
Where you earn -
+ {/* Side by side once each tile keeps "AdSense" beside its radio (about 19rem of card); stacked + on the narrowest phones (section 08). */} +
{SOURCES.map((s) => (