@tetsuo-ai/marketplace-react 0.4.1 → 0.6.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 (84) hide show
  1. package/CHANGELOG.md +65 -0
  2. package/README.md +97 -51
  3. package/dist/chunk-7NKRSPPN.js +227 -0
  4. package/dist/chunk-7NKRSPPN.js.map +1 -0
  5. package/dist/{chunk-JVXGNW3Q.js → chunk-CDDHUFMG.js} +6 -5
  6. package/dist/chunk-CDDHUFMG.js.map +1 -0
  7. package/dist/chunk-FIDFPM5A.cjs +40 -0
  8. package/dist/chunk-FIDFPM5A.cjs.map +1 -0
  9. package/dist/chunk-IJKWKY4H.cjs +1370 -0
  10. package/dist/chunk-IJKWKY4H.cjs.map +1 -0
  11. package/dist/chunk-JTSG5FGC.cjs +397 -0
  12. package/dist/chunk-JTSG5FGC.cjs.map +1 -0
  13. package/dist/chunk-ONC6L3IX.cjs +97 -0
  14. package/dist/chunk-ONC6L3IX.cjs.map +1 -0
  15. package/dist/chunk-R76EUYDI.cjs +233 -0
  16. package/dist/chunk-R76EUYDI.cjs.map +1 -0
  17. package/dist/{chunk-XLA7DARS.js → chunk-RG5JZ6JL.js} +159 -36
  18. package/dist/chunk-RG5JZ6JL.js.map +1 -0
  19. package/dist/components/index.cjs +158 -1594
  20. package/dist/components/index.cjs.map +1 -1
  21. package/dist/components/index.d.cts +2 -2
  22. package/dist/components/index.d.ts +2 -2
  23. package/dist/components/index.js +2 -2
  24. package/dist/hooks/index.cjs +656 -509
  25. package/dist/hooks/index.cjs.map +1 -1
  26. package/dist/hooks/index.d.cts +63 -29
  27. package/dist/hooks/index.d.ts +63 -29
  28. package/dist/hooks/index.js +619 -196
  29. package/dist/hooks/index.js.map +1 -1
  30. package/dist/{index-CmVz0OOm.d.ts → index-BAyr1ODZ.d.ts} +28 -3
  31. package/dist/{index-DAZzhuO4.d.cts → index-C20NVU7_.d.cts} +28 -3
  32. package/dist/index.cjs +284 -1833
  33. package/dist/index.cjs.map +1 -1
  34. package/dist/index.d.cts +7 -8
  35. package/dist/index.d.ts +7 -8
  36. package/dist/index.js +64 -4
  37. package/dist/index.js.map +1 -1
  38. package/dist/signers/index.cjs +22 -161
  39. package/dist/signers/index.cjs.map +1 -1
  40. package/dist/signers/index.d.cts +16 -11
  41. package/dist/signers/index.d.ts +16 -11
  42. package/dist/signers/index.js +1 -1
  43. package/dist/testing/index.d.cts +1 -1
  44. package/dist/testing/index.d.ts +1 -1
  45. package/dist/theme/agenc-tailwind-preset.cjs +134 -108
  46. package/dist/{types-jvISR6bc.d.cts → types-B10rndEI.d.cts} +16 -7
  47. package/dist/{types-jvISR6bc.d.ts → types-B10rndEI.d.ts} +16 -7
  48. package/dist/{useAgentTrackRecord-DPt3SfYz.d.cts → useAgentTrackRecord-Ch7gHTFj.d.cts} +1 -1
  49. package/dist/{useAgentTrackRecord-DPt3SfYz.d.ts → useAgentTrackRecord-Ch7gHTFj.d.ts} +1 -1
  50. package/package.json +7 -4
  51. package/src/components/HireCheckoutModal.tsx +5 -2
  52. package/src/hooks/index.ts +1 -0
  53. package/src/hooks/internal.ts +178 -24
  54. package/src/hooks/useAgentTrackRecord.ts +5 -2
  55. package/src/hooks/useCompletionBond.ts +56 -21
  56. package/src/hooks/useDispute.ts +46 -9
  57. package/src/hooks/useHire.ts +113 -23
  58. package/src/hooks/useHumanlessHireFlow.ts +335 -115
  59. package/src/hooks/useListing.ts +2 -2
  60. package/src/hooks/useListings.ts +2 -2
  61. package/src/hooks/useRateHire.ts +32 -5
  62. package/src/hooks/useReferrerEarnings.ts +4 -1
  63. package/src/hooks/useSubmissionReview.ts +95 -32
  64. package/src/hooks/useTaskActivation.ts +51 -9
  65. package/src/hooks/useTaskGuarantee.ts +4 -1
  66. package/src/hooks/useTaskLifecycle.ts +104 -24
  67. package/src/hooks/useTaskStatus.ts +121 -26
  68. package/src/hooks/useTaskWork.ts +76 -12
  69. package/src/hooks/useWalletSigner.ts +11 -16
  70. package/src/index.ts +3 -0
  71. package/src/provider/AgencProvider.tsx +95 -3
  72. package/src/provider/referrer.ts +1 -1
  73. package/src/signers/README.md +13 -7
  74. package/src/signers/index.ts +6 -1
  75. package/src/signers/strings.ts +13 -1
  76. package/src/signers/types.ts +16 -5
  77. package/src/signers/wallet-account.ts +115 -29
  78. package/src/signers/wallet-adapter.ts +38 -4
  79. package/src/theme/agenc-tailwind-preset.cjs +134 -108
  80. package/src/types.ts +27 -1
  81. package/dist/chunk-JVXGNW3Q.js.map +0 -1
  82. package/dist/chunk-ON6XR4XO.js +0 -128
  83. package/dist/chunk-ON6XR4XO.js.map +0 -1
  84. package/dist/chunk-XLA7DARS.js.map +0 -1
@@ -1,18 +1,19 @@
1
1
  import { ReadTransportUnsupportedError } from '../chunk-AKPPKMQ2.js';
2
- import { useAgencContext, queryKeys, pdaKey, requireClient, resolveActivationModerationAccounts, mutationStatusOf, resolveReferrerArgs, withoutReferrerArgs, resolveHireListingModerationAccounts, signerAddress } from '../chunk-XLA7DARS.js';
3
- export { QUERY_KEY_ROOT, queryKeys, useHire, useTaskGuarantee, useWalletSigner } from '../chunk-XLA7DARS.js';
2
+ import { useAgencContext, queryKeys, pdaKey, requireClient, snapshotRecord, stabilizeSelectedTransactionSigner, snapshotFixedBytes32, resolveActivationModerationAccounts, mutationStatusOf, withoutReferrerArgs, resolveReferrerArgs, snapshotOptionalFixedBytes, snapshotRecordArray } from '../chunk-RG5JZ6JL.js';
3
+ export { QUERY_KEY_ROOT, queryKeys, useHire, useTaskGuarantee, useWalletSigner } from '../chunk-RG5JZ6JL.js';
4
4
  import { t } from '../chunk-H6PJIDQR.js';
