arl-protocol-sdk 0.2.2 → 0.3.1
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.
- package/README.md +38 -0
- package/package.json +1 -1
- package/protocol/src/index.d.ts +2 -0
- package/protocol/src/index.js +1 -0
- package/protocol/src/reputationRead.d.ts +57 -0
- package/protocol/src/reputationRead.js +100 -0
- package/sdk/src/agentScore.d.ts +840 -0
- package/sdk/src/agentScore.js +335 -0
- package/sdk/src/audit.d.ts +30 -0
- package/sdk/src/audit.js +101 -0
- package/sdk/src/index.d.ts +5 -0
- package/sdk/src/index.js +5 -0
- package/sdk/src/passport.d.ts +25 -0
- package/sdk/src/passport.js +88 -0
- package/sdk/src/payOnProof.d.ts +75 -0
- package/sdk/src/payOnProof.js +137 -0
- package/sdk/src/validators.d.ts +27 -0
- package/sdk/src/validators.js +82 -0
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { type Address, type PublicClient } from "viem";
|
|
2
|
+
import { type HistoryOptions } from "./agentScore.ts";
|
|
3
|
+
export interface ValidatorRecord {
|
|
4
|
+
token: "ARL" | "USDC";
|
|
5
|
+
evaluator: Address;
|
|
6
|
+
validator: Address;
|
|
7
|
+
/** Stake and the part locked as bonds on running jobs, in base units of the stake token. */
|
|
8
|
+
stake?: string;
|
|
9
|
+
locked?: string;
|
|
10
|
+
/** Jobs it accepted a seat on. */
|
|
11
|
+
accepted: number;
|
|
12
|
+
/** Votes cast, by direction. */
|
|
13
|
+
approved: number;
|
|
14
|
+
rejected: number;
|
|
15
|
+
/** Times a bond of its was slashed, and the total, in base units. */
|
|
16
|
+
slashes: number;
|
|
17
|
+
slashed: string;
|
|
18
|
+
/** Unix seconds of its first stake. */
|
|
19
|
+
since?: number;
|
|
20
|
+
}
|
|
21
|
+
export interface Validators {
|
|
22
|
+
/** The block everything was read at. */
|
|
23
|
+
block: bigint;
|
|
24
|
+
validators: ValidatorRecord[];
|
|
25
|
+
}
|
|
26
|
+
/** Reads every validator that ever staked on a verified evaluator, most active first. */
|
|
27
|
+
export declare function getValidators(client: PublicClient, opts?: HistoryOptions): Promise<Validators>;
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
// The validators of the verified evaluators: who has staked, how much, and what each has done.
|
|
2
|
+
// Anyone can stake and be named on a committee; this is the public record a client or a provider
|
|
3
|
+
// reads before naming one.
|
|
4
|
+
//
|
|
5
|
+
// What a validator did (accepted jobs, votes, slashes) comes from the evaluators' events; its
|
|
6
|
+
// stake and the part locked in running jobs are read from the contract at the same block.
|
|
7
|
+
import { getAddress, isAddressEqual, parseAbi } from "viem";
|
|
8
|
+
import { HISTORY_START, VERIFIED_EVALUATORS, blockTime, readProtocolLogs, } from "./agentScore.js";
|
|
9
|
+
const stakeAbi = parseAbi([
|
|
10
|
+
"function stakeOf(address validator) view returns (uint256)",
|
|
11
|
+
"function lockedOf(address validator) view returns (uint256)",
|
|
12
|
+
]);
|
|
13
|
+
/** Most validators whose stake is read in one answer; the rest are listed without it. */
|
|
14
|
+
const MAX_STAKE_READS = 25;
|
|
15
|
+
/** Reads every validator that ever staked on a verified evaluator, most active first. */
|
|
16
|
+
export async function getValidators(client, opts = {}) {
|
|
17
|
+
const head = await client.getBlock();
|
|
18
|
+
const logs = await readProtocolLogs(client, HISTORY_START, head.number, opts);
|
|
19
|
+
const records = new Map();
|
|
20
|
+
for (const l of logs) {
|
|
21
|
+
const deployment = VERIFIED_EVALUATORS.find((e) => isAddressEqual(e.evaluator, l.address));
|
|
22
|
+
if (!deployment)
|
|
23
|
+
continue;
|
|
24
|
+
const args = l.args;
|
|
25
|
+
const who = l.eventName === "Slashed" ? args.account : args.validator;
|
|
26
|
+
if (typeof who !== "string")
|
|
27
|
+
continue;
|
|
28
|
+
const key = `${deployment.token}:${who.toLowerCase()}`;
|
|
29
|
+
let r = records.get(key);
|
|
30
|
+
if (!r) {
|
|
31
|
+
// A slash of an address that never staked is a challenger's bond, not a validator's.
|
|
32
|
+
if (l.eventName !== "Staked")
|
|
33
|
+
continue;
|
|
34
|
+
r = {
|
|
35
|
+
token: deployment.token,
|
|
36
|
+
evaluator: deployment.evaluator,
|
|
37
|
+
validator: getAddress(who),
|
|
38
|
+
accepted: 0,
|
|
39
|
+
approved: 0,
|
|
40
|
+
rejected: 0,
|
|
41
|
+
slashes: 0,
|
|
42
|
+
slashed: "0",
|
|
43
|
+
firstBlock: l.blockNumber,
|
|
44
|
+
};
|
|
45
|
+
records.set(key, r);
|
|
46
|
+
}
|
|
47
|
+
if (l.eventName === "Accepted")
|
|
48
|
+
r.accepted += 1;
|
|
49
|
+
else if (l.eventName === "Voted") {
|
|
50
|
+
if (args.approve === true)
|
|
51
|
+
r.approved += 1;
|
|
52
|
+
else
|
|
53
|
+
r.rejected += 1;
|
|
54
|
+
}
|
|
55
|
+
else if (l.eventName === "Slashed") {
|
|
56
|
+
r.slashes += 1;
|
|
57
|
+
r.slashed = (BigInt(r.slashed) + args.amount).toString();
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
const list = [...records.values()].sort((a, b) => b.approved + b.rejected - (a.approved + a.rejected) ||
|
|
61
|
+
b.accepted - a.accepted ||
|
|
62
|
+
a.validator.localeCompare(b.validator));
|
|
63
|
+
const at = { blockNumber: head.number };
|
|
64
|
+
const validators = [];
|
|
65
|
+
for (const [i, { firstBlock, ...r }] of list.entries()) {
|
|
66
|
+
if (firstBlock !== undefined)
|
|
67
|
+
r.since = await blockTime(client, firstBlock);
|
|
68
|
+
if (i < MAX_STAKE_READS) {
|
|
69
|
+
const read = (functionName) => client.readContract({
|
|
70
|
+
address: r.evaluator,
|
|
71
|
+
abi: stakeAbi,
|
|
72
|
+
functionName,
|
|
73
|
+
args: [r.validator],
|
|
74
|
+
...at,
|
|
75
|
+
});
|
|
76
|
+
r.stake = (await read("stakeOf")).toString();
|
|
77
|
+
r.locked = (await read("lockedOf")).toString();
|
|
78
|
+
}
|
|
79
|
+
validators.push(r);
|
|
80
|
+
}
|
|
81
|
+
return { block: head.number, validators };
|
|
82
|
+
}
|