arl-protocol-sdk 0.2.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,75 @@
1
+ import type { Hex } from "viem";
2
+ import { approveCommittee, checkFundedJob, submitDeliverable, waitForAcceptance, type EscrowOfferInput } from "./escrowProvider.ts";
3
+ import { type VerifiedClients } from "./verified.ts";
4
+ /** Header with the deliverable the service submits for the job. */
5
+ export declare const DELIVERABLE_HEADER = "X-ARL-Deliverable";
6
+ type BodyInit = NonNullable<ConstructorParameters<typeof Response>[0]>;
7
+ type HeadersInit = NonNullable<ConstructorParameters<typeof Headers>[0]>;
8
+ /** What the handler returns: the response body and the deliverable the committee will check. */
9
+ export interface PayOnProofResult {
10
+ body: BodyInit | null;
11
+ /** 32-byte deliverable (for re-execution jobs, the result manifest's hash). */
12
+ deliverable: Hex;
13
+ status?: number;
14
+ headers?: HeadersInit;
15
+ }
16
+ /**
17
+ * Jobs already served. A job pays for one run, so a job id is recorded before the work starts.
18
+ * The default lives in memory and is lost on restart: a service with more than one instance, or
19
+ * one that restarts, passes a durable store (a database table, a KV namespace).
20
+ */
21
+ export interface UsedJobs {
22
+ has(key: string): boolean | Promise<boolean>;
23
+ add(key: string): void | Promise<void>;
24
+ delete(key: string): void | Promise<void>;
25
+ }
26
+ export interface PayOnProofDeps {
27
+ checkFundedJob: typeof checkFundedJob;
28
+ approveCommittee: typeof approveCommittee;
29
+ waitForAcceptance: typeof waitForAcceptance;
30
+ submitDeliverable: typeof submitDeliverable;
31
+ }
32
+ export interface PayOnProofConfig {
33
+ /** The service's own clients: `walletClient` is the provider named in the offer. */
34
+ clients: VerifiedClients;
35
+ offer: EscrowOfferInput;
36
+ usedJobs?: UsedJobs;
37
+ /** How long to wait for committee members to accept before submitting. */
38
+ acceptance?: {
39
+ timeoutMs?: number;
40
+ pollMs?: number;
41
+ };
42
+ /**
43
+ * Keeps the submission alive after the response is sent, on runtimes that stop work when the
44
+ * response ends (Cloudflare Workers: `ctx.waitUntil`, Vercel: `waitUntil`).
45
+ */
46
+ waitUntil?: (work: Promise<unknown>) => void;
47
+ /** Called when the background submission fails; the job then ends refunded to the client. */
48
+ onError?: (error: unknown, jobId: bigint) => void;
49
+ /** For tests: replaces the on-chain calls. */
50
+ deps?: Partial<PayOnProofDeps>;
51
+ }
52
+ export type PayOnProofHandler = (request: Request, job: {
53
+ jobId: bigint;
54
+ client: `0x${string}`;
55
+ }) => Promise<PayOnProofResult>;
56
+ export declare function memoryUsedJobs(): UsedJobs;
57
+ /** Wraps `handler` so every call is paid through a verified job before it runs. */
58
+ export declare function payOnProof(config: PayOnProofConfig, handler: PayOnProofHandler): (request: Request) => Promise<Response>;
59
+ /** The subset of an Express request and response the adapter uses. */
60
+ interface ExpressRequest {
61
+ method: string;
62
+ originalUrl: string;
63
+ protocol: string;
64
+ headers: Record<string, string | string[] | undefined>;
65
+ body?: unknown;
66
+ get(name: string): string | undefined;
67
+ }
68
+ interface ExpressResponse {
69
+ status(code: number): ExpressResponse;
70
+ setHeader(name: string, value: string): unknown;
71
+ send(body: unknown): unknown;
72
+ }
73
+ /** `payOnProof` as an Express handler: `app.post("/run", expressPayOnProof(config, handler))`. */
74
+ export declare function expressPayOnProof(config: PayOnProofConfig, handler: PayOnProofHandler): (req: ExpressRequest, res: ExpressResponse, next: (e?: unknown) => void) => Promise<void>;
75
+ export {};
@@ -0,0 +1,137 @@
1
+ // Pay-on-proof: one wrapper turns an HTTP handler into a service paid through a verified job
2
+ // (spec/x402-arl-escrow). The client pays into escrow first, the service does the work, and the
3
+ // money reaches the service only after a staked committee has checked the result.
4
+ //
5
+ // Any runtime that speaks the Fetch API (Next.js route handlers, Hono, Cloudflare Workers, Bun,
6
+ // Deno) uses `payOnProof` directly; `expressPayOnProof` adapts it to Express.
7
+ //
8
+ // export const POST = payOnProof(
9
+ // { clients, offer: { chainId: 8453, provider, specUri, specHash, budget, committee, threshold: 2 } },
10
+ // async (req) => {
11
+ // const result = await runTheJob(await req.json()); // the work the spec describes
12
+ // return { body: JSON.stringify(result), deliverable: resultHash };
13
+ // },
14
+ // );
15
+ //
16
+ // Without an `X-ARL-Job` header the service answers 402 with the offer; `payVerified` (or any
17
+ // x402 client that knows the `arl-escrow` scheme) opens and funds the job and asks again. With a
18
+ // funded job matching the offer, the handler runs once per job, the response carries the job and
19
+ // the deliverable, and the deliverable is submitted on chain as soon as enough committee members
20
+ // have accepted the job.
21
+ import { approveCommittee, buildEscrowOffer, checkFundedJob, submitDeliverable, waitForAcceptance, } from "./escrowProvider.js";
22
+ import { JOB_HEADER, parseEscrowOffer } from "./payVerified.js";
23
+ import { VerifiedJobError } from "./verified.js";
24
+ /** Header with the deliverable the service submits for the job. */
25
+ export const DELIVERABLE_HEADER = "X-ARL-Deliverable";
26
+ export function memoryUsedJobs() {
27
+ const used = new Set();
28
+ return {
29
+ has: (k) => used.has(k),
30
+ add: (k) => {
31
+ used.add(k);
32
+ },
33
+ delete: (k) => {
34
+ used.delete(k);
35
+ },
36
+ };
37
+ }
38
+ const json = (status, body, headers) => new Response(JSON.stringify(body), {
39
+ status,
40
+ headers: { "content-type": "application/json", ...Object.fromEntries(new Headers(headers)) },
41
+ });
42
+ /**
43
+ * What a caller may learn from a failure: the SDK's own checks explain themselves (a job on another
44
+ * chain, an unfunded job); anything else (an RPC or library error) stays on the server.
45
+ */
46
+ const publicReason = (e, fallback) => e instanceof VerifiedJobError ? (e.message.split("\n")[0] ?? fallback) : fallback;
47
+ /** Wraps `handler` so every call is paid through a verified job before it runs. */
48
+ export function payOnProof(config, handler) {
49
+ const offerBody = buildEscrowOffer(config.offer);
50
+ const offer = parseEscrowOffer(offerBody);
51
+ const used = config.usedJobs ?? memoryUsedJobs();
52
+ const deps = {
53
+ checkFundedJob,
54
+ approveCommittee,
55
+ waitForAcceptance,
56
+ submitDeliverable,
57
+ ...config.deps,
58
+ };
59
+ return async (request) => {
60
+ const header = request.headers.get(JOB_HEADER);
61
+ if (!header)
62
+ return json(402, offerBody);
63
+ let job;
64
+ try {
65
+ job = await deps.checkFundedJob(config.clients.publicClient, offer, header);
66
+ }
67
+ catch (e) {
68
+ return json(402, { ...offerBody, error: publicReason(e, "could not check the job") });
69
+ }
70
+ // One run per job: recorded before the work, released only if the work never started.
71
+ const key = `${offer.network}:${offer.jobs}:${job.jobId.toString()}`.toLowerCase();
72
+ if (await used.has(key))
73
+ return json(409, { error: "this job was already served" });
74
+ await used.add(key);
75
+ try {
76
+ await deps.approveCommittee(config.clients, offer, job.jobId);
77
+ }
78
+ catch (e) {
79
+ await used.delete(key);
80
+ return json(503, {
81
+ error: `could not approve the committee: ${publicReason(e, "try again")}`,
82
+ });
83
+ }
84
+ const result = await handler(request, job);
85
+ if (!/^0x[0-9a-fA-F]{64}$/.test(result.deliverable)) {
86
+ throw new Error("the handler must return a 32-byte deliverable");
87
+ }
88
+ const submission = (async () => {
89
+ await deps.waitForAcceptance(config.clients.publicClient, offer, job.jobId, config.acceptance);
90
+ await deps.submitDeliverable(config.clients, offer, job.jobId, result.deliverable);
91
+ })().catch((e) => {
92
+ config.onError?.(e, job.jobId);
93
+ });
94
+ config.waitUntil?.(submission);
95
+ const headers = new Headers(result.headers);
96
+ headers.set(JOB_HEADER, header);
97
+ headers.set(DELIVERABLE_HEADER, result.deliverable);
98
+ return new Response(result.body, { status: result.status ?? 200, headers });
99
+ };
100
+ }
101
+ /** `payOnProof` as an Express handler: `app.post("/run", expressPayOnProof(config, handler))`. */
102
+ export function expressPayOnProof(config, handler) {
103
+ const fetchHandler = payOnProof(config, handler);
104
+ return async (req, res, next) => {
105
+ try {
106
+ const headers = new Headers();
107
+ for (const [k, v] of Object.entries(req.headers)) {
108
+ if (typeof v === "string")
109
+ headers.set(k, v);
110
+ else if (Array.isArray(v))
111
+ headers.set(k, v.join(", "));
112
+ }
113
+ const hasBody = req.method !== "GET" && req.method !== "HEAD" && req.body !== undefined;
114
+ const body = !hasBody
115
+ ? undefined
116
+ : typeof req.body === "string" || req.body instanceof Uint8Array
117
+ ? req.body
118
+ : JSON.stringify(req.body);
119
+ const url = `${req.protocol}://${req.get("host") ?? "localhost"}${req.originalUrl}`;
120
+ const init = {
121
+ method: req.method,
122
+ headers,
123
+ };
124
+ if (body !== undefined)
125
+ init.body = body;
126
+ const response = await fetchHandler(new Request(url, init));
127
+ res.status(response.status);
128
+ response.headers.forEach((value, name) => {
129
+ res.setHeader(name, value);
130
+ });
131
+ res.send(Buffer.from(await response.arrayBuffer()));
132
+ }
133
+ catch (e) {
134
+ next(e);
135
+ }
136
+ };
137
+ }