arl-protocol-sdk 0.2.2 → 0.3.2

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,58 @@
1
+ import { type Address, type Hex, type PublicClient } from "viem";
2
+ import type { HistoryOptions } from "./agentScore.ts";
3
+ import { type JobAudit } from "./audit.ts";
4
+ /** EAS and its SchemaRegistry on Base (OP Stack predeploys). */
5
+ export declare const EAS: Address;
6
+ export declare const EAS_SCHEMA_REGISTRY: Address;
7
+ /** The receipt's EAS schema. Field order and types are part of the schema's identity. */
8
+ export declare const RECEIPT_SCHEMA = "uint256 chainId,address escrow,uint256 jobId,address client,address provider,uint256 providerAgentId,bool approved,bytes32 deliverable,bytes32 specHash,bytes32 voteHash,uint64 finalizedAt";
9
+ /** The schema's UID: no resolver, not revocable (a settled job does not change). */
10
+ export declare function receiptSchemaUid(): Hex;
11
+ export interface JobReceipt {
12
+ chainId: number;
13
+ escrow: Address;
14
+ jobId: bigint;
15
+ client: Address;
16
+ provider: Address;
17
+ providerAgentId: bigint;
18
+ /** The committee's verdict as finalized: true paid the provider, false refunded the client. */
19
+ approved: boolean;
20
+ deliverable: Hex;
21
+ specHash: Hex;
22
+ voteHash: Hex;
23
+ /** Unix seconds of the Finalized event. */
24
+ finalizedAt: number;
25
+ }
26
+ /** An unsigned transaction, for the caller's own wallet. */
27
+ export interface PreparedCall {
28
+ to: Address;
29
+ data: Hex;
30
+ value: "0";
31
+ }
32
+ /**
33
+ * The receipt of a job, from its audit trail. Null while the job is not finalized, or when the
34
+ * trail lacks an event the receipt needs (it is then not a job of the verified evaluator).
35
+ */
36
+ export declare function receiptFromAudit(audit: JobAudit, chainId?: number): JobReceipt | null;
37
+ /** The receipt as EAS attestation data, in the schema's field order. */
38
+ export declare function encodeReceipt(r: JobReceipt): Hex;
39
+ /** The unsigned EAS `attest` call for a receipt: recipient is the provider, never expires. */
40
+ export declare function prepareReceiptAttestation(r: JobReceipt): PreparedCall;
41
+ /** The unsigned call that registers the receipt schema; needed once, by anyone. */
42
+ export declare function prepareReceiptSchemaRegistration(): PreparedCall;
43
+ export interface JobReceiptAnswer {
44
+ /** The block the job was read at. */
45
+ block: bigint;
46
+ /** Null while the job is not finalized. */
47
+ receipt: JobReceipt | null;
48
+ schema: string;
49
+ schemaUid: Hex;
50
+ /** Whether the schema is registered on EAS yet; an attestation needs it. */
51
+ schemaRegistered: boolean;
52
+ /** The unsigned `attest` call, when there is a receipt. */
53
+ attest?: PreparedCall;
54
+ /** The unsigned `register` call, while the schema is not registered. */
55
+ registerSchema?: PreparedCall;
56
+ }
57
+ /** Reads a job's receipt and prepares the calls that put it on EAS. */
58
+ export declare function getJobReceipt(client: PublicClient, token: "ARL" | "USDC", jobId: bigint, opts?: HistoryOptions): Promise<JobReceiptAnswer>;
@@ -0,0 +1,157 @@
1
+ // A portable receipt for a finalized verified job, as an Ethereum Attestation Service (EAS)
2
+ // attestation on Base. The receipt restates what the escrow and the evaluator already recorded
3
+ // (who, what was delivered, what the committee decided), in one record another platform can read
4
+ // without knowing ARL's contracts.
5
+ //
6
+ // Nothing here signs or sends. The SDK builds the receipt from the job's audit trail and prepares
7
+ // the unsigned `attest` transaction; whoever wants the receipt on EAS (usually the provider, whose
8
+ // record it is) sends it from their own wallet. A receipt is only as true as the job it names:
9
+ // anyone can check it against the audit trail, and this module's `receiptFromAudit` is that check.
10
+ import { encodeAbiParameters, encodeFunctionData, encodePacked, keccak256, parseAbi, } from "viem";
11
+ import { getJobAudit } from "./audit.js";
12
+ /** EAS and its SchemaRegistry on Base (OP Stack predeploys). */
13
+ export const EAS = "0x4200000000000000000000000000000000000021";
14
+ export const EAS_SCHEMA_REGISTRY = "0x4200000000000000000000000000000000000020";
15
+ /** The receipt's EAS schema. Field order and types are part of the schema's identity. */
16
+ export const RECEIPT_SCHEMA = "uint256 chainId,address escrow,uint256 jobId,address client,address provider,uint256 providerAgentId,bool approved,bytes32 deliverable,bytes32 specHash,bytes32 voteHash,uint64 finalizedAt";
17
+ const ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
18
+ const ZERO_BYTES32 = `0x${"00".repeat(32)}`;
19
+ const easAbi = parseAbi([
20
+ "struct AttestationRequestData { address recipient; uint64 expirationTime; bool revocable; bytes32 refUID; bytes data; uint256 value; }",
21
+ "struct AttestationRequest { bytes32 schema; AttestationRequestData data; }",
22
+ "function attest(AttestationRequest request) payable returns (bytes32)",
23
+ ]);
24
+ const registryAbi = parseAbi([
25
+ "struct SchemaRecord { bytes32 uid; address resolver; bool revocable; string schema; }",
26
+ "function register(string schema, address resolver, bool revocable) returns (bytes32)",
27
+ "function getSchema(bytes32 uid) view returns (SchemaRecord)",
28
+ ]);
29
+ /** The schema's UID: no resolver, not revocable (a settled job does not change). */
30
+ export function receiptSchemaUid() {
31
+ return keccak256(encodePacked(["string", "address", "bool"], [RECEIPT_SCHEMA, ZERO_ADDRESS, false]));
32
+ }
33
+ const bytes32 = (v) => typeof v === "string" && /^0x[0-9a-fA-F]{64}$/.test(v) ? v : null;
34
+ /**
35
+ * The receipt of a job, from its audit trail. Null while the job is not finalized, or when the
36
+ * trail lacks an event the receipt needs (it is then not a job of the verified evaluator).
37
+ */
38
+ export function receiptFromAudit(audit, chainId = 8453) {
39
+ const last = (event) => audit.entries.filter((e) => e.event === event).at(-1);
40
+ const created = last("JobCreated");
41
+ const configured = last("Configured");
42
+ const submitted = last("JobSubmitted");
43
+ const finalized = last("Finalized");
44
+ if (!created?.actor || !configured || !finalized)
45
+ return null;
46
+ const provider = created.detail.provider;
47
+ const agent = configured.detail.providerAgentId;
48
+ const specHash = bytes32(configured.detail.specHash);
49
+ const voteHash = bytes32(finalized.detail.voteHash);
50
+ if (typeof provider !== "string" ||
51
+ typeof agent !== "string" ||
52
+ typeof finalized.detail.approved !== "boolean" ||
53
+ !specHash ||
54
+ !voteHash)
55
+ return null;
56
+ return {
57
+ chainId,
58
+ escrow: audit.escrow,
59
+ jobId: audit.jobId,
60
+ client: created.actor,
61
+ provider: provider,
62
+ providerAgentId: BigInt(agent),
63
+ approved: finalized.detail.approved,
64
+ // A job rejected before any delivery has no deliverable.
65
+ deliverable: bytes32(submitted?.detail.deliverable) ?? ZERO_BYTES32,
66
+ specHash,
67
+ voteHash,
68
+ finalizedAt: finalized.at,
69
+ };
70
+ }
71
+ /** The receipt as EAS attestation data, in the schema's field order. */
72
+ export function encodeReceipt(r) {
73
+ return encodeAbiParameters([
74
+ { type: "uint256" },
75
+ { type: "address" },
76
+ { type: "uint256" },
77
+ { type: "address" },
78
+ { type: "address" },
79
+ { type: "uint256" },
80
+ { type: "bool" },
81
+ { type: "bytes32" },
82
+ { type: "bytes32" },
83
+ { type: "bytes32" },
84
+ { type: "uint64" },
85
+ ], [
86
+ BigInt(r.chainId),
87
+ r.escrow,
88
+ r.jobId,
89
+ r.client,
90
+ r.provider,
91
+ r.providerAgentId,
92
+ r.approved,
93
+ r.deliverable,
94
+ r.specHash,
95
+ r.voteHash,
96
+ BigInt(r.finalizedAt),
97
+ ]);
98
+ }
99
+ /** The unsigned EAS `attest` call for a receipt: recipient is the provider, never expires. */
100
+ export function prepareReceiptAttestation(r) {
101
+ return {
102
+ to: EAS,
103
+ data: encodeFunctionData({
104
+ abi: easAbi,
105
+ functionName: "attest",
106
+ args: [
107
+ {
108
+ schema: receiptSchemaUid(),
109
+ data: {
110
+ recipient: r.provider,
111
+ expirationTime: 0n,
112
+ revocable: false,
113
+ refUID: ZERO_BYTES32,
114
+ data: encodeReceipt(r),
115
+ value: 0n,
116
+ },
117
+ },
118
+ ],
119
+ }),
120
+ value: "0",
121
+ };
122
+ }
123
+ /** The unsigned call that registers the receipt schema; needed once, by anyone. */
124
+ export function prepareReceiptSchemaRegistration() {
125
+ return {
126
+ to: EAS_SCHEMA_REGISTRY,
127
+ data: encodeFunctionData({
128
+ abi: registryAbi,
129
+ functionName: "register",
130
+ args: [RECEIPT_SCHEMA, ZERO_ADDRESS, false],
131
+ }),
132
+ value: "0",
133
+ };
134
+ }
135
+ /** Reads a job's receipt and prepares the calls that put it on EAS. */
136
+ export async function getJobReceipt(client, token, jobId, opts = {}) {
137
+ const audit = await getJobAudit(client, token, jobId, opts);
138
+ const receipt = receiptFromAudit(audit);
139
+ const schemaUid = receiptSchemaUid();
140
+ const record = await client.readContract({
141
+ address: EAS_SCHEMA_REGISTRY,
142
+ abi: registryAbi,
143
+ functionName: "getSchema",
144
+ args: [schemaUid],
145
+ blockNumber: audit.block,
146
+ });
147
+ const schemaRegistered = record.uid.toLowerCase() === schemaUid.toLowerCase();
148
+ return {
149
+ block: audit.block,
150
+ receipt,
151
+ schema: RECEIPT_SCHEMA,
152
+ schemaUid,
153
+ schemaRegistered,
154
+ ...(receipt ? { attest: prepareReceiptAttestation(receipt) } : {}),
155
+ ...(schemaRegistered ? {} : { registerSchema: prepareReceiptSchemaRegistration() }),
156
+ };
157
+ }
@@ -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
+ }