@tetsuo-ai/marketplace-react 0.1.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 (112) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/LICENSE +21 -0
  3. package/README.md +172 -0
  4. package/dist/chunk-5OTKSRHM.js +128 -0
  5. package/dist/chunk-5OTKSRHM.js.map +1 -0
  6. package/dist/chunk-ABS77JB2.js +94 -0
  7. package/dist/chunk-ABS77JB2.js.map +1 -0
  8. package/dist/chunk-GN5DYVN5.js +35 -0
  9. package/dist/chunk-GN5DYVN5.js.map +1 -0
  10. package/dist/chunk-KJMR6OGC.js +1198 -0
  11. package/dist/chunk-KJMR6OGC.js.map +1 -0
  12. package/dist/chunk-YORZNYZZ.js +107 -0
  13. package/dist/chunk-YORZNYZZ.js.map +1 -0
  14. package/dist/components/agenc-components.css +570 -0
  15. package/dist/components/index.cjs +1335 -0
  16. package/dist/components/index.cjs.map +1 -0
  17. package/dist/components/index.d.cts +5 -0
  18. package/dist/components/index.d.ts +5 -0
  19. package/dist/components/index.js +5 -0
  20. package/dist/components/index.js.map +1 -0
  21. package/dist/hooks/index.cjs +493 -0
  22. package/dist/hooks/index.cjs.map +1 -0
  23. package/dist/hooks/index.d.cts +294 -0
  24. package/dist/hooks/index.d.ts +294 -0
  25. package/dist/hooks/index.js +339 -0
  26. package/dist/hooks/index.js.map +1 -0
  27. package/dist/index-BLrlBVj-.d.cts +1129 -0
  28. package/dist/index-CKTYsNPH.d.ts +1129 -0
  29. package/dist/index.cjs +1690 -0
  30. package/dist/index.cjs.map +1 -0
  31. package/dist/index.d.cts +235 -0
  32. package/dist/index.d.ts +235 -0
  33. package/dist/index.js +127 -0
  34. package/dist/index.js.map +1 -0
  35. package/dist/signers/index.cjs +166 -0
  36. package/dist/signers/index.cjs.map +1 -0
  37. package/dist/signers/index.d.cts +136 -0
  38. package/dist/signers/index.d.ts +136 -0
  39. package/dist/signers/index.js +4 -0
  40. package/dist/signers/index.js.map +1 -0
  41. package/dist/testing/index.cjs +62 -0
  42. package/dist/testing/index.cjs.map +1 -0
  43. package/dist/testing/index.d.cts +71 -0
  44. package/dist/testing/index.d.ts +71 -0
  45. package/dist/testing/index.js +60 -0
  46. package/dist/testing/index.js.map +1 -0
  47. package/dist/theme/agenc-tailwind-preset.cjs +184 -0
  48. package/dist/theme/agenc-tokens.css +132 -0
  49. package/dist/types-jvISR6bc.d.cts +135 -0
  50. package/dist/types-jvISR6bc.d.ts +135 -0
  51. package/dist/useAgentTrackRecord-BLf1nrbu.d.cts +249 -0
  52. package/dist/useAgentTrackRecord-BLf1nrbu.d.ts +249 -0
  53. package/package.json +139 -0
  54. package/src/components/DisputeBanner.stories.tsx +39 -0
  55. package/src/components/DisputeBanner.tsx +110 -0
  56. package/src/components/HireButton.stories.tsx +72 -0
  57. package/src/components/HireButton.tsx +151 -0
  58. package/src/components/HireCheckoutModal.stories.tsx +107 -0
  59. package/src/components/HireCheckoutModal.tsx +284 -0
  60. package/src/components/ListingCard.stories.tsx +55 -0
  61. package/src/components/ListingCard.tsx +148 -0
  62. package/src/components/ListingGrid.stories.tsx +44 -0
  63. package/src/components/ListingGrid.tsx +137 -0
  64. package/src/components/Modal.tsx +121 -0
  65. package/src/components/PoweredByAgenC.tsx +85 -0
  66. package/src/components/ProviderCard.stories.tsx +61 -0
  67. package/src/components/ProviderCard.tsx +154 -0
  68. package/src/components/ReferrerDisclosure.tsx +67 -0
  69. package/src/components/ReviewPanel.stories.tsx +65 -0
  70. package/src/components/ReviewPanel.tsx +141 -0
  71. package/src/components/TaskTimeline.stories.tsx +43 -0
  72. package/src/components/TaskTimeline.tsx +156 -0
  73. package/src/components/__fixtures__/index.tsx +173 -0
  74. package/src/components/agenc-components.css +570 -0
  75. package/src/components/badges.tsx +115 -0
  76. package/src/components/format.ts +150 -0
  77. package/src/components/index.ts +102 -0
  78. package/src/components/primitives.tsx +236 -0
  79. package/src/components/strings.ts +131 -0
  80. package/src/components/useFocusTrap.ts +122 -0
  81. package/src/hooks/index.ts +90 -0
  82. package/src/hooks/internal.ts +70 -0
  83. package/src/hooks/useAgentTrackRecord.ts +166 -0
  84. package/src/hooks/useDispute.ts +130 -0
  85. package/src/hooks/useHire.ts +198 -0
  86. package/src/hooks/useListing.ts +138 -0
  87. package/src/hooks/useListings.ts +133 -0
  88. package/src/hooks/useReferrerEarnings.ts +134 -0
  89. package/src/hooks/useSubmissionReview.ts +179 -0
  90. package/src/hooks/useTaskStatus.ts +192 -0
  91. package/src/hooks/useWalletSigner.ts +99 -0
  92. package/src/index.ts +170 -0
  93. package/src/provider/AgencProvider.tsx +169 -0
  94. package/src/provider/context.ts +35 -0
  95. package/src/provider/index.ts +17 -0
  96. package/src/provider/network.ts +68 -0
  97. package/src/provider/referrer.ts +97 -0
  98. package/src/signers/README.md +130 -0
  99. package/src/signers/embedded-wallet-mock.ts +158 -0
  100. package/src/signers/embedded-wallet.ts +64 -0
  101. package/src/signers/index.ts +48 -0
  102. package/src/signers/strings.ts +39 -0
  103. package/src/signers/types.ts +158 -0
  104. package/src/signers/wallet-account.ts +128 -0
  105. package/src/signers/wallet-adapter.ts +149 -0
  106. package/src/strings/index.ts +119 -0
  107. package/src/testing/index.ts +24 -0
  108. package/src/theme/agenc-tailwind-preset.cjs +184 -0
  109. package/src/theme/agenc-tokens.css +132 -0
  110. package/src/theme/index.ts +94 -0
  111. package/src/transport/index.ts +164 -0
  112. package/src/types.ts +224 -0
