arl-protocol-sdk 0.2.0 → 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.
@@ -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
+ }
@@ -10,7 +10,7 @@ export declare const BASE_MAINNET_VERIFIED: {
10
10
  readonly chainId: 8453;
11
11
  readonly token: "0xde91E6f39D50bBd875f831dcc1134A3D7f3aaDb4";
12
12
  readonly jobs: "0x9aE99bF9a59aF47E81346B7c0b93Cd2B610455fC";
13
- readonly evaluator: "0x6648e141cb7473822ddBd8bC039b91e5af3259B4";
13
+ readonly evaluator: "0x0D160C869bd2a7AaEDd29e11fc60fdAEf21c3E28";
14
14
  readonly arbiterSafe: "0x8FF6c3aD0991Ac848BFf5d0acD78BBc5e190466f";
15
15
  };
16
16
  /** The jobs escrow and evaluator of a chain, or undefined on the local chain. */
@@ -149,6 +149,21 @@ export declare const verifiedEvaluatorAbi: readonly [{
149
149
  readonly name: "voteHash";
150
150
  }];
151
151
  }];
152
+ }, {
153
+ readonly name: "outcomesOf";
154
+ readonly type: "function";
155
+ readonly stateMutability: "view";
156
+ readonly inputs: readonly [{
157
+ readonly type: "uint256";
158
+ readonly name: "agentId";
159
+ }];
160
+ readonly outputs: readonly [{
161
+ readonly type: "uint64";
162
+ readonly name: "approved";
163
+ }, {
164
+ readonly type: "uint64";
165
+ readonly name: "rejected";
166
+ }];
152
167
  }, {
153
168
  readonly name: "finalize";
154
169
  readonly type: "function";
@@ -158,6 +173,14 @@ export declare const verifiedEvaluatorAbi: readonly [{
158
173
  readonly name: "jobId";
159
174
  }];
160
175
  readonly outputs: readonly [];
176
+ }, {
177
+ readonly name: "minChallengeWindow";
178
+ readonly type: "function";
179
+ readonly stateMutability: "view";
180
+ readonly inputs: readonly [];
181
+ readonly outputs: readonly [{
182
+ readonly type: "uint64";
183
+ }];
161
184
  }];
162
185
  /** ARLVerifiedEvaluator.Phase, by index. */
163
186
  export declare const VERDICT_PHASES: readonly ["None", "Configured", "Approved", "Rejected", "Disputed", "Finalized", "Released", "Failed"];
@@ -201,6 +224,21 @@ export declare function checkVerifiedChain(client: PublicClient): Promise<number
201
224
  export declare function walletAccount(wallet: VerifiedClients["walletClient"]): Account;
202
225
  /** Checks the parameters the evaluator would reject, before any transaction is sent. */
203
226
  export declare function checkOpenParams(p: OpenVerifiedJobParams): void;
227
+ /**
228
+ * The windows and lifetime openVerifiedJob uses when the caller gives none. The challenge window
229
+ * defaults to the evaluator's minimum (one day on Base Mainnet) and the job lives long enough for
230
+ * the evaluator's own check at configure and at voting start (`_checkFits`: the vote window plus
231
+ * two challenge windows), with a day to spare for the committee to accept.
232
+ */
233
+ export declare function defaultWindows(minChallengeWindow: bigint, p: {
234
+ voteWindow?: bigint;
235
+ challengeWindow?: bigint;
236
+ expiresIn?: bigint;
237
+ }): {
238
+ voteWindow: bigint;
239
+ challengeWindow: bigint;
240
+ expiresIn: bigint;
241
+ };
204
242
  /**
205
243
  * Creates the job (the caller is its client) and configures the committee in two transactions.
206
244
  * The provider then approves the committee and sets the budget; the client funds the job.
@@ -225,5 +263,15 @@ export declare function getVerdict(publicClient: PublicClient, jobId: bigint, ev
225
263
  deliverable: `0x${string}`;
226
264
  voteHash: `0x${string}`;
227
265
  }>;
266
+ export interface AgentOutcomes {
267
+ approved: bigint;
268
+ rejected: bigint;
269
+ }
270
+ /**
271
+ * Approved and rejected job counts recorded by `ARLVerifiedEvaluator` for an ERC-8004 agent.
272
+ * Accepts either `(publicClient, evaluator, agentId)` or `(publicClient, agentId, evaluator?)`.
273
+ */
274
+ export declare function getOutcomes(publicClient: PublicClient, evaluator: Address, agentId: bigint): Promise<AgentOutcomes>;
275
+ export declare function getOutcomes(publicClient: PublicClient, agentId: bigint, evaluator?: Address): Promise<AgentOutcomes>;
228
276
  /** Pays out after the challenge window: anyone may call it. */
229
277
  export declare function finalizeJob({ publicClient, walletClient }: VerifiedClients, jobId: bigint, evaluator?: Address): Promise<Hash>;
@@ -19,7 +19,7 @@ export const BASE_MAINNET_VERIFIED = {
19
19
  chainId: 8453,
20
20
  token: "0xde91E6f39D50bBd875f831dcc1134A3D7f3aaDb4",
21
21
  jobs: "0x9aE99bF9a59aF47E81346B7c0b93Cd2B610455fC",
22
- evaluator: "0x6648e141cb7473822ddBd8bC039b91e5af3259B4",
22
+ evaluator: "0x0D160C869bd2a7AaEDd29e11fc60fdAEf21c3E28",
23
23
  arbiterSafe: "0x8FF6c3aD0991Ac848BFf5d0acD78BBc5e190466f",
24
24
  };