5
5
  import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
6
6
  import { useState, useMemo, useCallback, useRef, useEffect } from 'react';
7
- import { TaskStatus, facade, findTaskPda } from '@tetsuo-ai/marketplace-sdk';
7
+ import { TaskStatus, facade, hireAndActivate, resumeHireAndActivate, HireAndActivateError, HireAndActivateFinalizedFailure, snapshotStructuredClone } from '@tetsuo-ai/marketplace-sdk';
8
+ import { address } from '@solana/kit';
8
9
 
9
10
  var DEFAULT_PAGE_SIZE = 12;
10
11
  function useListings(filter, options) {
11
- const { read } = useAgencContext();
12
+ const { read, cacheNamespace } = useAgencContext();
12
13
  const pageSize = options?.pageSize ?? DEFAULT_PAGE_SIZE;
13
14
  const enabled = options?.enabled ?? true;
14
15
  const query = useQuery({
15
- queryKey: queryKeys.listings(filter),
16
+ queryKey: queryKeys.listings(filter, cacheNamespace),
16
17
  queryFn: () => read.listActiveListings(filter),
17
18
  enabled
18
19
  });
@@ -41,10 +42,10 @@ function useListings(filter, options) {
41
42
  };
42
43
  }
43
44
  function useListing(pda, options) {
44
- const { read } = useAgencContext();
45
+ const { read, cacheNamespace } = useAgencContext();
45
46
  const enabled = (options?.enabled ?? true) && Boolean(pda);
46
47
  const query = useQuery({
47
- queryKey: queryKeys.listing(pda ? pdaKey(pda) : ""),
48
+ queryKey: queryKeys.listing(pda ? pdaKey(pda) : "", cacheNamespace),
48
49
  enabled,
49
50
  queryFn: async () => {
50
51
  const result = await read.getListing(pda);
@@ -100,10 +101,13 @@ function projectTrackRecord(raw) {
100
101
  };
101
102
  }
102
103
  function useAgentTrackRecord(agentPda, options) {
103
- const { read } = useAgencContext();
104
+ const { read, cacheNamespace } = useAgencContext();
104
105
  const enabled = (options?.enabled ?? true) && Boolean(agentPda);
105
106
  const query = useQuery({
106
- queryKey: queryKeys.agentTrackRecord(agentPda ? pdaKey(agentPda) : ""),
107
+ queryKey: queryKeys.agentTrackRecord(
108
+ agentPda ? pdaKey(agentPda) : "",
109
+ cacheNamespace
110
+ ),
107
111
  enabled,
108
112
  queryFn: async () => {
109
113
  const raw = await read.agentTrackRecord(agentPda);
@@ -127,17 +131,32 @@ var TERMINAL_STATUSES = /* @__PURE__ */ new Set([
127
131
  TaskStatus.Cancelled,
128
132
  TaskStatus.RejectFrozen
129
133
  ]);
134
+ var DEFAULT_MAX_EVENTS = 256;
135
+ var MAX_POLL_INTERVAL_MS = 2147483647;
130
136
  function hasResult(task) {
131
137
  return task !== null && task.result.length > 0 && task.result.some((b) => b !== 0);
132
138
  }
133
139
  function useTaskStatus(taskPda, options) {
134
- useAgencContext();
140
+ const ctx = useAgencContext();
135
141
  const reader = options?.taskReader;
136
142
  const enabled = (options?.enabled ?? true) && Boolean(taskPda) && Boolean(reader);
137
143
  const pollIntervalMs = options?.pollIntervalMs ?? 2e3;
138
- const [events, setEvents] = useState([]);
144
+ const maxEvents = options?.maxEvents ?? DEFAULT_MAX_EVENTS;
145
+ if (!Number.isSafeInteger(pollIntervalMs) || pollIntervalMs < 0 || pollIntervalMs > MAX_POLL_INTERVAL_MS) {
146
+ throw new RangeError(
147
+ `useTaskStatus: pollIntervalMs must be a non-negative integer no greater than ${MAX_POLL_INTERVAL_MS} (got ${pollIntervalMs})`
148
+ );
149
+ }
150
+ if (!Number.isSafeInteger(maxEvents) || maxEvents < 0) {
151
+ throw new RangeError(
152
+ `useTaskStatus: maxEvents must be a non-negative safe integer (got ${maxEvents})`
153
+ );
154
+ }
155
+ const taskIdentity = taskPda ? pdaKey(taskPda) : "";
156
+ const [eventState, setEventState] = useState(() => ({ taskIdentity, events: [] }));
157
+ const events = eventState.taskIdentity === taskIdentity ? eventState.events : [];
139
158
  const query = useQuery({
140
- queryKey: queryKeys.taskStatus(taskPda ? pdaKey(taskPda) : ""),
159
+ queryKey: queryKeys.taskStatus(taskIdentity, ctx.cacheNamespace),
141
160
  enabled,
142
161
  queryFn: () => reader(taskPda),
143
162
  // Poll until terminal / target reached; then stop (return `false`).
@@ -155,22 +174,52 @@ function useTaskStatus(taskPda, options) {
155
174
  refetchRef.current = query.refetch;
156
175
  const eventsSource = options?.events;
157
176
  useEffect(() => {
158
- if (!eventsSource) return;
177
+ setEventState({ taskIdentity, events: [] });
178
+ if (!enabled || !eventsSource || !taskPda) return;
179
+ const controller = new AbortController();
180
+ const aborted = /* @__PURE__ */ Symbol("aborted");
181
+ const abortPromise = new Promise((resolve) => {
182
+ controller.signal.addEventListener("abort", () => resolve(aborted), {
183
+ once: true
184
+ });
185
+ });
186
+ let iterator = null;
159
187
  let cancelled = false;
160
- (async () => {
188
+ let finished = false;
189
+ void (async () => {
161
190
  try {
162
- for await (const ev of eventsSource) {
191
+ const iterable = typeof eventsSource === "function" ? eventsSource({ signal: controller.signal, taskPda }) : eventsSource;
192
+ iterator = iterable[Symbol.asyncIterator]();
193
+ while (!cancelled) {
194
+ const next = await Promise.race([iterator.next(), abortPromise]);
195
+ if (next === aborted) break;
163
196
  if (cancelled) break;
164
- setEvents((prev) => [...prev, ev]);
197
+ if (next.done) {
198
+ finished = true;
199
+ break;
200
+ }
201
+ setEventState((prev) => ({
202
+ taskIdentity,
203
+ events: prev.taskIdentity === taskIdentity ? maxEvents === 0 ? [] : [...prev.events, next.value].slice(-maxEvents) : maxEvents === 0 ? [] : [next.value]
204
+ }));
165
205
  void refetchRef.current();
166
206
  }
167
207
  } catch {
208
+ } finally {
209
+ finished = true;
168
210
  }
169
211
  })();
170
212
  return () => {
171
213
  cancelled = true;
214
+ controller.abort();
215
+ if (!finished && iterator?.return) {
216
+ try {
217
+ void Promise.resolve(iterator.return()).catch(() => void 0);
218
+ } catch {
219
+ }
220
+ }
172
221
  };
173
- }, [eventsSource]);
222
+ }, [enabled, eventsSource, maxEvents, taskIdentity, taskPda]);
174
223
  const task = query.data ?? null;
175
224
  return {
176
225
  task,
@@ -190,62 +239,106 @@ function statusOf(m) {
190
239
  }
191
240
  function useSubmissionReview(taskPda) {
192
241
  const ctx = useAgencContext();
242
+ const lastAction = useRef(
243
+ null
244
+ );
193
245
  const acceptMut = useMutation({
194
- mutationFn: async (input) => {
195
- const client = requireClient(ctx.client);
246
+ mutationFn: async ({ client, input }) => {
196
247
  const { signature: signature2 } = await client.acceptTaskResult({
197
248
  ...input,
198
- task: taskPda,
199
- creator: input.creator ?? client.signer
249
+ task: taskPda
200
250
  });
201
251
  return signature2;
202
252
  }
203
253
  });
204
254
  const rejectMut = useMutation({
205
- mutationFn: async (input) => {
206
- const client = requireClient(ctx.client);
255
+ mutationFn: async ({ client, input }) => {
207
256
  const ix = await facade.rejectTaskResult({
208
257
  ...input,
209
- task: taskPda,
210
- creator: input.creator ?? client.signer
258
+ task: taskPda
211
259
  });
212
260
  const { signature: signature2 } = await client.send([ix]);
213
261
  return signature2;
214
262
  }
215
263
  });
216
264
  const requestChangesMut = useMutation({
217
- mutationFn: async (input) => {
218
- const client = requireClient(ctx.client);
265
+ mutationFn: async ({ client, input }) => {
219
266
  const ix = await facade.requestChanges({
220
267
  ...input,
221
- task: taskPda,
222
- creator: input.creator ?? client.signer
268
+ task: taskPda
223
269
  });
224
270
  const { signature: signature2 } = await client.send([ix]);
225
271
  return signature2;
226
272
  }
227
273
  });
228
274
  const accept = useCallback(
229
- (input) => acceptMut.mutateAsync(input),
230
- [acceptMut]
275
+ async (input) => {
276
+ const client = requireClient(ctx.client);
277
+ const detachedInput = snapshotRecord(input);
278
+ const creator = stabilizeSelectedTransactionSigner(
279
+ client.signer,
280
+ detachedInput.creator
281
+ );
282
+ const snapshottedInput = snapshotRecord({
283
+ ...detachedInput,
284
+ creator,
285
+ ...detachedInput.bidSettlement === void 0 ? {} : { bidSettlement: snapshotRecord(detachedInput.bidSettlement) }
286
+ });
287
+ lastAction.current = "accept";
288
+ return acceptMut.mutateAsync({ client, input: snapshottedInput });
289
+ },
290
+ [acceptMut, ctx.client]
231
291
  );
232
292
  const reject = useCallback(
233
- (input) => rejectMut.mutateAsync(input),
234
- [rejectMut]
293
+ async (input) => {
294
+ const client = requireClient(ctx.client);
295
+ const detachedInput = snapshotRecord(input);
296
+ const creator = stabilizeSelectedTransactionSigner(
297
+ client.signer,
298
+ detachedInput.creator
299
+ );
300
+ const snapshottedInput = snapshotRecord({
301
+ ...detachedInput,
302
+ creator,
303
+ rejectionHash: snapshotFixedBytes32(
304
+ detachedInput.rejectionHash,
305
+ "useSubmissionReview.reject: rejectionHash"
306
+ )
307
+ });
308
+ lastAction.current = "reject";
309
+ return rejectMut.mutateAsync({ client, input: snapshottedInput });
310
+ },
311
+ [ctx.client, rejectMut]
235
312
  );
236
313
  const requestChanges = useCallback(
237
- (input) => requestChangesMut.mutateAsync(input),
238
- [requestChangesMut]
314
+ async (input) => {
315
+ const client = requireClient(ctx.client);
316
+ const detachedInput = snapshotRecord(input);
317
+ const creator = stabilizeSelectedTransactionSigner(
318
+ client.signer,
319
+ detachedInput.creator
320
+ );
321
+ const snapshottedInput = snapshotRecord({
322
+ ...detachedInput,
323
+ creator,
324
+ changesHash: snapshotFixedBytes32(
325
+ detachedInput.changesHash,
326
+ "useSubmissionReview.requestChanges: changesHash"
327
+ )
328
+ });
329
+ lastAction.current = "requestChanges";
330
+ return requestChangesMut.mutateAsync({
331
+ client,
332
+ input: snapshottedInput
333
+ });
334
+ },
335
+ [ctx.client, requestChangesMut]
239
336
  );
240
337
  const anyPending = acceptMut.isPending || rejectMut.isPending || requestChangesMut.isPending;
241
- const status = anyPending ? "pending" : statusOf(
242
- // Surface the most recently-touched verb's terminal state.
243
- [acceptMut, rejectMut, requestChangesMut].find(
244
- (m) => m.isError || m.isSuccess
245
- ) ?? acceptMut
246
- );
247
- const error = acceptMut.error ?? rejectMut.error ?? requestChangesMut.error ?? null;
248
- const signature = acceptMut.data ?? rejectMut.data ?? requestChangesMut.data ?? null;
338
+ const latest = lastAction.current === "reject" ? rejectMut : lastAction.current === "requestChanges" ? requestChangesMut : acceptMut;
339
+ const status = anyPending ? "pending" : statusOf(latest);
340
+ const error = latest.error ?? null;
341
+ const signature = latest.data ?? null;
249
342
  return {
250
343
  accept,
251
344
  reject,
@@ -254,6 +347,7 @@ function useSubmissionReview(taskPda) {
254
347
  error,
255
348
  signature,
256
349
  reset: () => {
350
+ lastAction.current = null;
257
351
  acceptMut.reset();
258
352
  rejectMut.reset();
259
353
  requestChangesMut.reset();
@@ -263,27 +357,56 @@ function useSubmissionReview(taskPda) {
263
357
  function useTaskActivation(taskPda) {
264
358
  const ctx = useAgencContext();
265
359
  const mutation = useMutation({
266
- mutationFn: async (input) => {
267
- const client = requireClient(ctx.client);
360
+ mutationFn: async ({
361
+ client,
362
+ input,
363
+ taskPda: snapshottedTaskPda,
364
+ creator,
365
+ orchestrationRpcUrl,
366
+ orchestrationRpc
367
+ }) => {
268
368
  const callerResolved = input.moderationAttestor !== void 0 || input.moderatorIsAttestor !== void 0 || input.taskModeration !== void 0;
269
369
  const resolved = callerResolved ? {} : await resolveActivationModerationAccounts({
270
- rpcUrl: ctx.rpcUrl,
271
- task: taskPda,
370
+ rpcUrl: orchestrationRpcUrl,
371
+ ...orchestrationRpc === null ? {} : { rpc: orchestrationRpc },
372
+ task: snapshottedTaskPda,
272
373
  jobSpecHash: input.jobSpecHash,
273
374
  moderator: input.moderator
274
375
  });
275
376
  const { signature } = await client.setTaskJobSpec({
276
377
  ...input,
277
378
  ...resolved,
278
- task: taskPda,
279
- creator: input.creator ?? client.signer
379
+ task: snapshottedTaskPda,
380
+ creator
280
381
  });
281
382
  return signature;
282
383
  }
283
384
  });
284
385
  const activate = useCallback(
285
- (input) => mutation.mutateAsync(input),
286
- [mutation]
386
+ async (input) => {
387
+ const client = requireClient(ctx.client);
388
+ const detachedInput = { ...input };
389
+ const snapshottedInput = {
390
+ ...detachedInput,
391
+ jobSpecHash: snapshotFixedBytes32(
392
+ detachedInput.jobSpecHash,
393
+ "useTaskActivation: jobSpecHash"
394
+ )
395
+ };
396
+ const creator = stabilizeSelectedTransactionSigner(
397
+ client.signer,
398
+ detachedInput.creator
399
+ );
400
+ return mutation.mutateAsync({
401
+ client,
402
+ input: snapshottedInput,
403
+ taskPda,
404
+ creator,
405
+ orchestrationRpcUrl: ctx.orchestrationRpcUrl,
406
+ orchestrationRpc: ctx.orchestrationRpc
407
+ });
408
+ },
409
+ [ctx, mutation]
287
410
  );
288
411
  return {
289
412
  activate,
@@ -301,20 +424,114 @@ function emptyProgress() {
301
424
  activationSignature: null,
302
425
  jobSpecHash: null,
303
426
  jobSpecUri: null,
304
- referrerInjected: false
427
+ referrerInjected: false,
428
+ recovery: null
305
429
  };
306
430
  }
307
- function validateModerationResult(result) {
431
+ function readCreatorAddress(creator, label) {
432
+ try {
433
+ return address(creator.address);
434
+ } catch (cause) {
435
+ throw new TypeError(
436
+ `useHumanlessHireFlow: ${label} must expose a valid Solana address`,
437
+ { cause }
438
+ );
439
+ }
440
+ }
441
+ function assertCreatorUnchanged(creator, expectedAddress) {
442
+ if (readCreatorAddress(creator, "creator") !== expectedAddress) {
443
+ throw new TypeError(
444
+ "useHumanlessHireFlow: creator address changed after enqueue; no transaction was submitted"
445
+ );
446
+ }
447
+ return creator;
448
+ }
449
+ function snapshotFlowInput(input, defaultCreator) {
450
+ let jobSpec;
451
+ try {
452
+ jobSpec = snapshotStructuredClone(
453
+ input.jobSpec,
454
+ "useHumanlessHireFlow: jobSpec"
455
+ );
456
+ } catch (cause) {
457
+ throw new TypeError(
458
+ "useHumanlessHireFlow: jobSpec must be structured-cloneable",
459
+ { cause }
460
+ );
461
+ }
462
+ const creator = stabilizeSelectedTransactionSigner(
463
+ defaultCreator,
464
+ input.creator
465
+ );
466
+ return {
467
+ creatorAddress: readCreatorAddress(creator, "creator"),
468
+ input: {
469
+ ...input,
470
+ hire: {
471
+ ...input.hire,
472
+ taskId: snapshotFixedBytes32(
473
+ input.hire.taskId,
474
+ "useHumanlessHireFlow: hire.taskId"
475
+ ),
476
+ listingSpecHash: snapshotFixedBytes32(
477
+ input.hire.listingSpecHash,
478
+ "useHumanlessHireFlow: hire.listingSpecHash"
479
+ ),
480
+ taskJobSpecHash: snapshotFixedBytes32(
481
+ input.hire.taskJobSpecHash,
482
+ "useHumanlessHireFlow: hire.taskJobSpecHash"
483
+ )
484
+ },
485
+ jobSpec,
486
+ ...input.activation === void 0 ? {} : { activation: { ...input.activation } },
487
+ creator
488
+ }
489
+ };
490
+ }
491
+ function snapshotRecovery(recovery) {
492
+ return recovery.phase === "activating" ? {
493
+ ...recovery,
494
+ jobSpecHash: snapshotFixedBytes32(
495
+ recovery.jobSpecHash,
496
+ "useHumanlessHireFlow: recovery.jobSpecHash"
497
+ )
498
+ } : { ...recovery };
499
+ }
500
+ function progressFromRecovery(recovery, referrerInjected) {
501
+ const committed = recovery.phase !== "hiring";
502
+ const activating = recovery.phase === "activating" ? recovery : null;
503
+ return {
504
+ taskPda: recovery.taskPda,
505
+ hireSignature: committed && recovery.hireSignature !== "" ? recovery.hireSignature : null,
506
+ activationSignature: null,
507
+ jobSpecHash: activating?.jobSpecHash ?? null,
508
+ jobSpecUri: activating?.jobSpecUri ?? null,
509
+ referrerInjected,
510
+ recovery
511
+ };
512
+ }
513
+ function validateModerationResult(result, committedHash) {
308
514
  if (result.moderationAttested !== true) {
309
515
  throw new Error(
310
516
  "Task moderation was not attested; activation was not signed."
311
517
  );
312
518
  }
313
- if (!(result.jobSpecHash instanceof Uint8Array) || result.jobSpecHash.byteLength !== 32) {
519
+ let jobSpecHash;
520
+ try {
521
+ jobSpecHash = snapshotFixedBytes32(
522
+ result.jobSpecHash,
523
+ "useHumanlessHireFlow: moderation.jobSpecHash"
524
+ );
525
+ } catch {
314
526
  throw new Error(
315
527
  "Task moderation returned an invalid jobSpecHash; activation was not signed."
316
528
  );
317
529
  }
530
+ if (!jobSpecHash.every((byte, index) => byte === committedHash[index])) {
531
+ throw new Error(
532
+ "Task moderation returned a jobSpecHash different from the hash committed at hire; activation was not signed."
533
+ );
534
+ }
318
535
  const jobSpecUri = result.jobSpecUri.trim();
319
536
  if (!jobSpecUri) {
320
537
  throw new Error(
@@ -327,7 +544,7 @@ function validateModerationResult(result) {
327
544
  );
328
545
  }
329
546
  return {
330
- jobSpecHash: result.jobSpecHash,
547
+ jobSpecHash,
331
548
  jobSpecUri,
332
549
  moderator: result.moderator
333
550
  };
@@ -338,107 +555,157 @@ function useHumanlessHireFlow() {
338
555
  const [progress, setProgress] = useState(emptyProgress);
339
556
  const flowInFlight = useRef(false);
340
557
  const mutation = useMutation({
341
- mutationFn: async (input) => {
342
- const client = requireClient(ctx.client);
343
- const creator = input.creator ?? client.signer;
344
- const { referrerArgs, referrerInjected } = resolveReferrerArgs(ctx);
558
+ mutationFn: async ({
559
+ input,
560
+ creatorAddress,
561
+ recovery,
562
+ client,
563
+ rpc,
564
+ rpcUrl,
565
+ referral
566
+ }) => {
567
+ const creator = assertCreatorUnchanged(input.creator, creatorAddress);
568
+ const { referrerArgs, referrerInjected } = referral;
345
569
  const hireInput = withoutReferrerArgs(input.hire);
346
- setPhase("hiring");
347
- setProgress(emptyProgress());
570
+ const activationInput = { ...input.activation ?? {} };
571
+ let activationRecovery = recovery?.phase === "activating" ? recovery : null;
572
+ setPhase(recovery?.phase ?? "hiring");
573
+ setProgress(
574
+ recovery === null ? { ...emptyProgress(), referrerInjected } : progressFromRecovery(recovery, referrerInjected)
575
+ );
348
576
  try {
349
- const hireListingSpecHash = input.hire.listingSpecHash;
350
- let hireModerationArgs = {};
351
- if (input.hire.moderationAttestor === void 0 && input.hire.moderatorIsAttestor === void 0 && input.hire.listingModeration === void 0 && hireListingSpecHash !== void 0) {
352
- hireModerationArgs = await resolveHireListingModerationAccounts({
353
- rpcUrl: ctx.rpcUrl,
354
- listing: input.hire.listing,
355
- listingSpecHash: hireListingSpecHash,
356
- moderator: input.hire.moderator
357
- });
358
- }
359
- const hireResult = await client.hireFromListingHumanless({
360
- ...hireInput,
361
- ...hireModerationArgs,
362
- creator,
363
- ...referrerArgs
364
- });
365
- const [taskPda] = await findTaskPda({
366
- creator: signerAddress(creator),
367
- taskId: input.hire.taskId
368
- });
369
- setProgress({
370
- ...emptyProgress(),
371
- taskPda,
372
- hireSignature: hireResult.signature,
373
- referrerInjected
374
- });
375
- setPhase("moderating");
376
- const moderation = await input.hostAndModerateJobSpec({
377
- taskPda,
378
- taskId: input.hire.taskId,
379
- listing: input.hire.listing,
577
+ const orchestration = {
578
+ hire: {
579
+ ...hireInput,
580
+ ...referrerArgs
581
+ },
380
582
  jobSpec: input.jobSpec,
381
- hireSignature: hireResult.signature,
382
- referrerInjected
383
- });
384
- const { jobSpecHash, jobSpecUri, moderator } = validateModerationResult(moderation);
385
- setProgress((current) => ({
386
- ...current,
387
- jobSpecHash,
388
- jobSpecUri
389
- }));
390
- setPhase("activating");
391
- const activationModerator = input.activation?.moderator ?? moderator;
392
- const activationCallerResolved = input.activation?.moderationAttestor !== void 0 || input.activation?.moderatorIsAttestor !== void 0 || input.activation?.taskModeration !== void 0;
393
- const activationModerationArgs = activationCallerResolved ? {} : await resolveActivationModerationAccounts({
394
- rpcUrl: ctx.rpcUrl,
395
- task: taskPda,
396
- jobSpecHash,
397
- moderator: activationModerator
398
- });
399
- const activationResult = await client.setTaskJobSpec({
400
- ...input.activation ?? {},
401
- ...activationModerationArgs,
402
- task: taskPda,
583
+ activation: activationInput,
403
584
  creator,
404
- jobSpecHash,
405
- jobSpecUri,
406
- moderator: activationModerator
407
- });
585
+ hostAndModerateJobSpec: async (host) => {
586
+ const committed = {
587
+ phase: "moderating",
588
+ taskPda: host.taskPda,
589
+ hireSignature: host.hireSignature,
590
+ hireIntentDigest: host.hireIntentDigest,
591
+ ...host.hireReconciled === true ? { hireReconciled: true } : {}
592
+ };
593
+ setProgress(progressFromRecovery(committed, referrerInjected));
594
+ const moderation = await input.hostAndModerateJobSpec({
595
+ taskPda: host.taskPda,
596
+ taskId: host.taskId,
597
+ listing: host.listing,
598
+ jobSpec: host.jobSpec,
599
+ hireSignature: host.hireSignature,
600
+ ...host.hireReconciled === true ? { hireReconciled: true } : {},
601
+ referrerInjected
602
+ });
603
+ const validated = validateModerationResult(
604
+ moderation,
605
+ input.hire.taskJobSpecHash
606
+ );
607
+ const activationModerator = input.activation?.moderator ?? validated.moderator;
608
+ activationRecovery = {
609
+ phase: "activating",
610
+ taskPda: host.taskPda,
611
+ hireSignature: host.hireSignature,
612
+ hireIntentDigest: host.hireIntentDigest,
613
+ ...host.hireReconciled === true ? { hireReconciled: true } : {},
614
+ ...validated,
615
+ moderator: activationModerator
616
+ };
617
+ return moderation;
618
+ },
619
+ onPhase: (nextPhase) => {
620
+ setPhase(nextPhase);
621
+ if (nextPhase === "activating" && activationRecovery !== null) {
622
+ setProgress(
623
+ progressFromRecovery(activationRecovery, referrerInjected)
624
+ );
625
+ }
626
+ },
627
+ ...rpc !== null ? { rpc } : {},
628
+ ...rpcUrl !== null ? { rpcUrl } : {}
629
+ };
630
+ const orchestrationResult = recovery === null ? await hireAndActivate(client, orchestration) : await resumeHireAndActivate(client, orchestration, recovery);
408
631
  const result = {
409
- taskPda,
410
- hireSignature: hireResult.signature,
411
- activationSignature: activationResult.signature,
412
- jobSpecHash,
413
- jobSpecUri,
632
+ taskPda: orchestrationResult.taskPda,
633
+ hireSignature: orchestrationResult.hireSignature,
634
+ activationSignature: orchestrationResult.activationSignature,
635
+ jobSpecHash: orchestrationResult.jobSpecHash,
636
+ jobSpecUri: orchestrationResult.jobSpecUri,
414
637
  referrerInjected,
415
- moderation: moderation.moderation
638
+ ...orchestrationResult.hireReconciled === true ? { hireReconciled: true } : {},
639
+ ...orchestrationResult.activationReconciled === true ? { activationReconciled: true } : {},
640
+ moderation: orchestrationResult.moderation
416
641
  };
417
- setProgress((current) => ({
418
- ...current,
419
- activationSignature: activationResult.signature
420
- }));
642
+ setProgress({
643
+ taskPda: result.taskPda,
644
+ hireSignature: result.hireSignature || null,
645
+ activationSignature: result.activationSignature || null,
646
+ jobSpecHash: result.jobSpecHash,
647
+ jobSpecUri: result.jobSpecUri,
648
+ referrerInjected,
649
+ recovery: null
650
+ });
421
651
  setPhase("activated");
422
652
  return result;
423
653
  } catch (error) {
654
+ if (error instanceof HireAndActivateError) {
655
+ setProgress(progressFromRecovery(error.progress, referrerInjected));
656
+ } else if (error instanceof HireAndActivateFinalizedFailure) {
657
+ setProgress({ ...emptyProgress(), referrerInjected });
658
+ }
424
659
  setPhase("error");
425
660
  throw error;
426
661
  }
427
662
  }
428
663
  });
429
- const hireAndActivate = useCallback(
664
+ const hireAndActivate$1 = useCallback(
430
665
  async (input) => {
431
666
  if (flowInFlight.current) {
432
667
  throw new Error("A humanless hire flow is already in progress.");
433
668
  }
434
669
  flowInFlight.current = true;
435
670
  try {
436
- return await mutation.mutateAsync(input);
671
+ const client = requireClient(ctx.client);
672
+ const snapshot = snapshotFlowInput(input, client.signer);
673
+ return await mutation.mutateAsync({
674
+ ...snapshot,
675
+ recovery: null,
676
+ client,
677
+ rpc: ctx.orchestrationRpc,
678
+ rpcUrl: ctx.orchestrationRpcUrl,
679
+ referral: resolveReferrerArgs(ctx)
680
+ });
437
681
  } finally {
438
682
  flowInFlight.current = false;
439
683
  }
440
684
  },
441
- [mutation]
685
+ [ctx, mutation]
686
+ );
687
+ const resumeHireAndActivate$1 = useCallback(
688
+ async (input, recovery) => {
689
+ if (flowInFlight.current) {
690
+ throw new Error("A humanless hire flow is already in progress.");
691
+ }
692
+ flowInFlight.current = true;
693
+ try {
694
+ const client = requireClient(ctx.client);
695
+ const snapshot = snapshotFlowInput(input, client.signer);
696
+ return await mutation.mutateAsync({
697
+ ...snapshot,
698
+ recovery: snapshotRecovery(recovery),
699
+ client,
700
+ rpc: ctx.orchestrationRpc,
701
+ rpcUrl: ctx.orchestrationRpcUrl,
702
+ referral: resolveReferrerArgs(ctx)
703
+ });
704
+ } finally {
705
+ flowInFlight.current = false;
706
+ }
707
+ },
708
+ [ctx, mutation]
442
709
  );
443
710
  const reset = useCallback(() => {
444
711
  mutation.reset();
@@ -446,7 +713,8 @@ function useHumanlessHireFlow() {
446
713
  setProgress(emptyProgress());
447
714
  }, [mutation]);
448
715
  return {
449
- hireAndActivate,
716
+ hireAndActivate: hireAndActivate$1,
717
+ resumeHireAndActivate: resumeHireAndActivate$1,
450
718
  phase,
451
719
  status: mutationStatusOf(mutation),
452
720
  progress,
@@ -458,9 +726,9 @@ function useHumanlessHireFlow() {
458
726
  }
459
727
  function useTaskWork(taskPda) {
460
728
  const ctx = useAgencContext();
729
+ const lastAction = useRef(null);
461
730
  const claimMut = useMutation({
462
- mutationFn: async (input) => {
463
- const client = requireClient(ctx.client);
731
+ mutationFn: async ({ client, input }) => {
464
732
  const { signature } = await client.claimTaskWithJobSpec({
465
733
  ...input,
466
734
  task: taskPda
@@ -469,8 +737,7 @@ function useTaskWork(taskPda) {
469
737
  }
470
738
  });
471
739
  const submitMut = useMutation({
472
- mutationFn: async (input) => {
473
- const client = requireClient(ctx.client);
740
+ mutationFn: async ({ client, input }) => {
474
741
  const { signature } = await client.submitTaskResult({
475
742
  ...input,
476
743
  task: taskPda
@@ -478,21 +745,66 @@ function useTaskWork(taskPda) {
478
745
  return signature;
479
746
  }
480
747
  });
481
- const claim = useCallback((input) => claimMut.mutateAsync(input), [claimMut]);
748
+ const claim = useCallback(
749
+ async (input) => {
750
+ const client = requireClient(ctx.client);
751
+ const detachedInput = snapshotRecord(input);
752
+ const authority = stabilizeSelectedTransactionSigner(
753
+ client.signer,
754
+ detachedInput.authority
755
+ );
756
+ const snapshottedInput = snapshotRecord({
757
+ ...detachedInput,
758
+ authority,
759
+ ...detachedInput.jobSpecHash === void 0 ? {} : {
760
+ jobSpecHash: snapshotFixedBytes32(
761
+ detachedInput.jobSpecHash,
762
+ "useTaskWork.claim: jobSpecHash"
763
+ )
764
+ }
765
+ });
766
+ lastAction.current = "claim";
767
+ return claimMut.mutateAsync({ client, input: snapshottedInput });
768
+ },
769
+ [claimMut, ctx.client]
770
+ );
482
771
  const submit = useCallback(
483
- (input) => submitMut.mutateAsync(input),
484
- [submitMut]
772
+ async (input) => {
773
+ const client = requireClient(ctx.client);
774
+ const detachedInput = snapshotRecord(input);
775
+ const authority = stabilizeSelectedTransactionSigner(
776
+ client.signer,
777
+ detachedInput.authority
778
+ );
779
+ const snapshottedInput = snapshotRecord({
780
+ ...detachedInput,
781
+ authority,
782
+ proofHash: snapshotFixedBytes32(
783
+ detachedInput.proofHash,
784
+ "useTaskWork.submit: proofHash"
785
+ ),
786
+ resultData: snapshotOptionalFixedBytes(
787
+ detachedInput.resultData,
788
+ 64,
789
+ "useTaskWork.submit: resultData"
790
+ )
791
+ });
792
+ lastAction.current = "submit";
793
+ return submitMut.mutateAsync({ client, input: snapshottedInput });
794
+ },
795
+ [ctx.client, submitMut]
485
796
  );
486
797
  const active = claimMut.isPending || submitMut.isPending;
487
- const latest = [claimMut, submitMut].find((m) => m.isError || m.isSuccess) ?? claimMut;
798
+ const latest = lastAction.current === "submit" ? submitMut : claimMut;
488
799
  return {
489
800
  claim,
490
801
  submit,
491
802
  status: active ? "pending" : mutationStatusOf(latest),
492
803
  signature: latest.data ?? null,
493
- error: claimMut.error ?? submitMut.error ?? null,
804
+ error: latest.error ?? null,
494
805
  isPending: active,
495
806
  reset: () => {
807
+ lastAction.current = null;
496
808
  claimMut.reset();
497
809
  submitMut.reset();
498
810
  }
@@ -500,62 +812,108 @@ function useTaskWork(taskPda) {
500
812
  }
501
813
  function useTaskLifecycle(taskPda) {
502
814
  const ctx = useAgencContext();
815
+ const lastAction = useRef(null);
503
816
  const cancelMut = useMutation({
504
- mutationFn: async (input) => {
505
- const client = requireClient(ctx.client);
817
+ mutationFn: async ({ client, input }) => {
506
818
  const { signature } = await client.cancelTask({
507
- ...input ?? {},
508
- task: taskPda,
509
- authority: input?.authority ?? client.signer
819
+ ...input,
820
+ task: taskPda
510
821
  });
511
822
  return signature;
512
823
  }
513
824
  });
514
825
  const closeMut = useMutation({
515
- mutationFn: async (input) => {
516
- const client = requireClient(ctx.client);
826
+ mutationFn: async ({ client, input }) => {
517
827
  const { signature } = await client.closeTask({
518
- ...input ?? {},
519
- task: taskPda,
520
- authority: input?.authority ?? client.signer
828
+ ...input,
829
+ task: taskPda
521
830
  });
522
831
  return signature;
523
832
  }
524
833
  });
525
834
  const autoAcceptMut = useMutation({
526
- mutationFn: async (input) => {
527
- const client = requireClient(ctx.client);
835
+ mutationFn: async ({ client, input }) => {
528
836
  const { signature } = await client.autoAcceptTaskResult({
529
837
  ...input,
530
- task: taskPda,
531
- authority: input.authority ?? client.signer
838
+ task: taskPda
532
839
  });
533
840
  return signature;
534
841
  }
535
842
  });
536
843
  const cancel = useCallback(
537
- (input) => cancelMut.mutateAsync(input),
538
- [cancelMut]
844
+ async (input) => {
845
+ const client = requireClient(ctx.client);
846
+ const detachedInput = snapshotRecord(input ?? {});
847
+ const authority = stabilizeSelectedTransactionSigner(
848
+ client.signer,
849
+ detachedInput.authority
850
+ );
851
+ const snapshottedInput = snapshotRecord({
852
+ ...detachedInput,
853
+ authority,
854
+ // audit F5/F12: cancelTask requires the bond PDAs; the SDK facade derives
855
+ // them from authority / workerBondAuthority. Default the worker wallet to
856
+ // the task PDA itself — it can never be a bond poster (PDAs can't sign),
857
+ // so the derived worker-bond PDA is the empty no-op account.
858
+ workerBondAuthority: detachedInput.workerBondAuthority ?? taskPda,
859
+ ...detachedInput.workerAccounts === void 0 ? {} : {
860
+ workerAccounts: snapshotRecordArray(detachedInput.workerAccounts)
861
+ },
862
+ ...detachedInput.bidSettlement === void 0 ? {} : { bidSettlement: snapshotRecord(detachedInput.bidSettlement) }
863
+ });
864
+ lastAction.current = "cancel";
865
+ return cancelMut.mutateAsync({ client, input: snapshottedInput });
866
+ },
867
+ [cancelMut, ctx.client]
539
868
  );
540
869
  const close = useCallback(
541
- (input) => closeMut.mutateAsync(input),
542
- [closeMut]
870
+ async (input) => {
871
+ const client = requireClient(ctx.client);
872
+ const detachedInput = snapshotRecord(input ?? {});
873
+ const authority = stabilizeSelectedTransactionSigner(
874
+ client.signer,
875
+ detachedInput.authority
876
+ );
877
+ const snapshottedInput = snapshotRecord({
878
+ ...detachedInput,
879
+ authority,
880
+ ...detachedInput.children === void 0 ? {} : { children: snapshotRecordArray(detachedInput.children) }
881
+ });
882
+ lastAction.current = "close";
883
+ return closeMut.mutateAsync({ client, input: snapshottedInput });
884
+ },
885
+ [closeMut, ctx.client]
543
886
  );
544
887
  const autoAccept = useCallback(
545
- (input) => autoAcceptMut.mutateAsync(input),
546
- [autoAcceptMut]
888
+ async (input) => {
889
+ const client = requireClient(ctx.client);
890
+ const detachedInput = snapshotRecord(input);
891
+ const authority = stabilizeSelectedTransactionSigner(
892
+ client.signer,
893
+ detachedInput.authority
894
+ );
895
+ const snapshottedInput = snapshotRecord({
896
+ ...detachedInput,
897
+ authority,
898
+ ...detachedInput.bidSettlement === void 0 ? {} : { bidSettlement: snapshotRecord(detachedInput.bidSettlement) }
899
+ });
900
+ lastAction.current = "autoAccept";
901
+ return autoAcceptMut.mutateAsync({ client, input: snapshottedInput });
902
+ },
903
+ [autoAcceptMut, ctx.client]
547
904
  );
548
905
  const active = cancelMut.isPending || closeMut.isPending || autoAcceptMut.isPending;
549
- const latest = [cancelMut, closeMut, autoAcceptMut].find((m) => m.isError || m.isSuccess) ?? cancelMut;
906
+ const latest = lastAction.current === "close" ? closeMut : lastAction.current === "autoAccept" ? autoAcceptMut : cancelMut;
550
907
  return {
551
908
  cancel,
552
909
  close,
553
910
  autoAccept,
554
911
  status: active ? "pending" : mutationStatusOf(latest),
555
912
  signature: latest.data ?? null,
556
- error: cancelMut.error ?? closeMut.error ?? autoAcceptMut.error ?? null,
913
+ error: latest.error ?? null,
557
914
  isPending: active,
558
915
  reset: () => {
916
+ lastAction.current = null;
559
917
  cancelMut.reset();
560
918
  closeMut.reset();
561
919
  autoAcceptMut.reset();
@@ -565,17 +923,35 @@ function useTaskLifecycle(taskPda) {
565
923
  function useRateHire(taskPda) {
566
924
  const ctx = useAgencContext();
567
925
  const mutation = useMutation({
568
- mutationFn: async (input) => {
569
- const client = requireClient(ctx.client);
926
+ mutationFn: async ({ client, input }) => {
570
927
  const { signature } = await client.rateHire({
571
928
  ...input,
572
- task: taskPda,
573
- buyer: input.buyer ?? client.signer
929
+ task: taskPda
574
930
  });
575
931
  return signature;
576
932
  }
577
933
  });
578
- const rate = useCallback((input) => mutation.mutateAsync(input), [mutation]);
934
+ const rate = useCallback(
935
+ async (input) => {
936
+ const client = requireClient(ctx.client);
937
+ const detachedInput = snapshotRecord(input);
938
+ const buyer = stabilizeSelectedTransactionSigner(
939
+ client.signer,
940
+ detachedInput.buyer
941
+ );
942
+ const snapshottedInput = snapshotRecord({
943
+ ...detachedInput,
944
+ buyer,
945
+ reviewHash: snapshotOptionalFixedBytes(
946
+ detachedInput.reviewHash,
947
+ 32,
948
+ "useRateHire.rate: reviewHash"
949
+ )
950
+ });
951
+ return mutation.mutateAsync({ client, input: snapshottedInput });
952
+ },
953
+ [ctx.client, mutation]
954
+ );
579
955
  return {
580
956
  rate,
581
957
  status: mutationStatusOf(mutation),
@@ -590,25 +966,50 @@ function useDispute(taskPda, options) {
590
966
  const reader = options?.disputeReader;
591
967
  const enabled = (options?.enabled ?? true) && Boolean(taskPda) && Boolean(reader);
592
968
  const read = useQuery({
593
- queryKey: queryKeys.dispute(taskPda ? pdaKey(taskPda) : ""),
969
+ queryKey: queryKeys.dispute(
970
+ taskPda ? pdaKey(taskPda) : "",
971
+ ctx.cacheNamespace
972
+ ),
594
973
  enabled,
595
974
  queryFn: () => reader(taskPda)
596
975
  });
597
976
  const mutation = useMutation({
598
- mutationFn: async (input) => {
599
- const client = requireClient(ctx.client);
977
+ mutationFn: async ({ client, input }) => {
600
978
  const { signature } = await client.initiateDispute({
601
979
  ...input,
602
- task: taskPda,
603
- authority: input.authority ?? client.signer
980
+ task: taskPda
604
981
  });
605
982
  void read.refetch();
606
983
  return signature;
607
984
  }
608
985
  });
609
986
  const initiate = useCallback(
610
- (input) => mutation.mutateAsync(input),
611
- [mutation]
987
+ async (input) => {
988
+ const client = requireClient(ctx.client);
989
+ const detachedInput = snapshotRecord(input);
990
+ const authority = stabilizeSelectedTransactionSigner(
991
+ client.signer,
992
+ detachedInput.authority
993
+ );
994
+ const snapshottedInput = snapshotRecord({
995
+ ...detachedInput,
996
+ authority,
997
+ disputeId: snapshotFixedBytes32(
998
+ detachedInput.disputeId,
999
+ "useDispute.initiate: disputeId"
1000
+ ),
1001
+ taskId: snapshotFixedBytes32(
1002
+ detachedInput.taskId,
1003
+ "useDispute.initiate: taskId"
1004
+ ),
1005
+ evidenceHash: snapshotFixedBytes32(
1006
+ detachedInput.evidenceHash,
1007
+ "useDispute.initiate: evidenceHash"
1008
+ )
1009
+ });
1010
+ return mutation.mutateAsync({ client, input: snapshottedInput });
1011
+ },
1012
+ [ctx.client, mutation]
612
1013
  );
613
1014
  const status = mutation.isPending ? "pending" : mutation.isError ? "error" : mutation.isSuccess ? "success" : "idle";
614
1015
  return {
@@ -625,56 +1026,75 @@ function useDispute(taskPda, options) {
625
1026
  function useCompletionBond(taskPda) {
626
1027
  const ctx = useAgencContext();
627
1028
  const queryClient = useQueryClient();
1029
+ const lastAction = useRef(null);
628
1030
  const invalidateGuarantee = useCallback(() => {
629
1031
  void queryClient.invalidateQueries({
630
- queryKey: queryKeys.taskGuarantee(pdaKey(taskPda))
1032
+ queryKey: queryKeys.taskGuarantee(pdaKey(taskPda), ctx.cacheNamespace)
631
1033
  });
632
- }, [queryClient, taskPda]);
1034
+ }, [ctx.cacheNamespace, queryClient, taskPda]);
633
1035
  const postMut = useMutation({
634
- mutationFn: async (input) => {
635
- const client = requireClient(ctx.client);
1036
+ mutationFn: async ({ client, input }) => {
636
1037
  const { signature } = await client.postCompletionBond({
637
1038
  ...input,
638
- task: taskPda,
639
- authority: input.authority ?? client.signer
1039
+ task: taskPda
640
1040
  });
641
1041
  invalidateGuarantee();
642
1042
  return signature;
643
1043
  }
644
1044
  });
645
1045
  const reclaimMut = useMutation({
646
- mutationFn: async (input) => {
647
- const client = requireClient(ctx.client);
1046
+ mutationFn: async ({ client, input }) => {
648
1047
  const { signature } = await client.reclaimCompletionBond({
649
1048
  ...input,
650
- task: taskPda,
651
- party: input.party ?? client.signer.address
1049
+ task: taskPda
652
1050
  });
653
1051
  invalidateGuarantee();
654
1052
  return signature;
655
1053
  }
656
1054
  });
657
1055
  const post = useCallback(
658
- (input) => postMut.mutateAsync(input),
659
- [postMut]
1056
+ async (input) => {
1057
+ const client = requireClient(ctx.client);
1058
+ const detachedInput = snapshotRecord(input);
1059
+ const authority = stabilizeSelectedTransactionSigner(
1060
+ client.signer,
1061
+ detachedInput.authority
1062
+ );
1063
+ const snapshottedInput = snapshotRecord({
1064
+ ...detachedInput,
1065
+ authority
1066
+ });
1067
+ lastAction.current = "post";
1068
+ return postMut.mutateAsync({ client, input: snapshottedInput });
1069
+ },
1070
+ [ctx.client, postMut]
660
1071
  );
661
1072
  const reclaim = useCallback(
662
- (input) => reclaimMut.mutateAsync(input),
663
- [reclaimMut]
1073
+ async (input) => {
1074
+ const client = requireClient(ctx.client);
1075
+ const detachedInput = snapshotRecord(input);
1076
+ const feePayer = stabilizeSelectedTransactionSigner(client.signer);
1077
+ const snapshottedInput = snapshotRecord({
1078
+ ...detachedInput,
1079
+ party: detachedInput.party ?? feePayer.address
1080
+ });
1081
+ lastAction.current = "reclaim";
1082
+ return reclaimMut.mutateAsync({ client, input: snapshottedInput });
1083
+ },
1084
+ [ctx.client, reclaimMut]
664
1085
  );
665
1086
  const isPending = postMut.isPending || reclaimMut.isPending;
666
- const status = isPending ? "pending" : mutationStatusOf(
667
- // Surface the most recently-touched verb's terminal state.
668
- [postMut, reclaimMut].find((m) => m.isError || m.isSuccess) ?? postMut
669
- );
1087
+ const latest = lastAction.current === "reclaim" ? reclaimMut : postMut;
1088
+ const status = isPending ? "pending" : mutationStatusOf(latest);
670
1089
  return {
671
1090
  post,
672
1091
  reclaim,
673
1092
  status,
674
- error: postMut.error ?? reclaimMut.error ?? null,
675
- signature: postMut.data ?? reclaimMut.data ?? null,
1093
+ error: latest.error ?? null,
1094
+ signature: latest.data ?? null,
676
1095
  isPending,
677
1096
  reset: () => {
1097
+ lastAction.current = null;
678
1098
  postMut.reset();
679
1099
  reclaimMut.reset();
680
1100
  }
@@ -693,7 +1113,10 @@ function useReferrerEarnings(wallet) {
693
1113
  const enabled = capability.live && earningsBase !== null && Boolean(wallet);
694
1114
  const query = useQuery(
695
1115
  {
696
- queryKey: queryKeys.referrerEarnings(wallet ? pdaKey(wallet) : ""),
1116
+ queryKey: queryKeys.referrerEarnings(
1117
+ wallet ? pdaKey(wallet) : "",
1118
+ ctx.cacheNamespace
1119
+ ),
697
1120
  enabled,
698
1121
  queryFn: async () => {
699
1122
  const url = `${earningsBase}/api/explorer/referrers/${encodeURIComponent(