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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions fe/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,16 @@ NEXT_PUBLIC_USDC_ASSET=
# The backend API from #16. Its /config must report the same addresses as above.
NEXT_PUBLIC_API_URL=

# The proof relay from #17. While empty, proving revenue runs on a mock (src/lib/reclaim/mock.ts) whose
# proofs the real contract refuses. Only the e2e RPC stub accepts them.
# The proof relay from #17 (the same server as the API; see docs/api.md). While empty, proving revenue runs
# on a mock (src/lib/reclaim/mock.ts) whose proofs the real contract refuses. Only the e2e RPC stub accepts them.
NEXT_PUBLIC_RELAY_URL=
# Google OAuth client id (type "Web application") for the AdSense sign-in popup. Its authorized JavaScript
# origins must list this front end's origins. Public by design; the client secret is never used here.
NEXT_PUBLIC_GOOGLE_CLIENT_ID=

# WalletConnect, for mobile wallets. From the Reown dashboard.
NEXT_PUBLIC_WALLET_CONNECT_PROJECT_ID=

# Set to 1 only for Playwright runs: swaps the real wallet for a test wallet.
# Set to 1 only for Playwright runs: swaps the real wallet for a test wallet, and shortens the
# Reclaim mock's delays and the wait between polls of a relay job.
NEXT_PUBLIC_E2E=
4 changes: 2 additions & 2 deletions fe/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,8 +113,8 @@ Deliberately left out:
- **Animation libraries.** CSS transitions cover what the design needs (§7).
- **vaul.** Mobile sheets start as a Base UI dialog styled as a sheet. Add vaul only if swipe to
dismiss turns out to matter, after checking it is still maintained.
- **A Reclaim browser SDK, for now.** Which one depends on how the #17 relay is built. Ask
@Lin1er before installing anything.
- **A Reclaim browser SDK.** The #17 relay makes the proof with zkFetch; the browser only signs in
with Google Identity Services, loaded as Google's script, not a package (`lib/reclaim/relay.ts`).

## 4. State

Expand Down
25 changes: 17 additions & 8 deletions fe/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,15 @@ pnpm test:e2e # Playwright, tests/e2e
It uses Playwright's own Chromium. Google Chrome works too (`PW_CHANNEL=chrome`), but on a Mac with
a Chrome update pending, Chrome's updater can keep a finished run from exiting. It starts its own
`next dev` on port 3219 (or `PW_PORT`), built into `.next-e2e` (`NEXT_DIST_DIR`), so it runs
alongside your own `next dev`. Any other `NEXT_DIST_DIR` makes Next add its type folder to
`tsconfig.json`; do not commit that. It sets its own environment (`playwright.config.ts`): the test
wallet (`NEXT_PUBLIC_E2E=1`), a fake RPC URL and a fake #16 API URL whose answers each spec decides
(`tests/e2e/rpc.ts`, `tests/e2e/api.ts`), so a run never touches testnet or a real API and needs no
browser extension.
alongside your own `next dev`. A second one, on the port after it and built into `.next-e2e-relay`,
has the relay and the Google client id set, for `tests/e2e/relay.spec.ts`: there Google's sign-in is
a stub and the spec answers the relay. Every run starts both, which takes longer and needs both
ports free; `PW_RELAY=0` leaves the relay build and its specs out. Both folders' types are in
`tsconfig.json`; any other `NEXT_DIST_DIR` makes Next add its own, so do not commit that.

It sets its own environment (`playwright.config.ts`): the test wallet (`NEXT_PUBLIC_E2E=1`), a fake
RPC URL and a fake #16 API URL whose answers each spec decides (`tests/e2e/rpc.ts`,
`tests/e2e/api.ts`), so a run never touches testnet or a real API and needs no browser extension.

## Environment

Expand All @@ -60,10 +64,15 @@ browser. Never put a secret in one.
- **`NEXT_PUBLIC_WALLET_CONNECT_PROJECT_ID`** is only needed for mobile wallets. Without it,
desktop browser wallets still work.

