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 CHANGED
@@ -55,14 +55,52 @@ A task that fails validation sends no transaction. `prepareTask` and `fundingTra
55
55
  the same calls unsigned, for wallets that sign elsewhere. `parseTask`, `taskHash`,
56
56
  `checkTaskAgainstPolicy` and the other protocol functions are exported too.
57
57
 
58
+ ## Get paid on proof (sell a service to agents)
59
+
60
+ `payOnProof` wraps an HTTP handler so every call is paid through a verified job. The client pays
61
+ into escrow first, the service does the work, and the money reaches the service only after a
62
+ staked committee has checked the result. It works in any runtime with the Fetch API (Next.js route
63
+ handlers, Hono, Cloudflare Workers, Bun, Deno); `expressPayOnProof` does the same for Express.
64
+
65
+ ```ts
66
+ import { payOnProof } from "arl-protocol-sdk";
67
+
68
+ export const POST = payOnProof(
69
+ {
70
+ clients, // the service's own wallet is the provider
71
+ offer: { chainId: 8453, provider, specUri, specHash, budget, committee, threshold: 2 },
72
+ },
73
+ async (req, job) => {
74
+ const result = await runTheJob(await req.json()); // the work the spec describes
75
+ return { body: JSON.stringify(result), deliverable: resultHash };
76
+ },
77
+ );
78
+ ```
79
+
80
+ Without an `X-ARL-Job` header the service answers `402` with an `arl-escrow` offer;
81
+ `payVerified` (or any x402 client that knows the scheme) opens and funds the job and asks again.
82
+ The scheme is specified in
83
+ [spec/x402-arl-escrow](https://github.com/armanalabsai/arlcoin.io/tree/main/spec/x402-arl-escrow/v0.2.0).
84
+ For a funded job that matches the offer, the handler runs once, the response carries
85
+ `X-ARL-Job` and `X-ARL-Deliverable`, and the deliverable is submitted on chain as soon as enough
86
+ committee members have accepted the job. A job is served once: the default record of served jobs
87
+ lives in memory, so a service with several instances or restarts passes `usedJobs` backed by a
88
+ database or KV store. On runtimes that stop work when the response ends, pass `waitUntil`.
89
+
58
90
  ## Also in the SDK
59
91
 
60
92
  | Function | What it does |
61
93
  | ------------------------------------------ | ------------------------------------------------------------------------- |
62
94
  | `streamComputePayment`, `stopComputeStream` | Pay a compute provider per second (`COMPUTE_PAYMENT` on Base Mainnet) |
63
95
  | `quoteArl`, `acquireArl` | Buy exact ARL in the official Uniswap v3 pools, paying USDC, USDT or ETH |
64
- | `openVerifiedJob`, `getVerdict`, `finalizeJob` | Verified jobs: a committee of staked ARL validators checks the work |
96
+ | `openVerifiedJob`, `getVerdict`, `getOutcomes`, `finalizeJob` | Verified jobs: a committee of staked ARL validators checks the work, and `getOutcomes` reads an agent's verified `outcomesOf` counts |
65
97
  | `payVerified` | Pay a service that answers HTTP 402 with an ARL escrow offer |
98
+ | `payOnProof`, `expressPayOnProof` | Sell a service paid through a verified job (the provider side of `payVerified`) |
99
+ | `getAgentScore` | An agent's arl-reputation/1 score on Base Mainnet, from verified outcomes only |
100
+ | `getJobAudit` | Every on-chain event of a verified job in order: who acted, when, with what hashes |
101
+ | `getAgentPassport` | An agent's ERC-8004 identity and its verified record in one answer |
102
+ | `getValidators` | Every validator that staked: stake, locked bonds, jobs accepted, votes and slashes |
103
+ | `getTrustGraph` | Every agent with a verified outcome, its score, and an edge per client and agent |
66
104
 
67
105
  ## Contracts on Base Mainnet
68
106
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "arl-protocol-sdk",
3
- "version": "0.2.0",
3
+ "version": "0.3.1",
4
4
  "description": "ARL Protocol SDK: escrowed and verified jobs for AI agents, compute payments and ARL purchase on Base Mainnet",
5
5
  "keywords": [
6
6
  "arl",
@@ -7,14 +7,14 @@ export const BASE_MAINNET_TASK_DEPLOYMENTS = {
7
7
  chainId: 8453,
8
8
  token: "0xde91E6f39D50bBd875f831dcc1134A3D7f3aaDb4",
9
9
  jobs: "0x9aE99bF9a59aF47E81346B7c0b93Cd2B610455fC",
10
- evaluator: "0x6648e141cb7473822ddBd8bC039b91e5af3259B4",
10
+ evaluator: "0x0D160C869bd2a7AaEDd29e11fc60fdAEf21c3E28",
11
11
  arbiter: ARBITER_SAFE,
12
12
  },
13
13
  USDC: {
14
14
  chainId: 8453,
15
15
  token: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
16
16
  jobs: "0xE3eA0EAEc3Cf9DA2d0856A0f784A4B1671AeFD04",
17
- evaluator: "0x6bFfdEace7d0B2F7711f604F0A5D2545be2961AF",
17
+ evaluator: "0x7A00D45598Da7C13feEA8962fc1110FC4Db4D850",
18
18
  arbiter: ARBITER_SAFE,
19
19
  },
20
20
  };
@@ -63,10 +63,5 @@ export interface EvidenceResult {
63
63
  /** The settlement differs from the committee's decision (a dispute was ruled). */
64
64
  overturned: boolean;
65
65
  }
66
- /**
67
- * Checks that the settlement record, task, proof and policy describe the same job and agree.
68
- * Throws EvidenceError (or the document's own error) on the first inconsistency. It does not
69
- * re-read the chain: run `arl-verifier verify-bundle` on `settlement` for that.
70
- */
71
66
  export declare function checkEvidence(raw: EvidenceV2): EvidenceResult;
72
67
  export {};
@@ -16,14 +16,25 @@ const TIER_INDEX = { fallback: 0, reexecution: 1, attested: 2 };
16
16
  * Throws EvidenceError (or the document's own error) on the first inconsistency. It does not
17
17
  * re-read the chain: run `arl-verifier verify-bundle` on `settlement` for that.
18
18
  */
19
+ function isObject(v) {
20
+ return typeof v === "object" && v !== null && !Array.isArray(v);
21
+ }
19
22
  export function checkEvidence(raw) {
20
- // The bundle is untrusted input: check the versions as plain values.
21
- const versions = raw;
22
- if (versions.version !== EVIDENCE_VERSION)
23
+ // The bundle is untrusted input: check its shape before reading it (security report
24
+ // 2026-11-17: a missing field must be the caller's EvidenceError, not a TypeError).
25
+ const doc = raw;
26
+ if (!isObject(doc) || doc.version !== EVIDENCE_VERSION)
23
27
  throw new EvidenceError("version must be arl-evidence/2");
24
- if (versions.settlement.version !== "arl-evidence/1") {
28
+ const record = doc.settlement;
29
+ if (!isObject(record) || record.version !== "arl-evidence/1") {
25
30
  throw new EvidenceError("settlement must be arl-evidence/1");
26
31
  }
32
+ if (!isObject(record.job) ||
33
+ !isObject(record.config) ||
34
+ !Array.isArray(record.config.committee) ||
35
+ !Array.isArray(record.votes)) {
36
+ throw new EvidenceError("settlement record is incomplete");
37
+ }
27
38
  const s = raw.settlement;
28
39
  const task = parseTask(raw.task);
29
40
  const proof = parseProof(raw.proof);
@@ -90,6 +101,11 @@ export function checkEvidence(raw) {
90
101
  if (s.decided?.approved === true && approvals < task.verification.threshold) {
91
102
  throw new EvidenceError("decided approved without enough approvals");
92
103
  }
104
+ // A committee rejection happens only once no deliverable can reach the threshold.
105
+ const open = s.config.committee.length - approvals - rejections;
106
+ if (s.decided?.approved === false && approvals + open >= task.verification.threshold) {
107
+ throw new EvidenceError("decided rejected while the threshold was still reachable");
108
+ }
93
109
  if (s.settlement === null)
94
110
  return { outcome: "pending", approvals, rejections, overturned: false };
95
111
  // On chain a provider is paid only through the evaluator's settlement, which always follows a
@@ -7,6 +7,8 @@ export { POLICY_VERSION, PolicyError, checkTaskAgainstPolicy, decideVote, effect
7
7
  export type { ModelAllowance, Policy, RuleOutcome, VoteDecision } from "./policy.ts";
8
8
  export { DEFAULT_PARAMS, REPUTATION_VERSION, ReputationError, reputationScore, } from "./reputation.ts";
9
9
  export type { Outcome, OutcomeKind, Score, ScoreParams } from "./reputation.ts";
10
+ export { FEEDBACK_TAG, outcomesFromChain } from "./reputationRead.ts";
11
+ export type { EvaluatorLogs, FeedbackRecord, JobRecord, ReadResult } from "./reputationRead.ts";
10
12
  export { EVIDENCE_VERSION, EvidenceError, checkEvidence } from "./evidence.ts";
11
13
  export type { EvidenceResult, EvidenceV2, SettlementRecord } from "./evidence.ts";
12
14
  export { BASE_MAINNET_TASK_DEPLOYMENTS, taskDeployment, type TaskDeployment, } from "./deployments.ts";
@@ -3,6 +3,7 @@ export { BOUNDS, EVIDENCE_KINDS, TASK_VERSION, TIERS, TOKENS, TaskError, WORKLOA
3
3
  export { PROOF_VERSION, ProofError, REEXEC_RESULT_VERSION, checkProofAgainstTask, parseProof, proofHash, submittedDeliverable, } from "./proof.js";
4
4
  export { POLICY_VERSION, PolicyError, checkTaskAgainstPolicy, decideVote, effectiveBond, parsePolicy, policyHash, } from "./policy.js";
5
5
  export { DEFAULT_PARAMS, REPUTATION_VERSION, ReputationError, reputationScore, } from "./reputation.js";
6
+ export { FEEDBACK_TAG, outcomesFromChain } from "./reputationRead.js";
6
7
  export { EVIDENCE_VERSION, EvidenceError, checkEvidence } from "./evidence.js";
7
8
  export { BASE_MAINNET_TASK_DEPLOYMENTS, taskDeployment, } from "./deployments.js";
8
9
  export { BUILTIN_POLICIES, builtinPolicy } from "./policies.js";
@@ -43,6 +43,60 @@ const RAW = [
43
43
  required_evidence: ["artifact", "model-verdict"],
44
44
  model: { allowed: true, max_budget: { ARL: ARL_100, USDC: "100000000" }, models: [] },
45
45
  },
46
+ // Job-type policies: one per common kind of agent work, each paired with a task template in
47
+ // spec/arl-policy/v0.1.0/templates and a validator checklist in the spec README.
48
+ {
49
+ version: POLICY_VERSION,
50
+ id: "code-tests",
51
+ workload_classes: ["reexec"],
52
+ tiers: ["reexecution"],
53
+ committee: { min_size: 3, max_size: 7 },
54
+ vote_window_seconds: [3600, 86400],
55
+ challenge_window_seconds: [86400, 259200],
56
+ min_bond_floor: ARL_100,
57
+ bond_covers_budget: true,
58
+ required_evidence: ["result-manifest", "logs"],
59
+ model: { allowed: false, max_budget: {}, models: [] },
60
+ },
61
+ {
62
+ version: POLICY_VERSION,
63
+ id: "data-recompute",
64
+ workload_classes: ["reexec"],
65
+ tiers: ["reexecution"],
66
+ committee: { min_size: 3, max_size: 7 },
67
+ vote_window_seconds: [3600, 86400],
68
+ challenge_window_seconds: [86400, 259200],
69
+ min_bond_floor: ARL_100,
70
+ bond_covers_budget: true,
71
+ required_evidence: ["result-manifest", "artifact"],
72
+ model: { allowed: false, max_budget: {}, models: [] },
73
+ },
74
+ {
75
+ version: POLICY_VERSION,
76
+ id: "gpu-inference",
77
+ workload_classes: ["attested"],
78
+ tiers: ["attested"],
79
+ committee: { min_size: 3, max_size: 7 },
80
+ vote_window_seconds: [3600, 172800],
81
+ challenge_window_seconds: [86400, 259200],
82
+ min_bond_floor: ARL_100,
83
+ bond_covers_budget: true,
84
+ required_evidence: ["attestation", "result-manifest", "logs"],
85
+ model: { allowed: false, max_budget: {}, models: [] },
86
+ },
87
+ {
88
+ version: POLICY_VERSION,
89
+ id: "research-sources",
90
+ workload_classes: ["model-assisted"],
91
+ tiers: ["attested"],
92
+ committee: { min_size: 3, max_size: 7 },
93
+ vote_window_seconds: [3600, 172800],
94
+ challenge_window_seconds: [86400, 259200],
95
+ min_bond_floor: ARL_100,
96
+ bond_covers_budget: true,
97
+ required_evidence: ["artifact", "model-verdict", "logs"],
98
+ model: { allowed: true, max_budget: { ARL: ARL_100, USDC: "100000000" }, models: [] },
99
+ },
46
100
  ];
47
101
  /** The built-in policies, validated, by id. */
48
102
  export const BUILTIN_POLICIES = new Map(RAW.map((r) => {
@@ -0,0 +1,57 @@
1
+ import type { Outcome } from "./reputation.ts";
2
+ export declare const FEEDBACK_TAG = "arl-verified";
3
+ type Address = `0x${string}`;
4
+ type Hex = `0x${string}`;
5
+ /** A NewFeedback event of the ReputationRegistry. */
6
+ export interface FeedbackRecord {
7
+ /** The evaluator that wrote it (the event's clientAddress). */
8
+ evaluator: Address;
9
+ agentId: bigint;
10
+ value: bigint;
11
+ valueDecimals: number;
12
+ tag1: string;
13
+ feedbackHash: Hex;
14
+ /** Unix seconds of the block. */
15
+ timestamp: number;
16
+ revoked?: boolean;
17
+ }
18
+ /** Events of one verified evaluator, for the jobs that matter. */
19
+ export interface EvaluatorLogs {
20
+ evaluator: Address;
21
+ /** The ARLJobs escrow this evaluator settles. */
22
+ escrow: Address;
23
+ token: Outcome["token"];
24
+ configured: {
25
+ jobId: bigint;
26
+ providerAgentId: bigint;
27
+ }[];
28
+ committeeApproved: bigint[];
29
+ /** Jobs whose agent could not be bound at approval (FeedbackFailed before any vote). */
30
+ unbound: bigint[];
31
+ finalized: {
32
+ jobId: bigint;
33
+ voteHash: Hex;
34
+ }[];
35
+ disputed: bigint[];
36
+ failed: bigint[];
37
+ }
38
+ export interface JobRecord {
39
+ escrow: Address;
40
+ jobId: bigint;
41
+ client: Address;
42
+ budget: bigint;
43
+ /** ARLJobs status name. */
44
+ status: string;
45
+ /** Unix seconds of the JobExpired event, when the job was refunded after its deadline. */
46
+ expiredAt?: number;
47
+ }
48
+ export interface ReadResult {
49
+ outcomes: Outcome[];
50
+ /** Records that could not be joined, with the reason. */
51
+ skipped: {
52
+ what: string;
53
+ reason: string;
54
+ }[];
55
+ }
56
+ export declare function outcomesFromChain(agentId: bigint, feedback: readonly FeedbackRecord[], evaluators: readonly EvaluatorLogs[], jobs: readonly JobRecord[]): ReadResult;
57
+ export {};
@@ -0,0 +1,100 @@
1
+ // arl-reputation/1 read path (spec/arl-reputation/v0.1.0, "Read path"): turns what the chain
2
+ // recorded into the outcomes `reputationScore` takes. Pure: the caller reads the logs and jobs.
3
+ //
4
+ // Completed and rejected outcomes come only from the feedback the deployed verified evaluators
5
+ // wrote to the ERC-8004 ReputationRegistry (tag "arl-verified", value 100 or 0). Each record is
6
+ // joined to its job through the evaluator's Finalized event with the same vote hash. Expired
7
+ // outcomes are jobs the agent took (CommitteeApproved with the agent bound) that were refunded
8
+ // after their deadline without a committee failure. Anything that does not join is left out and
9
+ // reported, never guessed.
10
+ export const FEEDBACK_TAG = "arl-verified";
11
+ const key = (escrow, jobId) => `${escrow.toLowerCase()}:${jobId.toString()}`;
12
+ const same = (a, b) => a.toLowerCase() === b.toLowerCase();
13
+ export function outcomesFromChain(agentId, feedback, evaluators, jobs) {
14
+ const jobByKey = new Map(jobs.map((j) => [key(j.escrow, j.jobId), j]));
15
+ const outcomes = [];
16
+ const skipped = [];
17
+ const counted = new Set();
18
+ for (const f of feedback) {
19
+ const what = `feedback ${f.feedbackHash} from ${f.evaluator}`;
20
+ if (f.agentId !== agentId || f.tag1 !== FEEDBACK_TAG || f.revoked)
21
+ continue;
22
+ const ev = evaluators.find((e) => same(e.evaluator, f.evaluator));
23
+ if (!ev)
24
+ continue; // only the deployed evaluators are allowed clients
25
+ if (f.valueDecimals !== 0 || (f.value !== 100n && f.value !== 0n)) {
26
+ skipped.push({ what, reason: "value is not 100 or 0" });
27
+ continue;
28
+ }
29
+ const fin = ev.finalized.filter((x) => x.voteHash.toLowerCase() === f.feedbackHash.toLowerCase());
30
+ const jobIds = [...new Set(fin.map((x) => x.jobId))];
31
+ if (jobIds.length !== 1) {
32
+ skipped.push({
33
+ what,
34
+ reason: `${String(jobIds.length)} finalized jobs carry this vote hash`,
35
+ });
36
+ continue;
37
+ }
38
+ const jobId = jobIds[0];
39
+ const conf = ev.configured.find((c) => c.jobId === jobId);
40
+ if (!conf || conf.providerAgentId !== agentId) {
41
+ skipped.push({ what, reason: `job ${jobId.toString()} is not configured for this agent` });
42
+ continue;
43
+ }
44
+ const job = jobByKey.get(key(ev.escrow, jobId));
45
+ if (!job) {
46
+ skipped.push({ what, reason: `job ${jobId.toString()} was not read` });
47
+ continue;
48
+ }
49
+ const k = key(ev.escrow, jobId);
50
+ if (counted.has(k)) {
51
+ skipped.push({ what, reason: `job ${jobId.toString()} already counted` });
52
+ continue;
53
+ }
54
+ counted.add(k);
55
+ outcomes.push({
56
+ job: `${ev.escrow}:${jobId.toString()}`,
57
+ client: job.client,
58
+ token: ev.token,
59
+ budget: job.budget.toString(),
60
+ outcome: f.value === 100n ? "completed" : "rejected",
61
+ final_at: f.timestamp,
62
+ disputed: ev.disputed.includes(jobId),
63
+ });
64
+ }
65
+ for (const ev of evaluators) {
66
+ for (const c of ev.configured) {
67
+ if (c.providerAgentId !== agentId)
68
+ continue;
69
+ const k = key(ev.escrow, c.jobId);
70
+ if (counted.has(k))
71
+ continue;
72
+ if (!ev.committeeApproved.includes(c.jobId) || ev.unbound.includes(c.jobId))
73
+ continue;
74
+ if (ev.failed.includes(c.jobId))
75
+ continue; // the committee did not decide: excluded
76
+ const job = jobByKey.get(k);
77
+ if (!job || job.status !== "Expired")
78
+ continue;
79
+ if (job.expiredAt === undefined) {
80
+ skipped.push({
81
+ what: `job ${c.jobId.toString()}`,
82
+ reason: "expired without a JobExpired time",
83
+ });
84
+ continue;
85
+ }
86
+ counted.add(k);
87
+ outcomes.push({
88
+ job: `${ev.escrow}:${c.jobId.toString()}`,
89
+ client: job.client,
90
+ token: ev.token,
91
+ budget: job.budget.toString(),
92
+ outcome: "expired",
93
+ final_at: job.expiredAt,
94
+ disputed: ev.disputed.includes(c.jobId),
95
+ });
96
+ }
97
+ }
98
+ outcomes.sort((a, b) => a.final_at - b.final_at || a.job.localeCompare(b.job));
99
+ return { outcomes, skipped };
100
+ }