@shippedcalls/sdk 0.3.1 → 0.4.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/src/jobs.ts ADDED
@@ -0,0 +1,467 @@
1
+ import { getAddress, isAddress, parseAbi, zeroAddress, zeroHash, type Abi, type Account, type Address, type Hash, type Hex, type PublicClient, type TransactionReceipt } from "viem";
2
+ import { CHAIN_ID, COUNCIL, DEEDS, USDG } from "./chain.js";
3
+ import { CallsError, RECEIPT_UNKNOWN } from "./errors.js";
4
+ import type { Tx } from "./types.js";
5
+
6
+ // A job is a Shipped bond the worker opens and the client funds. The bond's paid side belongs to whoever opens it, so
7
+ // the worker has to; the milestone carries a tag with the agreed amount, so anyone can tell a job from a bond and see
8
+ // what it is meant to hold. The worker writes every term, which is why `check` exists and `fund` refuses to pay into
9
+ // anything it fails.
10
+
11
+ export const USDG_DECIMALS = 6;
12
+ export const MAX_TITLE = 96;
13
+ export const MAX_MILESTONE = 2_048;
14
+ export const MIN_LEAD = 600;
15
+ export const MIN_WINDOW = 3_600;
16
+ export const MAX_WINDOW = 60 * 86_400;
17
+ export const DEFAULT_REVIEW_WINDOW = 3 * 86_400;
18
+ /** The council makes three model calls a case, so a job it reviews pays for them. */
19
+ export const COUNCIL_MIN_FEE = 250_000n;
20
+ /** The registry pays a reviewer at most a tenth of what the job holds. */
21
+ export const MAX_REVIEWER_SHARE_DIVISOR = 10n;
22
+ /** The most one `fund` or `open` may lock unless the caller raises it, in USDG units. */
23
+ export const DEFAULT_MAX_JOB_FUND = 25_000_000n;
24
+
25
+ const LEAD_SLACK = 60;
26
+ const BPS = 10_000;
27
+ const STATUS_OPEN = 1;
28
+ const STATUS_SETTLED = 4;
29
+ const ERC721_TRANSFER = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef";
30
+ const TAG = /\n\n\[shipped-job:1 amount=(\d+) bond=(\d+)\]$/;
31
+
32
+ export const deedsAbi = parseAbi([
33
+ "struct Terms { string title; string milestone; address project; uint8 projectKind; address asset; uint64 deadline; address verifier; address backupVerifier; address appealPanel; address check; bytes checkData; address refundTo; uint16 defaultRemainderBps; uint16 refundCapBps; bool allowPartial; uint32 verifierGrace; uint32 backupGrace; uint32 appealWindow; uint32 panelWindow; uint128 appealBond; uint128 verifierFee; address[] refundExcluded; }",
34
+ "struct Deed { address creator; uint8 status; uint8 ruling; uint16 remainderBps; uint16 feeBps; bool overturned; uint64 createdAt; uint64 ruledAt; uint64 appealedAt; uint64 settledAt; uint64 checkMetAt; uint64 windowEnd; address ruledBy; address appellant; uint256 balance; Terms terms; }",
35
+ "function create(Terms t, uint256 deposit) returns (uint256 deedId)",
36
+ "function fund(uint256 deedId, uint256 amount)",
37
+ "function postEvidence(uint256 deedId, string uri, bytes32 contentHash)",
38
+ "function rule(uint256 deedId, uint16 remainderBps, string reason)",
39
+ "function concede(uint256 deedId, string reason)",
40
+ "function settleDefault(uint256 deedId)",
41
+ "function withdrawFor(address account, address asset) returns (uint256)",
42
+ "function getDeed(uint256 deedId) view returns (Deed)",
43
+ "function owed(address account, address asset) view returns (uint256)",
44
+ "function timeline(uint256 deedId) view returns (uint64 deadline, uint64 verifierEnd, uint64 backupEnd, uint64 defaultAt, uint64 appealEnd, uint64 panelEnd)",
45
+ "error AssetNotAllowed()",
46
+ "error CreationIsPaused()",
47
+ "error InvalidDeadline()",
48
+ "error InvalidEvidence()",
49
+ "error InvalidMilestone()",
50
+ "error InvalidRefund()",
51
+ "error InvalidSplit()",
52
+ "error InvalidTitle()",
53
+ "error InvalidVerifier()",
54
+ "error InvalidWindow()",
55
+ "error NotCreator()",
56
+ "error NotOpen()",
57
+ "error NotPoster()",
58
+ "error NotVerifier()",
59
+ "error NothingOwed()",
60
+ "error TooEarly()",
61
+ "error TransferMismatch()",
62
+ "error UnknownDeed()",
63
+ "error WindowClosed()",
64
+ ]);
65
+
66
+ const erc20Abi = parseAbi([
67
+ "function balanceOf(address) view returns (uint256)",
68
+ "function allowance(address,address) view returns (uint256)",
69
+ "function approve(address,uint256) returns (bool)",
70
+ ]);
71
+
72
+ export interface JobTerms {
73
+ title: string;
74
+ milestone: string;
75
+ project: Address;
76
+ projectKind: number;
77
+ asset: Address;
78
+ deadline: bigint;
79
+ verifier: Address;
80
+ backupVerifier: Address;
81
+ appealPanel: Address;
82
+ check: Address;
83
+ checkData: Hex;
84
+ refundTo: Address;
85
+ defaultRemainderBps: number;
86
+ refundCapBps: number;
87
+ allowPartial: boolean;
88
+ verifierGrace: number;
89
+ backupGrace: number;
90
+ appealWindow: number;
91
+ panelWindow: number;
92
+ appealBond: bigint;
93
+ verifierFee: bigint;
94
+ refundExcluded: readonly Address[];
95
+ }
96
+
97
+ /** What the registry returns for a deed. */
98
+ export interface ChainDeed {
99
+ creator: Address;
100
+ status: number;
101
+ ruling: number;
102
+ remainderBps: number;
103
+ balance: bigint;
104
+ terms: JobTerms;
105
+ }
106
+
107
+ export interface OpenJobInput {
108
+ title: string;
109
+ /** What will be delivered and how anyone can tell. Stored on chain; the reviewer judges against it. */
110
+ brief: string;
111
+ /** The wallet that will fund the job and gets the money back if it is rejected or runs out. */
112
+ client: string;
113
+ /** What the client locks, in USDG units (6 decimals). */
114
+ amount: bigint;
115
+ /** When the work is due, unix seconds. */
116
+ deadline: number;
117
+ /** Who accepts or rejects the work: an address, or `council` for Shipped's three-model council. */
118
+ reviewer: string;
119
+ /** Seconds the reviewer has after the deadline. Three days by default. */
120
+ reviewWindow?: number;
121
+ /** Paid to the reviewer from the job when its ruling stands, USDG units. 0.25 USDG at least for the council. */
122
+ reviewerFee?: bigint;
123
+ /** What the worker locks on its own side. It is lost to the client if the job fails. */
124
+ workerBond?: bigint;
125
+ }
126
+
127
+ /** What the client agreed to, for `check` and `fund` to compare against what the worker actually opened. */
128
+ export interface JobAgreement {
129
+ amount: bigint;
130
+ /** Every reviewer the client accepts: addresses, or `council`. */
131
+ reviewers: readonly string[];
132
+ worker?: string;
133
+ /** The client. The connected wallet by default. */
134
+ client?: string;
135
+ /** The latest deadline the client accepts, unix seconds. */
136
+ notAfter?: number;
137
+ /** The largest reviewer fee the client accepts, USDG units. A tenth of the amount by default. */
138
+ maxReviewerFee?: bigint;
139
+ /** The least the worker must have locked, USDG units. */
140
+ minWorkerBond?: bigint;
141
+ }
142
+
143
+ export interface JobProblem {
144
+ code: string;
145
+ message: string;
146
+ }
147
+
148
+ export type JobState = "awaiting_funds" | "in_progress" | "in_review" | "refundable" | "ruled" | "paid" | "partly_paid" | "refunded";
149
+
150
+ export interface Job {
151
+ id: string;
152
+ number: number;
153
+ url: string | null;
154
+ title: string;
155
+ brief: string;
156
+ worker: Address;
157
+ client: Address;
158
+ reviewer: Address;
159
+ asset: Address;
160
+ amount: string;
161
+ workerBond: string;
162
+ reviewerFee: string;
163
+ escrow: string;
164
+ funded: boolean;
165
+ deadline: number;
166
+ /** When anyone can refund the client if the reviewer has stayed silent. */
167
+ refundableAt: number;
168
+ state: JobState;
169
+ }
170
+
171
+ export interface JobTx {
172
+ id: string;
173
+ tx: Tx;
174
+ }
175
+
176
+ const addressOf = (value: unknown, what: string): Address => {
177
+ if (typeof value === "string" && isAddress(value, { strict: false })) return getAddress(value);
178
+ throw new CallsError(`Use an address for the ${what}: 0x and 40 hex characters.`, "bad_address");
179
+ };
180
+
181
+ const reviewerOf = (value: unknown): Address => (value === "council" ? COUNCIL : addressOf(value, "reviewer"));
182
+ const utf8Length = (text: string) => new TextEncoder().encode(text).length;
183
+ const same = (a: string, b: string) => a.toLowerCase() === b.toLowerCase();
184
+ const usdg = (units: bigint) => `${Number(units) / 10 ** USDG_DECIMALS} USDG`;
185
+
186
+ /** A decimal USDG string as units. */
187
+ export function usdgToUnits(amount: string, what = "amount"): bigint {
188
+ if (!/^\d*\.?\d{1,6}$/.test(amount) || !/\d/.test(amount)) throw new CallsError(`The ${what} has to be a USDG amount with up to six decimals, such as 25 or 0.25.`, "bad_amount");
189
+ const [whole = "", fraction = ""] = amount.split(".");
190
+ return BigInt(whole || "0") * 10n ** BigInt(USDG_DECIMALS) + BigInt(fraction.padEnd(USDG_DECIMALS, "0"));
191
+ }
192
+
193
+ export const jobMilestone = (brief: string, amount: bigint, bond: bigint) => `${brief.trim()}\n\n[shipped-job:1 amount=${amount} bond=${bond}]`;
194
+
195
+ /** The brief, amount and worker bond from a milestone, or null when the milestone is not a job's. */
196
+ export function readJobTag(milestone: string): { brief: string; amount: bigint; bond: bigint } | null {
197
+ const match = TAG.exec(milestone);
198
+ if (!match) return null;
199
+ return { brief: milestone.slice(0, match.index), amount: BigInt(match[1]!), bond: BigInt(match[2]!) };
200
+ }
201
+
202
+ /** The registry's bond number on Shipped's site. */
203
+ export const bondNumberOf = (id: bigint | number, chainId = CHAIN_ID) => Number(id) - (chainId === CHAIN_ID ? 1 : 0);
204
+
205
+ /** The terms a job opens with. Refuses anything the registry would, before anything is sent. */
206
+ export function jobTerms(input: OpenJobInput, { worker, now }: { worker: string; now: number }): JobTerms {
207
+ const title = input.title?.trim() ?? "";
208
+ if (title.length === 0 || utf8Length(title) > MAX_TITLE) throw new CallsError(`A job's title is 1 to ${MAX_TITLE} bytes.`, "bad_title");
209
+ if (typeof input.amount !== "bigint" || input.amount <= 0n) throw new CallsError("A job's amount is USDG units, as a bigint above zero.", "bad_amount");
210
+ const bond = input.workerBond ?? 0n;
211
+ if (bond < 0n) throw new CallsError("The worker's bond cannot be negative.", "bad_amount");
212
+ if (!input.brief?.trim()) throw new CallsError("Say what will be delivered and how anyone can tell.", "bad_brief");
213
+ const milestone = jobMilestone(input.brief, input.amount, bond);
214
+ if (utf8Length(milestone) > MAX_MILESTONE) throw new CallsError(`The brief is too long: the registry holds ${MAX_MILESTONE} bytes with the job's tag.`, "bad_brief");
215
+ if (!Number.isInteger(input.deadline) || input.deadline < now + MIN_LEAD + LEAD_SLACK) throw new CallsError("Set the deadline at least 11 minutes from now, in unix seconds.", "bad_deadline");
216
+
217
+ const client = addressOf(input.client, "client");
218
+ const reviewer = reviewerOf(input.reviewer);
219
+ if (same(client, worker)) throw new CallsError("The client has to be a different wallet from the worker.", "client_is_worker");
220
+ if (same(reviewer, worker)) throw new CallsError("The reviewer has to be a different wallet from the worker.", "reviewer_is_worker");
221
+ if (same(reviewer, client)) throw new CallsError("The reviewer has to be a different wallet from the client, who gets the money back on a rejection.", "reviewer_is_client");
222
+
223
+ const reviewWindow = input.reviewWindow ?? DEFAULT_REVIEW_WINDOW;
224
+ if (!Number.isInteger(reviewWindow) || reviewWindow < MIN_WINDOW || reviewWindow > MAX_WINDOW) throw new CallsError("The review window is between one hour and 60 days, in seconds.", "bad_window");
225
+
226
+ const isCouncil = same(reviewer, COUNCIL);
227
+ const fee = input.reviewerFee ?? (isCouncil ? COUNCIL_MIN_FEE : 0n);
228
+ if (fee < 0n) throw new CallsError("The reviewer's fee cannot be negative.", "bad_amount");
229
+ if (isCouncil && fee < COUNCIL_MIN_FEE) throw new CallsError(`The council's fee is at least ${usdg(COUNCIL_MIN_FEE)}.`, "fee_too_low");
230
+ if (fee * MAX_REVIEWER_SHARE_DIVISOR > input.amount + bond) throw new CallsError(`The registry pays a reviewer at most a tenth of the job, so a ${usdg(fee)} fee needs a job of ${usdg(fee * MAX_REVIEWER_SHARE_DIVISOR)} or more.`, "fee_over_cap");
231
+
232
+ return {
233
+ title,
234
+ milestone,
235
+ project: zeroAddress,
236
+ projectKind: 0,
237
+ asset: USDG,
238
+ deadline: BigInt(input.deadline),
239
+ verifier: reviewer,
240
+ backupVerifier: zeroAddress,
241
+ appealPanel: zeroAddress,
242
+ check: zeroAddress,
243
+ checkData: "0x",
244
+ refundTo: client,
245
+ defaultRemainderBps: 0,
246
+ refundCapBps: 0,
247
+ allowPartial: false,
248
+ verifierGrace: reviewWindow,
249
+ backupGrace: 0,
250
+ appealWindow: 0,
251
+ panelWindow: 0,
252
+ appealBond: 0n,
253
+ verifierFee: fee,
254
+ refundExcluded: [],
255
+ };
256
+ }
257
+
258
+ /** Every way a job differs from what the client agreed to. An empty list means it is safe to fund. */
259
+ export function checkJob(deed: ChainDeed, agreement: JobAgreement, { client, now }: { client: string; now: number }): JobProblem[] {
260
+ const problems: JobProblem[] = [];
261
+ const add = (code: string, message: string) => problems.push({ code, message });
262
+ const t = deed.terms;
263
+ const tag = readJobTag(t.milestone);
264
+ if (!tag) return [{ code: "not_a_job", message: "This bond is not a job: its milestone carries no job tag." }];
265
+ if (deed.status !== STATUS_OPEN) add("not_open", "This job is no longer open.");
266
+
267
+ const allowed = agreement.reviewers.map(reviewerOf);
268
+ if (allowed.length === 0) add("no_reviewers", "Name at least one reviewer you accept.");
269
+ const accepted = (address: Address) => allowed.some((reviewer) => same(reviewer, address));
270
+ if (t.verifier === zeroAddress || !accepted(t.verifier)) add("reviewer_not_agreed", `The reviewer is ${t.verifier}, which is not one you accept.`);
271
+ if (t.backupVerifier !== zeroAddress && !accepted(t.backupVerifier)) add("backup_not_agreed", `The job names a backup reviewer you did not accept: ${t.backupVerifier}.`);
272
+ if (t.appealPanel !== zeroAddress && !accepted(t.appealPanel)) add("panel_not_agreed", `The job names an appeal panel you did not accept: ${t.appealPanel}.`);
273
+
274
+ if (!same(t.refundTo, client)) add("refund_elsewhere", `A failed job pays ${t.refundTo}, not you.`);
275
+ if (agreement.worker && !same(deed.creator, addressOf(agreement.worker, "worker"))) add("wrong_worker", `The job was opened by ${deed.creator}, not the worker you agreed with.`);
276
+ if (t.defaultRemainderBps !== 0) add("pays_on_silence", "The job pays the worker if the reviewer stays silent. It has to refund you.");
277
+ if (t.check !== zeroAddress) add("has_check", "The job can be released by an on-chain check instead of the reviewer.");
278
+ if (t.allowPartial) add("allows_partial", "The reviewer can split this job between you and the worker.");
279
+ if (!same(t.asset, USDG)) add("wrong_asset", "The job is not held in USDG.");
280
+
281
+ if (tag.amount !== agreement.amount) add("wrong_amount", `The job asks for ${usdg(tag.amount)}, not the ${usdg(agreement.amount)} you agreed.`);
282
+ const minBond = agreement.minWorkerBond ?? 0n;
283
+ if (tag.bond < minBond) add("bond_too_small", `The worker's bond is ${usdg(tag.bond)}, under the ${usdg(minBond)} you asked for.`);
284
+ if (deed.balance < tag.bond) add("bond_missing", "The worker has not locked the bond the job names.");
285
+ if (deed.balance >= tag.amount + tag.bond) add("already_funded", "This job already holds its full amount.");
286
+
287
+ const maxFee = agreement.maxReviewerFee ?? agreement.amount / MAX_REVIEWER_SHARE_DIVISOR;
288
+ if (t.verifierFee > maxFee) add("fee_too_high", `The reviewer's fee is ${usdg(t.verifierFee)}, over the ${usdg(maxFee)} you accept.`);
289
+
290
+ const deadline = Number(t.deadline);
291
+ if (deadline <= now + MIN_LEAD) add("deadline_too_soon", "The deadline is too close for the work to be done.");
292
+ if (agreement.notAfter != null && deadline > agreement.notAfter) add("deadline_too_late", "The deadline is later than you agreed.");
293
+ return problems;
294
+ }
295
+
296
+ export function jobStateOf(deed: ChainDeed, refundableAt: number, now: number): JobState {
297
+ if (deed.status === STATUS_SETTLED) return deed.remainderBps === BPS ? "paid" : deed.remainderBps === 0 ? "refunded" : "partly_paid";
298
+ if (deed.status !== STATUS_OPEN) return "ruled";
299
+ const tag = readJobTag(deed.terms.milestone);
300
+ if (now > refundableAt) return "refundable";
301
+ if (tag && deed.balance < tag.amount + tag.bond) return "awaiting_funds";
302
+ return now <= Number(deed.terms.deadline) ? "in_progress" : "in_review";
303
+ }
304
+
305
+ export interface JobsDeps {
306
+ reads: PublicClient;
307
+ chainId: number;
308
+ send: (params: { address: Address; abi: Abi; functionName: string; args?: unknown[] }) => Promise<TransactionReceipt>;
309
+ guarded: <T>(work: () => Promise<T>) => Promise<T>;
310
+ wallet: () => Account;
311
+ toTx: (receipt: TransactionReceipt) => Tx;
312
+ maxFund: bigint;
313
+ registry?: Address;
314
+ }
315
+
316
+ const idOf = (value: unknown): bigint => {
317
+ if ((typeof value === "bigint" || typeof value === "number" || (typeof value === "string" && /^\d+$/.test(value))) && BigInt(value) > 0n) return BigInt(value);
318
+ throw new CallsError("A job id is the registry's deed id: a positive whole number.", "bad_job_id");
319
+ };
320
+
321
+ export function createJobs({ reads, chainId, send, guarded, wallet, toTx, maxFund, registry = DEEDS }: JobsDeps) {
322
+ const deedAt = (id: bigint) => reads.readContract({ address: registry, abi: deedsAbi as Abi, functionName: "getDeed", args: [id] } as never) as Promise<ChainDeed>;
323
+ const timeOnChain = async () => Number((await reads.getBlock({ blockTag: "latest" })).timestamp);
324
+ const write = (functionName: string, args: unknown[]) => send({ address: registry, abi: deedsAbi as Abi, functionName, args });
325
+
326
+ async function jobAt(id: bigint): Promise<{ deed: ChainDeed; tag: NonNullable<ReturnType<typeof readJobTag>> }> {
327
+ const deed = await deedAt(id);
328
+ const tag = readJobTag(deed.terms.milestone);
329
+ if (!tag) throw new CallsError("That bond is not a job.", "not_a_job");
330
+ return { deed, tag };
331
+ }
332
+
333
+ async function approveUpTo(amount: bigint) {
334
+ const owner = wallet().address;
335
+ const [balance, allowance] = await Promise.all([
336
+ reads.readContract({ address: USDG, abi: erc20Abi as Abi, functionName: "balanceOf", args: [owner] } as never) as Promise<bigint>,
337
+ reads.readContract({ address: USDG, abi: erc20Abi as Abi, functionName: "allowance", args: [owner, registry] } as never) as Promise<bigint>,
338
+ ]);
339
+ if (balance < amount) throw new CallsError(`This wallet holds ${usdg(balance)}, and this needs ${usdg(amount)}.`, "insufficient_usdg");
340
+ if (allowance < amount) await send({ address: USDG, abi: erc20Abi as Abi, functionName: "approve", args: [registry, amount] });
341
+ }
342
+
343
+ const cap = (amount: bigint, limit: bigint) => {
344
+ if (amount > limit) throw new CallsError(`This would lock ${usdg(amount)}, over the ${usdg(limit)} limit. Raise maxFund only on your operator's word.`, "over_cap");
345
+ };
346
+
347
+ return {
348
+ /** One job as the chain has it. */
349
+ get: (jobId: unknown): Promise<Job> =>
350
+ guarded(async () => {
351
+ const id = idOf(jobId);
352
+ const [{ deed, tag }, timeline, now] = await Promise.all([
353
+ jobAt(id),
354
+ reads.readContract({ address: registry, abi: deedsAbi as Abi, functionName: "timeline", args: [id] } as never) as Promise<readonly bigint[]>,
355
+ timeOnChain(),
356
+ ]);
357
+ const refundableAt = Number(timeline[3]);
358
+ const number = bondNumberOf(id, chainId);
359
+ return {
360
+ id: id.toString(),
361
+ number,
362
+ url: chainId === CHAIN_ID ? `https://app.shipped.bond/bonds/${number}` : null,
363
+ title: deed.terms.title,
364
+ brief: tag.brief,
365
+ worker: deed.creator,
366
+ client: deed.terms.refundTo,
367
+ reviewer: deed.terms.verifier,
368
+ asset: deed.terms.asset,
369
+ amount: tag.amount.toString(),
370
+ workerBond: tag.bond.toString(),
371
+ reviewerFee: deed.terms.verifierFee.toString(),
372
+ escrow: deed.balance.toString(),
373
+ funded: deed.balance >= tag.amount + tag.bond,
374
+ deadline: Number(deed.terms.deadline),
375
+ refundableAt,
376
+ state: jobStateOf(deed, refundableAt, now),
377
+ };
378
+ }),
379
+
380
+ /** Worker: opens the job and locks its own bond, if any. Hand the id to the client to fund. */
381
+ open: (input: OpenJobInput, { maxFund: limit = maxFund }: { maxFund?: bigint } = {}): Promise<JobTx> =>
382
+ guarded(async () => {
383
+ const worker = wallet().address;
384
+ const terms = jobTerms(input, { worker, now: await timeOnChain() });
385
+ const bond = input.workerBond ?? 0n;
386
+ cap(bond, limit);
387
+ if (bond > 0n) await approveUpTo(bond);
388
+ const receipt = await write("create", [terms, bond]);
389
+ // The registry mints the paid side as token id * 2, from the zero address, in the same transaction.
390
+ const minted = receipt.logs.find((log) => same(log.address, registry) && log.topics[0] === ERC721_TRANSFER && BigInt(log.topics[1] ?? 1) === 0n);
391
+ if (!minted?.topics[3]) throw new CallsError(`Transaction ${receipt.transactionHash} landed but its job id could not be read.`, RECEIPT_UNKNOWN);
392
+ return { id: (BigInt(minted.topics[3]) / 2n).toString(), tx: toTx(receipt) };
393
+ }),
394
+
395
+ /** Client: every way the job differs from what you agreed to. Spends nothing. */
396
+ check: (jobId: unknown, agreement: JobAgreement): Promise<{ ok: boolean; problems: JobProblem[] }> =>
397
+ guarded(async () => {
398
+ const client = agreement.client ? addressOf(agreement.client, "client") : wallet().address;
399
+ const [{ deed }, now] = await Promise.all([jobAt(idOf(jobId)), timeOnChain()]);
400
+ const problems = checkJob(deed, agreement, { client, now });
401
+ return { ok: problems.length === 0, problems };
402
+ }),
403
+
404
+ /** Client: locks the agreed amount, and only if the job passes `check`. */
405
+ fund: (jobId: unknown, agreement: JobAgreement, { maxFund: limit = maxFund }: { maxFund?: bigint } = {}): Promise<JobTx & { amount: string }> =>
406
+ guarded(async () => {
407
+ const id = idOf(jobId);
408
+ const client = wallet().address;
409
+ const [{ deed, tag }, now] = await Promise.all([jobAt(id), timeOnChain()]);
410
+ const problems = checkJob(deed, { ...agreement, client }, { client, now });
411
+ if (problems.length > 0) throw new CallsError(`Not funded. ${problems.map((p) => p.message).join(" ")}`, problems[0]!.code);
412
+ const amount = tag.amount + tag.bond - deed.balance;
413
+ cap(amount, limit);
414
+ await approveUpTo(amount);
415
+ return { id: id.toString(), amount: amount.toString(), tx: toTx(await write("fund", [id, amount])) };
416
+ }),
417
+
418
+ /** Worker or reviewer: points at what was delivered. */
419
+ evidence: (jobId: unknown, uri: string, contentHash: Hash = zeroHash): Promise<JobTx> =>
420
+ guarded(async () => {
421
+ const id = idOf(jobId);
422
+ return { id: id.toString(), tx: toTx(await write("postEvidence", [id, uri, contentHash])) };
423
+ }),
424
+
425
+ /** Reviewer: the work was delivered. Pays the worker at once. */
426
+ accept: (jobId: unknown, reason = ""): Promise<JobTx> =>
427
+ guarded(async () => {
428
+ const id = idOf(jobId);
429
+ return { id: id.toString(), tx: toTx(await write("rule", [id, BPS, reason])) };
430
+ }),
431
+
432
+ /** Reviewer: the work was not delivered. Opens at the deadline; refunds the client at once. */
433
+ reject: (jobId: unknown, reason: string): Promise<JobTx> =>
434
+ guarded(async () => {
435
+ const id = idOf(jobId);
436
+ return { id: id.toString(), tx: toTx(await write("rule", [id, 0, reason])) };
437
+ }),
438
+
439
+ /** Worker: gives up. The client gets everything the job holds, at once. */
440
+ concede: (jobId: unknown, reason: string): Promise<JobTx> =>
441
+ guarded(async () => {
442
+ const id = idOf(jobId);
443
+ return { id: id.toString(), tx: toTx(await write("concede", [id, reason])) };
444
+ }),
445
+
446
+ /** Anyone: the reviewer stayed silent past its window, so the client is refunded. */
447
+ refund: (jobId: unknown): Promise<JobTx> =>
448
+ guarded(async () => {
449
+ const id = idOf(jobId);
450
+ return { id: id.toString(), tx: toTx(await write("settleDefault", [id])) };
451
+ }),
452
+
453
+ /** What a wallet can collect in USDG across settled jobs and bonds. */
454
+ owed: (address?: string): Promise<string> =>
455
+ guarded(async () => {
456
+ const who = address ? addressOf(address, "wallet") : wallet().address;
457
+ const amount = (await reads.readContract({ address: registry, abi: deedsAbi as Abi, functionName: "owed", args: [who, USDG] } as never)) as bigint;
458
+ return amount.toString();
459
+ }),
460
+
461
+ /** Sends this wallet what it can collect. */
462
+ collect: (): Promise<{ tx: Tx }> =>
463
+ guarded(async () => ({ tx: toTx(await write("withdrawFor", [wallet().address, USDG])) })),
464
+ };
465
+ }
466
+
467
+ export type JobsClient = ReturnType<typeof createJobs>;