feat(lepton): attribution package (RFB 6.01) + creator-dashboard
Adds @settlekit/attribution — reuse-detection, weighted provenance lineage,
and HMAC-signed proofs-of-citation — wired live into the rsshub-citation-toll
sidecar (POST /attribution/{detect,proof,verify}) and persisted via
PgLineageStore/PgProofStore over new lepton_lineage_edges + lepton_citation_proofs
tables.
Adds apps/creator-dashboard — a Next.js earnings view in the Statement
greenbar-ledger design system, driven by real domain logic (createSource +
computeRoyaltyDistribution + detectReuse, not mocks). Statement / Sources /
Payouts / Reuse & proofs (interactive) / Wallet. next build green.
Also bundles in-progress settlement hardening: settlement-core idempotency
concurrency, api env validation, bundles + contracts/worker tweaks.
Verified: 943 vitest tests, 27 Foundry tests, next build all green.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
parent
bcd51b5829
commit
71e89bdfd8
@ -30,6 +30,10 @@ Also done: **`services/sidecars/owncast-stream`** — per-second streaming settl
|
||||
|
||||
Three creator-monetization patterns now share one settlement spine: **per-citation** (RSSHub), **per-listen** (Navidrome), **per-second** (Owncast).
|
||||
|
||||
Also done (Phase 3 — creator products): **`apps/creator-dashboard`** — a Next.js earnings view in the Statement greenbar-ledger design system (gradient-free, tabular-mono, credit/debit semantics). It is NOT mocked: `lib/data.ts` drives the real domain logic — sources built with `createSource`, every paid access run through `computeRoyaltyDistribution` (so a creator earns their author share *plus* the recursive cut of everything that cites them), and the attribution panel runs `detectReuse` + issues a real signed proof. Pages: **Statement** (lifetime/settled/pending + recent royalty lines), **Sources** (authored vs cited, recursive cut), **Payouts** (settlement sweeps), **Reuse & proofs** (interactive `/api/detect` + worked proof-of-citation), **Wallet**. `next build` green (9 routes); swap `lib/data.ts` for the Pg stores to go live. Public (no auth gate) so it doubles as the demo link.
|
||||
|
||||
Also done (RFB 6.01): **`@settlekit/attribution`** — the reuse-detection / proof-of-citation layer the citation toll was designed around. A weighted provenance DAG (`LineageGraph` + `computeAttributionShares`, the citation split expressed as fractions any consumer can use), w-shingling reuse detection (`detectReuse`: does an agent's generated text get grounded in a known source?), and HMAC-signed, expiring, replay-protected proofs-of-citation (`issueCitationProof`/`verifyCitationProof`). Pure + fully tested (30 tests), persisted via `PgLineageStore`/`PgProofStore` over new `lepton_lineage_edges` + `lepton_citation_proofs` tables. Wired live into the **rsshub-citation-toll** sidecar: `POST /attribution/detect` quotes the toll owed for implicit reuse, `POST /attribution/proof` issues a presentable proof, `POST /attribution/verify` checks + consumes its nonce. This closes the loop from *explicit* fetch-tolls to *implicit* reuse-tolls at the agent boundary.
|
||||
|
||||
**Live-wiring seams done:** `settlementProviderFromEnv` (flip to Circle by `SETTLEMENT_PROVIDER=circle` + creds, no code change) is wired into every sidecar's `startSidecar`; the RSS sidecar has a `createFeedPoller` that fetches a live RSSHub JSON feed and ingests on an interval. Gateway settlement is wired via `configureSettlement` with a `GatewayTransferPort` (host supplies the signer).
|
||||
|
||||
## Phase 4 status (on-chain contracts — done, Foundry-tested)
|
||||
|
||||
@ -19,7 +19,7 @@
|
||||
"build": "tsc -b",
|
||||
"dev": "node --import tsx/esm src/server.ts",
|
||||
"start": "node dist/server.js",
|
||||
"typecheck": "tsc -b --noEmit",
|
||||
"typecheck": "tsc -b",
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
|
||||
@ -386,6 +386,54 @@ function loadFileDelivery(env: Env): FileDeliveryConfig {
|
||||
* Build {@link ApiConfig} from a process environment. Defaults to `process.env`
|
||||
* but accepts an explicit env map for tests.
|
||||
*/
|
||||
/**
|
||||
* Dev-only fallback secrets. They keep `pnpm dev` zero-config, but are public
|
||||
* (they live in this source file) so using them in production would let anyone
|
||||
* forge sessions, webhook signatures, and license tokens. {@link assertProductionReady}
|
||||
* rejects them when NODE_ENV=production.
|
||||
*/
|
||||
const DEV_DEFAULT_SECRETS = {
|
||||
LICENSE_TOKEN_SECRET: "settlekit-dev-license-secret",
|
||||
WEBHOOK_SIGNING_SECRET: "settlekit-dev-webhook-secret",
|
||||
AUTH_COOKIE_SECRET: "settlekit-dev-auth-cookie-secret",
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Fail closed in production: a misconfigured deploy must crash on boot with a
|
||||
* clear message rather than silently running on in-memory data (lost on every
|
||||
* restart) or with publicly-known signing secrets. Dev/test keep the
|
||||
* convenient fallbacks.
|
||||
*/
|
||||
function assertProductionReady(
|
||||
env: Env,
|
||||
cfg: {
|
||||
database: DatabaseConfig | null;
|
||||
licenseTokenSecret: string;
|
||||
webhookSigningSecret: string;
|
||||
authCookieSecret: string;
|
||||
},
|
||||
): void {
|
||||
if (env.NODE_ENV !== "production") return;
|
||||
const problems: string[] = [];
|
||||
if (cfg.database === null) {
|
||||
problems.push("DATABASE_URL must be set (in-memory stores lose all data on restart)");
|
||||
}
|
||||
if (cfg.licenseTokenSecret === DEV_DEFAULT_SECRETS.LICENSE_TOKEN_SECRET) {
|
||||
problems.push("LICENSE_TOKEN_SECRET must be set (the dev default is public and forgeable)");
|
||||
}
|
||||
if (cfg.webhookSigningSecret === DEV_DEFAULT_SECRETS.WEBHOOK_SIGNING_SECRET) {
|
||||
problems.push("WEBHOOK_SIGNING_SECRET must be set (the dev default is public and forgeable)");
|
||||
}
|
||||
if (cfg.authCookieSecret === DEV_DEFAULT_SECRETS.AUTH_COOKIE_SECRET) {
|
||||
problems.push("AUTH_COOKIE_SECRET must be set (the dev default is public and forgeable)");
|
||||
}
|
||||
if (problems.length > 0) {
|
||||
throw new Error(
|
||||
`Refusing to boot in production with insecure configuration:\n - ${problems.join("\n - ")}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export function loadConfig(env: Env = process.env): ApiConfig {
|
||||
const database = loadDatabase(env);
|
||||
const arc = loadArc(env);
|
||||
@ -399,11 +447,17 @@ export function loadConfig(env: Env = process.env): ApiConfig {
|
||||
const email = loadEmail(env);
|
||||
const s3 = loadS3(env);
|
||||
|
||||
const licenseTokenSecret = optionalString(env, "LICENSE_TOKEN_SECRET", DEV_DEFAULT_SECRETS.LICENSE_TOKEN_SECRET);
|
||||
const webhookSigningSecret = optionalString(env, "WEBHOOK_SIGNING_SECRET", DEV_DEFAULT_SECRETS.WEBHOOK_SIGNING_SECRET);
|
||||
const authCookieSecret = optionalString(env, "AUTH_COOKIE_SECRET", DEV_DEFAULT_SECRETS.AUTH_COOKIE_SECRET);
|
||||
|
||||
assertProductionReady(env, { database, licenseTokenSecret, webhookSigningSecret, authCookieSecret });
|
||||
|
||||
return {
|
||||
port: intInRange(env, "PORT", 8787, 1, 65_535),
|
||||
licenseTokenSecret: optionalString(env, "LICENSE_TOKEN_SECRET", "settlekit-dev-license-secret"),
|
||||
webhookSigningSecret: optionalString(env, "WEBHOOK_SIGNING_SECRET", "settlekit-dev-webhook-secret"),
|
||||
authCookieSecret: optionalString(env, "AUTH_COOKIE_SECRET", "settlekit-dev-auth-cookie-secret"),
|
||||
licenseTokenSecret,
|
||||
webhookSigningSecret,
|
||||
authCookieSecret,
|
||||
fileDelivery: loadFileDelivery(env),
|
||||
...(optionalRaw(env, "CCTP_IRIS_BASE_URL")
|
||||
? { cctpIrisBaseUrl: optionalRaw(env, "CCTP_IRIS_BASE_URL") as string }
|
||||
|
||||
@ -292,17 +292,12 @@ export async function createContext(): Promise<AppContext> {
|
||||
|
||||
const products = pick<EntityStore<Product>>(db, (d) => new PgProductStore(d), () => new InMemoryEntityStore<Product>());
|
||||
|
||||
// Bundle validation needs a synchronous product-existence check, but Postgres
|
||||
// lookups are async — so track known product ids in a set (primed at boot,
|
||||
// updated on save) and gate bundle creation against it.
|
||||
const knownProductIds = new Set<string>();
|
||||
for (const p of await products.list()) knownProductIds.add(p.id);
|
||||
const trackedProducts: EntityStore<Product> = {
|
||||
async save(p) { const r = await products.save(p); knownProductIds.add(p.id); return r; },
|
||||
findById: (id) => products.findById(id),
|
||||
list: (predicate) => products.list(predicate),
|
||||
async delete(id) { const ok = await products.delete(id); if (ok) knownProductIds.delete(id); return ok; },
|
||||
};
|
||||
// Bundle validation checks product existence against the store directly (async).
|
||||
// A previous process-local id cache went stale across instances under
|
||||
// horizontal scaling, spuriously rejecting bundles whose products were created
|
||||
// on another instance; querying the store is always consistent.
|
||||
const productExists = async (productId: string): Promise<boolean> =>
|
||||
(await products.findById(productId)) != null;
|
||||
|
||||
const entitlementRepo = pick<EntitlementRepository>(db, (d) => new PgEntitlementRepository(d), () => new InMemoryEntitlementRepository());
|
||||
const apiKeyStore = pick<ApiKeyStore>(db, (d) => new PgApiKeyStore(d), () => new InMemoryApiKeyStore());
|
||||
@ -398,7 +393,7 @@ export async function createContext(): Promise<AppContext> {
|
||||
entitlementRepo,
|
||||
entitlements: new EntitlementService(entitlementRepo),
|
||||
|
||||
products: trackedProducts,
|
||||
products,
|
||||
prices,
|
||||
customers: pick<EntityStore<Customer>>(db, (d) => new PgCustomerStore(d), () => new InMemoryEntityStore<Customer>()),
|
||||
deliveryRuns: pick<EntityStore<DeliveryRun>>(db, (d) => new PgDeliveryRunStore(d), () => new InMemoryEntityStore<DeliveryRun>()),
|
||||
@ -472,7 +467,7 @@ export async function createContext(): Promise<AppContext> {
|
||||
discordGrants,
|
||||
|
||||
saas: new SaasService({ plans: planStore, seats: seatStore }),
|
||||
bundles: new BundleService(bundleStore, (productId: string) => knownProductIds.has(productId)),
|
||||
bundles: new BundleService(bundleStore, productExists),
|
||||
bundleStore,
|
||||
agentServices: new AgentServiceService({
|
||||
services: agentServiceStore,
|
||||
|
||||
29
apps/api/test/env.test.ts
Normal file
29
apps/api/test/env.test.ts
Normal file
@ -0,0 +1,29 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { loadConfig } from "../src/config/env.js";
|
||||
|
||||
const prodSecrets = {
|
||||
DATABASE_URL: "postgres://user:pass@localhost:5432/settlekit",
|
||||
LICENSE_TOKEN_SECRET: "a-real-license-secret",
|
||||
WEBHOOK_SIGNING_SECRET: "a-real-webhook-secret",
|
||||
AUTH_COOKIE_SECRET: "a-real-auth-cookie-secret",
|
||||
};
|
||||
|
||||
describe("loadConfig production fail-closed guard", () => {
|
||||
it("boots with dev defaults when NODE_ENV is not production", () => {
|
||||
expect(() => loadConfig({})).not.toThrow();
|
||||
});
|
||||
|
||||
it("refuses to boot in production without DATABASE_URL", () => {
|
||||
expect(() => loadConfig({ NODE_ENV: "production" })).toThrow(/DATABASE_URL must be set/);
|
||||
});
|
||||
|
||||
it("refuses to boot in production with dev-default signing secrets", () => {
|
||||
expect(() =>
|
||||
loadConfig({ NODE_ENV: "production", DATABASE_URL: prodSecrets.DATABASE_URL }),
|
||||
).toThrow(/LICENSE_TOKEN_SECRET must be set/);
|
||||
});
|
||||
|
||||
it("boots in production once DB and real secrets are supplied", () => {
|
||||
expect(() => loadConfig({ NODE_ENV: "production", ...prodSecrets })).not.toThrow();
|
||||
});
|
||||
});
|
||||
@ -15,7 +15,7 @@
|
||||
"scripts": {
|
||||
"build": "tsc -b",
|
||||
"dev": "node --import tsx/esm src/index.ts",
|
||||
"typecheck": "tsc -b --noEmit",
|
||||
"typecheck": "tsc -b",
|
||||
"clean": "rm -rf dist"
|
||||
},
|
||||
"engines": {
|
||||
|
||||
1
apps/creator-dashboard/.gitignore
vendored
Normal file
1
apps/creator-dashboard/.gitignore
vendored
Normal file
@ -0,0 +1 @@
|
||||
.vercel
|
||||
12
apps/creator-dashboard/app/api/detect/route.ts
Normal file
12
apps/creator-dashboard/app/api/detect/route.ts
Normal file
@ -0,0 +1,12 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { detectGroundingForText } from "@/lib/data";
|
||||
|
||||
// Run reuse detection over the demo source corpus. The same call the
|
||||
// rsshub-citation-toll sidecar exposes at POST /attribution/detect.
|
||||
export async function POST(request: Request) {
|
||||
const body = (await request.json().catch(() => null)) as { text?: string } | null;
|
||||
if (body === null || typeof body.text !== "string") {
|
||||
return NextResponse.json({ error: "text required" }, { status: 400 });
|
||||
}
|
||||
return NextResponse.json({ data: detectGroundingForText(body.text) });
|
||||
}
|
||||
75
apps/creator-dashboard/app/attribution/page.tsx
Normal file
75
apps/creator-dashboard/app/attribution/page.tsx
Normal file
@ -0,0 +1,75 @@
|
||||
import { Card, PageHeader } from "@/components/ui";
|
||||
import { ReuseDetector } from "@/components/ReuseDetector";
|
||||
import { getCreatorContext } from "@/lib/data";
|
||||
import { formatUsdc } from "@/lib/format";
|
||||
|
||||
export default function AttributionPage() {
|
||||
const { attribution } = getCreatorContext();
|
||||
const { proof } = attribution;
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader
|
||||
title="Reuse & proofs"
|
||||
description="The citation toll charges deliberate fetches. Attribution closes the loop — it detects when an agent's output was grounded in your work and charges that implicit reuse (RFB 6.01)."
|
||||
/>
|
||||
|
||||
<Card title="Try it — detect grounding in your sources">
|
||||
<ReuseDetector />
|
||||
</Card>
|
||||
|
||||
<Card title="Worked example">
|
||||
<p className="muted" style={{ marginTop: 0 }}>
|
||||
An agent produced this answer:
|
||||
</p>
|
||||
<blockquote
|
||||
style={{
|
||||
margin: "0 0 16px",
|
||||
padding: "12px 14px",
|
||||
borderLeft: "3px solid var(--accent)",
|
||||
background: "var(--bg-elevated)",
|
||||
borderRadius: "var(--radius-sm)",
|
||||
}}
|
||||
>
|
||||
{attribution.answer}
|
||||
</blockquote>
|
||||
|
||||
<div className="detail-grid">
|
||||
<dt>Grounded in</dt>
|
||||
<dd>
|
||||
{attribution.matches.map((m) => (
|
||||
<span key={m.sourceId} className="badge badge-good" style={{ marginRight: 6 }}>
|
||||
{m.title} · {(m.score * 100).toFixed(0)}%
|
||||
</span>
|
||||
))}
|
||||
</dd>
|
||||
<dt>Toll owed</dt>
|
||||
<dd className="mono">{formatUsdc(attribution.quoteUsdc)}</dd>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
<Card title="Proof-of-citation">
|
||||
<p className="muted" style={{ marginTop: 0 }}>
|
||||
After settling, the agent receives a signed, expiring, replay-protected token it presents downstream.
|
||||
Anyone holding the secret can verify it without re-querying the chain.
|
||||
</p>
|
||||
<div className="detail-grid">
|
||||
<dt>Agent</dt>
|
||||
<dd className="mono">{proof.agent}</dd>
|
||||
<dt>Access</dt>
|
||||
<dd className="mono">{proof.accessId}</dd>
|
||||
<dt>Sources</dt>
|
||||
<dd className="mono">{proof.sourceIds.join(", ")}</dd>
|
||||
<dt>Amount</dt>
|
||||
<dd className="mono">{proof.amountUsdc ? formatUsdc(proof.amountUsdc) : "—"}</dd>
|
||||
<dt>Expires</dt>
|
||||
<dd className="mono">{proof.expiresAt ?? "never"}</dd>
|
||||
<dt>Signature</dt>
|
||||
<dd className="mono" style={{ wordBreak: "break-all", color: "var(--text-muted)" }}>
|
||||
{proof.signature}
|
||||
</dd>
|
||||
</div>
|
||||
</Card>
|
||||
</>
|
||||
);
|
||||
}
|
||||
754
apps/creator-dashboard/app/globals.css
Normal file
754
apps/creator-dashboard/app/globals.css
Normal file
@ -0,0 +1,754 @@
|
||||
:root {
|
||||
/* STATEMENT — greenbar ledger palette (see @settlekit/ui) */
|
||||
--bg: #ebede4;
|
||||
--bg-panel: #f3f4ec;
|
||||
--bg-elevated: #dde3d1;
|
||||
--border: #cdd3c5;
|
||||
--border-strong: #b4bca9;
|
||||
--text: #18211c;
|
||||
--text-muted: #45524b;
|
||||
--text-dim: #79847c;
|
||||
--accent: #1e40a2;
|
||||
--accent-hover: #16306f;
|
||||
--accent-soft: rgba(30, 64, 162, 0.1);
|
||||
--good: #2c6e49;
|
||||
--good-soft: rgba(44, 110, 73, 0.12);
|
||||
--warn: #9a6a18;
|
||||
--warn-soft: rgba(154, 106, 24, 0.12);
|
||||
--bad: #a33a2b;
|
||||
--bad-soft: rgba(163, 58, 43, 0.1);
|
||||
--radius: 4px;
|
||||
--radius-sm: 3px;
|
||||
--font-sans: var(--font-archivo), "Archivo", system-ui, -apple-system,
|
||||
"Segoe UI", Roboto, sans-serif;
|
||||
--font-mono: var(--font-mono-plex), "IBM Plex Mono", ui-monospace, "SF Mono",
|
||||
Menlo, Consolas, monospace;
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
html,
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font-family: var(--font-sans);
|
||||
font-size: 14px;
|
||||
line-height: 1.5;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
|
||||
a {
|
||||
color: inherit;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
code {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 0.85em;
|
||||
background: var(--bg-elevated);
|
||||
padding: 1px 5px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
/* ---------- App shell ---------- */
|
||||
.app-shell {
|
||||
display: grid;
|
||||
grid-template-columns: 248px 1fr;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
.sidebar {
|
||||
background: var(--bg-panel);
|
||||
border-right: 1px solid var(--border);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
position: sticky;
|
||||
top: 0;
|
||||
height: 100vh;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.sidebar-brand {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
font-weight: 700;
|
||||
font-size: 16px;
|
||||
padding: 18px 20px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.sidebar-logo {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.sidebar-nav {
|
||||
padding: 12px 12px 24px;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.nav-group {
|
||||
margin-bottom: 18px;
|
||||
}
|
||||
|
||||
.nav-group-title {
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.06em;
|
||||
font-size: 10px;
|
||||
font-weight: 600;
|
||||
color: var(--text-dim);
|
||||
padding: 6px 10px;
|
||||
}
|
||||
|
||||
.nav-link {
|
||||
display: block;
|
||||
padding: 7px 10px;
|
||||
border-radius: var(--radius-sm);
|
||||
color: var(--text-muted);
|
||||
font-size: 13px;
|
||||
transition: background 0.12s, color 0.12s;
|
||||
}
|
||||
|
||||
.nav-link:hover {
|
||||
background: var(--bg-elevated);
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.nav-link.active {
|
||||
background: var(--accent-soft);
|
||||
color: var(--accent);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.sidebar-footer {
|
||||
padding: 14px 20px;
|
||||
border-top: 1px solid var(--border);
|
||||
font-size: 11px;
|
||||
color: var(--text-dim);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.sidebar-signout {
|
||||
display: inline-block;
|
||||
align-self: flex-start;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
color: var(--text-muted);
|
||||
padding: 4px 0;
|
||||
}
|
||||
|
||||
.sidebar-signout:hover {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
/* ---------- Auth shell ---------- */
|
||||
.auth-shell {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 100vh;
|
||||
padding: 32px 20px;
|
||||
}
|
||||
|
||||
.auth-shell-inner {
|
||||
width: 100%;
|
||||
max-width: 400px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 22px;
|
||||
}
|
||||
|
||||
.auth-brand {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 10px;
|
||||
font-weight: 700;
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
.auth-heading {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.auth-heading .page-title {
|
||||
font-size: 20px;
|
||||
}
|
||||
|
||||
.auth-card {
|
||||
background: var(--bg-panel);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
padding: 24px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 18px;
|
||||
}
|
||||
|
||||
.auth-card .form {
|
||||
max-width: none;
|
||||
}
|
||||
|
||||
.auth-method-toggle {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.auth-alt {
|
||||
text-align: center;
|
||||
font-size: 13px;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.auth-alt a {
|
||||
color: var(--accent);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.main {
|
||||
padding: 28px 32px 64px;
|
||||
max-width: 1180px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
/* ---------- Page header ---------- */
|
||||
.page-header {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
.page-title {
|
||||
font-size: 22px;
|
||||
font-weight: 700;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.page-desc {
|
||||
color: var(--text-muted);
|
||||
margin: 4px 0 0;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
/* ---------- Cards & stats ---------- */
|
||||
.card {
|
||||
background: var(--bg-panel);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
padding: 20px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.card-title {
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
margin: 0 0 14px;
|
||||
}
|
||||
|
||||
.stat-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
|
||||
gap: 14px;
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
.stat-card {
|
||||
background: var(--bg-panel);
|
||||
border: 1px solid var(--border);
|
||||
border-left: 3px solid var(--border-strong);
|
||||
border-radius: var(--radius);
|
||||
padding: 16px 18px;
|
||||
}
|
||||
|
||||
.stat-card.tone-good {
|
||||
border-left-color: var(--good);
|
||||
}
|
||||
.stat-card.tone-warn {
|
||||
border-left-color: var(--warn);
|
||||
}
|
||||
.stat-card.tone-bad {
|
||||
border-left-color: var(--bad);
|
||||
}
|
||||
.stat-card.tone-default {
|
||||
border-left-color: var(--accent);
|
||||
}
|
||||
|
||||
.stat-label {
|
||||
font-size: 12px;
|
||||
color: var(--text-muted);
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.stat-value {
|
||||
font-size: 24px;
|
||||
font-weight: 700;
|
||||
letter-spacing: -0.01em;
|
||||
}
|
||||
|
||||
.stat-hint {
|
||||
font-size: 11px;
|
||||
color: var(--text-dim);
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
/* ---------- Tables ---------- */
|
||||
.table-wrap {
|
||||
overflow-x: auto;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
}
|
||||
|
||||
.data-table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.data-table th {
|
||||
text-align: left;
|
||||
font-weight: 600;
|
||||
color: var(--text-muted);
|
||||
padding: 10px 14px;
|
||||
background: var(--bg-elevated);
|
||||
border-bottom: 1px solid var(--border);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.data-table td {
|
||||
padding: 11px 14px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
.data-table tr:last-child td {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.data-table tbody tr:hover {
|
||||
background: var(--bg-elevated);
|
||||
}
|
||||
|
||||
.ta-right {
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.mono {
|
||||
font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
/* ---------- Badges ---------- */
|
||||
.badge {
|
||||
display: inline-block;
|
||||
padding: 2px 9px;
|
||||
border-radius: 999px;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
text-transform: capitalize;
|
||||
border: 1px solid transparent;
|
||||
}
|
||||
|
||||
.badge-good {
|
||||
background: var(--good-soft);
|
||||
color: var(--good);
|
||||
}
|
||||
.badge-warn {
|
||||
background: var(--warn-soft);
|
||||
color: var(--warn);
|
||||
}
|
||||
.badge-bad {
|
||||
background: var(--bad-soft);
|
||||
color: var(--bad);
|
||||
}
|
||||
.badge-neutral {
|
||||
background: var(--bg-elevated);
|
||||
color: var(--text-muted);
|
||||
border-color: var(--border);
|
||||
}
|
||||
|
||||
/* ---------- Buttons ---------- */
|
||||
.btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 8px 14px;
|
||||
border-radius: var(--radius-sm);
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
border: 1px solid var(--border-strong);
|
||||
background: var(--bg-elevated);
|
||||
color: var(--text);
|
||||
transition: background 0.12s, border-color 0.12s;
|
||||
}
|
||||
|
||||
.btn:hover {
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
background: var(--accent);
|
||||
border-color: var(--accent);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.btn-primary:hover {
|
||||
background: var(--accent-hover);
|
||||
}
|
||||
|
||||
.btn:disabled {
|
||||
opacity: 0.55;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
/* ---------- Empty / error states ---------- */
|
||||
.empty-state {
|
||||
text-align: center;
|
||||
padding: 48px 24px;
|
||||
border: 1px dashed var(--border-strong);
|
||||
border-radius: var(--radius);
|
||||
background: var(--bg-panel);
|
||||
}
|
||||
|
||||
.empty-icon {
|
||||
font-size: 28px;
|
||||
color: var(--text-dim);
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.empty-title {
|
||||
font-weight: 600;
|
||||
font-size: 15px;
|
||||
}
|
||||
|
||||
.empty-message {
|
||||
color: var(--text-muted);
|
||||
max-width: 420px;
|
||||
margin: 6px auto 0;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.empty-action {
|
||||
margin-top: 16px;
|
||||
}
|
||||
|
||||
.error-banner {
|
||||
background: var(--bad-soft);
|
||||
border: 1px solid rgba(240, 99, 99, 0.4);
|
||||
color: var(--bad);
|
||||
padding: 10px 14px;
|
||||
border-radius: var(--radius-sm);
|
||||
font-size: 12px;
|
||||
margin-bottom: 18px;
|
||||
}
|
||||
|
||||
/* ---------- Sub navigation ---------- */
|
||||
.subnav {
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
margin-bottom: 22px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.subnav-link {
|
||||
padding: 8px 14px;
|
||||
font-size: 13px;
|
||||
color: var(--text-muted);
|
||||
border-bottom: 2px solid transparent;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.subnav-link:hover {
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
/* ---------- Forms ---------- */
|
||||
.form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
max-width: 640px;
|
||||
}
|
||||
|
||||
.field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.field label {
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.field-hint {
|
||||
font-size: 12px;
|
||||
color: var(--text-dim);
|
||||
}
|
||||
|
||||
.input,
|
||||
.select,
|
||||
.textarea {
|
||||
background: var(--bg);
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--radius-sm);
|
||||
color: var(--text);
|
||||
padding: 9px 11px;
|
||||
font-size: 13px;
|
||||
font-family: inherit;
|
||||
}
|
||||
|
||||
.input:focus,
|
||||
.select:focus,
|
||||
.textarea:focus {
|
||||
outline: none;
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
.textarea {
|
||||
resize: vertical;
|
||||
min-height: 80px;
|
||||
}
|
||||
|
||||
.form-row {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.form-row > .field {
|
||||
flex: 1;
|
||||
min-width: 160px;
|
||||
}
|
||||
|
||||
.form-message {
|
||||
font-size: 13px;
|
||||
padding: 8px 12px;
|
||||
border-radius: var(--radius-sm);
|
||||
}
|
||||
|
||||
.form-message.ok {
|
||||
background: var(--good-soft);
|
||||
color: var(--good);
|
||||
}
|
||||
|
||||
.form-message.err {
|
||||
background: var(--bad-soft);
|
||||
color: var(--bad);
|
||||
}
|
||||
|
||||
/* ---------- Choice grid (product builder) ---------- */
|
||||
.choice-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.choice {
|
||||
text-align: left;
|
||||
background: var(--bg);
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--radius);
|
||||
padding: 14px 16px;
|
||||
cursor: pointer;
|
||||
transition: border-color 0.12s, background 0.12s;
|
||||
}
|
||||
|
||||
.choice:hover {
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
.choice.selected {
|
||||
border-color: var(--accent);
|
||||
background: var(--accent-soft);
|
||||
}
|
||||
|
||||
.choice-title {
|
||||
font-weight: 600;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.choice-desc {
|
||||
font-size: 12px;
|
||||
color: var(--text-muted);
|
||||
margin-top: 3px;
|
||||
}
|
||||
|
||||
.step-label {
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
color: var(--accent);
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.builder-actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 10px;
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
/* ---------- Misc ---------- */
|
||||
.muted {
|
||||
color: var(--text-muted);
|
||||
}
|
||||
.dim {
|
||||
color: var(--text-dim);
|
||||
}
|
||||
.row-between {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
}
|
||||
.tag-list {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.tag {
|
||||
background: var(--bg-elevated);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 4px;
|
||||
padding: 1px 7px;
|
||||
font-size: 11px;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
.detail-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 160px 1fr;
|
||||
gap: 10px 18px;
|
||||
font-size: 13px;
|
||||
}
|
||||
.detail-grid dt {
|
||||
color: var(--text-muted);
|
||||
}
|
||||
.detail-grid dd {
|
||||
margin: 0;
|
||||
font-weight: 500;
|
||||
}
|
||||
.breadcrumb {
|
||||
font-size: 12px;
|
||||
color: var(--text-dim);
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
.breadcrumb a:hover {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
/* ---------- Button variants ---------- */
|
||||
.btn-ghost {
|
||||
background: transparent;
|
||||
border-color: var(--border-strong);
|
||||
color: var(--text-muted);
|
||||
}
|
||||
.btn-ghost:hover {
|
||||
color: var(--text);
|
||||
border-color: var(--accent);
|
||||
}
|
||||
.btn-sm {
|
||||
padding: 5px 11px;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
/* ---------- Onboarding checklist ---------- */
|
||||
.onboarding {
|
||||
border-color: var(--accent);
|
||||
background: var(--bg-panel);
|
||||
border-left: 3px solid var(--accent);
|
||||
}
|
||||
.onboarding-head {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
}
|
||||
.onboarding-pct {
|
||||
font-size: 22px;
|
||||
font-weight: 700;
|
||||
color: var(--accent);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.onboarding-progress {
|
||||
height: 6px;
|
||||
border-radius: 999px;
|
||||
background: var(--bg-elevated);
|
||||
overflow: hidden;
|
||||
margin: 14px 0 18px;
|
||||
}
|
||||
.onboarding-progress-fill {
|
||||
height: 100%;
|
||||
background: var(--accent);
|
||||
border-radius: 999px;
|
||||
transition: width 0.3s ease;
|
||||
}
|
||||
.onboarding-steps {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
.onboarding-step {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 12px 14px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--bg-elevated);
|
||||
}
|
||||
.onboarding-step.next {
|
||||
border-color: var(--accent);
|
||||
}
|
||||
.onboarding-step.done {
|
||||
opacity: 0.7;
|
||||
}
|
||||
.onboarding-check {
|
||||
flex: 0 0 22px;
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border-radius: 999px;
|
||||
font-size: 13px;
|
||||
background: var(--bg-panel);
|
||||
color: var(--text-dim);
|
||||
}
|
||||
.onboarding-step.done .onboarding-check {
|
||||
background: var(--good-soft);
|
||||
color: var(--good);
|
||||
}
|
||||
.onboarding-step-body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
}
|
||||
.onboarding-step-title {
|
||||
font-weight: 600;
|
||||
font-size: 14px;
|
||||
}
|
||||
.onboarding-step.done .onboarding-step-title {
|
||||
text-decoration: line-through;
|
||||
text-decoration-color: var(--text-dim);
|
||||
}
|
||||
.onboarding-step-status {
|
||||
font-size: 12px;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
38
apps/creator-dashboard/app/layout.tsx
Normal file
38
apps/creator-dashboard/app/layout.tsx
Normal file
@ -0,0 +1,38 @@
|
||||
import type { Metadata } from "next";
|
||||
import type { ReactNode } from "react";
|
||||
import { Archivo, IBM_Plex_Mono } from "next/font/google";
|
||||
import { Sidebar } from "@/components/Sidebar";
|
||||
import "./globals.css";
|
||||
|
||||
const archivo = Archivo({
|
||||
subsets: ["latin"],
|
||||
weight: ["400", "500", "600", "700", "800", "900"],
|
||||
variable: "--font-archivo",
|
||||
display: "swap",
|
||||
});
|
||||
|
||||
const plexMono = IBM_Plex_Mono({
|
||||
subsets: ["latin"],
|
||||
weight: ["400", "500", "600", "700"],
|
||||
variable: "--font-mono-plex",
|
||||
display: "swap",
|
||||
});
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "SettleKit — Creator Earnings",
|
||||
description:
|
||||
"See your per-citation, per-listen, and per-second USDC royalties — the recursive split that follows your work through every hand that cites it.",
|
||||
};
|
||||
|
||||
export default function RootLayout({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<html lang="en" className={`${archivo.variable} ${plexMono.variable}`}>
|
||||
<body>
|
||||
<div className="app-shell">
|
||||
<Sidebar />
|
||||
<main className="main">{children}</main>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
16
apps/creator-dashboard/app/not-found.tsx
Normal file
16
apps/creator-dashboard/app/not-found.tsx
Normal file
@ -0,0 +1,16 @@
|
||||
import Link from "next/link";
|
||||
|
||||
export default function NotFound() {
|
||||
return (
|
||||
<div className="empty-state">
|
||||
<div className="empty-icon">∅</div>
|
||||
<div className="empty-title">Page not found</div>
|
||||
<p className="empty-message">This statement line doesn't exist.</p>
|
||||
<div className="empty-action">
|
||||
<Link className="btn btn-primary" href="/">
|
||||
Back to statement
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
53
apps/creator-dashboard/app/page.tsx
Normal file
53
apps/creator-dashboard/app/page.tsx
Normal file
@ -0,0 +1,53 @@
|
||||
import { Card, DataTable, EmptyState, PageHeader, StatCard, StatGrid, StatusBadge } from "@/components/ui";
|
||||
import { getCreatorContext, type StatementLine } from "@/lib/data";
|
||||
import { formatNumber, formatUsdc, formatDateTime } from "@/lib/format";
|
||||
|
||||
export default function StatementPage() {
|
||||
const ctx = getCreatorContext();
|
||||
const { totals, statement, me } = ctx;
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader
|
||||
title="Statement"
|
||||
description={`Earnings for ${me.name} (${me.handle}) — your author share plus the recursive cut of everything that cites your work.`}
|
||||
/>
|
||||
|
||||
<StatGrid>
|
||||
<StatCard label="Lifetime earned" value={formatUsdc(totals.lifetime.amount)} tone="good" hint="Author + citation shares" />
|
||||
<StatCard label="Settled" value={formatUsdc(totals.settled.amount)} tone="good" hint="Paid out on-chain" />
|
||||
<StatCard label="Pending" value={formatUsdc(totals.pending.amount)} tone="warn" hint="Awaiting next sweep" />
|
||||
<StatCard label="Paying accesses" value={formatNumber(totals.payingAccesses)} hint="Citations that paid you" />
|
||||
<StatCard label="Sources" value={formatNumber(totals.sourcesAuthored)} hint="Works you authored" />
|
||||
</StatGrid>
|
||||
|
||||
<Card title="Recent royalty lines">
|
||||
<DataTable<StatementLine>
|
||||
rows={statement}
|
||||
getKey={(r) => `${r.accessId}-${r.depth}-${r.createdAt}`}
|
||||
columns={[
|
||||
{ header: "Posted", cell: (r) => <span className="mono">{formatDateTime(r.createdAt)}</span> },
|
||||
{ header: "Source", cell: (r) => r.sourceTitle },
|
||||
{
|
||||
header: "Tier",
|
||||
cell: (r) => (
|
||||
<span className="badge badge-neutral">{r.depth === 0 ? "Author" : `Citation · L${r.depth}`}</span>
|
||||
),
|
||||
},
|
||||
{ header: "Status", cell: (r) => <StatusBadge status={r.status} /> },
|
||||
{
|
||||
header: "Credit",
|
||||
align: "right",
|
||||
cell: (r) => (
|
||||
<span className="mono" style={{ color: "var(--good)", fontWeight: 600 }}>
|
||||
+{formatUsdc(r.amount.amount)}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
]}
|
||||
empty={<EmptyState title="No earnings yet" message="When agents cite your sources, royalty lines will print here." />}
|
||||
/>
|
||||
</Card>
|
||||
</>
|
||||
);
|
||||
}
|
||||
43
apps/creator-dashboard/app/payouts/page.tsx
Normal file
43
apps/creator-dashboard/app/payouts/page.tsx
Normal file
@ -0,0 +1,43 @@
|
||||
import { Card, DataTable, EmptyState, PageHeader, StatCard, StatGrid } from "@/components/ui";
|
||||
import { getCreatorContext, type PayoutSweep } from "@/lib/data";
|
||||
import { formatNumber, formatUsdc } from "@/lib/format";
|
||||
|
||||
export default function PayoutsPage() {
|
||||
const { payouts, totals } = getCreatorContext();
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader
|
||||
title="Payouts"
|
||||
description="Settled sweeps roll your accrued royalty lines into one gas-free on-chain settlement per batch."
|
||||
/>
|
||||
|
||||
<StatGrid>
|
||||
<StatCard label="Settled" value={formatUsdc(totals.settled.amount)} tone="good" hint={`${payouts.length} sweeps`} />
|
||||
<StatCard label="Pending" value={formatUsdc(totals.pending.amount)} tone="warn" hint="Included in the next sweep" />
|
||||
<StatCard label="Lifetime" value={formatUsdc(totals.lifetime.amount)} hint="All royalty lines" />
|
||||
</StatGrid>
|
||||
|
||||
<Card title="Settlement sweeps">
|
||||
<DataTable<PayoutSweep>
|
||||
rows={payouts}
|
||||
getKey={(r) => r.settlementId}
|
||||
columns={[
|
||||
{ header: "Settlement", cell: (r) => <span className="mono">{r.settlementId}</span> },
|
||||
{ header: "Lines batched", align: "right", cell: (r) => <span className="mono">{formatNumber(r.legs)}</span> },
|
||||
{
|
||||
header: "Amount",
|
||||
align: "right",
|
||||
cell: (r) => (
|
||||
<span className="mono" style={{ color: "var(--good)", fontWeight: 600 }}>
|
||||
+{formatUsdc(r.amount.amount)}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
]}
|
||||
empty={<EmptyState title="No payouts yet" message="Once royalty lines are swept, settlements will list here." />}
|
||||
/>
|
||||
</Card>
|
||||
</>
|
||||
);
|
||||
}
|
||||
50
apps/creator-dashboard/app/settings/wallet/page.tsx
Normal file
50
apps/creator-dashboard/app/settings/wallet/page.tsx
Normal file
@ -0,0 +1,50 @@
|
||||
import { Card, PageHeader } from "@/components/ui";
|
||||
import { getCreatorContext } from "@/lib/data";
|
||||
import { shortWallet } from "@/lib/format";
|
||||
|
||||
export default function WalletSettingsPage() {
|
||||
const { me } = getCreatorContext();
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader
|
||||
title="Wallet"
|
||||
description="Your payout wallet is the rule that turns attribution into settlement. Map your identity once; every citation routes here."
|
||||
/>
|
||||
|
||||
<Card title="Payout wallet">
|
||||
<div className="detail-grid">
|
||||
<dt>Creator</dt>
|
||||
<dd>
|
||||
{me.name} <span className="dim">({me.handle})</span>
|
||||
</dd>
|
||||
<dt>Network</dt>
|
||||
<dd className="mono">arc</dd>
|
||||
<dt>Address</dt>
|
||||
<dd className="mono" title={me.wallet}>
|
||||
{shortWallet(me.wallet)}
|
||||
</dd>
|
||||
<dt>Payee key</dt>
|
||||
<dd className="mono">rss · {me.handle}</dd>
|
||||
</div>
|
||||
<p className="field-hint" style={{ marginTop: 14 }}>
|
||||
Registered in the payee registry as <code>{`{ kind: "rss", externalId: "${me.handle}" } → ${shortWallet(me.wallet)}`}</code>.
|
||||
Until a creator claims their handle, earnings accrue to an escrow wallet and are released on registration.
|
||||
</p>
|
||||
</Card>
|
||||
|
||||
<Card title="Cash out">
|
||||
<p className="muted" style={{ marginTop: 0 }}>
|
||||
Settled USDC can be swept to fiat through the Circle Payments Network off-ramp (e.g. USDC → local
|
||||
currency). This is wired in <code>packages/payouts-cpn</code> and activates once Circle CPN credentials
|
||||
are configured.
|
||||
</p>
|
||||
<div className="builder-actions">
|
||||
<button className="btn" disabled>
|
||||
Connect off-ramp (needs Circle CPN creds)
|
||||
</button>
|
||||
</div>
|
||||
</Card>
|
||||
</>
|
||||
);
|
||||
}
|
||||
63
apps/creator-dashboard/app/sources/page.tsx
Normal file
63
apps/creator-dashboard/app/sources/page.tsx
Normal file
@ -0,0 +1,63 @@
|
||||
import { Card, DataTable, EmptyState, PageHeader, StatusBadge } from "@/components/ui";
|
||||
import { getCreatorContext, type SourceStat } from "@/lib/data";
|
||||
import { formatNumber, formatUsdc } from "@/lib/format";
|
||||
|
||||
export default function SourcesPage() {
|
||||
const { sources } = getCreatorContext();
|
||||
const mine = sources.filter((s) => s.isMine);
|
||||
const others = sources.filter((s) => !s.isMine);
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader
|
||||
title="Sources"
|
||||
description="Your priced, citeable works — and the works you cite, which route a share back to their authors."
|
||||
/>
|
||||
|
||||
<Card title="Authored by you">
|
||||
<DataTable<SourceStat>
|
||||
rows={mine}
|
||||
getKey={(r) => r.id}
|
||||
columns={[
|
||||
{ header: "Title", cell: (r) => r.title },
|
||||
{ header: "Per-access toll", cell: (r) => <span className="mono">{formatUsdc(r.priceUsdc)}</span> },
|
||||
{ header: "Accesses", align: "right", cell: (r) => <span className="mono">{formatNumber(r.accesses)}</span> },
|
||||
{ header: "Cites", cell: (r) => (r.citesCount > 0 ? <StatusBadge status="active" /> : <span className="dim">—</span>) },
|
||||
{
|
||||
header: "Earned by you",
|
||||
align: "right",
|
||||
cell: (r) => (
|
||||
<span className="mono" style={{ color: "var(--good)", fontWeight: 600 }}>
|
||||
+{formatUsdc(r.earnedByMe.amount)}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
]}
|
||||
empty={<EmptyState title="No sources" message="Register a source to start charging per-citation tolls." />}
|
||||
/>
|
||||
</Card>
|
||||
|
||||
<Card title="Works you cite">
|
||||
<DataTable<SourceStat>
|
||||
rows={others}
|
||||
getKey={(r) => r.id}
|
||||
columns={[
|
||||
{ header: "Title", cell: (r) => r.title },
|
||||
{ header: "Per-access toll", cell: (r) => <span className="mono">{formatUsdc(r.priceUsdc)}</span> },
|
||||
{ header: "Accesses", align: "right", cell: (r) => <span className="mono">{formatNumber(r.accesses)}</span> },
|
||||
{
|
||||
header: "Your recursive cut",
|
||||
align: "right",
|
||||
cell: (r) => (
|
||||
<span className="mono" style={{ color: r.earnedByMe.amount === "0" ? "var(--text-dim)" : "var(--good)", fontWeight: 600 }}>
|
||||
{r.earnedByMe.amount === "0" ? "—" : `+${formatUsdc(r.earnedByMe.amount)}`}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
]}
|
||||
empty={<EmptyState title="No citations" message="Sources you cite will appear here." />}
|
||||
/>
|
||||
</Card>
|
||||
</>
|
||||
);
|
||||
}
|
||||
116
apps/creator-dashboard/components/ReuseDetector.tsx
Normal file
116
apps/creator-dashboard/components/ReuseDetector.tsx
Normal file
@ -0,0 +1,116 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
|
||||
interface Match {
|
||||
sourceId: string;
|
||||
title: string;
|
||||
score: number;
|
||||
matched: number;
|
||||
total: number;
|
||||
wallet?: string;
|
||||
}
|
||||
|
||||
interface DetectResult {
|
||||
grounded: boolean;
|
||||
matches: Match[];
|
||||
quoteUsdc: string;
|
||||
}
|
||||
|
||||
const SAMPLE =
|
||||
"Royalties should follow a work through every hand that made it, and when settlement is sub-cent and gas-free a citation can pay its source automatically.";
|
||||
|
||||
export function ReuseDetector() {
|
||||
const [text, setText] = useState(SAMPLE);
|
||||
const [result, setResult] = useState<DetectResult | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
async function run() {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const res = await fetch("/api/detect", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ text }),
|
||||
});
|
||||
const json = (await res.json()) as { data?: DetectResult; error?: string };
|
||||
if (!res.ok || json.data === undefined) {
|
||||
setError(json.error ?? "detection failed");
|
||||
setResult(null);
|
||||
} else {
|
||||
setResult(json.data);
|
||||
}
|
||||
} catch {
|
||||
setError("network error");
|
||||
setResult(null);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="form">
|
||||
<div className="field">
|
||||
<label htmlFor="answer">Agent answer</label>
|
||||
<textarea
|
||||
id="answer"
|
||||
className="textarea"
|
||||
rows={4}
|
||||
value={text}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
placeholder="Paste the text an agent produced…"
|
||||
/>
|
||||
<span className="field-hint">
|
||||
We shingle the text and check containment against your source corpus — the same call the citation-toll
|
||||
sidecar exposes at <code>POST /attribution/detect</code>.
|
||||
</span>
|
||||
</div>
|
||||
<div className="builder-actions">
|
||||
<button className="btn btn-primary" onClick={run} disabled={loading || text.trim().length === 0}>
|
||||
{loading ? "Detecting…" : "Detect reuse"}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{error ? <div className="form-message err">{error}</div> : null}
|
||||
|
||||
{result ? (
|
||||
<div style={{ marginTop: 8 }}>
|
||||
<div className="row-between" style={{ marginBottom: 10 }}>
|
||||
<span className={`badge ${result.grounded ? "badge-good" : "badge-neutral"}`}>
|
||||
{result.grounded ? "Grounded in your sources" : "No grounding detected"}
|
||||
</span>
|
||||
<span className="mono" style={{ fontWeight: 600 }}>
|
||||
Toll owed: {result.quoteUsdc} USDC
|
||||
</span>
|
||||
</div>
|
||||
{result.matches.length > 0 ? (
|
||||
<div className="table-wrap">
|
||||
<table className="data-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Source</th>
|
||||
<th className="ta-right">Containment</th>
|
||||
<th className="ta-right">Shingles</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{result.matches.map((m) => (
|
||||
<tr key={m.sourceId}>
|
||||
<td>{m.title}</td>
|
||||
<td className="ta-right mono">{(m.score * 100).toFixed(0)}%</td>
|
||||
<td className="ta-right mono">
|
||||
{m.matched}/{m.total}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
42
apps/creator-dashboard/components/Sidebar.tsx
Normal file
42
apps/creator-dashboard/components/Sidebar.tsx
Normal file
@ -0,0 +1,42 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { NAV_GROUPS } from "@/lib/nav";
|
||||
|
||||
function isActive(pathname: string, href: string): boolean {
|
||||
if (href === "/") return pathname === "/";
|
||||
return pathname === href || pathname.startsWith(`${href}/`);
|
||||
}
|
||||
|
||||
export function Sidebar() {
|
||||
const pathname = usePathname();
|
||||
|
||||
return (
|
||||
<aside className="sidebar">
|
||||
<div className="sidebar-brand">
|
||||
<span className="sidebar-logo">◆</span>
|
||||
<span>SettleKit · Creator</span>
|
||||
</div>
|
||||
<nav className="sidebar-nav">
|
||||
{NAV_GROUPS.map((group) => (
|
||||
<div className="nav-group" key={group.title}>
|
||||
<div className="nav-group-title">{group.title}</div>
|
||||
{group.items.map((item) => (
|
||||
<Link
|
||||
key={item.href}
|
||||
href={item.href}
|
||||
className={isActive(pathname, item.href) ? "nav-link active" : "nav-link"}
|
||||
>
|
||||
{item.label}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</nav>
|
||||
<div className="sidebar-footer">
|
||||
<span>Royalties that follow a work · USDC native</span>
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
183
apps/creator-dashboard/components/ui.tsx
Normal file
183
apps/creator-dashboard/components/ui.tsx
Normal file
@ -0,0 +1,183 @@
|
||||
// Presentational primitives shared across pages. Server-component friendly
|
||||
// (no client hooks) so they can render inside server components.
|
||||
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
export function PageHeader({
|
||||
title,
|
||||
description,
|
||||
action,
|
||||
}: {
|
||||
title: string;
|
||||
description?: string;
|
||||
action?: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div className="page-header">
|
||||
<div>
|
||||
<h1 className="page-title">{title}</h1>
|
||||
{description ? <p className="page-desc">{description}</p> : null}
|
||||
</div>
|
||||
{action ? <div className="page-action">{action}</div> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function Card({
|
||||
children,
|
||||
title,
|
||||
}: {
|
||||
children: ReactNode;
|
||||
title?: string;
|
||||
}) {
|
||||
return (
|
||||
<section className="card">
|
||||
{title ? <h2 className="card-title">{title}</h2> : null}
|
||||
{children}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
export function StatCard({
|
||||
label,
|
||||
value,
|
||||
hint,
|
||||
tone = "default",
|
||||
}: {
|
||||
label: string;
|
||||
value: string;
|
||||
hint?: string;
|
||||
tone?: "default" | "good" | "warn" | "bad";
|
||||
}) {
|
||||
return (
|
||||
<div className={`stat-card tone-${tone}`}>
|
||||
<div className="stat-label">{label}</div>
|
||||
<div className="stat-value">{value}</div>
|
||||
{hint ? <div className="stat-hint">{hint}</div> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function StatGrid({ children }: { children: ReactNode }) {
|
||||
return <div className="stat-grid">{children}</div>;
|
||||
}
|
||||
|
||||
const STATUS_TONES: Record<string, string> = {
|
||||
succeeded: "good",
|
||||
active: "good",
|
||||
paid: "good",
|
||||
granted: "good",
|
||||
published: "good",
|
||||
approved: "good",
|
||||
enabled: "good",
|
||||
assigned: "good",
|
||||
pending: "warn",
|
||||
trialing: "warn",
|
||||
in_transit: "warn",
|
||||
retrying: "warn",
|
||||
past_due: "warn",
|
||||
funded: "warn",
|
||||
submitted: "warn",
|
||||
open: "warn",
|
||||
draft: "neutral",
|
||||
failed: "bad",
|
||||
canceled: "bad",
|
||||
revoked: "bad",
|
||||
refunded: "bad",
|
||||
expired: "bad",
|
||||
disabled: "bad",
|
||||
};
|
||||
|
||||
export function StatusBadge({ status }: { status: string }) {
|
||||
const tone = STATUS_TONES[status] ?? "neutral";
|
||||
const label = status.replace(/_/g, " ");
|
||||
return <span className={`badge badge-${tone}`}>{label}</span>;
|
||||
}
|
||||
|
||||
export function EmptyState({
|
||||
title,
|
||||
message,
|
||||
action,
|
||||
}: {
|
||||
title: string;
|
||||
message: string;
|
||||
action?: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div className="empty-state">
|
||||
<div className="empty-icon">∅</div>
|
||||
<div className="empty-title">{title}</div>
|
||||
<p className="empty-message">{message}</p>
|
||||
{action ? <div className="empty-action">{action}</div> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBanner({ error }: { error: string | null }) {
|
||||
if (!error) return null;
|
||||
return (
|
||||
<div className="error-banner" role="alert">
|
||||
<strong>API unavailable.</strong> {error}. Showing empty state — start the
|
||||
API at <code>NEXT_PUBLIC_API_URL</code> to load live data.
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function DataTable<T>({
|
||||
columns,
|
||||
rows,
|
||||
getKey,
|
||||
empty,
|
||||
}: {
|
||||
columns: { header: string; cell: (row: T) => ReactNode; align?: "right" }[];
|
||||
rows: T[];
|
||||
getKey: (row: T) => string;
|
||||
empty: ReactNode;
|
||||
}) {
|
||||
if (rows.length === 0) return <>{empty}</>;
|
||||
return (
|
||||
<div className="table-wrap">
|
||||
<table className="data-table">
|
||||
<thead>
|
||||
<tr>
|
||||
{columns.map((c) => (
|
||||
<th key={c.header} className={c.align === "right" ? "ta-right" : ""}>
|
||||
{c.header}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((row) => (
|
||||
<tr key={getKey(row)}>
|
||||
{columns.map((c) => (
|
||||
<td
|
||||
key={c.header}
|
||||
className={c.align === "right" ? "ta-right" : ""}
|
||||
>
|
||||
{c.cell(row)}
|
||||
</td>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function SubNav({
|
||||
items,
|
||||
}: {
|
||||
items: { label: string; href: string }[];
|
||||
}) {
|
||||
return (
|
||||
<div className="subnav">
|
||||
{items.map((i) => (
|
||||
<a key={i.href} href={i.href} className="subnav-link">
|
||||
{i.label}
|
||||
</a>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
391
apps/creator-dashboard/lib/data.ts
Normal file
391
apps/creator-dashboard/lib/data.ts
Normal file
@ -0,0 +1,391 @@
|
||||
/**
|
||||
* The creator dashboard's data layer.
|
||||
*
|
||||
* This is NOT mocked JSON — it drives the real settlement domain logic so the
|
||||
* UI shows exactly what the spine produces:
|
||||
*
|
||||
* - sources are built with @settlekit/citation-toll `createSource` (with real
|
||||
* citation edges between works);
|
||||
* - every simulated paid access runs through `computeRoyaltyDistribution`, the
|
||||
* same recursive split the toll handler uses, so a creator earns both from
|
||||
* their own work and from the recursive share of everything that cites it;
|
||||
* - the attribution panel runs @settlekit/attribution `detectReuse` over the
|
||||
* sources and issues a real signed proof-of-citation.
|
||||
*
|
||||
* A fixed clock + fixed access counts make the dataset deterministic across
|
||||
* renders. Swap this module for the Pg-backed stores to go live.
|
||||
*/
|
||||
|
||||
import {
|
||||
type Money,
|
||||
addMoney,
|
||||
isOk,
|
||||
money,
|
||||
} from "@settlekit/common";
|
||||
import {
|
||||
InMemorySourceRegistry,
|
||||
type Citation,
|
||||
type CreateSourceInput,
|
||||
type PersistedRoyaltyLeg,
|
||||
type RoyaltyLeg,
|
||||
type Source,
|
||||
computeRoyaltyDistribution,
|
||||
createSource,
|
||||
} from "@settlekit/citation-toll";
|
||||
import { detectReuse, issueCitationProof, type CitationProof, type ReuseMatch } from "@settlekit/attribution";
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* Seed: creators + their citeable works */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
export interface Creator {
|
||||
wallet: string;
|
||||
name: string;
|
||||
handle: string;
|
||||
}
|
||||
|
||||
const CREATORS: Record<string, Creator> = {
|
||||
ada: { wallet: "0xada0000000000000000000000000000000000001", name: "Ada Okafor", handle: "@ada" },
|
||||
bo: { wallet: "0xb00000000000000000000000000000000000000b", name: "Bo Tan", handle: "@bo" },
|
||||
cyd: { wallet: "0xcyd000000000000000000000000000000000000c", name: "Cyd Marín", handle: "@cyd" },
|
||||
};
|
||||
|
||||
/** The signed-in creator whose statement this dashboard shows. */
|
||||
export const ME = CREATORS.ada;
|
||||
|
||||
interface SourceSeed {
|
||||
slug: string;
|
||||
title: string;
|
||||
author: Creator;
|
||||
priceUsdc: string;
|
||||
summary: string;
|
||||
body: string;
|
||||
/** Slugs of works this one is grounded in, with their revenue share (bps). */
|
||||
cites?: { slug: string; shareBps: number }[];
|
||||
/** Deterministic number of paid accesses to simulate. */
|
||||
accesses: number;
|
||||
}
|
||||
|
||||
const SEEDS: SourceSeed[] = [
|
||||
{
|
||||
slug: "primer",
|
||||
title: "The Recursive Settlement Primer",
|
||||
author: CREATORS.ada,
|
||||
priceUsdc: "0.0009",
|
||||
summary: "Why royalties should follow a work through every hand that cites it.",
|
||||
body:
|
||||
"Royalties should follow a work through every hand that made it. When settlement is sub-cent " +
|
||||
"and gas-free, a citation can pay its source automatically, and that payment can fan out " +
|
||||
"recursively to everything the source itself was grounded in.",
|
||||
accesses: 1200,
|
||||
},
|
||||
{
|
||||
slug: "proof",
|
||||
title: "Proof-of-Citation, Explained",
|
||||
author: CREATORS.ada,
|
||||
priceUsdc: "0.0006",
|
||||
summary: "A signed, expiring token an agent presents to prove it cited and paid for a source.",
|
||||
body:
|
||||
"A proof-of-citation is an HMAC-signed claim that an agent cited a set of sources under a paid " +
|
||||
"access. It is expiring and replay-protected, so a seller can trust it without re-querying the chain.",
|
||||
accesses: 300,
|
||||
},
|
||||
{
|
||||
slug: "practice",
|
||||
title: "Nanopayments in Practice",
|
||||
author: CREATORS.bo,
|
||||
priceUsdc: "0.0008",
|
||||
summary: "Wiring per-citation tolls into a real agent pipeline.",
|
||||
body:
|
||||
"In practice an agent pays a fraction of a cent per citation, the toll is batched into one " +
|
||||
"on-chain settlement, and the recursive split routes a share back to the primer it was grounded in.",
|
||||
cites: [{ slug: "primer", shareBps: 3500 }],
|
||||
accesses: 800,
|
||||
},
|
||||
{
|
||||
slug: "agent-tolls",
|
||||
title: "Agent Citation Tolls at the Boundary",
|
||||
author: CREATORS.cyd,
|
||||
priceUsdc: "0.0007",
|
||||
summary: "Charging implicit reuse, not just deliberate fetches.",
|
||||
body:
|
||||
"Reuse detection closes the loop: given the text an agent produced, detect which sources it was " +
|
||||
"grounded in and charge the toll, then settle recursively through the citation lineage.",
|
||||
cites: [{ slug: "practice", shareBps: 3000 }],
|
||||
accesses: 640,
|
||||
},
|
||||
];
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* Build the source graph + simulate paid accesses */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
const CLOCK = new Date("2026-06-18T09:00:00.000Z");
|
||||
|
||||
function buildRegistry(): { registry: InMemorySourceRegistry; bySlug: Map<string, Source> } {
|
||||
const registry = new InMemorySourceRegistry();
|
||||
const bySlug = new Map<string, Source>();
|
||||
|
||||
// Two passes: originals first so derived works can cite their ids.
|
||||
const ordered = [...SEEDS].sort((a, b) => (a.cites ? 1 : 0) - (b.cites ? 1 : 0));
|
||||
for (const seed of ordered) {
|
||||
const cites: Citation[] = (seed.cites ?? []).map((c) => {
|
||||
const parent = bySlug.get(c.slug);
|
||||
if (parent === undefined) throw new Error(`seed ${seed.slug} cites unknown ${c.slug}`);
|
||||
return { sourceId: parent.id, shareBps: c.shareBps };
|
||||
});
|
||||
const created = createSourceOrThrow({
|
||||
organizationId: "org_creator_demo",
|
||||
title: seed.title,
|
||||
authorWallet: seed.author.wallet,
|
||||
priceUsdc: seed.priceUsdc,
|
||||
body: seed.body,
|
||||
summary: seed.summary,
|
||||
cites,
|
||||
});
|
||||
registry.add(created);
|
||||
bySlug.set(seed.slug, created);
|
||||
}
|
||||
return { registry, bySlug };
|
||||
}
|
||||
|
||||
function createSourceOrThrow(input: CreateSourceInput): Source {
|
||||
const r = createSource(input, CLOCK);
|
||||
if (!isOk(r)) throw new Error("createSource failed in seed");
|
||||
return r.value;
|
||||
}
|
||||
|
||||
export interface RoyaltyEvent extends RoyaltyLeg {
|
||||
accessId: string;
|
||||
/** The accessed source whose access generated this leg. */
|
||||
accessedSourceId: string;
|
||||
status: PersistedRoyaltyLeg["status"];
|
||||
settlementId?: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
function simulateLedger(): { registry: InMemorySourceRegistry; bySlug: Map<string, Source>; events: RoyaltyEvent[] } {
|
||||
const { registry, bySlug } = buildRegistry();
|
||||
const events: RoyaltyEvent[] = [];
|
||||
let seq = 0;
|
||||
|
||||
for (const seed of SEEDS) {
|
||||
const source = bySlug.get(seed.slug);
|
||||
if (source === undefined) continue;
|
||||
const distribution = computeRoyaltyDistribution(registry, source.id);
|
||||
if (distribution === undefined) continue;
|
||||
|
||||
for (let access = 0; access < seed.accesses; access++) {
|
||||
const accessId = `acc_${seed.slug}_${access}`;
|
||||
for (const leg of distribution.legs) {
|
||||
seq++;
|
||||
// Deterministically settle ~70% of legs; the rest stay pending.
|
||||
const settled = seq % 10 < 7;
|
||||
events.push({
|
||||
...leg,
|
||||
accessId,
|
||||
accessedSourceId: source.id,
|
||||
status: settled ? "settled" : "pending",
|
||||
...(settled ? { settlementId: `set_${(seq % 6) + 1}` } : {}),
|
||||
createdAt: new Date(CLOCK.getTime() + seq * 1000).toISOString(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
return { registry, bySlug, events };
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* Aggregations for the UI */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
function sum(amounts: Money[]): Money {
|
||||
return amounts.reduce<Money>((acc, m) => addMoney(acc, m), money("0"));
|
||||
}
|
||||
|
||||
export interface SourceStat {
|
||||
id: string;
|
||||
title: string;
|
||||
priceUsdc: string;
|
||||
isMine: boolean;
|
||||
accesses: number;
|
||||
/** What the signed-in creator earned attributable to this source's accesses. */
|
||||
earnedByMe: Money;
|
||||
/** Whether this source cites another (it routes a share onward). */
|
||||
citesCount: number;
|
||||
}
|
||||
|
||||
export interface StatementLine {
|
||||
accessId: string;
|
||||
sourceTitle: string;
|
||||
amount: Money;
|
||||
depth: number;
|
||||
status: PersistedRoyaltyLeg["status"];
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export interface PayoutSweep {
|
||||
settlementId: string;
|
||||
legs: number;
|
||||
amount: Money;
|
||||
}
|
||||
|
||||
export interface AttributionExample {
|
||||
answer: string;
|
||||
matches: (ReuseMatch & { title: string })[];
|
||||
quoteUsdc: string;
|
||||
proof: CitationProof;
|
||||
}
|
||||
|
||||
export interface CreatorContext {
|
||||
me: Creator;
|
||||
totals: {
|
||||
lifetime: Money;
|
||||
settled: Money;
|
||||
pending: Money;
|
||||
payingAccesses: number;
|
||||
sourcesAuthored: number;
|
||||
};
|
||||
statement: StatementLine[];
|
||||
sources: SourceStat[];
|
||||
payouts: PayoutSweep[];
|
||||
attribution: AttributionExample;
|
||||
}
|
||||
|
||||
export function getCreatorContext(): CreatorContext {
|
||||
const { registry, bySlug, events } = simulateLedger();
|
||||
const titleById = new Map<string, Source>();
|
||||
for (const s of registry.all()) titleById.set(s.id, s);
|
||||
|
||||
const mine = events.filter((e) => e.wallet.toLowerCase() === ME.wallet.toLowerCase());
|
||||
|
||||
const settled = mine.filter((e) => e.status === "settled");
|
||||
const pending = mine.filter((e) => e.status === "pending");
|
||||
|
||||
const statement: StatementLine[] = mine
|
||||
.slice()
|
||||
.sort((a, b) => (a.createdAt < b.createdAt ? 1 : -1))
|
||||
.slice(0, 40)
|
||||
.map((e) => ({
|
||||
accessId: e.accessId,
|
||||
sourceTitle: titleById.get(e.accessedSourceId)?.title ?? e.accessedSourceId,
|
||||
amount: e.amount,
|
||||
depth: e.depth,
|
||||
status: e.status,
|
||||
createdAt: e.createdAt,
|
||||
}));
|
||||
|
||||
// Per-source: accesses + what I earned attributable to that accessed source.
|
||||
const sources: SourceStat[] = registry.all().map((s) => {
|
||||
const accesses = SEEDS.find((seed) => bySlug.get(seed.slug)?.id === s.id)?.accesses ?? 0;
|
||||
const earnedByMe = sum(
|
||||
mine.filter((e) => e.accessedSourceId === s.id).map((e) => e.amount),
|
||||
);
|
||||
return {
|
||||
id: s.id,
|
||||
title: s.title,
|
||||
priceUsdc: s.priceUsdc,
|
||||
isMine: s.authorWallet.toLowerCase() === ME.wallet.toLowerCase(),
|
||||
accesses,
|
||||
earnedByMe,
|
||||
citesCount: s.cites.length,
|
||||
};
|
||||
});
|
||||
|
||||
// Payout sweeps: settled legs grouped by their settlement id.
|
||||
const bySweep = new Map<string, RoyaltyEvent[]>();
|
||||
for (const e of settled) {
|
||||
if (e.settlementId === undefined) continue;
|
||||
const arr = bySweep.get(e.settlementId) ?? [];
|
||||
arr.push(e);
|
||||
bySweep.set(e.settlementId, arr);
|
||||
}
|
||||
const payouts: PayoutSweep[] = [...bySweep.entries()]
|
||||
.map(([settlementId, legs]) => ({
|
||||
settlementId,
|
||||
legs: legs.length,
|
||||
amount: sum(legs.map((l) => l.amount)),
|
||||
}))
|
||||
.sort((a, b) => a.settlementId.localeCompare(b.settlementId));
|
||||
|
||||
return {
|
||||
me: ME,
|
||||
totals: {
|
||||
lifetime: sum(mine.map((e) => e.amount)),
|
||||
settled: sum(settled.map((e) => e.amount)),
|
||||
pending: sum(pending.map((e) => e.amount)),
|
||||
payingAccesses: new Set(mine.map((e) => e.accessId)).size,
|
||||
sourcesAuthored: sources.filter((s) => s.isMine).length,
|
||||
},
|
||||
statement,
|
||||
sources,
|
||||
payouts,
|
||||
attribution: buildAttributionExample(registry),
|
||||
};
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* Attribution worked example (real detectReuse + signed proof) */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
const PROOF_SECRET = process.env.CITATION_PROOF_SECRET ?? "dev-citation-proof-secret";
|
||||
|
||||
/** Run reuse detection for arbitrary text against the demo source corpus. */
|
||||
export function detectGroundingForText(text: string): {
|
||||
grounded: boolean;
|
||||
matches: (ReuseMatch & { title: string })[];
|
||||
quoteUsdc: string;
|
||||
} {
|
||||
const { registry } = buildRegistry();
|
||||
const candidates = registry.all().map((s) => ({
|
||||
id: s.id,
|
||||
text: [s.title, s.summary, s.body].join(". "),
|
||||
wallet: s.authorWallet,
|
||||
}));
|
||||
const report = detectReuse(text, candidates);
|
||||
const titleById = new Map(registry.all().map((s) => [s.id, s.title]));
|
||||
const matches = report.matches.map((m) => ({ ...m, title: titleById.get(m.sourceId) ?? m.sourceId }));
|
||||
const quote = sum(
|
||||
report.matches.map((m) => {
|
||||
const s = registry.get(m.sourceId);
|
||||
return s !== undefined ? money(s.priceUsdc) : money("0");
|
||||
}),
|
||||
);
|
||||
return { grounded: report.grounded, matches, quoteUsdc: quote.amount };
|
||||
}
|
||||
|
||||
function buildAttributionExample(registry: InMemorySourceRegistry): AttributionExample {
|
||||
const answer =
|
||||
"Royalties should follow a work through every hand that made it, and when settlement is " +
|
||||
"sub-cent and gas-free a citation can pay its source automatically.";
|
||||
|
||||
const candidates = registry.all().map((s) => ({
|
||||
id: s.id,
|
||||
text: [s.title, s.summary, s.body].join(". "),
|
||||
wallet: s.authorWallet,
|
||||
}));
|
||||
const report = detectReuse(answer, candidates);
|
||||
|
||||
const titleById = new Map(registry.all().map((s) => [s.id, s.title]));
|
||||
const matches = report.matches.map((m) => ({ ...m, title: titleById.get(m.sourceId) ?? m.sourceId }));
|
||||
const quote = sum(
|
||||
report.matches.map((m) => {
|
||||
const s = registry.get(m.sourceId);
|
||||
return s !== undefined ? money(s.priceUsdc) : money("0");
|
||||
}),
|
||||
);
|
||||
|
||||
const proof = issueCitationProof(
|
||||
{
|
||||
agent: "agent_research_demo",
|
||||
sourceIds: report.matches.map((m) => m.sourceId),
|
||||
accessId: "acc_demo_1",
|
||||
amountUsdc: quote.amount,
|
||||
ttlSeconds: 3600,
|
||||
},
|
||||
PROOF_SECRET,
|
||||
CLOCK,
|
||||
);
|
||||
|
||||
return { answer, matches, quoteUsdc: quote.amount, proof };
|
||||
}
|
||||
45
apps/creator-dashboard/lib/format.ts
Normal file
45
apps/creator-dashboard/lib/format.ts
Normal file
@ -0,0 +1,45 @@
|
||||
// Formatting helpers. Money here is a decimal USDC string (the shape the
|
||||
// settlement spine produces, e.g. "0.0008"), not minor units.
|
||||
|
||||
/** Format a decimal USDC string, keeping sub-cent precision when present. */
|
||||
export function formatUsdc(amount: string | null | undefined): string {
|
||||
if (amount == null || amount === "") return "—";
|
||||
const value = Number(amount);
|
||||
if (Number.isNaN(value)) return `${amount} USDC`;
|
||||
const formatted = value.toLocaleString("en-US", {
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 6,
|
||||
});
|
||||
return `${formatted} USDC`;
|
||||
}
|
||||
|
||||
export function formatNumber(n: number | null | undefined): string {
|
||||
if (n == null) return "—";
|
||||
return n.toLocaleString("en-US");
|
||||
}
|
||||
|
||||
/** Render an ISO timestamp as a short readable date-time. */
|
||||
export function formatDateTime(iso: string | null | undefined): string {
|
||||
if (!iso) return "—";
|
||||
const d = new Date(iso);
|
||||
if (Number.isNaN(d.getTime())) return iso;
|
||||
return d.toLocaleString("en-US", {
|
||||
year: "numeric",
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
});
|
||||
}
|
||||
|
||||
/** Title-case a snake_case enum value for display. */
|
||||
export function humanize(value: string | null | undefined): string {
|
||||
if (!value) return "—";
|
||||
return value.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
|
||||
}
|
||||
|
||||
/** Shorten a wallet address for display: 0x1234…abcd. */
|
||||
export function shortWallet(wallet: string): string {
|
||||
if (wallet.length <= 12) return wallet;
|
||||
return `${wallet.slice(0, 6)}…${wallet.slice(-4)}`;
|
||||
}
|
||||
31
apps/creator-dashboard/lib/nav.ts
Normal file
31
apps/creator-dashboard/lib/nav.ts
Normal file
@ -0,0 +1,31 @@
|
||||
// Sidebar navigation for the creator dashboard — the surfaces a creator who
|
||||
// earns per-citation / per-listen / per-second royalties actually needs.
|
||||
|
||||
export interface NavItem {
|
||||
label: string;
|
||||
href: string;
|
||||
}
|
||||
|
||||
export interface NavGroup {
|
||||
title: string;
|
||||
items: NavItem[];
|
||||
}
|
||||
|
||||
export const NAV_GROUPS: NavGroup[] = [
|
||||
{
|
||||
title: "Earnings",
|
||||
items: [
|
||||
{ label: "Statement", href: "/" },
|
||||
{ label: "Sources", href: "/sources" },
|
||||
{ label: "Payouts", href: "/payouts" },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "Attribution",
|
||||
items: [{ label: "Reuse & proofs", href: "/attribution" }],
|
||||
},
|
||||
{
|
||||
title: "Account",
|
||||
items: [{ label: "Wallet", href: "/settings/wallet" }],
|
||||
},
|
||||
];
|
||||
5
apps/creator-dashboard/next-env.d.ts
vendored
Normal file
5
apps/creator-dashboard/next-env.d.ts
vendored
Normal file
@ -0,0 +1,5 @@
|
||||
/// <reference types="next" />
|
||||
/// <reference types="next/image-types/global" />
|
||||
|
||||
// NOTE: This file should not be edited
|
||||
// see https://nextjs.org/docs/app/building-your-application/configuring/typescript for more information.
|
||||
18
apps/creator-dashboard/next.config.mjs
Normal file
18
apps/creator-dashboard/next.config.mjs
Normal file
@ -0,0 +1,18 @@
|
||||
/** @type {import('next').NextConfig} */
|
||||
const nextConfig = {
|
||||
reactStrictMode: true,
|
||||
// Workspace domain packages ship compiled ESM; transpile them so Next can
|
||||
// bundle them into the server runtime without resolution surprises.
|
||||
transpilePackages: [
|
||||
"@settlekit/attribution",
|
||||
"@settlekit/citation-toll",
|
||||
"@settlekit/common",
|
||||
"@settlekit/payee-registry",
|
||||
"@settlekit/platform-billing",
|
||||
],
|
||||
env: {
|
||||
NEXT_PUBLIC_API_URL: process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:8787",
|
||||
},
|
||||
};
|
||||
|
||||
export default nextConfig;
|
||||
29
apps/creator-dashboard/package.json
Normal file
29
apps/creator-dashboard/package.json
Normal file
@ -0,0 +1,29 @@
|
||||
{
|
||||
"name": "@settlekit/creator-dashboard",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"description": "SettleKit creator dashboard — see per-citation / per-listen / per-second earnings, payouts, and reuse attribution in USDC.",
|
||||
"scripts": {
|
||||
"dev": "next dev -p 3007",
|
||||
"build": "next build",
|
||||
"start": "next start -p 3007",
|
||||
"lint": "next lint",
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@settlekit/attribution": "workspace:*",
|
||||
"@settlekit/citation-toll": "workspace:*",
|
||||
"@settlekit/common": "workspace:*",
|
||||
"@settlekit/payee-registry": "workspace:*",
|
||||
"@settlekit/platform-billing": "workspace:*",
|
||||
"next": "^14.2.5",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^20.14.0",
|
||||
"@types/react": "^18.3.3",
|
||||
"@types/react-dom": "^18.3.0",
|
||||
"typescript": "^5.5.4"
|
||||
}
|
||||
}
|
||||
24
apps/creator-dashboard/tsconfig.json
Normal file
24
apps/creator-dashboard/tsconfig.json
Normal file
@ -0,0 +1,24 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"lib": ["dom", "dom.iterable", "ES2022"],
|
||||
"allowJs": true,
|
||||
"skipLibCheck": true,
|
||||
"strict": true,
|
||||
"noEmit": true,
|
||||
"esModuleInterop": true,
|
||||
"module": "esnext",
|
||||
"moduleResolution": "bundler",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"jsx": "preserve",
|
||||
"incremental": true,
|
||||
"plugins": [{ "name": "next" }],
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"@/*": ["./*"]
|
||||
}
|
||||
},
|
||||
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
|
||||
"exclude": ["node_modules"]
|
||||
}
|
||||
6
apps/creator-dashboard/vercel.json
Normal file
6
apps/creator-dashboard/vercel.json
Normal file
@ -0,0 +1,6 @@
|
||||
{
|
||||
"$schema": "https://openapi.vercel.sh/vercel.json",
|
||||
"framework": "nextjs",
|
||||
"installCommand": "corepack enable && pnpm install --frozen-lockfile",
|
||||
"buildCommand": "pnpm --filter @settlekit/creator-dashboard... build"
|
||||
}
|
||||
@ -12,7 +12,7 @@
|
||||
"github": "node --import tsx src/github-repo-sale.ts",
|
||||
"bundle": "node --import tsx src/bundle-checkout.ts",
|
||||
"build": "tsc -b",
|
||||
"typecheck": "tsc -b --noEmit",
|
||||
"typecheck": "tsc -b",
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
|
||||
@ -12,6 +12,7 @@
|
||||
"build": "tsc -b",
|
||||
"start": "node ./dist/index.js",
|
||||
"dev": "node --enable-source-maps ./dist/index.js",
|
||||
"typecheck": "tsc -b",
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
|
||||
@ -155,6 +155,16 @@ function requireArcAddress(env: Env, key: string): ArcAddress {
|
||||
* `process.env` but accepts an explicit env map for tests.
|
||||
*/
|
||||
export function loadConfig(env: Env = process.env): WorkerConfig {
|
||||
// Fail closed in production: a worker without a shared database runs on a
|
||||
// process-local in-memory store, isolated from the API's Postgres — it would
|
||||
// "succeed" while delivering and settling nothing durable.
|
||||
const hasDatabase = Boolean(env.DATABASE_URL && env.DATABASE_URL.length > 0);
|
||||
if (env.NODE_ENV === "production" && !hasDatabase) {
|
||||
throw new ConfigError(
|
||||
"DATABASE_URL must be set in production: an in-memory worker is isolated from the API database and processes nothing durable.",
|
||||
);
|
||||
}
|
||||
|
||||
const intervals: JobIntervals = {
|
||||
deliveryRunnerMs: intInRange(env, "WORKER_DELIVERY_INTERVAL_MS", 5_000, 250, 3_600_000),
|
||||
paymentConfirmMs: intInRange(env, "WORKER_PAYMENT_INTERVAL_MS", 10_000, 250, 3_600_000),
|
||||
|
||||
@ -42,6 +42,7 @@ contract LeptonStreamSettlement {
|
||||
error NotParty();
|
||||
error ZeroRate();
|
||||
error ZeroReserve();
|
||||
error InvalidPayee();
|
||||
error TransferFailed();
|
||||
|
||||
constructor(IERC20 _token) {
|
||||
@ -51,6 +52,10 @@ contract LeptonStreamSettlement {
|
||||
/** Open a stream, depositing `reserve` from the caller (the payer). */
|
||||
function open(bytes32 id, address payee, uint256 ratePerSecond, uint256 reserve) external {
|
||||
if (_streams[id].open) revert AlreadyExists();
|
||||
// A zero payee would lock funds: once any value accrues, settle()/close()
|
||||
// revert on the transfer to address(0), and close() pays the payee before
|
||||
// refunding the payer — so the reserve can never be recovered.
|
||||
if (payee == address(0) || payee == msg.sender) revert InvalidPayee();
|
||||
if (ratePerSecond == 0) revert ZeroRate();
|
||||
if (reserve == 0) revert ZeroReserve();
|
||||
if (!token.transferFrom(msg.sender, address(this), reserve)) revert TransferFailed();
|
||||
|
||||
@ -35,6 +35,18 @@ contract LeptonStreamSettlementTest is Test {
|
||||
assertEq(usdc.balanceOf(streamer), 10);
|
||||
}
|
||||
|
||||
function testRejectsZeroPayee() public {
|
||||
vm.prank(viewer);
|
||||
vm.expectRevert(LeptonStreamSettlement.InvalidPayee.selector);
|
||||
stream.open(keccak256("zero-payee"), address(0), RATE, RESERVE);
|
||||
}
|
||||
|
||||
function testRejectsSelfPayee() public {
|
||||
vm.prank(viewer);
|
||||
vm.expectRevert(LeptonStreamSettlement.InvalidPayee.selector);
|
||||
stream.open(keccak256("self-payee"), viewer, RATE, RESERVE);
|
||||
}
|
||||
|
||||
function testPauseExcludesTime() public {
|
||||
vm.warp(1_000_005); // watched 5s
|
||||
vm.prank(viewer);
|
||||
|
||||
@ -14,6 +14,7 @@
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest",
|
||||
"typecheck": "tsc -b",
|
||||
"typecheck:all": "tsc -b && pnpm --filter \"./apps/*\" --workspace-concurrency=1 typecheck",
|
||||
"clean": "rm -rf packages/*/dist"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
26
packages/attribution/package.json
Normal file
26
packages/attribution/package.json
Normal file
@ -0,0 +1,26 @@
|
||||
{
|
||||
"name": "@settlekit/attribution",
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"main": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"default": "./dist/index.js"
|
||||
}
|
||||
},
|
||||
"files": ["dist"],
|
||||
"scripts": {
|
||||
"build": "tsc -b",
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@settlekit/common": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^20.14.0",
|
||||
"typescript": "^5.5.4",
|
||||
"vitest": "^2.0.5"
|
||||
}
|
||||
}
|
||||
5
packages/attribution/src/index.ts
Normal file
5
packages/attribution/src/index.ts
Normal file
@ -0,0 +1,5 @@
|
||||
export * from "./types.js";
|
||||
export * from "./lineage-graph.js";
|
||||
export * from "./reuse-detector.js";
|
||||
export * from "./proof.js";
|
||||
export * from "./store.js";
|
||||
179
packages/attribution/src/lineage-graph.ts
Normal file
179
packages/attribution/src/lineage-graph.ts
Normal file
@ -0,0 +1,179 @@
|
||||
/**
|
||||
* The provenance lineage graph.
|
||||
*
|
||||
* A weighted "derives-from" DAG. {@link computeAttributionShares} walks it the
|
||||
* way the citation-toll split walks the source graph — each node keeps the share
|
||||
* it does not route onward and passes the rest to the ancestors it derives from,
|
||||
* recursively — but expressed as fractions in [0, 1] rather than money, so any
|
||||
* consumer can use them: settle a payment, attribute a credit, or rank a result.
|
||||
*
|
||||
* The walk is cycle-safe (a node never re-enters its own path) and diamond-aware
|
||||
* (an ancestor reached by two paths accumulates both shares, recording the
|
||||
* shallowest depth).
|
||||
*/
|
||||
|
||||
import {
|
||||
type Result,
|
||||
type SettleKitError,
|
||||
err,
|
||||
ok,
|
||||
validationError,
|
||||
} from "@settlekit/common";
|
||||
import type { AttributionShare, LineageEdge } from "./types.js";
|
||||
|
||||
/** Float comparison slack — provenance weights are small fractions, not money. */
|
||||
const EPSILON = 1e-9;
|
||||
|
||||
/** Validate a single lineage edge: a real weight in (0, 1] with distinct ends. */
|
||||
export function validateLineageEdge(edge: LineageEdge): Result<LineageEdge, SettleKitError> {
|
||||
if (edge.child === edge.parent) {
|
||||
return err(validationError(`lineage edge cannot point a work at itself (${edge.child})`));
|
||||
}
|
||||
if (!Number.isFinite(edge.weight) || edge.weight <= 0 || edge.weight > 1 + EPSILON) {
|
||||
return err(validationError(`lineage edge weight must be in (0, 1], got ${edge.weight}`));
|
||||
}
|
||||
return ok({ ...edge, weight: Math.min(edge.weight, 1) });
|
||||
}
|
||||
|
||||
/**
|
||||
* A mutable, in-memory provenance DAG. Build it directly for tests, or snapshot
|
||||
* a {@link LineageStore} into one with {@link loadLineageGraph}.
|
||||
*/
|
||||
export class LineageGraph {
|
||||
/** child -> (parent -> edge), so re-adding the same pair replaces it. */
|
||||
private readonly out = new Map<string, Map<string, LineageEdge>>();
|
||||
/** parent -> set of children, for descendant queries. */
|
||||
private readonly incoming = new Map<string, Set<string>>();
|
||||
|
||||
constructor(edges: readonly LineageEdge[] = []) {
|
||||
for (const edge of edges) {
|
||||
this.addEdge(edge);
|
||||
}
|
||||
}
|
||||
|
||||
/** Add (or replace) a derives-from edge. Throws on an invalid weight/self-edge. */
|
||||
addEdge(edge: LineageEdge): this {
|
||||
const validated = validateLineageEdge(edge);
|
||||
if (!validated.ok) {
|
||||
throw validated.error;
|
||||
}
|
||||
const e = validated.value;
|
||||
let parents = this.out.get(e.child);
|
||||
if (parents === undefined) {
|
||||
parents = new Map();
|
||||
this.out.set(e.child, parents);
|
||||
}
|
||||
parents.set(e.parent, e);
|
||||
let children = this.incoming.get(e.parent);
|
||||
if (children === undefined) {
|
||||
children = new Set();
|
||||
this.incoming.set(e.parent, children);
|
||||
}
|
||||
children.add(e.child);
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Direct ancestors `child` derives from. */
|
||||
parentsOf(child: string): readonly LineageEdge[] {
|
||||
return [...(this.out.get(child)?.values() ?? [])];
|
||||
}
|
||||
|
||||
/** Direct descendants that derive from `parent`. */
|
||||
childrenOf(parent: string): readonly string[] {
|
||||
return [...(this.incoming.get(parent) ?? [])];
|
||||
}
|
||||
|
||||
/** Every edge in the graph. */
|
||||
edges(): readonly LineageEdge[] {
|
||||
const all: LineageEdge[] = [];
|
||||
for (const parents of this.out.values()) {
|
||||
all.push(...parents.values());
|
||||
}
|
||||
return all;
|
||||
}
|
||||
|
||||
/** Every node id that appears as a child or a parent. */
|
||||
nodes(): readonly string[] {
|
||||
const ids = new Set<string>();
|
||||
for (const [child, parents] of this.out) {
|
||||
ids.add(child);
|
||||
for (const parent of parents.keys()) {
|
||||
ids.add(parent);
|
||||
}
|
||||
}
|
||||
return [...ids];
|
||||
}
|
||||
|
||||
/** All transitive ancestors of `id` (cycle-safe), nearest excluded of self. */
|
||||
ancestors(id: string): readonly string[] {
|
||||
const seen = new Set<string>();
|
||||
const visit = (node: string): void => {
|
||||
for (const edge of this.parentsOf(node)) {
|
||||
if (!seen.has(edge.parent)) {
|
||||
seen.add(edge.parent);
|
||||
visit(edge.parent);
|
||||
}
|
||||
}
|
||||
};
|
||||
visit(id);
|
||||
seen.delete(id);
|
||||
return [...seen];
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a node over-attributes — its outgoing edge weights sum past 100%,
|
||||
* which would leave it a negative self-share. Useful as a data-integrity check
|
||||
* before settling against the graph.
|
||||
*/
|
||||
isConserving(id: string): boolean {
|
||||
const total = this.parentsOf(id).reduce((sum, e) => sum + e.weight, 0);
|
||||
return total <= 1 + EPSILON;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fractional attribution of `rootId`'s value across its provenance lineage.
|
||||
*
|
||||
* Returns one {@link AttributionShare} per node that retains a positive share
|
||||
* (including the root itself). Shares sum to 1 when every node is conserving.
|
||||
*/
|
||||
export function computeAttributionShares(
|
||||
graph: LineageGraph,
|
||||
rootId: string,
|
||||
): readonly AttributionShare[] {
|
||||
const acc = new Map<string, { share: number; depth: number }>();
|
||||
|
||||
const add = (nodeId: string, share: number, depth: number): void => {
|
||||
const existing = acc.get(nodeId);
|
||||
if (existing === undefined) {
|
||||
acc.set(nodeId, { share, depth });
|
||||
} else {
|
||||
existing.share += share;
|
||||
existing.depth = Math.min(existing.depth, depth);
|
||||
}
|
||||
};
|
||||
|
||||
const recurse = (id: string, amount: number, depth: number, path: ReadonlySet<string>): void => {
|
||||
const edges = graph
|
||||
.parentsOf(id)
|
||||
.filter((e) => e.parent !== id && !path.has(e.parent));
|
||||
|
||||
let routed = 0;
|
||||
for (const edge of edges) {
|
||||
routed += amount * edge.weight;
|
||||
}
|
||||
add(id, amount - routed, depth);
|
||||
|
||||
const nextPath = new Set(path).add(id);
|
||||
for (const edge of edges) {
|
||||
recurse(edge.parent, amount * edge.weight, depth + 1, nextPath);
|
||||
}
|
||||
};
|
||||
|
||||
recurse(rootId, 1, 0, new Set());
|
||||
|
||||
return [...acc.entries()]
|
||||
.map(([nodeId, a]) => ({ nodeId, share: a.share, depth: a.depth }))
|
||||
.filter((s) => s.share > EPSILON)
|
||||
.sort((a, b) => a.depth - b.depth || a.nodeId.localeCompare(b.nodeId));
|
||||
}
|
||||
107
packages/attribution/src/proof.ts
Normal file
107
packages/attribution/src/proof.ts
Normal file
@ -0,0 +1,107 @@
|
||||
/**
|
||||
* Proof-of-citation.
|
||||
*
|
||||
* After an agent pays a citation toll, it can present a signed, expiring proof
|
||||
* to a downstream seller (or drop it in an audit log) attesting *which* sources
|
||||
* it cited and under which paid-access event — verifiable with a shared secret,
|
||||
* without trusting the agent or re-querying the settlement chain. The signature
|
||||
* is an HMAC-SHA256 over a canonical encoding of the claim, so two parties that
|
||||
* share the secret always agree on the bytes being signed.
|
||||
*/
|
||||
|
||||
import { createHmac, randomUUID, timingSafeEqual } from "node:crypto";
|
||||
import {
|
||||
type IsoTimestamp,
|
||||
type Result,
|
||||
SettleKitError,
|
||||
err,
|
||||
isPast,
|
||||
ok,
|
||||
toIso,
|
||||
} from "@settlekit/common";
|
||||
import type { CitationProof, IssueProofInput, ProofClaim } from "./types.js";
|
||||
|
||||
/**
|
||||
* Canonical encoding of a claim. Field order is fixed and `sourceIds` is sorted,
|
||||
* so the same logical claim always serializes to the same bytes regardless of
|
||||
* how the caller ordered things. Undefined optionals are omitted.
|
||||
*/
|
||||
function canonicalize(claim: ProofClaim): string {
|
||||
const ordered: Array<[string, unknown]> = [
|
||||
["agent", claim.agent],
|
||||
["sourceIds", [...claim.sourceIds].sort()],
|
||||
["accessId", claim.accessId],
|
||||
["issuedAt", claim.issuedAt],
|
||||
["nonce", claim.nonce],
|
||||
];
|
||||
if (claim.amountUsdc !== undefined) {
|
||||
ordered.push(["amountUsdc", claim.amountUsdc]);
|
||||
}
|
||||
if (claim.expiresAt !== undefined) {
|
||||
ordered.push(["expiresAt", claim.expiresAt]);
|
||||
}
|
||||
return JSON.stringify(ordered);
|
||||
}
|
||||
|
||||
/** HMAC-SHA256 of the canonical claim, hex-encoded. */
|
||||
export function signClaim(claim: ProofClaim, secret: string): string {
|
||||
return createHmac("sha256", secret).update(canonicalize(claim)).digest("hex");
|
||||
}
|
||||
|
||||
/** Attach a signature to a claim, producing a presentable {@link CitationProof}. */
|
||||
export function signCitationProof(claim: ProofClaim, secret: string): CitationProof {
|
||||
return { ...claim, signature: signClaim(claim, secret) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Build and sign a fresh proof. Generates the nonce and `issuedAt`/`expiresAt`
|
||||
* timestamps from `now`, then signs.
|
||||
*/
|
||||
export function issueCitationProof(
|
||||
input: IssueProofInput,
|
||||
secret: string,
|
||||
now: Date = new Date(),
|
||||
): CitationProof {
|
||||
const issuedAt: IsoTimestamp = toIso(now);
|
||||
const claim: ProofClaim = {
|
||||
agent: input.agent,
|
||||
sourceIds: input.sourceIds,
|
||||
accessId: input.accessId,
|
||||
...(input.amountUsdc !== undefined ? { amountUsdc: input.amountUsdc } : {}),
|
||||
issuedAt,
|
||||
...(input.ttlSeconds !== undefined
|
||||
? { expiresAt: toIso(new Date(now.getTime() + input.ttlSeconds * 1000)) }
|
||||
: {}),
|
||||
nonce: randomUUID(),
|
||||
};
|
||||
return signCitationProof(claim, secret);
|
||||
}
|
||||
|
||||
/** Constant-time comparison of two hex signatures of equal length. */
|
||||
function signaturesEqual(a: string, b: string): boolean {
|
||||
if (a.length !== b.length) {
|
||||
return false;
|
||||
}
|
||||
return timingSafeEqual(Buffer.from(a, "hex"), Buffer.from(b, "hex"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify a proof's signature and expiry. Returns the underlying claim on
|
||||
* success, or an `unauthorized` error when the signature is forged or the proof
|
||||
* has expired.
|
||||
*/
|
||||
export function verifyCitationProof(
|
||||
proof: CitationProof,
|
||||
secret: string,
|
||||
now: Date = new Date(),
|
||||
): Result<ProofClaim, SettleKitError> {
|
||||
const { signature, ...claim } = proof;
|
||||
const expected = signClaim(claim, secret);
|
||||
if (!signaturesEqual(signature, expected)) {
|
||||
return err(new SettleKitError({ code: "unauthorized", message: "invalid citation proof signature" }));
|
||||
}
|
||||
if (claim.expiresAt !== undefined && isPast(claim.expiresAt, now)) {
|
||||
return err(new SettleKitError({ code: "unauthorized", message: "citation proof expired" }));
|
||||
}
|
||||
return ok(claim);
|
||||
}
|
||||
96
packages/attribution/src/reuse-detector.ts
Normal file
96
packages/attribution/src/reuse-detector.ts
Normal file
@ -0,0 +1,96 @@
|
||||
/**
|
||||
* Reuse detection: did this generated text get grounded in a known source?
|
||||
*
|
||||
* Uses w-shingling (sliding windows of `k` words) and containment scoring: the
|
||||
* fraction of the *answer's* shingles that also appear in a candidate source.
|
||||
* Containment (answer ⊆ source) — rather than Jaccard — is the right shape here
|
||||
* because a short answer can be fully grounded in a long source without the two
|
||||
* shingle sets being similar in size. Cheap, deterministic, dependency-free; a
|
||||
* good first gate before charging a citation toll for implicit reuse.
|
||||
*/
|
||||
|
||||
import { createHash } from "node:crypto";
|
||||
import type { ReuseCandidate, ReuseMatch, ReuseOptions, ReuseReport } from "./types.js";
|
||||
|
||||
const DEFAULT_SHINGLE_SIZE = 4;
|
||||
const DEFAULT_THRESHOLD = 0.18;
|
||||
const DEFAULT_MIN_MATCHED = 2;
|
||||
|
||||
/** Lowercase, strip punctuation to spaces, collapse runs, and split to words. */
|
||||
export function tokenize(text: string): string[] {
|
||||
return text
|
||||
.toLowerCase()
|
||||
.replace(/[^\p{L}\p{N}]+/gu, " ")
|
||||
.trim()
|
||||
.split(/\s+/)
|
||||
.filter((t) => t.length > 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* The set of `k`-word shingles in `text`. For text shorter than `k`, the whole
|
||||
* token run is one shingle, so short answers still produce a usable signal.
|
||||
*/
|
||||
export function shingleSet(text: string, k: number = DEFAULT_SHINGLE_SIZE): Set<string> {
|
||||
const tokens = tokenize(text);
|
||||
const set = new Set<string>();
|
||||
if (tokens.length === 0) {
|
||||
return set;
|
||||
}
|
||||
const size = Math.max(1, Math.min(k, tokens.length));
|
||||
for (let i = 0; i + size <= tokens.length; i++) {
|
||||
set.add(tokens.slice(i, i + size).join(" "));
|
||||
}
|
||||
return set;
|
||||
}
|
||||
|
||||
/** Stable hash of the normalized token stream — an audit / dedupe key. */
|
||||
export function textFingerprint(text: string): string {
|
||||
return createHash("sha256").update(tokenize(text).join(" ")).digest("hex");
|
||||
}
|
||||
|
||||
/**
|
||||
* Score generated `text` against each candidate source and report which ones it
|
||||
* is grounded in. Matches are returned strongest-first.
|
||||
*/
|
||||
export function detectReuse(
|
||||
text: string,
|
||||
candidates: readonly ReuseCandidate[],
|
||||
options: ReuseOptions = {},
|
||||
): ReuseReport {
|
||||
const k = options.shingleSize ?? DEFAULT_SHINGLE_SIZE;
|
||||
const threshold = options.threshold ?? DEFAULT_THRESHOLD;
|
||||
const minMatched = options.minMatched ?? DEFAULT_MIN_MATCHED;
|
||||
|
||||
const answer = shingleSet(text, k);
|
||||
const total = answer.size;
|
||||
const textHash = textFingerprint(text);
|
||||
|
||||
if (total === 0) {
|
||||
return { textHash, total: 0, matches: [], grounded: false };
|
||||
}
|
||||
|
||||
const matches: ReuseMatch[] = [];
|
||||
for (const candidate of candidates) {
|
||||
const source = shingleSet(candidate.text, k);
|
||||
let matched = 0;
|
||||
for (const shingle of answer) {
|
||||
if (source.has(shingle)) {
|
||||
matched++;
|
||||
}
|
||||
}
|
||||
const score = matched / total;
|
||||
if (matched >= minMatched && score >= threshold) {
|
||||
matches.push({
|
||||
sourceId: candidate.id,
|
||||
...(candidate.wallet !== undefined ? { wallet: candidate.wallet } : {}),
|
||||
score,
|
||||
matched,
|
||||
total,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
matches.sort((a, b) => b.score - a.score || b.matched - a.matched || a.sourceId.localeCompare(b.sourceId));
|
||||
|
||||
return { textHash, total, matches, grounded: matches.length > 0 };
|
||||
}
|
||||
93
packages/attribution/src/store.ts
Normal file
93
packages/attribution/src/store.ts
Normal file
@ -0,0 +1,93 @@
|
||||
/**
|
||||
* Persistence interfaces for attribution.
|
||||
*
|
||||
* {@link LineageStore} persists the provenance DAG; {@link loadLineageGraph}
|
||||
* snapshots it into an in-memory {@link LineageGraph} for the (synchronous)
|
||||
* attribution walk. {@link ProofStore} records issued proofs for audit and
|
||||
* gives stateless sellers replay protection via {@link ProofStore.consume}.
|
||||
* In-memory implementations live here for dev/tests; the Pg-backed stores live
|
||||
* in @settlekit/persistence (over the `lepton_*` tables).
|
||||
*/
|
||||
|
||||
import { LineageGraph } from "./lineage-graph.js";
|
||||
import type { CitationProof, LineageEdge } from "./types.js";
|
||||
|
||||
/** Async store for provenance lineage edges. */
|
||||
export interface LineageStore {
|
||||
/** Insert or replace the edge for a (child, parent) pair. */
|
||||
addEdge(edge: LineageEdge): Promise<LineageEdge>;
|
||||
/** Direct ancestors `child` derives from. */
|
||||
parentsOf(child: string): Promise<LineageEdge[]>;
|
||||
/** Direct descendants that derive from `parent`. */
|
||||
childrenOf(parent: string): Promise<LineageEdge[]>;
|
||||
/** Every edge (used to snapshot the graph for the attribution walk). */
|
||||
allEdges(): Promise<LineageEdge[]>;
|
||||
}
|
||||
|
||||
/** Async store for issued proofs-of-citation. */
|
||||
export interface ProofStore {
|
||||
record(proof: CitationProof): Promise<CitationProof>;
|
||||
findByNonce(nonce: string): Promise<CitationProof | undefined>;
|
||||
listByAccess(accessId: string): Promise<CitationProof[]>;
|
||||
/**
|
||||
* Atomically claim a nonce: returns `true` the first time it is seen and
|
||||
* `false` on every replay. A seller calls this after verifying the signature
|
||||
* to reject a proof that is being presented twice.
|
||||
*/
|
||||
consume(nonce: string): Promise<boolean>;
|
||||
}
|
||||
|
||||
/** Snapshot a {@link LineageStore} into a synchronous {@link LineageGraph}. */
|
||||
export async function loadLineageGraph(store: LineageStore): Promise<LineageGraph> {
|
||||
return new LineageGraph(await store.allEdges());
|
||||
}
|
||||
|
||||
/** In-memory {@link LineageStore} (dev/tests). */
|
||||
export class InMemoryLineageStore implements LineageStore {
|
||||
/** `${child}|${parent}` -> edge, so re-adding a pair replaces it. */
|
||||
private readonly edges = new Map<string, LineageEdge>();
|
||||
|
||||
async addEdge(edge: LineageEdge): Promise<LineageEdge> {
|
||||
this.edges.set(`${edge.child}|${edge.parent}`, edge);
|
||||
return edge;
|
||||
}
|
||||
|
||||
async parentsOf(child: string): Promise<LineageEdge[]> {
|
||||
return [...this.edges.values()].filter((e) => e.child === child);
|
||||
}
|
||||
|
||||
async childrenOf(parent: string): Promise<LineageEdge[]> {
|
||||
return [...this.edges.values()].filter((e) => e.parent === parent);
|
||||
}
|
||||
|
||||
async allEdges(): Promise<LineageEdge[]> {
|
||||
return [...this.edges.values()];
|
||||
}
|
||||
}
|
||||
|
||||
/** In-memory {@link ProofStore} (dev/tests). */
|
||||
export class InMemoryProofStore implements ProofStore {
|
||||
private readonly byNonce = new Map<string, CitationProof>();
|
||||
private readonly consumed = new Set<string>();
|
||||
|
||||
async record(proof: CitationProof): Promise<CitationProof> {
|
||||
this.byNonce.set(proof.nonce, proof);
|
||||
return proof;
|
||||
}
|
||||
|
||||
async findByNonce(nonce: string): Promise<CitationProof | undefined> {
|
||||
return this.byNonce.get(nonce);
|
||||
}
|
||||
|
||||
async listByAccess(accessId: string): Promise<CitationProof[]> {
|
||||
return [...this.byNonce.values()].filter((p) => p.accessId === accessId);
|
||||
}
|
||||
|
||||
async consume(nonce: string): Promise<boolean> {
|
||||
if (this.consumed.has(nonce)) {
|
||||
return false;
|
||||
}
|
||||
this.consumed.add(nonce);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
138
packages/attribution/src/types.ts
Normal file
138
packages/attribution/src/types.ts
Normal file
@ -0,0 +1,138 @@
|
||||
/**
|
||||
* Attribution domain types.
|
||||
*
|
||||
* The citation toll (@settlekit/citation-toll) charges an agent that *explicitly*
|
||||
* fetches a gated source. Attribution closes the other half of the loop:
|
||||
*
|
||||
* - **reuse detection** — given the text an agent actually produced, decide
|
||||
* which sources it was grounded in, so the toll can be charged for *implicit*
|
||||
* reuse, not just deliberate fetches;
|
||||
* - **provenance lineage** — a generic weighted DAG of "this work derives from
|
||||
* that work", so an attributed payment fans recursively through every
|
||||
* ancestor (the citation-toll split, expressed as fractional shares that any
|
||||
* consumer — money, credit, ranking — can use);
|
||||
* - **proof-of-citation** — a signed, expiring token an agent presents to a
|
||||
* seller (or an audit log) attesting that it cited and paid for a set of
|
||||
* sources, verifiable without trusting the agent.
|
||||
*
|
||||
* Everything here is pure: no I/O, no clocks except the ones you pass in.
|
||||
*/
|
||||
|
||||
import type { IsoTimestamp } from "@settlekit/common";
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* Provenance lineage */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
/**
|
||||
* A directed "derives-from" edge in the provenance graph: `child` attributes
|
||||
* `weight` of its value to `parent`. `weight` is a fraction in (0, 1]; the sum
|
||||
* of a child's outgoing weights must not exceed 1 (the child keeps the rest).
|
||||
*/
|
||||
export interface LineageEdge {
|
||||
/** The derived work. */
|
||||
child: string;
|
||||
/** The ancestor the child is grounded in. */
|
||||
parent: string;
|
||||
/** Fraction of `child`'s value routed to `parent`, in (0, 1]. */
|
||||
weight: number;
|
||||
}
|
||||
|
||||
/** A node's fractional share of some root work's total attributed value. */
|
||||
export interface AttributionShare {
|
||||
nodeId: string;
|
||||
/** Fraction of the root's value attributed here, in (0, 1]. */
|
||||
share: number;
|
||||
/** Shortest distance from the root (0 = the root itself). */
|
||||
depth: number;
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* Reuse detection */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
/** A candidate source the detector compares generated text against. */
|
||||
export interface ReuseCandidate {
|
||||
/** Source id (matches a citation-toll source / lineage node). */
|
||||
id: string;
|
||||
/** The source text the agent may have been grounded in. */
|
||||
text: string;
|
||||
/** Optional payout wallet, carried through to the match for convenience. */
|
||||
wallet?: string;
|
||||
}
|
||||
|
||||
/** A detected grounding of generated text in one candidate source. */
|
||||
export interface ReuseMatch {
|
||||
sourceId: string;
|
||||
wallet?: string;
|
||||
/**
|
||||
* Containment score in [0, 1]: the fraction of the generated text's shingles
|
||||
* that also appear in this source. 1.0 means the answer is fully covered by
|
||||
* the source.
|
||||
*/
|
||||
score: number;
|
||||
/** How many of the generated text's shingles this source covers. */
|
||||
matched: number;
|
||||
/** Total shingles in the generated text (the score denominator). */
|
||||
total: number;
|
||||
}
|
||||
|
||||
/** The result of checking generated text against a set of candidates. */
|
||||
export interface ReuseReport {
|
||||
/** Stable hash of the normalized generated text (audit / dedupe key). */
|
||||
textHash: string;
|
||||
/** Total shingles extracted from the generated text. */
|
||||
total: number;
|
||||
/** Candidates that cleared the detection threshold, strongest first. */
|
||||
matches: readonly ReuseMatch[];
|
||||
/** True when at least one candidate cleared the threshold. */
|
||||
grounded: boolean;
|
||||
}
|
||||
|
||||
/** Tunables for {@link detectReuse}. */
|
||||
export interface ReuseOptions {
|
||||
/** Words per shingle. Default 4. Falls back to single words for short text. */
|
||||
shingleSize?: number;
|
||||
/** Minimum containment score to count as a match. Default 0.18. */
|
||||
threshold?: number;
|
||||
/** Minimum number of matched shingles to count as a match. Default 2. */
|
||||
minMatched?: number;
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* Proof-of-citation */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
/** The signed claim payload — what the agent attests to. */
|
||||
export interface ProofClaim {
|
||||
/** The agent / payer presenting the proof. */
|
||||
agent: string;
|
||||
/** The cited source ids (order-insensitive; canonicalized on sign). */
|
||||
sourceIds: readonly string[];
|
||||
/** The paid-access event these citations were settled under. */
|
||||
accessId: string;
|
||||
/** Total settled, decimal USDC string, if a payment backed the citation. */
|
||||
amountUsdc?: string;
|
||||
/** When the proof was issued. */
|
||||
issuedAt: IsoTimestamp;
|
||||
/** When the proof stops being valid (omitted = no expiry). */
|
||||
expiresAt?: IsoTimestamp;
|
||||
/** One-time value for replay protection. */
|
||||
nonce: string;
|
||||
}
|
||||
|
||||
/** A signed proof-of-citation an agent presents to a seller / audit log. */
|
||||
export interface CitationProof extends ProofClaim {
|
||||
/** HMAC-SHA256 of the canonical claim, hex-encoded. */
|
||||
signature: string;
|
||||
}
|
||||
|
||||
/** Input to {@link issueCitationProof}. */
|
||||
export interface IssueProofInput {
|
||||
agent: string;
|
||||
sourceIds: readonly string[];
|
||||
accessId: string;
|
||||
amountUsdc?: string;
|
||||
/** Time-to-live in seconds. Omit for a proof that never expires. */
|
||||
ttlSeconds?: number;
|
||||
}
|
||||
107
packages/attribution/test/lineage-graph.test.ts
Normal file
107
packages/attribution/test/lineage-graph.test.ts
Normal file
@ -0,0 +1,107 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
LineageGraph,
|
||||
computeAttributionShares,
|
||||
validateLineageEdge,
|
||||
} from "../src/lineage-graph.js";
|
||||
|
||||
const sum = (shares: readonly { share: number }[]): number =>
|
||||
shares.reduce((s, x) => s + x.share, 0);
|
||||
const shareOf = (shares: readonly { nodeId: string; share: number }[], id: string): number =>
|
||||
shares.find((s) => s.nodeId === id)?.share ?? 0;
|
||||
|
||||
describe("validateLineageEdge", () => {
|
||||
it("rejects self-edges", () => {
|
||||
const r = validateLineageEdge({ child: "a", parent: "a", weight: 0.5 });
|
||||
expect(r.ok).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects weights outside (0, 1]", () => {
|
||||
expect(validateLineageEdge({ child: "a", parent: "b", weight: 0 }).ok).toBe(false);
|
||||
expect(validateLineageEdge({ child: "a", parent: "b", weight: -0.1 }).ok).toBe(false);
|
||||
expect(validateLineageEdge({ child: "a", parent: "b", weight: 1.5 }).ok).toBe(false);
|
||||
expect(validateLineageEdge({ child: "a", parent: "b", weight: 1 }).ok).toBe(true);
|
||||
});
|
||||
|
||||
it("addEdge throws on an invalid weight", () => {
|
||||
expect(() => new LineageGraph().addEdge({ child: "a", parent: "b", weight: 2 })).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("computeAttributionShares", () => {
|
||||
it("attributes everything to a root with no ancestors", () => {
|
||||
const shares = computeAttributionShares(new LineageGraph(), "leaf");
|
||||
expect(shares).toEqual([{ nodeId: "leaf", share: 1, depth: 0 }]);
|
||||
});
|
||||
|
||||
it("routes the configured fraction to a direct ancestor", () => {
|
||||
const g = new LineageGraph([{ child: "answer", parent: "src", weight: 0.4 }]);
|
||||
const shares = computeAttributionShares(g, "answer");
|
||||
expect(shareOf(shares, "answer")).toBeCloseTo(0.6, 9);
|
||||
expect(shareOf(shares, "src")).toBeCloseTo(0.4, 9);
|
||||
expect(sum(shares)).toBeCloseTo(1, 9);
|
||||
});
|
||||
|
||||
it("recurses through a multi-hop lineage and conserves the whole", () => {
|
||||
// answer -0.5-> remix -0.5-> original
|
||||
const g = new LineageGraph([
|
||||
{ child: "answer", parent: "remix", weight: 0.5 },
|
||||
{ child: "remix", parent: "original", weight: 0.5 },
|
||||
]);
|
||||
const shares = computeAttributionShares(g, "answer");
|
||||
expect(shareOf(shares, "answer")).toBeCloseTo(0.5, 9);
|
||||
expect(shareOf(shares, "remix")).toBeCloseTo(0.25, 9);
|
||||
expect(shareOf(shares, "original")).toBeCloseTo(0.25, 9);
|
||||
expect(sum(shares)).toBeCloseTo(1, 9);
|
||||
});
|
||||
|
||||
it("accumulates a diamond ancestor from both paths and records shallowest depth", () => {
|
||||
// answer derives from b and c (0.5 each); both derive fully from shared 'a'
|
||||
const g = new LineageGraph([
|
||||
{ child: "answer", parent: "b", weight: 0.5 },
|
||||
{ child: "answer", parent: "c", weight: 0.5 },
|
||||
{ child: "b", parent: "a", weight: 1 },
|
||||
{ child: "c", parent: "a", weight: 1 },
|
||||
]);
|
||||
const shares = computeAttributionShares(g, "answer");
|
||||
// answer keeps nothing (routes 100%), b and c keep nothing (route 100% to a)
|
||||
expect(shareOf(shares, "a")).toBeCloseTo(1, 9);
|
||||
expect(shares.find((s) => s.nodeId === "a")?.depth).toBe(2);
|
||||
expect(sum(shares)).toBeCloseTo(1, 9);
|
||||
});
|
||||
|
||||
it("does not loop forever on a cycle", () => {
|
||||
const g = new LineageGraph([
|
||||
{ child: "a", parent: "b", weight: 0.5 },
|
||||
{ child: "b", parent: "a", weight: 0.5 },
|
||||
]);
|
||||
const shares = computeAttributionShares(g, "a");
|
||||
expect(sum(shares)).toBeGreaterThan(0);
|
||||
expect(shares.length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("LineageGraph queries", () => {
|
||||
const g = new LineageGraph([
|
||||
{ child: "answer", parent: "remix", weight: 0.5 },
|
||||
{ child: "remix", parent: "original", weight: 0.5 },
|
||||
]);
|
||||
|
||||
it("walks transitive ancestors", () => {
|
||||
expect([...g.ancestors("answer")].sort()).toEqual(["original", "remix"]);
|
||||
expect(g.ancestors("original")).toEqual([]);
|
||||
});
|
||||
|
||||
it("reports direct children", () => {
|
||||
expect(g.childrenOf("original")).toEqual(["remix"]);
|
||||
});
|
||||
|
||||
it("flags over-attribution", () => {
|
||||
const over = new LineageGraph([
|
||||
{ child: "x", parent: "p", weight: 0.7 },
|
||||
{ child: "x", parent: "q", weight: 0.7 },
|
||||
]);
|
||||
expect(over.isConserving("x")).toBe(false);
|
||||
expect(g.isConserving("answer")).toBe(true);
|
||||
});
|
||||
});
|
||||
80
packages/attribution/test/proof.test.ts
Normal file
80
packages/attribution/test/proof.test.ts
Normal file
@ -0,0 +1,80 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { isErr, isOk } from "@settlekit/common";
|
||||
import {
|
||||
issueCitationProof,
|
||||
signClaim,
|
||||
signCitationProof,
|
||||
verifyCitationProof,
|
||||
} from "../src/proof.js";
|
||||
import type { ProofClaim } from "../src/types.js";
|
||||
|
||||
const SECRET = "shared-toll-secret";
|
||||
|
||||
const claim: ProofClaim = {
|
||||
agent: "agent_research_1",
|
||||
sourceIds: ["src_b", "src_a"],
|
||||
accessId: "acc_42",
|
||||
amountUsdc: "0.0008",
|
||||
issuedAt: "2026-06-19T00:00:00.000Z",
|
||||
nonce: "nonce-1",
|
||||
};
|
||||
|
||||
describe("signCitationProof / verifyCitationProof", () => {
|
||||
it("round-trips a valid proof", () => {
|
||||
const proof = signCitationProof(claim, SECRET);
|
||||
const result = verifyCitationProof(proof, SECRET);
|
||||
expect(isOk(result)).toBe(true);
|
||||
if (isOk(result)) {
|
||||
expect(result.value.accessId).toBe("acc_42");
|
||||
}
|
||||
});
|
||||
|
||||
it("is canonical: sourceId order does not change the signature", () => {
|
||||
const a = signClaim(claim, SECRET);
|
||||
const b = signClaim({ ...claim, sourceIds: ["src_a", "src_b"] }, SECRET);
|
||||
expect(a).toBe(b);
|
||||
});
|
||||
|
||||
it("rejects a tampered claim", () => {
|
||||
const proof = signCitationProof(claim, SECRET);
|
||||
const tampered = { ...proof, sourceIds: ["src_a", "src_b", "src_smuggled"] };
|
||||
expect(isErr(verifyCitationProof(tampered, SECRET))).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects the wrong secret", () => {
|
||||
const proof = signCitationProof(claim, SECRET);
|
||||
expect(isErr(verifyCitationProof(proof, "other-secret"))).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("issueCitationProof", () => {
|
||||
it("stamps issuedAt, an expiry, and a nonce", () => {
|
||||
const now = new Date("2026-06-19T12:00:00.000Z");
|
||||
const proof = issueCitationProof(
|
||||
{ agent: "a1", sourceIds: ["s1"], accessId: "acc_1", ttlSeconds: 300 },
|
||||
SECRET,
|
||||
now,
|
||||
);
|
||||
expect(proof.issuedAt).toBe("2026-06-19T12:00:00.000Z");
|
||||
expect(proof.expiresAt).toBe("2026-06-19T12:05:00.000Z");
|
||||
expect(proof.nonce).toMatch(/[0-9a-f-]{36}/);
|
||||
expect(isOk(verifyCitationProof(proof, SECRET, now))).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects an expired proof", () => {
|
||||
const now = new Date("2026-06-19T12:00:00.000Z");
|
||||
const proof = issueCitationProof(
|
||||
{ agent: "a1", sourceIds: ["s1"], accessId: "acc_1", ttlSeconds: 60 },
|
||||
SECRET,
|
||||
now,
|
||||
);
|
||||
const later = new Date("2026-06-19T12:02:00.000Z");
|
||||
const result = verifyCitationProof(proof, SECRET, later);
|
||||
expect(isErr(result)).toBe(true);
|
||||
});
|
||||
|
||||
it("omits expiry when no ttl is given", () => {
|
||||
const proof = issueCitationProof({ agent: "a1", sourceIds: ["s1"], accessId: "acc_1" }, SECRET);
|
||||
expect(proof.expiresAt).toBeUndefined();
|
||||
});
|
||||
});
|
||||
71
packages/attribution/test/reuse-detector.test.ts
Normal file
71
packages/attribution/test/reuse-detector.test.ts
Normal file
@ -0,0 +1,71 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { detectReuse, shingleSet, textFingerprint, tokenize } from "../src/reuse-detector.js";
|
||||
|
||||
const ARTICLE = `The Arc network settles USDC nanopayments gas-free using Gateway
|
||||
burn intents, so an agent can pay a fraction of a cent per citation and have it
|
||||
batched into a single on-chain settlement.`;
|
||||
|
||||
describe("tokenize / shingleSet", () => {
|
||||
it("lowercases and strips punctuation", () => {
|
||||
expect(tokenize("Hello, World! Foo-bar")).toEqual(["hello", "world", "foo", "bar"]);
|
||||
});
|
||||
|
||||
it("produces sliding k-word shingles", () => {
|
||||
const s = shingleSet("a b c d", 2);
|
||||
expect([...s].sort()).toEqual(["a b", "b c", "c d"]);
|
||||
});
|
||||
|
||||
it("falls back to one shingle for text shorter than k", () => {
|
||||
expect([...shingleSet("two words", 4)]).toEqual(["two words"]);
|
||||
});
|
||||
|
||||
it("returns an empty set for empty text", () => {
|
||||
expect(shingleSet(" ", 4).size).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("textFingerprint", () => {
|
||||
it("is stable across whitespace and case differences", () => {
|
||||
expect(textFingerprint("Hello World")).toBe(textFingerprint("hello world"));
|
||||
});
|
||||
});
|
||||
|
||||
describe("detectReuse", () => {
|
||||
it("flags an answer copied from a source", () => {
|
||||
const answer = "an agent can pay a fraction of a cent per citation and have it batched";
|
||||
const report = detectReuse(answer, [
|
||||
{ id: "src_arc", text: ARTICLE, wallet: "0xauthor" },
|
||||
{ id: "src_other", text: "completely unrelated text about gardening tomatoes" },
|
||||
]);
|
||||
expect(report.grounded).toBe(true);
|
||||
expect(report.matches[0]?.sourceId).toBe("src_arc");
|
||||
expect(report.matches[0]?.wallet).toBe("0xauthor");
|
||||
expect(report.matches[0]?.score).toBeGreaterThan(0.5);
|
||||
// the unrelated source should not clear the threshold
|
||||
expect(report.matches.some((m) => m.sourceId === "src_other")).toBe(false);
|
||||
});
|
||||
|
||||
it("does not flag original text", () => {
|
||||
const report = detectReuse(
|
||||
"a wholly independent sentence sharing no phrases with the corpus whatsoever",
|
||||
[{ id: "src_arc", text: ARTICLE }],
|
||||
);
|
||||
expect(report.grounded).toBe(false);
|
||||
expect(report.matches).toEqual([]);
|
||||
});
|
||||
|
||||
it("handles empty generated text", () => {
|
||||
const report = detectReuse("", [{ id: "src_arc", text: ARTICLE }]);
|
||||
expect(report.total).toBe(0);
|
||||
expect(report.grounded).toBe(false);
|
||||
});
|
||||
|
||||
it("ranks the strongest grounding first", () => {
|
||||
const answer = "the arc network settles usdc nanopayments gas free using gateway burn intents";
|
||||
const report = detectReuse(answer, [
|
||||
{ id: "weak", text: "the arc network is interesting" },
|
||||
{ id: "strong", text: ARTICLE },
|
||||
]);
|
||||
expect(report.matches[0]?.sourceId).toBe("strong");
|
||||
});
|
||||
});
|
||||
42
packages/attribution/test/store.test.ts
Normal file
42
packages/attribution/test/store.test.ts
Normal file
@ -0,0 +1,42 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
InMemoryLineageStore,
|
||||
InMemoryProofStore,
|
||||
loadLineageGraph,
|
||||
} from "../src/store.js";
|
||||
import { computeAttributionShares } from "../src/lineage-graph.js";
|
||||
import { issueCitationProof } from "../src/proof.js";
|
||||
|
||||
describe("InMemoryLineageStore", () => {
|
||||
it("persists edges, dedupes a pair, and snapshots into a graph", async () => {
|
||||
const store = new InMemoryLineageStore();
|
||||
await store.addEdge({ child: "answer", parent: "src", weight: 0.3 });
|
||||
await store.addEdge({ child: "answer", parent: "src", weight: 0.4 }); // replaces
|
||||
await store.addEdge({ child: "src", parent: "root", weight: 0.5 });
|
||||
|
||||
expect((await store.parentsOf("answer")).length).toBe(1);
|
||||
expect((await store.parentsOf("answer"))[0]?.weight).toBe(0.4);
|
||||
expect((await store.childrenOf("root")).map((e) => e.child)).toEqual(["src"]);
|
||||
|
||||
const graph = await loadLineageGraph(store);
|
||||
const shares = computeAttributionShares(graph, "answer");
|
||||
expect(shares.reduce((s, x) => s + x.share, 0)).toBeCloseTo(1, 9);
|
||||
expect(shares.map((s) => s.nodeId).sort()).toEqual(["answer", "root", "src"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("InMemoryProofStore", () => {
|
||||
it("records and finds proofs by nonce and access", async () => {
|
||||
const store = new InMemoryProofStore();
|
||||
const proof = issueCitationProof({ agent: "a1", sourceIds: ["s1"], accessId: "acc_1" }, "secret");
|
||||
await store.record(proof);
|
||||
expect((await store.findByNonce(proof.nonce))?.accessId).toBe("acc_1");
|
||||
expect((await store.listByAccess("acc_1")).length).toBe(1);
|
||||
});
|
||||
|
||||
it("consume() succeeds once then rejects replays", async () => {
|
||||
const store = new InMemoryProofStore();
|
||||
expect(await store.consume("nonce-x")).toBe(true);
|
||||
expect(await store.consume("nonce-x")).toBe(false);
|
||||
});
|
||||
});
|
||||
11
packages/attribution/tsconfig.json
Normal file
11
packages/attribution/tsconfig.json
Normal file
@ -0,0 +1,11 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": "./src",
|
||||
"outDir": "./dist",
|
||||
"composite": true
|
||||
},
|
||||
"references": [{ "path": "../common" }],
|
||||
"include": ["src/**/*"],
|
||||
"exclude": ["dist", "node_modules", "**/*.test.ts"]
|
||||
}
|
||||
@ -63,10 +63,12 @@ export function createBundle(input: CreateBundleInput): Bundle {
|
||||
}
|
||||
|
||||
/**
|
||||
* Synchronous lookup of whether a product id exists/belongs to the bundle's
|
||||
* organization. Injected so validation stays decoupled from the product store.
|
||||
* Lookup of whether a product id exists/belongs to the bundle's organization.
|
||||
* Injected so validation stays decoupled from the product store. May be async
|
||||
* so it can consult a database directly — never a process-local cache, which
|
||||
* goes stale across instances under horizontal scaling.
|
||||
*/
|
||||
export type ProductExistsLookup = (productId: string) => boolean;
|
||||
export type ProductExistsLookup = (productId: string) => boolean | Promise<boolean>;
|
||||
|
||||
/** Input for {@link validateBundle}. */
|
||||
export interface ValidateBundleInput {
|
||||
@ -83,7 +85,9 @@ export interface ValidateBundleInput {
|
||||
*
|
||||
* Returns a {@link Result} so callers can branch without exceptions.
|
||||
*/
|
||||
export function validateBundle(input: ValidateBundleInput): Result<true, SettleKitError> {
|
||||
export async function validateBundle(
|
||||
input: ValidateBundleInput,
|
||||
): Promise<Result<true, SettleKitError>> {
|
||||
const { bundle, productExists } = input;
|
||||
|
||||
if (bundle.productIds.length === 0) {
|
||||
@ -104,7 +108,7 @@ export function validateBundle(input: ValidateBundleInput): Result<true, SettleK
|
||||
}
|
||||
seen.add(productId);
|
||||
|
||||
if (!productExists(productId)) {
|
||||
if (!(await productExists(productId))) {
|
||||
return err(
|
||||
new SettleKitError({
|
||||
code: "not_found",
|
||||
|
||||
@ -61,7 +61,7 @@ export class BundleService {
|
||||
now: request.now,
|
||||
});
|
||||
|
||||
const validation = validateBundle({ bundle, productExists: this.productExists });
|
||||
const validation = await validateBundle({ bundle, productExists: this.productExists });
|
||||
if (isErr(validation)) {
|
||||
return err(validation.error);
|
||||
}
|
||||
|
||||
@ -11,7 +11,7 @@ const knownProducts = new Set(["prod_a", "prod_b"]);
|
||||
const productExists = (id: string): boolean => knownProducts.has(id);
|
||||
|
||||
describe("validateBundle", () => {
|
||||
it("rejects empty bundles", () => {
|
||||
it("rejects empty bundles", async () => {
|
||||
const bundle = createBundle({
|
||||
merchantId: "m",
|
||||
organizationId: "o",
|
||||
@ -19,28 +19,28 @@ describe("validateBundle", () => {
|
||||
productIds: [],
|
||||
price: money("0"),
|
||||
});
|
||||
const result = validateBundle({ bundle, productExists });
|
||||
const result = await validateBundle({ bundle, productExists });
|
||||
expect(isErr(result)).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects self-references (cycles)", () => {
|
||||
const result = validateBundle({
|
||||
it("rejects self-references (cycles)", async () => {
|
||||
const result = await validateBundle({
|
||||
bundle: { id: "bndl_x", productIds: ["bndl_x"] },
|
||||
productExists: () => true,
|
||||
});
|
||||
expect(isErr(result)).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects duplicate products", () => {
|
||||
const result = validateBundle({
|
||||
it("rejects duplicate products", async () => {
|
||||
const result = await validateBundle({
|
||||
bundle: { id: "bndl_x", productIds: ["prod_a", "prod_a"] },
|
||||
productExists,
|
||||
});
|
||||
expect(isErr(result)).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects unknown products", () => {
|
||||
const result = validateBundle({
|
||||
it("rejects unknown products", async () => {
|
||||
const result = await validateBundle({
|
||||
bundle: { id: "bndl_x", productIds: ["prod_a", "prod_missing"] },
|
||||
productExists,
|
||||
});
|
||||
@ -50,8 +50,8 @@ describe("validateBundle", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("accepts a valid bundle", () => {
|
||||
const result = validateBundle({
|
||||
it("accepts a valid bundle", async () => {
|
||||
const result = await validateBundle({
|
||||
bundle: { id: "bndl_x", productIds: ["prod_a", "prod_b"] },
|
||||
productExists,
|
||||
});
|
||||
|
||||
@ -34,6 +34,8 @@ import {
|
||||
leptonPayeeSplits,
|
||||
leptonSettlements,
|
||||
leptonNonces,
|
||||
leptonLineageEdges,
|
||||
leptonCitationProofs,
|
||||
} from "./lepton.js";
|
||||
import {
|
||||
organizations,
|
||||
@ -206,6 +208,8 @@ export const schema = {
|
||||
leptonPayeeSplits,
|
||||
leptonSettlements,
|
||||
leptonNonces,
|
||||
leptonLineageEdges,
|
||||
leptonCitationProofs,
|
||||
} as const;
|
||||
|
||||
/** The static type of the SettleKit schema object. */
|
||||
|
||||
@ -220,6 +220,43 @@ export const leptonSettlements = pgTable(
|
||||
}),
|
||||
);
|
||||
|
||||
/** A provenance "derives-from" edge: `childId` routes `weight` of its value to
|
||||
* `parentId`. The canonical {@link LineageEdge} lives in `metadata.__doc`. */
|
||||
export const leptonLineageEdges = pgTable(
|
||||
"lepton_lineage_edges",
|
||||
{
|
||||
id: idColumn(),
|
||||
childId: text("child_id").notNull(),
|
||||
parentId: text("parent_id").notNull(),
|
||||
metadata: metadataColumn(),
|
||||
createdAt: requiredTimestamp("created_at"),
|
||||
},
|
||||
(t) => ({
|
||||
edgeIdx: uniqueIndex("lepton_lineage_edges_pair_idx").on(t.childId, t.parentId),
|
||||
childIdx: index("lepton_lineage_edges_child_idx").on(t.childId),
|
||||
parentIdx: index("lepton_lineage_edges_parent_idx").on(t.parentId),
|
||||
}),
|
||||
);
|
||||
|
||||
/** A signed proof-of-citation an agent presented. `consumed` gives stateless
|
||||
* sellers replay protection; the canonical proof lives in `metadata.__doc`. */
|
||||
export const leptonCitationProofs = pgTable(
|
||||
"lepton_citation_proofs",
|
||||
{
|
||||
id: idColumn(),
|
||||
nonce: text("nonce").notNull(),
|
||||
agent: text("agent").notNull(),
|
||||
accessId: text("access_id").notNull(),
|
||||
consumed: boolean("consumed").notNull().default(false),
|
||||
metadata: metadataColumn(),
|
||||
createdAt: requiredTimestamp("created_at"),
|
||||
},
|
||||
(t) => ({
|
||||
nonceIdx: uniqueIndex("lepton_citation_proofs_nonce_idx").on(t.nonce),
|
||||
accessIdx: index("lepton_citation_proofs_access_idx").on(t.accessId),
|
||||
}),
|
||||
);
|
||||
|
||||
/** One-time x402 nonces for replay protection. */
|
||||
export const leptonNonces = pgTable(
|
||||
"lepton_nonces",
|
||||
|
||||
@ -142,6 +142,8 @@ const EXPECTED_TABLE_NAMES = [
|
||||
"lepton_payee_splits",
|
||||
"lepton_settlements",
|
||||
"lepton_nonces",
|
||||
"lepton_lineage_edges",
|
||||
"lepton_citation_proofs",
|
||||
] as const;
|
||||
|
||||
describe("schema table coverage", () => {
|
||||
|
||||
@ -19,6 +19,7 @@
|
||||
"@settlekit/common": "workspace:*",
|
||||
"@settlekit/database": "workspace:*",
|
||||
"@settlekit/settlement-core": "workspace:*",
|
||||
"@settlekit/attribution": "workspace:*",
|
||||
"@settlekit/citation-toll": "workspace:*",
|
||||
"@settlekit/payee-registry": "workspace:*",
|
||||
"@settlekit/streaming": "workspace:*",
|
||||
|
||||
122
packages/persistence/src/attribution-store.ts
Normal file
122
packages/persistence/src/attribution-store.ts
Normal file
@ -0,0 +1,122 @@
|
||||
/**
|
||||
* Postgres-backed attribution stores: the provenance lineage graph
|
||||
* (`lepton_lineage_edges`) and issued proofs-of-citation
|
||||
* (`lepton_citation_proofs`). Canonical entities live in `metadata.__doc`;
|
||||
* columns are projections for graph queries and replay protection.
|
||||
*/
|
||||
|
||||
import {
|
||||
and,
|
||||
eq,
|
||||
type Database,
|
||||
leptonCitationProofs,
|
||||
leptonLineageEdges,
|
||||
} from "@settlekit/database";
|
||||
import { uuid } from "@settlekit/common";
|
||||
import type {
|
||||
CitationProof,
|
||||
LineageEdge,
|
||||
LineageStore,
|
||||
ProofStore,
|
||||
} from "@settlekit/attribution";
|
||||
import { packDoc, unpackDoc, unpackDocs } from "./codec.js";
|
||||
|
||||
export class PgLineageStore implements LineageStore {
|
||||
constructor(
|
||||
private readonly db: Database,
|
||||
private readonly now: () => Date = () => new Date(),
|
||||
) {}
|
||||
|
||||
async addEdge(edge: LineageEdge): Promise<LineageEdge> {
|
||||
const projection = {
|
||||
childId: edge.child,
|
||||
parentId: edge.parent,
|
||||
metadata: packDoc(edge),
|
||||
createdAt: this.now(),
|
||||
};
|
||||
await this.db
|
||||
.insert(leptonLineageEdges)
|
||||
.values({ id: `lin_${uuid().replace(/-/g, "").slice(0, 24)}`, ...projection })
|
||||
.onConflictDoUpdate({
|
||||
target: [leptonLineageEdges.childId, leptonLineageEdges.parentId],
|
||||
set: { metadata: projection.metadata },
|
||||
});
|
||||
return edge;
|
||||
}
|
||||
|
||||
async parentsOf(child: string): Promise<LineageEdge[]> {
|
||||
const rows = await this.db
|
||||
.select({ metadata: leptonLineageEdges.metadata })
|
||||
.from(leptonLineageEdges)
|
||||
.where(eq(leptonLineageEdges.childId, child));
|
||||
return unpackDocs<LineageEdge>(rows);
|
||||
}
|
||||
|
||||
async childrenOf(parent: string): Promise<LineageEdge[]> {
|
||||
const rows = await this.db
|
||||
.select({ metadata: leptonLineageEdges.metadata })
|
||||
.from(leptonLineageEdges)
|
||||
.where(eq(leptonLineageEdges.parentId, parent));
|
||||
return unpackDocs<LineageEdge>(rows);
|
||||
}
|
||||
|
||||
async allEdges(): Promise<LineageEdge[]> {
|
||||
const rows = await this.db
|
||||
.select({ metadata: leptonLineageEdges.metadata })
|
||||
.from(leptonLineageEdges);
|
||||
return unpackDocs<LineageEdge>(rows);
|
||||
}
|
||||
}
|
||||
|
||||
export class PgProofStore implements ProofStore {
|
||||
constructor(
|
||||
private readonly db: Database,
|
||||
private readonly now: () => Date = () => new Date(),
|
||||
) {}
|
||||
|
||||
async record(proof: CitationProof): Promise<CitationProof> {
|
||||
const projection = {
|
||||
nonce: proof.nonce,
|
||||
agent: proof.agent,
|
||||
accessId: proof.accessId,
|
||||
metadata: packDoc(proof),
|
||||
createdAt: new Date(proof.issuedAt),
|
||||
};
|
||||
await this.db
|
||||
.insert(leptonCitationProofs)
|
||||
.values({ id: `prf_${uuid().replace(/-/g, "").slice(0, 24)}`, ...projection })
|
||||
.onConflictDoUpdate({ target: leptonCitationProofs.nonce, set: { metadata: projection.metadata } });
|
||||
return proof;
|
||||
}
|
||||
|
||||
async findByNonce(nonce: string): Promise<CitationProof | undefined> {
|
||||
const rows = await this.db
|
||||
.select({ metadata: leptonCitationProofs.metadata })
|
||||
.from(leptonCitationProofs)
|
||||
.where(eq(leptonCitationProofs.nonce, nonce))
|
||||
.limit(1);
|
||||
return unpackDoc<CitationProof>(rows[0]) ?? undefined;
|
||||
}
|
||||
|
||||
async listByAccess(accessId: string): Promise<CitationProof[]> {
|
||||
const rows = await this.db
|
||||
.select({ metadata: leptonCitationProofs.metadata })
|
||||
.from(leptonCitationProofs)
|
||||
.where(eq(leptonCitationProofs.accessId, accessId));
|
||||
return unpackDocs<CitationProof>(rows);
|
||||
}
|
||||
|
||||
/**
|
||||
* Atomically claim a recorded nonce. The conditional `UPDATE ... WHERE
|
||||
* consumed = false RETURNING` flips the flag and reports a row only on the
|
||||
* first call, so concurrent sellers cannot both accept the same proof.
|
||||
*/
|
||||
async consume(nonce: string): Promise<boolean> {
|
||||
const claimed = await this.db
|
||||
.update(leptonCitationProofs)
|
||||
.set({ consumed: true })
|
||||
.where(and(eq(leptonCitationProofs.nonce, nonce), eq(leptonCitationProofs.consumed, false)))
|
||||
.returning({ id: leptonCitationProofs.id });
|
||||
return claimed.length > 0;
|
||||
}
|
||||
}
|
||||
@ -10,6 +10,7 @@ export * from "./agent-reputation-store.js";
|
||||
export * from "./agent-service-store.js";
|
||||
export * from "./agent-usage-store.js";
|
||||
export * from "./api-key-store.js";
|
||||
export * from "./attribution-store.js";
|
||||
export * from "./auth-store.js";
|
||||
export * from "./bundle-store.js";
|
||||
export * from "./checkout-repository.js";
|
||||
|
||||
@ -50,6 +50,40 @@ export class PgIdempotencyStore implements SettlementReceiptStore {
|
||||
.onConflictDoUpdate({ target: leptonSettlements.reference, set: projection });
|
||||
}
|
||||
|
||||
/**
|
||||
* Atomically claim a reference by inserting its pending receipt; the unique
|
||||
* constraint on `reference` makes this safe across processes. Returns true
|
||||
* only when this caller inserted the row (and must therefore settle).
|
||||
*/
|
||||
async reserve(pending: SettlementReceipt): Promise<boolean> {
|
||||
const rows = await this.db
|
||||
.insert(leptonSettlements)
|
||||
.values({
|
||||
id: pending.id,
|
||||
reference: pending.reference,
|
||||
recipient: pending.to,
|
||||
amount: pending.amount.amount,
|
||||
network: pending.network,
|
||||
status: pending.status,
|
||||
provider: pending.provider,
|
||||
txHash: null,
|
||||
batchId: null,
|
||||
createdAt: new Date(pending.createdAt),
|
||||
settledAt: null,
|
||||
metadata: packDoc(pending),
|
||||
})
|
||||
.onConflictDoNothing({ target: leptonSettlements.reference })
|
||||
.returning({ id: leptonSettlements.id });
|
||||
return rows.length > 0;
|
||||
}
|
||||
|
||||
/** Remove a still-pending claim so a failed settlement can be retried. */
|
||||
async release(reference: string): Promise<void> {
|
||||
await this.db
|
||||
.delete(leptonSettlements)
|
||||
.where(and(eq(leptonSettlements.reference, reference), eq(leptonSettlements.status, "pending")));
|
||||
}
|
||||
|
||||
async listByStatus(status: SettlementStatus): Promise<SettlementReceipt[]> {
|
||||
const rows = await this.db
|
||||
.select({ metadata: leptonSettlements.metadata })
|
||||
|
||||
@ -9,6 +9,7 @@
|
||||
{ "path": "../common" },
|
||||
{ "path": "../database" },
|
||||
{ "path": "../settlement-core" },
|
||||
{ "path": "../attribution" },
|
||||
{ "path": "../citation-toll" },
|
||||
{ "path": "../payee-registry" },
|
||||
{ "path": "../streaming" },
|
||||
|
||||
@ -72,7 +72,7 @@ export class CircleSettlementProvider implements SettlementProvider {
|
||||
}
|
||||
|
||||
async settle(request: SettlementRequest): Promise<SettlementReceipt> {
|
||||
return withIdempotency(this.idempotency, request, async () => {
|
||||
return withIdempotency(this.idempotency, request, "circle", async () => {
|
||||
const createdAt = toIso(new Date());
|
||||
const created = await this.config.wallets.createTransfer({
|
||||
walletId: this.config.walletId,
|
||||
|
||||
@ -82,7 +82,7 @@ export class GatewaySettlementProvider implements SettlementProvider {
|
||||
}
|
||||
|
||||
async settle(request: SettlementRequest): Promise<SettlementReceipt> {
|
||||
return withIdempotency(this.idempotency, request, async () => {
|
||||
return withIdempotency(this.idempotency, request, "gateway", async () => {
|
||||
const createdAt = toIso(new Date());
|
||||
const amount: Money = money(request.amountUsdc);
|
||||
const { txHash, batchId } = await this.port.transfer({
|
||||
|
||||
@ -3,12 +3,14 @@
|
||||
* versions live in @settlekit/persistence so settlement survives restarts.
|
||||
*/
|
||||
|
||||
import { generateSecret, uuid } from "@settlekit/common";
|
||||
import { conflict, generateSecret, money, toIso, uuid } from "@settlekit/common";
|
||||
import type {
|
||||
IdempotencyStore,
|
||||
NonceStore,
|
||||
SettlementProviderName,
|
||||
SettlementReceipt,
|
||||
SettlementReceiptStore,
|
||||
SettlementRequest,
|
||||
SettlementStatus,
|
||||
} from "./types.js";
|
||||
|
||||
@ -17,6 +19,27 @@ export function settlementId(): string {
|
||||
return `stl_${uuid().replace(/-/g, "").slice(0, 24)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The placeholder receipt written when a reference is first claimed via
|
||||
* {@link IdempotencyStore.reserve}. {@link withIdempotency} upgrades it to the
|
||||
* real receipt on success or releases it on failure.
|
||||
*/
|
||||
function pendingReceipt(
|
||||
request: SettlementRequest,
|
||||
provider: SettlementProviderName,
|
||||
): SettlementReceipt {
|
||||
return {
|
||||
id: settlementId(),
|
||||
reference: request.reference,
|
||||
to: request.to,
|
||||
amount: money(request.amountUsdc),
|
||||
network: request.network,
|
||||
status: "pending",
|
||||
provider,
|
||||
createdAt: toIso(new Date()),
|
||||
};
|
||||
}
|
||||
|
||||
export class InMemoryIdempotencyStore implements IdempotencyStore {
|
||||
private readonly byReference = new Map<string, SettlementReceipt>();
|
||||
|
||||
@ -27,6 +50,20 @@ export class InMemoryIdempotencyStore implements IdempotencyStore {
|
||||
async put(receipt: SettlementReceipt): Promise<void> {
|
||||
this.byReference.set(receipt.reference, receipt);
|
||||
}
|
||||
|
||||
// Atomic by construction: JS runs this synchronously to completion, so there
|
||||
// is no await between the has() check and the set() that could interleave.
|
||||
async reserve(pending: SettlementReceipt): Promise<boolean> {
|
||||
if (this.byReference.has(pending.reference)) return false;
|
||||
this.byReference.set(pending.reference, pending);
|
||||
return true;
|
||||
}
|
||||
|
||||
async release(reference: string): Promise<void> {
|
||||
if (this.byReference.get(reference)?.status === "pending") {
|
||||
this.byReference.delete(reference);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** In-memory queryable receipt store (dev/tests). */
|
||||
@ -41,6 +78,18 @@ export class InMemorySettlementReceiptStore implements SettlementReceiptStore {
|
||||
this.byReference.set(receipt.reference, receipt);
|
||||
}
|
||||
|
||||
async reserve(pending: SettlementReceipt): Promise<boolean> {
|
||||
if (this.byReference.has(pending.reference)) return false;
|
||||
this.byReference.set(pending.reference, pending);
|
||||
return true;
|
||||
}
|
||||
|
||||
async release(reference: string): Promise<void> {
|
||||
if (this.byReference.get(reference)?.status === "pending") {
|
||||
this.byReference.delete(reference);
|
||||
}
|
||||
}
|
||||
|
||||
async listByStatus(status: SettlementStatus): Promise<SettlementReceipt[]> {
|
||||
return [...this.byReference.values()].filter((r) => r.status === status);
|
||||
}
|
||||
@ -63,17 +112,45 @@ export class InMemoryNonceStore implements NonceStore {
|
||||
/**
|
||||
* Wrap a provider's settle() with idempotency: a repeated `reference` returns
|
||||
* the stored receipt instead of issuing a second transfer.
|
||||
*
|
||||
* Concurrency safety: a naive get()-then-settle() check is a TOCTOU race — two
|
||||
* simultaneous requests with the same reference both see "not settled" and both
|
||||
* transfer, double-spending. So when the store supports an atomic
|
||||
* {@link IdempotencyStore.reserve}, exactly one concurrent caller wins the
|
||||
* claim and runs settle(); the rest return the recorded receipt or, if the
|
||||
* winner is still in flight, a retryable conflict. A settle() that throws
|
||||
* releases the claim so the reference can be retried.
|
||||
*/
|
||||
export async function withIdempotency(
|
||||
store: IdempotencyStore,
|
||||
request: { reference: string },
|
||||
request: SettlementRequest,
|
||||
provider: SettlementProviderName,
|
||||
settle: () => Promise<SettlementReceipt>,
|
||||
): Promise<SettlementReceipt> {
|
||||
const existing = await store.get(request.reference);
|
||||
if (existing !== undefined) {
|
||||
if (existing !== undefined && existing.status !== "pending") {
|
||||
return existing;
|
||||
}
|
||||
const receipt = await settle();
|
||||
await store.put(receipt);
|
||||
return receipt;
|
||||
|
||||
// Atomically claim the reference so only one concurrent caller settles it.
|
||||
if (store.reserve) {
|
||||
const won = existing === undefined ? await store.reserve(pendingReceipt(request, provider)) : false;
|
||||
if (!won) {
|
||||
const after = await store.get(request.reference);
|
||||
if (after !== undefined && after.status !== "pending") return after;
|
||||
throw conflict(`settlement for reference ${request.reference} is already in progress`, {
|
||||
reference: request.reference,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const receipt = await settle();
|
||||
await store.put(receipt);
|
||||
return receipt;
|
||||
} catch (error) {
|
||||
// Release a *pending* claim so a retry of a failed settlement can proceed.
|
||||
await store.release?.(request.reference);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
@ -22,7 +22,7 @@ export class LocalSettlementProvider implements SettlementProvider {
|
||||
}
|
||||
|
||||
async settle(request: SettlementRequest): Promise<SettlementReceipt> {
|
||||
return withIdempotency(this.idempotency, request, async () => {
|
||||
return withIdempotency(this.idempotency, request, "local", async () => {
|
||||
const now = toIso(new Date());
|
||||
const receipt: SettlementReceipt = {
|
||||
id: settlementId(),
|
||||
|
||||
@ -59,6 +59,22 @@ export interface SettlementProvider {
|
||||
export interface IdempotencyStore {
|
||||
get(reference: string): Promise<SettlementReceipt | undefined>;
|
||||
put(receipt: SettlementReceipt): Promise<void>;
|
||||
/**
|
||||
* Atomically record a `pending` receipt **iff** its `reference` is still
|
||||
* unclaimed, returning `true` when THIS caller won the claim (and must
|
||||
* therefore perform the settlement) and `false` when another caller already
|
||||
* holds it. This is what makes {@link IdempotencyStore} safe under concurrency
|
||||
* and across processes: without an atomic claim, two simultaneous requests
|
||||
* with the same reference both pass a get()-then-settle() check and double
|
||||
* spend. Optional — stores that omit it fall back to non-atomic get/put.
|
||||
*/
|
||||
reserve?(pending: SettlementReceipt): Promise<boolean>;
|
||||
/**
|
||||
* Drop a `pending` claim so a later retry of a *failed* settlement can
|
||||
* proceed. Only removes a claim still in `pending` status — a recorded
|
||||
* (settled/failed) receipt is never deleted.
|
||||
*/
|
||||
release?(reference: string): Promise<void>;
|
||||
}
|
||||
|
||||
/** A queryable receipt store (the settlement worker reconciles by status). */
|
||||
|
||||
@ -0,0 +1,87 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { InMemoryIdempotencyStore, withIdempotency } from "../src/idempotency.js";
|
||||
import type { SettlementReceipt, SettlementRequest } from "../src/types.js";
|
||||
|
||||
const req: SettlementRequest = {
|
||||
reference: "ref-concurrent",
|
||||
to: "0xrecipient",
|
||||
amountUsdc: "1.25",
|
||||
network: "arc",
|
||||
};
|
||||
|
||||
function receiptFor(): SettlementReceipt {
|
||||
return {
|
||||
id: `stl_${Math.random().toString(16).slice(2)}`,
|
||||
reference: req.reference,
|
||||
to: req.to,
|
||||
amount: { amount: req.amountUsdc, currency: "USDC" },
|
||||
network: req.network,
|
||||
status: "settled",
|
||||
provider: "local",
|
||||
txHash: "0xabc",
|
||||
createdAt: new Date().toISOString(),
|
||||
settledAt: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
/** A settle() that yields to the event loop, so two callers can interleave. */
|
||||
function slowSettle(counter: { n: number }): () => Promise<SettlementReceipt> {
|
||||
return async () => {
|
||||
counter.n += 1;
|
||||
await new Promise((r) => setTimeout(r, 5));
|
||||
return receiptFor();
|
||||
};
|
||||
}
|
||||
|
||||
describe("withIdempotency concurrency", () => {
|
||||
it("runs settle() exactly once for concurrent identical references", async () => {
|
||||
const store = new InMemoryIdempotencyStore();
|
||||
const counter = { n: 0 };
|
||||
|
||||
const results = await Promise.allSettled([
|
||||
withIdempotency(store, req, "local", slowSettle(counter)),
|
||||
withIdempotency(store, req, "local", slowSettle(counter)),
|
||||
withIdempotency(store, req, "local", slowSettle(counter)),
|
||||
]);
|
||||
|
||||
// The whole point: the money only moves once, no matter how many race.
|
||||
expect(counter.n).toBe(1);
|
||||
|
||||
const fulfilled = results.filter((r) => r.status === "fulfilled");
|
||||
expect(fulfilled.length).toBeGreaterThanOrEqual(1);
|
||||
// Any caller that did not win the claim must conflict, never double-settle.
|
||||
for (const r of results) {
|
||||
if (r.status === "rejected") {
|
||||
expect(String(r.reason)).toMatch(/already in progress/i);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it("returns the recorded receipt on a sequential retry (no second settle)", async () => {
|
||||
const store = new InMemoryIdempotencyStore();
|
||||
const counter = { n: 0 };
|
||||
|
||||
const first = await withIdempotency(store, req, "local", slowSettle(counter));
|
||||
const second = await withIdempotency(store, req, "local", slowSettle(counter));
|
||||
|
||||
expect(counter.n).toBe(1);
|
||||
expect(second.id).toBe(first.id);
|
||||
expect(second.status).toBe("settled");
|
||||
});
|
||||
|
||||
it("releases the claim when settle() fails so a retry can proceed", async () => {
|
||||
const store = new InMemoryIdempotencyStore();
|
||||
|
||||
await expect(
|
||||
withIdempotency(store, req, "local", async () => {
|
||||
throw new Error("transfer boom");
|
||||
}),
|
||||
).rejects.toThrow(/boom/);
|
||||
|
||||
// Claim released: the reference is retryable and now settles cleanly.
|
||||
const counter = { n: 0 };
|
||||
const ok = await withIdempotency(store, req, "local", slowSettle(counter));
|
||||
expect(counter.n).toBe(1);
|
||||
expect(ok.status).toBe("settled");
|
||||
});
|
||||
});
|
||||
62
pnpm-lock.yaml
generated
62
pnpm-lock.yaml
generated
@ -295,6 +295,46 @@ importers:
|
||||
specifier: ^5.5.4
|
||||
version: 5.9.3
|
||||
|
||||
apps/creator-dashboard:
|
||||
dependencies:
|
||||
'@settlekit/attribution':
|
||||
specifier: workspace:*
|
||||
version: link:../../packages/attribution
|
||||
'@settlekit/citation-toll':
|
||||
specifier: workspace:*
|
||||
version: link:../../packages/citation-toll
|
||||
'@settlekit/common':
|
||||
specifier: workspace:*
|
||||
version: link:../../packages/common
|
||||
'@settlekit/payee-registry':
|
||||
specifier: workspace:*
|
||||
version: link:../../packages/payee-registry
|
||||
'@settlekit/platform-billing':
|
||||
specifier: workspace:*
|
||||
version: link:../../packages/platform-billing
|
||||
next:
|
||||
specifier: ^14.2.5
|
||||
version: 14.2.35(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
|
||||
react:
|
||||
specifier: ^18.3.1
|
||||
version: 18.3.1
|
||||
react-dom:
|
||||
specifier: ^18.3.1
|
||||
version: 18.3.1(react@18.3.1)
|
||||
devDependencies:
|
||||
'@types/node':
|
||||
specifier: ^20.14.0
|
||||
version: 20.19.43
|
||||
'@types/react':
|
||||
specifier: ^18.3.3
|
||||
version: 18.3.31
|
||||
'@types/react-dom':
|
||||
specifier: ^18.3.0
|
||||
version: 18.3.7(@types/react@18.3.31)
|
||||
typescript:
|
||||
specifier: ^5.5.4
|
||||
version: 5.9.3
|
||||
|
||||
apps/dashboard:
|
||||
dependencies:
|
||||
next:
|
||||
@ -756,6 +796,22 @@ importers:
|
||||
specifier: ^2.0.5
|
||||
version: 2.1.9(@types/node@20.19.43)
|
||||
|
||||
packages/attribution:
|
||||
dependencies:
|
||||
'@settlekit/common':
|
||||
specifier: workspace:*
|
||||
version: link:../common
|
||||
devDependencies:
|
||||
'@types/node':
|
||||
specifier: ^20.14.0
|
||||
version: 20.19.43
|
||||
typescript:
|
||||
specifier: ^5.5.4
|
||||
version: 5.9.3
|
||||
vitest:
|
||||
specifier: ^2.0.5
|
||||
version: 2.1.9(@types/node@20.19.43)
|
||||
|
||||
packages/audit-log:
|
||||
dependencies:
|
||||
'@settlekit/common':
|
||||
@ -1614,6 +1670,9 @@ importers:
|
||||
'@settlekit/api-keys':
|
||||
specifier: workspace:*
|
||||
version: link:../api-keys
|
||||
'@settlekit/attribution':
|
||||
specifier: workspace:*
|
||||
version: link:../attribution
|
||||
'@settlekit/auth':
|
||||
specifier: workspace:*
|
||||
version: link:../auth
|
||||
@ -2296,6 +2355,9 @@ importers:
|
||||
'@hono/node-server':
|
||||
specifier: ^1.13.7
|
||||
version: 1.19.14(hono@4.12.25)
|
||||
'@settlekit/attribution':
|
||||
specifier: workspace:*
|
||||
version: link:../../../packages/attribution
|
||||
'@settlekit/citation-toll':
|
||||
specifier: workspace:*
|
||||
version: link:../../../packages/citation-toll
|
||||
|
||||
@ -20,6 +20,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@hono/node-server": "^1.13.7",
|
||||
"@settlekit/attribution": "workspace:*",
|
||||
"@settlekit/common": "workspace:*",
|
||||
"@settlekit/x402": "workspace:*",
|
||||
"@settlekit/x402-client": "workspace:*",
|
||||
|
||||
103
services/sidecars/rsshub-citation-toll/src/attribution.ts
Normal file
103
services/sidecars/rsshub-citation-toll/src/attribution.ts
Normal file
@ -0,0 +1,103 @@
|
||||
/**
|
||||
* Attribution at the agent boundary (RFB 6.01).
|
||||
*
|
||||
* The citation toll charges an agent that *fetches* a gated article. This closes
|
||||
* the loop for *implicit* reuse: given the text an agent actually produced, it
|
||||
* detects which ingested sources that text was grounded in (@settlekit/attribution
|
||||
* reuse detection), quotes the toll owed, and issues a signed proof-of-citation
|
||||
* the agent can present downstream. Verification consumes the proof's nonce, so
|
||||
* a proof cannot be replayed.
|
||||
*/
|
||||
|
||||
import {
|
||||
type CitationProof,
|
||||
type ProofStore,
|
||||
type ReuseCandidate,
|
||||
type ReuseOptions,
|
||||
type ReuseReport,
|
||||
detectReuse,
|
||||
issueCitationProof,
|
||||
verifyCitationProof,
|
||||
} from "@settlekit/attribution";
|
||||
import { type Money, addMoney, money } from "@settlekit/common";
|
||||
import type { SourceRegistry } from "@settlekit/citation-toll";
|
||||
|
||||
/** A grounding report plus the toll owed for the sources it matched. */
|
||||
export interface GroundingQuote extends ReuseReport {
|
||||
/** Sum of the matched sources' per-access tolls. */
|
||||
quoteUsdc: string;
|
||||
}
|
||||
|
||||
export interface IssueProofRequest {
|
||||
agent: string;
|
||||
accessId: string;
|
||||
sourceIds: readonly string[];
|
||||
amountUsdc?: string;
|
||||
ttlSeconds?: number;
|
||||
}
|
||||
|
||||
export interface AttributionService {
|
||||
/** Detect which ingested sources the given text is grounded in. */
|
||||
detect(text: string, options?: ReuseOptions): GroundingQuote;
|
||||
/** Issue and record a signed proof-of-citation. */
|
||||
issueProof(request: IssueProofRequest): Promise<CitationProof>;
|
||||
/** Verify a presented proof and atomically consume its nonce (anti-replay). */
|
||||
verify(proof: CitationProof): Promise<{ valid: boolean; reason?: string }>;
|
||||
}
|
||||
|
||||
/** Build reuse candidates from the registry's sources (title + summary + body). */
|
||||
function candidatesFrom(registry: SourceRegistry): ReuseCandidate[] {
|
||||
return registry.all().map((s) => ({
|
||||
id: s.id,
|
||||
text: [s.title, s.summary, s.body].filter((t) => t.length > 0).join(". "),
|
||||
wallet: s.authorWallet,
|
||||
}));
|
||||
}
|
||||
|
||||
export function createAttributionService(deps: {
|
||||
registry: SourceRegistry;
|
||||
proofStore: ProofStore;
|
||||
proofSecret: string;
|
||||
now?: () => Date;
|
||||
}): AttributionService {
|
||||
const now = deps.now ?? (() => new Date());
|
||||
|
||||
return {
|
||||
detect(text, options) {
|
||||
const report = detectReuse(text, candidatesFrom(deps.registry), options);
|
||||
const quote = report.matches.reduce<Money>((sum, m) => {
|
||||
const source = deps.registry.get(m.sourceId);
|
||||
return source !== undefined ? addMoney(sum, money(source.priceUsdc)) : sum;
|
||||
}, money("0"));
|
||||
return { ...report, quoteUsdc: quote.amount };
|
||||
},
|
||||
|
||||
async issueProof(request) {
|
||||
const proof = issueCitationProof(
|
||||
{
|
||||
agent: request.agent,
|
||||
sourceIds: request.sourceIds,
|
||||
accessId: request.accessId,
|
||||
...(request.amountUsdc !== undefined ? { amountUsdc: request.amountUsdc } : {}),
|
||||
...(request.ttlSeconds !== undefined ? { ttlSeconds: request.ttlSeconds } : {}),
|
||||
},
|
||||
deps.proofSecret,
|
||||
now(),
|
||||
);
|
||||
await deps.proofStore.record(proof);
|
||||
return proof;
|
||||
},
|
||||
|
||||
async verify(proof) {
|
||||
const result = verifyCitationProof(proof, deps.proofSecret, now());
|
||||
if (!result.ok) {
|
||||
return { valid: false, reason: result.error.message };
|
||||
}
|
||||
const fresh = await deps.proofStore.consume(proof.nonce);
|
||||
if (!fresh) {
|
||||
return { valid: false, reason: "citation proof already consumed" };
|
||||
}
|
||||
return { valid: true };
|
||||
},
|
||||
};
|
||||
}
|
||||
@ -14,6 +14,8 @@ export interface SidecarConfig {
|
||||
escrowWallet: string;
|
||||
/** Optional Arc indexer base URL; when set, tolls are verified on-chain. */
|
||||
indexerUrl?: string;
|
||||
/** HMAC secret for signing proofs-of-citation an agent presents downstream. */
|
||||
proofSecret: string;
|
||||
}
|
||||
|
||||
function env(vars: NodeJS.ProcessEnv, name: string, fallback: string): string {
|
||||
@ -29,6 +31,7 @@ export function loadConfig(vars: NodeJS.ProcessEnv = process.env): SidecarConfig
|
||||
defaultPriceUsdc: env(vars, "DEFAULT_TOLL_USDC", "0.0005"),
|
||||
network: env(vars, "NETWORK", "arc") as PaymentNetwork,
|
||||
escrowWallet: env(vars, "ESCROW_WALLET", "0x0000000000000000000000000000000000e5c70w"),
|
||||
proofSecret: env(vars, "CITATION_PROOF_SECRET", "dev-citation-proof-secret"),
|
||||
...(indexerUrl !== undefined && indexerUrl.length > 0 ? { indexerUrl } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
@ -17,6 +17,12 @@ import {
|
||||
sweepPendingRoyalties,
|
||||
} from "@settlekit/citation-toll";
|
||||
import { InMemoryPayeeRegistry, type PayeeRegistry } from "@settlekit/payee-registry";
|
||||
import {
|
||||
type CitationProof,
|
||||
InMemoryProofStore,
|
||||
type ProofStore,
|
||||
} from "@settlekit/attribution";
|
||||
import { type AttributionService, createAttributionService } from "./attribution.js";
|
||||
import {
|
||||
LocalSettlementProvider,
|
||||
type SettlementProvider,
|
||||
@ -40,6 +46,8 @@ export interface Sidecar {
|
||||
payees: PayeeRegistry;
|
||||
royaltyLegStore: RoyaltyLegStore;
|
||||
settlementProvider: SettlementProvider;
|
||||
proofStore: ProofStore;
|
||||
attribution: AttributionService;
|
||||
ingestor: RssCitationIngestor;
|
||||
/** Local x402 settler for demos/tests; real agents settle on-chain. */
|
||||
demoSettler: Settler;
|
||||
@ -61,6 +69,12 @@ export function createSidecar(
|
||||
const payees = new InMemoryPayeeRegistry();
|
||||
const royaltyLegStore = new InMemoryRoyaltyLegStore();
|
||||
const settlementProvider = options.settlementProvider ?? new LocalSettlementProvider();
|
||||
const proofStore = new InMemoryProofStore();
|
||||
const attribution = createAttributionService({
|
||||
registry,
|
||||
proofStore,
|
||||
proofSecret: config.proofSecret,
|
||||
});
|
||||
const ingestor = createRssIngestor({ registry, payees, config });
|
||||
|
||||
// x402 verification: on-chain via the Arc indexer when configured, else a
|
||||
@ -101,6 +115,52 @@ export function createSidecar(
|
||||
// x402-gated citation content: GET /articles/:id returns a 402 until paid.
|
||||
app.all("/articles/:id", (c) => tollRouter(c.req.raw));
|
||||
|
||||
// Attribution: detect which ingested sources an agent's generated text was
|
||||
// grounded in, and quote the toll owed for that implicit reuse (RFB 6.01).
|
||||
app.post("/attribution/detect", async (c) => {
|
||||
const body = (await c.req.json().catch(() => null)) as { text?: string } | null;
|
||||
if (body === null || typeof body.text !== "string") {
|
||||
return c.json({ error: "text required" }, 400);
|
||||
}
|
||||
return c.json({ data: attribution.detect(body.text) });
|
||||
});
|
||||
|
||||
// Attribution: issue a signed proof-of-citation an agent presents downstream.
|
||||
app.post("/attribution/proof", async (c) => {
|
||||
const body = (await c.req.json().catch(() => null)) as Partial<{
|
||||
agent: string;
|
||||
accessId: string;
|
||||
sourceIds: string[];
|
||||
amountUsdc: string;
|
||||
ttlSeconds: number;
|
||||
}> | null;
|
||||
if (
|
||||
body === null ||
|
||||
typeof body.agent !== "string" ||
|
||||
typeof body.accessId !== "string" ||
|
||||
!Array.isArray(body.sourceIds)
|
||||
) {
|
||||
return c.json({ error: "agent, accessId, sourceIds[] required" }, 400);
|
||||
}
|
||||
const proof = await attribution.issueProof({
|
||||
agent: body.agent,
|
||||
accessId: body.accessId,
|
||||
sourceIds: body.sourceIds,
|
||||
...(typeof body.amountUsdc === "string" ? { amountUsdc: body.amountUsdc } : {}),
|
||||
...(typeof body.ttlSeconds === "number" ? { ttlSeconds: body.ttlSeconds } : {}),
|
||||
});
|
||||
return c.json({ data: proof });
|
||||
});
|
||||
|
||||
// Attribution: verify a presented proof and consume its nonce (anti-replay).
|
||||
app.post("/attribution/verify", async (c) => {
|
||||
const body = (await c.req.json().catch(() => null)) as { proof?: CitationProof } | null;
|
||||
if (body === null || body.proof === undefined) {
|
||||
return c.json({ error: "proof required" }, 400);
|
||||
}
|
||||
return c.json({ data: await attribution.verify(body.proof) });
|
||||
});
|
||||
|
||||
// Admin: sweep pending royalties into author payouts (the settlement worker
|
||||
// does this on a schedule in production; exposed here so the full flow is
|
||||
// demonstrable end to end).
|
||||
@ -116,6 +176,8 @@ export function createSidecar(
|
||||
payees,
|
||||
royaltyLegStore,
|
||||
settlementProvider,
|
||||
proofStore,
|
||||
attribution,
|
||||
ingestor,
|
||||
demoSettler: localSettlement.settler,
|
||||
};
|
||||
|
||||
102
services/sidecars/rsshub-citation-toll/test/attribution.test.ts
Normal file
102
services/sidecars/rsshub-citation-toll/test/attribution.test.ts
Normal file
@ -0,0 +1,102 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { loadConfig } from "../src/config.js";
|
||||
import { createSidecar } from "../src/sidecar.js";
|
||||
import type { RssItem } from "../src/ingestor.js";
|
||||
|
||||
const ITEM: RssItem = {
|
||||
feedId: "research",
|
||||
itemId: "p1",
|
||||
title: "Arc nanopayments",
|
||||
author: { externalId: "u/ada", displayName: "Ada", wallet: "0xAda" },
|
||||
content:
|
||||
"The Arc network settles USDC nanopayments gas-free using Gateway burn intents, " +
|
||||
"so an agent can pay a fraction of a cent per citation batched into one on-chain settlement.",
|
||||
};
|
||||
|
||||
function sidecar() {
|
||||
return createSidecar(loadConfig({ ESCROW_WALLET: "0xEscrow" } as unknown as NodeJS.ProcessEnv));
|
||||
}
|
||||
|
||||
async function post(app: ReturnType<typeof sidecar>["app"], path: string, body: unknown) {
|
||||
const res = await app.fetch(
|
||||
new Request(`http://local${path}`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
}),
|
||||
);
|
||||
return { status: res.status, json: (await res.json()) as { data?: unknown; error?: string } };
|
||||
}
|
||||
|
||||
describe("POST /attribution/detect", () => {
|
||||
it("flags an agent answer grounded in an ingested source and quotes the toll", async () => {
|
||||
const s = sidecar();
|
||||
await s.ingestor.ingest(ITEM);
|
||||
|
||||
const { status, json } = await post(s.app, "/attribution/detect", {
|
||||
text: "an agent can pay a fraction of a cent per citation batched into one on-chain settlement",
|
||||
});
|
||||
expect(status).toBe(200);
|
||||
const data = json.data as {
|
||||
grounded: boolean;
|
||||
matches: { sourceId: string; wallet?: string }[];
|
||||
quoteUsdc: string;
|
||||
};
|
||||
expect(data.grounded).toBe(true);
|
||||
expect(data.matches[0]?.wallet).toBe("0xAda");
|
||||
expect(data.quoteUsdc).toBe("0.0005"); // one matched source at the default toll
|
||||
});
|
||||
|
||||
it("does not flag unrelated text", async () => {
|
||||
const s = sidecar();
|
||||
await s.ingestor.ingest(ITEM);
|
||||
const { json } = await post(s.app, "/attribution/detect", {
|
||||
text: "a recipe for sourdough bread with rye flour and a long cold ferment",
|
||||
});
|
||||
expect((json.data as { grounded: boolean }).grounded).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects a missing text field", async () => {
|
||||
const s = sidecar();
|
||||
const { status } = await post(s.app, "/attribution/detect", {});
|
||||
expect(status).toBe(400);
|
||||
});
|
||||
});
|
||||
|
||||
describe("proof-of-citation lifecycle", () => {
|
||||
it("issues, verifies once, and rejects a replay", async () => {
|
||||
const s = sidecar();
|
||||
const issued = await post(s.app, "/attribution/proof", {
|
||||
agent: "agent_1",
|
||||
accessId: "acc_1",
|
||||
sourceIds: ["src_a"],
|
||||
amountUsdc: "0.0005",
|
||||
ttlSeconds: 300,
|
||||
});
|
||||
expect(issued.status).toBe(200);
|
||||
const proof = issued.json.data as { signature: string; nonce: string };
|
||||
expect(proof.signature).toMatch(/^[0-9a-f]+$/);
|
||||
expect(await s.proofStore.findByNonce(proof.nonce)).toBeDefined();
|
||||
|
||||
const first = await post(s.app, "/attribution/verify", { proof });
|
||||
expect((first.json.data as { valid: boolean }).valid).toBe(true);
|
||||
|
||||
const replay = await post(s.app, "/attribution/verify", { proof });
|
||||
const replayData = replay.json.data as { valid: boolean; reason?: string };
|
||||
expect(replayData.valid).toBe(false);
|
||||
expect(replayData.reason).toContain("consumed");
|
||||
});
|
||||
|
||||
it("rejects a tampered proof", async () => {
|
||||
const s = sidecar();
|
||||
const issued = await post(s.app, "/attribution/proof", {
|
||||
agent: "agent_1",
|
||||
accessId: "acc_1",
|
||||
sourceIds: ["src_a"],
|
||||
});
|
||||
const proof = issued.json.data as Record<string, unknown>;
|
||||
const tampered = { ...proof, agent: "agent_evil" };
|
||||
const res = await post(s.app, "/attribution/verify", { proof: tampered });
|
||||
expect((res.json.data as { valid: boolean }).valid).toBe(false);
|
||||
});
|
||||
});
|
||||
@ -8,6 +8,7 @@
|
||||
},
|
||||
"references": [
|
||||
{ "path": "../../../packages/common" },
|
||||
{ "path": "../../../packages/attribution" },
|
||||
{ "path": "../../../packages/x402" },
|
||||
{ "path": "../../../packages/x402-client" },
|
||||
{ "path": "../../../packages/citation-toll" },
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user