arl-protocol-sdk 0.0.0-stage → 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.
- package/README.md +79 -2
- package/package.json +32 -4
- package/protocol/src/canonical.d.ts +7 -0
- package/protocol/src/canonical.js +35 -0
- package/protocol/src/deployments.d.ts +17 -0
- package/protocol/src/deployments.js +24 -0
- package/protocol/src/evidence.d.ts +72 -0
- package/protocol/src/evidence.js +107 -0
- package/protocol/src/index.d.ts +14 -0
- package/protocol/src/index.js +9 -0
- package/protocol/src/policies.d.ts +5 -0
- package/protocol/src/policies.js +56 -0
- package/protocol/src/policy.d.ts +65 -0
- package/protocol/src/policy.js +202 -0
- package/protocol/src/prepare.d.ts +176 -0
- package/protocol/src/prepare.js +104 -0
- package/protocol/src/proof.d.ts +70 -0
- package/protocol/src/proof.js +239 -0
- package/protocol/src/reputation.d.ts +47 -0
- package/protocol/src/reputation.js +74 -0
- package/protocol/src/task.d.ts +121 -0
- package/protocol/src/task.js +322 -0
- package/sdk/src/abi.d.ts +358 -0
- package/sdk/src/abi.js +465 -0
- package/sdk/src/acquireArl.d.ts +34 -0
- package/sdk/src/acquireArl.js +126 -0
- package/sdk/src/escrowProvider.d.ts +73 -0
- package/sdk/src/escrowProvider.js +169 -0
- package/sdk/src/index.d.ts +9 -0
- package/sdk/src/index.js +10 -0
- package/sdk/src/jobs.d.ts +278 -0
- package/sdk/src/jobs.js +220 -0
- package/sdk/src/openTask.d.ts +23 -0
- package/sdk/src/openTask.js +116 -0
- package/sdk/src/payVerified.d.ts +45 -0
- package/sdk/src/payVerified.js +147 -0
- package/sdk/src/streaming.d.ts +80 -0
- package/sdk/src/streaming.js +229 -0
- package/sdk/src/verified.d.ts +229 -0
- package/sdk/src/verified.js +220 -0
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
// The service side of an arl-escrow payment (spec/x402-arl-escrow, v0.2.0 draft): build the 402
|
|
2
|
+
// offer, check the job a client funded before doing the work, approve the committee and submit
|
|
3
|
+
// the deliverable.
|
|
4
|
+
//
|
|
5
|
+
// res.status(402).json(buildEscrowOffer({ chainId, provider, specUri, specHash, budget, … }));
|
|
6
|
+
// const job = await checkFundedJob(publicClient, offer, req.headers["x-arl-job"]);
|
|
7
|
+
// await approveCommittee(clients, offer, job.jobId); // validators can now accept
|
|
8
|
+
// … run the spec …
|
|
9
|
+
// await waitForAcceptance(publicClient, offer, job.jobId); // threshold members accepted
|
|
10
|
+
// await submitDeliverable(clients, offer, job.jobId, deliverableHash);
|
|
11
|
+
import { getAddress, parseAbi } from "viem";
|
|
12
|
+
import { ESCROW_SCHEME } from "./payVerified.js";
|
|
13
|
+
import { VerifiedJobError, checkEvaluationFits, checkVerifiedChain, verifiedDeployment, walletAccount, } from "./verified.js";
|
|
14
|
+
/** The 402 body offering payment through a verified job. */
|
|
15
|
+
export function buildEscrowOffer(input) {
|
|
16
|
+
const known = verifiedDeployment(input.chainId);
|
|
17
|
+
const jobs = input.jobs ?? known?.jobs;
|
|
18
|
+
const evaluator = input.evaluator ?? known?.evaluator;
|
|
19
|
+
if (!jobs || !evaluator)
|
|
20
|
+
throw new VerifiedJobError("jobs and evaluator are required locally");
|
|
21
|
+
if (input.budget <= 0n)
|
|
22
|
+
throw new VerifiedJobError("budget must be positive");
|
|
23
|
+
return {
|
|
24
|
+
x402Version: 2,
|
|
25
|
+
accepts: [
|
|
26
|
+
{
|
|
27
|
+
scheme: ESCROW_SCHEME,
|
|
28
|
+
network: `eip155:${String(input.chainId)}`,
|
|
29
|
+
amount: input.budget.toString(),
|
|
30
|
+
payTo: getAddress(input.provider),
|
|
31
|
+
extra: {
|
|
32
|
+
jobs: getAddress(jobs),
|
|
33
|
+
evaluator: getAddress(evaluator),
|
|
34
|
+
specUri: input.specUri,
|
|
35
|
+
specHash: input.specHash,
|
|
36
|
+
committee: input.committee.map((c) => getAddress(c)),
|
|
37
|
+
threshold: input.threshold,
|
|
38
|
+
voteWindow: (input.voteWindow ?? 3600n).toString(),
|
|
39
|
+
challengeWindow: (input.challengeWindow ?? 86400n).toString(),
|
|
40
|
+
bond: (input.bond ?? 100n * 10n ** 18n).toString(),
|
|
41
|
+
expiresIn: (input.expiresIn ?? 259200n).toString(),
|
|
42
|
+
},
|
|
43
|
+
},
|
|
44
|
+
],
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
const jobsAbi = parseAbi([
|
|
48
|
+
"struct Job { uint256 id; address client; address provider; address evaluator; string description; uint256 budget; uint256 expiredAt; uint8 status; address hook; }",
|
|
49
|
+
"function getJob(uint256 jobId) view returns (Job)",
|
|
50
|
+
"function submit(uint256 jobId, bytes32 deliverable, bytes optParams)",
|
|
51
|
+
]);
|
|
52
|
+
const evaluatorAbi = parseAbi([
|
|
53
|
+
"struct Config { uint8 tier; uint8 threshold; uint64 voteWindow; uint64 challengeWindow; uint96 bond; uint256 providerAgentId; bytes32 specHash; address[] committee; }",
|
|
54
|
+
"function getConfig(uint256 jobId) view returns (Config)",
|
|
55
|
+
"function approveCommittee(uint256 jobId)",
|
|
56
|
+
"function voteOf(uint256 jobId, address validator) view returns (uint8)",
|
|
57
|
+
]);
|
|
58
|
+
/** ARLVerifiedEvaluator member states (`voteOf`): accepted (2), voted (3, 4), absent (5). */
|
|
59
|
+
const ACCEPTED = 2;
|
|
60
|
+
const ABSENT = 5;
|
|
61
|
+
/** ARLJobs.JobStatus.Funded. */
|
|
62
|
+
const FUNDED = 1;
|
|
63
|
+
/**
|
|
64
|
+
* Checks the job named by the `X-ARL-Job` header against the offer before any work: same chain
|
|
65
|
+
* and escrow, the service as provider, the offer's evaluator, budget, spec, committee and
|
|
66
|
+
* threshold, and the job funded. Returns the job id and the client.
|
|
67
|
+
*/
|
|
68
|
+
export async function checkFundedJob(publicClient, offer, header) {
|
|
69
|
+
const m = /^(\d+):(0x[0-9a-fA-F]{40}):(\d+)$/.exec(header ?? "");
|
|
70
|
+
if (!m)
|
|
71
|
+
throw new VerifiedJobError("missing or malformed X-ARL-Job header");
|
|
72
|
+
const chainId = await checkVerifiedChain(publicClient);
|
|
73
|
+
if (Number(m[1]) !== chainId || `eip155:${String(chainId)}` !== offer.network)
|
|
74
|
+
throw new VerifiedJobError("the job is on another chain");
|
|
75
|
+
if (getAddress(m[2] ?? "") !== offer.jobs)
|
|
76
|
+
throw new VerifiedJobError("the job is in another escrow");
|
|
77
|
+
const jobId = BigInt(m[3] ?? "0");
|
|
78
|
+
const job = await publicClient.readContract({
|
|
79
|
+
address: offer.jobs,
|
|
80
|
+
abi: jobsAbi,
|
|
81
|
+
functionName: "getJob",
|
|
82
|
+
args: [jobId],
|
|
83
|
+
});
|
|
84
|
+
const cfg = await publicClient.readContract({
|
|
85
|
+
address: offer.evaluator,
|
|
86
|
+
abi: evaluatorAbi,
|
|
87
|
+
functionName: "getConfig",
|
|
88
|
+
args: [jobId],
|
|
89
|
+
});
|
|
90
|
+
const problems = [];
|
|
91
|
+
if (job.status !== FUNDED)
|
|
92
|
+
problems.push("not funded");
|
|
93
|
+
if (getAddress(job.provider) !== offer.provider)
|
|
94
|
+
problems.push("another provider");
|
|
95
|
+
if (getAddress(job.evaluator) !== offer.evaluator)
|
|
96
|
+
problems.push("another evaluator");
|
|
97
|
+
if (job.budget !== offer.budget)
|
|
98
|
+
problems.push("another budget");
|
|
99
|
+
if (cfg.specHash.toLowerCase() !== offer.specHash.toLowerCase())
|
|
100
|
+
problems.push("another spec");
|
|
101
|
+
if (cfg.threshold !== offer.threshold)
|
|
102
|
+
problems.push("another threshold");
|
|
103
|
+
const committee = cfg.committee.map((c) => getAddress(c)).join();
|
|
104
|
+
if (committee !== offer.committee.join())
|
|
105
|
+
problems.push("another committee");
|
|
106
|
+
if (problems.length > 0)
|
|
107
|
+
throw new VerifiedJobError(`job ${jobId.toString()}: ${problems.join(", ")}`);
|
|
108
|
+
await checkEvaluationFits(publicClient, offer.jobs, jobId);
|
|
109
|
+
return { jobId, client: getAddress(job.client) };
|
|
110
|
+
}
|
|
111
|
+
async function send({ publicClient, walletClient }, address, abi, functionName, args) {
|
|
112
|
+
const hash = await walletClient.writeContract({
|
|
113
|
+
account: walletAccount(walletClient),
|
|
114
|
+
chain: walletClient.chain,
|
|
115
|
+
address,
|
|
116
|
+
abi,
|
|
117
|
+
functionName,
|
|
118
|
+
args,
|
|
119
|
+
});
|
|
120
|
+
const r = await publicClient.waitForTransactionReceipt({ hash });
|
|
121
|
+
if (r.status !== "success")
|
|
122
|
+
throw new VerifiedJobError(`${functionName} reverted`);
|
|
123
|
+
return hash;
|
|
124
|
+
}
|
|
125
|
+
/** As the provider: approves the committee, so the validators can accept the job. */
|
|
126
|
+
export function approveCommittee(clients, offer, jobId) {
|
|
127
|
+
return send(clients, offer.evaluator, evaluatorAbi, "approveCommittee", [jobId]);
|
|
128
|
+
}
|
|
129
|
+
/** How many committee members of the job have accepted it (and locked their bond). */
|
|
130
|
+
export async function acceptedCount(publicClient, offer, jobId) {
|
|
131
|
+
const states = await Promise.all(offer.committee.map((member) => publicClient.readContract({
|
|
132
|
+
address: offer.evaluator,
|
|
133
|
+
abi: evaluatorAbi,
|
|
134
|
+
functionName: "voteOf",
|
|
135
|
+
args: [jobId, member],
|
|
136
|
+
})));
|
|
137
|
+
return states.filter((s) => s >= ACCEPTED && s !== ABSENT).length;
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Waits until `threshold` committee members have accepted the job. Submitting before then lets
|
|
141
|
+
* the job end undecided (the client is refunded and the provider is not paid) if not enough
|
|
142
|
+
* members accept in time.
|
|
143
|
+
*/
|
|
144
|
+
export async function waitForAcceptance(publicClient, offer, jobId, { timeoutMs = 30 * 60_000, pollMs = 15_000 } = {}) {
|
|
145
|
+
const until = Date.now() + timeoutMs;
|
|
146
|
+
for (;;) {
|
|
147
|
+
const accepted = await acceptedCount(publicClient, offer, jobId);
|
|
148
|
+
if (accepted >= offer.threshold)
|
|
149
|
+
return accepted;
|
|
150
|
+
if (Date.now() >= until)
|
|
151
|
+
throw new VerifiedJobError(`job ${jobId.toString()}: ${String(accepted)} of ${String(offer.threshold)} members accepted`);
|
|
152
|
+
await new Promise((r) => setTimeout(r, pollMs));
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* As the provider: submits the deliverable hash (the result manifest's deliverable). Refuses
|
|
157
|
+
* while fewer than `threshold` committee members have accepted (see `waitForAcceptance`), unless
|
|
158
|
+
* `requireAccepted` is false.
|
|
159
|
+
*/
|
|
160
|
+
export async function submitDeliverable(clients, offer, jobId, deliverable, { requireAccepted = true } = {}) {
|
|
161
|
+
if (!/^0x[0-9a-fA-F]{64}$/.test(deliverable))
|
|
162
|
+
throw new VerifiedJobError("deliverable must be 32 bytes");
|
|
163
|
+
if (requireAccepted) {
|
|
164
|
+
const accepted = await acceptedCount(clients.publicClient, offer, jobId);
|
|
165
|
+
if (accepted < offer.threshold)
|
|
166
|
+
throw new VerifiedJobError(`job ${jobId.toString()}: only ${String(accepted)} of ${String(offer.threshold)} members accepted; submit after waitForAcceptance`);
|
|
167
|
+
}
|
|
168
|
+
return send(clients, offer.jobs, jobsAbi, "submit", [jobId, deliverable, "0x"]);
|
|
169
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export { computePaymentAbi } from "./abi.ts";
|
|
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";
|
|
4
|
+
export { ESCROW_SCHEME, JOB_HEADER, fundVerifiedJob, parseEscrowOffer, payVerified, type EscrowOffer, type PayVerifiedOptions, } from "./payVerified.ts";
|
|
5
|
+
export { ARL_SWAP, acquireArl, quoteArl, type AcquireArlParams, type ArlQuoteToken, } from "./acquireArl.ts";
|
|
6
|
+
export { acceptedCount, approveCommittee, buildEscrowOffer, checkFundedJob, submitDeliverable, waitForAcceptance, type EscrowOfferInput, } from "./escrowProvider.ts";
|
|
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";
|
package/sdk/src/index.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export { computePaymentAbi } from "./abi.js";
|
|
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";
|
|
4
|
+
export { ESCROW_SCHEME, JOB_HEADER, fundVerifiedJob, parseEscrowOffer, payVerified, } from "./payVerified.js";
|
|
5
|
+
export { ARL_SWAP, acquireArl, quoteArl, } from "./acquireArl.js";
|
|
6
|
+
export { acceptedCount, approveCommittee, buildEscrowOffer, checkFundedJob, submitDeliverable, waitForAcceptance, } from "./escrowProvider.js";
|
|
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";
|
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
import { type Address, type Hash, type Hex, type PublicClient, type WalletClient } from "viem";
|
|
2
|
+
/** The ARL escrows on Base Mainnet (contracts/deploy/base-mainnet-jobs.json). */
|
|
3
|
+
export declare const ESCROWS: {
|
|
4
|
+
readonly ARL: "0x9aE99bF9a59aF47E81346B7c0b93Cd2B610455fC";
|
|
5
|
+
readonly USDC: "0xE3eA0EAEc3Cf9DA2d0856A0f784A4B1671AeFD04";
|
|
6
|
+
};
|
|
7
|
+
export type Escrow = keyof typeof ESCROWS;
|
|
8
|
+
export declare const BASE_MAINNET_CHAIN_ID = 8453;
|
|
9
|
+
export declare const STATUS: readonly ["Open", "Funded", "Submitted", "Completed", "Rejected", "Expired"];
|
|
10
|
+
export declare const jobsAbi: readonly [{
|
|
11
|
+
readonly name: "paymentToken";
|
|
12
|
+
readonly type: "function";
|
|
13
|
+
readonly stateMutability: "view";
|
|
14
|
+
readonly inputs: readonly [];
|
|
15
|
+
readonly outputs: readonly [{
|
|
16
|
+
readonly type: "address";
|
|
17
|
+
}];
|
|
18
|
+
}, {
|
|
19
|
+
readonly name: "getJob";
|
|
20
|
+
readonly type: "function";
|
|
21
|
+
readonly stateMutability: "view";
|
|
22
|
+
readonly inputs: readonly [{
|
|
23
|
+
readonly type: "uint256";
|
|
24
|
+
readonly name: "jobId";
|
|
25
|
+
}];
|
|
26
|
+
readonly outputs: readonly [{
|
|
27
|
+
readonly type: "tuple";
|
|
28
|
+
readonly components: readonly [{
|
|
29
|
+
readonly type: "uint256";
|
|
30
|
+
readonly name: "id";
|
|
31
|
+
}, {
|
|
32
|
+
readonly type: "address";
|
|
33
|
+
readonly name: "client";
|
|
34
|
+
}, {
|
|
35
|
+
readonly type: "address";
|
|
36
|
+
readonly name: "provider";
|
|
37
|
+
}, {
|
|
38
|
+
readonly type: "address";
|
|
39
|
+
readonly name: "evaluator";
|
|
40
|
+
}, {
|
|
41
|
+
readonly type: "string";
|
|
42
|
+
readonly name: "description";
|
|
43
|
+
}, {
|
|
44
|
+
readonly type: "uint256";
|
|
45
|
+
readonly name: "budget";
|
|
46
|
+
}, {
|
|
47
|
+
readonly type: "uint256";
|
|
48
|
+
readonly name: "expiredAt";
|
|
49
|
+
}, {
|
|
50
|
+
readonly type: "uint8";
|
|
51
|
+
readonly name: "status";
|
|
52
|
+
}, {
|
|
53
|
+
readonly type: "address";
|
|
54
|
+
readonly name: "hook";
|
|
55
|
+
}];
|
|
56
|
+
}];
|
|
57
|
+
}, {
|
|
58
|
+
readonly name: "createJob";
|
|
59
|
+
readonly type: "function";
|
|
60
|
+
readonly stateMutability: "nonpayable";
|
|
61
|
+
readonly inputs: readonly [{
|
|
62
|
+
readonly type: "address";
|
|
63
|
+
readonly name: "provider";
|
|
64
|
+
}, {
|
|
65
|
+
readonly type: "address";
|
|
66
|
+
readonly name: "evaluator";
|
|
67
|
+
}, {
|
|
68
|
+
readonly type: "uint256";
|
|
69
|
+
readonly name: "expiredAt";
|
|
70
|
+
}, {
|
|
71
|
+
readonly type: "string";
|
|
72
|
+
readonly name: "description";
|
|
73
|
+
}, {
|
|
74
|
+
readonly type: "address";
|
|
75
|
+
readonly name: "hook";
|
|
76
|
+
}];
|
|
77
|
+
readonly outputs: readonly [{
|
|
78
|
+
readonly type: "uint256";
|
|
79
|
+
}];
|
|
80
|
+
}, {
|
|
81
|
+
readonly name: "setBudget";
|
|
82
|
+
readonly type: "function";
|
|
83
|
+
readonly stateMutability: "nonpayable";
|
|
84
|
+
readonly inputs: readonly [{
|
|
85
|
+
readonly type: "uint256";
|
|
86
|
+
readonly name: "jobId";
|
|
87
|
+
}, {
|
|
88
|
+
readonly type: "uint256";
|
|
89
|
+
readonly name: "amount";
|
|
90
|
+
}, {
|
|
91
|
+
readonly type: "bytes";
|
|
92
|
+
readonly name: "optParams";
|
|
93
|
+
}];
|
|
94
|
+
readonly outputs: readonly [];
|
|
95
|
+
}, {
|
|
96
|
+
readonly name: "fund";
|
|
97
|
+
readonly type: "function";
|
|
98
|
+
readonly stateMutability: "nonpayable";
|
|
99
|
+
readonly inputs: readonly [{
|
|
100
|
+
readonly type: "uint256";
|
|
101
|
+
readonly name: "jobId";
|
|
102
|
+
}, {
|
|
103
|
+
readonly type: "uint256";
|
|
104
|
+
readonly name: "expectedBudget";
|
|
105
|
+
}, {
|
|
106
|
+
readonly type: "bytes";
|
|
107
|
+
readonly name: "optParams";
|
|
108
|
+
}];
|
|
109
|
+
readonly outputs: readonly [];
|
|
110
|
+
}, {
|
|
111
|
+
readonly name: "submit";
|
|
112
|
+
readonly type: "function";
|
|
113
|
+
readonly stateMutability: "nonpayable";
|
|
114
|
+
readonly inputs: readonly [{
|
|
115
|
+
readonly type: "uint256";
|
|
116
|
+
readonly name: "jobId";
|
|
117
|
+
}, {
|
|
118
|
+
readonly type: "bytes32";
|
|
119
|
+
readonly name: "deliverable";
|
|
120
|
+
}, {
|
|
121
|
+
readonly type: "bytes";
|
|
122
|
+
readonly name: "optParams";
|
|
123
|
+
}];
|
|
124
|
+
readonly outputs: readonly [];
|
|
125
|
+
}, {
|
|
126
|
+
readonly name: "complete";
|
|
127
|
+
readonly type: "function";
|
|
128
|
+
readonly stateMutability: "nonpayable";
|
|
129
|
+
readonly inputs: readonly [{
|
|
130
|
+
readonly type: "uint256";
|
|
131
|
+
readonly name: "jobId";
|
|
132
|
+
}, {
|
|
133
|
+
readonly type: "bytes32";
|
|
134
|
+
readonly name: "reason";
|
|
135
|
+
}, {
|
|
136
|
+
readonly type: "bytes";
|
|
137
|
+
readonly name: "optParams";
|
|
138
|
+
}];
|
|
139
|
+
readonly outputs: readonly [];
|
|
140
|
+
}, {
|
|
141
|
+
readonly name: "reject";
|
|
142
|
+
readonly type: "function";
|
|
143
|
+
readonly stateMutability: "nonpayable";
|
|
144
|
+
readonly inputs: readonly [{
|
|
145
|
+
readonly type: "uint256";
|
|
146
|
+
readonly name: "jobId";
|
|
147
|
+
}, {
|
|
148
|
+
readonly type: "bytes32";
|
|
149
|
+
readonly name: "reason";
|
|
150
|
+
}, {
|
|
151
|
+
readonly type: "bytes";
|
|
152
|
+
readonly name: "optParams";
|
|
153
|
+
}];
|
|
154
|
+
readonly outputs: readonly [];
|
|
155
|
+
}, {
|
|
156
|
+
readonly name: "claimRefund";
|
|
157
|
+
readonly type: "function";
|
|
158
|
+
readonly stateMutability: "nonpayable";
|
|
159
|
+
readonly inputs: readonly [{
|
|
160
|
+
readonly type: "uint256";
|
|
161
|
+
readonly name: "jobId";
|
|
162
|
+
}];
|
|
163
|
+
readonly outputs: readonly [];
|
|
164
|
+
}, {
|
|
165
|
+
readonly name: "JobCreated";
|
|
166
|
+
readonly type: "event";
|
|
167
|
+
readonly inputs: readonly [{
|
|
168
|
+
readonly type: "uint256";
|
|
169
|
+
readonly name: "jobId";
|
|
170
|
+
readonly indexed: true;
|
|
171
|
+
}, {
|
|
172
|
+
readonly type: "address";
|
|
173
|
+
readonly name: "client";
|
|
174
|
+
readonly indexed: true;
|
|
175
|
+
}, {
|
|
176
|
+
readonly type: "address";
|
|
177
|
+
readonly name: "provider";
|
|
178
|
+
readonly indexed: true;
|
|
179
|
+
}, {
|
|
180
|
+
readonly type: "address";
|
|
181
|
+
readonly name: "evaluator";
|
|
182
|
+
}, {
|
|
183
|
+
readonly type: "uint256";
|
|
184
|
+
readonly name: "expiredAt";
|
|
185
|
+
}, {
|
|
186
|
+
readonly type: "address";
|
|
187
|
+
readonly name: "hook";
|
|
188
|
+
}];
|
|
189
|
+
}];
|
|
190
|
+
export declare const erc20Abi: readonly [{
|
|
191
|
+
readonly name: "decimals";
|
|
192
|
+
readonly type: "function";
|
|
193
|
+
readonly stateMutability: "view";
|
|
194
|
+
readonly inputs: readonly [];
|
|
195
|
+
readonly outputs: readonly [{
|
|
196
|
+
readonly type: "uint8";
|
|
197
|
+
}];
|
|
198
|
+
}, {
|
|
199
|
+
readonly name: "allowance";
|
|
200
|
+
readonly type: "function";
|
|
201
|
+
readonly stateMutability: "view";
|
|
202
|
+
readonly inputs: readonly [{
|
|
203
|
+
readonly type: "address";
|
|
204
|
+
readonly name: "owner";
|
|
205
|
+
}, {
|
|
206
|
+
readonly type: "address";
|
|
207
|
+
readonly name: "spender";
|
|
208
|
+
}];
|
|
209
|
+
readonly outputs: readonly [{
|
|
210
|
+
readonly type: "uint256";
|
|
211
|
+
}];
|
|
212
|
+
}, {
|
|
213
|
+
readonly name: "approve";
|
|
214
|
+
readonly type: "function";
|
|
215
|
+
readonly stateMutability: "nonpayable";
|
|
216
|
+
readonly inputs: readonly [{
|
|
217
|
+
readonly type: "address";
|
|
218
|
+
readonly name: "spender";
|
|
219
|
+
}, {
|
|
220
|
+
readonly type: "uint256";
|
|
221
|
+
readonly name: "amount";
|
|
222
|
+
}];
|
|
223
|
+
readonly outputs: readonly [{
|
|
224
|
+
readonly type: "bool";
|
|
225
|
+
}];
|
|
226
|
+
}];
|
|
227
|
+
export interface Clients {
|
|
228
|
+
publicClient: PublicClient;
|
|
229
|
+
walletClient: WalletClient;
|
|
230
|
+
}
|
|
231
|
+
export declare class ArlJobError extends Error {
|
|
232
|
+
constructor(message: string);
|
|
233
|
+
}
|
|
234
|
+
/** A text becomes its keccak256 hash; a 32-byte hex value is used as it is. */
|
|
235
|
+
export declare function toBytes32(value: string): Hex;
|
|
236
|
+
export declare function checkAddress(value: string, what: string): Address;
|
|
237
|
+
export declare function parseAmount(value: string | number, decimals: number): bigint;
|
|
238
|
+
export declare function parseJobId(value: string | number): bigint;
|
|
239
|
+
export interface JobView {
|
|
240
|
+
jobId: string;
|
|
241
|
+
escrow: Address;
|
|
242
|
+
client: Address;
|
|
243
|
+
provider: Address;
|
|
244
|
+
evaluator: Address;
|
|
245
|
+
description: string;
|
|
246
|
+
budget: string;
|
|
247
|
+
expiresAt: string;
|
|
248
|
+
/** Open, Funded, Submitted, Completed, Rejected or Expired. */
|
|
249
|
+
status: string;
|
|
250
|
+
}
|
|
251
|
+
export declare function getJob(c: Clients, escrow: Address, jobId: bigint): Promise<JobView>;
|
|
252
|
+
export interface CreateJobInput {
|
|
253
|
+
provider: string;
|
|
254
|
+
/** The account that approves the work; empty means the wallet itself. */
|
|
255
|
+
evaluator?: string;
|
|
256
|
+
hoursUntilDeadline: number;
|
|
257
|
+
description: string;
|
|
258
|
+
}
|
|
259
|
+
export declare function createJob(c: Clients, escrow: Address, input: CreateJobInput): Promise<{
|
|
260
|
+
jobId: string;
|
|
261
|
+
txHash: Hash;
|
|
262
|
+
}>;
|
|
263
|
+
export declare function setBudget(c: Clients, escrow: Address, jobId: bigint, amount: string): Promise<{
|
|
264
|
+
txHash: Hash;
|
|
265
|
+
}>;
|
|
266
|
+
/** Funds the agreed budget, approving the escrow first when its allowance is too low. */
|
|
267
|
+
export declare function fundJob(c: Clients, escrow: Address, jobId: bigint): Promise<{
|
|
268
|
+
txHash: Hash;
|
|
269
|
+
approveTxHash?: Hash;
|
|
270
|
+
budget: string;
|
|
271
|
+
}>;
|
|
272
|
+
export declare function submitWork(c: Clients, escrow: Address, jobId: bigint, deliverable: string): Promise<{
|
|
273
|
+
txHash: Hash;
|
|
274
|
+
deliverable: Hex;
|
|
275
|
+
}>;
|
|
276
|
+
export declare function settleJob(c: Clients, escrow: Address, jobId: bigint, outcome: "complete" | "reject" | "claimRefund", reason: string): Promise<{
|
|
277
|
+
txHash: Hash;
|
|
278
|
+
}>;
|
package/sdk/src/jobs.js
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
// Plain escrowed jobs (ERC-8183) on the ARL escrows on Base Mainnet, in the fewest calls: create a
|
|
2
|
+
// job, agree a budget, fund it, hand in the work, and settle it (complete, reject or refund).
|
|
3
|
+
// Amounts are plain numbers in token units ("10" is 10 ARL); approvals happen automatically.
|
|
4
|
+
import { formatUnits, getAddress, isAddress, isHex, keccak256, parseAbi, parseEventLogs, parseUnits, stringToHex, } from "viem";
|
|
5
|
+
/** The ARL escrows on Base Mainnet (contracts/deploy/base-mainnet-jobs.json). */
|
|
6
|
+
export const ESCROWS = {
|
|
7
|
+
ARL: "0x9aE99bF9a59aF47E81346B7c0b93Cd2B610455fC",
|
|
8
|
+
USDC: "0xE3eA0EAEc3Cf9DA2d0856A0f784A4B1671AeFD04",
|
|
9
|
+
};
|
|
10
|
+
export const BASE_MAINNET_CHAIN_ID = 8453;
|
|
11
|
+
export const STATUS = ["Open", "Funded", "Submitted", "Completed", "Rejected", "Expired"];
|
|
12
|
+
export const jobsAbi = parseAbi([
|
|
13
|
+
"struct Job { uint256 id; address client; address provider; address evaluator; string description; uint256 budget; uint256 expiredAt; uint8 status; address hook; }",
|
|
14
|
+
"function paymentToken() view returns (address)",
|
|
15
|
+
"function getJob(uint256 jobId) view returns (Job)",
|
|
16
|
+
"function createJob(address provider, address evaluator, uint256 expiredAt, string description, address hook) returns (uint256)",
|
|
17
|
+
"function setBudget(uint256 jobId, uint256 amount, bytes optParams)",
|
|
18
|
+
"function fund(uint256 jobId, uint256 expectedBudget, bytes optParams)",
|
|
19
|
+
"function submit(uint256 jobId, bytes32 deliverable, bytes optParams)",
|
|
20
|
+
"function complete(uint256 jobId, bytes32 reason, bytes optParams)",
|
|
21
|
+
"function reject(uint256 jobId, bytes32 reason, bytes optParams)",
|
|
22
|
+
"function claimRefund(uint256 jobId)",
|
|
23
|
+
"event JobCreated(uint256 indexed jobId, address indexed client, address indexed provider, address evaluator, uint256 expiredAt, address hook)",
|
|
24
|
+
]);
|
|
25
|
+
export const erc20Abi = parseAbi([
|
|
26
|
+
"function decimals() view returns (uint8)",
|
|
27
|
+
"function allowance(address owner, address spender) view returns (uint256)",
|
|
28
|
+
"function approve(address spender, uint256 amount) returns (bool)",
|
|
29
|
+
]);
|
|
30
|
+
export class ArlJobError extends Error {
|
|
31
|
+
constructor(message) {
|
|
32
|
+
super(message);
|
|
33
|
+
this.name = "ArlJobError";
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
/** A text becomes its keccak256 hash; a 32-byte hex value is used as it is. */
|
|
37
|
+
export function toBytes32(value) {
|
|
38
|
+
const v = value.trim();
|
|
39
|
+
if (isHex(v) && v.length === 66)
|
|
40
|
+
return v;
|
|
41
|
+
if (v === "")
|
|
42
|
+
throw new ArlJobError("the deliverable or reason is empty");
|
|
43
|
+
return keccak256(stringToHex(v));
|
|
44
|
+
}
|
|
45
|
+
export function checkAddress(value, what) {
|
|
46
|
+
const v = value.trim();
|
|
47
|
+
if (!isAddress(v, { strict: false }))
|
|
48
|
+
throw new ArlJobError(`${what} is not an address: ${v}`);
|
|
49
|
+
return getAddress(v);
|
|
50
|
+
}
|
|
51
|
+
export function parseAmount(value, decimals) {
|
|
52
|
+
const v = String(value).trim();
|
|
53
|
+
if (!/^\d+(\.\d+)?$/.test(v))
|
|
54
|
+
throw new ArlJobError(`not a positive amount: ${v}`);
|
|
55
|
+
const amount = parseUnits(v, decimals);
|
|
56
|
+
if (amount === 0n)
|
|
57
|
+
throw new ArlJobError("the amount must be above zero");
|
|
58
|
+
return amount;
|
|
59
|
+
}
|
|
60
|
+
export function parseJobId(value) {
|
|
61
|
+
const v = String(value).trim();
|
|
62
|
+
if (!/^\d+$/.test(v) || v === "0")
|
|
63
|
+
throw new ArlJobError(`not a job id: ${v}`);
|
|
64
|
+
return BigInt(v);
|
|
65
|
+
}
|
|
66
|
+
function sender(c) {
|
|
67
|
+
const account = c.walletClient.account;
|
|
68
|
+
if (!account)
|
|
69
|
+
throw new ArlJobError("the wallet credential has no account");
|
|
70
|
+
return account.address;
|
|
71
|
+
}
|
|
72
|
+
async function checkChain(c) {
|
|
73
|
+
const id = await c.publicClient.getChainId();
|
|
74
|
+
if (id !== BASE_MAINNET_CHAIN_ID)
|
|
75
|
+
throw new ArlJobError(`the RPC serves chain ${String(id)}, not Base Mainnet (8453)`);
|
|
76
|
+
}
|
|
77
|
+
async function send(c, escrow, functionName, args) {
|
|
78
|
+
const { request } = await c.publicClient.simulateContract({
|
|
79
|
+
address: escrow,
|
|
80
|
+
abi: jobsAbi,
|
|
81
|
+
functionName,
|
|
82
|
+
args: args,
|
|
83
|
+
account: sender(c),
|
|
84
|
+
});
|
|
85
|
+
const hash = await c.walletClient.writeContract(request);
|
|
86
|
+
const receipt = await c.publicClient.waitForTransactionReceipt({ hash });
|
|
87
|
+
if (receipt.status !== "success")
|
|
88
|
+
throw new ArlJobError(`transaction ${hash} reverted`);
|
|
89
|
+
return hash;
|
|
90
|
+
}
|
|
91
|
+
async function decimalsOf(c, escrow) {
|
|
92
|
+
const token = await c.publicClient.readContract({
|
|
93
|
+
address: escrow,
|
|
94
|
+
abi: jobsAbi,
|
|
95
|
+
functionName: "paymentToken",
|
|
96
|
+
});
|
|
97
|
+
return c.publicClient.readContract({ address: token, abi: erc20Abi, functionName: "decimals" });
|
|
98
|
+
}
|
|
99
|
+
export async function getJob(c, escrow, jobId) {
|
|
100
|
+
const job = await c.publicClient.readContract({
|
|
101
|
+
address: escrow,
|
|
102
|
+
abi: jobsAbi,
|
|
103
|
+
functionName: "getJob",
|
|
104
|
+
args: [jobId],
|
|
105
|
+
});
|
|
106
|
+
if (job.id === 0n)
|
|
107
|
+
throw new ArlJobError(`job ${jobId.toString()} does not exist`);
|
|
108
|
+
const decimals = await decimalsOf(c, escrow);
|
|
109
|
+
return {
|
|
110
|
+
jobId: job.id.toString(),
|
|
111
|
+
escrow,
|
|
112
|
+
client: job.client,
|
|
113
|
+
provider: job.provider,
|
|
114
|
+
evaluator: job.evaluator,
|
|
115
|
+
description: job.description,
|
|
116
|
+
budget: formatUnits(job.budget, decimals),
|
|
117
|
+
expiresAt: new Date(Number(job.expiredAt) * 1000).toISOString(),
|
|
118
|
+
status: STATUS[job.status] ?? String(job.status),
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
export async function createJob(c, escrow, input) {
|
|
122
|
+
await checkChain(c);
|
|
123
|
+
const provider = checkAddress(input.provider, "the provider");
|
|
124
|
+
const evaluator = input.evaluator?.trim()
|
|
125
|
+
? checkAddress(input.evaluator, "the evaluator")
|
|
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");
|
|
132
|
+
if (!(input.hoursUntilDeadline >= 1 && input.hoursUntilDeadline <= 24 * 365))
|
|
133
|
+
throw new ArlJobError("the deadline must be between 1 hour and 365 days away");
|
|
134
|
+
const { timestamp } = await c.publicClient.getBlock();
|
|
135
|
+
const expiredAt = timestamp + BigInt(Math.round(input.hoursUntilDeadline * 3600));
|
|
136
|
+
const { request } = await c.publicClient.simulateContract({
|
|
137
|
+
address: escrow,
|
|
138
|
+
abi: jobsAbi,
|
|
139
|
+
functionName: "createJob",
|
|
140
|
+
args: [
|
|
141
|
+
provider,
|
|
142
|
+
evaluator,
|
|
143
|
+
expiredAt,
|
|
144
|
+
input.description,
|
|
145
|
+
"0x0000000000000000000000000000000000000000",
|
|
146
|
+
],
|
|
147
|
+
account: sender(c),
|
|
148
|
+
});
|
|
149
|
+
const hash = await c.walletClient.writeContract(request);
|
|
150
|
+
const receipt = await c.publicClient.waitForTransactionReceipt({ hash });
|
|
151
|
+
if (receipt.status !== "success")
|
|
152
|
+
throw new ArlJobError(`transaction ${hash} reverted`);
|
|
153
|
+
const [created] = parseEventLogs({ abi: jobsAbi, eventName: "JobCreated", logs: receipt.logs });
|
|
154
|
+
if (!created)
|
|
155
|
+
throw new ArlJobError("the job was created but its id could not be read");
|
|
156
|
+
return { jobId: created.args.jobId.toString(), txHash: hash };
|
|
157
|
+
}
|
|
158
|
+
export async function setBudget(c, escrow, jobId, amount) {
|
|
159
|
+
await checkChain(c);
|
|
160
|
+
const value = parseAmount(amount, await decimalsOf(c, escrow));
|
|
161
|
+
return { txHash: await send(c, escrow, "setBudget", [jobId, value, "0x"]) };
|
|
162
|
+
}
|
|
163
|
+
/** Funds the agreed budget, approving the escrow first when its allowance is too low. */
|
|
164
|
+
export async function fundJob(c, escrow, jobId) {
|
|
165
|
+
await checkChain(c);
|
|
166
|
+
const job = await c.publicClient.readContract({
|
|
167
|
+
address: escrow,
|
|
168
|
+
abi: jobsAbi,
|
|
169
|
+
functionName: "getJob",
|
|
170
|
+
args: [jobId],
|
|
171
|
+
});
|
|
172
|
+
if (job.budget === 0n)
|
|
173
|
+
throw new ArlJobError("no budget is set: use Set Budget first");
|
|
174
|
+
const token = await c.publicClient.readContract({
|
|
175
|
+
address: escrow,
|
|
176
|
+
abi: jobsAbi,
|
|
177
|
+
functionName: "paymentToken",
|
|
178
|
+
});
|
|
179
|
+
const me = sender(c);
|
|
180
|
+
const allowance = await c.publicClient.readContract({
|
|
181
|
+
address: token,
|
|
182
|
+
abi: erc20Abi,
|
|
183
|
+
functionName: "allowance",
|
|
184
|
+
args: [me, escrow],
|
|
185
|
+
});
|
|
186
|
+
let approveTxHash;
|
|
187
|
+
if (allowance < job.budget) {
|
|
188
|
+
const { request } = await c.publicClient.simulateContract({
|
|
189
|
+
address: token,
|
|
190
|
+
abi: erc20Abi,
|
|
191
|
+
functionName: "approve",
|
|
192
|
+
args: [escrow, job.budget],
|
|
193
|
+
account: me,
|
|
194
|
+
});
|
|
195
|
+
approveTxHash = await c.walletClient.writeContract(request);
|
|
196
|
+
await c.publicClient.waitForTransactionReceipt({ hash: approveTxHash });
|
|
197
|
+
}
|
|
198
|
+
const txHash = await send(c, escrow, "fund", [jobId, job.budget, "0x"]);
|
|
199
|
+
const decimals = await c.publicClient.readContract({
|
|
200
|
+
address: token,
|
|
201
|
+
abi: erc20Abi,
|
|
202
|
+
functionName: "decimals",
|
|
203
|
+
});
|
|
204
|
+
return {
|
|
205
|
+
txHash,
|
|
206
|
+
...(approveTxHash ? { approveTxHash } : {}),
|
|
207
|
+
budget: formatUnits(job.budget, decimals),
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
export async function submitWork(c, escrow, jobId, deliverable) {
|
|
211
|
+
await checkChain(c);
|
|
212
|
+
const value = toBytes32(deliverable);
|
|
213
|
+
return { txHash: await send(c, escrow, "submit", [jobId, value, "0x"]), deliverable: value };
|
|
214
|
+
}
|
|
215
|
+
export async function settleJob(c, escrow, jobId, outcome, reason) {
|
|
216
|
+
await checkChain(c);
|
|
217
|
+
if (outcome === "claimRefund")
|
|
218
|
+
return { txHash: await send(c, escrow, "claimRefund", [jobId]) };
|
|
219
|
+
return { txHash: await send(c, escrow, outcome, [jobId, toBytes32(reason || outcome), "0x"]) };
|
|
220
|
+
}
|