@@ -0,0 +1,122 @@
1
+ /**
2
+ * `useFocusTrap` — an accessible focus trap for the modal surface.
3
+ *
4
+ * `HireCheckoutModal` is a money-handling dialog published to third-party
5
+ * sites, so accessibility is STRUCTURAL (PLAN_2 A3): when the modal is open
6
+ * this hook
7
+ * - moves focus into the dialog (the first focusable element, or the dialog
8
+ * container itself);
9
+ * - cycles Tab / Shift+Tab within the dialog (a real trap, not just an
10
+ * initial focus);
11
+ * - RECAPTURES focus that escapes the dialog via a document-level `focusin`
12
+ * listener (a Tab from browser autofill UI, a third-party widget, or
13
+ * programmatic focus pulls focus back in — a container-scoped keydown alone
14
+ * never sees it);
15
+ * - invokes `onEscape` when Escape is pressed;
16
+ * - restores focus to the element that was focused before the dialog opened on
17
+ * close/unmount.
18
+ *
19
+ * SSR-safe: every `document` access happens inside `useEffect`, which never
20
+ * runs on the server. The hook is a no-op while `active` is false.
21
+ *
22
+ * @module components/useFocusTrap
23
+ */
24
+ import { useEffect, type RefObject } from "react";
25
+
26
+ /** Selector matching the natively focusable, non-disabled elements. */
27
+ const FOCUSABLE_SELECTOR = [
28
+ "a[href]",
29
+ "button:not([disabled])",
30
+ "textarea:not([disabled])",
31
+ "input:not([disabled])",
32
+ "select:not([disabled])",
33
+ '[tabindex]:not([tabindex="-1"])',
34
+ ].join(",");
35
+
36
+ function focusableWithin(container: HTMLElement): HTMLElement[] {
37
+ return Array.from(
38
+ container.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR),
39
+ ).filter((el) => el.offsetParent !== null || el === document.activeElement);
40
+ }
41
+
42
+ /**
43
+ * Trap keyboard focus within `containerRef` while `active`.
44
+ *
45
+ * @param containerRef - Ref to the dialog container element.
46
+ * @param active - Whether the trap is engaged (the modal is open).
47
+ * @param onEscape - Called when Escape is pressed inside the trap.
48
+ */
49
+ export function useFocusTrap(
50
+ containerRef: RefObject<HTMLElement | null>,
51
+ active: boolean,
52
+ onEscape?: () => void,
53
+ ): void {
54
+ useEffect(() => {
55
+ if (!active) return;
56
+ const container = containerRef.current;
57
+ if (!container) return;
58
+
59
+ // Remember what had focus so we can restore it on close.
60
+ const previouslyFocused =
61
+ document.activeElement instanceof HTMLElement
62
+ ? document.activeElement
63
+ : null;
64
+
65
+ // Move focus into the dialog (first focusable, else the container).
66
+ const initial = focusableWithin(container)[0] ?? container;
67
+ initial.focus();
68
+
69
+ function onKeyDown(event: KeyboardEvent): void {
70
+ if (event.key === "Escape") {
71
+ event.stopPropagation();
72
+ onEscape?.();
73
+ return;
74
+ }
75
+ if (event.key !== "Tab") return;
76
+ const focusable = focusableWithin(container!);
77
+ if (focusable.length === 0) {
78
+ // Nothing to tab to — keep focus on the container.
79
+ event.preventDefault();
80
+ container!.focus();
81
+ return;
82
+ }
83
+ const first = focusable[0]!;
84
+ const last = focusable[focusable.length - 1]!;
85
+ const activeEl = document.activeElement;
86
+ if (event.shiftKey) {
87
+ if (activeEl === first || activeEl === container) {
88
+ event.preventDefault();
89
+ last.focus();
90
+ }
91
+ } else if (activeEl === last) {
92
+ event.preventDefault();
93
+ first.focus();
94
+ }
95
+ }
96
+
97
+ // Document-level recapture: a container-scoped keydown listener never sees a
98
+ // Tab pressed while focus is OUTSIDE the dialog (browser autofill UI, a
99
+ // third-party widget on the embedder's page, programmatic focus, or tabbing
100
+ // back into the page from the address bar). When focus lands on something
101
+ // the dialog does not contain, pull it back to the first focusable element
102
+ // (or the container) so a keyboard/AT user cannot fall out of a money modal.
103
+ function onFocusIn(event: FocusEvent): void {
104
+ const target = event.target;
105
+ if (!(target instanceof Node)) return;
106
+ if (container!.contains(target)) return;
107
+ // Focus escaped the dialog — recapture it.
108
+ event.stopPropagation();
109
+ const focusable = focusableWithin(container!);
110
+ (focusable[0] ?? container!).focus();
111
+ }
112
+
113
+ container.addEventListener("keydown", onKeyDown);
114
+ document.addEventListener("focusin", onFocusIn);
115
+ return () => {
116
+ container.removeEventListener("keydown", onKeyDown);
117
+ document.removeEventListener("focusin", onFocusIn);
118
+ // Restore focus to where it was before the dialog opened.
119
+ previouslyFocused?.focus();
120
+ };
121
+ }, [containerRef, active, onEscape]);
122
+ }
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Headless hooks for `@tetsuo-ai/marketplace-react` (PLAN_2 Part A2).
3
+ *
4
+ * Every hook binds to the foundation context (`useAgencContext`) + TanStack
5
+ * Query (bundled), surfaces typed `AgencError`s from the runtime client
6
+ * UNTOUCHED, and is SSR-safe (no `window`/`document` at module scope).
7
+ *
8
+ * Referrer-related surfaces (`useHire`'s injection, `useReferrerEarnings`) are
9
+ * gated by the P6.2 capability check: not-live today, so no referrer is ever
10
+ * injected and no earnings are ever fabricated.
11
+ *
12
+ * @module hooks
13
+ */
14
+
15
+ // Reads
16
+ export {
17
+ useListings,
18
+ type ListingRow,
19
+ type UseListingsFilter,
20
+ type UseListingsOptions,
21
+ type UseListingsResult,
22
+ } from "./useListings.js";
23
+ export {
24
+ useListing,
25
+ type ListingDetail,
26
+ type UseListingOptions,
27
+ type UseListingResult,
28
+ } from "./useListing.js";
29
+ export {
30
+ useAgentTrackRecord,
31
+ projectTrackRecord,
32
+ type AgentTrackRecord,
33
+ type TrackRecordOutcome,
34
+ type UseAgentTrackRecordOptions,
35
+ type UseAgentTrackRecordResult,
36
+ } from "./useAgentTrackRecord.js";
37
+ export {
38
+ useTaskStatus,
39
+ type ObservedEvent,
40
+ type TaskEventsSource,
41
+ type TaskReader,
42
+ type UseTaskStatusOptions,
43
+ type UseTaskStatusResult,
44
+ } from "./useTaskStatus.js";
45
+
46
+ // Writes
47
+ export {
48
+ useHire,
49
+ type AnyHireInput,
50
+ type HireInput,
51
+ type HireResult,
52
+ type HireStatus,
53
+ type HumanlessHireInput,
54
+ type UseHireResult,
55
+ } from "./useHire.js";
56
+ export {
57
+ useSubmissionReview,
58
+ type AcceptInput,
59
+ type RejectInput,
60
+ type RequestChangesInput,
61
+ type ReviewAction,
62
+ type ReviewStatus,
63
+ type UseSubmissionReviewResult,
64
+ } from "./useSubmissionReview.js";
65
+ export {
66
+ useDispute,
67
+ type DisputeReader,
68
+ type DisputeStatus,
69
+ type InitiateDisputeInput,
70
+ type UseDisputeOptions,
71
+ type UseDisputeResult,
72
+ } from "./useDispute.js";
73
+
74
+ // Wallet bridge
75
+ export {
76
+ useWalletSigner,
77
+ type UseWalletSignerOptions,
78
+ type UseWalletSignerResult,
79
+ type WalletSignerAdapter,
80
+ } from "./useWalletSigner.js";
81
+
82
+ // Referrer earnings (P6.2-gated)
83
+ export {
84
+ useReferrerEarnings,
85
+ type ReferrerHire,
86
+ type UseReferrerEarningsResult,
87
+ } from "./useReferrerEarnings.js";
88
+
89
+ // Shared query-key factory (consumers can invalidate sub-trees).
90
+ export { queryKeys, QUERY_KEY_ROOT } from "./internal.js";
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Internal helpers shared by the headless hooks.
3
+ *
4
+ * - A namespaced TanStack Query key factory so every hook's cache entries are
5
+ * stable, collision-free, and individually invalidatable.
6
+ * - Tiny guards that turn a missing write client / signer into a clear,
7
+ * catalog-routed error (never a `null.method()` crash) BEFORE a mutation runs.
8
+ *
9
+ * SSR-safe: pure functions, no `window`/`document`, no module-scope side
10
+ * effects.
11
+ *
12
+ * @module hooks/internal
13
+ */
14
+ import { t } from "../strings/index.js";
15
+ import type { Address, MarketplaceClient } from "../types.js";
16
+
17
+ /** Root namespace for every cache key this package writes. */
18
+ export const QUERY_KEY_ROOT = "agenc" as const;
19
+
20
+ /**
21
+ * Stable, hierarchical TanStack Query keys. Hooks build their keys ONLY through
22
+ * this factory so a consumer (or a hook) can invalidate a whole sub-tree
23
+ * (`["agenc", "listings"]`) or one entity (`["agenc", "listing", pda]`).
24
+ *
25
+ * `JSON.stringify` is intentionally NOT used — TanStack compares keys
26
+ * structurally, so passing the raw filter object keeps equality correct for
27
+ * `bigint`/`Address` values without a serialization step.
28
+ */
29
+ export const queryKeys = {
30
+ /** All listings list queries (with their filter object as the leaf). */
31
+ listings: (filter?: unknown) =>
32
+ [QUERY_KEY_ROOT, "listings", filter ?? null] as const,
33
+ /** One listing + its joined provider/track-record/moderation. */
34
+ listing: (pda: string) => [QUERY_KEY_ROOT, "listing", pda] as const,
35
+ /** One agent's indexer track record. */
36
+ agentTrackRecord: (agentPda: string) =>
37
+ [QUERY_KEY_ROOT, "agentTrackRecord", agentPda] as const,
38
+ /** One task's status (read via transport / svm decode). */
39
+ taskStatus: (taskPda: string) =>
40
+ [QUERY_KEY_ROOT, "taskStatus", taskPda] as const,
41
+ /** One task's dispute record. */
42
+ dispute: (taskPda: string) => [QUERY_KEY_ROOT, "dispute", taskPda] as const,
43
+ /** One referrer wallet's earnings (P6.2-gated; see useReferrerEarnings). */
44
+ referrerEarnings: (wallet: string) =>
45
+ [QUERY_KEY_ROOT, "referrerEarnings", wallet] as const,
46
+ } as const;
47
+
48
+ /**
49
+ * Assert a write client exists, returning it narrowed to non-null. Throws a
50
+ * clear, catalog-routed error when the provider was configured read-only (no
51
+ * `client` and no resolvable `rpcUrl` + `signer`).
52
+ *
53
+ * Mutating hooks call this at the top of their `mutationFn` so the failure is a
54
+ * descriptive Error in the mutation's `error` channel — never a crash.
55
+ *
56
+ * @throws Error (`provider.missingWriteClient`) when `client` is null.
57
+ */
58
+ export function requireClient(
59
+ client: MarketplaceClient | null,
60
+ ): MarketplaceClient {
61
+ if (client === null) {
62
+ throw new Error(t("provider.missingWriteClient"));
63
+ }
64
+ return client;
65
+ }
66
+
67
+ /** Coerce an `Address | string` to its string form for use as a cache key. */
68
+ export function pdaKey(pda: Address | string): string {
69
+ return String(pda);
70
+ }
@@ -0,0 +1,166 @@
1
+ /**
2
+ * `useAgentTrackRecord(agentPda)` — provider reputation hook (PARTIAL, P6.6).
3
+ *
4
+ * Reads the indexer's reconstructed track record for an agent and projects the
5
+ * `{ completionRate, disputeRate, slashHistory, recentOutcomes }` contract.
6
+ *
7
+ * ## P6.6 scope (honest about what is and isn't available)
8
+ *
9
+ * The v1 indexer record (`IndexerAgentTrackRecord`) is event-reconstructed and
10
+ * exposes raw COUNTS: `completions`, `disputesInitiated`, `disputesLost`, and a
11
+ * `slashHistory`. It does NOT yet expose the denominators a true RATE needs
12
+ * (total tasks taken, total disputes faced) — that aggregation lands in
13
+ * PLAN.md P6.6. So:
14
+ * - `slashHistory` and the dispute COUNTS are real today (passed through);
15
+ * - `completionRate` / `disputeRate` are RATIOS and are only meaningful once a
16
+ * denominator exists. Today they are computed from the available counts where
17
+ * a denominator is inferable (completions vs. completions+disputesLost as a
18
+ * conservative proxy) and otherwise `null`. Treat them as provisional until
19
+ * P6.6. The `partial` flag is the audit signal — `true` today.
20
+ * - `recentOutcomes` is reconstructed from `slashHistory` (the only per-event
21
+ * stream in v1); a richer outcome feed lands with P6.6.
22
+ *
23
+ * Indexer-native: the gPA fallback has no aggregated track record, so under it
24
+ * `read.agentTrackRecord` throws `ReadTransportUnsupportedError` and this hook
25
+ * surfaces that error (a track record is not reconstructable trustlessly).
26
+ *
27
+ * @module hooks/useAgentTrackRecord
28
+ */
29
+ import { useQuery } from "@tanstack/react-query";
30
+ import { useAgencContext } from "../provider/context.js";
31
+ import type { Address, IndexerAgentTrackRecord } from "../types.js";
32
+ import { pdaKey, queryKeys } from "./internal.js";
33
+
34
+ /** A reconstructed outcome event (v1: derived from the slash history). */
35
+ export interface TrackRecordOutcome {
36
+ /** Outcome kind. v1 only reconstructs slashes from the event stream. */
37
+ kind: "slash";
38
+ /** The raw slash event from the indexer record. */
39
+ event: IndexerAgentTrackRecord["slashHistory"][number];
40
+ }
41
+
42
+ /** The projected track record {@link useAgentTrackRecord} returns. */
43
+ export interface AgentTrackRecord {
44
+ /** The agent PDA. */
45
+ agent: Address | string;
46
+ /** Completed-task count (real today). */
47
+ completions: number;
48
+ /** Disputes the agent initiated (real today). */
49
+ disputesInitiated: number;
50
+ /** Disputes the agent lost (real today). */
51
+ disputesLost: number;
52
+ /**
53
+ * Completion rate in `[0,1]`, or `null` when no denominator is inferable.
54
+ * PROVISIONAL until P6.6 supplies the true total-tasks denominator.
55
+ */
56
+ completionRate: number | null;
57
+ /**
58
+ * Dispute rate in `[0,1]`, or `null` when no denominator is inferable.
59
+ * PROVISIONAL until P6.6.
60
+ */
61
+ disputeRate: number | null;
62
+ /** Reconstructed slash history (real today). */
63
+ slashHistory: IndexerAgentTrackRecord["slashHistory"];
64
+ /** Reconstructed recent outcomes (v1: from slash history). */
65
+ recentOutcomes: TrackRecordOutcome[];
66
+ /** True while any rate is provisional/derived (P6.6 audit signal). */
67
+ partial: boolean;
68
+ }
69
+
70
+ /** Options for {@link useAgentTrackRecord}. */
71
+ export interface UseAgentTrackRecordOptions {
72
+ /** Disable the query. Default `true` when `agentPda` is set. */
73
+ enabled?: boolean;
74
+ }
75
+
76
+ /** Return value of {@link useAgentTrackRecord}. */
77
+ export interface UseAgentTrackRecordResult {
78
+ /** The projected track record, or null until loaded. */
79
+ trackRecord: AgentTrackRecord | null;
80
+ /** Convenience: `trackRecord?.completionRate ?? null`. */
81
+ completionRate: number | null;
82
+ /** Convenience: `trackRecord?.disputeRate ?? null`. */
83
+ disputeRate: number | null;
84
+ /** Convenience: `trackRecord?.slashHistory ?? []`. */
85
+ slashHistory: IndexerAgentTrackRecord["slashHistory"];
86
+ /** Convenience: `trackRecord?.recentOutcomes ?? []`. */
87
+ recentOutcomes: TrackRecordOutcome[];
88
+ /** True while loading. */
89
+ isLoading: boolean;
90
+ /** The error (e.g. `ReadTransportUnsupportedError` under gPA), or null. */
91
+ error: Error | null;
92
+ /** Force a refetch. */
93
+ refetch: () => void;
94
+ }
95
+
96
+ /**
97
+ * Project the raw indexer record into the partial track-record contract. Kept
98
+ * exported + pure so structural tests can assert the projection directly.
99
+ */
100
+ export function projectTrackRecord(
101
+ raw: IndexerAgentTrackRecord,
102
+ ): AgentTrackRecord {
103
+ const completions = raw.completions;
104
+ const disputesLost = raw.disputesLost;
105
+ // Conservative proxy denominator: settled outcomes we can SEE (completions +
106
+ // lost disputes). This is NOT the true total-tasks denominator (P6.6); when
107
+ // it is zero there is nothing to rate, so the rates are null.
108
+ const settledKnown = completions + disputesLost;
109
+ const completionRate =
110
+ settledKnown > 0 ? completions / settledKnown : null;
111
+ const disputeRate =
112
+ settledKnown > 0 ? disputesLost / settledKnown : null;
113
+
114
+ return {
115
+ agent: raw.agent,
116
+ completions,
117
+ disputesInitiated: raw.disputesInitiated,
118
+ disputesLost,
119
+ completionRate,
120
+ disputeRate,
121
+ slashHistory: raw.slashHistory,
122
+ recentOutcomes: raw.slashHistory.map((event) => ({
123
+ kind: "slash" as const,
124
+ event,
125
+ })),
126
+ // Always partial in v1: every rate is a proxy until P6.6 lands the real
127
+ // denominators and outcome feed.
128
+ partial: true,
129
+ };
130
+ }
131
+
132
+ /**
133
+ * Read an agent's (partial) track record.
134
+ *
135
+ * @param agentPda - The AgentRegistration PDA (falsy disables the hook).
136
+ * @param options - `enabled` override.
137
+ * @returns {@link UseAgentTrackRecordResult}.
138
+ */
139
+ export function useAgentTrackRecord(
140
+ agentPda: Address | string | undefined | null,
141
+ options?: UseAgentTrackRecordOptions,
142
+ ): UseAgentTrackRecordResult {
143
+ const { read } = useAgencContext();
144
+ const enabled = (options?.enabled ?? true) && Boolean(agentPda);
145
+
146
+ const query = useQuery<AgentTrackRecord, Error>({
147
+ queryKey: queryKeys.agentTrackRecord(agentPda ? pdaKey(agentPda) : ""),
148
+ enabled,
149
+ queryFn: async () => {
150
+ const raw = await read.agentTrackRecord(agentPda as Address | string);
151
+ return projectTrackRecord(raw);
152
+ },
153
+ });
154
+
155
+ const tr = query.data ?? null;
156
+ return {
157
+ trackRecord: tr,
158
+ completionRate: tr?.completionRate ?? null,
159
+ disputeRate: tr?.disputeRate ?? null,
160
+ slashHistory: tr?.slashHistory ?? [],
161
+ recentOutcomes: tr?.recentOutcomes ?? [],
162
+ isLoading: query.isLoading,
163
+ error: query.error ?? null,
164
+ refetch: () => void query.refetch(),
165
+ };
166
+ }
@@ -0,0 +1,130 @@
1
+ /**
2
+ * `useDispute(taskPda)` — dispute entry point + state for one task.
3
+ *
4
+ * Reads the task's `Dispute` account (via an injected reader seam — same reason
5
+ * as `useTaskStatus`: the unified read transport has no raw account fetch and
6
+ * litesvm has no RPC) and exposes `initiate(...)` which opens a dispute through
7
+ * the write client (`client.initiateDispute`). Typed `AgencError`s surface
8
+ * UNTOUCHED.
9
+ *
10
+ * @module hooks/useDispute
11
+ */
12
+ import { useMutation, useQuery } from "@tanstack/react-query";
13
+ import { useCallback } from "react";
14
+ import {
15
+ type Dispute,
16
+ type facade as facadeNs,
17
+ } from "@tetsuo-ai/marketplace-sdk";
18
+ import { useAgencContext } from "../provider/context.js";
19
+ import type { Address } from "../types.js";
20
+ import { pdaKey, queryKeys, requireClient } from "./internal.js";
21
+
22
+ /** Reads a Dispute account for a task, returning the decoded value or null. */
23
+ export type DisputeReader = (
24
+ taskPda: Address | string,
25
+ ) => Promise<Dispute | null>;
26
+
27
+ /**
28
+ * Per-call input for `initiate(...)`. This is the SDK `facade.initiateDispute`
29
+ * input minus the fee-payer `authority` signer (defaulted to the client's
30
+ * signer; pass it to override). `task` is bound at hook construction.
31
+ */
32
+ export type InitiateDisputeInput = Omit<
33
+ Parameters<typeof facadeNs.initiateDispute>[0],
34
+ "task" | "authority"
35
+ > & {
36
+ /** Override the initiator authority signer (defaults to the client signer). */
37
+ authority?: Parameters<typeof facadeNs.initiateDispute>[0]["authority"];
38
+ };
39
+
40
+ /** Lifecycle status of the initiate mutation. */
41
+ export type DisputeStatus = "idle" | "pending" | "success" | "error";
42
+
43
+ /** Options for {@link useDispute}. */
44
+ export interface UseDisputeOptions {
45
+ /** How to read the Dispute account. Without it the read stays idle. */
46
+ disputeReader?: DisputeReader;
47
+ /** Disable the read query. Default `true` when `taskPda` + reader exist. */
48
+ enabled?: boolean;
49
+ }
50
+
51
+ /** Return value of {@link useDispute}. */
52
+ export interface UseDisputeResult {
53
+ /** The decoded dispute, or null (none open / not yet read). */
54
+ dispute: Dispute | null;
55
+ /** Open a dispute. Resolves to the tx signature; rejects with `AgencError`. */
56
+ initiate: (input: InitiateDisputeInput) => Promise<string>;
57
+ /** Status of the initiate mutation. */
58
+ status: DisputeStatus;
59
+ /** Signature of the last successful initiate, or null. */
60
+ signature: string | null;
61
+ /** The read OR initiate error, or null. */
62
+ error: Error | null;
63
+ /** True while reading the dispute. */
64
+ isLoading: boolean;
65
+ /** Force a dispute refetch. */
66
+ refetch: () => void;
67
+ /** Reset the initiate mutation. */
68
+ reset: () => void;
69
+ }
70
+
71
+ /**
72
+ * Dispute entry + state for one task.
73
+ *
74
+ * @param taskPda - The Task PDA (falsy disables the read).
75
+ * @param options - Reader + enabled.
76
+ * @returns {@link UseDisputeResult}.
77
+ */
78
+ export function useDispute(
79
+ taskPda: Address | string | undefined | null,
80
+ options?: UseDisputeOptions,
81
+ ): UseDisputeResult {
82
+ const ctx = useAgencContext();
83
+ const reader = options?.disputeReader;
84
+ const enabled =
85
+ (options?.enabled ?? true) && Boolean(taskPda) && Boolean(reader);
86
+
87
+ const read = useQuery<Dispute | null, Error>({
88
+ queryKey: queryKeys.dispute(taskPda ? pdaKey(taskPda) : ""),
89
+ enabled,
90
+ queryFn: () => reader!(taskPda as Address | string),
91
+ });
92
+
93
+ const mutation = useMutation<string, Error, InitiateDisputeInput>({
94
+ mutationFn: async (input) => {
95
+ const client = requireClient(ctx.client);
96
+ const { signature } = await client.initiateDispute({
97
+ ...input,
98
+ task: taskPda as Address,
99
+ authority: input.authority ?? client.signer,
100
+ } as Parameters<typeof facadeNs.initiateDispute>[0]);
101
+ // A new dispute exists — refresh the read.
102
+ void read.refetch();
103
+ return signature;
104
+ },
105
+ });
106
+
107
+ const initiate = useCallback(
108
+ (input: InitiateDisputeInput) => mutation.mutateAsync(input),
109
+ [mutation],
110
+ );
111
+
112
+ const status: DisputeStatus = mutation.isPending
113
+ ? "pending"
114
+ : mutation.isError
115
+ ? "error"
116
+ : mutation.isSuccess
117
+ ? "success"
118
+ : "idle";
119
+
120
+ return {
121
+ dispute: read.data ?? null,
122
+ initiate,
123
+ status,
124
+ signature: mutation.data ?? null,
125
+ error: mutation.error ?? read.error ?? null,
126
+ isLoading: read.isLoading,
127
+ refetch: () => void read.refetch(),
128
+ reset: mutation.reset,
129
+ };
130
+ }