diff --git a/fe/.env.example b/fe/.env.example index 7ec6fee..1e14adc 100644 --- a/fe/.env.example +++ b/fe/.env.example @@ -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= diff --git a/fe/README.md b/fe/README.md index ae59758..ce2f287 100644 --- a/fe/README.md +++ b/fe/README.md @@ -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. diff --git a/fe/playwright.config.ts b/fe/playwright.config.ts index 98863b3..0b3cd88 100644 --- a/fe/playwright.config.ts +++ b/fe/playwright.config.ts @@ -23,6 +23,8 @@ function server(port: number, distDir: string, proving: Record) 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", @@ -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", }), ] : []), 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..b80f860 100644 --- a/fe/src/lib/errors.test.ts +++ b/fe/src/lib/errors.test.ts @@ -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"); @@ -125,6 +133,8 @@ describe("proveFailureCopy", () => { "relayNotReady", "googleSignIn", "noAdsense", + "googleSignInAdmob", + "noAdmob", "relayFailed", "relayBusy", "proofRunning", @@ -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) { diff --git a/fe/src/lib/errors.ts b/fe/src/lib/errors.ts index 9656763..b496930 100644 --- a/fe/src/lib/errors.ts +++ b/fe/src/lib/errors.ts @@ -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 { @@ -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 { @@ -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. @@ -237,6 +239,8 @@ export type ProveFailure = | "relayNotReady" | "googleSignIn" | "noAdsense" + | "googleSignInAdmob" + | "noAdmob" | "relayFailed" | "relayBusy" | "proofRunning" @@ -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", 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..e0c66dc 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,15 +27,24 @@ 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. */ 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..8489555 100644 --- a/fe/src/lib/stellar/contract.test.ts +++ b/fe/src/lib/stellar/contract.test.ts @@ -1,5 +1,19 @@ import { describe, expect, it } from "vitest"; -import { contractCode } from "./contract"; +import { scValToNative, xdr } from "@stellar/stellar-sdk"; +import { advanceArgs, contractCode, provenUsd, sourceArg, withSource, type AdvanceRequest } from "./contract"; + +const BORROWER = "GA2CD6PMHMBTCFAQDO3R22BSZN5ZSVTAKVNOKXL2SONZBLGRAYIOWWH2"; +const REQ: AdvanceRequest = { + revenueUsd: "360.00", + pubId: "pub-1", + windowStart: "2026-07-01", + windowEnd: "2026-09-30", + timestampS: 1n, + epoch: 1n, + signature: "00".repeat(64), + recoveryId: 0, +}; +const native = (args: xdr.ScVal[]) => args.map((a) => scValToNative(a) as unknown); describe("contractCode", () => { it("reads the contract's error number out of a simulation error", () => { @@ -10,3 +24,36 @@ 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"); + // Without micros, the exact decimal is cut to cents rather than handed to `quote` as it is. + expect(provenUsd({ revenueUsd: "12.345678", source: "admob" })).toBe("12.34"); + }); +}); + +describe("the revenue source on the contract's calls (#94)", () => { + it("is the contract's Source enum: a vector holding the variant's name", () => { + expect(sourceArg(undefined).toXDR("base64")).toBe(xdr.ScVal.scvVec([xdr.ScVal.scvSymbol("AdSense")]).toXDR("base64")); + expect(sourceArg("admob").toXDR("base64")).toBe(xdr.ScVal.scvVec([xdr.ScVal.scvSymbol("AdMob")]).toXDR("base64")); + }); + + it("is left out for the contract before #94, so its calls are what they were", () => { + const args = advanceArgs(BORROWER, REQ, false); + expect(native(args)).toEqual([BORROWER, "360.00", "pub-1", "2026-07-01", "2026-09-30", 1n, 1n, Buffer.alloc(64), 0]); + expect(withSource("admob", args, false)).toBe(args); + }); + + it("leads the call once the contract takes it, and an AdMob proof gives its signed micros", () => { + expect(native(advanceArgs(BORROWER, REQ, true)).slice(0, 3)).toEqual([["AdSense"], BORROWER, "360.00"]); + const admob = { ...REQ, revenueUsd: "360.004567", source: "admob" as const, revenueMicros: "360004567" }; + expect(native(advanceArgs(BORROWER, admob, true)).slice(0, 3)).toEqual([["AdMob"], BORROWER, "360004567"]); + }); +}); diff --git a/fe/src/lib/stellar/contract.ts b/fe/src/lib/stellar/contract.ts index e4753d5..967a662 100644 --- a/fe/src/lib/stellar/contract.ts +++ b/fe/src/lib/stellar/contract.ts @@ -9,7 +9,7 @@ import { xdr, } from "@stellar/stellar-sdk"; import { sourceAccount } from "./account"; -import { ADVANCE_CONTRACT_ID as CONTRACT_ID, NETWORK_PASSPHRASE, RPC_URL } from "./network"; +import { ADVANCE_CONTRACT_ID as CONTRACT_ID, CONTRACT_TAKES_SOURCE, NETWORK_PASSPHRASE, RPC_URL } from "./network"; import { SubmitError, submitSigned, waitFor } from "./submit"; /** @@ -164,6 +164,16 @@ async function write( const str = (v: string) => nativeToScVal(v, { type: "string" }); const bytes32 = (hex: string) => xdr.ScVal.scvBytes(Buffer.from(hex, "hex")); +/** The contract's `Source` enum (#94): a unit variant is a vector holding its name. */ +export function sourceArg(source: "admob" | undefined): xdr.ScVal { + return xdr.ScVal.scvVec([xdr.ScVal.scvSymbol(source === "admob" ? "AdMob" : "AdSense")]); +} + +/** `source` in front of `args` when the contract takes it (`CONTRACT_TAKES_SOURCE`). */ +export function withSource(source: "admob" | undefined, args: xdr.ScVal[], takesSource = CONTRACT_TAKES_SOURCE): xdr.ScVal[] { + return takesSource ? [sourceArg(source), ...args] : args; +} + // ---- Reads ---- /** The advance this attested revenue would size to, in stroops. The figure 2b shows (#20). */ @@ -223,8 +233,10 @@ export async function nullifierFor( pubId: string, windowStart: string, windowEnd: string, + revenueSource?: "admob", ): Promise { - const raw = await read(source, "nullifier_for", [str(pubId), str(windowStart), str(windowEnd)]); + const args = withSource(revenueSource, [str(pubId), str(windowStart), str(windowEnd)]); + const raw = await read(source, "nullifier_for", args); return Buffer.from(raw).toString("hex"); } @@ -241,20 +253,44 @@ 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; }; -function advanceArgs(borrower: string, req: AdvanceRequest): xdr.ScVal[] { - return [ - new Address(borrower).toScVal(), - str(req.revenueUsd), - str(req.pubId), - str(req.windowStart), - str(req.windowEnd), - nativeToScVal(req.timestampS, { type: "u64" }), - nativeToScVal(req.epoch, { type: "u64" }), - xdr.ScVal.scvBytes(Buffer.from(req.signature, "hex")), - nativeToScVal(req.recoveryId, { type: "u32" }), - ]; +/** + * 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") return req.revenueUsd; + // Without micros, the exact decimal cut to cents: `quote` refuses a third decimal place. + if (!req.revenueMicros || !/^\d+$/.test(req.revenueMicros)) return req.revenueUsd.replace(/^(\d+\.\d{2})\d+$/, "$1"); + const cents = BigInt(req.revenueMicros) / 10_000n; + return `${cents / 100n}.${(cents % 100n).toString().padStart(2, "0")}`; +} + +export function advanceArgs(borrower: string, req: AdvanceRequest, takesSource = CONTRACT_TAKES_SOURCE): xdr.ScVal[] { + return withSource( + req.source, + [ + new Address(borrower).toScVal(), + // The figure the attestor signed: for AdMob the micros string, which #94 reads as micros because the + // source says so. The contract before #94 has no AdMob template and refuses an AdMob proof. + str(req.source === "admob" && req.revenueMicros ? req.revenueMicros : req.revenueUsd), + str(req.pubId), + str(req.windowStart), + str(req.windowEnd), + nativeToScVal(req.timestampS, { type: "u64" }), + nativeToScVal(req.epoch, { type: "u64" }), + xdr.ScVal.scvBytes(Buffer.from(req.signature, "hex")), + nativeToScVal(req.recoveryId, { type: "u32" }), + ], + takesSource, + ); } /** diff --git a/fe/src/lib/stellar/network.ts b/fe/src/lib/stellar/network.ts index 0560a63..6ce4cd0 100644 --- a/fe/src/lib/stellar/network.ts +++ b/fe/src/lib/stellar/network.ts @@ -22,6 +22,13 @@ export const USDC = (() => { /** The advance contract (`docs/deployments.md`). */ export const ADVANCE_CONTRACT_ID = process.env.NEXT_PUBLIC_ADVANCE_CONTRACT_ID ?? ""; +/** + * `"1"` once the deployed contract runs #94, whose `request_advance` and `nullifier_for` take the revenue + * source as their first argument. Set it when that upgrade executes, not before: the contract before it + * refuses the extra argument, and the one after refuses its absence. + */ +export const CONTRACT_TAKES_SOURCE = process.env.NEXT_PUBLIC_CONTRACT_TAKES_SOURCE === "1"; + const EXPLORER = "https://stellar.expert/explorer/testnet"; /** stellar.expert, the "View on Stellar Expert" link in the wallet menu. */ diff --git a/fe/src/modules/advance/Advance.tsx b/fe/src/modules/advance/Advance.tsx index 1994966..2896439 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, @@ -57,14 +66,15 @@ const quoteKey = (address: string, revenueUsd: string) => ["quote", address, rev const sizingKey = (address: string) => ["sizing", address] as const; /** - * "Reading your revenue". The words describe the relay (#17): about a minute, more behind a queue, and - * the job id is kept for the tab, so other pages are safe and a closed tab loses it (lib/reclaim/relay.ts). - * The mock (no relay) does not resume after leaving, which is acceptable for a build without proofs. + * "Reading your AdSense revenue", or AdMob's (#97). The words describe the relay (#17): about a minute, + * more behind a queue, and the job id is kept for the tab, so other pages are safe and a closed tab loses + * it (lib/reclaim/relay.ts). The mock (no relay) does not resume after leaving, which is acceptable for a + * build without proofs. */ -function ReadingRevenue() { +function ReadingRevenue({ source }: { source: RevenueSource }) { return ( ); @@ -85,6 +95,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. @@ -107,8 +119,9 @@ export function Advance() { useEffect(() => { if (!address) return; const pending = loadPending(address); + const kept = proofRunning(address); if (pending) void pickUp(pending); - else if (proofRunning(address)) void prove(); + else if (kept) void prove(kept); // `pickUp` and `prove` only read refs and setters; they run per mount and per wallet. // eslint-disable-next-line react-hooks/exhaustive-deps }, [address]); @@ -122,8 +135,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,13 +151,16 @@ 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; const nullifier = useQuery({ - queryKey: ["nullifier", address, received?.req.pubId, received?.req.windowStart, received?.req.windowEnd], - queryFn: () => nullifierFor(address as string, received!.req.pubId, received!.req.windowStart, received!.req.windowEnd), + queryKey: ["nullifier", address, received?.req.source, received?.req.pubId, received?.req.windowStart, received?.req.windowEnd], + queryFn: () => { + const r = received!.req; + return nullifierFor(address as string, r.pubId, r.windowStart, r.windowEnd, r.source); + }, enabled: !!address && !!received, staleTime: Infinity, }); @@ -170,7 +186,8 @@ export function Advance() { if (pending) return void pickUp(pending); // Likewise a proof the relay may still be making (a poll that failed kept its id): wait on it, so // "Reading your revenue" on the start is always backed by a running session. - if (proofRunning(me)) return void prove(); + const kept = proofRunning(me); + if (kept) return void prove(kept); setFlow({ at: "start" }); } @@ -179,11 +196,16 @@ export function Advance() { setFlow({ at: "offer", req: r }); } - async function prove() { + /** + * Prove `src`, the choice on 2a unless a kept job names its own. That becomes the choice, so Prove + * again and Back after a resumed job stay on its source. + */ + async function prove(src: RevenueSource = source) { leave(); + setSource(src); const id = attempt.current; setFlow({ at: "proving", stage: "waiting" }); - const s = proveRevenue(me, (stage) => { + const s = proveRevenue(me, src, (stage) => { if (id === attempt.current) setFlow({ at: "proving", stage }); }); session.current = s; @@ -207,8 +229,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 +242,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" }); } } @@ -399,11 +421,12 @@ export function Advance() { // A transaction left waiting from an earlier visit is picked up by the effect above, after this // first render. Show it as sending from the start, so 2a and its "Prove my revenue" never flash. // Likewise a proof the relay is still making for this wallet: the effect waits on it. - if (proofRunning(me)) { + const kept = proofRunning(me); + if (kept) { return ( - + ); @@ -426,7 +449,9 @@ export function Advance() { walletName={wallet} terms={terms.isPending ? "loading" : terms.data} usdc={usdc.isError ? "error" : usdc.data} - onProve={prove} + source={source} + onSource={setSource} + onProve={() => void prove()} /> ); @@ -439,12 +464,12 @@ export function Advance() { {flow.at === "checking" ? ( ) : flow.stage === "waiting" ? ( session.current?.reopen()}> Open the window again @@ -452,7 +477,7 @@ export function Advance() { } /> ) : ( - + )} @@ -463,12 +488,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 ? ( onFailureAction(action, offerFailure, flow.req, "prove")} /> @@ -556,6 +583,7 @@ export function Advance() { beforeOffer={flow.during === "prove"} allowing={allowing} terms={terms.data} + sourceName={SOURCE_NAME[flow.req?.source ?? "adsense"]} onAction={(action) => onFailureAction(action, flow.failure, flow.req, flow.during)} /> diff --git a/fe/src/modules/advance/components/FailurePanel.tsx b/fe/src/modules/advance/components/FailurePanel.tsx index aeabd54..f5e0cec 100644 --- a/fe/src/modules/advance/components/FailurePanel.tsx +++ b/fe/src/modules/advance/components/FailurePanel.tsx @@ -33,9 +33,12 @@ export function FailurePanel({ beforeOffer, allowing, terms, + sourceName, onAction, }: { failure: AdvanceFailure; + /** Where the proof came from, `AdSense` or `AdMob`, for the contract's refusals that name it (#97). */ + sourceName?: string; /** The contract's rate and minimum, from `sizing()`, for "not enough revenue". */ terms?: Sizing; walletName: string; @@ -66,7 +69,7 @@ export function FailurePanel({ let copy; if ("code" in failure) { - copy = contractFailureCopy(failure.code); + copy = contractFailureCopy(failure.code, sourceName); switch (failure.code) { case 11: case 14: @@ -132,6 +135,8 @@ export function FailurePanel({ // The relay's failures (#17). Not on the board yet; "Prove again" with "Back", as its pairs are. case "googleSignIn": case "noAdsense": + case "googleSignInAdmob": + case "noAdmob": case "relayFailed": case "relayBusy": case "proofRunning": diff --git a/fe/src/modules/advance/components/ProveRevenue.tsx b/fe/src/modules/advance/components/ProveRevenue.tsx index 5dce400..5632022 100644 --- a/fe/src/modules/advance/components/ProveRevenue.tsx +++ b/fe/src/modules/advance/components/ProveRevenue.tsx @@ -2,14 +2,17 @@ import { Check, CircleAlert, EyeOff } from "lucide-react"; import type { ReactNode } from "react"; import { IlloProvingRevenue } from "@/components/illustrations/ProvingRevenue"; import { Button } from "@/components/ui/Button"; +import { cn } from "@/lib/cn"; import { SkeletonBlock } from "@/components/ui/Skeleton"; +import { SOURCE_NAME, type RevenueSource } from "@/lib/reclaim"; import type { Sizing } from "@/lib/stellar/contract"; import { shareWords, usdcWords } from "../cap"; import type { UsdcStatus } from "@/lib/stellar/trustline"; /** - * 2a Prove revenue. What will be read (AdSense revenue for the last three months, nothing else), what - * will not, and the button that opens the Reclaim session. From a tablet up it adds the two lists and + * 2a Prove revenue. Where the revenue comes from (AdSense or AdMob, #97), what will be read (that + * revenue for the last three months, nothing else), what will not, and the button that opens Google's + * sign-in. From a tablet up it adds the two lists and * the wallet card; a phone keeps the card, the button and the rule. * * Section 08: on a tablet the side cards sit in a row under the Prove card; from 1024 they make the side @@ -20,6 +23,8 @@ export function ProveRevenue({ walletName, usdc, terms, + source, + onSource, onProve, }: { walletName: string; @@ -30,8 +35,12 @@ export function ProveRevenue({ terms?: Sizing | "loading"; /** Read from the ledger. `undefined` while loading, `"error"` when the read failed. */ usdc: UsdcStatus | "error" | undefined; + /** The source the press will prove. */ + source: RevenueSource; + onSource: (source: RevenueSource) => void; onProve: () => void; }) { + const name = SOURCE_NAME[source]; return (
@@ -41,8 +50,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 +60,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 + {/* Side by side once each tile keeps "AdSense" beside its radio (about 19rem of card); stacked + on the narrowest phones (section 08). The details are one word, so neither tile wraps. */} +
+ {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", diff --git a/fe/tests/e2e/advance.spec.ts b/fe/tests/e2e/advance.spec.ts index 8a014a4..bfe465d 100644 --- a/fe/tests/e2e/advance.spec.ts +++ b/fe/tests/e2e/advance.spec.ts @@ -57,7 +57,7 @@ test("prove, see the offer with its derivation, accept, and receive the USDC", a // The Reclaim session, then the check on Stellar await expect(heading(page, "Sign in with Google in the new window")).toBeVisible(); await expect(page.getByRole("button", { name: "Open the window again" })).toBeVisible(); - await expect(heading(page, "Reading your revenue")).toBeVisible(); + await expect(heading(page, "Reading your AdSense revenue")).toBeVisible(); await expect(heading(page, "Checking your proof")).toBeVisible(); // 2b: the contract's figure and how it was reached diff --git a/fe/tests/e2e/relay.spec.ts b/fe/tests/e2e/relay.spec.ts index b361427..04872d4 100644 --- a/fe/tests/e2e/relay.spec.ts +++ b/fe/tests/e2e/relay.spec.ts @@ -1,7 +1,7 @@ import { expect, test, type Page } from "@playwright/test"; import { E2E_ADDRESS } from "../../src/lib/stellar/wallet-e2e"; import { frameLedger, mockApi } from "./api"; -import { mockRpc } from "./rpc"; +import { mockRpc, type Chain } from "./rpc"; // #17: proving through the relay, on the build whose NEXT_PUBLIC_RELAY_URL and Google client id are set // (the relay-* projects in playwright.config.ts). Google's sign-in is a stub on `window.google`, which @@ -15,7 +15,7 @@ test.afterEach(async ({ page }) => { /** What Google's popup does when it opens: hand back a token, close, be blocked, or stay open. */ type Popup = "ok" | "closed" | "blocked" | "open"; -type Gis = { mode: Popup; opened: number }; +type Gis = { mode: Popup; opened: number; scopes: string[] }; declare global { interface Window { __gis: Gis; @@ -25,7 +25,7 @@ declare global { /** A stand-in for Google Identity Services' token client, counting the popups it opens. */ async function stubGoogle(page: Page, mode: Popup) { await page.addInitScript((m: Popup) => { - window.__gis = { mode: m, opened: 0 }; + window.__gis = { mode: m, opened: 0, scopes: [] }; type Config = { scope: string; callback: (r: object) => void; error_callback?: (e: object) => void }; window.google = { accounts: { @@ -33,6 +33,7 @@ async function stubGoogle(page: Page, mode: Popup) { initTokenClient: (c: Config) => ({ requestAccessToken: () => { window.__gis.opened++; + window.__gis.scopes.push(c.scope); const now = window.__gis.mode; setTimeout(() => { if (now === "ok") c.callback({ access_token: "ya29.e2e", scope: c.scope }); @@ -67,7 +68,7 @@ type Relay = { post: { status: number; body: object }; jobs: Record; hold?: boolean; - posts: { borrower: string; accessToken: string }[]; + posts: { borrower: string; accessToken: string; source?: string }[]; }; function relayFor(jobs: Relay["jobs"] = { j1: [{ id: "j1", stage: "proving" }, done("j1")] }): Relay { @@ -96,16 +97,18 @@ async function mockRelay(page: Page, relay: Relay) { } /** `popup` null leaves `window.google` unset, so the app loads Google's script itself (routed by the test). */ -async function connect(page: Page, relay: Relay, popup: Popup | null) { +async function connect(page: Page, relay: Relay, popup: Popup | null): Promise { if (popup) await stubGoogle(page, popup); await mockRelay(page, relay); - await mockRpc(page, { account: true, trustline: true }); + const chain: Chain = { account: true, trustline: true }; + await mockRpc(page, chain); await mockApi(page, frameLedger()); await page.goto("/start"); await page.getByRole("button", { name: "Get started" }).click(); await page.getByRole("button", { name: "Connect wallet" }).click(); await page.getByRole("dialog", { name: "Connect wallet" }).getByRole("button").first().click(); await expect(page).toHaveURL(/\/advance$/); + return chain; } const heading = (page: Page, name: string) => page.getByRole("heading", { name, exact: true }); @@ -114,13 +117,15 @@ const proveAgain = (page: Page) => page.getByRole("button", { name: "Prove again test("signs in with Google, the relay proves, and the offer follows", async ({ page }) => { const relay = relayFor(); - await connect(page, relay, "ok"); + const chain = await connect(page, relay, "ok"); await prove(page); await expect(heading(page, "Sign in with Google in the new window")).toBeVisible(); - await expect(heading(page, "Reading your revenue")).toBeVisible(); + await expect(heading(page, "Reading your AdSense revenue")).toBeVisible(); await expect(page.getByText("This takes about a minute, longer when others are proving too.", { exact: false })).toBeVisible(); await expect(page.getByRole("button", { name: "Accept 90.00 USDC" })).toBeVisible(); expect(relay.posts).toEqual([{ borrower: E2E_ADDRESS, accessToken: "ya29.e2e" }]); + // This build runs as against #94's contract (playwright.config.ts): the check led with the source. + expect(chain.sourced).toContainEqual({ fn: "request_advance", source: "AdSense" }); expect(await opened(page)).toBe(1); }); @@ -173,7 +178,7 @@ test("leaving while the relay proves and coming back waits on the same job, with relay.hold = true; await connect(page, relay, "ok"); await prove(page); - await expect(heading(page, "Reading your revenue")).toBeVisible(); + await expect(heading(page, "Reading your AdSense revenue")).toBeVisible(); // The top nav on desktop, the tab bar on a phone: whichever is shown. await page.getByRole("link", { name: "History", exact: true }).filter({ visible: true }).click(); await expect(page).toHaveURL(/\/history$/); @@ -248,7 +253,7 @@ test("coming back with a proof still running shows it at once, never 2a's button relay.hold = true; await connect(page, relay, "ok"); await prove(page); - await expect(heading(page, "Reading your revenue")).toBeVisible(); + await expect(heading(page, "Reading your AdSense revenue")).toBeVisible(); await page.getByRole("link", { name: "History", exact: true }).filter({ visible: true }).click(); await expect(page).toHaveURL(/\/history$/); // Watch every change to the page from here on: 2a's button must never be put on it. @@ -260,7 +265,7 @@ test("coming back with a proof still running shows it at once, never 2a's button }).observe(document.body, { childList: true, subtree: true }); }); await page.getByRole("link", { name: "Advance", exact: true }).filter({ visible: true }).click(); - await expect(heading(page, "Reading your revenue")).toBeVisible(); + await expect(heading(page, "Reading your AdSense revenue")).toBeVisible(); expect(await page.evaluate(() => (window as unknown as { __sawProve: boolean }).__sawProve)).toBe(false); }); @@ -289,3 +294,81 @@ test("Back after a kept job the relay no longer has returns to 2a", async ({ pag await expect(page.getByRole("button", { name: "Prove my revenue" })).toBeVisible(); expect(await opened(page)).toBe(0); }); + +// #97: AdMob, chosen on 2a. The relay answers it as docs/api.md says: the signed micros beside the exact +// decimal, and `source: "admob"` on the request. +const ADMOB_SCOPE = "https://www.googleapis.com/auth/admob.readonly"; + +function doneAdmob(id: string) { + const d = done(id); + return { ...d, request: { ...d.request, revenueUsd: "360.004567", source: "admob", revenueMicros: "360004567" } }; +} + +const chooseAdmob = (page: Page) => page.getByRole("radio", { name: /AdMob/ }).check(); + +test("AdMob, chosen on 2a, asks Google for AdMob only, and the offer names it", async ({ page }) => { + const relay = relayFor({ j1: [{ id: "j1", stage: "proving" }, doneAdmob("j1")] }); + const chain = await connect(page, relay, "ok"); + const group = page.getByRole("group", { name: "Where you earn" }); + await expect(group.getByRole("radio", { name: /AdSense/ })).toBeChecked(); + await chooseAdmob(page); + // The highlighted tile is the chosen one, never the other. Polled: the colours ease over 150 ms. + const fill = (name: RegExp) => group.locator("label").filter({ hasText: name }).evaluate((l) => getComputedStyle(l).backgroundColor); + const BRAND_SUBTLE = "rgb(255, 243, 234)"; + await expect.poll(() => fill(/AdMob/)).toBe(BRAND_SUBTLE); + await expect.poll(() => fill(/AdSense/)).not.toBe(BRAND_SUBTLE); + await expect(page.getByText("We read your AdMob revenue for the last three months", { exact: false })).toBeVisible(); + await prove(page); + await expect(page.getByText("Pick the Google account that owns your AdMob, and allow Forepay to see your AdMob reports.", { exact: false })).toBeVisible(); + // Sized from the micros truncated to cents: $360.00, so 90 USDC at 25%. + await expect(page.getByRole("button", { name: "Accept 90.00 USDC" })).toBeVisible(); + await expect(page.getByText("you earned on AdMob from", { exact: false })).toBeVisible(); + await expect(page.getByText("$360.00", { exact: true }).first()).toBeVisible(); + expect(relay.posts).toEqual([{ borrower: E2E_ADDRESS, accessToken: "ya29.e2e", source: "admob" }]); + expect(await page.evaluate(() => window.__gis.scopes)).toEqual([ADMOB_SCOPE]); + // Accepted: 2d reads the advance back under its AdMob nullifier, sized from the micros like the offer. + await page.getByRole("button", { name: "Accept 90.00 USDC" }).click(); + await expect(heading(page, "Advance received")).toBeVisible(); + await expect(page.getByText("90.00 USDC", { exact: true })).toBeVisible(); + expect(chain.sourced).toContainEqual({ fn: "request_advance", source: "AdMob" }); + expect(chain.sourced).toContainEqual({ fn: "nullifier_for", source: "AdMob" }); + expect(chain.sourced?.some((c) => c.source !== "AdMob")).toBe(false); +}); + +test("a Google account with no AdMob is named as AdMob, and Prove again stays on AdMob", async ({ page }) => { + const relay = relayFor({ j1: [{ id: "j1", stage: "failed", error: { code: "account", message: "no AdMob account" } }] }); + await connect(page, relay, "ok"); + await chooseAdmob(page); + await prove(page); + await expect(heading(page, "We could not use your AdMob account")).toBeVisible(); + relay.post = { status: 202, body: { id: "j2", stage: "queued" } }; + relay.jobs.j2 = [doneAdmob("j2")]; + await proveAgain(page); + await expect(page.getByRole("button", { name: "Accept 90.00 USDC" })).toBeVisible(); + expect(relay.posts.map((p) => p.source)).toEqual(["admob", "admob"]); +}); + +test("an AdMob proof resumed after leaving stays AdMob: its reading, its failure, Prove again and Back", async ({ page }) => { + const relay = relayFor({ j1: [{ id: "j1", stage: "failed", error: { code: "account", message: "no AdMob account" } }] }); + relay.hold = true; + await connect(page, relay, "ok"); + await chooseAdmob(page); + await prove(page); + await expect(heading(page, "Reading your AdMob revenue")).toBeVisible(); + await page.getByRole("link", { name: "History", exact: true }).filter({ visible: true }).click(); + await expect(page).toHaveURL(/\/history$/); + await page.getByRole("link", { name: "Advance", exact: true }).filter({ visible: true }).click(); + // Back on a fresh mount, whose choice would start as AdSense: the kept job names AdMob. + await expect(heading(page, "Reading your AdMob revenue")).toBeVisible(); + relay.hold = false; + await expect(heading(page, "We could not use your AdMob account")).toBeVisible(); + relay.post = { status: 202, body: { id: "j2", stage: "queued" } }; + relay.jobs.j2 = [{ id: "j2", stage: "failed", error: { code: "account", message: "no AdMob account" } }]; + await proveAgain(page); + await expect.poll(() => relay.posts.length).toBe(2); + await expect(heading(page, "We could not use your AdMob account")).toBeVisible(); + expect(relay.posts.map((p) => p.source)).toEqual(["admob", "admob"]); + expect(await page.evaluate(() => window.__gis.scopes)).toEqual([ADMOB_SCOPE, ADMOB_SCOPE]); + await page.getByRole("button", { name: "Back" }).click(); + await expect(page.getByRole("radio", { name: /AdMob/ })).toBeChecked(); +}); diff --git a/fe/tests/e2e/rpc.ts b/fe/tests/e2e/rpc.ts index 2eb0d7b..042538b 100644 --- a/fe/tests/e2e/rpc.ts +++ b/fe/tests/e2e/rpc.ts @@ -35,6 +35,11 @@ export type Chain = { send?: "ok" | "refused" | "failed"; /** How the advance contract answers (#20). Leave it out and it accepts every proof. */ advance?: AdvanceChain; + /** + * Every `request_advance` and `nullifier_for`, simulated or sent, with the revenue source it led with + * (`"AdSense"`, `"AdMob"`), or null when it had none, as before #94 (NEXT_PUBLIC_CONTRACT_TAKES_SOURCE). + */ + sourced?: { fn: string; source: string | null }[]; /** The USDC the wallet holds, in stroops, once it has a trustline. Defaults to none (#21). */ usdc?: bigint; /** @@ -154,6 +159,13 @@ function size(revenueUsd: string): bigint { return stroops > CAP_STROOPS ? CAP_STROOPS : stroops; } +/** The figure a `request_advance` signed, as dollars: #94's AdMob takes micros, truncated to cents. */ +function signedUsd(revenue: string, revenueSource: string | null): string { + if (revenueSource !== "AdMob") return revenue; + const cents = BigInt(revenue) / 10_000n; + return `${cents / 100n}.${(cents % 100n).toString().padStart(2, "0")}`; +} + function i128(v: bigint) { return nativeToScVal(v, { type: "i128" }); } @@ -174,14 +186,26 @@ function storedAdvance(borrower: string, revenueUsd: string) { ]); } -/** The contract call inside a transaction, or null for a classic one (changeTrust). */ -function contractCall(envelope: string): { fn: string; args: xdr.ScVal[]; source: string } | null { +/** The contract's `Source` (#94) when `arg` is one: a vector holding just the variant's name. */ +function revenueSource(arg: xdr.ScVal | undefined): string | null { + if (arg?.switch() !== xdr.ScValType.scvVec()) return null; + const items = arg.vec() ?? []; + return items.length === 1 && items[0].switch() === xdr.ScValType.scvSymbol() ? items[0].sym().toString() : null; +} + +/** + * The contract call inside a transaction, or null for a classic one (changeTrust). A leading revenue + * source (#94) is taken off `args` and given as `revenueSource`, so the arguments after it keep their places. + */ +function contractCall(envelope: string): { fn: string; args: xdr.ScVal[]; source: string; revenueSource: string | null } | null { const tx = TransactionBuilder.fromXDR(envelope, Networks.TESTNET); if (tx instanceof FeeBumpTransaction) return null; const op = tx.operations[0] as Operation.InvokeHostFunction; if (op.type !== "invokeHostFunction") return null; const call = op.func.invokeContract(); - return { fn: call.functionName().toString(), args: call.args(), source: tx.source }; + const args = call.args(); + const revenue = revenueSource(args[0]); + return { fn: call.functionName().toString(), args: revenue ? args.slice(1) : args, source: tx.source, revenueSource: revenue }; } function contractError(code: number) { @@ -267,6 +291,9 @@ export async function mockRpc(page: Page, chain: Chain) { const call = contractCall(body.params.transaction as string); const adv = chain.advance ?? {}; if (!call) return route.fulfill({ status: 400, body: "not a contract call" }); + if (call.fn === "request_advance" || call.fn === "nullifier_for") { + (chain.sourced ??= []).push({ fn: call.fn, source: call.revenueSource }); + } if (!ADVANCE_CALLS.has(call.fn)) { if (!chain.contract) return route.fulfill({ status: 400, body: `unexpected contract call ${call.fn}` }); if (chain.contract.refuse !== undefined) return reply(contractError(chain.contract.refuse)); @@ -279,7 +306,7 @@ export async function mockRpc(page: Page, chain: Chain) { } case "request_advance": { checks += 1; - const revenueUsd = scValToNative(call.args[1]) as string; + const revenueUsd = signedUsd(scValToNative(call.args[1]) as string, call.revenueSource); const stroops = size(revenueUsd); if (checks > 1 && adv.acceptDelayMs) await new Promise((r) => setTimeout(r, adv.acceptDelayMs)); if (stroops < MIN_STROOPS) return reply(contractError(31)); @@ -330,7 +357,7 @@ export async function mockRpc(page: Page, chain: Chain) { return reply({ status: "ERROR", hash: adv.hash, latestLedger: 100, latestLedgerCloseTime: "0" }); } if (adv.send !== "failed" && adv.send !== "pending") { - sentAdvance = { revenueUsd: scValToNative(call.args[1]) as string, source: call.source }; + sentAdvance = { revenueUsd: signedUsd(scValToNative(call.args[1]) as string, call.revenueSource), source: call.source }; } if (adv.loseSendAnswer) { adv.loseSendAnswer = false;