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.
- package/README.md +39 -1
- package/package.json +1 -1
- package/protocol/src/deployments.js +2 -2
- package/protocol/src/evidence.d.ts +0 -5
- package/protocol/src/evidence.js +20 -4
- package/protocol/src/index.d.ts +2 -0
- package/protocol/src/index.js +1 -0
- package/protocol/src/policies.js +54 -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 +6 -1
- package/sdk/src/index.js +6 -1
- 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
- package/sdk/src/verified.d.ts +49 -1
- package/sdk/src/verified.js +44 -4
|
@@ -0,0 +1,335 @@
|
|
|
1
|
+
// An agent's ARL score (arl-reputation/1) read from Base Mainnet, the spec's read path end to end:
|
|
2
|
+
//
|
|
3
|
+
// const { score, outcomes } = await getAgentScore(publicClient, 42n);
|
|
4
|
+
// score.score_bps // 0-10000, or null below 3 outcomes from 2 clients
|
|
5
|
+
//
|
|
6
|
+
// It reads the feedback the verified evaluators wrote to the ERC-8004 ReputationRegistry, the
|
|
7
|
+
// evaluators' own events and the jobs, joins them with `outcomesFromChain` and scores them with
|
|
8
|
+
// `reputationScore` (packages/protocol). Only the deployed verified evaluators count: earlier
|
|
9
|
+
// evaluators never had a job (contracts/deploy/base-mainnet-jobs.json).
|
|
10
|
+
import { getAddress, isAddressEqual, parseAbi, } from "viem";
|
|
11
|
+
import { outcomesFromChain, reputationScore, } from "../../protocol/src/index.js";
|
|
12
|
+
import { STATUS, jobsAbi } from "./jobs.js";
|
|
13
|
+
export const REPUTATION_REGISTRY = "0x8004BAa17C55a88189AE136b182e5fdA19dE9b63";
|
|
14
|
+
/** The verified evaluators on Base Mainnet, with their escrow and creation block. */
|
|
15
|
+
export const VERIFIED_EVALUATORS = [
|
|
16
|
+
{
|
|
17
|
+
token: "ARL",
|
|
18
|
+
evaluator: "0x0D160C869bd2a7AaEDd29e11fc60fdAEf21c3E28",
|
|
19
|
+
escrow: "0x9aE99bF9a59aF47E81346B7c0b93Cd2B610455fC",
|
|
20
|
+
fromBlock: 59577368n,
|
|
21
|
+
},
|
|
22
|
+
{
|
|
23
|
+
token: "USDC",
|
|
24
|
+
evaluator: "0x7A00D45598Da7C13feEA8962fc1110FC4Db4D850",
|
|
25
|
+
escrow: "0xE3eA0EAEc3Cf9DA2d0856A0f784A4B1671AeFD04",
|
|
26
|
+
fromBlock: 59579724n,
|
|
27
|
+
},
|
|
28
|
+
];
|
|
29
|
+
const registryEvents = parseAbi([
|
|
30
|
+
"event NewFeedback(uint256 indexed agentId, address indexed clientAddress, uint64 feedbackIndex, int128 value, uint8 valueDecimals, string indexed indexedTag1, string tag1, string tag2, string endpoint, string feedbackURI, bytes32 feedbackHash)",
|
|
31
|
+
]);
|
|
32
|
+
/** Every event of the escrow and the verified evaluator. */
|
|
33
|
+
export const protocolEvents = parseAbi([
|
|
34
|
+
"event JobCreated(uint256 indexed jobId, address indexed client, address indexed provider, address evaluator, uint256 expiredAt, address hook)",
|
|
35
|
+
"event ProviderSet(uint256 indexed jobId, address indexed provider)",
|
|
36
|
+
"event BudgetSet(uint256 indexed jobId, uint256 amount)",
|
|
37
|
+
"event JobFunded(uint256 indexed jobId, address indexed client, uint256 amount)",
|
|
38
|
+
"event JobSubmitted(uint256 indexed jobId, address indexed provider, bytes32 deliverable)",
|
|
39
|
+
"event JobCompleted(uint256 indexed jobId, address indexed evaluator, bytes32 reason)",
|
|
40
|
+
"event JobRejected(uint256 indexed jobId, address indexed rejector, bytes32 reason)",
|
|
41
|
+
"event JobExpired(uint256 indexed jobId)",
|
|
42
|
+
"event PaymentReleased(uint256 indexed jobId, address indexed provider, uint256 amount)",
|
|
43
|
+
"event Refunded(uint256 indexed jobId, address indexed client, uint256 amount)",
|
|
44
|
+
"event Configured(uint256 indexed jobId, uint8 tier, uint8 threshold, uint64 voteWindow, uint64 challengeWindow, uint96 bond, uint256 providerAgentId, bytes32 specHash, address[] committee)",
|
|
45
|
+
"event CommitteeApproved(uint256 indexed jobId, address indexed provider)",
|
|
46
|
+
"event Accepted(uint256 indexed jobId, address indexed validator, uint256 bond)",
|
|
47
|
+
"event VotingStarted(uint256 indexed jobId, uint64 voteEnds)",
|
|
48
|
+
"event Voted(uint256 indexed jobId, address indexed validator, bool approve, bytes32 deliverable, bytes32 evidence)",
|
|
49
|
+
"event Decided(uint256 indexed jobId, bool approved, uint64 challengeEnds)",
|
|
50
|
+
"event Disputed(uint256 indexed jobId, address indexed challenger, bytes32 evidence)",
|
|
51
|
+
"event Resolved(uint256 indexed jobId, bool approved, bool overturned, bytes32 reason)",
|
|
52
|
+
"event Slashed(uint256 indexed jobId, address indexed account, uint256 amount)",
|
|
53
|
+
"event Failed(uint256 indexed jobId)",
|
|
54
|
+
"event Finalized(uint256 indexed jobId, bool approved, bytes32 voteHash)",
|
|
55
|
+
"event Released(uint256 indexed jobId)",
|
|
56
|
+
"event FeedbackFailed(uint256 indexed jobId, uint256 agentId)",
|
|
57
|
+
"event RefundDeferred(uint256 indexed jobId)",
|
|
58
|
+
"event DisputeExpired(uint256 indexed jobId)",
|
|
59
|
+
"event Staked(address indexed validator, uint256 amount)",
|
|
60
|
+
"event Unstaked(address indexed validator, uint256 amount)",
|
|
61
|
+
]);
|
|
62
|
+
const MAX_SPAN = 50000n;
|
|
63
|
+
const MIN_SPAN = 500n;
|
|
64
|
+
// A rate limit and a range that is too wide are told apart by their wording: asking for a smaller
|
|
65
|
+
// range does not help against a rate limit, and waiting does not help against a range limit.
|
|
66
|
+
const TOO_WIDE = /block range|range (is )?too|max(imum)? (block )?range|query returned more than|response size|10000 results|-32614|-32602/i;
|
|
67
|
+
const RATE_LIMITED = /rate limit|request limit|limit exceeded|too many requests|status: 429|-32011|-32005|-32016/i;
|
|
68
|
+
const errorText = (e) => e instanceof Error
|
|
69
|
+
? `${e.message} ${e.details ?? ""} ${e.cause instanceof Error ? e.cause.message : ""}`
|
|
70
|
+
: String(e);
|
|
71
|
+
/** How many block ranges are read at once, while the endpoint allows it. */
|
|
72
|
+
const CONCURRENCY = 2;
|
|
73
|
+
/**
|
|
74
|
+
* getLogs over [from, to] in spans the endpoint accepts. The ranges are fixed 50,000-block steps
|
|
75
|
+
* from `from` (so a finished range is always asked for the same way and can be cached) and are
|
|
76
|
+
* read two at a time; the answer keeps block order. Once the endpoint rate-limits a request the
|
|
77
|
+
* rest are read one after another.
|
|
78
|
+
*/
|
|
79
|
+
export async function logsInRange(from, to, read, wholeRange = false) {
|
|
80
|
+
// A client that stores finished scans itself takes the whole range in one request.
|
|
81
|
+
if (wholeRange)
|
|
82
|
+
return read(from, to);
|
|
83
|
+
const spans = [];
|
|
84
|
+
for (let start = from; start <= to; start += MAX_SPAN) {
|
|
85
|
+
const end = start + MAX_SPAN - 1n;
|
|
86
|
+
spans.push([start, end < to ? end : to]);
|
|
87
|
+
}
|
|
88
|
+
const parts = new Array(spans.length);
|
|
89
|
+
let next = 0;
|
|
90
|
+
let limited = false;
|
|
91
|
+
const worker = async (id) => {
|
|
92
|
+
while (next < spans.length && !(limited && id > 0)) {
|
|
93
|
+
const i = next++;
|
|
94
|
+
const [start, end] = spans[i];
|
|
95
|
+
parts[i] = await logsInSpan(start, end, read, () => {
|
|
96
|
+
limited = true;
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
await Promise.all(Array.from({ length: Math.min(CONCURRENCY, spans.length) }, (_, id) => worker(id)));
|
|
101
|
+
return parts.flat();
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* One range: the span halves when the endpoint asks for a smaller range, and a rate-limited
|
|
105
|
+
* request waits and is asked again (three times at most).
|
|
106
|
+
*/
|
|
107
|
+
async function logsInSpan(from, to, read, onRateLimited) {
|
|
108
|
+
const out = [];
|
|
109
|
+
let span = MAX_SPAN;
|
|
110
|
+
let start = from;
|
|
111
|
+
let waits = 0;
|
|
112
|
+
while (start <= to) {
|
|
113
|
+
const end = start + span - 1n < to ? start + span - 1n : to;
|
|
114
|
+
try {
|
|
115
|
+
out.push(...(await read(start, end)));
|
|
116
|
+
start = end + 1n;
|
|
117
|
+
waits = 0;
|
|
118
|
+
}
|
|
119
|
+
catch (e) {
|
|
120
|
+
const text = errorText(e);
|
|
121
|
+
if (TOO_WIDE.test(text) && span > MIN_SPAN) {
|
|
122
|
+
span /= 2n;
|
|
123
|
+
}
|
|
124
|
+
else if (RATE_LIMITED.test(text) && waits < 5) {
|
|
125
|
+
onRateLimited();
|
|
126
|
+
waits += 1;
|
|
127
|
+
await new Promise((r) => setTimeout(r, 1000 * waits));
|
|
128
|
+
}
|
|
129
|
+
else {
|
|
130
|
+
throw e;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
return out;
|
|
135
|
+
}
|
|
136
|
+
/** The first block any verified evaluator has code at: where every scan starts. */
|
|
137
|
+
export const HISTORY_START = VERIFIED_EVALUATORS.reduce((min, e) => (e.fromBlock < min ? e.fromBlock : min), VERIFIED_EVALUATORS[0].fromBlock);
|
|
138
|
+
/**
|
|
139
|
+
* The events of every escrow and evaluator in [from, to], in one request per range. The filter is
|
|
140
|
+
* the same for every caller, so a provider that stores finished ranges serves the score, the
|
|
141
|
+
* trust graph and the audit trail from one store.
|
|
142
|
+
*/
|
|
143
|
+
export function readProtocolLogs(client, from, to, opts = {}) {
|
|
144
|
+
return logsInRange(from, to, (fromBlock, toBlock) => client.getLogs({
|
|
145
|
+
address: VERIFIED_EVALUATORS.flatMap((e) => [e.evaluator, e.escrow]),
|
|
146
|
+
events: protocolEvents,
|
|
147
|
+
fromBlock,
|
|
148
|
+
toBlock,
|
|
149
|
+
}), opts.wholeRange);
|
|
150
|
+
}
|
|
151
|
+
/** Everything the verified evaluators recorded, read once and used for any number of agents. */
|
|
152
|
+
async function readHistory(client, opts = {}) {
|
|
153
|
+
const head = await client.getBlock();
|
|
154
|
+
const to = head.number;
|
|
155
|
+
const from = HISTORY_START;
|
|
156
|
+
// Two reads per block range: the feedback the evaluators wrote to the registry, and the
|
|
157
|
+
// evaluators' and escrows' events (few, for every job) in one request. Neither filter names the
|
|
158
|
+
// agent, so a provider that stores finished ranges serves every agent from the same store.
|
|
159
|
+
const [feedbackLogs, protocolLogs] = await Promise.all([
|
|
160
|
+
logsInRange(from, to, (fromBlock, toBlock) => client.getLogs({
|
|
161
|
+
address: REPUTATION_REGISTRY,
|
|
162
|
+
event: registryEvents[0],
|
|
163
|
+
args: { clientAddress: VERIFIED_EVALUATORS.map((e) => e.evaluator) },
|
|
164
|
+
fromBlock,
|
|
165
|
+
toBlock,
|
|
166
|
+
}), opts.wholeRange),
|
|
167
|
+
readProtocolLogs(client, from, to, opts),
|
|
168
|
+
]);
|
|
169
|
+
return { head, to, feedbackLogs, protocolLogs };
|
|
170
|
+
}
|
|
171
|
+
/** One agent's verified outcomes from the history, with the jobs read at the history's block. */
|
|
172
|
+
async function agentOutcomes(client, history, agentId) {
|
|
173
|
+
const { to, feedbackLogs, protocolLogs } = history;
|
|
174
|
+
const evaluators = [];
|
|
175
|
+
const jobs = [];
|
|
176
|
+
for (const e of VERIFIED_EVALUATORS) {
|
|
177
|
+
const ev = {
|
|
178
|
+
evaluator: e.evaluator,
|
|
179
|
+
escrow: e.escrow,
|
|
180
|
+
token: e.token,
|
|
181
|
+
configured: [],
|
|
182
|
+
committeeApproved: [],
|
|
183
|
+
unbound: [],
|
|
184
|
+
finalized: [],
|
|
185
|
+
disputed: [],
|
|
186
|
+
failed: [],
|
|
187
|
+
};
|
|
188
|
+
const of = (address) => protocolLogs.filter((l) => isAddressEqual(l.address, address));
|
|
189
|
+
const logs = of(e.evaluator);
|
|
190
|
+
const approvedTx = new Map();
|
|
191
|
+
for (const l of logs) {
|
|
192
|
+
const a = l.args;
|
|
193
|
+
const jobId = a.jobId;
|
|
194
|
+
switch (l.eventName) {
|
|
195
|
+
case "Configured":
|
|
196
|
+
ev.configured.push({ jobId, providerAgentId: a.providerAgentId });
|
|
197
|
+
break;
|
|
198
|
+
case "CommitteeApproved":
|
|
199
|
+
ev.committeeApproved.push(jobId);
|
|
200
|
+
approvedTx.set(l.transactionHash, jobId);
|
|
201
|
+
break;
|
|
202
|
+
case "Finalized":
|
|
203
|
+
ev.finalized.push({ jobId, voteHash: a.voteHash });
|
|
204
|
+
break;
|
|
205
|
+
case "Disputed":
|
|
206
|
+
ev.disputed.push(jobId);
|
|
207
|
+
break;
|
|
208
|
+
case "Failed":
|
|
209
|
+
ev.failed.push(jobId);
|
|
210
|
+
break;
|
|
211
|
+
default:
|
|
212
|
+
break;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
// FeedbackFailed in the approval transaction: the agent could not be bound to the job.
|
|
216
|
+
for (const l of logs)
|
|
217
|
+
if (l.eventName === "FeedbackFailed" && approvedTx.get(l.transactionHash) !== undefined)
|
|
218
|
+
ev.unbound.push(l.args.jobId);
|
|
219
|
+
evaluators.push(ev);
|
|
220
|
+
const mine = ev.configured.filter((c) => c.providerAgentId === agentId).map((c) => c.jobId);
|
|
221
|
+
const expiredBlock = new Map();
|
|
222
|
+
for (const l of of(e.escrow)) {
|
|
223
|
+
const id = l.args.jobId;
|
|
224
|
+
if (l.eventName === "JobExpired" && id !== undefined && mine.includes(id))
|
|
225
|
+
expiredBlock.set(id, l.blockNumber);
|
|
226
|
+
}
|
|
227
|
+
for (const jobId of mine) {
|
|
228
|
+
const j = await client.readContract({
|
|
229
|
+
address: e.escrow,
|
|
230
|
+
abi: jobsAbi,
|
|
231
|
+
functionName: "getJob",
|
|
232
|
+
args: [jobId],
|
|
233
|
+
blockNumber: to,
|
|
234
|
+
});
|
|
235
|
+
const at = expiredBlock.get(jobId);
|
|
236
|
+
jobs.push({
|
|
237
|
+
escrow: e.escrow,
|
|
238
|
+
jobId,
|
|
239
|
+
client: j.client,
|
|
240
|
+
budget: j.budget,
|
|
241
|
+
status: STATUS[j.status] ?? `Status ${String(j.status)}`,
|
|
242
|
+
...(at === undefined ? {} : { expiredAt: await blockTime(client, at) }),
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
const feedback = [];
|
|
247
|
+
for (const l of feedbackLogs) {
|
|
248
|
+
if (l.args.agentId !== agentId)
|
|
249
|
+
continue;
|
|
250
|
+
feedback.push({
|
|
251
|
+
evaluator: l.args.clientAddress,
|
|
252
|
+
agentId: l.args.agentId,
|
|
253
|
+
value: l.args.value,
|
|
254
|
+
valueDecimals: l.args.valueDecimals,
|
|
255
|
+
tag1: l.args.tag1,
|
|
256
|
+
feedbackHash: l.args.feedbackHash,
|
|
257
|
+
timestamp: await blockTime(client, l.blockNumber),
|
|
258
|
+
});
|
|
259
|
+
}
|
|
260
|
+
return outcomesFromChain(agentId, feedback, evaluators, jobs);
|
|
261
|
+
}
|
|
262
|
+
export async function getAgentScore(client, agentId, opts = {}) {
|
|
263
|
+
const history = await readHistory(client, opts);
|
|
264
|
+
const { outcomes, skipped } = await agentOutcomes(client, history, agentId);
|
|
265
|
+
const now = opts.now ?? Number(history.head.timestamp);
|
|
266
|
+
return {
|
|
267
|
+
agentId,
|
|
268
|
+
block: history.to,
|
|
269
|
+
score: reputationScore(outcomes, now),
|
|
270
|
+
outcomes,
|
|
271
|
+
skipped,
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
/**
|
|
275
|
+
* The trust graph of verified work: every agent with a verified outcome, its score, and an edge
|
|
276
|
+
* for each client it worked for. Built from the same records as the score, so an edge exists only
|
|
277
|
+
* where a committee settled a job (or the agent let one expire).
|
|
278
|
+
*/
|
|
279
|
+
export async function getTrustGraph(client, opts = {}) {
|
|
280
|
+
const history = await readHistory(client, opts);
|
|
281
|
+
const now = opts.now ?? Number(history.head.timestamp);
|
|
282
|
+
const ids = new Set();
|
|
283
|
+
for (const l of history.protocolLogs) {
|
|
284
|
+
if (l.eventName === "Configured")
|
|
285
|
+
ids.add(l.args.providerAgentId);
|
|
286
|
+
}
|
|
287
|
+
const agents = [];
|
|
288
|
+
const edges = new Map();
|
|
289
|
+
for (const agentId of [...ids].sort((x, y) => (x < y ? -1 : x > y ? 1 : 0))) {
|
|
290
|
+
const { outcomes } = await agentOutcomes(client, history, agentId);
|
|
291
|
+
if (outcomes.length === 0)
|
|
292
|
+
continue;
|
|
293
|
+
agents.push({ agentId, score: reputationScore(outcomes, now) });
|
|
294
|
+
for (const o of outcomes) {
|
|
295
|
+
const key = `${o.client.toLowerCase()}:${agentId.toString()}`;
|
|
296
|
+
let e = edges.get(key);
|
|
297
|
+
if (!e) {
|
|
298
|
+
e = {
|
|
299
|
+
client: getAddress(o.client),
|
|
300
|
+
agentId,
|
|
301
|
+
completed: 0,
|
|
302
|
+
rejected: 0,
|
|
303
|
+
expired: 0,
|
|
304
|
+
disputed: 0,
|
|
305
|
+
paid: {},
|
|
306
|
+
first: o.final_at,
|
|
307
|
+
latest: o.final_at,
|
|
308
|
+
};
|
|
309
|
+
edges.set(key, e);
|
|
310
|
+
}
|
|
311
|
+
if (o.outcome === "completed") {
|
|
312
|
+
e.completed += 1;
|
|
313
|
+
e.paid[o.token] = (BigInt(e.paid[o.token] ?? "0") + BigInt(o.budget)).toString();
|
|
314
|
+
}
|
|
315
|
+
else if (o.outcome === "rejected")
|
|
316
|
+
e.rejected += 1;
|
|
317
|
+
else if (o.outcome === "expired")
|
|
318
|
+
e.expired += 1;
|
|
319
|
+
if (o.disputed)
|
|
320
|
+
e.disputed += 1;
|
|
321
|
+
e.first = Math.min(e.first, o.final_at);
|
|
322
|
+
e.latest = Math.max(e.latest, o.final_at);
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
return { block: history.to, agents, edges: [...edges.values()] };
|
|
326
|
+
}
|
|
327
|
+
const times = new Map();
|
|
328
|
+
export async function blockTime(client, block) {
|
|
329
|
+
const known = times.get(block);
|
|
330
|
+
if (known !== undefined)
|
|
331
|
+
return known;
|
|
332
|
+
const t = Number((await client.getBlock({ blockNumber: block })).timestamp);
|
|
333
|
+
times.set(block, t);
|
|
334
|
+
return t;
|
|
335
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { type Address, type Hex, type PublicClient } from "viem";
|
|
2
|
+
import { type HistoryOptions } from "./agentScore.ts";
|
|
3
|
+
export type AuditValue = string | boolean | number | string[];
|
|
4
|
+
export interface AuditEntry {
|
|
5
|
+
/** What happened, in one sentence. */
|
|
6
|
+
step: string;
|
|
7
|
+
/** The on-chain event's name. */
|
|
8
|
+
event: string;
|
|
9
|
+
contract: "escrow" | "evaluator";
|
|
10
|
+
block: bigint;
|
|
11
|
+
/** Unix seconds of the block. */
|
|
12
|
+
at: number;
|
|
13
|
+
transaction: Hex;
|
|
14
|
+
logIndex: number;
|
|
15
|
+
/** Who acted, where the event names them. */
|
|
16
|
+
actor?: Address;
|
|
17
|
+
/** The event's other values: amounts in base units, hashes as emitted. */
|
|
18
|
+
detail: Record<string, AuditValue>;
|
|
19
|
+
}
|
|
20
|
+
export interface JobAudit {
|
|
21
|
+
token: "ARL" | "USDC";
|
|
22
|
+
escrow: Address;
|
|
23
|
+
evaluator: Address;
|
|
24
|
+
jobId: bigint;
|
|
25
|
+
/** The block the trail was read at. */
|
|
26
|
+
block: bigint;
|
|
27
|
+
entries: AuditEntry[];
|
|
28
|
+
}
|
|
29
|
+
/** Reads the audit trail of a job on the ARL or the USDC escrow of the verified evaluators. */
|
|
30
|
+
export declare function getJobAudit(client: PublicClient, token: "ARL" | "USDC", jobId: bigint, opts?: HistoryOptions): Promise<JobAudit>;
|
package/sdk/src/audit.js
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
// The audit trail of one verified job: every event the escrow and the evaluator emitted for it, in
|
|
2
|
+
// order, with who acted, when, in which transaction and with which hashes. It answers the question
|
|
3
|
+
// an auditor asks about work an AI agent was paid for: who approved it, when, and on what evidence.
|
|
4
|
+
//
|
|
5
|
+
// Nothing here is interpreted beyond naming the step: each entry is one on-chain event, and the
|
|
6
|
+
// block the trail was read at is part of the answer, so anyone can re-read it.
|
|
7
|
+
import { getAddress, isAddressEqual } from "viem";
|
|
8
|
+
import { HISTORY_START, VERIFIED_EVALUATORS, blockTime, readProtocolLogs, } from "./agentScore.js";
|
|
9
|
+
/** What each event means, in the words of the flow (spec/x402-arl-escrow). */
|
|
10
|
+
const STEPS = {
|
|
11
|
+
JobCreated: "The client opened the job",
|
|
12
|
+
ProviderSet: "The provider was set",
|
|
13
|
+
BudgetSet: "The budget was set",
|
|
14
|
+
JobFunded: "The client funded the escrow",
|
|
15
|
+
Configured: "The client configured the verification (committee, threshold, windows, bond, spec)",
|
|
16
|
+
CommitteeApproved: "The provider approved the committee",
|
|
17
|
+
Accepted: "A committee member accepted the job and locked its bond",
|
|
18
|
+
JobSubmitted: "The provider submitted the deliverable",
|
|
19
|
+
VotingStarted: "The vote window opened",
|
|
20
|
+
Voted: "A committee member voted",
|
|
21
|
+
Decided: "The committee reached a verdict; the challenge window opened",
|
|
22
|
+
Disputed: "The verdict was disputed",
|
|
23
|
+
Resolved: "The arbiter ruled on the dispute",
|
|
24
|
+
DisputeExpired: "The arbiter did not rule in time; the verdict stood",
|
|
25
|
+
Slashed: "A bond was slashed",
|
|
26
|
+
Failed: "The committee did not decide; the job failed",
|
|
27
|
+
Finalized: "The verdict was finalized",
|
|
28
|
+
JobCompleted: "The escrow marked the job completed",
|
|
29
|
+
PaymentReleased: "The escrow paid the provider",
|
|
30
|
+
JobRejected: "The escrow marked the job rejected",
|
|
31
|
+
Refunded: "The escrow refunded the client",
|
|
32
|
+
RefundDeferred: "The refund could not be sent and waits for the client to claim it",
|
|
33
|
+
JobExpired: "The job expired",
|
|
34
|
+
Released: "The bonds were released",
|
|
35
|
+
FeedbackFailed: "The outcome could not be written to the reputation registry",
|
|
36
|
+
};
|
|
37
|
+
/** The argument that names who acted, per event. */
|
|
38
|
+
const ACTOR = {
|
|
39
|
+
JobCreated: "client",
|
|
40
|
+
JobFunded: "client",
|
|
41
|
+
ProviderSet: "provider",
|
|
42
|
+
CommitteeApproved: "provider",
|
|
43
|
+
JobSubmitted: "provider",
|
|
44
|
+
Accepted: "validator",
|
|
45
|
+
Voted: "validator",
|
|
46
|
+
Disputed: "challenger",
|
|
47
|
+
Slashed: "account",
|
|
48
|
+
JobCompleted: "evaluator",
|
|
49
|
+
JobRejected: "rejector",
|
|
50
|
+
};
|
|
51
|
+
const plain = (v) => typeof v === "bigint"
|
|
52
|
+
? v.toString()
|
|
53
|
+
: Array.isArray(v)
|
|
54
|
+
? v.map((x) => String(x))
|
|
55
|
+
: typeof v === "boolean" || typeof v === "number"
|
|
56
|
+
? v
|
|
57
|
+
: String(v);
|
|
58
|
+
/** Reads the audit trail of a job on the ARL or the USDC escrow of the verified evaluators. */
|
|
59
|
+
export async function getJobAudit(client, token, jobId, opts = {}) {
|
|
60
|
+
const deployment = VERIFIED_EVALUATORS.find((e) => e.token === token);
|
|
61
|
+
if (!deployment)
|
|
62
|
+
throw new Error(`no verified evaluator for ${token}`);
|
|
63
|
+
const head = await client.getBlock();
|
|
64
|
+
const logs = await readProtocolLogs(client, HISTORY_START, head.number, opts);
|
|
65
|
+
const entries = [];
|
|
66
|
+
for (const l of logs) {
|
|
67
|
+
const fromEscrow = isAddressEqual(l.address, deployment.escrow);
|
|
68
|
+
if (!fromEscrow && !isAddressEqual(l.address, deployment.evaluator))
|
|
69
|
+
continue;
|
|
70
|
+
const args = l.args;
|
|
71
|
+
if (args.jobId !== jobId)
|
|
72
|
+
continue;
|
|
73
|
+
const actorKey = ACTOR[l.eventName];
|
|
74
|
+
const detail = {};
|
|
75
|
+
for (const [k, v] of Object.entries(args)) {
|
|
76
|
+
if (k !== "jobId" && k !== actorKey)
|
|
77
|
+
detail[k] = plain(v);
|
|
78
|
+
}
|
|
79
|
+
const actor = actorKey === undefined ? undefined : args[actorKey];
|
|
80
|
+
entries.push({
|
|
81
|
+
step: STEPS[l.eventName] ?? l.eventName,
|
|
82
|
+
event: l.eventName,
|
|
83
|
+
contract: fromEscrow ? "escrow" : "evaluator",
|
|
84
|
+
block: l.blockNumber,
|
|
85
|
+
at: await blockTime(client, l.blockNumber),
|
|
86
|
+
transaction: l.transactionHash,
|
|
87
|
+
logIndex: l.logIndex,
|
|
88
|
+
...(typeof actor === "string" ? { actor: getAddress(actor) } : {}),
|
|
89
|
+
detail,
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
entries.sort((a, b) => a.block === b.block ? a.logIndex - b.logIndex : a.block < b.block ? -1 : 1);
|
|
93
|
+
return {
|
|
94
|
+
token,
|
|
95
|
+
escrow: deployment.escrow,
|
|
96
|
+
evaluator: deployment.evaluator,
|
|
97
|
+
jobId,
|
|
98
|
+
block: head.number,
|
|
99
|
+
entries,
|
|
100
|
+
};
|
|
101
|
+
}
|
package/sdk/src/index.d.ts
CHANGED
|
@@ -1,9 +1,14 @@
|
|
|
1
1
|
export { computePaymentAbi } from "./abi.ts";
|
|
2
2
|
export { BASE_MAINNET_CHAIN_ID, COMPUTE_PAYMENT, MAX_STREAM_DURATION_SECONDS, StreamingError, planStream, stopComputeStream, streamComputePayment, type ComputeStream, type StopComputeStreamParams, type StreamComputePaymentParams, type StreamSettlement, type StreamingClients, type StreamingErrorCode, } from "./streaming.ts";
|
|
3
|
-
export { BASE_MAINNET_VERIFIED, VERDICT_PHASES, VerifiedJobError, checkEvaluationFits, checkOpenParams, checkVerifiedChain, finalizeJob, getVerdict, openVerifiedJob, verifiedEvaluatorAbi, verifiedDeployment, verifiedJobsAbi, walletAccount, type OpenVerifiedJobParams, type VerifiedClients, } from "./verified.ts";
|
|
3
|
+
export { BASE_MAINNET_VERIFIED, VERDICT_PHASES, VerifiedJobError, checkEvaluationFits, checkOpenParams, checkVerifiedChain, finalizeJob, getOutcomes, getVerdict, openVerifiedJob, defaultWindows, verifiedEvaluatorAbi, verifiedDeployment, verifiedJobsAbi, walletAccount, type AgentOutcomes, type OpenVerifiedJobParams, type VerifiedClients, } from "./verified.ts";
|
|
4
4
|
export { ESCROW_SCHEME, JOB_HEADER, fundVerifiedJob, parseEscrowOffer, payVerified, type EscrowOffer, type PayVerifiedOptions, } from "./payVerified.ts";
|
|
5
5
|
export { ARL_SWAP, acquireArl, quoteArl, type AcquireArlParams, type ArlQuoteToken, } from "./acquireArl.ts";
|
|
6
6
|
export { acceptedCount, approveCommittee, buildEscrowOffer, checkFundedJob, submitDeliverable, waitForAcceptance, type EscrowOfferInput, } from "./escrowProvider.ts";
|
|
7
|
+
export { DELIVERABLE_HEADER, expressPayOnProof, memoryUsedJobs, payOnProof, type PayOnProofConfig, type PayOnProofDeps, type PayOnProofHandler, type PayOnProofResult, type UsedJobs, } from "./payOnProof.ts";
|
|
7
8
|
export { ArlJobError, ESCROWS, STATUS as JOB_STATUS, createJob, fundJob, getJob, setBudget, settleJob, submitWork, toBytes32, type Clients as JobClients, type CreateJobInput, type Escrow, type JobView, } from "./jobs.ts";
|
|
8
9
|
export * from "../../protocol/src/index.ts";
|
|
9
10
|
export { openTask, type OpenTaskOptions, type OpenedTask } from "./openTask.ts";
|
|
11
|
+
export { REPUTATION_REGISTRY, VERIFIED_EVALUATORS, getAgentScore, getTrustGraph, type AgentScore, type HistoryOptions, type TrustEdge, type TrustGraph, } from "./agentScore.ts";
|
|
12
|
+
export { getJobAudit, type AuditEntry, type AuditValue, type JobAudit } from "./audit.ts";
|
|
13
|
+
export { IDENTITY_REGISTRY, getAgentPassport, type AgentPassport } from "./passport.ts";
|
|
14
|
+
export { getValidators, type ValidatorRecord, type Validators } from "./validators.ts";
|
package/sdk/src/index.js
CHANGED
|
@@ -1,10 +1,15 @@
|
|
|
1
1
|
export { computePaymentAbi } from "./abi.js";
|
|
2
2
|
export { BASE_MAINNET_CHAIN_ID, COMPUTE_PAYMENT, MAX_STREAM_DURATION_SECONDS, StreamingError, planStream, stopComputeStream, streamComputePayment, } from "./streaming.js";
|
|
3
|
-
export { BASE_MAINNET_VERIFIED, VERDICT_PHASES, VerifiedJobError, checkEvaluationFits, checkOpenParams, checkVerifiedChain, finalizeJob, getVerdict, openVerifiedJob, verifiedEvaluatorAbi, verifiedDeployment, verifiedJobsAbi, walletAccount, } from "./verified.js";
|
|
3
|
+
export { BASE_MAINNET_VERIFIED, VERDICT_PHASES, VerifiedJobError, checkEvaluationFits, checkOpenParams, checkVerifiedChain, finalizeJob, getOutcomes, getVerdict, openVerifiedJob, defaultWindows, verifiedEvaluatorAbi, verifiedDeployment, verifiedJobsAbi, walletAccount, } from "./verified.js";
|
|
4
4
|
export { ESCROW_SCHEME, JOB_HEADER, fundVerifiedJob, parseEscrowOffer, payVerified, } from "./payVerified.js";
|
|
5
5
|
export { ARL_SWAP, acquireArl, quoteArl, } from "./acquireArl.js";
|
|
6
6
|
export { acceptedCount, approveCommittee, buildEscrowOffer, checkFundedJob, submitDeliverable, waitForAcceptance, } from "./escrowProvider.js";
|
|
7
|
+
export { DELIVERABLE_HEADER, expressPayOnProof, memoryUsedJobs, payOnProof, } from "./payOnProof.js";
|
|
7
8
|
export { ArlJobError, ESCROWS, STATUS as JOB_STATUS, createJob, fundJob, getJob, setBudget, settleJob, submitWork, toBytes32, } from "./jobs.js";
|
|
8
9
|
// arl-task/1 and the other protocol documents (packages/protocol), and opening a task on chain.
|
|
9
10
|
export * from "../../protocol/src/index.js";
|
|
10
11
|
export { openTask } from "./openTask.js";
|
|
12
|
+
export { REPUTATION_REGISTRY, VERIFIED_EVALUATORS, getAgentScore, getTrustGraph, } from "./agentScore.js";
|
|
13
|
+
export { getJobAudit } from "./audit.js";
|
|
14
|
+
export { IDENTITY_REGISTRY, getAgentPassport } from "./passport.js";
|
|
15
|
+
export { getValidators } from "./validators.js";
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { type Address, type PublicClient } from "viem";
|
|
2
|
+
import type { Outcome, Score } from "../../protocol/src/index.ts";
|
|
3
|
+
import { type HistoryOptions } from "./agentScore.ts";
|
|
4
|
+
/** Canonical ERC-8004 IdentityRegistry on Base Mainnet. */
|
|
5
|
+
export declare const IDENTITY_REGISTRY: Address;
|
|
6
|
+
export interface AgentPassport {
|
|
7
|
+
agentId: bigint;
|
|
8
|
+
/** The block everything was read at. */
|
|
9
|
+
block: bigint;
|
|
10
|
+
/** False when the IdentityRegistry has no such agent; the record below is then empty. */
|
|
11
|
+
registered: boolean;
|
|
12
|
+
owner?: Address;
|
|
13
|
+
/** As stated by the owner in the registration file. Untrusted. */
|
|
14
|
+
name?: string;
|
|
15
|
+
description?: string;
|
|
16
|
+
/** Where the registration file is, when it is not stored on chain. */
|
|
17
|
+
registrationUri?: string;
|
|
18
|
+
score: Score;
|
|
19
|
+
outcomes: Outcome[];
|
|
20
|
+
/** Unix seconds of the first and the latest verified outcome. */
|
|
21
|
+
firstOutcomeAt?: number;
|
|
22
|
+
latestOutcomeAt?: number;
|
|
23
|
+
}
|
|
24
|
+
/** Reads an agent's identity and its verified record at one block. */
|
|
25
|
+
export declare function getAgentPassport(client: PublicClient, agentId: bigint, opts?: HistoryOptions): Promise<AgentPassport>;
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
// The agent passport: one answer that says who an ERC-8004 agent is and what it has verifiably
|
|
2
|
+
// done. Identity comes from the IdentityRegistry (owner and registration file), the record from
|
|
3
|
+
// the verified evaluators (arl-reputation/1). Another platform can use it as its sign-in and
|
|
4
|
+
// trust check for an agent.
|
|
5
|
+
//
|
|
6
|
+
// The registration file is written by the agent's owner: everything taken from it is untrusted
|
|
7
|
+
// text, cut to a short length and stripped of control characters, and nothing in it changes the
|
|
8
|
+
// score.
|
|
9
|
+
import { getAddress, parseAbi } from "viem";
|
|
10
|
+
import { getAgentScore } from "./agentScore.js";
|
|
11
|
+
/** Canonical ERC-8004 IdentityRegistry on Base Mainnet. */
|
|
12
|
+
export const IDENTITY_REGISTRY = "0x8004A169FB4a3325136EB29fA0ceB6D2e539a432";
|
|
13
|
+
const identityAbi = parseAbi([
|
|
14
|
+
"function ownerOf(uint256 tokenId) view returns (address)",
|
|
15
|
+
"function tokenURI(uint256 tokenId) view returns (string)",
|
|
16
|
+
]);
|
|
17
|
+
const DATA_URI = "data:application/json;base64,";
|
|
18
|
+
const LIMITS = { name: 80, description: 500, uri: 512, file: 16_384 };
|
|
19
|
+
/** Untrusted text from a registration file: trimmed, bounded, no control characters. */
|
|
20
|
+
function clean(v, max) {
|
|
21
|
+
if (typeof v !== "string")
|
|
22
|
+
return undefined;
|
|
23
|
+
const s = v.replace(/\p{Cc}/gu, " ").trim();
|
|
24
|
+
return s === "" ? undefined : s.slice(0, max);
|
|
25
|
+
}
|
|
26
|
+
function registration(uri) {
|
|
27
|
+
if (!uri.startsWith(DATA_URI)) {
|
|
28
|
+
const where = clean(uri, LIMITS.uri);
|
|
29
|
+
return where === undefined ? {} : { registrationUri: where };
|
|
30
|
+
}
|
|
31
|
+
try {
|
|
32
|
+
const encoded = uri.slice(DATA_URI.length, DATA_URI.length + LIMITS.file * 2);
|
|
33
|
+
const file = JSON.parse(new TextDecoder().decode(base64(encoded)));
|
|
34
|
+
const name = clean(file.name, LIMITS.name);
|
|
35
|
+
const description = clean(file.description, LIMITS.description);
|
|
36
|
+
return { ...(name ? { name } : {}), ...(description ? { description } : {}) };
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
return {};
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
function base64(text) {
|
|
43
|
+
const binary = atob(text);
|
|
44
|
+
const bytes = new Uint8Array(binary.length);
|
|
45
|
+
for (let i = 0; i < binary.length; i++)
|
|
46
|
+
bytes[i] = binary.charCodeAt(i);
|
|
47
|
+
return bytes;
|
|
48
|
+
}
|
|
49
|
+
/** Reads an agent's identity and its verified record at one block. */
|
|
50
|
+
export async function getAgentPassport(client, agentId, opts = {}) {
|
|
51
|
+
const scored = await getAgentScore(client, agentId, opts);
|
|
52
|
+
const at = { blockNumber: scored.block };
|
|
53
|
+
let owner;
|
|
54
|
+
let uri = "";
|
|
55
|
+
try {
|
|
56
|
+
owner = getAddress(await client.readContract({
|
|
57
|
+
address: IDENTITY_REGISTRY,
|
|
58
|
+
abi: identityAbi,
|
|
59
|
+
functionName: "ownerOf",
|
|
60
|
+
args: [agentId],
|
|
61
|
+
...at,
|
|
62
|
+
}));
|
|
63
|
+
uri = await client.readContract({
|
|
64
|
+
address: IDENTITY_REGISTRY,
|
|
65
|
+
abi: identityAbi,
|
|
66
|
+
functionName: "tokenURI",
|
|
67
|
+
args: [agentId],
|
|
68
|
+
...at,
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
catch (e) {
|
|
72
|
+
// ownerOf reverts for an agent that does not exist; any other failure is the caller's to see.
|
|
73
|
+
if (!/revert|nonexistent|ERC721/i.test(e instanceof Error ? e.message : String(e)))
|
|
74
|
+
throw e;
|
|
75
|
+
}
|
|
76
|
+
const times = scored.outcomes.map((o) => o.final_at);
|
|
77
|
+
return {
|
|
78
|
+
agentId,
|
|
79
|
+
block: scored.block,
|
|
80
|
+
registered: owner !== undefined,
|
|
81
|
+
...(owner ? { owner, ...registration(uri) } : {}),
|
|
82
|
+
score: scored.score,
|
|
83
|
+
outcomes: scored.outcomes,
|
|
84
|
+
...(times.length > 0
|
|
85
|
+
? { firstOutcomeAt: Math.min(...times), latestOutcomeAt: Math.max(...times) }
|
|
86
|
+
: {}),
|
|
87
|
+
};
|
|
88
|
+
}
|