@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,294 @@
1
+ import { DecodedProgramAccount, ServiceListing, ListActiveListingsOptions, IndexerAgentTrackRecord, IndexerListing, Task, TaskStatus } from '@tetsuo-ai/marketplace-sdk';
2
+ import { Address, TransactionSigner } from '@solana/kit';
3
+ export { A as AcceptInput, a as AgentTrackRecord, b as AnyHireInput, D as DisputeReader, c as DisputeStatus, H as HireInput, d as HireResult, e as HireStatus, f as HumanlessHireInput, I as InitiateDisputeInput, R as RejectInput, g as RequestChangesInput, h as ReviewAction, i as ReviewStatus, T as TrackRecordOutcome, U as UseAgentTrackRecordOptions, j as UseAgentTrackRecordResult, k as UseDisputeOptions, l as UseDisputeResult, m as UseHireResult, n as UseSubmissionReviewResult, p as projectTrackRecord, u as useAgentTrackRecord, o as useDispute, q as useHire, r as useSubmissionReview } from '../useAgentTrackRecord-BLf1nrbu.js';
4
+
5
+ /** A decoded active listing row (address + decoded account). */
6
+ type ListingRow = DecodedProgramAccount<ServiceListing>;
7
+ /** Filter for {@link useListings}. Mirrors the SDK's `ListActiveListingsOptions`. */
8
+ type UseListingsFilter = ListActiveListingsOptions;
9
+ /** Options for {@link useListings}. */
10
+ interface UseListingsOptions {
11
+ /** Rows revealed per page / per `fetchMore()` call. Default `12`. */
12
+ pageSize?: number;
13
+ /**
14
+ * Disable the query (e.g. until a filter is ready). When `false` the hook
15
+ * returns the idle state and makes no request. Default `true`.
16
+ */
17
+ enabled?: boolean;
18
+ }
19
+ /** Return value of {@link useListings}. */
20
+ interface UseListingsResult {
21
+ /** The currently-revealed window of listings (grows via `fetchMore`). */
22
+ listings: ListingRow[];
23
+ /** Total active listings the transport returned (the full fetched set). */
24
+ total: number;
25
+ /** True while the underlying fetch is in flight (first load / refetch). */
26
+ isLoading: boolean;
27
+ /** The fetch error (typed `AgencError` for on-chain failures), or null. */
28
+ error: Error | null;
29
+ /** Whether more rows remain in the fetched set to reveal. */
30
+ hasMore: boolean;
31
+ /** Reveal the next `pageSize` rows from the fetched set. No-op when exhausted. */
32
+ fetchMore: () => void;
33
+ /** Force a fresh fetch from the transport. */
34
+ refetch: () => void;
35
+ }
36
+ /**
37
+ * Read active service listings for a grid.
38
+ *
39
+ * @param filter - Optional provider/category/state filter (SDK semantics).
40
+ * @param options - Page size + enabled flag.
41
+ * @returns {@link UseListingsResult}.
42
+ *
43
+ * @example
44
+ * ```tsx
45
+ * const { listings, isLoading, fetchMore, hasMore } = useListings({
46
+ * category: "code-generation",
47
+ * });
48
+ * ```
49
+ */
50
+ declare function useListings(filter?: UseListingsFilter, options?: UseListingsOptions): UseListingsResult;
51
+
52
+ /** The joined detail payload {@link useListing} resolves. */
53
+ interface ListingDetail {
54
+ /** The listing PDA. */
55
+ address: Address;
56
+ /** The decoded on-chain `ServiceListing`. */
57
+ listing: ServiceListing;
58
+ /** The provider's agent PDA (`ServiceListing.providerAgent`). */
59
+ provider: Address;
60
+ /**
61
+ * The provider's indexer track record, or `null` when unavailable (the gPA
62
+ * fallback has no trustless aggregated equivalent).
63
+ */
64
+ trackRecord: IndexerAgentTrackRecord | null;
65
+ /**
66
+ * The listing's indexer projection (carries `metadataValid`,
67
+ * `metadataIssues`, the pinned `specHash`), or `null` under the gPA fallback.
68
+ * The v1 read model does not yet project a standalone attestation verdict.
69
+ */
70
+ moderation: IndexerListing | null;
71
+ }
72
+ /** Options for {@link useListing}. */
73
+ interface UseListingOptions {
74
+ /** Disable the query (no `pda` yet, etc.). Default `true` when `pda` is set. */
75
+ enabled?: boolean;
76
+ }
77
+ /** Return value of {@link useListing}. */
78
+ interface UseListingResult {
79
+ /** The joined detail, or null until loaded. */
80
+ detail: ListingDetail | null;
81
+ /** The decoded listing, or null until loaded (convenience projection). */
82
+ listing: ServiceListing | null;
83
+ /** The provider agent PDA, or null until loaded. */
84
+ provider: Address | null;
85
+ /** The provider's track record, or null (unavailable / not yet loaded). */
86
+ trackRecord: IndexerAgentTrackRecord | null;
87
+ /** The listing's indexer/moderation projection, or null. */
88
+ moderation: IndexerListing | null;
89
+ /** True while loading. */
90
+ isLoading: boolean;
91
+ /** The error, or null. */
92
+ error: Error | null;
93
+ /** Force a refetch. */
94
+ refetch: () => void;
95
+ }
96
+ /**
97
+ * Read one listing and join its provider track record + moderation projection.
98
+ *
99
+ * @param pda - The ServiceListing PDA (string or Address). When falsy the query
100
+ * is disabled.
101
+ * @param options - `enabled` override.
102
+ * @returns {@link UseListingResult}.
103
+ */
104
+ declare function useListing(pda: Address | string | undefined | null, options?: UseListingOptions): UseListingResult;
105
+
106
+ /** Reads a Task account, returning the decoded {@link Task} or null if absent. */
107
+ type TaskReader = (pda: Address | string) => Promise<Task | null>;
108
+ /**
109
+ * A single coordination event observed for the watched task. Kept loosely typed
110
+ * (the SDK's `AgencEvent` union) so this hook does not pin the event schema.
111
+ */
112
+ type ObservedEvent = unknown;
113
+ /**
114
+ * An async source of coordination events for the watched task. Pass the result
115
+ * of the SDK's `subscribeMarketplaceEvents(...)` (already address-filtered) or
116
+ * any async iterable. Optional.
117
+ */
118
+ type TaskEventsSource = AsyncIterable<ObservedEvent>;
119
+ /** Options for {@link useTaskStatus}. */
120
+ interface UseTaskStatusOptions {
121
+ /**
122
+ * How to read the Task account. REQUIRED for any live status — without it the
123
+ * hook stays idle. See the module doc for wiring patterns.
124
+ */
125
+ taskReader?: TaskReader;
126
+ /**
127
+ * Optional event source. When given, observed events are appended to
128
+ * `events` and each triggers a refetch. Drained in a browser-only effect and
129
+ * aborted on unmount.
130
+ */
131
+ events?: TaskEventsSource;
132
+ /**
133
+ * Stop polling once the task reaches this status (in addition to terminal
134
+ * statuses). Useful to await a specific transition (e.g. `Completed`).
135
+ */
136
+ targetStatus?: TaskStatus;
137
+ /** Poll interval in ms while non-terminal. Default `2000`. */
138
+ pollIntervalMs?: number;
139
+ /** Disable the hook entirely. Default `true` when `taskPda` + reader exist. */
140
+ enabled?: boolean;
141
+ }
142
+ /** Return value of {@link useTaskStatus}. */
143
+ interface UseTaskStatusResult {
144
+ /** The decoded Task, or null until first read. */
145
+ task: Task | null;
146
+ /** The task status, or null until first read. */
147
+ status: TaskStatus | null;
148
+ /**
149
+ * The submission projection. v1 surfaces the task's on-chain `result` bytes
150
+ * (the worker's submitted result) once present; a richer submission read
151
+ * lands with the indexer projection. `null` until a result exists.
152
+ */
153
+ submission: Uint8Array | null;
154
+ /** Coordination events observed for this task (chronological). */
155
+ events: ObservedEvent[];
156
+ /** True while the first read is in flight. */
157
+ isLoading: boolean;
158
+ /** The read error, or null. */
159
+ error: Error | null;
160
+ /** Force a refetch. */
161
+ refetch: () => void;
162
+ }
163
+ /**
164
+ * Watch a task's status.
165
+ *
166
+ * @param taskPda - The Task PDA to watch (falsy disables the hook).
167
+ * @param options - Reader, event source, target status, poll interval.
168
+ * @returns {@link UseTaskStatusResult}.
169
+ */
170
+ declare function useTaskStatus(taskPda: Address | string | undefined | null, options?: UseTaskStatusOptions): UseTaskStatusResult;
171
+
172
+ /**
173
+ * The minimal adapter shape this hook bridges. The forthcoming
174
+ * `@tetsuo-ai/signer-adapters` hook is expected to return exactly this shape
175
+ * (its `signerFromWalletAccount(...)` resolves the `signer`); until it ships,
176
+ * any object matching this interface works.
177
+ */
178
+ interface WalletSignerAdapter {
179
+ /** The resolved kit signer, or null when no wallet is connected. */
180
+ signer: TransactionSigner | null;
181
+ /** Whether a wallet is currently connected. */
182
+ connected?: boolean;
183
+ /** Trigger the wallet connect flow (browser-only). Optional. */
184
+ connect?: () => void | Promise<void>;
185
+ }
186
+ /** Options for {@link useWalletSigner}. */
187
+ interface UseWalletSignerOptions {
188
+ /**
189
+ * A wallet adapter (e.g. the signer-adapters hook's result). When omitted the
190
+ * hook falls back to the provider's `config.signer`.
191
+ */
192
+ adapter?: WalletSignerAdapter;
193
+ }
194
+ /** Return value of {@link useWalletSigner}. */
195
+ interface UseWalletSignerResult {
196
+ /** The resolved kit `TransactionSigner`, or null. */
197
+ signer: TransactionSigner | null;
198
+ /** Whether a signer is available (adapter-connected or provider-configured). */
199
+ connected: boolean;
200
+ /** Trigger the wallet connect flow. No-op when no adapter `connect` exists. */
201
+ connect: () => void | Promise<void>;
202
+ }
203
+ /**
204
+ * Resolve the active signer for write operations.
205
+ *
206
+ * @param options - Optional wallet adapter; falls back to the provider signer.
207
+ * @returns {@link UseWalletSignerResult}.
208
+ *
209
+ * @example
210
+ * ```tsx
211
+ * // Once @tetsuo-ai/signer-adapters ships:
212
+ * const adapter = useWalletStandardSigner(); // returns WalletSignerAdapter
213
+ * const { signer, connected, connect } = useWalletSigner({ adapter });
214
+ * ```
215
+ */
216
+ declare function useWalletSigner(options?: UseWalletSignerOptions): UseWalletSignerResult;
217
+
218
+ /** A single referral-earning hire (shape defined now; populated post-P6.2). */
219
+ interface ReferrerHire {
220
+ /** The minted Task PDA of the referred hire. */
221
+ taskPda: string;
222
+ /** The HireRecord PDA carrying the snapshotted referrer fields. */
223
+ hireRecordPda: string;
224
+ /** Referral fee earned on this hire, in lamports. */
225
+ feeLamports: bigint;
226
+ /** Transaction signature of the hire. */
227
+ signature: string;
228
+ }
229
+ /** Return value of {@link useReferrerEarnings}. */
230
+ interface UseReferrerEarningsResult {
231
+ /**
232
+ * Whether referral settlement is live on this cluster. ALWAYS `false` today
233
+ * (the P6.2 gate). When false, the numbers below are the documented not-live
234
+ * zero state, not real data.
235
+ */
236
+ live: boolean;
237
+ /** Total lamports earned. `0n` while not live (never fabricated). */
238
+ totalLamports: bigint;
239
+ /** Per-hire earnings. `[]` while not live. */
240
+ hires: ReferrerHire[];
241
+ /** True while a (post-P6.2) fetch is in flight. Always false today. */
242
+ isLoading: boolean;
243
+ /** The fetch error, or null. */
244
+ error: Error | null;
245
+ /**
246
+ * Human-readable reason the data is not live (the capability reason). Present
247
+ * while `live` is false.
248
+ */
249
+ reason?: string;
250
+ /** Force a refetch (no-op while not live). */
251
+ refetch: () => void;
252
+ }
253
+ /**
254
+ * Read a referrer wallet's earnings.
255
+ *
256
+ * @param wallet - The referrer wallet (base58 / Address). Falsy disables the
257
+ * (future) fetch; the not-live state is still returned.
258
+ * @returns {@link UseReferrerEarningsResult} — the not-live zero state today.
259
+ *
260
+ * @example
261
+ * ```tsx
262
+ * const { live, totalLamports, hires, reason } = useReferrerEarnings(myWallet);
263
+ * // today: live === false, totalLamports === 0n, hires === []
264
+ * ```
265
+ */
266
+ declare function useReferrerEarnings(wallet: Address | string | undefined | null): UseReferrerEarningsResult;
267
+
268
+ /** Root namespace for every cache key this package writes. */
269
+ declare const QUERY_KEY_ROOT: "agenc";
270
+ /**
271
+ * Stable, hierarchical TanStack Query keys. Hooks build their keys ONLY through
272
+ * this factory so a consumer (or a hook) can invalidate a whole sub-tree
273
+ * (`["agenc", "listings"]`) or one entity (`["agenc", "listing", pda]`).
274
+ *
275
+ * `JSON.stringify` is intentionally NOT used — TanStack compares keys
276
+ * structurally, so passing the raw filter object keeps equality correct for
277
+ * `bigint`/`Address` values without a serialization step.
278
+ */
279
+ declare const queryKeys: {
280
+ /** All listings list queries (with their filter object as the leaf). */
281
+ readonly listings: (filter?: unknown) => readonly ["agenc", "listings", {} | null];
282
+ /** One listing + its joined provider/track-record/moderation. */
283
+ readonly listing: (pda: string) => readonly ["agenc", "listing", string];
284
+ /** One agent's indexer track record. */
285
+ readonly agentTrackRecord: (agentPda: string) => readonly ["agenc", "agentTrackRecord", string];
286
+ /** One task's status (read via transport / svm decode). */
287
+ readonly taskStatus: (taskPda: string) => readonly ["agenc", "taskStatus", string];
288
+ /** One task's dispute record. */
289
+ readonly dispute: (taskPda: string) => readonly ["agenc", "dispute", string];
290
+ /** One referrer wallet's earnings (P6.2-gated; see useReferrerEarnings). */
291
+ readonly referrerEarnings: (wallet: string) => readonly ["agenc", "referrerEarnings", string];
292
+ };
293
+
294
+ export { type ListingDetail, type ListingRow, type ObservedEvent, QUERY_KEY_ROOT, type ReferrerHire, type TaskEventsSource, type TaskReader, type UseListingOptions, type UseListingResult, type UseListingsFilter, type UseListingsOptions, type UseListingsResult, type UseReferrerEarningsResult, type UseTaskStatusOptions, type UseTaskStatusResult, type UseWalletSignerOptions, type UseWalletSignerResult, type WalletSignerAdapter, queryKeys, useListing, useListings, useReferrerEarnings, useTaskStatus, useWalletSigner };
@@ -0,0 +1,339 @@
1
+ import { ReadTransportUnsupportedError } from '../chunk-ABS77JB2.js';
2
+ import { useAgencContext, queryKeys, pdaKey, requireClient } from '../chunk-YORZNYZZ.js';
3
+ export { QUERY_KEY_ROOT, queryKeys, useHire, useWalletSigner } from '../chunk-YORZNYZZ.js';
4
+ import { t } from '../chunk-GN5DYVN5.js';
5
+ import { useQuery, useMutation } from '@tanstack/react-query';
6
+ import { useState, useMemo, useCallback, useRef, useEffect } from 'react';
7
+ import { TaskStatus, facade } from '@tetsuo-ai/marketplace-sdk';
8
+
9
+ var DEFAULT_PAGE_SIZE = 12;
10
+ function useListings(filter, options) {
11
+ const { read } = useAgencContext();
12
+ const pageSize = options?.pageSize ?? DEFAULT_PAGE_SIZE;
13
+ const enabled = options?.enabled ?? true;
14
+ const query = useQuery({
15
+ queryKey: queryKeys.listings(filter),
16
+ queryFn: () => read.listActiveListings(filter),
17
+ enabled
18
+ });
19
+ const [visible, setVisible] = useState(pageSize);
20
+ const all = query.data ?? [];
21
+ const windowSize = Math.min(Math.max(visible, pageSize), all.length);
22
+ const listings = useMemo(
23
+ () => all.slice(0, windowSize),
24
+ [all, windowSize]
25
+ );
26
+ const fetchMore = useCallback(() => {
27
+ setVisible((current) => current + pageSize);
28
+ }, [pageSize]);
29
+ const refetch = useCallback(() => {
30
+ setVisible(pageSize);
31
+ void query.refetch();
32
+ }, [pageSize, query]);
33
+ return {
34
+ listings,
35
+ total: all.length,
36
+ isLoading: query.isLoading,
37
+ error: query.error ?? null,
38
+ hasMore: windowSize < all.length,
39
+ fetchMore,
40
+ refetch
41
+ };
42
+ }
43
+ function useListing(pda, options) {
44
+ const { read } = useAgencContext();
45
+ const enabled = (options?.enabled ?? true) && Boolean(pda);
46
+ const query = useQuery({
47
+ queryKey: queryKeys.listing(pda ? pdaKey(pda) : ""),
48
+ enabled,
49
+ queryFn: async () => {
50
+ const result = await read.getListing(pda);
51
+ const provider = result.account.providerAgent;
52
+ let trackRecord = null;
53
+ try {
54
+ trackRecord = await read.agentTrackRecord(provider);
55
+ } catch (err) {
56
+ if (!(err instanceof ReadTransportUnsupportedError)) throw err;
57
+ }
58
+ return {
59
+ address: result.address,
60
+ listing: result.account,
61
+ provider,
62
+ trackRecord,
63
+ moderation: result.indexer ?? null
64
+ };
65
+ }
66
+ });
67
+ const detail = query.data ?? null;
68
+ return {
69
+ detail,
70
+ listing: detail?.listing ?? null,
71
+ provider: detail?.provider ?? null,
72
+ trackRecord: detail?.trackRecord ?? null,
73
+ moderation: detail?.moderation ?? null,
74
+ isLoading: query.isLoading,
75
+ error: query.error ?? null,
76
+ refetch: () => void query.refetch()
77
+ };
78
+ }
79
+ function projectTrackRecord(raw) {
80
+ const completions = raw.completions;
81
+ const disputesLost = raw.disputesLost;
82
+ const settledKnown = completions + disputesLost;
83
+ const completionRate = settledKnown > 0 ? completions / settledKnown : null;
84
+ const disputeRate = settledKnown > 0 ? disputesLost / settledKnown : null;
85
+ return {
86
+ agent: raw.agent,
87
+ completions,
88
+ disputesInitiated: raw.disputesInitiated,
89
+ disputesLost,
90
+ completionRate,
91
+ disputeRate,
92
+ slashHistory: raw.slashHistory,
93
+ recentOutcomes: raw.slashHistory.map((event) => ({
94
+ kind: "slash",
95
+ event
96
+ })),
97
+ // Always partial in v1: every rate is a proxy until P6.6 lands the real
98
+ // denominators and outcome feed.
99
+ partial: true
100
+ };
101
+ }
102
+ function useAgentTrackRecord(agentPda, options) {
103
+ const { read } = useAgencContext();
104
+ const enabled = (options?.enabled ?? true) && Boolean(agentPda);
105
+ const query = useQuery({
106
+ queryKey: queryKeys.agentTrackRecord(agentPda ? pdaKey(agentPda) : ""),
107
+ enabled,
108
+ queryFn: async () => {
109
+ const raw = await read.agentTrackRecord(agentPda);
110
+ return projectTrackRecord(raw);
111
+ }
112
+ });
113
+ const tr = query.data ?? null;
114
+ return {
115
+ trackRecord: tr,
116
+ completionRate: tr?.completionRate ?? null,
117
+ disputeRate: tr?.disputeRate ?? null,
118
+ slashHistory: tr?.slashHistory ?? [],
119
+ recentOutcomes: tr?.recentOutcomes ?? [],
120
+ isLoading: query.isLoading,
121
+ error: query.error ?? null,
122
+ refetch: () => void query.refetch()
123
+ };
124
+ }
125
+ var TERMINAL_STATUSES = /* @__PURE__ */ new Set([
126
+ TaskStatus.Completed,
127
+ TaskStatus.Cancelled,
128
+ TaskStatus.RejectFrozen
129
+ ]);
130
+ function hasResult(task) {
131
+ return task !== null && task.result.length > 0 && task.result.some((b) => b !== 0);
132
+ }
133
+ function useTaskStatus(taskPda, options) {
134
+ useAgencContext();
135
+ const reader = options?.taskReader;
136
+ const enabled = (options?.enabled ?? true) && Boolean(taskPda) && Boolean(reader);
137
+ const pollIntervalMs = options?.pollIntervalMs ?? 2e3;
138
+ const [events, setEvents] = useState([]);
139
+ const query = useQuery({
140
+ queryKey: queryKeys.taskStatus(taskPda ? pdaKey(taskPda) : ""),
141
+ enabled,
142
+ queryFn: () => reader(taskPda),
143
+ // Poll until terminal / target reached; then stop (return `false`).
144
+ refetchInterval: (q) => {
145
+ const task2 = q.state.data ?? null;
146
+ if (task2 === null) return pollIntervalMs;
147
+ if (TERMINAL_STATUSES.has(task2.status)) return false;
148
+ if (options?.targetStatus !== void 0 && task2.status === options.targetStatus) {
149
+ return false;
150
+ }
151
+ return pollIntervalMs;
152
+ }
153
+ });
154
+ const refetchRef = useRef(query.refetch);
155
+ refetchRef.current = query.refetch;
156
+ const eventsSource = options?.events;
157
+ useEffect(() => {
158
+ if (!eventsSource) return;
159
+ let cancelled = false;
160
+ (async () => {
161
+ try {
162
+ for await (const ev of eventsSource) {
163
+ if (cancelled) break;
164
+ setEvents((prev) => [...prev, ev]);
165
+ void refetchRef.current();
166
+ }
167
+ } catch {
168
+ }
169
+ })();
170
+ return () => {
171
+ cancelled = true;
172
+ };
173
+ }, [eventsSource]);
174
+ const task = query.data ?? null;
175
+ return {
176
+ task,
177
+ status: task?.status ?? null,
178
+ submission: hasResult(task) ? Uint8Array.from(task.result) : null,
179
+ events,
180
+ isLoading: query.isLoading,
181
+ error: query.error ?? null,
182
+ refetch: () => void query.refetch()
183
+ };
184
+ }
185
+ function statusOf(m) {
186
+ if (m.isPending) return "pending";
187
+ if (m.isError) return "error";
188
+ if (m.isSuccess) return "success";
189
+ return "idle";
190
+ }
191
+ function useSubmissionReview(taskPda) {
192
+ const ctx = useAgencContext();
193
+ const acceptMut = useMutation({
194
+ mutationFn: async (input) => {
195
+ const client = requireClient(ctx.client);
196
+ const { signature: signature2 } = await client.acceptTaskResult({
197
+ ...input,
198
+ task: taskPda,
199
+ creator: input.creator ?? client.signer
200
+ });
201
+ return signature2;
202
+ }
203
+ });
204
+ const rejectMut = useMutation({
205
+ mutationFn: async (input) => {
206
+ const client = requireClient(ctx.client);
207
+ const ix = await facade.rejectTaskResult({
208
+ ...input,
209
+ task: taskPda,
210
+ creator: input.creator ?? client.signer
211
+ });
212
+ const { signature: signature2 } = await client.send([ix]);
213
+ return signature2;
214
+ }
215
+ });
216
+ const requestChangesMut = useMutation({
217
+ mutationFn: async (input) => {
218
+ const client = requireClient(ctx.client);
219
+ const ix = await facade.requestChanges({
220
+ ...input,
221
+ task: taskPda,
222
+ creator: input.creator ?? client.signer
223
+ });
224
+ const { signature: signature2 } = await client.send([ix]);
225
+ return signature2;
226
+ }
227
+ });
228
+ const accept = useCallback(
229
+ (input) => acceptMut.mutateAsync(input),
230
+ [acceptMut]
231
+ );
232
+ const reject = useCallback(
233
+ (input) => rejectMut.mutateAsync(input),
234
+ [rejectMut]
235
+ );
236
+ const requestChanges = useCallback(
237
+ (input) => requestChangesMut.mutateAsync(input),
238
+ [requestChangesMut]
239
+ );
240
+ 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;
249
+ return {
250
+ accept,
251
+ reject,
252
+ requestChanges,
253
+ status,
254
+ error,
255
+ signature,
256
+ reset: () => {
257
+ acceptMut.reset();
258
+ rejectMut.reset();
259
+ requestChangesMut.reset();
260
+ }
261
+ };
262
+ }
263
+ function useDispute(taskPda, options) {
264
+ const ctx = useAgencContext();
265
+ const reader = options?.disputeReader;
266
+ const enabled = (options?.enabled ?? true) && Boolean(taskPda) && Boolean(reader);
267
+ const read = useQuery({
268
+ queryKey: queryKeys.dispute(taskPda ? pdaKey(taskPda) : ""),
269
+ enabled,
270
+ queryFn: () => reader(taskPda)
271
+ });
272
+ const mutation = useMutation({
273
+ mutationFn: async (input) => {
274
+ const client = requireClient(ctx.client);
275
+ const { signature } = await client.initiateDispute({
276
+ ...input,
277
+ task: taskPda,
278
+ authority: input.authority ?? client.signer
279
+ });
280
+ void read.refetch();
281
+ return signature;
282
+ }
283
+ });
284
+ const initiate = useCallback(
285
+ (input) => mutation.mutateAsync(input),
286
+ [mutation]
287
+ );
288
+ const status = mutation.isPending ? "pending" : mutation.isError ? "error" : mutation.isSuccess ? "success" : "idle";
289
+ return {
290
+ dispute: read.data ?? null,
291
+ initiate,
292
+ status,
293
+ signature: mutation.data ?? null,
294
+ error: mutation.error ?? read.error ?? null,
295
+ isLoading: read.isLoading,
296
+ refetch: () => void read.refetch(),
297
+ reset: mutation.reset
298
+ };
299
+ }
300
+ function useReferrerEarnings(wallet) {
301
+ const ctx = useAgencContext();
302
+ const capability = ctx.resolveReferrerCapability();
303
+ const enabled = capability.live && Boolean(wallet);
304
+ const query = useQuery(
305
+ {
306
+ queryKey: queryKeys.referrerEarnings(wallet ? pdaKey(wallet) : ""),
307
+ enabled,
308
+ queryFn: async () => {
309
+ throw new Error(
310
+ "useReferrerEarnings: the P6.2 referrer earnings path is not deployed; this query must never run while capability.live is false."
311
+ );
312
+ }
313
+ }
314
+ );
315
+ if (!capability.live) {
316
+ return {
317
+ live: false,
318
+ totalLamports: 0n,
319
+ hires: [],
320
+ isLoading: false,
321
+ error: null,
322
+ reason: capability.reason ?? t("referrer.notLiveReason"),
323
+ refetch: () => {
324
+ }
325
+ };
326
+ }
327
+ return {
328
+ live: true,
329
+ totalLamports: query.data?.totalLamports ?? 0n,
330
+ hires: query.data?.hires ?? [],
331
+ isLoading: query.isLoading,
332
+ error: query.error ?? null,
333
+ refetch: () => void query.refetch()
334
+ };
335
+ }
336
+
337
+ export { projectTrackRecord, useAgentTrackRecord, useDispute, useListing, useListings, useReferrerEarnings, useSubmissionReview, useTaskStatus };
338
+ //# sourceMappingURL=index.js.map
339
+ //# sourceMappingURL=index.js.map