@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,1013 @@
1
+ import * as react_jsx_runtime from 'react/jsx-runtime';
2
+ import React__default from 'react';
3
+ import { QueryClient } from '@tanstack/react-query';
4
+ import { Hex, Chain, TransactionReceipt, PublicClient } from 'viem';
5
+ import { ChainId } from '@provex/utils/chain';
6
+ import * as _provex_utils_payment from '@provex/utils/payment';
7
+ import { ProviderKey, SubProviderKey, TakerTier } from '@provex/utils/payment';
8
+ import { UserReputation } from '@provex/utils/reputation';
9
+ import { Currency } from '@provex/utils/currencies';
10
+ import { TokenInfo } from '@provex/utils/tokens';
11
+
12
+ /**
13
+ * @fileoverview Hook for fetching deposits that match a buyer's criteria.
14
+ *
15
+ * Queries the IndexerAdapter for active V3 deposits that:
16
+ * - Support the specified payment method
17
+ * - Support the specified fiat currency
18
+ * - Have sufficient liquidity for the requested amount
19
+ * - Are accepting intents
20
+ *
21
+ * @see {@link @provex/utils/payment} for provider configuration
22
+ */
23
+
24
+ /**
25
+ * Lightweight deposit info returned by the hook.
26
+ * Maps from IndexedDeposit — same shape the UI already consumes.
27
+ */
28
+ interface DepositInfo {
29
+ escrow: Hex;
30
+ localId: bigint;
31
+ chainId: number;
32
+ participantAddress: Hex;
33
+ token: Hex;
34
+ remaining: bigint;
35
+ deposited: bigint;
36
+ minAmount: bigint;
37
+ maxAmount: bigint;
38
+ status: string;
39
+ acceptingIntents: boolean;
40
+ availableFunds: bigint;
41
+ conversionRates: Map<string, Map<string, bigint>>;
42
+ verifierPaymentMethodIds: Set<string>;
43
+ }
44
+ /** Options for the useDeposits hook. */
45
+ interface UseDepositsOptions {
46
+ token: TokenInfo;
47
+ paymentMethod: ProviderKey;
48
+ currency?: Currency;
49
+ refetchIntervalMs?: number;
50
+ }
51
+ /**
52
+ * Get the best (lowest) conversion rate for a deposit across the main provider
53
+ * and all sub-providers.
54
+ *
55
+ * Returns 0n when the deposit has no rate for the given payment method / currency.
56
+ */
57
+ declare function getRate({ deposit, paymentMethod, currency, }: {
58
+ deposit: DepositInfo | null | undefined;
59
+ paymentMethod: ProviderKey | SubProviderKey;
60
+ currency: Currency;
61
+ }): bigint;
62
+ /**
63
+ * Hook to fetch matchable deposits from the indexer.
64
+ *
65
+ * @example
66
+ * ```ts
67
+ * const { deposits, isLoading, getMatchableDeposits } = useDeposits({
68
+ * token: usdcToken,
69
+ * paymentMethod: 'venmo',
70
+ * })
71
+ *
72
+ * const matches = getMatchableDeposits(parseUnits('100', { decimals: 2 }))
73
+ * ```
74
+ */
75
+ declare function useDeposits(options: UseDepositsOptions): {
76
+ deposits: DepositInfo[];
77
+ isLoading: boolean;
78
+ isUpdating: boolean;
79
+ error: Error | null;
80
+ refetch: () => void;
81
+ filterDepositsByAmount: (amountInInt: bigint) => DepositInfo[];
82
+ getMatchableDeposits: (amountInInt: bigint | null | string) => DepositInfo[];
83
+ };
84
+
85
+ /**
86
+ * @fileoverview IndexerAdapter — data source abstraction for @provex/react.
87
+ *
88
+ * Decouples the react hooks from any specific indexer implementation.
89
+ * Consumers provide their own adapter:
90
+ * - `@provex/indexer-client` exports `createPonderAdapter()` for Ponder SQL
91
+ * - Third parties can implement against The Graph, REST APIs, or direct RPC
92
+ *
93
+ * All methods that return lists support optional pagination via `limit`/`cursor`.
94
+ * When omitted, the implementation returns all results.
95
+ */
96
+
97
+ /** Cursor-based pagination options. */
98
+ interface PaginationOptions {
99
+ /** Maximum number of results to return. */
100
+ limit?: number;
101
+ /** Opaque cursor from a previous response. Pass to fetch the next page. */
102
+ cursor?: string;
103
+ }
104
+ /** Paginated response wrapper. */
105
+ interface PaginatedResult<T> {
106
+ items: T[];
107
+ /** Cursor for the next page. Null when there are no more results. */
108
+ nextCursor: string | null;
109
+ }
110
+ /** A deposit with computed availability, rates, and payment method info. */
111
+ interface IndexedDeposit {
112
+ escrow: Hex;
113
+ localId: bigint;
114
+ chainId: ChainId;
115
+ participantAddress: Hex;
116
+ token: Hex;
117
+ remaining: bigint;
118
+ deposited: bigint;
119
+ minAmount: bigint;
120
+ maxAmount: bigint;
121
+ status: string;
122
+ acceptingIntents: boolean;
123
+ /** remaining + reclaimable - activeLocked */
124
+ availableFunds: bigint;
125
+ /** Map<paymentMethodId, Map<currencyId, rateValue>> */
126
+ conversionRates: Map<string, Map<string, bigint>>;
127
+ /** Set of payment method IDs this deposit accepts */
128
+ paymentMethodIds: Set<string>;
129
+ /** Verifier records for payee detail lookups */
130
+ verifiers: IndexedVerifier[];
131
+ }
132
+ /** A deposit verifier record. */
133
+ interface IndexedVerifier {
134
+ paymentMethodId: Hex;
135
+ payeeDetailsHash: Hex;
136
+ intentGatingService: Hex;
137
+ active: boolean;
138
+ }
139
+ /** An indexed intent with lifecycle status and expiry. */
140
+ interface IndexedIntent {
141
+ intentHash: Hex;
142
+ ownerAddress: Hex;
143
+ toAddress: Hex;
144
+ escrow: Hex;
145
+ depositLocalId: bigint;
146
+ amount: bigint;
147
+ timestamp: bigint;
148
+ paymentMethodId: Hex;
149
+ fiatCurrency: Hex;
150
+ conversionRate: bigint;
151
+ /** Expiry timestamp from fundsLocked (unix seconds), null if not locked */
152
+ expiryTime: bigint | null;
153
+ /** Lifecycle status */
154
+ status: 'pending' | 'signalled' | 'fulfilled' | 'pruned';
155
+ /** When the intent was pruned (unix seconds), null if not pruned */
156
+ prunedAt: bigint | null;
157
+ }
158
+ /** Pre-computed reputation data for tier calculation. */
159
+ interface ReputationData {
160
+ /** Total fulfilled volume in USDC (human-readable, e.g. 1500.50) */
161
+ fulfilledVolumeUsdc: number;
162
+ /** Number of fulfilled intents */
163
+ fulfilledCount: number;
164
+ /** Number of late cancellations (>15 min after signal) */
165
+ lateCancellations: number;
166
+ /** Unix timestamp (seconds) of most recent signaled intent per chain. Null if never signaled. */
167
+ lastSignaledAt: Partial<Record<ChainId, bigint>>;
168
+ }
169
+ /**
170
+ * Data source abstraction for @provex/react.
171
+ *
172
+ * Every method that returns a list accepts optional `PaginationOptions`.
173
+ * For batch queries, callers can specify multiple filter keys.
174
+ *
175
+ * Implementations:
176
+ * - `createPonderAdapter(ponderClient)` from `@provex/indexer-client`
177
+ * - Custom REST/Graph/RPC implementations
178
+ *
179
+ * @example
180
+ * ```ts
181
+ * // Using the Ponder adapter
182
+ * import { createPonderAdapter } from '@provex/indexer-client'
183
+ * const indexer = createPonderAdapter(ponderClient)
184
+ *
185
+ * // Using a custom REST API
186
+ * const indexer: IndexerAdapter = {
187
+ * getMatchableDeposits: ({ chainId, token, currencyId }) =>
188
+ * fetch(`/api/deposits?chain=${chainId}&token=${token}&currency=${currencyId}`)
189
+ * .then(r => r.json()),
190
+ * // ...
191
+ * }
192
+ * ```
193
+ */
194
+ interface IndexerAdapter {
195
+ /**
196
+ * Fetch active V3 deposits that match buyer criteria.
197
+ *
198
+ * Returns deposits with computed availability (remaining + reclaimable - locked),
199
+ * active conversion rates, and payment method IDs.
200
+ *
201
+ * The implementation should:
202
+ * - Filter to active, v3, acceptingIntents deposits on the given chain/token
203
+ * - Filter to deposits supporting the given currency
204
+ * - Include conversion rates and verifier data
205
+ * - Compute availableFunds from locked/unlocked/transferred events
206
+ *
207
+ * @param params.chainId - Chain to query
208
+ * @param params.token - Token address to filter by
209
+ * @param params.currencyId - Fiat currency contract ID to filter by
210
+ * @param params.pagination - Optional limit/cursor
211
+ */
212
+ getMatchableDeposits(params: {
213
+ chainId: ChainId;
214
+ token: Hex;
215
+ currencyId: Hex;
216
+ pagination?: PaginationOptions;
217
+ }): Promise<PaginatedResult<IndexedDeposit>>;
218
+ /**
219
+ * Fetch a single deposit with its verifiers.
220
+ *
221
+ * Used by usePayeeDetails to look up deposit info after an intent is signaled.
222
+ */
223
+ getDepositWithVerifiers(params: {
224
+ escrow: Hex;
225
+ localId: bigint;
226
+ chainId: ChainId;
227
+ }): Promise<IndexedDeposit | null>;
228
+ /**
229
+ * Fetch intent details including expiry time and lifecycle status.
230
+ *
231
+ * Combines intent signal data, lock data, and status (fulfilled/pruned/signalled)
232
+ * into a single response.
233
+ */
234
+ getIntent(params: {
235
+ intentHash: Hex;
236
+ chainId: ChainId;
237
+ }): Promise<IndexedIntent | null>;
238
+ /**
239
+ * Get the payee details hash for a deposit's payment method.
240
+ *
241
+ * Used before signaling an intent — the gating service needs this hash.
242
+ *
243
+ * @returns The payeeDetailsHash, or null if no verifier is found
244
+ */
245
+ getPayeeDetailsHash(params: {
246
+ escrow: Hex;
247
+ localId: bigint;
248
+ chainId: ChainId;
249
+ paymentMethodId: Hex;
250
+ }): Promise<Hex | null>;
251
+ /**
252
+ * Get user's reputation data for tier calculation.
253
+ *
254
+ * Returns pre-computed stats that the reputation hook uses to derive
255
+ * the tier, lock score, and cooldown.
256
+ *
257
+ * @param params.address - User's wallet address
258
+ * @param params.chainId - Optional chain filter. When set, only counts
259
+ * activity on that chain. When omitted, counts all chains.
260
+ */
261
+ getUserReputation(params: {
262
+ address: Hex;
263
+ chainId?: ChainId;
264
+ }): Promise<ReputationData>;
265
+ /**
266
+ * Check if a transaction has been indexed.
267
+ * Returns a truthy value when indexed, null when not yet.
268
+ */
269
+ getTransactionByHash(hash: Hex): Promise<unknown | null>;
270
+ /**
271
+ * Check a deposit's current indexed status.
272
+ * Returns null if the deposit isn't indexed yet.
273
+ */
274
+ getDepositById(depositId: Hex): Promise<{
275
+ status: string;
276
+ } | null>;
277
+ }
278
+
279
+ /**
280
+ * @fileoverview Types for the ProveXClient — framework-agnostic protocol client.
281
+ */
282
+
283
+ interface ProveXClientConfig {
284
+ /**
285
+ * The viem Chain object to operate on. Provides chain ID, RPC URLs,
286
+ * block explorers, and native currency config.
287
+ *
288
+ * Import from `viem/chains` or define your own for custom RPCs / testnets.
289
+ *
290
+ * @example
291
+ * ```ts
292
+ * import { base, pulsechain } from 'viem/chains'
293
+ *
294
+ * // Standard chain
295
+ * createProveXClient({ chain: base })
296
+ *
297
+ * // Custom RPC
298
+ * createProveXClient({
299
+ * chain: { ...base, rpcUrls: { default: { http: ['https://my-rpc.com'] } } }
300
+ * })
301
+ *
302
+ * // Testnet
303
+ * createProveXClient({ chain: pulsechainV4, escrowAddress: '0x...' })
304
+ * ```
305
+ */
306
+ chain: Chain;
307
+ /**
308
+ * Backend API URL. Defaults to `https://app.provex.com`.
309
+ * Override for self-hosted or staging deployments.
310
+ */
311
+ apiUrl?: string;
312
+ /**
313
+ * Wallet adapter for signing transactions.
314
+ * Omit for prepare-only mode (`.prepare()` works without a wallet).
315
+ */
316
+ wallet?: WalletAdapter;
317
+ /**
318
+ * Data source adapter for indexer queries.
319
+ * Omit if you only need on-chain reads and `.prepare()`.
320
+ */
321
+ indexer?: IndexerAdapter;
322
+ /** Override the default V3 escrow address for this chain. */
323
+ escrowAddress?: Hex;
324
+ /** Called with the tx hash immediately after wallet submission. */
325
+ onTransactionHash?: (hash: Hex) => void;
326
+ /** Called when indexer sync takes longer than expected. */
327
+ onSlowSync?: () => void;
328
+ }
329
+ /** Framework-agnostic wallet interface. Works with wagmi, ethers, or custom. */
330
+ interface WalletAdapter {
331
+ /** Connected address, or undefined if disconnected. */
332
+ address?: Hex;
333
+ /** Sign and send a transaction. Returns the tx hash. */
334
+ sendTransaction(tx: {
335
+ to: Hex;
336
+ data: Hex;
337
+ value?: bigint;
338
+ chainId: number;
339
+ maxFeePerGas?: bigint;
340
+ maxPriorityFeePerGas?: bigint;
341
+ }): Promise<Hex>;
342
+ /** Read from a contract (optional — falls back to public RPC). */
343
+ readContract?(params: {
344
+ address: Hex;
345
+ abi: readonly unknown[];
346
+ functionName: string;
347
+ args?: readonly unknown[];
348
+ chainId?: number;
349
+ }): Promise<unknown>;
350
+ }
351
+ /**
352
+ * Unsigned transaction data. Pass to any wallet, multisig, relayer, or batch builder.
353
+ *
354
+ * @example
355
+ * ```ts
356
+ * const prepared = await client.addFunds.prepare({ depositId: 1n, amount: 100n })
357
+ * // Hand to Safe SDK, Privy, gasless relay, etc.
358
+ * await safeSDK.createTransaction({ transactions: [prepared] })
359
+ * ```
360
+ */
361
+ interface PreparedTransaction {
362
+ to: Hex;
363
+ data: Hex;
364
+ value: bigint;
365
+ chainId: number;
366
+ }
367
+ /** Result of a fully executed transaction. */
368
+ interface TransactionResult {
369
+ hash: Hex;
370
+ receipt: TransactionReceipt;
371
+ }
372
+ /**
373
+ * A protocol write operation. Callable to execute the full lifecycle,
374
+ * or use `.prepare()` to get unsigned transaction data.
375
+ *
376
+ * @example
377
+ * ```ts
378
+ * // Full execute: gas → wallet → receipt → indexer sync
379
+ * const { hash } = await client.addFunds({ depositId: 1n, amount: 100n })
380
+ *
381
+ * // Prepare only: returns { to, data, value, chainId }
382
+ * const prepared = await client.addFunds.prepare({ depositId: 1n, amount: 100n })
383
+ * ```
384
+ */
385
+ interface WritableMethod<TParams> {
386
+ /** Execute the full transaction lifecycle. Requires a wallet. */
387
+ (params: TParams): Promise<TransactionResult>;
388
+ /** Return unsigned transaction data only. No wallet needed. */
389
+ prepare(params: TParams): Promise<PreparedTransaction>;
390
+ }
391
+ type ProveXErrorCode = 'WALLET_REJECTED' | 'WALLET_NOT_CONNECTED' | 'TX_REVERTED' | 'INSUFFICIENT_FUNDS' | 'INSUFFICIENT_LIQUIDITY' | 'INDEXER_TIMEOUT' | 'INDEXER_NOT_CONFIGURED' | 'CONTRACT_ERROR' | 'API_ERROR' | 'VALIDATION_ERROR' | 'UNKNOWN';
392
+ /**
393
+ * Typed error for ProveX protocol operations.
394
+ * Non-React consumers catch these directly; React hooks map them to UI state.
395
+ */
396
+ declare class ProveXError extends Error {
397
+ readonly code: ProveXErrorCode;
398
+ readonly cause?: Error;
399
+ constructor(code: ProveXErrorCode, message: string, cause?: Error);
400
+ /** Check if this error was caused by the user rejecting in their wallet. */
401
+ get isRejection(): boolean;
402
+ }
403
+ /** Options for registering or validating a maker's payment identity. */
404
+ interface MakerRegistrationParams {
405
+ /** Payment provider key (e.g. 'venmo', 'zelle', 'revolut') */
406
+ providerKey: string;
407
+ /** Provider-specific user ID (e.g. Venmo username, Zelle phone) */
408
+ providerId: string;
409
+ /** Optional Telegram handle for contact */
410
+ telegramHandle?: string;
411
+ }
412
+ /** Payee details returned by the API. */
413
+ interface PayeeDetails {
414
+ payeeId?: string;
415
+ name?: string;
416
+ platformName?: string;
417
+ [key: string]: unknown;
418
+ }
419
+ /** Attestation request for zkTLS proof submission. */
420
+ interface AttestationParams {
421
+ /** Payment platform (e.g. 'chase', 'venmo') */
422
+ platform: string;
423
+ /** Action type (e.g. 'transfer_zelle', 'transfer_venmo') */
424
+ actionType: string;
425
+ /** Reclaim proofs */
426
+ proofs: unknown[];
427
+ /** Chain ID for the attestation */
428
+ chainId: number;
429
+ /** Verifying contract address */
430
+ verifyingContract: Hex;
431
+ /** Intent data for the attestation */
432
+ intent: unknown;
433
+ }
434
+ /** Attestation response with signed payment proof. */
435
+ interface AttestationResponse {
436
+ success: boolean;
437
+ message?: string;
438
+ statusCode?: number;
439
+ responseObject: {
440
+ paymentProof?: unknown;
441
+ [key: string]: unknown;
442
+ };
443
+ }
444
+ /**
445
+ * Human-readable params for signaling an intent (buyer side).
446
+ *
447
+ * The SDK handles:
448
+ * 1. Looking up payee details from the indexer
449
+ * 2. Requesting a gating service signature from the API
450
+ * 3. Building and simulating the on-chain transaction
451
+ * 4. Extracting the intent hash from the IntentSignaled event
452
+ *
453
+ * @example
454
+ * ```ts
455
+ * const { hash, intentHash } = await client.signalIntent({
456
+ * deposit: { escrow: '0x...', localId: 1n },
457
+ * paymentMethod: '0x...', // bytes32 payment method hash
458
+ * tokenAmount: 100_000000n,
459
+ * toAddress: '0x...',
460
+ * fiatCurrencyCode: '0x...', // bytes32 currency code hash
461
+ * conversionRate: 1_000000000000000000n,
462
+ * })
463
+ * ```
464
+ */
465
+ interface SignalIntentParams {
466
+ deposit: {
467
+ escrow: Hex;
468
+ localId: bigint;
469
+ };
470
+ paymentMethod: Hex;
471
+ tokenAmount: bigint;
472
+ toAddress: Hex;
473
+ fiatCurrencyCode: Hex;
474
+ conversionRate: bigint;
475
+ subProvider?: string;
476
+ }
477
+ /** Result of a signalIntent call. Extends TransactionResult with the intent hash. */
478
+ interface SignalIntentResult extends TransactionResult {
479
+ /** The on-chain intent hash, extracted from the IntentSignaled event. */
480
+ intentHash: Hex;
481
+ }
482
+ /** Raw on-chain params matching the Orchestrator's signalIntent signature. */
483
+ interface SignalIntentRawParams {
484
+ escrow: Hex;
485
+ depositId: bigint;
486
+ amount: bigint;
487
+ to: Hex;
488
+ paymentMethod: Hex;
489
+ fiatCurrency: Hex;
490
+ conversionRate: bigint;
491
+ referrer: Hex;
492
+ referrerFee: bigint;
493
+ gatingServiceSignature: Hex;
494
+ signatureExpiration: bigint;
495
+ postIntentHook: Hex;
496
+ data: Hex;
497
+ }
498
+ /** Raw contract-level params matching the V3 Escrow's createDeposit signature. */
499
+ interface CreateDepositRawParams {
500
+ token: Hex;
501
+ amount: bigint;
502
+ intentAmountRange: {
503
+ min: bigint;
504
+ max: bigint;
505
+ };
506
+ paymentMethods: Hex[];
507
+ paymentMethodData: Array<{
508
+ intentGatingService: Hex;
509
+ payeeDetails: Hex;
510
+ data: Hex;
511
+ }>;
512
+ currencies: Array<Array<{
513
+ code: Hex;
514
+ minConversionRate: bigint;
515
+ }>>;
516
+ delegate: Hex;
517
+ intentGuardian: Hex;
518
+ retainOnEmpty: boolean;
519
+ }
520
+ /** A payment method to include in a new deposit. */
521
+ interface DepositPaymentMethod {
522
+ /** Provider key (e.g., 'venmo', 'zelle', 'revolut', 'wise'). */
523
+ provider: string;
524
+ /** Plaintext payee identifier — SDK hashes and registers it automatically. */
525
+ payeeId: string;
526
+ /**
527
+ * Currencies this payment method accepts, with minimum conversion rates.
528
+ *
529
+ * @example
530
+ * ```ts
531
+ * currencies: [
532
+ * { code: 'USD', minRate: 0n }, // accept any rate
533
+ * { code: 'EUR', minRate: 980000000000000000n }, // min 0.98 EUR/USDC
534
+ * ]
535
+ * ```
536
+ */
537
+ currencies: Array<{
538
+ code: string;
539
+ minRate: bigint;
540
+ }>;
541
+ /**
542
+ * Custom intent gating service address. Defaults to the protocol's
543
+ * standard Reclaim gating service for this chain.
544
+ */
545
+ intentGatingService?: Hex;
546
+ /**
547
+ * Custom data field for the payment method (encoded ABI params).
548
+ * Defaults to the standard Reclaim witness signer encoding.
549
+ */
550
+ data?: Hex;
551
+ }
552
+ /**
553
+ * Human-readable params for creating a deposit.
554
+ * The SDK handles hashing, sub-provider expansion, maker registration, and
555
+ * all the encoding needed to build the on-chain transaction.
556
+ *
557
+ * @example
558
+ * ```ts
559
+ * await client.createDeposit({
560
+ * token: USDC_ADDRESS,
561
+ * amount: 1000_000000n,
562
+ * intentRange: { min: 10_000000n, max: 500_000000n },
563
+ * paymentMethods: [
564
+ * { provider: 'venmo', payeeId: '@myvenmo', currencies: [{ code: 'USD', minRate: 0n }] },
565
+ * ],
566
+ * })
567
+ * ```
568
+ */
569
+ interface CreateDepositParams {
570
+ /** ERC-20 token address (e.g., USDC). */
571
+ token: Hex;
572
+ /** Deposit amount in the token's smallest unit (e.g., 6 decimals for USDC). */
573
+ amount: bigint;
574
+ /**
575
+ * Min/max intent amount range buyers can signal.
576
+ * `min` defaults to 1_000000n (1 USDC). `max` defaults to `amount`.
577
+ */
578
+ intentRange?: {
579
+ min?: bigint;
580
+ max?: bigint;
581
+ };
582
+ /** Payment methods the depositor accepts. */
583
+ paymentMethods: DepositPaymentMethod[];
584
+ /** Optional Telegram handle for buyer-seller contact. */
585
+ telegramHandle?: string;
586
+ /** Delegate address that can manage this deposit. Defaults to zero (no delegate). */
587
+ delegate?: Hex;
588
+ /** Guardian address for intent gating. Defaults to zero (no guardian). */
589
+ intentGuardian?: Hex;
590
+ /** Keep deposit active even when fully claimed. Defaults to false. */
591
+ retainOnEmpty?: boolean;
592
+ }
593
+
594
+ /**
595
+ * @fileoverview React hook for the V3 intent signaling flow.
596
+ *
597
+ * Thin state wrapper around ProveXClient.signalIntent() —
598
+ * manages status, error messages, and loading state for the UI.
599
+ */
600
+
601
+ /** Status of the signal intent flow. */
602
+ type SignalIntentStatus = 'input' | 'loading_payee' | 'loading_intent' | 'prompt_wallet_confirm' | 'writing_intent' | 'success' | 'error';
603
+ /**
604
+ * Hook for signaling intent to buy tokens via the V3 Orchestrator.
605
+ *
606
+ * Delegates to ProveXClient.signalIntent() for the full multi-step flow:
607
+ * 1. Fetch payee details from indexer
608
+ * 2. Request gating signature from API
609
+ * 3. Simulate, submit, and parse IntentSignaled event
610
+ *
611
+ * @example
612
+ * ```ts
613
+ * const { startOrder, status, message, isLoading } = useSignalIntent({
614
+ * wallet,
615
+ * chainId: 369,
616
+ * deposit: selectedDeposit,
617
+ * onSuccess: (intentHash) => navigate(`/verify/${intentHash}`),
618
+ * })
619
+ * ```
620
+ */
621
+ declare function useSignalIntent({ wallet, onSuccess, onFailure, deposit, refetchDeposits, }: {
622
+ /** Wallet adapter for signing transactions. */
623
+ wallet: WalletAdapter;
624
+ /** @deprecated Chain is resolved from ProvexProvider. Kept for API compat. */
625
+ chainId?: ChainId;
626
+ /** Called when the intent is signaled successfully. */
627
+ onSuccess: (intentHash: Hex) => void;
628
+ /** Called when the flow fails. */
629
+ onFailure?: () => void;
630
+ /** The deposit to signal intent against. */
631
+ deposit: DepositInfo | null;
632
+ /** Called on failure to refresh deposit data. */
633
+ refetchDeposits?: () => void;
634
+ }): {
635
+ startOrder: ({ paymentMethod, depositId, tokenAmount, toAddress, fiatCurrencyCode, conversionRate, subProvider, }: {
636
+ paymentMethod: Hex;
637
+ depositId: bigint;
638
+ tokenAmount: bigint;
639
+ toAddress: Hex;
640
+ fiatCurrencyCode: Hex;
641
+ conversionRate: bigint;
642
+ subProvider?: SubProviderKey;
643
+ }) => Promise<void>;
644
+ status: SignalIntentStatus;
645
+ message: string | null;
646
+ isLoading: boolean;
647
+ };
648
+
649
+ /**
650
+ * @fileoverview Hook for calculating reputation-based trading limits.
651
+ *
652
+ * Applies tier-based restrictions on transaction caps and cooldowns.
653
+ * Pure computation -- no Ponder, no contract reads.
654
+ *
655
+ * @see {@link useReputation} for fetching the user's tier
656
+ * @see {@link @provex/utils/reputation} for tier definitions
657
+ */
658
+
659
+ /** Input parameters for calculating reputation limits. */
660
+ interface ReputationLimitsParams {
661
+ /** Current chain ID */
662
+ chainId: ChainId;
663
+ /** Currently selected payment method */
664
+ selectedPaymentMethod: ProviderKey;
665
+ /** User's reputation tier */
666
+ tier: TakerTier;
667
+ /** Amount in fiat currency (for cap exceeded check) - in token base units (e.g., 6 decimals for USDC) */
668
+ amountInInt?: bigint | null;
669
+ /** When the user's cooldown ends (from useReputation) */
670
+ cooldownEndsAt?: Date | null;
671
+ }
672
+ /** Result of the useReputationLimits hook. */
673
+ interface ReputationLimits {
674
+ /** Whether reputation limits apply */
675
+ hasLimits: boolean;
676
+ /** Alternative providers with no cooldown */
677
+ noCooldownProviders: ProviderKey[];
678
+ /** Cooldown hours for the selected payment method (category, not remaining) */
679
+ selectedProviderCooldownHours: number;
680
+ /** Remaining cooldown time in formatted string (e.g., "5h 30m") - null if not on cooldown */
681
+ cooldownRemaining: string | null;
682
+ /** Whether user is currently on cooldown for the selected payment method */
683
+ isOnCooldown: boolean;
684
+ /** Effective cap in USD for the selected payment method (null if no cap) */
685
+ effectiveCap: number | null;
686
+ /** Whether the current amount exceeds the cap */
687
+ amountExceedsCap: boolean;
688
+ /** Error message when cap is exceeded */
689
+ capExceededMessage: string | null;
690
+ }
691
+ /**
692
+ * Hook to calculate reputation-based limits for payment methods.
693
+ *
694
+ * @example
695
+ * ```ts
696
+ * const {
697
+ * noCooldownProviders,
698
+ * selectedProviderCooldownHours,
699
+ * effectiveCap,
700
+ * amountExceedsCap,
701
+ * capExceededMessage,
702
+ * } = useReputationLimits({
703
+ * chainId,
704
+ * selectedPaymentMethod,
705
+ * tier: reputation.tier,
706
+ * amountInInt,
707
+ * })
708
+ * ```
709
+ */
710
+ declare function useReputationLimits({ chainId, selectedPaymentMethod, tier, amountInInt, cooldownEndsAt, }: ReputationLimitsParams): ReputationLimits;
711
+
712
+ /** Intent status values representing the lifecycle state. */
713
+ declare const intentStatuses: {
714
+ readonly pending: "pending";
715
+ readonly signalled: "signalled";
716
+ readonly fulfilled: "fulfilled";
717
+ readonly pruned: "pruned";
718
+ };
719
+ type IntentStatus = (typeof intentStatuses)[keyof typeof intentStatuses];
720
+ /** Payee details from the API. */
721
+ interface PayeeInfo {
722
+ payeeId?: string;
723
+ name?: string;
724
+ platformName?: string;
725
+ [key: string]: unknown;
726
+ }
727
+ /**
728
+ * Hook to fetch intent details and payee information.
729
+ *
730
+ * @param intentHash - The intent hash to look up
731
+ * @param chainId - The chain ID to query
732
+ * @returns Intent details, payee info, and loading state
733
+ */
734
+ declare function usePayeeDetails({ intentHash, chainId, }: {
735
+ intentHash: Hex | null;
736
+ chainId: ChainId;
737
+ }): {
738
+ intentStatus: IntentStatus | null;
739
+ isFetching: boolean;
740
+ isValid: boolean;
741
+ intent: {
742
+ owner: `0x${string}`;
743
+ to: `0x${string}`;
744
+ escrow: `0x${string}`;
745
+ depositId: bigint;
746
+ amount: bigint;
747
+ timestamp: bigint;
748
+ paymentMethod: `0x${string}`;
749
+ fiatCurrency: `0x${string}`;
750
+ conversionRate: bigint;
751
+ } | null;
752
+ providerKey: _provex_utils_payment.ProviderKey | null;
753
+ userId: `0x${string}` | null;
754
+ payeeDetails: PayeeInfo | null;
755
+ deposit: IndexedDeposit | null;
756
+ expiryTime: bigint | null;
757
+ isV2Intent: boolean;
758
+ isPruned: boolean;
759
+ prunedAt: bigint | null;
760
+ isFulfilled: boolean;
761
+ refetch: () => void;
762
+ refetchAll: () => Promise<IntentStatus | null>;
763
+ };
764
+
765
+ /** Configuration for ProvexProvider. */
766
+ interface ProvexConfig {
767
+ /** Backend API URL (e.g. "https://app.provex.com") */
768
+ apiUrl: string;
769
+ /** The viem Chain object. Import from `viem/chains`. */
770
+ chain: Chain;
771
+ /** @deprecated Use `chain.id` — kept for backward compat during migration. */
772
+ chainId?: ChainId;
773
+ }
774
+ /** Buy flow phases. */
775
+ type BuyPhase = 'browse' | 'committed' | 'proving' | 'complete';
776
+ /** Theme overrides applied as CSS custom properties on the root element. */
777
+ interface ProvexTheme {
778
+ accent?: string;
779
+ background?: string;
780
+ backgroundCard?: string;
781
+ text?: string;
782
+ textMuted?: string;
783
+ border?: string;
784
+ error?: string;
785
+ radius?: string;
786
+ font?: string;
787
+ }
788
+ /** Options for the useProvexBuy hook. */
789
+ interface UseProvexBuyOptions {
790
+ /** Wallet adapter — host app's wallet connection. */
791
+ wallet: WalletAdapter;
792
+ /** Called when the user signals intent (USDC reserved). */
793
+ onIntentSignaled?: (intentHash: string, chainId: number) => void;
794
+ /** Called when the full flow completes (USDC released). */
795
+ onComplete?: (intentHash: string, chainId: number) => void;
796
+ /** Restrict to specific payment methods. */
797
+ paymentMethods?: ProviderKey[];
798
+ }
799
+ /** Return value of the useProvexBuy hook — the full buy-flow state machine. */
800
+ interface UseProvexBuyReturn {
801
+ /** Current phase of the buy flow. */
802
+ phase: BuyPhase;
803
+ /** Fiat amount entered by the user (string for input binding). */
804
+ amount: string;
805
+ /** Set the fiat amount. */
806
+ setAmount: (value: string) => void;
807
+ /** Currently selected payment method, or empty string if none. */
808
+ selectedPaymentMethod: ProviderKey | '';
809
+ /** Set the selected payment method. */
810
+ setSelectedPaymentMethod: (method: ProviderKey) => void;
811
+ /** Payment methods available for the current chain. */
812
+ availablePaymentMethods: ProviderKey[];
813
+ /** All deposits matching the current criteria. */
814
+ deposits: DepositInfo[];
815
+ /** The best deposit selected for the current amount. */
816
+ selectedDeposit: DepositInfo | null;
817
+ /** Manually select a deposit (advanced use). */
818
+ selectDeposit: (deposit: DepositInfo) => void;
819
+ /** True while deposits are loading for the first time. */
820
+ isLoadingDeposits: boolean;
821
+ /** Best rate for the current amount/payment method (raw 18-decimal). */
822
+ rate: bigint | null;
823
+ /** Human-readable rate string (e.g. "1 USDC = $1.01"). */
824
+ rateDisplay: string | null;
825
+ /** Token amount the user will receive (base units). */
826
+ tokenAmount: bigint | null;
827
+ /** Human-readable token amount (e.g. "99.50"). */
828
+ tokenAmountDisplay: string | null;
829
+ /** Token info for the current chain. */
830
+ token: TokenInfo | null;
831
+ /** Currency info (e.g. USD). */
832
+ currency: Currency | null;
833
+ /** User reputation data. */
834
+ reputation: UserReputation;
835
+ /** Reputation-based limits for the selected payment method. */
836
+ limits: ReputationLimits;
837
+ /** Protocol fee percentage string (e.g. "0%"), or null if loading. */
838
+ feePercentage: string | null;
839
+ /** Seller's payment details (name, handle, platform). */
840
+ payeeDetails: PayeeInfo | null;
841
+ /** Seller's display name. */
842
+ payeeName: string | null;
843
+ /** Seller's payment handle (e.g. Venmo username, Zelle email). */
844
+ payeeId: string | null;
845
+ /** True while payee details are loading. */
846
+ isPayeeLoading: boolean;
847
+ /** Intent expiry time. */
848
+ intentExpiryTime: Date | null;
849
+ /** Whether the intent has expired (pruned). */
850
+ isIntentExpired: boolean;
851
+ /** Indexed intent lifecycle status (signalled, fulfilled, pruned). */
852
+ indexedIntentStatus: IntentStatus | null;
853
+ /** Whether the order form can be submitted. */
854
+ canSubmit: boolean;
855
+ /** User-facing validation message, or null when valid. */
856
+ validationMessage: string | null;
857
+ /** Submit the order (signal intent on-chain). */
858
+ submitOrder: () => Promise<void>;
859
+ /** Confirm payment was sent (transitions to proving/complete). */
860
+ confirmPayment: () => void;
861
+ /** Reset the flow back to browse. */
862
+ reset: () => void;
863
+ /** Intent hash after successful order submission. */
864
+ intentHash: Hex | null;
865
+ /** Current status of the signal intent flow. */
866
+ intentStatus: SignalIntentStatus;
867
+ /** Error message from the intent flow. */
868
+ intentError: string | null;
869
+ /** True while the intent is being submitted. */
870
+ isSubmitting: boolean;
871
+ /** Chain ID for the current configuration. */
872
+ chainId: ChainId;
873
+ }
874
+ /** Props for the ProvexBuy widget component (Layer 3). */
875
+ interface BuyProps {
876
+ /** Wallet adapter — host app's wallet connection. */
877
+ wallet: WalletAdapter;
878
+ /** Called when the user signals intent (USDC reserved). */
879
+ onIntentSignaled?: (intentHash: string, chainId: number) => void;
880
+ /** Called when the full flow completes (USDC released). */
881
+ onComplete?: (intentHash: string, chainId: number) => void;
882
+ /** Restrict to specific payment methods. */
883
+ paymentMethods?: ProviderKey[];
884
+ /** CSS class name for the root container. */
885
+ className?: string;
886
+ /** Inline styles for the root container. */
887
+ style?: React.CSSProperties;
888
+ /** Theme overrides applied as CSS custom properties. */
889
+ theme?: ProvexTheme;
890
+ }
891
+ /** Common props accepted by all phase components. */
892
+ interface PhaseComponentProps {
893
+ /** CSS class name. */
894
+ className?: string;
895
+ /** Inline styles. */
896
+ style?: React.CSSProperties;
897
+ }
898
+ /** Props for a phase component with a custom render prop. */
899
+ interface PhaseRenderProps<TState> extends PhaseComponentProps {
900
+ /** Custom render function — receives the phase state, returns JSX. */
901
+ render?: (state: TState) => React.ReactNode;
902
+ }
903
+
904
+ /**
905
+ * @fileoverview Thin API client for @provex/react.
906
+ *
907
+ * Provides typed get/post methods for the Provex backend API.
908
+ * No external dependencies — uses the Fetch API directly.
909
+ */
910
+ /** API client for making typed requests to the Provex backend. */
911
+ interface ApiClient {
912
+ /** Send a GET request and parse the JSON response. */
913
+ get: <T>(path: string, options?: RequestInit) => Promise<T>;
914
+ /** Send a POST request with a JSON body and parse the response. */
915
+ post: <T>(path: string, body: unknown, options?: RequestInit) => Promise<T>;
916
+ }
917
+ /** Create an API client that targets the given base URL. */
918
+ declare function createApiClient(apiUrl: string): ApiClient;
919
+
920
+ /** Shape of the context value provided by ProvexProvider. */
921
+ interface ProvexContextValue {
922
+ /** User-supplied configuration (apiUrl, chain). */
923
+ config: ProvexConfig;
924
+ /** Data source adapter for indexer queries. */
925
+ indexer: IndexerAdapter;
926
+ /** Thin fetch wrapper for the Provex backend API. */
927
+ apiClient: ApiClient;
928
+ /** Public clients keyed by chain ID. Always contains at least `config.chain.id`. */
929
+ publicClients: Record<number, PublicClient>;
930
+ /** Optional wallet adapter for write operations. */
931
+ wallet?: WalletAdapter;
932
+ }
933
+ /** Props for the ProvexProvider component. */
934
+ interface ProvexProviderProps {
935
+ /** Protocol configuration. */
936
+ config: ProvexConfig;
937
+ /**
938
+ * Data source adapter. Implement IndexerAdapter against any backend:
939
+ * - `createPonderAdapter()` from `@provex/indexer-client` (default for Provex apps)
940
+ * - Custom REST, Graph, or RPC implementation
941
+ */
942
+ indexer: IndexerAdapter;
943
+ /** Optional external QueryClient — if omitted, a default one is created. */
944
+ queryClient?: QueryClient;
945
+ /**
946
+ * Viem public client for the primary chain (`config.chain.id`).
947
+ * Shorthand for `publicClients={{ [config.chain.id]: client }}`.
948
+ */
949
+ publicClient?: PublicClient;
950
+ /**
951
+ * Viem public clients keyed by chain ID. Use when your app reads from
952
+ * multiple chains (e.g., cross-chain deposits).
953
+ */
954
+ publicClients?: Record<number, PublicClient>;
955
+ /**
956
+ * Wallet adapter for write operations (signalIntent, createDeposit, etc).
957
+ * Omit for read-only apps.
958
+ */
959
+ wallet?: WalletAdapter;
960
+ /** Child components that consume the context. */
961
+ children: React__default.ReactNode;
962
+ }
963
+ /**
964
+ * ProvexProvider — wrap your app (or a subtree) with this to enable
965
+ * Provex hooks and components.
966
+ *
967
+ * @example
968
+ * ```tsx
969
+ * import { createPonderAdapter } from '@provex/indexer-client'
970
+ * import { createPublicClient, http } from 'viem'
971
+ * import { base } from 'viem/chains'
972
+ *
973
+ * const publicClient = createPublicClient({ chain: base, transport: http() })
974
+ *
975
+ * <ProvexProvider
976
+ * config={{ apiUrl: 'https://app.provex.com', chain: base }}
977
+ * indexer={createPonderAdapter()}
978
+ * publicClient={publicClient}
979
+ * wallet={myWalletAdapter}
980
+ * >
981
+ * <App />
982
+ * </ProvexProvider>
983
+ * ```
984
+ */
985
+ declare function ProvexProvider({ config, indexer, queryClient, publicClient, publicClients, wallet, children, }: ProvexProviderProps): react_jsx_runtime.JSX.Element;
986
+ /**
987
+ * useProvex — access the Provex context (config, indexer, apiClient,
988
+ * publicClients, wallet).
989
+ *
990
+ * Must be called within a ProvexProvider. Throws if used outside the provider.
991
+ */
992
+ declare function useProvex(): ProvexContextValue;
993
+ /**
994
+ * Get the public client for a specific chain, or the primary chain if omitted.
995
+ * Returns `undefined` if no client is registered for that chain.
996
+ */
997
+ declare function useProvexPublicClient(chainId?: number): PublicClient | undefined;
998
+ /**
999
+ * Get the optional public client without requiring ProvexProvider.
1000
+ * Returns `undefined` outside the provider or when no client is registered.
1001
+ */
1002
+ declare function useOptionalProvexPublicClient(chainId?: number): PublicClient | undefined;
1003
+ /**
1004
+ * Get the configured wallet adapter, if any. Returns `undefined` for
1005
+ * read-only apps that did not pass a wallet to ProvexProvider.
1006
+ */
1007
+ declare function useProvexWallet(): WalletAdapter | undefined;
1008
+ /**
1009
+ * Get the optional wallet adapter without requiring ProvexProvider.
1010
+ */
1011
+ declare function useOptionalProvexWallet(): WalletAdapter | undefined;
1012
+
1013
+ export { type IndexedVerifier as $, type AttestationParams as A, type BuyProps as B, type CreateDepositRawParams as C, type DepositPaymentMethod as D, useDeposits as E, getRate as F, usePayeeDetails as G, intentStatuses as H, type IndexerAdapter as I, useSignalIntent as J, useProvexPublicClient as K, useOptionalProvexPublicClient as L, type MakerRegistrationParams as M, useProvexWallet as N, useOptionalProvexWallet as O, type ProveXClientConfig as P, type ReputationLimitsParams as Q, type ReputationData as R, type SignalIntentParams as S, type TransactionResult as T, type UseProvexBuyOptions as U, type ReputationLimits as V, type WritableMethod as W, type DepositInfo as X, type IntentStatus as Y, type PayeeInfo as Z, type SignalIntentStatus as _, type PaginationOptions as a, type PaginatedResult as b, type IndexedDeposit as c, type IndexedIntent as d, type CreateDepositParams as e, type PreparedTransaction as f, type SignalIntentResult as g, type PayeeDetails as h, type AttestationResponse as i, type WalletAdapter as j, type UseProvexBuyReturn as k, type PhaseRenderProps as l, type ProvexConfig as m, type BuyPhase as n, type ProvexTheme as o, type PhaseComponentProps as p, ProvexProvider as q, type ProvexContextValue as r, type ProvexProviderProps as s, ProveXError as t, useProvex as u, type ProveXErrorCode as v, type SignalIntentRawParams as w, createApiClient as x, type ApiClient as y, useReputationLimits as z };