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