## Proving revenue is mocked until #17
## 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
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.

The Reclaim session and the proof relay (#17) do not exist yet, so `src/lib/reclaim/` answers from a
mock while `NEXT_PUBLIC_RELAY_URL` is empty. It walks through the session (window open, reading) and
`src/lib/reclaim/` answers from a mock while `NEXT_PUBLIC_RELAY_URL` is empty. It walks through the session (window open, reading) and
returns fixed values. Everything after it, the offer from `quote`, the proof check, `request_advance`
and the receipt, is the real contract client. On testnet the contract refuses the mock's proof, so the
whole flow only completes in the e2e run, against the stubbed RPC.
Expand Down
69 changes: 51 additions & 18 deletions fe/playwright.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,35 +3,68 @@ import { defineConfig, devices } from "@playwright/test";
// End to end runs with the test wallet (NEXT_PUBLIC_E2E=1) and with every Stellar RPC call and #16 API
// call answered by the spec itself (tests/e2e/rpc.ts, tests/e2e/api.ts), so a run never touches testnet
// or a real API and never needs a browser extension.
// PW_PORT lets two worktrees run their e2e suites side by side.
// PW_PORT (and the port after it, for the relay build) lets two worktrees run their e2e suites side by side.
const PORT = Number(process.env.PW_PORT ?? 3219);
const RELAY_PORT = PORT + 1;
// PW_RELAY=0 leaves out the relay build and its specs, for a quicker run of the others.
const RELAY = process.env.PW_RELAY !== "0";
const RELAY_SPEC = /relay\.spec\.ts$/;

export default defineConfig({
testDir: "tests/e2e",
fullyParallel: true,
// Playwright's own Chromium (`npx playwright install chromium`, once). Google Chrome can hold a run
// open after it ends while an update is pending; PW_CHANNEL=chrome still uses it when wanted.
use: { baseURL: `http://localhost:${PORT}`, channel: process.env.PW_CHANNEL, trace: "retain-on-failure" },
projects: [
{ name: "desktop", use: { ...devices["Desktop Chrome"], viewport: { width: 1440, height: 960 } } },
{ name: "mobile", use: { ...devices["Pixel 7"], viewport: { width: 390, height: 844 } } },
],
webServer: {
command: `npx next dev --port ${PORT}`,
port: PORT,
/** One dev server. `proving` sets the Reclaim seam: the mock (no relay) or the relay. */
function server(port: number, distDir: string, proving: Record<string, string>) {
return {
command: `npx next dev --port ${port}`,
port,
// Never reuse whatever already listens on the port: it may be another app entirely.
reuseExistingServer: false,
timeout: 180_000,
env: {
NEXT_DIST_DIR: ".next-e2e",
NEXT_DIST_DIR: distDir,
NEXT_PUBLIC_E2E: "1",
// The Reclaim mock, whatever .env.local says.
NEXT_PUBLIC_RELAY_URL: "",
// The Reclaim mock or the stubbed relay, whatever .env.local says.
NEXT_PUBLIC_GOOGLE_CLIENT_ID: "",
...proving,
NEXT_PUBLIC_STELLAR_RPC_URL: "https://rpc.e2e.invalid",
NEXT_PUBLIC_API_URL: "https://api.e2e.invalid",
// Advance contract (dev), from docs/deployments.md. The stub answers for it; nothing is sent.
NEXT_PUBLIC_ADVANCE_CONTRACT_ID: "CA3YGQHU42EL2TAOG7NJ5DDT5FLKKQNDWIUFFU6KV7QJHCFGLAGYXLID",
NEXT_PUBLIC_USDC_ASSET: "USDC:GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5",
},
},
};
}

/**
* The real proving seam (#17), on a second build whose relay and Google client are set. The relay
* and Google's sign-in are answered by the spec (tests/e2e/relay.spec.ts).
*/
function relayProjects() {
const use = { baseURL: `http://localhost:${RELAY_PORT}` };
return [
{ name: "relay-desktop", testMatch: RELAY_SPEC, use: { ...devices["Desktop Chrome"], viewport: { width: 1440, height: 960 }, ...use } },
{ name: "relay-mobile", testMatch: RELAY_SPEC, use: { ...devices["Pixel 7"], viewport: { width: 390, height: 844 }, ...use } },
];
}

export default defineConfig({
testDir: "tests/e2e",
fullyParallel: true,
// Playwright's own Chromium (`npx playwright install chromium`, once). Google Chrome can hold a run
// open after it ends while an update is pending; PW_CHANNEL=chrome still uses it when wanted.
use: { baseURL: `http://localhost:${PORT}`, channel: process.env.PW_CHANNEL, trace: "retain-on-failure" },
projects: [
{ name: "desktop", testIgnore: RELAY_SPEC, use: { ...devices["Desktop Chrome"], viewport: { width: 1440, height: 960 } } },
{ name: "mobile", testIgnore: RELAY_SPEC, use: { ...devices["Pixel 7"], viewport: { width: 390, height: 844 } } },
...(RELAY ? relayProjects() : []),
],
webServer: [
server(PORT, ".next-e2e", { NEXT_PUBLIC_RELAY_URL: "" }),
...(RELAY
? [
server(RELAY_PORT, ".next-e2e-relay", {
NEXT_PUBLIC_RELAY_URL: "https://relay.e2e.invalid",
NEXT_PUBLIC_GOOGLE_CLIENT_ID: "e2e.apps.googleusercontent.com",
}),
]
: []),
],
});
16 changes: 16 additions & 0 deletions fe/src/lib/errors.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,15 @@ describe("proveFailureCopy", () => {
"walletWrongNetwork",
"walletNoAnswer",
"relayNotReady",
"googleSignIn",
"noAdsense",
"relayFailed",
"relayBusy",
"proofRunning",
"proofGone",
"relayUnreachable",
"googleUnavailable",
"popupBlocked",
];

it("keeps every failure inside the copy rules, and never says Something went wrong", () => {
Expand All @@ -134,6 +143,13 @@ 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) {
expect(proveFailureCopy(k).body).toMatch(/Nothing was charged/);
}
for (const k of ["relayBusy", "googleUnavailable", "popupBlocked"] as const) {
expect(proveFailureCopy(k).body).toMatch(/Nothing was read or charged/);
}
expect(proveFailureCopy("charged").body).not.toMatch(/Nothing was charged/);
expect(proveFailureCopy("unconfirmed").body).not.toMatch(/Nothing was charged/);
});
Expand Down
69 changes: 66 additions & 3 deletions fe/src/lib/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,16 @@ export function contractFailureCopy(code: number): FailureCopy {
* - `simulationFailed`: Stellar answered, but could not run the request, with no contract code to say why.
* - `notConfigured`: this build is missing an address it needs, so nothing reached the network.
* - `walletLocked`, `walletWrongNetwork`, `walletNoAnswer`: the wallet could not sign, for that reason.
* - `relayNotReady`: proofs are meant to come from the #17 relay, and its client is not built yet.
* - `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`).
* - `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.
* - `proofGone`: the relay no longer has the proof this tab was waiting on (it restarted, or an hour passed).
* - `relayUnreachable`: the relay did not answer. Not Stellar: nothing on chain was asked.
* - `googleUnavailable`: Google's sign-in did not load.
* - `popupBlocked`: the browser blocked Google's sign-in window. The creator closed nothing.
*/
export type ProveFailure =
| "cancelled"
Expand All @@ -225,13 +234,22 @@ export type ProveFailure =
| "walletLocked"
| "walletWrongNetwork"
| "walletNoAnswer"
| "relayNotReady";
| "relayNotReady"
| "googleSignIn"
| "noAdsense"
| "relayFailed"
| "relayBusy"
| "proofRunning"
| "proofGone"
| "relayUnreachable"
| "googleUnavailable"
| "popupBlocked";

export function proveFailureCopy(kind: ProveFailure, walletName = "Freighter"): FailureCopy {
switch (kind) {
case "cancelled":
return {
title: "You closed the AdSense window",
title: "You closed the Google window",
body: "Nothing was read or saved. Start again when you are ready.",
};
case "declined":
Expand Down Expand Up @@ -303,6 +321,51 @@ export function proveFailureCopy(kind: ProveFailure, walletName = "Freighter"):
title: "Proving revenue is not open yet",
body: "Forepay cannot read AdSense revenue yet. Try again later.",
};
case "googleSignIn":
return {
title: "Google did not let us read AdSense",
body: "Sign in again and allow Forepay to see your AdSense reports. Nothing was charged.",
};
case "noAdsense":
return {
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 "relayFailed":
return {
title: "We could not finish your proof",
body: "Nothing was charged. Try again in a few minutes.",
};
case "relayBusy":
return {
title: "Forepay is busy right now",
body: "Many creators are proving at once. Nothing was read or charged. Try again in a few minutes.",
};
case "proofRunning":
return {
title: "Your proof is already being made",
body: "A proof for this wallet started earlier, in a tab that no longer has it. Wait a few minutes for it to end, then prove again. Nothing was charged.",
};
case "proofGone":
return {
title: "Your earlier proof is gone",
body: "We no longer have the proof you started earlier. Prove your revenue again, it takes about a minute. Nothing was charged.",
};
case "relayUnreachable":
return {
title: "We could not reach Forepay",
body: "Nothing was charged. Check your connection, then try again.",
};
case "googleUnavailable":
return {
title: "Google sign-in did not load",
body: "Nothing was read or charged. Check your connection, then try again.",
};
case "popupBlocked":
return {
title: "Your browser blocked the Google window",
body: "Allow pop-ups for Forepay, then try again. Nothing was read or charged.",
};
}
}

Expand Down
3 changes: 2 additions & 1 deletion fe/src/lib/reclaim/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,9 @@ describe("proveRevenue", () => {
session.abandon();
});

it("says the relay is not ready rather than pretending, once a relay URL is set", async () => {
it("says the relay is not ready rather than pretending, when the Google client id is missing", async () => {
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);
});
Expand Down
34 changes: 28 additions & 6 deletions fe/src/lib/reclaim/index.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,42 @@
/**
* Proving AdSense revenue with Reclaim, and getting back the attested values `request_advance` takes
* Proving AdSense revenue, and getting back the attested values `request_advance` takes
* (ARCHITECTURE.md §2, `lib/reclaim/`). The seam between the app and the #17 relay.
*
* The Reclaim session and the relay do not exist yet (#17), and which Reclaim SDK runs in the browser
* depends on how the relay is built (ARCHITECTURE.md §3), so none is installed. Until
* NEXT_PUBLIC_RELAY_URL is set, a mock walks through the same stages with realistic delays and
* With NEXT_PUBLIC_RELAY_URL and NEXT_PUBLIC_GOOGLE_CLIENT_ID set, the creator signs in with Google's
* own popup and the relay makes the proof (`relay.ts`). No Reclaim SDK runs in the browser. While
* NEXT_PUBLIC_RELAY_URL is empty, a mock walks through the same stages with realistic delays and
* returns fixed values. Everything after this seam (quote, request_advance, signing, errors) is real.
*/
import { mockProveRevenue } from "./mock";
import { googleSignIn, preloadGoogleSignIn, relayProveRevenue, sessionJobs } from "./relay";
import { RelayNotReadyError, type ProveSession, type ProveStage } from "./session";

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

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

export function proveRevenue(borrower: string, onStage: (stage: ProveStage) => void): ProveSession {
if (!RELAY_URL) return mockProveRevenue(borrower, onStage);
return { result: Promise.reject(new RelayNotReadyError()), reopen: () => {}, abandon: () => {} };
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 });
}

/** 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;
}

/** Load Google's sign-in ahead of "Prove my revenue", so the popup opens inside the press. */
export function preloadSignIn(): void {
if (RELAY_URL && GOOGLE_CLIENT_ID) preloadGoogleSignIn();
}
Loading