arl-protocol-sdk 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +22 -2
  2. package/package.json +5 -5
  3. package/protocol/src/canonical.d.ts +7 -0
  4. package/protocol/src/canonical.js +35 -0
  5. package/protocol/src/deployments.d.ts +17 -0
  6. package/protocol/src/deployments.js +24 -0
  7. package/protocol/src/evidence.d.ts +72 -0
  8. package/protocol/src/evidence.js +107 -0
  9. package/protocol/src/index.d.ts +14 -0
  10. package/protocol/src/index.js +9 -0
  11. package/protocol/src/policies.d.ts +5 -0
  12. package/protocol/src/policies.js +56 -0
  13. package/protocol/src/policy.d.ts +65 -0
  14. package/protocol/src/policy.js +202 -0
  15. package/protocol/src/prepare.d.ts +176 -0
  16. package/protocol/src/prepare.js +104 -0
  17. package/protocol/src/proof.d.ts +70 -0
  18. package/protocol/src/proof.js +239 -0
  19. package/protocol/src/reputation.d.ts +47 -0
  20. package/protocol/src/reputation.js +74 -0
  21. package/protocol/src/task.d.ts +121 -0
  22. package/protocol/src/task.js +322 -0
  23. package/{index.d.ts → sdk/src/index.d.ts} +2 -0
  24. package/{index.js → sdk/src/index.js} +3 -0
  25. package/{jobs.d.ts → sdk/src/jobs.d.ts} +2 -2
  26. package/{jobs.js → sdk/src/jobs.js} +7 -2
  27. package/sdk/src/openTask.d.ts +23 -0
  28. package/sdk/src/openTask.js +116 -0
  29. package/{verified.d.ts → sdk/src/verified.d.ts} +6 -2
  30. package/{verified.js → sdk/src/verified.js} +3 -3
  31. /package/{abi.d.ts → sdk/src/abi.d.ts} +0 -0
  32. /package/{abi.js → sdk/src/abi.js} +0 -0
  33. /package/{acquireArl.d.ts → sdk/src/acquireArl.d.ts} +0 -0
  34. /package/{acquireArl.js → sdk/src/acquireArl.js} +0 -0
  35. /package/{escrowProvider.d.ts → sdk/src/escrowProvider.d.ts} +0 -0
  36. /package/{escrowProvider.js → sdk/src/escrowProvider.js} +0 -0
  37. /package/{payVerified.d.ts → sdk/src/payVerified.d.ts} +0 -0
  38. /package/{payVerified.js → sdk/src/payVerified.js} +0 -0
  39. /package/{streaming.d.ts → sdk/src/streaming.d.ts} +0 -0
  40. /package/{streaming.js → sdk/src/streaming.js} +0 -0
