@provex/react 1.2.5 → 1.3.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.
@@ -0,0 +1,2165 @@
1
+ import { createContext, useMemo, useContext, useCallback, useState, useRef, useEffect } from 'react';
2
+ import { QueryClient, QueryClientProvider, useQueryClient, useQuery } from '@tanstack/react-query';
3
+ import { createPublicClient, http, encodeAbiParameters, parseAbiParameters, zeroAddress, encodeFunctionData, decodeEventLog } from 'viem';
4
+ import { jsx, Fragment, jsxs } from 'react/jsx-runtime';
5
+ import { SUPPORTED_CURRENCIES, tickerToContractId } from '@provex/utils/currencies';
6
+ import { parseUnits, formatUnits } from '@provex/utils/units';
7
+ import { providerConfigs, providerKeyToContractId, computePayeeDetailsHash, tiers, verifiablePaymentMethods, getPlatformRisk, verifierGetsKey, isSubProviderKey, getParentProviderKey, getPaymentMethodName } from '@provex/utils/payment';
8
+ import { convertCurrencyToTokenOutput } from '@provex/utils/conversionRates';
9
+ import { getLatestContract, reclaimSigners } from '@provex/utils/contracts';
10
+ import { normalizeFeePrecision } from '@provex/utils/fees';
11
+ import { V3EscrowAbi, OrchestratorAbi, PaymentVerifierRegistryAbi, UnifiedPaymentVerifierAbi, NullifierRegistryAbi } from '@provex/abis';
12
+ import { publicClient, getDefaultToken } from '@provex/utils/tokens';
13
+ import { chainIdToChain } from '@provex/utils/chain';
14
+ import { base } from 'viem/chains';
15
+ import { DEFAULT_REPUTATION, getTierFromVolume, TIER_ORDER, TAKER_TIERS, getVolumeRangeDisplay, getCooldownHours, getEffectiveCap } from '@provex/utils/reputation';
16
+
17
+ // src/lib/api.ts
18
+ function createApiClient(apiUrl) {
19
+ async function request(path, options) {
20
+ const url = `${apiUrl}${path}`;
21
+ const response = await fetch(url, {
22
+ ...options,
23
+ headers: {
24
+ "Content-Type": "application/json",
25
+ ...options.headers
26
+ }
27
+ });
28
+ if (!response.ok) {
29
+ throw new Error(`API request failed: ${response.status} ${response.statusText} (${url})`);
30
+ }
31
+ return response.json();
32
+ }
33
+ return {
34
+ get: (path, options) => request(path, { ...options, method: "GET" }),
35
+ post: (path, body, options) => request(path, {
36
+ ...options,
37
+ method: "POST",
38
+ body: JSON.stringify(body)
39
+ })
40
+ };
41
+ }
42
+ var ProvexContext = createContext(null);
43
+ var defaultQueryClient = new QueryClient({
44
+ defaultOptions: {
45
+ queries: {
46
+ staleTime: 3e4,
47
+ refetchOnWindowFocus: false
48
+ }
49
+ }
50
+ });
51
+ function ProvexProvider({
52
+ config,
53
+ indexer,
54
+ queryClient,
55
+ publicClient: publicClient2,
56
+ publicClients,
57
+ wallet,
58
+ children
59
+ }) {
60
+ const resolvedQueryClient = queryClient ?? defaultQueryClient;
61
+ const contextValue = useMemo(() => {
62
+ const apiClient = createApiClient(config.apiUrl);
63
+ const chainId = config.chain.id;
64
+ const base2 = publicClients ?? {};
65
+ const resolved = { ...base2 };
66
+ if (publicClient2 && !resolved[chainId]) {
67
+ resolved[chainId] = publicClient2;
68
+ }
69
+ if (!resolved[chainId]) {
70
+ resolved[chainId] = createPublicClient({ chain: config.chain, transport: http() });
71
+ }
72
+ return { config, indexer, apiClient, publicClients: resolved, wallet };
73
+ }, [config, indexer, publicClient2, publicClients, wallet]);
74
+ return /* @__PURE__ */ jsx(ProvexContext.Provider, { value: contextValue, children: /* @__PURE__ */ jsx(QueryClientProvider, { client: resolvedQueryClient, children }) });
75
+ }
76
+ function useProvex() {
77
+ const context = useContext(ProvexContext);
78
+ if (!context) {
79
+ throw new Error("useProvex must be used within a <ProvexProvider>");
80
+ }
81
+ return context;
82
+ }
83
+ function useOptionalProvex() {
84
+ return useContext(ProvexContext);
85
+ }
86
+ function useProvexPublicClient(chainId) {
87
+ const { config, publicClients } = useProvex();
88
+ const target = chainId ?? config.chain.id;
89
+ return publicClients[target];
90
+ }
91
+ function useOptionalProvexPublicClient(chainId) {
92
+ const ctx = useOptionalProvex();
93
+ if (!ctx) return void 0;
94
+ const target = chainId ?? ctx.config.chain.id;
95
+ return ctx.publicClients[target];
96
+ }
97
+ function useProvexWallet() {
98
+ return useProvex().wallet;
99
+ }
100
+ function useOptionalProvexWallet() {
101
+ return useOptionalProvex()?.wallet;
102
+ }
103
+ var DEFAULT_REFETCH_INTERVAL_MS = 5e3;
104
+ function getRate({
105
+ deposit,
106
+ paymentMethod,
107
+ currency
108
+ }) {
109
+ if (!deposit) return 0n;
110
+ const paymentConfig = providerConfigs(deposit.chainId)[paymentMethod];
111
+ const candidateKeys = [
112
+ paymentMethod,
113
+ ...Array.from(paymentConfig?.subProviders ?? []).map((sp) => sp.key)
114
+ ];
115
+ let minRate = null;
116
+ for (const key of candidateKeys) {
117
+ const contractId = providerKeyToContractId(key).toLowerCase();
118
+ const value = deposit.conversionRates.get(contractId)?.get(currency.contractId.toLowerCase());
119
+ if (value) {
120
+ if (minRate === null || value < minRate) {
121
+ minRate = value;
122
+ }
123
+ }
124
+ }
125
+ return minRate ?? 0n;
126
+ }
127
+ function toDepositInfo(deposit) {
128
+ return {
129
+ escrow: deposit.escrow,
130
+ localId: deposit.localId,
131
+ chainId: deposit.chainId,
132
+ participantAddress: deposit.participantAddress,
133
+ token: deposit.token,
134
+ remaining: deposit.remaining,
135
+ deposited: deposit.deposited,
136
+ minAmount: deposit.minAmount,
137
+ maxAmount: deposit.maxAmount,
138
+ status: deposit.status,
139
+ acceptingIntents: deposit.acceptingIntents,
140
+ availableFunds: deposit.availableFunds,
141
+ conversionRates: deposit.conversionRates,
142
+ verifierPaymentMethodIds: deposit.paymentMethodIds
143
+ };
144
+ }
145
+ function useDeposits(options) {
146
+ const {
147
+ token,
148
+ currency = SUPPORTED_CURRENCIES.USD,
149
+ paymentMethod,
150
+ refetchIntervalMs = DEFAULT_REFETCH_INTERVAL_MS
151
+ } = options;
152
+ const { indexer } = useProvex();
153
+ const queryClient = useQueryClient();
154
+ const paymentMethodIds = useMemo(() => {
155
+ const paymentConfig = providerConfigs(token.chainId)[paymentMethod];
156
+ return /* @__PURE__ */ new Set([
157
+ providerKeyToContractId(paymentMethod).toLowerCase(),
158
+ ...paymentConfig.v2Verifiers.map((v) => v.toLowerCase()),
159
+ ...Array.from(paymentConfig.subProviders).flatMap((subProvider) => [
160
+ providerKeyToContractId(subProvider.key).toLowerCase(),
161
+ ...subProvider.v2Verifiers(token.chainId).map((v) => v.toLowerCase())
162
+ ])
163
+ ]);
164
+ }, [token.chainId, paymentMethod]);
165
+ const depositsQuery = useQuery({
166
+ queryKey: ["provex", "deposits", token.address, token.chainId, currency.contractId, paymentMethod],
167
+ queryFn: async () => {
168
+ const result = await indexer.getMatchableDeposits({
169
+ chainId: token.chainId,
170
+ token: token.address,
171
+ currencyId: currency.contractId
172
+ });
173
+ return result.items.filter((d) => {
174
+ for (const id of d.paymentMethodIds) {
175
+ if (paymentMethodIds.has(id)) return true;
176
+ }
177
+ return false;
178
+ }).map(toDepositInfo);
179
+ },
180
+ staleTime: refetchIntervalMs,
181
+ refetchInterval: refetchIntervalMs
182
+ });
183
+ const deposits = useMemo(() => depositsQuery.data ?? [], [depositsQuery.data]);
184
+ const canAcceptAmount = useCallback((deposit, amount) => {
185
+ return amount <= deposit.availableFunds && amount >= deposit.minAmount && amount <= deposit.maxAmount;
186
+ }, []);
187
+ const filterDepositsByAmount = useCallback((amountInInt) => {
188
+ if (!amountInInt || !currency) return [];
189
+ const matchable = [];
190
+ for (const deposit of deposits) {
191
+ const rate = getRate({ deposit, paymentMethod, currency });
192
+ if (rate === 0n) continue;
193
+ const amountToken = convertCurrencyToTokenOutput({
194
+ token,
195
+ currency,
196
+ currencyAmountInt: amountInInt,
197
+ rate
198
+ });
199
+ if (canAcceptAmount(deposit, amountToken)) {
200
+ matchable.push({ deposit, rate });
201
+ }
202
+ }
203
+ return matchable.sort((a, b) => {
204
+ if (a.rate < b.rate) return -1;
205
+ if (a.rate > b.rate) return 1;
206
+ if (a.deposit.localId < b.deposit.localId) return -1;
207
+ if (a.deposit.localId > b.deposit.localId) return 1;
208
+ return 0;
209
+ }).map((m) => m.deposit);
210
+ }, [deposits, currency, paymentMethod, token, canAcceptAmount]);
211
+ const refetch = useCallback(() => {
212
+ queryClient.invalidateQueries({
213
+ queryKey: ["provex", "deposits", token.address, token.chainId, currency.contractId, paymentMethod]
214
+ });
215
+ }, [queryClient, token.address, token.chainId, currency.contractId, paymentMethod]);
216
+ return {
217
+ deposits,
218
+ isLoading: depositsQuery.isLoading,
219
+ isUpdating: depositsQuery.isFetching && !depositsQuery.isLoading,
220
+ error: depositsQuery.error,
221
+ refetch,
222
+ filterDepositsByAmount,
223
+ getMatchableDeposits: (amountInInt) => {
224
+ if (typeof amountInInt === "string") {
225
+ amountInInt = parseUnits(amountInInt, { decimals: currency?.decimals || 2 });
226
+ }
227
+ if (!amountInInt) return [];
228
+ return filterDepositsByAmount(amountInInt);
229
+ }
230
+ };
231
+ }
232
+
233
+ // src/client/types.ts
234
+ var PROVEX_DEFAULTS = {
235
+ 8453: { apiUrl: "https://app.provex.com", indexerUrl: "https://indexer.provex.com" },
236
+ 369: { apiUrl: "https://app.provex.com", indexerUrl: "https://indexer.provex.com" }
237
+ };
238
+ var ProveXError = class extends Error {
239
+ code;
240
+ cause;
241
+ constructor(code, message, cause) {
242
+ super(message);
243
+ this.name = "ProveXError";
244
+ this.code = code;
245
+ this.cause = cause;
246
+ }
247
+ /** Check if this error was caused by the user rejecting in their wallet. */
248
+ get isRejection() {
249
+ return this.code === "WALLET_REJECTED";
250
+ }
251
+ };
252
+ var getTransactionGasInputs = async (chainId) => {
253
+ const chain = chainIdToChain.get(chainId);
254
+ if (!chain) {
255
+ throw new Error(`Unsupported chainId: ${chainId}`);
256
+ }
257
+ const block = await publicClient(chain).getBlock({
258
+ blockTag: "latest"
259
+ });
260
+ if (!block.baseFeePerGas) {
261
+ throw new Error(`No baseFeePerGas available for chainId: ${chainId}`);
262
+ }
263
+ return {
264
+ maxFeePerGas: block.baseFeePerGas * 2n,
265
+ maxPriorityFeePerGas: block.baseFeePerGas / 5n
266
+ };
267
+ };
268
+
269
+ // src/lib/updates.ts
270
+ var POLL_INTERVAL_MS = 1e3;
271
+ var SLOW_SYNC_THRESHOLD_MS = 15e3;
272
+ var checkMutation = async ({
273
+ queryDeposit,
274
+ depositIdHex,
275
+ status,
276
+ onSuccess,
277
+ onSlowSync,
278
+ slowSyncThresholdMs = SLOW_SYNC_THRESHOLD_MS
279
+ }) => {
280
+ const startTime = Date.now();
281
+ let slowSyncFired = false;
282
+ while (true) {
283
+ const result = await queryDeposit(depositIdHex);
284
+ if (result?.status === status) {
285
+ break;
286
+ }
287
+ if (!slowSyncFired && onSlowSync && Date.now() - startTime > slowSyncThresholdMs) {
288
+ slowSyncFired = true;
289
+ onSlowSync();
290
+ }
291
+ await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
292
+ }
293
+ setTimeout(() => {
294
+ onSuccess?.();
295
+ }, POLL_INTERVAL_MS);
296
+ };
297
+ var checkTransactionIndexed = async ({
298
+ queryTransaction,
299
+ hash,
300
+ onSuccess,
301
+ onSlowSync,
302
+ slowSyncThresholdMs = SLOW_SYNC_THRESHOLD_MS
303
+ }) => {
304
+ const startTime = Date.now();
305
+ let slowSyncFired = false;
306
+ while (true) {
307
+ const result = await queryTransaction(hash);
308
+ if (result) {
309
+ break;
310
+ }
311
+ if (!slowSyncFired && onSlowSync && Date.now() - startTime > slowSyncThresholdMs) {
312
+ slowSyncFired = true;
313
+ onSlowSync();
314
+ }
315
+ await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
316
+ }
317
+ onSuccess?.();
318
+ };
319
+
320
+ // src/lib/errors.ts
321
+ var ERROR_PATTERNS = [
322
+ // Wallet / signer rejections
323
+ { pattern: /user rejected|user denied|rejected the request|user cancelled|user canceled/i, message: "Transaction was cancelled." },
324
+ // On-chain reverts — specific errors first (first match wins)
325
+ { pattern: /InsufficientDepositLiquidity|0xc3df48f3/i, message: "This deposit no longer has enough available liquidity. Please try a smaller amount or a different deposit." },
326
+ { pattern: /execution reverted/i, message: "Transaction failed on-chain. The order may no longer be available." },
327
+ // Gas / balance issues
328
+ { pattern: /insufficient funds/i, message: "Insufficient funds for gas fees." },
329
+ { pattern: /gas required exceeds/i, message: "Transaction requires more gas than allowed." },
330
+ // Transaction replacement / nonce issues
331
+ { pattern: /could not replace existing tx|replacement transaction underpriced|nonce too low/i, message: "A previous transaction is still pending. Please wait for it to confirm or speed it up in your wallet." },
332
+ // Deposit state errors
333
+ { pattern: /DepositNotAcceptingIntents|0x67688c1a/i, message: "This deposit is currently paused. Please try a different deposit." },
334
+ // Network / RPC errors
335
+ { pattern: /could not detect network|network changed/i, message: "Network connection issue. Please check your wallet network." },
336
+ { pattern: /disconnected|not connected/i, message: "Wallet disconnected. Please reconnect and try again." },
337
+ { pattern: /timeout|etimedout/i, message: "Request timed out. Please try again." },
338
+ { pattern: /fetch failed|econnrefused|enotfound/i, message: "Unable to reach the server. Please check your connection." },
339
+ // Rate limiting / service unavailable
340
+ { pattern: /429|too many requests/i, message: "Too many requests. Please wait a moment and try again." },
341
+ { pattern: /503|service unavailable/i, message: "Service temporarily unavailable. Please try again shortly." },
342
+ // Nullifier / double-spend (keep the original — it's already user-friendly)
343
+ { pattern: /nullifier has already been used/i, message: "This payment has already been verified and cannot be used again." },
344
+ { pattern: /already been verified/i, message: "This payment has already been verified and cannot be used again." }
345
+ ];
346
+ function getUserFriendlyErrorMessage(error) {
347
+ const raw = extractErrorString(error);
348
+ for (const { pattern, message } of ERROR_PATTERNS) {
349
+ if (pattern.test(raw)) {
350
+ return message;
351
+ }
352
+ }
353
+ return "Something went wrong. Please try again.";
354
+ }
355
+ function isUserRejectionError(error) {
356
+ const raw = extractErrorString(error);
357
+ return /user rejected|user denied|rejected the request|user cancelled|user canceled/i.test(raw);
358
+ }
359
+ function extractErrorString(error) {
360
+ if (error instanceof Error) return error.message;
361
+ if (typeof error === "string") return error;
362
+ try {
363
+ return JSON.stringify(error);
364
+ } catch {
365
+ return String(error);
366
+ }
367
+ }
368
+
369
+ // src/client/ProveXClient.ts
370
+ var ProveXClient = class {
371
+ /** The viem Chain object — carries RPC URLs, chain ID, and metadata. */
372
+ chain;
373
+ /** Numeric chain ID (derived from chain.id). */
374
+ chainId;
375
+ wallet;
376
+ indexer;
377
+ escrowOverride;
378
+ onTransactionHash;
379
+ apiUrl;
380
+ onSlowSync;
381
+ /** Lazily-created public client for RPC calls. */
382
+ _publicClient = null;
383
+ /** Cached orchestrator address (lazy-loaded). */
384
+ cachedOrchestratorAddress = null;
385
+ constructor(config) {
386
+ this.chain = config.chain;
387
+ this.chainId = config.chain.id;
388
+ const defaults = PROVEX_DEFAULTS[this.chainId];
389
+ this.wallet = config.wallet;
390
+ this.indexer = config.indexer;
391
+ this.escrowOverride = config.escrowAddress;
392
+ this.onTransactionHash = config.onTransactionHash;
393
+ this.onSlowSync = config.onSlowSync;
394
+ this.apiUrl = config.apiUrl ?? defaults?.apiUrl ?? "https://app.provex.com";
395
+ this.createDepositRaw = this.buildWritableMethod({
396
+ abi: V3EscrowAbi,
397
+ contractResolver: () => this.getEscrowAddress(),
398
+ functionName: "createDeposit",
399
+ argsMapper: (params) => [params]
400
+ });
401
+ this.addFunds = this.buildWritableMethod({
402
+ abi: V3EscrowAbi,
403
+ contractResolver: () => this.getEscrowAddress(),
404
+ functionName: "addFunds",
405
+ argsMapper: (params) => [params.depositId, params.amount]
406
+ });
407
+ this.removeFunds = this.buildWritableMethod({
408
+ abi: V3EscrowAbi,
409
+ contractResolver: () => this.getEscrowAddress(),
410
+ functionName: "removeFunds",
411
+ argsMapper: (params) => [params.depositId, params.amount]
412
+ });
413
+ this.withdrawDeposit = this.buildWritableMethod({
414
+ abi: V3EscrowAbi,
415
+ contractResolver: () => this.getEscrowAddress(),
416
+ functionName: "withdrawDeposit",
417
+ argsMapper: (params) => [params.depositId]
418
+ });
419
+ this.pruneExpiredIntents = this.buildWritableMethod({
420
+ abi: V3EscrowAbi,
421
+ contractResolver: () => this.getEscrowAddress(),
422
+ functionName: "pruneExpiredIntents",
423
+ argsMapper: (params) => [params.depositId]
424
+ });
425
+ this.setAcceptingIntents = this.buildWritableMethod({
426
+ abi: V3EscrowAbi,
427
+ contractResolver: () => this.getEscrowAddress(),
428
+ functionName: "setAcceptingIntents",
429
+ argsMapper: (params) => [params.depositId, params.accepting]
430
+ });
431
+ this.setRetainOnEmpty = this.buildWritableMethod({
432
+ abi: V3EscrowAbi,
433
+ contractResolver: () => this.getEscrowAddress(),
434
+ functionName: "setRetainOnEmpty",
435
+ argsMapper: (params) => [params.depositId, params.retain]
436
+ });
437
+ this.setIntentRange = this.buildWritableMethod({
438
+ abi: V3EscrowAbi,
439
+ contractResolver: () => this.getEscrowAddress(),
440
+ functionName: "setIntentRange",
441
+ argsMapper: (params) => [params.depositId, { min: params.min, max: params.max }]
442
+ });
443
+ this.setPaymentMethodActive = this.buildWritableMethod({
444
+ abi: V3EscrowAbi,
445
+ contractResolver: () => this.getEscrowAddress(),
446
+ functionName: "setPaymentMethodActive",
447
+ argsMapper: (params) => [params.depositId, params.paymentMethod, params.active]
448
+ });
449
+ this.setCurrencyMinRate = this.buildWritableMethod({
450
+ abi: V3EscrowAbi,
451
+ contractResolver: () => this.getEscrowAddress(),
452
+ functionName: "setCurrencyMinRate",
453
+ argsMapper: (params) => [params.depositId, params.paymentMethod, params.currency, params.rate]
454
+ });
455
+ this.addCurrencies = this.buildWritableMethod({
456
+ abi: V3EscrowAbi,
457
+ contractResolver: () => this.getEscrowAddress(),
458
+ functionName: "addCurrencies",
459
+ argsMapper: (params) => [params.depositId, params.paymentMethod, params.currencies]
460
+ });
461
+ this.deactivateCurrency = this.buildWritableMethod({
462
+ abi: V3EscrowAbi,
463
+ contractResolver: () => this.getEscrowAddress(),
464
+ functionName: "deactivateCurrency",
465
+ argsMapper: (params) => [params.depositId, params.paymentMethod, params.currencyCode]
466
+ });
467
+ this.addPaymentMethods = this.buildWritableMethod({
468
+ abi: V3EscrowAbi,
469
+ contractResolver: () => this.getEscrowAddress(),
470
+ functionName: "addPaymentMethods",
471
+ argsMapper: (params) => [params.depositId, params.paymentMethods, params.paymentMethodData, params.currencies]
472
+ });
473
+ this.cancelIntent = this.buildWritableMethod({
474
+ abi: OrchestratorAbi,
475
+ contractResolver: () => this.getOrchestratorAddress(),
476
+ functionName: "cancelIntent",
477
+ argsMapper: (params) => [params.intentHash]
478
+ });
479
+ this.releaseFundsToPayer = this.buildWritableMethod({
480
+ abi: OrchestratorAbi,
481
+ contractResolver: () => this.getOrchestratorAddress(),
482
+ functionName: "releaseFundsToPayer",
483
+ argsMapper: (params) => [params.intentHash]
484
+ });
485
+ this.approve = this.buildWritableMethod({
486
+ abi: [{ name: "approve", type: "function", stateMutability: "nonpayable", inputs: [{ name: "spender", type: "address" }, { name: "amount", type: "uint256" }], outputs: [{ name: "", type: "bool" }] }],
487
+ contractResolver: (_params) => _params.token,
488
+ functionName: "approve",
489
+ argsMapper: (params) => [params.spender, params.amount ?? BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")]
490
+ });
491
+ }
492
+ // ─── Address Resolution ──────────────────────────────────────────────────
493
+ /** Get the V3 escrow address for this client's chain. */
494
+ getEscrowAddress() {
495
+ if (this.escrowOverride) return this.escrowOverride;
496
+ const addr = getLatestContract(this.chainId, "escrow", "v3");
497
+ if (!addr) throw new ProveXError("VALIDATION_ERROR", `No V3 escrow found for chain ${this.chainId}`);
498
+ return addr;
499
+ }
500
+ /** Get the orchestrator address (cached after first read). */
501
+ async getOrchestratorAddress() {
502
+ if (this.cachedOrchestratorAddress) return this.cachedOrchestratorAddress;
503
+ const escrow = this.getEscrowAddress();
504
+ const result = await this.readContract({
505
+ address: escrow,
506
+ abi: V3EscrowAbi,
507
+ functionName: "orchestrator"
508
+ });
509
+ this.cachedOrchestratorAddress = result;
510
+ return this.cachedOrchestratorAddress;
511
+ }
512
+ // ─── Indexer Reads ───────────────────────────────────────────────────────
513
+ requireIndexer() {
514
+ if (!this.indexer) throw new ProveXError("INDEXER_NOT_CONFIGURED", "No IndexerAdapter provided. Pass `indexer` to createProveXClient().");
515
+ return this.indexer;
516
+ }
517
+ async getMatchableDeposits(params) {
518
+ return this.requireIndexer().getMatchableDeposits({ ...params, chainId: this.chainId });
519
+ }
520
+ async getDepositWithVerifiers(params) {
521
+ return this.requireIndexer().getDepositWithVerifiers({ ...params, chainId: this.chainId });
522
+ }
523
+ async getIntent(intentHash) {
524
+ return this.requireIndexer().getIntent({ intentHash, chainId: this.chainId });
525
+ }
526
+ async getPayeeDetailsHash(params) {
527
+ return this.requireIndexer().getPayeeDetailsHash({ ...params, chainId: this.chainId });
528
+ }
529
+ async getUserReputation(address) {
530
+ return this.requireIndexer().getUserReputation({ address, chainId: this.chainId });
531
+ }
532
+ // ─── On-Chain Reads ──────────────────────────────────────────────────────
533
+ async getProtocolFees() {
534
+ const orchestrator = await this.getOrchestratorAddress();
535
+ const [feeRaw, feeRecipient] = await Promise.all([
536
+ this.readContract({ address: orchestrator, abi: OrchestratorAbi, functionName: "protocolFee" }),
537
+ this.readContract({ address: orchestrator, abi: OrchestratorAbi, functionName: "protocolFeeRecipient" })
538
+ ]);
539
+ return {
540
+ feeRaw,
541
+ feeInfo: normalizeFeePrecision(feeRaw),
542
+ feeRecipient
543
+ };
544
+ }
545
+ async getDeposit(depositId) {
546
+ return this.readContract({
547
+ address: this.getEscrowAddress(),
548
+ abi: V3EscrowAbi,
549
+ functionName: "getDeposit",
550
+ args: [depositId]
551
+ });
552
+ }
553
+ async getAccountDeposits(account) {
554
+ return this.readContract({
555
+ address: this.getEscrowAddress(),
556
+ abi: V3EscrowAbi,
557
+ functionName: "getAccountDeposits",
558
+ args: [account]
559
+ });
560
+ }
561
+ async getDepositCounter() {
562
+ return this.readContract({
563
+ address: this.getEscrowAddress(),
564
+ abi: V3EscrowAbi,
565
+ functionName: "depositCounter"
566
+ });
567
+ }
568
+ async getAllowance(params) {
569
+ return this.readContract({
570
+ address: params.token,
571
+ abi: [{ name: "allowance", type: "function", stateMutability: "view", inputs: [{ name: "owner", type: "address" }, { name: "spender", type: "address" }], outputs: [{ name: "", type: "uint256" }] }],
572
+ functionName: "allowance",
573
+ args: [params.owner, params.spender]
574
+ });
575
+ }
576
+ async checkNullifierUsed(params) {
577
+ try {
578
+ const orchestrator = await this.getOrchestratorAddress();
579
+ const verifierRegistry = await this.readContract({ address: orchestrator, abi: OrchestratorAbi, functionName: "paymentVerifierRegistry" });
580
+ const verifier = await this.readContract({ address: verifierRegistry, abi: PaymentVerifierRegistryAbi, functionName: "getVerifier", args: [params.paymentMethodId] });
581
+ const nullifierRegistry = await this.readContract({ address: verifier, abi: UnifiedPaymentVerifierAbi, functionName: "nullifierRegistry" });
582
+ return await this.readContract({ address: nullifierRegistry, abi: NullifierRegistryAbi, functionName: "isNullified", args: [params.nullifier] });
583
+ } catch {
584
+ return null;
585
+ }
586
+ }
587
+ // ─── Escrow Writes ───────────────────────────────────────────────────────
588
+ /** Low-level deposit creation — pass pre-hashed contract params directly. */
589
+ createDepositRaw;
590
+ addFunds;
591
+ removeFunds;
592
+ withdrawDeposit;
593
+ pruneExpiredIntents;
594
+ setAcceptingIntents;
595
+ setRetainOnEmpty;
596
+ setIntentRange;
597
+ setPaymentMethodActive;
598
+ setCurrencyMinRate;
599
+ addCurrencies;
600
+ deactivateCurrency;
601
+ addPaymentMethods;
602
+ /**
603
+ * Create a deposit with human-readable params.
604
+ *
605
+ * Handles all encoding internally:
606
+ * 1. Registers payee details with the API (so buyers can discover them)
607
+ * 2. Hashes provider keys and currency codes to bytes32
608
+ * 3. Expands sub-providers (e.g., 'zelle' → zelle-chase, zelle-bofa, zelle-citi)
609
+ * 4. Encodes gating service witness signers
610
+ * 5. Submits the on-chain transaction
611
+ *
612
+ * @example
613
+ * ```ts
614
+ * await client.createDeposit({
615
+ * token: USDC_ADDRESS,
616
+ * amount: 1000_000000n,
617
+ * intentRange: { min: 10_000000n, max: 500_000000n },
618
+ * paymentMethods: [
619
+ * { provider: 'venmo', payeeId: '@myvenmo', currencies: [{ code: 'USD', minRate: 0n }] },
620
+ * ],
621
+ * retainOnEmpty: true,
622
+ * })
623
+ * ```
624
+ */
625
+ async createDeposit(params) {
626
+ await Promise.all(
627
+ params.paymentMethods.map(
628
+ (pm) => this.registerMaker({
629
+ providerKey: pm.provider,
630
+ providerId: pm.payeeId,
631
+ telegramHandle: params.telegramHandle
632
+ }).catch((err) => {
633
+ console.warn(`[ProveXClient] Failed to register maker for ${pm.provider}:`, err);
634
+ })
635
+ )
636
+ );
637
+ const rawParams = this.buildCreateDepositRawParams(params);
638
+ return this.createDepositRaw(rawParams);
639
+ }
640
+ /**
641
+ * Prepare an unsigned createDeposit transaction (no API call, no wallet).
642
+ *
643
+ * Use this for smart accounts, multisig, gasless relayers, or offline signing.
644
+ * Maker registration is NOT performed — call `registerMaker()` separately
645
+ * if you need buyers to discover the payee.
646
+ */
647
+ async prepareCreateDeposit(params) {
648
+ return this.createDepositRaw.prepare(this.buildCreateDepositRawParams(params));
649
+ }
650
+ /**
651
+ * Convert human-readable deposit params to raw contract params.
652
+ * Handles provider expansion, hashing, gating service encoding, and defaults.
653
+ */
654
+ buildCreateDepositRawParams(params) {
655
+ const expanded = [];
656
+ const configs = providerConfigs(this.chainId);
657
+ for (const pm of params.paymentMethods) {
658
+ const hash = computePayeeDetailsHash(pm.payeeId);
659
+ const config = configs[pm.provider];
660
+ if (config?.subProviders && config.subProviders.size > 0) {
661
+ for (const sub of config.subProviders) {
662
+ expanded.push({
663
+ providerKey: sub.key,
664
+ payeeDetailsHash: hash,
665
+ currencies: pm.currencies,
666
+ intentGatingService: pm.intentGatingService,
667
+ data: pm.data
668
+ });
669
+ }
670
+ } else {
671
+ expanded.push({
672
+ providerKey: pm.provider,
673
+ payeeDetailsHash: hash,
674
+ currencies: pm.currencies,
675
+ intentGatingService: pm.intentGatingService,
676
+ data: pm.data
677
+ });
678
+ }
679
+ }
680
+ const defaultGatingData = encodeAbiParameters(
681
+ parseAbiParameters(["address[]"]),
682
+ [[reclaimSigners.peerWitnessSigner, reclaimSigners.reclaimWitnessSigner]]
683
+ );
684
+ const defaultGatingService = getLatestContract(this.chainId, "gatingService", "v3") ?? zeroAddress;
685
+ return {
686
+ token: params.token,
687
+ amount: params.amount,
688
+ intentAmountRange: {
689
+ min: params.intentRange?.min ?? 1000000n,
690
+ max: params.intentRange?.max ?? params.amount
691
+ },
692
+ paymentMethods: expanded.map((p) => providerKeyToContractId(p.providerKey)),
693
+ paymentMethodData: expanded.map((p) => ({
694
+ intentGatingService: p.intentGatingService ?? defaultGatingService,
695
+ payeeDetails: p.payeeDetailsHash,
696
+ data: p.data ?? defaultGatingData
697
+ })),
698
+ currencies: expanded.map(
699
+ (p) => p.currencies.map((c) => ({
700
+ code: tickerToContractId(c.code),
701
+ minConversionRate: c.minRate
702
+ }))
703
+ ),
704
+ delegate: params.delegate ?? zeroAddress,
705
+ intentGuardian: params.intentGuardian ?? zeroAddress,
706
+ retainOnEmpty: params.retainOnEmpty ?? false
707
+ };
708
+ }
709
+ // ─── Orchestrator Writes ─────────────────────────────────────────────────
710
+ cancelIntent;
711
+ releaseFundsToPayer;
712
+ /**
713
+ * Signal an intent to buy tokens from a deposit (buyer side).
714
+ *
715
+ * Handles the full multi-step flow:
716
+ * 1. Fetches payee details hash from the indexer
717
+ * 2. Requests a gating service signature from the API
718
+ * 3. Simulates the transaction
719
+ * 4. Submits to Orchestrator.signalIntent()
720
+ * 5. Parses the IntentSignaled event to extract the intent hash
721
+ *
722
+ * @returns Transaction result with the on-chain intent hash.
723
+ * @throws {ProveXError} VALIDATION_ERROR if payee details or gating signature missing.
724
+ * @throws {ProveXError} API_ERROR if gating service rejects the intent.
725
+ * @throws {ProveXError} WALLET_REJECTED if user cancels in wallet.
726
+ *
727
+ * @example
728
+ * ```ts
729
+ * const { hash, intentHash } = await client.signalIntent({
730
+ * deposit: { escrow: '0x...', localId: 1n },
731
+ * paymentMethod: providerKeyToContractId('venmo'),
732
+ * tokenAmount: 100_000000n,
733
+ * toAddress: wallet.address,
734
+ * fiatCurrencyCode: tickerToContractId('USD'),
735
+ * conversionRate: 1_000000000000000000n,
736
+ * })
737
+ * ```
738
+ */
739
+ async signalIntent(params) {
740
+ const wallet = this.requireWallet();
741
+ const orchestrator = await this.getOrchestratorAddress();
742
+ const indexer = this.requireIndexer();
743
+ const payeeDetailsHash = await indexer.getPayeeDetailsHash({
744
+ escrow: params.deposit.escrow,
745
+ localId: params.deposit.localId,
746
+ chainId: this.chainId,
747
+ paymentMethodId: params.paymentMethod
748
+ });
749
+ if (!payeeDetailsHash) {
750
+ throw new ProveXError("VALIDATION_ERROR", "No payee details found for this deposit and payment method.");
751
+ }
752
+ const gatingResponse = await this.requestGatingSignature({
753
+ processorName: params.subProvider ?? "",
754
+ depositId: params.deposit.localId.toString(),
755
+ amount: params.tokenAmount.toString(),
756
+ payeeDetails: payeeDetailsHash,
757
+ toAddress: params.toAddress,
758
+ paymentMethod: params.paymentMethod,
759
+ fiatCurrency: params.fiatCurrencyCode,
760
+ conversionRate: params.conversionRate.toString(),
761
+ chainId: this.chainId.toString(),
762
+ orchestratorAddress: orchestrator,
763
+ escrowAddress: params.deposit.escrow
764
+ });
765
+ const rawParams = {
766
+ escrow: params.deposit.escrow,
767
+ depositId: params.deposit.localId,
768
+ amount: params.tokenAmount,
769
+ to: params.toAddress,
770
+ paymentMethod: params.paymentMethod,
771
+ fiatCurrency: params.fiatCurrencyCode,
772
+ conversionRate: params.conversionRate,
773
+ referrer: zeroAddress,
774
+ referrerFee: 0n,
775
+ gatingServiceSignature: gatingResponse.signature,
776
+ signatureExpiration: gatingResponse.expiration,
777
+ postIntentHook: zeroAddress,
778
+ data: "0x"
779
+ };
780
+ const publicClient2 = this.getPublicClient();
781
+ try {
782
+ await publicClient2.simulateContract({
783
+ address: orchestrator,
784
+ abi: OrchestratorAbi,
785
+ functionName: "signalIntent",
786
+ args: [rawParams],
787
+ account: params.toAddress
788
+ });
789
+ } catch (simError) {
790
+ throw new ProveXError("CONTRACT_ERROR", simError.message ?? "Signal intent simulation failed", simError);
791
+ }
792
+ const gasInputs = await getTransactionGasInputs(this.chainId);
793
+ const txData = encodeFunctionData({
794
+ abi: OrchestratorAbi,
795
+ functionName: "signalIntent",
796
+ args: [rawParams]
797
+ });
798
+ let txHash;
799
+ try {
800
+ txHash = await wallet.sendTransaction({
801
+ to: orchestrator,
802
+ data: txData,
803
+ chainId: this.chainId,
804
+ ...gasInputs
805
+ });
806
+ } catch (err) {
807
+ if (isUserRejectionError(err)) {
808
+ throw new ProveXError("WALLET_REJECTED", "Transaction was rejected in wallet.", err);
809
+ }
810
+ throw new ProveXError("CONTRACT_ERROR", err.message ?? "Transaction failed", err);
811
+ }
812
+ this.onTransactionHash?.(txHash);
813
+ const receipt = await publicClient2.waitForTransactionReceipt({ hash: txHash });
814
+ let intentHash = null;
815
+ for (const log of receipt.logs) {
816
+ try {
817
+ const decoded = decodeEventLog({
818
+ abi: OrchestratorAbi,
819
+ data: log.data,
820
+ topics: log.topics
821
+ });
822
+ if (decoded.eventName === "IntentSignaled") {
823
+ intentHash = decoded.args.intentHash;
824
+ break;
825
+ }
826
+ } catch {
827
+ }
828
+ }
829
+ if (!intentHash) {
830
+ throw new ProveXError("CONTRACT_ERROR", "Transaction succeeded but IntentSignaled event not found in receipt.");
831
+ }
832
+ if (this.indexer) {
833
+ await checkTransactionIndexed({
834
+ queryTransaction: this.indexer.getTransactionByHash,
835
+ hash: txHash,
836
+ onSlowSync: this.onSlowSync
837
+ });
838
+ }
839
+ return { hash: txHash, receipt, intentHash };
840
+ }
841
+ /**
842
+ * Request a gating service signature for intent signaling.
843
+ * The gating service validates the intent and returns a signature
844
+ * the Orchestrator contract verifies on-chain.
845
+ */
846
+ async requestGatingSignature(params) {
847
+ const res = await this.apiPost("/api/v0/attestation/verify/intent", params);
848
+ if (!res.success) {
849
+ throw new ProveXError("API_ERROR", res.message ?? "Gating service rejected the intent.");
850
+ }
851
+ const signature = res.responseObject.intentData?.gatingServiceSignature ?? res.responseObject.signedIntent;
852
+ if (!signature) {
853
+ throw new ProveXError("API_ERROR", "No signature received from gating service.");
854
+ }
855
+ const expiration = res.responseObject.signatureExpiration ? BigInt(res.responseObject.signatureExpiration) : BigInt(Math.floor(Date.now() / 1e3) + 3600);
856
+ return { signature, expiration };
857
+ }
858
+ // ─── ERC20 ───────────────────────────────────────────────────────────────
859
+ approve;
860
+ // ─── API Methods (Maker Registration, Attestation) ──────────────────────
861
+ /** Get payee details for a provider and user ID. */
862
+ async getPayeeInfo(params) {
863
+ try {
864
+ const res = await fetch(`${this.apiUrl}/api/v0/makers/${params.provider}/${params.userId}`);
865
+ if (!res.ok) return null;
866
+ const json = await res.json();
867
+ return json.responseObject ?? null;
868
+ } catch {
869
+ return null;
870
+ }
871
+ }
872
+ /** Validate a maker's payment identity before registration. */
873
+ async validateMaker(params) {
874
+ const res = await this.apiPost("/api/v0/makers/validate", {
875
+ processorName: params.providerKey,
876
+ depositData: {
877
+ [params.providerKey]: params.providerId,
878
+ telegramUsername: params.telegramHandle ?? ""
879
+ }
880
+ });
881
+ return res.responseObject ?? false;
882
+ }
883
+ /** Register a maker's payment identity (e.g., Venmo username). Required before creating deposits. */
884
+ async registerMaker(params) {
885
+ const res = await this.apiPost("/api/v0/makers/create", {
886
+ processorName: params.providerKey,
887
+ depositData: {
888
+ [params.providerKey]: params.providerId,
889
+ telegramUsername: params.telegramHandle ?? ""
890
+ }
891
+ });
892
+ return res.responseObject ?? null;
893
+ }
894
+ /**
895
+ * Submit zkTLS proofs and get a signed attestation for fulfillIntent.
896
+ * This is the proof verification step — after the buyer makes payment and
897
+ * generates proofs via the browser extension.
898
+ */
899
+ async getAttestation(params) {
900
+ const endpoint = `/api/v0/attestation/verify/${params.platform}/${params.actionType}`;
901
+ const proof = params.proofs.length === 1 ? params.proofs[0] : params.proofs;
902
+ const res = await fetch(`${this.apiUrl}${endpoint}`, {
903
+ method: "POST",
904
+ headers: { "Content-Type": "application/json" },
905
+ body: JSON.stringify({
906
+ proofType: "reclaim",
907
+ proof: JSON.stringify(proof),
908
+ chainId: params.chainId,
909
+ verifyingContract: params.verifyingContract,
910
+ intent: params.intent
911
+ })
912
+ });
913
+ if (!res.ok) {
914
+ let errorMessage = `Attestation error: ${res.status}`;
915
+ try {
916
+ const errorJson = await res.json();
917
+ if (errorJson.message) errorMessage = errorJson.message;
918
+ } catch {
919
+ }
920
+ return {
921
+ success: false,
922
+ message: errorMessage,
923
+ statusCode: res.status,
924
+ responseObject: {}
925
+ };
926
+ }
927
+ return await res.json();
928
+ }
929
+ /** Make a POST request to the API. */
930
+ async apiPost(path, body) {
931
+ const res = await fetch(`${this.apiUrl}${path}`, {
932
+ method: "POST",
933
+ headers: { "Content-Type": "application/json" },
934
+ body: JSON.stringify(body)
935
+ });
936
+ if (!res.ok) {
937
+ throw new ProveXError("API_ERROR", `API request failed: ${res.status}`);
938
+ }
939
+ return await res.json();
940
+ }
941
+ // ─── Indexer Sync ────────────────────────────────────────────────────────
942
+ async waitForTransactionIndexed(hash) {
943
+ const indexer = this.requireIndexer();
944
+ await checkTransactionIndexed({
945
+ queryTransaction: indexer.getTransactionByHash,
946
+ hash,
947
+ onSlowSync: this.onSlowSync
948
+ });
949
+ }
950
+ // ─── Internal Helpers ────────────────────────────────────────────────────
951
+ /** Get or create a viem PublicClient for this chain. Cached after first use. */
952
+ getPublicClient() {
953
+ if (!this._publicClient) {
954
+ this._publicClient = createPublicClient({ chain: this.chain, transport: http() });
955
+ }
956
+ return this._publicClient;
957
+ }
958
+ /** Read from a contract using wallet adapter or public RPC. */
959
+ async readContract(params) {
960
+ if (this.wallet?.readContract) {
961
+ return this.wallet.readContract({ ...params, chainId: this.chainId });
962
+ }
963
+ return this.getPublicClient().readContract(params);
964
+ }
965
+ /** Require a connected wallet, or throw. */
966
+ requireWallet() {
967
+ if (!this.wallet) throw new ProveXError("WALLET_NOT_CONNECTED", "No wallet adapter provided. Pass `wallet` to createProveXClient().");
968
+ if (!this.wallet.address) throw new ProveXError("WALLET_NOT_CONNECTED", "Wallet is not connected.");
969
+ return this.wallet;
970
+ }
971
+ /**
972
+ * Build a WritableMethod from an ABI definition.
973
+ * The returned function supports both execute (full lifecycle) and .prepare() (unsigned tx).
974
+ */
975
+ buildWritableMethod({
976
+ abi,
977
+ contractResolver,
978
+ functionName,
979
+ argsMapper
980
+ }) {
981
+ const prepare = async (params) => {
982
+ const to = await contractResolver(params);
983
+ const args = argsMapper(params);
984
+ const data = encodeFunctionData({
985
+ abi,
986
+ functionName,
987
+ args
988
+ });
989
+ return { to, data, value: 0n, chainId: this.chainId };
990
+ };
991
+ const execute = async (params) => {
992
+ const wallet = this.requireWallet();
993
+ const prepared = await prepare(params);
994
+ const gasInputs = await getTransactionGasInputs(this.chainId);
995
+ let hash;
996
+ try {
997
+ hash = await wallet.sendTransaction({ ...prepared, ...gasInputs });
998
+ } catch (err) {
999
+ if (isUserRejectionError(err)) {
1000
+ throw new ProveXError("WALLET_REJECTED", "Transaction was rejected in wallet.", err);
1001
+ }
1002
+ throw new ProveXError("CONTRACT_ERROR", err.message ?? "Transaction failed", err);
1003
+ }
1004
+ this.onTransactionHash?.(hash);
1005
+ const receipt = await this.getPublicClient().waitForTransactionReceipt({ hash });
1006
+ if (this.indexer) {
1007
+ await checkTransactionIndexed({
1008
+ queryTransaction: this.indexer.getTransactionByHash,
1009
+ hash,
1010
+ onSlowSync: this.onSlowSync
1011
+ });
1012
+ }
1013
+ return { hash, receipt };
1014
+ };
1015
+ execute.prepare = prepare;
1016
+ return execute;
1017
+ }
1018
+ };
1019
+ function createProveXClient(config) {
1020
+ return new ProveXClient(config);
1021
+ }
1022
+ var ERROR_PATTERNS2 = [
1023
+ { pattern: /user rejected|user denied|rejected the request|user cancelled|user canceled/i, message: "Transaction was cancelled." },
1024
+ { pattern: /InsufficientDepositLiquidity|0xc3df48f3/i, message: "This deposit no longer has enough available liquidity. Please try a smaller amount or a different deposit." },
1025
+ { pattern: /execution reverted/i, message: "Transaction failed on-chain. The order may no longer be available." },
1026
+ { pattern: /insufficient funds/i, message: "Insufficient funds for gas fees." },
1027
+ { pattern: /timeout|etimedout/i, message: "Request timed out. Please try again." }
1028
+ ];
1029
+ function getUserFriendlyErrorMessage2(error) {
1030
+ const raw = error instanceof Error ? error.message : String(error);
1031
+ for (const { pattern, message } of ERROR_PATTERNS2) {
1032
+ if (pattern.test(raw)) return message;
1033
+ }
1034
+ return "Something went wrong. Please try again.";
1035
+ }
1036
+ function useSignalIntent({
1037
+ wallet,
1038
+ onSuccess,
1039
+ onFailure,
1040
+ deposit,
1041
+ refetchDeposits
1042
+ }) {
1043
+ const provex = useOptionalProvex();
1044
+ const [status, setStatus] = useState("input");
1045
+ const [message, setMessage] = useState(null);
1046
+ const client = useMemo(() => {
1047
+ if (!provex) return null;
1048
+ return createProveXClient({
1049
+ chain: provex.config.chain,
1050
+ apiUrl: provex.config.apiUrl,
1051
+ wallet,
1052
+ indexer: provex.indexer
1053
+ });
1054
+ }, [provex, wallet]);
1055
+ const isLoading = useMemo(() => {
1056
+ return status === "loading_payee" || status === "loading_intent" || status === "prompt_wallet_confirm" || status === "writing_intent";
1057
+ }, [status]);
1058
+ const startOrder = useCallback(async ({
1059
+ paymentMethod,
1060
+ depositId,
1061
+ tokenAmount,
1062
+ toAddress,
1063
+ fiatCurrencyCode,
1064
+ conversionRate,
1065
+ subProvider
1066
+ }) => {
1067
+ if (!client || !deposit) {
1068
+ setStatus("error");
1069
+ setMessage("Client or deposit not available");
1070
+ return;
1071
+ }
1072
+ const escrow = deposit.escrow;
1073
+ if (!escrow) {
1074
+ setStatus("error");
1075
+ setMessage("No escrow address found");
1076
+ return;
1077
+ }
1078
+ setStatus("loading_intent");
1079
+ try {
1080
+ const result = await client.signalIntent({
1081
+ deposit: { escrow, localId: deposit.localId ?? depositId },
1082
+ paymentMethod,
1083
+ tokenAmount,
1084
+ toAddress,
1085
+ fiatCurrencyCode,
1086
+ conversionRate,
1087
+ subProvider
1088
+ });
1089
+ setStatus("success");
1090
+ setMessage("Intent signaled successfully");
1091
+ onSuccess(result.intentHash);
1092
+ } catch (error) {
1093
+ if (error instanceof ProveXError && error.isRejection) {
1094
+ setStatus("input");
1095
+ setMessage(null);
1096
+ return;
1097
+ }
1098
+ console.error("Failed to signal intent", error);
1099
+ setStatus("error");
1100
+ setMessage(getUserFriendlyErrorMessage2(error));
1101
+ refetchDeposits?.();
1102
+ onFailure?.();
1103
+ }
1104
+ }, [client, deposit, onSuccess, onFailure, refetchDeposits]);
1105
+ return {
1106
+ startOrder,
1107
+ status,
1108
+ message,
1109
+ isLoading
1110
+ };
1111
+ }
1112
+ function useReputation({
1113
+ address,
1114
+ chainId
1115
+ }) {
1116
+ const { indexer } = useProvex();
1117
+ const queryClient = useQueryClient();
1118
+ const isBase = chainId === base.id;
1119
+ const reputationQuery = useQuery({
1120
+ queryKey: ["provex", "reputation", address, isBase ? base.id : "all"],
1121
+ queryFn: async () => {
1122
+ if (!address) return null;
1123
+ return indexer.getUserReputation({
1124
+ address,
1125
+ chainId: isBase ? base.id : void 0
1126
+ });
1127
+ },
1128
+ enabled: !!address,
1129
+ staleTime: 6e4,
1130
+ refetchInterval: 12e4
1131
+ });
1132
+ const reputation = useMemo(() => {
1133
+ const data = reputationQuery.data;
1134
+ if (!data) return DEFAULT_REPUTATION;
1135
+ let tier = getTierFromVolume(data.fulfilledVolumeUsdc);
1136
+ const lockScore = data.lateCancellations * 50;
1137
+ const dilutedLockScore = data.fulfilledCount > 0 ? lockScore / (1 + data.fulfilledCount * 0.1) : lockScore;
1138
+ let tierPenalty = 0;
1139
+ if (dilutedLockScore >= 1e3) tierPenalty = 4;
1140
+ else if (dilutedLockScore >= 500) tierPenalty = 3;
1141
+ else if (dilutedLockScore >= 200) tierPenalty = 2;
1142
+ else if (dilutedLockScore >= 50) tierPenalty = 1;
1143
+ if (tierPenalty > 0) {
1144
+ const currentTierIndex = TIER_ORDER.indexOf(tier);
1145
+ const newTierIndex = Math.max(0, currentTierIndex - tierPenalty);
1146
+ tier = TIER_ORDER[newTierIndex] ?? "peasant";
1147
+ }
1148
+ const cooldownHours = TAKER_TIERS[tier].cooldownHours;
1149
+ let cooldownEndsAt = null;
1150
+ let isOnCooldown = false;
1151
+ const baseTimestamp = data.lastSignaledAt[base.id] ?? null;
1152
+ const pulseTimestamp = data.lastSignaledAt[369] ?? null;
1153
+ const candidateTimestamps = isBase ? [baseTimestamp] : [baseTimestamp, pulseTimestamp];
1154
+ const lastSignaledTimestamp = candidateTimestamps.filter((ts) => ts !== null).sort((a, b) => Number(b) - Number(a))[0] ?? null;
1155
+ if (cooldownHours > 0 && lastSignaledTimestamp) {
1156
+ const lastSignaledTime = Number(lastSignaledTimestamp) * 1e3;
1157
+ const cooldownMs = cooldownHours * 60 * 60 * 1e3;
1158
+ cooldownEndsAt = new Date(lastSignaledTime + cooldownMs);
1159
+ isOnCooldown = cooldownEndsAt > /* @__PURE__ */ new Date();
1160
+ }
1161
+ return {
1162
+ tier,
1163
+ fulfilledVolumeUsdc: data.fulfilledVolumeUsdc,
1164
+ lockScore: dilutedLockScore,
1165
+ cooldownEndsAt,
1166
+ isOnCooldown
1167
+ };
1168
+ }, [reputationQuery.data, isBase]);
1169
+ const hasLoadedData = reputationQuery.data !== void 0;
1170
+ const isLoading = reputationQuery.isLoading && !hasLoadedData;
1171
+ const refetch = useCallback(() => {
1172
+ queryClient.invalidateQueries({
1173
+ queryKey: ["provex", "reputation", address]
1174
+ });
1175
+ }, [queryClient, address]);
1176
+ return {
1177
+ reputation,
1178
+ isLoading,
1179
+ error: reputationQuery.error,
1180
+ refetch
1181
+ };
1182
+ }
1183
+ function getTierDisplayInfo(tier) {
1184
+ const config = TAKER_TIERS[tier];
1185
+ const colors = {
1186
+ [tiers.PEASANT]: "gray",
1187
+ [tiers.NEUTRAL]: "blue",
1188
+ [tiers.PLUS]: "green",
1189
+ [tiers.PRO]: "purple",
1190
+ [tiers.PLATINUM]: "yellow",
1191
+ [tiers.PRESIDENT]: "cyan"
1192
+ };
1193
+ return {
1194
+ name: config.name,
1195
+ baseCap: config.baseCap,
1196
+ cooldownHours: config.cooldownHours,
1197
+ color: colors[tier],
1198
+ volumeRangeDisplay: getVolumeRangeDisplay(tier)
1199
+ };
1200
+ }
1201
+ function useReputationLimits({
1202
+ chainId,
1203
+ selectedPaymentMethod,
1204
+ tier,
1205
+ amountInInt,
1206
+ cooldownEndsAt
1207
+ }) {
1208
+ const hasLimits = true;
1209
+ const { cooldownRemaining, isOnCooldown } = useMemo(() => {
1210
+ const providerCooldownHours = getCooldownHours({ tier, providerKey: selectedPaymentMethod }) ;
1211
+ const providerHasCooldown = providerCooldownHours > 0;
1212
+ if (!cooldownEndsAt || !providerHasCooldown) {
1213
+ return { cooldownRemaining: null, isOnCooldown: false };
1214
+ }
1215
+ const remainingMs = cooldownEndsAt.getTime() - Date.now();
1216
+ if (remainingMs <= 0) {
1217
+ return { cooldownRemaining: null, isOnCooldown: false };
1218
+ }
1219
+ const hours = Math.floor(remainingMs / (1e3 * 60 * 60));
1220
+ const minutes = Math.floor(remainingMs % (1e3 * 60 * 60) / (1e3 * 60));
1221
+ const formatted = hours > 0 ? `${hours}h ${minutes}m` : `${minutes}m`;
1222
+ return { cooldownRemaining: formatted, isOnCooldown: true };
1223
+ }, [cooldownEndsAt, hasLimits, tier, selectedPaymentMethod]);
1224
+ const noCooldownProviders = useMemo(() => {
1225
+ const available = verifiablePaymentMethods(chainId);
1226
+ return available.filter((key) => {
1227
+ if (key === selectedPaymentMethod) return false;
1228
+ const platformRisk = getPlatformRisk(chainId, key);
1229
+ if (!platformRisk.hasCooldown) return false;
1230
+ return getCooldownHours({ tier, providerKey: key }) === 0;
1231
+ });
1232
+ }, [hasLimits, chainId, selectedPaymentMethod, tier]);
1233
+ const selectedProviderCooldownHours = useMemo(() => {
1234
+ return getCooldownHours({ tier, providerKey: selectedPaymentMethod });
1235
+ }, [hasLimits, tier, selectedPaymentMethod]);
1236
+ const effectiveCap = useMemo(() => {
1237
+ return getEffectiveCap({ tier, providerKey: selectedPaymentMethod });
1238
+ }, [hasLimits, tier, selectedPaymentMethod]);
1239
+ const amountExceedsCap = useMemo(() => {
1240
+ if (effectiveCap === null) return false;
1241
+ if (!amountInInt) return false;
1242
+ const amountUsd = Number(amountInInt) / 1e6;
1243
+ return amountUsd > effectiveCap;
1244
+ }, [effectiveCap, amountInInt]);
1245
+ const capExceededMessage = useMemo(() => {
1246
+ if (!amountExceedsCap || effectiveCap === null) return null;
1247
+ const providerName = providerConfigs(chainId)[selectedPaymentMethod]?.name ?? selectedPaymentMethod;
1248
+ return `Amount exceeds your $${effectiveCap.toLocaleString()} limit for ${providerName}`;
1249
+ }, [amountExceedsCap, effectiveCap, chainId, selectedPaymentMethod]);
1250
+ return {
1251
+ hasLimits,
1252
+ noCooldownProviders,
1253
+ selectedProviderCooldownHours,
1254
+ cooldownRemaining,
1255
+ isOnCooldown,
1256
+ effectiveCap,
1257
+ amountExceedsCap,
1258
+ capExceededMessage
1259
+ };
1260
+ }
1261
+ var intentStatuses = {
1262
+ pending: "pending",
1263
+ signalled: "signalled",
1264
+ fulfilled: "fulfilled",
1265
+ pruned: "pruned"
1266
+ };
1267
+ function usePayeeDetails({
1268
+ intentHash,
1269
+ chainId
1270
+ }) {
1271
+ const { indexer, apiClient } = useProvex();
1272
+ const queryClient = useQueryClient();
1273
+ const intentQuery = useQuery({
1274
+ queryKey: ["provex", "intent", intentHash, chainId],
1275
+ queryFn: () => indexer.getIntent({ intentHash, chainId }),
1276
+ enabled: !!intentHash,
1277
+ staleTime: Infinity,
1278
+ refetchInterval: false
1279
+ });
1280
+ const indexedIntent = intentQuery.data ?? null;
1281
+ const intentStatus = useMemo(() => {
1282
+ if (!indexedIntent) return null;
1283
+ return indexedIntent.status;
1284
+ }, [indexedIntent]);
1285
+ const intent = useMemo(() => {
1286
+ if (!indexedIntent) return null;
1287
+ return {
1288
+ owner: indexedIntent.ownerAddress,
1289
+ to: indexedIntent.toAddress,
1290
+ escrow: indexedIntent.escrow,
1291
+ depositId: indexedIntent.depositLocalId,
1292
+ amount: indexedIntent.amount,
1293
+ timestamp: indexedIntent.timestamp,
1294
+ paymentMethod: indexedIntent.paymentMethodId,
1295
+ fiatCurrency: indexedIntent.fiatCurrency,
1296
+ conversionRate: indexedIntent.conversionRate
1297
+ };
1298
+ }, [indexedIntent]);
1299
+ const expiryTime = indexedIntent?.expiryTime ?? null;
1300
+ const depositQuery = useQuery({
1301
+ queryKey: ["provex", "deposit", indexedIntent?.escrow, indexedIntent?.depositLocalId, chainId],
1302
+ queryFn: () => indexer.getDepositWithVerifiers({
1303
+ escrow: indexedIntent.escrow,
1304
+ localId: indexedIntent.depositLocalId,
1305
+ chainId
1306
+ }),
1307
+ enabled: !!indexedIntent,
1308
+ staleTime: Infinity
1309
+ });
1310
+ const deposit = depositQuery.data ?? null;
1311
+ const providerKey = useMemo(() => {
1312
+ if (!deposit || !indexedIntent) return null;
1313
+ return verifierGetsKey(deposit.chainId, indexedIntent.paymentMethodId);
1314
+ }, [deposit, indexedIntent]);
1315
+ const userId = useMemo(() => {
1316
+ if (!deposit || !providerKey) return null;
1317
+ const verifier = deposit.verifiers.find(
1318
+ (v) => verifierGetsKey(deposit.chainId, v.paymentMethodId) === providerKey
1319
+ );
1320
+ return verifier?.payeeDetailsHash ?? null;
1321
+ }, [deposit, providerKey]);
1322
+ const apiProviderKey = useMemo(() => {
1323
+ if (!providerKey) return null;
1324
+ if (isSubProviderKey(providerKey)) {
1325
+ return getParentProviderKey(providerKey);
1326
+ }
1327
+ return providerKey;
1328
+ }, [providerKey]);
1329
+ const payeeDetailsQuery = useQuery({
1330
+ queryKey: ["provex", "payeeDetails", apiProviderKey, userId],
1331
+ queryFn: async () => {
1332
+ if (!userId || !apiProviderKey) return null;
1333
+ try {
1334
+ const response = await apiClient.get(
1335
+ `/api/v1/makers/${apiProviderKey}/${userId}`
1336
+ );
1337
+ return response.responseObject ?? null;
1338
+ } catch {
1339
+ return null;
1340
+ }
1341
+ },
1342
+ enabled: !!userId && !!apiProviderKey,
1343
+ staleTime: Infinity,
1344
+ retry: false
1345
+ });
1346
+ const payeeDetails = payeeDetailsQuery.data ?? null;
1347
+ const isFetching = intentQuery.isFetching || depositQuery.isFetching;
1348
+ const refetch = useCallback(() => {
1349
+ queryClient.invalidateQueries({ queryKey: ["provex", "intent", intentHash] });
1350
+ }, [queryClient, intentHash]);
1351
+ const refetchAll = useCallback(async () => {
1352
+ const [intentResult] = await Promise.all([
1353
+ intentQuery.refetch(),
1354
+ depositQuery.refetch(),
1355
+ payeeDetailsQuery.refetch()
1356
+ ]);
1357
+ const updated = intentResult.data;
1358
+ if (!updated) return null;
1359
+ return updated.status;
1360
+ }, [intentQuery, depositQuery, payeeDetailsQuery]);
1361
+ return useMemo(() => ({
1362
+ intentStatus,
1363
+ isFetching,
1364
+ isValid: !!intent,
1365
+ intent,
1366
+ providerKey,
1367
+ userId,
1368
+ payeeDetails,
1369
+ deposit,
1370
+ expiryTime,
1371
+ isV2Intent: false,
1372
+ // Adapter only returns V3 intents
1373
+ isPruned: indexedIntent?.status === "pruned",
1374
+ prunedAt: indexedIntent?.prunedAt ?? null,
1375
+ isFulfilled: indexedIntent?.status === "fulfilled",
1376
+ refetch,
1377
+ refetchAll
1378
+ }), [
1379
+ intentStatus,
1380
+ isFetching,
1381
+ intent,
1382
+ providerKey,
1383
+ userId,
1384
+ payeeDetails,
1385
+ deposit,
1386
+ expiryTime,
1387
+ indexedIntent,
1388
+ refetch,
1389
+ refetchAll
1390
+ ]);
1391
+ }
1392
+ function useContractRead(params) {
1393
+ const publicClient2 = useOptionalProvexPublicClient(params.chainId);
1394
+ const enabled = (params.query?.enabled ?? true) && !!publicClient2 && !!params.address;
1395
+ return useQuery({
1396
+ queryKey: [
1397
+ "provex",
1398
+ "readContract",
1399
+ params.chainId,
1400
+ params.address,
1401
+ params.functionName,
1402
+ params.args
1403
+ ],
1404
+ queryFn: async () => {
1405
+ if (!publicClient2) throw new Error("No public client available");
1406
+ if (!params.address) throw new Error("Missing contract address");
1407
+ const result = await publicClient2.readContract({
1408
+ address: params.address,
1409
+ abi: params.abi,
1410
+ functionName: params.functionName,
1411
+ args: params.args ?? []
1412
+ });
1413
+ return result;
1414
+ },
1415
+ enabled,
1416
+ staleTime: params.query?.staleTime,
1417
+ gcTime: params.query?.gcTime
1418
+ });
1419
+ }
1420
+ function useContractReads(params) {
1421
+ const firstChainId = params.contracts[0]?.chainId;
1422
+ const publicClient2 = useOptionalProvexPublicClient(firstChainId);
1423
+ const allHaveAddresses = params.contracts.every((c) => !!c.address);
1424
+ const enabled = (params.query?.enabled ?? true) && !!publicClient2 && allHaveAddresses && params.contracts.length > 0;
1425
+ return useQuery({
1426
+ queryKey: [
1427
+ "provex",
1428
+ "readContracts",
1429
+ firstChainId,
1430
+ params.contracts.map((c) => [c.address, c.functionName, c.args])
1431
+ ],
1432
+ queryFn: async () => {
1433
+ if (!publicClient2) throw new Error("No public client available");
1434
+ const results = await Promise.all(
1435
+ params.contracts.map(async (call) => {
1436
+ if (!call.address) {
1437
+ return {
1438
+ status: "failure",
1439
+ error: new Error("Missing contract address")
1440
+ };
1441
+ }
1442
+ try {
1443
+ const result = await publicClient2.readContract({
1444
+ address: call.address,
1445
+ abi: call.abi,
1446
+ functionName: call.functionName,
1447
+ args: call.args ?? []
1448
+ });
1449
+ return { status: "success", result };
1450
+ } catch (error) {
1451
+ return {
1452
+ status: "failure",
1453
+ error: error instanceof Error ? error : new Error(String(error))
1454
+ };
1455
+ }
1456
+ })
1457
+ );
1458
+ return results;
1459
+ },
1460
+ enabled,
1461
+ staleTime: params.query?.staleTime,
1462
+ gcTime: params.query?.gcTime
1463
+ });
1464
+ }
1465
+ var FEE_CACHE_STALE_TIME = 60 * 60 * 1e3;
1466
+ function useProtocolFees({
1467
+ chainId,
1468
+ escrowAddress,
1469
+ enabled = true
1470
+ }) {
1471
+ const {
1472
+ data: orchestratorAddress,
1473
+ isLoading: isLoadingOrchestrator,
1474
+ isError: isErrorOrchestrator,
1475
+ error: errorOrchestrator,
1476
+ refetch: refetchOrchestrator
1477
+ } = useContractRead({
1478
+ address: escrowAddress,
1479
+ abi: V3EscrowAbi,
1480
+ functionName: "orchestrator",
1481
+ chainId,
1482
+ query: {
1483
+ enabled,
1484
+ staleTime: FEE_CACHE_STALE_TIME,
1485
+ gcTime: FEE_CACHE_STALE_TIME
1486
+ }
1487
+ });
1488
+ const {
1489
+ data: feeData,
1490
+ isLoading: isLoadingFees,
1491
+ isError: isErrorFees,
1492
+ error: errorFees,
1493
+ refetch: refetchFees
1494
+ } = useContractReads({
1495
+ contracts: [
1496
+ {
1497
+ address: orchestratorAddress,
1498
+ abi: OrchestratorAbi,
1499
+ functionName: "protocolFee",
1500
+ chainId
1501
+ },
1502
+ {
1503
+ address: orchestratorAddress,
1504
+ abi: OrchestratorAbi,
1505
+ functionName: "protocolFeeRecipient",
1506
+ chainId
1507
+ }
1508
+ ],
1509
+ query: {
1510
+ enabled: enabled && !!orchestratorAddress,
1511
+ staleTime: FEE_CACHE_STALE_TIME,
1512
+ gcTime: FEE_CACHE_STALE_TIME
1513
+ }
1514
+ });
1515
+ const protocolFeeRaw = feeData?.[0]?.result;
1516
+ const protocolFeeRecipient = feeData?.[1]?.result;
1517
+ const feeInfo = useMemo(() => {
1518
+ if (protocolFeeRaw === void 0) return void 0;
1519
+ return normalizeFeePrecision(protocolFeeRaw);
1520
+ }, [protocolFeeRaw]);
1521
+ const isFeeQueryPending = !!orchestratorAddress && protocolFeeRaw === void 0 && !isErrorFees;
1522
+ const isLoading = isLoadingOrchestrator || isLoadingFees || isFeeQueryPending;
1523
+ const isError = isErrorOrchestrator || isErrorFees;
1524
+ const error = errorOrchestrator || errorFees || null;
1525
+ const refetch = () => {
1526
+ refetchOrchestrator();
1527
+ refetchFees();
1528
+ };
1529
+ return {
1530
+ protocolFeeRaw,
1531
+ feeInfo,
1532
+ protocolFeeRecipient,
1533
+ orchestratorAddress,
1534
+ isLoading,
1535
+ isError,
1536
+ error,
1537
+ refetch
1538
+ };
1539
+ }
1540
+ function useProtocolFeePercentage(params) {
1541
+ const { feeInfo } = useProtocolFees(params);
1542
+ return feeInfo?.percentage;
1543
+ }
1544
+ function parseAmountSafe(value, decimals) {
1545
+ if (!value || value === "." || value === "0.") return null;
1546
+ try {
1547
+ const parsed = parseUnits(value, { decimals });
1548
+ return parsed > 0n ? parsed : null;
1549
+ } catch {
1550
+ return null;
1551
+ }
1552
+ }
1553
+ function useProvexBuy({
1554
+ wallet,
1555
+ onIntentSignaled,
1556
+ onComplete,
1557
+ paymentMethods: allowedPaymentMethods
1558
+ }) {
1559
+ const { config } = useProvex();
1560
+ const [phase, setPhase] = useState("browse");
1561
+ const [amount, setAmountRaw] = useState("");
1562
+ const [selectedPaymentMethod, setSelectedPaymentMethod] = useState("");
1563
+ const [selectedDeposit, setSelectedDeposit] = useState(null);
1564
+ const [intentHash, setIntentHash] = useState(null);
1565
+ const [errorMessage, setErrorMessage] = useState(null);
1566
+ const chainId = config.chain?.id ?? config.chainId;
1567
+ const token = useMemo(() => getDefaultToken(chainId), [chainId]);
1568
+ const currency = SUPPORTED_CURRENCIES.USD;
1569
+ const availablePaymentMethods = useMemo(() => {
1570
+ const all = verifiablePaymentMethods(chainId);
1571
+ if (!allowedPaymentMethods || allowedPaymentMethods.length === 0) return all;
1572
+ return all.filter((pm) => allowedPaymentMethods.includes(pm));
1573
+ }, [chainId, allowedPaymentMethods]);
1574
+ const activePaymentMethod = useMemo(() => {
1575
+ if (selectedPaymentMethod) return selectedPaymentMethod;
1576
+ return availablePaymentMethods[0] ?? null;
1577
+ }, [selectedPaymentMethod, availablePaymentMethods]);
1578
+ const depositsResult = useDeposits({
1579
+ token,
1580
+ paymentMethod: activePaymentMethod,
1581
+ currency
1582
+ });
1583
+ const { reputation } = useReputation({
1584
+ address: wallet.address,
1585
+ chainId
1586
+ });
1587
+ const amountBigInt = useMemo(
1588
+ () => parseAmountSafe(amount, currency.decimals),
1589
+ [amount, currency.decimals]
1590
+ );
1591
+ const limits = useReputationLimits({
1592
+ chainId,
1593
+ selectedPaymentMethod: activePaymentMethod,
1594
+ tier: reputation.tier,
1595
+ amountInInt: amountBigInt,
1596
+ cooldownEndsAt: reputation.cooldownEndsAt
1597
+ });
1598
+ const signalIntent = useSignalIntent({
1599
+ wallet,
1600
+ chainId,
1601
+ deposit: selectedDeposit,
1602
+ onSuccess: (hash) => {
1603
+ setIntentHash(hash);
1604
+ setPhase("committed");
1605
+ onIntentSignaled?.(hash, chainId);
1606
+ },
1607
+ onFailure: () => {
1608
+ setErrorMessage("Order failed. Please try again.");
1609
+ },
1610
+ refetchDeposits: depositsResult.refetch
1611
+ });
1612
+ const escrowAddress = useMemo(
1613
+ () => getLatestContract(chainId, "escrow"),
1614
+ [chainId]
1615
+ );
1616
+ const { feeInfo } = useProtocolFees({
1617
+ chainId,
1618
+ escrowAddress: escrowAddress ?? "0x",
1619
+ enabled: !!escrowAddress
1620
+ });
1621
+ const payeeResult = usePayeeDetails({
1622
+ intentHash,
1623
+ chainId
1624
+ });
1625
+ const refetchAllRef = useRef(payeeResult.refetchAll);
1626
+ refetchAllRef.current = payeeResult.refetchAll;
1627
+ useEffect(() => {
1628
+ if (phase !== "committed" && phase !== "proving") return;
1629
+ if (!intentHash) return;
1630
+ const interval = setInterval(() => {
1631
+ refetchAllRef.current();
1632
+ }, 5e3);
1633
+ return () => clearInterval(interval);
1634
+ }, [phase, intentHash]);
1635
+ useEffect(() => {
1636
+ if (!payeeResult.isFulfilled) return;
1637
+ if (phase === "complete") return;
1638
+ setPhase("complete");
1639
+ if (intentHash) onComplete?.(intentHash, chainId);
1640
+ }, [payeeResult.isFulfilled, phase, intentHash, chainId, onComplete]);
1641
+ useEffect(() => {
1642
+ if (!payeeResult.isPruned) return;
1643
+ if (phase === "browse") return;
1644
+ setErrorMessage("Order expired. Please try again.");
1645
+ setPhase("browse");
1646
+ }, [payeeResult.isPruned, phase]);
1647
+ const intentExpiryTime = useMemo(() => {
1648
+ if (!payeeResult.expiryTime) return null;
1649
+ return new Date(Number(payeeResult.expiryTime) * 1e3);
1650
+ }, [payeeResult.expiryTime]);
1651
+ const matchableDeposits = useMemo(() => {
1652
+ if (!amountBigInt) return [];
1653
+ return depositsResult.getMatchableDeposits(amountBigInt);
1654
+ }, [amountBigInt, depositsResult]);
1655
+ const bestDeposit = matchableDeposits[0] ?? null;
1656
+ const bestRate = useMemo(() => {
1657
+ if (!bestDeposit || !activePaymentMethod) return null;
1658
+ const r = getRate({ deposit: bestDeposit, paymentMethod: activePaymentMethod, currency });
1659
+ return r === 0n ? null : r;
1660
+ }, [bestDeposit, activePaymentMethod, currency]);
1661
+ const tokenAmount = useMemo(() => {
1662
+ if (!amountBigInt || !bestRate || !token) return null;
1663
+ return convertCurrencyToTokenOutput({
1664
+ token,
1665
+ currency,
1666
+ currencyAmountInt: amountBigInt,
1667
+ rate: bestRate
1668
+ });
1669
+ }, [amountBigInt, bestRate, token, currency]);
1670
+ const rateDisplay = useMemo(() => {
1671
+ if (!bestRate || !token) return null;
1672
+ const rateFloat = Number(bestRate) / 1e18;
1673
+ return `1 ${token.symbol} = ${currency.symbol}${rateFloat.toFixed(currency.decimals)}`;
1674
+ }, [bestRate, token, currency]);
1675
+ const tokenAmountDisplay = useMemo(() => {
1676
+ if (!tokenAmount || !token) return null;
1677
+ return formatUnits(tokenAmount, { decimals: token.decimals });
1678
+ }, [tokenAmount, token]);
1679
+ const canSubmit = useMemo(() => {
1680
+ if (!wallet.address) return false;
1681
+ if (!activePaymentMethod) return false;
1682
+ if (!amountBigInt || amountBigInt <= 0n) return false;
1683
+ if (!bestDeposit) return false;
1684
+ if (limits.isOnCooldown) return false;
1685
+ if (limits.amountExceedsCap) return false;
1686
+ if (signalIntent.isLoading) return false;
1687
+ return true;
1688
+ }, [wallet.address, activePaymentMethod, amountBigInt, bestDeposit, limits, signalIntent.isLoading]);
1689
+ const validationMessage = useMemo(() => {
1690
+ if (!wallet.address) return "Connect your wallet to continue";
1691
+ if (!activePaymentMethod) return "Select a payment method";
1692
+ if (!amount) return null;
1693
+ if (!amountBigInt || amountBigInt <= 0n) return "Enter a valid amount";
1694
+ if (limits.isOnCooldown && limits.cooldownRemaining) {
1695
+ return `Cooldown active: ${limits.cooldownRemaining} remaining`;
1696
+ }
1697
+ if (limits.capExceededMessage) return limits.capExceededMessage;
1698
+ if (depositsResult.isLoading) return "Loading available orders...";
1699
+ if (!bestDeposit && amount) return "No orders available for this amount";
1700
+ return null;
1701
+ }, [wallet.address, activePaymentMethod, amount, amountBigInt, limits, depositsResult.isLoading, bestDeposit]);
1702
+ const setAmount = useCallback((value) => {
1703
+ if (value === "" || /^\d*\.?\d*$/.test(value)) {
1704
+ setAmountRaw(value);
1705
+ setErrorMessage(null);
1706
+ }
1707
+ }, []);
1708
+ const selectDeposit = useCallback((deposit) => {
1709
+ setSelectedDeposit(deposit);
1710
+ }, []);
1711
+ const submitOrder = useCallback(async () => {
1712
+ if (!canSubmit || !bestDeposit || !tokenAmount || !activePaymentMethod || !wallet.address) return;
1713
+ setSelectedDeposit(bestDeposit);
1714
+ setErrorMessage(null);
1715
+ const paymentMethodContractId = providerKeyToContractId(activePaymentMethod);
1716
+ await signalIntent.startOrder({
1717
+ paymentMethod: paymentMethodContractId,
1718
+ depositId: bestDeposit.localId,
1719
+ tokenAmount,
1720
+ toAddress: wallet.address,
1721
+ fiatCurrencyCode: currency.contractId,
1722
+ conversionRate: bestRate
1723
+ });
1724
+ }, [canSubmit, bestDeposit, tokenAmount, activePaymentMethod, wallet.address, signalIntent, currency.contractId, bestRate]);
1725
+ const confirmPayment = useCallback(() => {
1726
+ setPhase("proving");
1727
+ }, []);
1728
+ const reset = useCallback(() => {
1729
+ setPhase("browse");
1730
+ setAmountRaw("");
1731
+ setSelectedPaymentMethod("");
1732
+ setSelectedDeposit(null);
1733
+ setIntentHash(null);
1734
+ setErrorMessage(null);
1735
+ }, []);
1736
+ return {
1737
+ phase,
1738
+ amount,
1739
+ setAmount,
1740
+ selectedPaymentMethod,
1741
+ setSelectedPaymentMethod,
1742
+ availablePaymentMethods,
1743
+ deposits: depositsResult.deposits,
1744
+ selectedDeposit,
1745
+ selectDeposit,
1746
+ isLoadingDeposits: depositsResult.isLoading,
1747
+ rate: bestRate,
1748
+ rateDisplay,
1749
+ tokenAmount,
1750
+ tokenAmountDisplay,
1751
+ token,
1752
+ currency,
1753
+ reputation: reputation ?? DEFAULT_REPUTATION,
1754
+ limits,
1755
+ feePercentage: feeInfo?.percentage ?? null,
1756
+ payeeDetails: payeeResult.payeeDetails,
1757
+ payeeName: payeeResult.payeeDetails?.name ?? null,
1758
+ payeeId: payeeResult.payeeDetails?.payeeId ?? null,
1759
+ isPayeeLoading: payeeResult.isFetching,
1760
+ intentExpiryTime,
1761
+ isIntentExpired: payeeResult.isPruned,
1762
+ indexedIntentStatus: payeeResult.intentStatus,
1763
+ canSubmit,
1764
+ validationMessage,
1765
+ submitOrder,
1766
+ confirmPayment,
1767
+ reset,
1768
+ intentHash,
1769
+ intentStatus: signalIntent.status,
1770
+ intentError: errorMessage ?? signalIntent.message,
1771
+ isSubmitting: signalIntent.isLoading,
1772
+ chainId
1773
+ };
1774
+ }
1775
+ var ProvexBuyContext = createContext(null);
1776
+ function useProvexBuyContext() {
1777
+ const ctx = useContext(ProvexBuyContext);
1778
+ if (!ctx) {
1779
+ throw new Error(
1780
+ "useProvexBuyContext must be used within a <ProvexBuyProvider>. Wrap your component tree with <ProvexBuyProvider> or use useProvexBuy() directly."
1781
+ );
1782
+ }
1783
+ return ctx;
1784
+ }
1785
+ function ProvexBuyProvider({
1786
+ children,
1787
+ ...options
1788
+ }) {
1789
+ const buy = useProvexBuy(options);
1790
+ return /* @__PURE__ */ jsx(ProvexBuyContext.Provider, { value: buy, children });
1791
+ }
1792
+ var STATUS_MESSAGES = {
1793
+ input: "",
1794
+ loading_payee: "Loading payment details...",
1795
+ loading_intent: "Requesting signature...",
1796
+ loading_orchestrator: "Loading orchestrator...",
1797
+ prompt_wallet_confirm: "Confirm in your wallet...",
1798
+ writing_intent: "Submitting transaction...",
1799
+ success: "Order placed successfully!",
1800
+ error: "Something went wrong."
1801
+ };
1802
+ function BrowsePhase({
1803
+ className,
1804
+ style,
1805
+ render
1806
+ }) {
1807
+ const ctx = useProvexBuyContext();
1808
+ if (ctx.phase !== "browse") return null;
1809
+ const state = {
1810
+ amount: ctx.amount,
1811
+ setAmount: ctx.setAmount,
1812
+ selectedPaymentMethod: ctx.selectedPaymentMethod,
1813
+ setSelectedPaymentMethod: ctx.setSelectedPaymentMethod,
1814
+ availablePaymentMethods: ctx.availablePaymentMethods,
1815
+ chainId: ctx.chainId,
1816
+ rateDisplay: ctx.rateDisplay,
1817
+ tokenAmountDisplay: ctx.tokenAmountDisplay,
1818
+ token: ctx.token,
1819
+ currency: ctx.currency,
1820
+ canSubmit: ctx.canSubmit,
1821
+ isSubmitting: ctx.isSubmitting,
1822
+ validationMessage: ctx.validationMessage,
1823
+ intentError: ctx.intentError,
1824
+ intentStatus: ctx.intentStatus,
1825
+ isLoadingDeposits: ctx.isLoadingDeposits,
1826
+ deposits: ctx.deposits,
1827
+ submitOrder: ctx.submitOrder
1828
+ };
1829
+ if (render) return /* @__PURE__ */ jsx(Fragment, { children: render(state) });
1830
+ const tokenSymbol = ctx.token?.symbol ?? "USDC";
1831
+ const matchCount = ctx.deposits.length;
1832
+ const statusMessage = STATUS_MESSAGES[ctx.intentStatus] ?? "";
1833
+ return /* @__PURE__ */ jsxs(
1834
+ "div",
1835
+ {
1836
+ "data-provex-phase": "browse",
1837
+ "data-provex-section": "browse",
1838
+ className,
1839
+ style,
1840
+ children: [
1841
+ /* @__PURE__ */ jsxs("div", { "data-provex-field": "payment-method", children: [
1842
+ /* @__PURE__ */ jsx("label", { "data-provex-label": "payment-method", htmlFor: "provex-payment-method", children: "Payment Method" }),
1843
+ /* @__PURE__ */ jsx(
1844
+ "select",
1845
+ {
1846
+ "data-provex-select": "payment-method",
1847
+ id: "provex-payment-method",
1848
+ value: ctx.selectedPaymentMethod || (ctx.availablePaymentMethods[0] ?? ""),
1849
+ onChange: (e) => ctx.setSelectedPaymentMethod(e.target.value),
1850
+ children: ctx.availablePaymentMethods.map((pm) => /* @__PURE__ */ jsx("option", { value: pm, children: getPaymentMethodName(ctx.chainId, pm) }, pm))
1851
+ }
1852
+ )
1853
+ ] }),
1854
+ /* @__PURE__ */ jsxs("div", { "data-provex-field": "amount", children: [
1855
+ /* @__PURE__ */ jsxs("label", { "data-provex-label": "amount", htmlFor: "provex-amount", children: [
1856
+ "Amount (",
1857
+ ctx.currency?.ticker ?? "USD",
1858
+ ")"
1859
+ ] }),
1860
+ /* @__PURE__ */ jsxs("div", { "data-provex-input-group": "amount", children: [
1861
+ /* @__PURE__ */ jsx("span", { "data-provex-input-prefix": "", children: ctx.currency?.symbol ?? "$" }),
1862
+ /* @__PURE__ */ jsx(
1863
+ "input",
1864
+ {
1865
+ "data-provex-input": "amount",
1866
+ id: "provex-amount",
1867
+ type: "text",
1868
+ inputMode: "decimal",
1869
+ placeholder: "0.00",
1870
+ value: ctx.amount,
1871
+ onChange: (e) => ctx.setAmount(e.target.value),
1872
+ autoComplete: "off"
1873
+ }
1874
+ )
1875
+ ] })
1876
+ ] }),
1877
+ ctx.rateDisplay && /* @__PURE__ */ jsxs("div", { "data-provex-info": "rate", children: [
1878
+ /* @__PURE__ */ jsx("span", { "data-provex-label": "rate", children: "Rate" }),
1879
+ /* @__PURE__ */ jsx("span", { "data-provex-value": "rate", children: ctx.rateDisplay })
1880
+ ] }),
1881
+ ctx.tokenAmountDisplay && /* @__PURE__ */ jsxs("div", { "data-provex-info": "receive", children: [
1882
+ /* @__PURE__ */ jsx("span", { "data-provex-label": "receive", children: "You receive" }),
1883
+ /* @__PURE__ */ jsxs("span", { "data-provex-value": "receive", children: [
1884
+ ctx.tokenAmountDisplay,
1885
+ " ",
1886
+ tokenSymbol
1887
+ ] })
1888
+ ] }),
1889
+ ctx.isLoadingDeposits && ctx.amount && /* @__PURE__ */ jsx("div", { "data-provex-info": "loading", children: /* @__PURE__ */ jsx("span", { "data-provex-status": "loading", children: "Searching for orders..." }) }),
1890
+ !ctx.isLoadingDeposits && ctx.amount && matchCount > 0 && /* @__PURE__ */ jsx("div", { "data-provex-info": "match-count", children: /* @__PURE__ */ jsxs("span", { "data-provex-value": "match-count", children: [
1891
+ matchCount,
1892
+ " order",
1893
+ matchCount !== 1 ? "s" : "",
1894
+ " available"
1895
+ ] }) }),
1896
+ ctx.validationMessage && /* @__PURE__ */ jsx("p", { "data-provex-message": "validation", children: ctx.validationMessage }),
1897
+ ctx.intentError && /* @__PURE__ */ jsx("p", { "data-provex-message": "error", children: ctx.intentError }),
1898
+ ctx.isSubmitting && statusMessage && /* @__PURE__ */ jsx("p", { "data-provex-message": "status", children: statusMessage }),
1899
+ /* @__PURE__ */ jsx(
1900
+ "button",
1901
+ {
1902
+ "data-provex-button": "buy",
1903
+ type: "button",
1904
+ disabled: !ctx.canSubmit,
1905
+ onClick: ctx.submitOrder,
1906
+ children: ctx.isSubmitting ? "Processing..." : "Buy"
1907
+ }
1908
+ )
1909
+ ]
1910
+ }
1911
+ );
1912
+ }
1913
+ function CommittedPhase({
1914
+ className,
1915
+ style,
1916
+ render
1917
+ }) {
1918
+ const ctx = useProvexBuyContext();
1919
+ if (ctx.phase !== "committed") return null;
1920
+ const state = {
1921
+ intentHash: ctx.intentHash,
1922
+ amount: ctx.amount,
1923
+ currency: ctx.currency,
1924
+ selectedPaymentMethod: ctx.selectedPaymentMethod,
1925
+ chainId: ctx.chainId,
1926
+ tokenAmountDisplay: ctx.tokenAmountDisplay,
1927
+ token: ctx.token,
1928
+ confirmPayment: ctx.confirmPayment,
1929
+ payeeDetails: ctx.payeeDetails,
1930
+ payeeName: ctx.payeeName,
1931
+ payeeId: ctx.payeeId,
1932
+ isPayeeLoading: ctx.isPayeeLoading,
1933
+ intentExpiryTime: ctx.intentExpiryTime
1934
+ };
1935
+ if (render) return /* @__PURE__ */ jsx(Fragment, { children: render(state) });
1936
+ const tokenSymbol = ctx.token?.symbol ?? "USDC";
1937
+ const paymentName = ctx.selectedPaymentMethod ? getPaymentMethodName(ctx.chainId, ctx.selectedPaymentMethod) : "Unknown";
1938
+ return /* @__PURE__ */ jsxs(
1939
+ "div",
1940
+ {
1941
+ "data-provex-phase": "committed",
1942
+ "data-provex-section": "committed",
1943
+ className,
1944
+ style,
1945
+ children: [
1946
+ /* @__PURE__ */ jsxs("div", { "data-provex-info": "order-summary", children: [
1947
+ /* @__PURE__ */ jsx("p", { "data-provex-heading": "committed", children: "Order Placed" }),
1948
+ /* @__PURE__ */ jsxs("div", { "data-provex-detail": "amount", children: [
1949
+ /* @__PURE__ */ jsx("span", { "data-provex-label": "amount", children: "Amount" }),
1950
+ /* @__PURE__ */ jsxs("span", { "data-provex-value": "amount", children: [
1951
+ ctx.currency?.symbol,
1952
+ ctx.amount
1953
+ ] })
1954
+ ] }),
1955
+ /* @__PURE__ */ jsxs("div", { "data-provex-detail": "receive", children: [
1956
+ /* @__PURE__ */ jsx("span", { "data-provex-label": "receive", children: "You receive" }),
1957
+ /* @__PURE__ */ jsxs("span", { "data-provex-value": "receive", children: [
1958
+ ctx.tokenAmountDisplay,
1959
+ " ",
1960
+ tokenSymbol
1961
+ ] })
1962
+ ] }),
1963
+ /* @__PURE__ */ jsxs("div", { "data-provex-detail": "payment-method", children: [
1964
+ /* @__PURE__ */ jsx("span", { "data-provex-label": "payment-method", children: "Pay via" }),
1965
+ /* @__PURE__ */ jsx("span", { "data-provex-value": "payment-method", children: paymentName })
1966
+ ] }),
1967
+ ctx.intentHash && /* @__PURE__ */ jsxs("div", { "data-provex-detail": "intent-hash", children: [
1968
+ /* @__PURE__ */ jsx("span", { "data-provex-label": "intent-hash", children: "Order ID" }),
1969
+ /* @__PURE__ */ jsxs("span", { "data-provex-value": "intent-hash", title: ctx.intentHash, children: [
1970
+ ctx.intentHash.slice(0, 10),
1971
+ "...",
1972
+ ctx.intentHash.slice(-8)
1973
+ ] })
1974
+ ] })
1975
+ ] }),
1976
+ ctx.isPayeeLoading && /* @__PURE__ */ jsx("div", { "data-provex-info": "payee-loading", children: /* @__PURE__ */ jsx("span", { "data-provex-status": "loading", children: "Loading seller details..." }) }),
1977
+ !ctx.isPayeeLoading && ctx.payeeId && /* @__PURE__ */ jsxs("div", { "data-provex-info": "payee", children: [
1978
+ ctx.payeeName && /* @__PURE__ */ jsxs("div", { "data-provex-detail": "payee-name", children: [
1979
+ /* @__PURE__ */ jsx("span", { "data-provex-label": "payee-name", children: "Seller" }),
1980
+ /* @__PURE__ */ jsx("span", { "data-provex-value": "payee-name", children: ctx.payeeName })
1981
+ ] }),
1982
+ /* @__PURE__ */ jsxs("div", { "data-provex-detail": "payee-id", children: [
1983
+ /* @__PURE__ */ jsx("span", { "data-provex-label": "payee-id", children: "Send to" }),
1984
+ /* @__PURE__ */ jsx("span", { "data-provex-value": "payee-id", children: ctx.payeeId })
1985
+ ] })
1986
+ ] }),
1987
+ /* @__PURE__ */ jsx("div", { "data-provex-info": "instructions", children: /* @__PURE__ */ jsxs("p", { "data-provex-text": "instructions", children: [
1988
+ "Send ",
1989
+ ctx.currency?.symbol,
1990
+ ctx.amount,
1991
+ " via ",
1992
+ paymentName,
1993
+ " to the seller, then verify your payment to release the ",
1994
+ tokenSymbol,
1995
+ "."
1996
+ ] }) }),
1997
+ /* @__PURE__ */ jsx(
1998
+ "button",
1999
+ {
2000
+ "data-provex-button": "prove",
2001
+ type: "button",
2002
+ disabled: ctx.isPayeeLoading,
2003
+ onClick: ctx.confirmPayment,
2004
+ children: "I have paid"
2005
+ }
2006
+ )
2007
+ ]
2008
+ }
2009
+ );
2010
+ }
2011
+ function ProvingPhase({
2012
+ className,
2013
+ style,
2014
+ render
2015
+ }) {
2016
+ const ctx = useProvexBuyContext();
2017
+ if (ctx.phase !== "proving") return null;
2018
+ const state = {
2019
+ intentHash: ctx.intentHash,
2020
+ intentExpiryTime: ctx.intentExpiryTime,
2021
+ isIntentExpired: ctx.isIntentExpired,
2022
+ indexedIntentStatus: ctx.indexedIntentStatus
2023
+ };
2024
+ if (render) return /* @__PURE__ */ jsx(Fragment, { children: render(state) });
2025
+ const statusText = ctx.indexedIntentStatus === "fulfilled" ? "Payment verified!" : "Generating zero-knowledge proof of your payment...";
2026
+ return /* @__PURE__ */ jsxs(
2027
+ "div",
2028
+ {
2029
+ "data-provex-phase": "proving",
2030
+ "data-provex-section": "proving",
2031
+ className,
2032
+ style,
2033
+ children: [
2034
+ /* @__PURE__ */ jsx("p", { "data-provex-heading": "proving", children: "Verifying Payment" }),
2035
+ /* @__PURE__ */ jsx("p", { "data-provex-text": "proving", children: statusText }),
2036
+ ctx.intentHash && /* @__PURE__ */ jsxs("div", { "data-provex-detail": "intent-hash", children: [
2037
+ /* @__PURE__ */ jsx("span", { "data-provex-label": "intent-hash", children: "Order ID" }),
2038
+ /* @__PURE__ */ jsxs("span", { "data-provex-value": "intent-hash", title: ctx.intentHash, children: [
2039
+ ctx.intentHash.slice(0, 10),
2040
+ "...",
2041
+ ctx.intentHash.slice(-8)
2042
+ ] })
2043
+ ] }),
2044
+ /* @__PURE__ */ jsx("div", { "data-provex-info": "status", children: /* @__PURE__ */ jsx("span", { "data-provex-status": ctx.indexedIntentStatus ?? "proving", children: ctx.indexedIntentStatus === "fulfilled" ? "Complete" : "Processing..." }) })
2045
+ ]
2046
+ }
2047
+ );
2048
+ }
2049
+ function CompletePhase({
2050
+ className,
2051
+ style,
2052
+ render
2053
+ }) {
2054
+ const ctx = useProvexBuyContext();
2055
+ if (ctx.phase !== "complete") return null;
2056
+ const state = {
2057
+ intentHash: ctx.intentHash,
2058
+ chainId: ctx.chainId,
2059
+ reset: ctx.reset
2060
+ };
2061
+ if (render) return /* @__PURE__ */ jsx(Fragment, { children: render(state) });
2062
+ return /* @__PURE__ */ jsxs(
2063
+ "div",
2064
+ {
2065
+ "data-provex-phase": "complete",
2066
+ "data-provex-section": "complete",
2067
+ className,
2068
+ style,
2069
+ children: [
2070
+ /* @__PURE__ */ jsx("p", { "data-provex-heading": "complete", children: "Purchase Complete" }),
2071
+ /* @__PURE__ */ jsx("p", { "data-provex-text": "complete", children: "Your tokens have been released to your wallet." }),
2072
+ ctx.intentHash && /* @__PURE__ */ jsxs("div", { "data-provex-detail": "intent-hash", children: [
2073
+ /* @__PURE__ */ jsx("span", { "data-provex-label": "intent-hash", children: "Order ID" }),
2074
+ /* @__PURE__ */ jsxs("span", { "data-provex-value": "intent-hash", title: ctx.intentHash, children: [
2075
+ ctx.intentHash.slice(0, 10),
2076
+ "...",
2077
+ ctx.intentHash.slice(-8)
2078
+ ] })
2079
+ ] }),
2080
+ /* @__PURE__ */ jsx(
2081
+ "button",
2082
+ {
2083
+ "data-provex-button": "buy-more",
2084
+ type: "button",
2085
+ onClick: ctx.reset,
2086
+ children: "Buy More"
2087
+ }
2088
+ )
2089
+ ]
2090
+ }
2091
+ );
2092
+ }
2093
+ function applyTheme(baseStyle, theme) {
2094
+ if (!theme) return baseStyle;
2095
+ const vars = {};
2096
+ const themeEntries = [
2097
+ ["accent", theme.accent],
2098
+ ["background", theme.background],
2099
+ ["backgroundCard", theme.backgroundCard],
2100
+ ["text", theme.text],
2101
+ ["textMuted", theme.textMuted],
2102
+ ["border", theme.border],
2103
+ ["error", theme.error],
2104
+ ["radius", theme.radius],
2105
+ ["font", theme.font]
2106
+ ];
2107
+ for (const [key, value] of themeEntries) {
2108
+ if (value === void 0) continue;
2109
+ const kebab = key.replace(/[A-Z]/g, (ch) => `-${ch.toLowerCase()}`);
2110
+ vars[`--provex-${kebab}`] = value;
2111
+ }
2112
+ if (Object.keys(vars).length === 0) return baseStyle;
2113
+ return { ...baseStyle, ...vars };
2114
+ }
2115
+ function ProvexBuy({
2116
+ wallet,
2117
+ onIntentSignaled,
2118
+ onComplete,
2119
+ paymentMethods,
2120
+ className,
2121
+ style,
2122
+ theme
2123
+ }) {
2124
+ return /* @__PURE__ */ jsx(
2125
+ ProvexBuyProvider,
2126
+ {
2127
+ wallet,
2128
+ onIntentSignaled,
2129
+ onComplete,
2130
+ paymentMethods,
2131
+ children: /* @__PURE__ */ jsx(
2132
+ ProvexBuyRoot,
2133
+ {
2134
+ className,
2135
+ style: applyTheme(style, theme)
2136
+ }
2137
+ )
2138
+ }
2139
+ );
2140
+ }
2141
+ function ProvexBuyRoot({
2142
+ className,
2143
+ style
2144
+ }) {
2145
+ const { phase } = useProvexBuyContext();
2146
+ return /* @__PURE__ */ jsxs(
2147
+ "div",
2148
+ {
2149
+ className,
2150
+ style,
2151
+ "data-provex-root": "",
2152
+ "data-provex-phase": phase,
2153
+ children: [
2154
+ /* @__PURE__ */ jsx(BrowsePhase, {}),
2155
+ /* @__PURE__ */ jsx(CommittedPhase, {}),
2156
+ /* @__PURE__ */ jsx(ProvingPhase, {}),
2157
+ /* @__PURE__ */ jsx(CompletePhase, {})
2158
+ ]
2159
+ }
2160
+ );
2161
+ }
2162
+
2163
+ export { BrowsePhase, CommittedPhase, CompletePhase, ProveXClient, ProveXError, ProvexBuy, ProvexBuyProvider, ProvexProvider, ProvingPhase, checkMutation, checkTransactionIndexed, createApiClient, createProveXClient, getRate, getTierDisplayInfo, getTransactionGasInputs, getUserFriendlyErrorMessage, intentStatuses, isUserRejectionError, useContractRead, useDeposits, useOptionalProvex, useOptionalProvexPublicClient, useOptionalProvexWallet, usePayeeDetails, useProtocolFeePercentage, useProtocolFees, useProvex, useProvexBuy, useProvexBuyContext, useProvexPublicClient, useProvexWallet, useReputation, useReputationLimits, useSignalIntent };
2164
+ //# sourceMappingURL=chunk-7BVFQVKS.js.map
2165
+ //# sourceMappingURL=chunk-7BVFQVKS.js.map