25
25
  const ALLOWED = [8453, 31_337];
@@ -44,7 +44,9 @@ export const verifiedEvaluatorAbi = parseAbi([
44
44
  "struct Verdict { uint8 phase; bool providerApproved; uint8 approvals; uint8 rejections; uint8 topApprovals; uint64 voteEnds; uint64 challengeEnds; address challenger; uint256 bond; bytes32 deliverable; bytes32 voteHash; }",
45
45
  "function configure(uint256 jobId, Config cfg)",
46
46
  "function getVerdict(uint256 jobId) view returns (Verdict)",
47
+ "function outcomesOf(uint256 agentId) view returns (uint64 approved, uint64 rejected)",
47
48
  "function finalize(uint256 jobId)",
49
+ "function minChallengeWindow() view returns (uint64)",
48
50
  ]);
49
51
  /** ARLVerifiedEvaluator.Phase, by index. */
50
52
  export const VERDICT_PHASES = [
@@ -116,6 +118,21 @@ export function checkOpenParams(p) {
116
118
  if (!/^0x[0-9a-fA-F]{64}$/.test(p.specHash))
117
119
  throw new VerifiedJobError("specHash must be 32 bytes");
118
120
  }
121
+ /** Time left after the windows for the committee to accept before voting starts (one day). */
122
+ const ACCEPT_SLACK = 86400n;
123
+ /**
124
+ * The windows and lifetime openVerifiedJob uses when the caller gives none. The challenge window
125
+ * defaults to the evaluator's minimum (one day on Base Mainnet) and the job lives long enough for
126
+ * the evaluator's own check at configure and at voting start (`_checkFits`: the vote window plus
127
+ * two challenge windows), with a day to spare for the committee to accept.
128
+ */
129
+ export function defaultWindows(minChallengeWindow, p) {
130
+ const voteWindow = p.voteWindow ?? 3600n;
131
+ const challengeWindow = p.challengeWindow ?? (minChallengeWindow > 3600n ? minChallengeWindow : 3600n);
132
+ const needed = voteWindow + 2n * challengeWindow + ACCEPT_SLACK;
133
+ const expiresIn = p.expiresIn ?? (needed > 86400n ? needed : 86400n);
134
+ return { voteWindow, challengeWindow, expiresIn };
135
+ }
119
136
  /**
120
137
  * Creates the job (the caller is its client) and configures the committee in two transactions.
121
138
  * The provider then approves the committee and sets the budget; the client funds the job.
@@ -130,10 +147,14 @@ export async function openVerifiedJob({ publicClient, walletClient }, p) {
130
147
  throw new VerifiedJobError("jobs and evaluator are required locally");
131
148
  await requireCode(publicClient, jobs, "jobs escrow");
132
149
  await requireCode(publicClient, evaluator, "evaluator");
133
- const voteWindow = p.voteWindow ?? 3600n;
134
- const challengeWindow = p.challengeWindow ?? 3600n;
150
+ const minChallengeWindow = await publicClient.readContract({
151
+ address: evaluator,
152
+ abi: verifiedEvaluatorAbi,
153
+ functionName: "minChallengeWindow",
154
+ });
155
+ const { voteWindow, challengeWindow, expiresIn } = defaultWindows(minChallengeWindow, p);
135
156
  const { timestamp } = await publicClient.getBlock();
136
- const expiredAt = timestamp + (p.expiresIn ?? 86400n);
157
+ const expiredAt = timestamp + expiresIn;
137
158
  const from = walletAccount(walletClient);
138
159
  const createTx = await walletClient.writeContract({
139
160
  account: from,
@@ -199,6 +220,25 @@ export async function getVerdict(publicClient, jobId, evaluator) {
199
220
  });
200
221
  return { ...v, phaseName: VERDICT_PHASES[v.phase] ?? `Phase ${String(v.phase)}` };
201
222
  }
223
+ export async function getOutcomes(publicClient, evaluatorOrAgentId, agentIdOrEvaluator) {
224
+ const chainId = await checkVerifiedChain(publicClient);
225
+ const [evaluator, agentId] = typeof evaluatorOrAgentId === "bigint"
226
+ ? [agentIdOrEvaluator, evaluatorOrAgentId]
227
+ : [evaluatorOrAgentId, agentIdOrEvaluator];
228
+ if (typeof agentId !== "bigint" || agentId < 0n) {
229
+ throw new VerifiedJobError("agentId must be a non-negative bigint");
230
+ }
231
+ const address = evaluator ?? verifiedDeployment(chainId)?.evaluator;
232
+ if (!address)
233
+ throw new VerifiedJobError("evaluator is required locally");
234
+ const [approved, rejected] = await publicClient.readContract({
235
+ address,
236
+ abi: verifiedEvaluatorAbi,
237
+ functionName: "outcomesOf",
238
+ args: [agentId],
239
+ });
240
+ return { approved, rejected };
241
+ }
202
242
  /** Pays out after the challenge window: anyone may call it. */
203
243
  export async function finalizeJob({ publicClient, walletClient }, jobId, evaluator) {
204
244
  const chainId = await checkVerifiedChain(publicClient);