@@ -0,0 +1,322 @@
1
+ // arl-task/1: the standard description of one agent-to-agent task (spec/arl-task/v0.1.0).
2
+ // A task names the work, how it is accepted, how it is paid and how it is verified. Its
3
+ // keccak256 over canonical JSON is the task hash. The bounds below mirror the deployed contracts
4
+ // (ARLJobs and ARLVerifiedEvaluator on Base Mainnet), so a task that parses can always be opened
5
+ // and configured on chain; nothing here changes what the contracts accept.
6
+ import { canonicalHash } from "./canonical.js";
7
+ export const TASK_VERSION = "arl-task/1";
8
+ export const WORKLOAD_CLASSES = ["reexec", "attested", "model-assisted", "review"];
9
+ export const TIERS = ["fallback", "reexecution", "attested"];
10
+ export const EVIDENCE_KINDS = [
11
+ "result-manifest",
12
+ "logs",
13
+ "artifact",
14
+ "attestation",
15
+ "model-verdict",
16
+ ];
17
+ export const TOKENS = ["ARL", "USDC"];
18
+ /** Bounds of the deployed contracts and of this spec. */
19
+ export const BOUNDS = {
20
+ /** ARLJobs.MIN_DURATION and MAX_DURATION, in hours (5 minutes rounds up to 1 hour). */
21
+ deadlineHours: [1, 8760],
22
+ /** ARLVerifiedEvaluator.MIN_VOTE_WINDOW / MAX_VOTE_WINDOW. */
23
+ voteWindowSeconds: [600, 604_800],
24
+ /** minChallengeWindow on Base Mainnet (86400) / MAX_CHALLENGE_WINDOW. */
25
+ challengeWindowSeconds: [86_400, 2_592_000],
26
+ /** ARLVerifiedEvaluator.MAX_COMMITTEE. */
27
+ committeeSize: [1, 7],
28
+ title: 120,
29
+ description: 4000,
30
+ acceptance: [1, 20],
31
+ rule: 500,
32
+ /** ARLJobs.MAX_DESCRIPTION, in UTF-8 bytes (the on-chain job description). */
33
+ onchainDescription: 1024,
34
+ };
35
+ export class TaskError extends Error {
36
+ name = "TaskError";
37
+ }
38
+ const HASH = /^0x[0-9a-f]{64}$/;
39
+ const DIGITS = /^(0|[1-9][0-9]*)$/;
40
+ const RULE_ID = /^[a-z0-9][a-z0-9-]{0,31}$/;
41
+ const MEDIA_TYPE = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,62}\/[a-z0-9][a-z0-9!#$&^_.+-]{0,62}$/;
42
+ const POLICY = /^arl-policy\/1:[a-z0-9][a-z0-9-]{0,47}$/;
43
+ const URL_SCHEMES = ["https:", "ipfs:"];
44
+ const UINT256_MAX = (1n << 256n) - 1n;
45
+ function isRecord(v) {
46
+ return typeof v === "object" && v !== null && !Array.isArray(v);
47
+ }
48
+ function onlyKeys(v, allowed, what) {
49
+ for (const k of Object.keys(v)) {
50
+ if (!allowed.includes(k))
51
+ throw new TaskError(`${what}: unknown field ${k}`);
52
+ }
53
+ }
54
+ function text(v, max, what, allowEmpty = false) {
55
+ if (typeof v !== "string")
56
+ throw new TaskError(`${what} must be a string`);
57
+ if (!allowEmpty && v.trim().length === 0)
58
+ throw new TaskError(`${what} must not be empty`);
59
+ if (v.length > max)
60
+ throw new TaskError(`${what} must be at most ${max} characters`);
61
+ return v;
62
+ }
63
+ function int(v, [min, max], what) {
64
+ if (typeof v !== "number" || !Number.isSafeInteger(v) || v < min || v > max) {
65
+ throw new TaskError(`${what} must be an integer from ${min} to ${max}`);
66
+ }
67
+ return v;
68
+ }
69
+ function oneOf(v, values, what) {
70
+ if (typeof v !== "string" || !values.includes(v)) {
71
+ throw new TaskError(`${what} must be one of ${values.join(", ")}`);
72
+ }
73
+ return v;
74
+ }
75
+ function amount(v, what, positive) {
76
+ if (typeof v !== "string" || !DIGITS.test(v)) {
77
+ throw new TaskError(`${what} must be a decimal string of base units`);
78
+ }
79
+ const n = BigInt(v);
80
+ if (n > UINT256_MAX)
81
+ throw new TaskError(`${what} exceeds uint256`);
82
+ if (positive && n === 0n)
83
+ throw new TaskError(`${what} must be above zero`);
84
+ return v;
85
+ }
86
+ function url(v, what) {
87
+ const s = text(v, 2048, what);
88
+ let parsed;
89
+ try {
90
+ parsed = new URL(s);
91
+ }
92
+ catch {
93
+ throw new TaskError(`${what} is not a URL`);
94
+ }
95
+ if (!URL_SCHEMES.includes(parsed.protocol))
96
+ throw new TaskError(`${what} must be https or ipfs`);
97
+ return s;
98
+ }
99
+ function workload(v) {
100
+ if (!isRecord(v))
101
+ throw new TaskError("workload must be an object");
102
+ onlyKeys(v, ["class", "spec_uri", "spec_hash"], "workload");
103
+ const cls = oneOf(v.class, WORKLOAD_CLASSES, "workload.class");
104
+ const out = { class: cls };
105
+ if (v.spec_uri !== undefined)
106
+ out.spec_uri = url(v.spec_uri, "workload.spec_uri");
107
+ if (v.spec_hash !== undefined) {
108
+ if (typeof v.spec_hash !== "string" || !HASH.test(v.spec_hash)) {
109
+ throw new TaskError("workload.spec_hash must be 0x and 64 lowercase hex");
110
+ }
111
+ out.spec_hash = v.spec_hash;
112
+ }
113
+ if ((out.spec_uri === undefined) !== (out.spec_hash === undefined)) {
114
+ throw new TaskError("workload.spec_uri and workload.spec_hash go together");
115
+ }
116
+ if (cls === "reexec" && out.spec_hash === undefined) {
117
+ throw new TaskError("a reexec workload needs spec_uri and spec_hash (an arl-reexec/1 spec)");
118
+ }
119
+ return out;
120
+ }
121
+ function acceptance(v) {
122
+ if (!Array.isArray(v))
123
+ throw new TaskError("acceptance must be an array");
124
+ const [min, max] = BOUNDS.acceptance;
125
+ if (v.length < min || v.length > max) {
126
+ throw new TaskError(`acceptance must have ${min} to ${max} rules`);
127
+ }
128
+ const ids = new Set();
129
+ return v.map((r, i) => {
130
+ const what = `acceptance[${i}]`;
131
+ if (!isRecord(r))
132
+ throw new TaskError(`${what} must be an object`);
133
+ onlyKeys(r, ["id", "rule"], what);
134
+ if (typeof r.id !== "string" || !RULE_ID.test(r.id)) {
135
+ throw new TaskError(`${what}.id must be lowercase letters, digits and dashes`);
136
+ }
137
+ if (ids.has(r.id))
138
+ throw new TaskError(`${what}.id repeats ${r.id}`);
139
+ ids.add(r.id);
140
+ return { id: r.id, rule: text(r.rule, BOUNDS.rule, `${what}.rule`) };
141
+ });
142
+ }
143
+ function verification(v, cls) {
144
+ if (!isRecord(v))
145
+ throw new TaskError("verification must be an object");
146
+ onlyKeys(v, [
147
+ "policy",
148
+ "tier",
149
+ "committee_size",
150
+ "threshold",
151
+ "vote_window_seconds",
152
+ "challenge_window_seconds",
153
+ "bond_floor",
154
+ ], "verification");
155
+ if (typeof v.policy !== "string" || !POLICY.test(v.policy)) {
156
+ throw new TaskError("verification.policy must be arl-policy/1:<id>");
157
+ }
158
+ const tier = oneOf(v.tier, TIERS, "verification.tier");
159
+ const n = int(v.committee_size, BOUNDS.committeeSize, "verification.committee_size");
160
+ const t = int(v.threshold, [1, n], "verification.threshold");
161
+ // ARLVerifiedEvaluator._checkThreshold.
162
+ if (tier === "fallback") {
163
+ if (n !== 1 || t !== 1)
164
+ throw new TaskError("a fallback tier is exactly 1 of 1");
165
+ }
166
+ else if (t < 2 || 2 * t <= n) {
167
+ throw new TaskError("a checked tier needs a strict majority of at least 2");
168
+ }
169
+ if (cls === "reexec" && tier === "attested") {
170
+ throw new TaskError("a reexec workload uses the reexecution or fallback tier");
171
+ }
172
+ if (cls === "attested" && tier === "reexecution") {
173
+ throw new TaskError("an attested workload cannot be checked by re-execution");
174
+ }
175
+ return {
176
+ policy: v.policy,
177
+ tier,
178
+ committee_size: n,
179
+ threshold: t,
180
+ vote_window_seconds: int(v.vote_window_seconds, BOUNDS.voteWindowSeconds, "verification.vote_window_seconds"),
181
+ challenge_window_seconds: int(v.challenge_window_seconds, BOUNDS.challengeWindowSeconds, "verification.challenge_window_seconds"),
182
+ bond_floor: amount(v.bond_floor, "verification.bond_floor", true),
183
+ };
184
+ }
185
+ const TASK_KEYS = [
186
+ "version",
187
+ "title",
188
+ "description",
189
+ "workload",
190
+ "acceptance",
191
+ "deliverable",
192
+ "payment",
193
+ "verification",
194
+ "evidence",
195
+ ];
196
+ /** Validates an untrusted task document and returns it typed. Unknown fields are refused. */
197
+ export function parseTask(raw) {
198
+ if (!isRecord(raw))
199
+ throw new TaskError("task must be an object");
200
+ onlyKeys(raw, TASK_KEYS, "task");
201
+ if (raw.version !== TASK_VERSION)
202
+ throw new TaskError(`version must be ${TASK_VERSION}`);
203
+ const wl = workload(raw.workload);
204
+ if (!isRecord(raw.deliverable))
205
+ throw new TaskError("deliverable must be an object");
206
+ onlyKeys(raw.deliverable, ["media_type", "max_bytes"], "deliverable");
207
+ const mt = raw.deliverable.media_type;
208
+ if (typeof mt !== "string" || !MEDIA_TYPE.test(mt)) {
209
+ throw new TaskError("deliverable.media_type must be a lowercase media type");
210
+ }
211
+ const deliverable = { media_type: mt };
212
+ if (raw.deliverable.max_bytes !== undefined) {
213
+ deliverable.max_bytes = int(raw.deliverable.max_bytes, [1, Number.MAX_SAFE_INTEGER], "deliverable.max_bytes");
214
+ }
215
+ if (!isRecord(raw.payment))
216
+ throw new TaskError("payment must be an object");
217
+ onlyKeys(raw.payment, ["token", "budget", "deadline_hours"], "payment");
218
+ const payment = {
219
+ token: oneOf(raw.payment.token, TOKENS, "payment.token"),
220
+ budget: amount(raw.payment.budget, "payment.budget", true),
221
+ deadline_hours: int(raw.payment.deadline_hours, BOUNDS.deadlineHours, "payment.deadline_hours"),
222
+ };
223
+ const ver = verification(raw.verification, wl.class);
224
+ // ARLVerifiedEvaluator._checkWindows: the deadline must leave room for the vote window and two
225
+ // challenge windows.
226
+ const needed = ver.vote_window_seconds + 2 * ver.challenge_window_seconds;
227
+ if (payment.deadline_hours * 3600 < needed) {
228
+ throw new TaskError(`payment.deadline_hours must cover the vote window and two challenge windows (${Math.ceil(needed / 3600)} hours)`);
229
+ }
230
+ if (!Array.isArray(raw.evidence) || raw.evidence.length === 0) {
231
+ throw new TaskError("evidence must be a non-empty array");
232
+ }
233
+ const evidence = raw.evidence.map((e, i) => oneOf(e, EVIDENCE_KINDS, `evidence[${i}]`));
234
+ if (new Set(evidence).size !== evidence.length)
235
+ throw new TaskError("evidence repeats a kind");
236
+ if (wl.class === "reexec" && !evidence.includes("result-manifest")) {
237
+ throw new TaskError("a reexec workload requires result-manifest evidence");
238
+ }
239
+ if (wl.class === "attested" && !evidence.includes("attestation")) {
240
+ throw new TaskError("an attested workload requires attestation evidence");
241
+ }
242
+ if (wl.class === "model-assisted" && !evidence.includes("model-verdict")) {
243
+ throw new TaskError("a model-assisted workload requires model-verdict evidence");
244
+ }
245
+ return {
246
+ version: TASK_VERSION,
247
+ title: text(raw.title, BOUNDS.title, "title"),
248
+ description: text(raw.description, BOUNDS.description, "description", true),
249
+ workload: wl,
250
+ acceptance: acceptance(raw.acceptance),
251
+ deliverable,
252
+ payment,
253
+ verification: ver,
254
+ evidence,
255
+ };
256
+ }
257
+ /** keccak256 of the canonical task: the task hash. */
258
+ export function taskHash(task) {
259
+ return canonicalHash(task);
260
+ }
261
+ /**
262
+ * The value committed as `specHash` in `ARLVerifiedEvaluator.configure`: the workload spec hash
263
+ * for a reexec task (validators re-run that spec, unchanged from arl-reexec/1), otherwise the task
264
+ * hash.
265
+ */
266
+ export function committedSpecHash(task) {
267
+ return task.workload.class === "reexec" && task.workload.spec_hash !== undefined
268
+ ? task.workload.spec_hash
269
+ : taskHash(task);
270
+ }
271
+ /**
272
+ * The on-chain job description: `arl-task:<task hash>` followed by the task's URI, so anyone can
273
+ * fetch the task and check it against its hash. Must fit ARLJobs.MAX_DESCRIPTION.
274
+ */
275
+ export function jobDescription(task, taskUri) {
276
+ const s = `arl-task:${taskHash(task)} ${url(taskUri, "taskUri")}`;
277
+ if (new TextEncoder().encode(s).length > BOUNDS.onchainDescription) {
278
+ throw new TaskError("the task URI is too long for the on-chain description");
279
+ }
280
+ return s;
281
+ }
282
+ const TIER_INDEX = { fallback: 0, reexecution: 1, attested: 2 };
283
+ /**
284
+ * Maps a parsed task to the contract calls (pure: no chain access). `now` is the chain time in
285
+ * seconds. The committee is proposed by the client; it must not contain the client or provider.
286
+ */
287
+ export function onchainTerms(task, opts) {
288
+ const lower = (a) => a.toLowerCase();
289
+ if (opts.committee.length !== task.verification.committee_size) {
290
+ throw new TaskError("committee size differs from the task");
291
+ }
292
+ const seen = new Set();
293
+ for (const m of opts.committee) {
294
+ const k = lower(m);
295
+ if (k === lower(opts.client) || k === lower(opts.provider)) {
296
+ throw new TaskError("the committee must not contain the client or the provider");
297
+ }
298
+ if (seen.has(k))
299
+ throw new TaskError("the committee repeats a member");
300
+ seen.add(k);
301
+ }
302
+ return {
303
+ createJob: {
304
+ provider: opts.provider,
305
+ evaluator: opts.evaluator,
306
+ expiredAt: opts.now + BigInt(task.payment.deadline_hours) * 3600n,
307
+ description: jobDescription(task, opts.taskUri),
308
+ hook: "0x0000000000000000000000000000000000000000",
309
+ },
310
+ configure: {
311
+ tier: TIER_INDEX[task.verification.tier],
312
+ threshold: task.verification.threshold,
313
+ voteWindow: BigInt(task.verification.vote_window_seconds),
314
+ challengeWindow: BigInt(task.verification.challenge_window_seconds),
315
+ bond: BigInt(task.verification.bond_floor),
316
+ providerAgentId: opts.providerAgentId ?? 0n,
317
+ specHash: committedSpecHash(task),
318
+ committee: [...opts.committee],
319
+ },
320
+ budget: BigInt(task.payment.budget),
321
+ };
322
+ }
@@ -5,3 +5,5 @@ export { ESCROW_SCHEME, JOB_HEADER, fundVerifiedJob, parseEscrowOffer, payVerifi
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
7
  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
+ export * from "../../protocol/src/index.ts";
9
+ export { openTask, type OpenTaskOptions, type OpenedTask } from "./openTask.ts";
@@ -5,3 +5,6 @@ export { ESCROW_SCHEME, JOB_HEADER, fundVerifiedJob, parseEscrowOffer, payVerifi
5
5
  export { ARL_SWAP, acquireArl, quoteArl, } from "./acquireArl.js";
6
6
  export { acceptedCount, approveCommittee, buildEscrowOffer, checkFundedJob, submitDeliverable, waitForAcceptance, } from "./escrowProvider.js";
7
7
  export { ArlJobError, ESCROWS, STATUS as JOB_STATUS, createJob, fundJob, getJob, setBudget, settleJob, submitWork, toBytes32, } from "./jobs.js";
8
+ // arl-task/1 and the other protocol documents (packages/protocol), and opening a task on chain.
9
+ export * from "../../protocol/src/index.js";
10
+ export { openTask } from "./openTask.js";
@@ -1,8 +1,8 @@
1
1
  import { type Address, type Hash, type Hex, type PublicClient, type WalletClient } from "viem";
2
2
  /** The ARL escrows on Base Mainnet (contracts/deploy/base-mainnet-jobs.json). */
3
3
  export declare const ESCROWS: {
4
- readonly ARL: "0x4664d58FAFFb6ab1cf36717c70058a323E2A98f9";
5
- readonly USDC: "0xc833140D2eE8607fd41662cffFAc557f3D535bE6";
4
+ readonly ARL: "0x9aE99bF9a59aF47E81346B7c0b93Cd2B610455fC";
5
+ readonly USDC: "0xE3eA0EAEc3Cf9DA2d0856A0f784A4B1671AeFD04";
6
6
  };
7
7
  export type Escrow = keyof typeof ESCROWS;
8
8
  export declare const BASE_MAINNET_CHAIN_ID = 8453;
@@ -4,8 +4,8 @@
4
4
  import { formatUnits, getAddress, isAddress, isHex, keccak256, parseAbi, parseEventLogs, parseUnits, stringToHex, } from "viem";
5
5
  /** The ARL escrows on Base Mainnet (contracts/deploy/base-mainnet-jobs.json). */
6
6
  export const ESCROWS = {
7
- ARL: "0x4664d58FAFFb6ab1cf36717c70058a323E2A98f9",
8
- USDC: "0xc833140D2eE8607fd41662cffFAc557f3D535bE6",
7
+ ARL: "0x9aE99bF9a59aF47E81346B7c0b93Cd2B610455fC",
8
+ USDC: "0xE3eA0EAEc3Cf9DA2d0856A0f784A4B1671AeFD04",
9
9
  };
10
10
  export const BASE_MAINNET_CHAIN_ID = 8453;
11
11
  export const STATUS = ["Open", "Funded", "Submitted", "Completed", "Rejected", "Expired"];
@@ -124,6 +124,11 @@ export async function createJob(c, escrow, input) {
124
124
  const evaluator = input.evaluator?.trim()
125
125
  ? checkAddress(input.evaluator, "the evaluator")
126
126
  : sender(c);
127
+ // The contract allows these, but they defeat the escrow (security report 2026-11-15).
128
+ if (provider.toLowerCase() === evaluator.toLowerCase())
129
+ throw new ArlJobError("the provider cannot evaluate its own work");
130
+ if (provider.toLowerCase() === sender(c).toLowerCase())
131
+ throw new ArlJobError("the client cannot hire itself");
127
132
  if (!(input.hoursUntilDeadline >= 1 && input.hoursUntilDeadline <= 24 * 365))
128
133
  throw new ArlJobError("the deadline must be between 1 hour and 365 days away");
129
134
  const { timestamp } = await c.publicClient.getBlock();
@@ -0,0 +1,23 @@
1
+ import { type Address, type Hash, type Hex } from "viem";
2
+ import { type Policy, type TaskDeployment, type UnsignedTx } from "../../protocol/src/index.ts";
3
+ import { type VerifiedClients } from "./verified.ts";
4
+ export interface OpenTaskOptions {
5
+ /** Where anyone can fetch the task document (https or ipfs). */
6
+ taskUri: string;
7
+ provider: Address;
8
+ /** Staked validators, as many as the task's committee_size. */
9
+ committee: Address[];
10
+ /** The task's policy, when it is not one of the built-in policies. */
11
+ policy?: Policy;
12
+ providerAgentId?: bigint;
13
+ /** Required on a local chain; on Base Mainnet the deployment for the task's token is used. */
14
+ deployment?: TaskDeployment;
15
+ }
16
+ export interface OpenedTask {
17
+ jobId: bigint;
18
+ taskHash: Hex;
19
+ /** Transaction hashes, by step. */
20
+ txs: Record<UnsignedTx["step"], Hash>;
21
+ }
22
+ /** Validates `task`, then opens and funds it as a verified job from the wallet's account. */
23
+ export declare function openTask({ publicClient, walletClient }: VerifiedClients, task: unknown, opts: OpenTaskOptions): Promise<OpenedTask>;
@@ -0,0 +1,116 @@
1
+ // Open an arl-task/1 task (spec/arl-task/v0.1.0) as a verified job, paid and checked as the task
2
+ // says:
3
+ //
4
+ // const { jobId, taskHash } = await openTask(clients, task, {
5
+ // taskUri: "https://…/task.json", provider, committee: [v1, v2, v3] });
6
+ //
7
+ // The task is validated and checked against its arl-policy/1 policy before any transaction. Then
8
+ // the wallet (the job's client) creates the job, configures the committee, sets the budget,
9
+ // approves the escrow and funds it. The provider approves the committee next; the members accept
10
+ // and vote. Every transaction is the one `prepareTask` / `fundingTransactions` return, so wallets
11
+ // that cannot use this SDK (MCP, AgentKit) sign exactly the same calls.
12
+ import { parseEventLogs } from "viem";
13
+ import { fundingTransactions, openTaskAbi, prepareTask, taskDeployment, } from "../../protocol/src/index.js";
14
+ import { VerifiedJobError, checkVerifiedChain, walletAccount, } from "./verified.js";
15
+ const readAbi = [
16
+ {
17
+ type: "function",
18
+ name: "paymentToken",
19
+ stateMutability: "view",
20
+ inputs: [],
21
+ outputs: [{ type: "address" }],
22
+ },
23
+ {
24
+ type: "function",
25
+ name: "balanceOf",
26
+ stateMutability: "view",
27
+ inputs: [{ type: "address" }],
28
+ outputs: [{ type: "uint256" }],
29
+ },
30
+ ];
31
+ /** Validates `task`, then opens and funds it as a verified job from the wallet's account. */
32
+ export async function openTask({ publicClient, walletClient }, task, opts) {
33
+ const from = walletAccount(walletClient);
34
+ const chainId = await checkVerifiedChain(publicClient);
35
+ const token = task?.payment?.token;
36
+ const known = token === "ARL" || token === "USDC" ? taskDeployment(chainId, token) : undefined;
37
+ if (opts.deployment && known && opts.deployment.jobs.toLowerCase() !== known.jobs.toLowerCase()) {
38
+ throw new VerifiedJobError("on Base Mainnet the task opens on ARL's own escrow");
39
+ }
40
+ const deployment = opts.deployment ?? known;
41
+ const { timestamp } = await publicClient.getBlock();
42
+ // Throws TaskError or PolicyError; nothing has been sent yet.
43
+ const prepared = prepareTask({
44
+ task,
45
+ taskUri: opts.taskUri,
46
+ client: from.address,
47
+ provider: opts.provider,
48
+ committee: opts.committee,
49
+ deployment: deployment ?? missingDeployment(),
50
+ now: timestamp,
51
+ ...(opts.policy ? { policy: opts.policy } : {}),
52
+ ...(opts.providerAgentId === undefined ? {} : { providerAgentId: opts.providerAgentId }),
53
+ });
54
+ const d = prepared.deployment;
55
+ if (d.chainId !== chainId)
56
+ throw new VerifiedJobError("the deployment is for another chain");
57
+ for (const [a, what] of [
58
+ [d.jobs, "jobs escrow"],
59
+ [d.evaluator, "evaluator"],
60
+ [d.token, "token"],
61
+ ]) {
62
+ const code = await publicClient.getCode({ address: a });
63
+ if (code === undefined || code === "0x") {
64
+ throw new VerifiedJobError(`${what} ${a} has no code on this chain`);
65
+ }
66
+ }
67
+ const paidIn = await publicClient.readContract({
68
+ address: d.jobs,
69
+ abi: readAbi,
70
+ functionName: "paymentToken",
71
+ });
72
+ if (paidIn.toLowerCase() !== d.token.toLowerCase()) {
73
+ throw new VerifiedJobError("the escrow is paid in another token than the deployment says");
74
+ }
75
+ const balance = await publicClient.readContract({
76
+ address: d.token,
77
+ abi: readAbi,
78
+ functionName: "balanceOf",
79
+ args: [from.address],
80
+ });
81
+ if (balance < prepared.terms.budget) {
82
+ throw new VerifiedJobError(`the client holds less ${prepared.task.payment.token} than the budget`);
83
+ }
84
+ // One signature for both wallet client shapes VerifiedClients allows.
85
+ const wallet = walletClient;
86
+ const send = async (tx) => {
87
+ const hash = await wallet.sendTransaction({
88
+ account: from,
89
+ chain: walletClient.chain,
90
+ to: tx.to,
91
+ data: tx.data,
92
+ value: 0n,
93
+ });
94
+ const r = await publicClient.waitForTransactionReceipt({ hash });
95
+ if (r.status !== "success")
96
+ throw new VerifiedJobError(`${tx.step} reverted`);
97
+ return hash;
98
+ };
99
+ const createJob = await send(prepared.create);
100
+ const receipt = await publicClient.getTransactionReceipt({ hash: createJob });
101
+ const created = parseEventLogs({
102
+ abi: openTaskAbi,
103
+ eventName: "JobCreated",
104
+ logs: receipt.logs,
105
+ }).find((l) => l.address.toLowerCase() === d.jobs.toLowerCase());
106
+ if (!created)
107
+ throw new VerifiedJobError("JobCreated event missing");
108
+ const jobId = created.args.jobId;
109
+ const txs = { createJob };
110
+ for (const tx of fundingTransactions(prepared, jobId))
111
+ txs[tx.step] = await send(tx);
112
+ return { jobId, taskHash: prepared.taskHash, txs };
113
+ }
114
+ function missingDeployment() {
115
+ throw new VerifiedJobError("deployment is required on this chain");
116
+ }
@@ -9,8 +9,8 @@ import { type Account, type Address, type Chain, type Hash, type Hex, type Publi
9
9
  export declare const BASE_MAINNET_VERIFIED: {
10
10
  readonly chainId: 8453;
11
11
  readonly token: "0xde91E6f39D50bBd875f831dcc1134A3D7f3aaDb4";
12
- readonly jobs: "0x4664d58FAFFb6ab1cf36717c70058a323E2A98f9";
13
- readonly evaluator: "0x5cA6dab18E6b9a5Cd44a4FfFBdf2c5BA3Cd87DfF";
12
+ readonly jobs: "0x9aE99bF9a59aF47E81346B7c0b93Cd2B610455fC";
13
+ readonly evaluator: "0x6648e141cb7473822ddBd8bC039b91e5af3259B4";
14
14
  readonly arbiterSafe: "0x8FF6c3aD0991Ac848BFf5d0acD78BBc5e190466f";
15
15
  };
16
16
  /** The jobs escrow and evaluator of a chain, or undefined on the local chain. */
@@ -126,6 +126,9 @@ export declare const verifiedEvaluatorAbi: readonly [{
126
126
  }, {
127
127
  readonly type: "uint8";
128
128
  readonly name: "rejections";
129
+ }, {
130
+ readonly type: "uint8";
131
+ readonly name: "topApprovals";
129
132
  }, {
130
133
  readonly type: "uint64";
131
134
  readonly name: "voteEnds";
@@ -214,6 +217,7 @@ export declare function getVerdict(publicClient: PublicClient, jobId: bigint, ev
214
217
  providerApproved: boolean;
215
218
  approvals: number;
216
219
  rejections: number;
220
+ topApprovals: number;
217
221
  voteEnds: bigint;
218
222
  challengeEnds: bigint;
219
223
  challenger: `0x${string}`;
@@ -18,8 +18,8 @@ import { parseAbi, parseEventLogs, } from "viem";
18
18
  export const BASE_MAINNET_VERIFIED = {
19
19
  chainId: 8453,
20
20
  token: "0xde91E6f39D50bBd875f831dcc1134A3D7f3aaDb4",
21
- jobs: "0x4664d58FAFFb6ab1cf36717c70058a323E2A98f9",
22
- evaluator: "0x5cA6dab18E6b9a5Cd44a4FfFBdf2c5BA3Cd87DfF",
21
+ jobs: "0x9aE99bF9a59aF47E81346B7c0b93Cd2B610455fC",
22
+ evaluator: "0x6648e141cb7473822ddBd8bC039b91e5af3259B4",
23
23
  arbiterSafe: "0x8FF6c3aD0991Ac848BFf5d0acD78BBc5e190466f",
24
24
  };
25
25
  const ALLOWED = [8453, 31_337];
@@ -41,7 +41,7 @@ export const verifiedJobsAbi = parseAbi([
41
41
  ]);
42
42
  export const verifiedEvaluatorAbi = parseAbi([
43
43
  "struct Config { uint8 tier; uint8 threshold; uint64 voteWindow; uint64 challengeWindow; uint96 bond; uint256 providerAgentId; bytes32 specHash; address[] committee; }",
44
- "struct Verdict { uint8 phase; bool providerApproved; uint8 approvals; uint8 rejections; uint64 voteEnds; uint64 challengeEnds; address challenger; uint256 bond; bytes32 deliverable; bytes32 voteHash; }",
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
47
  "function finalize(uint256 jobId)",
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes