@oasisprotocol/privana-sdk 0.3.0 → 0.4.1
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/README.md +137 -17
- package/dist/chunk-CRJNDCDT.cjs +1773 -0
- package/dist/chunk-CRJNDCDT.cjs.map +1 -0
- package/dist/chunk-ZXFQJ5MG.js +1719 -0
- package/dist/chunk-ZXFQJ5MG.js.map +1 -0
- package/dist/index.cjs +326 -1728
- package/dist/index.cjs.map +1 -1
- package/dist/index.css +1 -1
- package/dist/index.css.map +1 -1
- package/dist/index.d.cts +68 -60
- package/dist/index.d.ts +68 -60
- package/dist/index.js +52 -1586
- package/dist/index.js.map +1 -1
- package/dist/on-ramp-DIAOtdeU.d.cts +115 -0
- package/dist/on-ramp-DIAOtdeU.d.ts +115 -0
- package/dist/on-ramp.cjs +958 -0
- package/dist/on-ramp.cjs.map +1 -0
- package/dist/on-ramp.d.cts +143 -0
- package/dist/on-ramp.d.ts +143 -0
- package/dist/on-ramp.js +955 -0
- package/dist/on-ramp.js.map +1 -0
- package/package.json +12 -1
package/dist/on-ramp.js
ADDED
|
@@ -0,0 +1,955 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { usePrivanaContext, usePrivateReadRequest, useDepositVerification, waitForTransactionReceipt, Skeleton, Button } from './chunk-ZXFQJ5MG.js';
|
|
3
|
+
import { useState, useRef, useEffect, useCallback, useMemo } from 'react';
|
|
4
|
+
import { parseAbiItem, zeroAddress, parseUnits, decodeEventLog, formatUnits } from 'viem';
|
|
5
|
+
import { useConfig, useAccount } from 'wagmi';
|
|
6
|
+
import { Loader2 } from 'lucide-react';
|
|
7
|
+
import { MoonPayBuyWidget } from '@moonpay/moonpay-react';
|
|
8
|
+
import { jsxs, jsx } from 'react/jsx-runtime';
|
|
9
|
+
|
|
10
|
+
var DEFAULT_DELIVERY_TIMEOUT_MS = 12e4;
|
|
11
|
+
var DEFAULT_VERIFICATION_TIMEOUT_MS = 10 * 6e4;
|
|
12
|
+
var DEFAULT_FINALITY_RETRY_INTERVAL_MS = 15e3;
|
|
13
|
+
var ERC20_TRANSFER_EVENT = parseAbiItem(
|
|
14
|
+
"event Transfer(address indexed from, address indexed to, uint256 value)"
|
|
15
|
+
);
|
|
16
|
+
function useFiatOnRamp(options) {
|
|
17
|
+
const { tokenId, onCredited, onError, onDebugEvent } = options;
|
|
18
|
+
const deliveryTimeout = options.deliveryTimeout ?? DEFAULT_DELIVERY_TIMEOUT_MS;
|
|
19
|
+
const deliveryPollInterval = options.deliveryPollInterval ?? 3e3;
|
|
20
|
+
const verificationTimeout = options.verificationTimeout ?? DEFAULT_VERIFICATION_TIMEOUT_MS;
|
|
21
|
+
const finalityRetryInterval = options.finalityRetryInterval ?? DEFAULT_FINALITY_RETRY_INTERVAL_MS;
|
|
22
|
+
const { client, enabledTokens } = usePrivanaContext();
|
|
23
|
+
const { executePrivateRead, privateReadReady } = usePrivateReadRequest();
|
|
24
|
+
const wagmiConfig = useConfig();
|
|
25
|
+
const selectedToken = enabledTokens.find((t) => t.id.toLowerCase() === tokenId.toLowerCase());
|
|
26
|
+
const [status, setStatus] = useState("idle");
|
|
27
|
+
const [pending, setPending] = useState([]);
|
|
28
|
+
const [error, setError] = useState(null);
|
|
29
|
+
const [depositAddress, setDepositAddress] = useState();
|
|
30
|
+
const [minDepositBaseUnits, setMinDepositBaseUnits] = useState();
|
|
31
|
+
const [activeIntentId, setActiveIntentId] = useState(null);
|
|
32
|
+
const [finalityProgress, setFinalityProgress] = useState({});
|
|
33
|
+
const onCreditedRef = useRef(onCredited);
|
|
34
|
+
const onErrorRef = useRef(onError);
|
|
35
|
+
const onDebugEventRef = useRef(onDebugEvent);
|
|
36
|
+
const statusRef = useRef(status);
|
|
37
|
+
const activeIntentIdRef = useRef(null);
|
|
38
|
+
const activeVerificationRecordRef = useRef(null);
|
|
39
|
+
const activeVerificationKeyRef = useRef(null);
|
|
40
|
+
const triggeredVerificationKeysRef = useRef(/* @__PURE__ */ new Set());
|
|
41
|
+
const closeReconcilePromiseRef = useRef(null);
|
|
42
|
+
const purchaseInitiatedRef = useRef(false);
|
|
43
|
+
useEffect(() => {
|
|
44
|
+
onCreditedRef.current = onCredited;
|
|
45
|
+
onErrorRef.current = onError;
|
|
46
|
+
onDebugEventRef.current = onDebugEvent;
|
|
47
|
+
}, [onCredited, onError, onDebugEvent]);
|
|
48
|
+
useEffect(() => {
|
|
49
|
+
statusRef.current = status;
|
|
50
|
+
}, [status]);
|
|
51
|
+
useEffect(() => {
|
|
52
|
+
activeIntentIdRef.current = activeIntentId;
|
|
53
|
+
}, [activeIntentId]);
|
|
54
|
+
useEffect(() => {
|
|
55
|
+
activeIntentIdRef.current = null;
|
|
56
|
+
setActiveIntentId(null);
|
|
57
|
+
}, [tokenId]);
|
|
58
|
+
const emitDebug = useCallback(
|
|
59
|
+
(event, payload) => {
|
|
60
|
+
onDebugEventRef.current?.({
|
|
61
|
+
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
62
|
+
event,
|
|
63
|
+
status: statusRef.current,
|
|
64
|
+
tokenId,
|
|
65
|
+
payload
|
|
66
|
+
});
|
|
67
|
+
},
|
|
68
|
+
[tokenId]
|
|
69
|
+
);
|
|
70
|
+
useEffect(() => {
|
|
71
|
+
emitDebug("private-read-state", { privateReadReady });
|
|
72
|
+
}, [emitDebug, privateReadReady]);
|
|
73
|
+
useEffect(() => {
|
|
74
|
+
if (!privateReadReady) {
|
|
75
|
+
emitDebug("deposit-address:skip", { reason: "private-read-not-ready" });
|
|
76
|
+
setDepositAddress(void 0);
|
|
77
|
+
setMinDepositBaseUnits(void 0);
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
let cancelled = false;
|
|
81
|
+
void (async () => {
|
|
82
|
+
try {
|
|
83
|
+
emitDebug("deposit-address:request");
|
|
84
|
+
const resp = await executePrivateRead(() => client.getDepositAddress());
|
|
85
|
+
if (cancelled) return;
|
|
86
|
+
setDepositAddress(resp.deposit_address);
|
|
87
|
+
const token = enabledTokens.find((t) => t.id.toLowerCase() === tokenId.toLowerCase());
|
|
88
|
+
const mins = token ? resp.min_deposit?.[String(token.chainId)] : void 0;
|
|
89
|
+
if (mins?.erc20) setMinDepositBaseUnits(BigInt(mins.erc20));
|
|
90
|
+
emitDebug("deposit-address:success", {
|
|
91
|
+
depositAddress: resp.deposit_address,
|
|
92
|
+
selectedToken: token ? summariseToken(token) : null,
|
|
93
|
+
minDepositBaseUnits: mins?.erc20 ?? null
|
|
94
|
+
});
|
|
95
|
+
} catch (err) {
|
|
96
|
+
if (!cancelled) {
|
|
97
|
+
emitDebug("deposit-address:error", errorPayload(err));
|
|
98
|
+
console.warn("Failed to fetch Privana deposit address:", err);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
})();
|
|
102
|
+
return () => {
|
|
103
|
+
cancelled = true;
|
|
104
|
+
};
|
|
105
|
+
}, [client, emitDebug, enabledTokens, executePrivateRead, privateReadReady, tokenId]);
|
|
106
|
+
const refreshPending = useCallback(async () => {
|
|
107
|
+
if (!privateReadReady) {
|
|
108
|
+
emitDebug("pending:skip", { reason: "private-read-not-ready" });
|
|
109
|
+
setPending([]);
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
try {
|
|
113
|
+
emitDebug("pending:request");
|
|
114
|
+
const { pending: rows } = await executePrivateRead(() => client.getPendingOnRamps());
|
|
115
|
+
setPending(rows);
|
|
116
|
+
emitDebug("pending:success", {
|
|
117
|
+
count: rows.length,
|
|
118
|
+
rows: rows.map(summariseOnRampRecord)
|
|
119
|
+
});
|
|
120
|
+
} catch (err) {
|
|
121
|
+
emitDebug("pending:error", errorPayload(err));
|
|
122
|
+
console.warn("Failed to load pending on-ramps:", err);
|
|
123
|
+
}
|
|
124
|
+
}, [client, emitDebug, executePrivateRead, privateReadReady]);
|
|
125
|
+
useEffect(() => {
|
|
126
|
+
refreshPending();
|
|
127
|
+
}, [refreshPending]);
|
|
128
|
+
const clearActiveVerification = useCallback(() => {
|
|
129
|
+
const key = activeVerificationKeyRef.current;
|
|
130
|
+
if (key) triggeredVerificationKeysRef.current.delete(key);
|
|
131
|
+
activeVerificationKeyRef.current = null;
|
|
132
|
+
activeVerificationRecordRef.current = null;
|
|
133
|
+
}, []);
|
|
134
|
+
const { verify } = useDepositVerification({
|
|
135
|
+
pollTimeout: verificationTimeout,
|
|
136
|
+
pollInterval: options.verificationPollInterval,
|
|
137
|
+
finalityRetryInterval,
|
|
138
|
+
onCheckRetry: (message) => {
|
|
139
|
+
const record = activeVerificationRecordRef.current;
|
|
140
|
+
if (!record) return;
|
|
141
|
+
emitDebug("verification:check-retry", {
|
|
142
|
+
message,
|
|
143
|
+
record: summariseOnRampRecord(record)
|
|
144
|
+
});
|
|
145
|
+
setFinalityProgress((prev) => ({ ...prev, [record.transaction_id]: message }));
|
|
146
|
+
},
|
|
147
|
+
onCredited: (depositTxHash) => {
|
|
148
|
+
const record = activeVerificationRecordRef.current;
|
|
149
|
+
emitDebug("verification:credited", {
|
|
150
|
+
depositTxHash,
|
|
151
|
+
record: record ? summariseOnRampRecord(record) : null
|
|
152
|
+
});
|
|
153
|
+
if (record && activeIntentIdRef.current === record.transaction_id) {
|
|
154
|
+
setStatus("credited");
|
|
155
|
+
}
|
|
156
|
+
if (record) {
|
|
157
|
+
setFinalityProgress((prev) => {
|
|
158
|
+
if (!(record.transaction_id in prev)) return prev;
|
|
159
|
+
const next = { ...prev };
|
|
160
|
+
delete next[record.transaction_id];
|
|
161
|
+
return next;
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
void (async () => {
|
|
165
|
+
try {
|
|
166
|
+
if (record && depositTxHash.startsWith("0x")) {
|
|
167
|
+
emitDebug("onramp:mark-deposit-triggered-request", {
|
|
168
|
+
transactionId: record.transaction_id,
|
|
169
|
+
depositTxHash
|
|
170
|
+
});
|
|
171
|
+
const updated = await executePrivateRead(
|
|
172
|
+
() => client.updateOnRamp(record.transaction_id, {
|
|
173
|
+
deposit_tx_hash: depositTxHash
|
|
174
|
+
})
|
|
175
|
+
);
|
|
176
|
+
emitDebug("onramp:mark-deposit-triggered-success", {
|
|
177
|
+
record: summariseOnRampRecord(updated)
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
} catch (err) {
|
|
181
|
+
emitDebug("onramp:mark-deposit-triggered-error", errorPayload(err));
|
|
182
|
+
console.warn("Failed to mark on-ramp row complete:", err);
|
|
183
|
+
} finally {
|
|
184
|
+
clearActiveVerification();
|
|
185
|
+
if (record && activeIntentIdRef.current === record.transaction_id) {
|
|
186
|
+
activeIntentIdRef.current = null;
|
|
187
|
+
setActiveIntentId(null);
|
|
188
|
+
}
|
|
189
|
+
void refreshPending();
|
|
190
|
+
}
|
|
191
|
+
})();
|
|
192
|
+
onCreditedRef.current?.(depositTxHash);
|
|
193
|
+
},
|
|
194
|
+
onCheckTimeout: (depositTxHash) => {
|
|
195
|
+
const record = activeVerificationRecordRef.current;
|
|
196
|
+
const err = new Error(
|
|
197
|
+
"Privana verification is still pending. Retry from the pending on-ramp list if it does not complete."
|
|
198
|
+
);
|
|
199
|
+
emitDebug("verification:timeout", { depositTxHash, message: err.message });
|
|
200
|
+
clearActiveVerification();
|
|
201
|
+
if (!record || activeIntentIdRef.current === record.transaction_id) {
|
|
202
|
+
setStatus("failed");
|
|
203
|
+
setError(err);
|
|
204
|
+
}
|
|
205
|
+
void refreshPending();
|
|
206
|
+
onErrorRef.current?.(err);
|
|
207
|
+
},
|
|
208
|
+
onError: (err) => {
|
|
209
|
+
const record = activeVerificationRecordRef.current;
|
|
210
|
+
emitDebug("verification:error", errorPayload(err));
|
|
211
|
+
clearActiveVerification();
|
|
212
|
+
if (!record || activeIntentIdRef.current === record.transaction_id) {
|
|
213
|
+
setStatus("failed");
|
|
214
|
+
setError(err);
|
|
215
|
+
}
|
|
216
|
+
onErrorRef.current?.(err);
|
|
217
|
+
}
|
|
218
|
+
});
|
|
219
|
+
const prepareOnRampIntent = useCallback(
|
|
220
|
+
async ({
|
|
221
|
+
currencyCode,
|
|
222
|
+
baseCurrencyCode,
|
|
223
|
+
baseCurrencyAmount
|
|
224
|
+
}) => {
|
|
225
|
+
try {
|
|
226
|
+
setError(null);
|
|
227
|
+
purchaseInitiatedRef.current = false;
|
|
228
|
+
const token = enabledTokens.find((t) => t.id.toLowerCase() === tokenId.toLowerCase());
|
|
229
|
+
if (!token) throw new Error(`Unknown token: ${tokenId}`);
|
|
230
|
+
if (!depositAddress) throw new Error("Privana deposit address is not ready");
|
|
231
|
+
emitDebug("intent:create-request", {
|
|
232
|
+
tokenId,
|
|
233
|
+
chainId: token.chainId,
|
|
234
|
+
currencyCode,
|
|
235
|
+
baseCurrencyCode: baseCurrencyCode ?? null,
|
|
236
|
+
baseCurrencyAmount: baseCurrencyAmount ?? null,
|
|
237
|
+
depositAddress
|
|
238
|
+
});
|
|
239
|
+
const record = await executePrivateRead(
|
|
240
|
+
() => client.createOnRampIntent({
|
|
241
|
+
wallet_address: depositAddress,
|
|
242
|
+
token_id: tokenId,
|
|
243
|
+
chain_id: token.chainId,
|
|
244
|
+
moonpay_currency_code: currencyCode,
|
|
245
|
+
base_currency_code: baseCurrencyCode,
|
|
246
|
+
base_currency_amount: baseCurrencyAmount
|
|
247
|
+
})
|
|
248
|
+
);
|
|
249
|
+
activeIntentIdRef.current = record.transaction_id;
|
|
250
|
+
setActiveIntentId(record.transaction_id);
|
|
251
|
+
emitDebug("intent:create-success", {
|
|
252
|
+
record: summariseOnRampRecord(record)
|
|
253
|
+
});
|
|
254
|
+
return record;
|
|
255
|
+
} catch (err) {
|
|
256
|
+
const e = err instanceof Error ? err : new Error("Failed to create on-ramp intent");
|
|
257
|
+
setStatus("failed");
|
|
258
|
+
setError(e);
|
|
259
|
+
emitDebug("intent:create-error", errorPayload(e));
|
|
260
|
+
onErrorRef.current?.(e);
|
|
261
|
+
throw e;
|
|
262
|
+
}
|
|
263
|
+
},
|
|
264
|
+
[client, depositAddress, emitDebug, enabledTokens, executePrivateRead, tokenId]
|
|
265
|
+
);
|
|
266
|
+
const registerOnRampTokenMapping = useCallback(
|
|
267
|
+
async (moonpayTransactionId) => {
|
|
268
|
+
const token = enabledTokens.find((t) => t.id.toLowerCase() === tokenId.toLowerCase());
|
|
269
|
+
if (!token) {
|
|
270
|
+
emitDebug("register-token-mapping:skip", {
|
|
271
|
+
moonpayTransactionId,
|
|
272
|
+
reason: "selected-token-not-found"
|
|
273
|
+
});
|
|
274
|
+
return;
|
|
275
|
+
}
|
|
276
|
+
const transactionId = activeIntentIdRef.current ?? moonpayTransactionId;
|
|
277
|
+
try {
|
|
278
|
+
emitDebug("register-token-mapping:request", {
|
|
279
|
+
transactionId,
|
|
280
|
+
moonpayTransactionId,
|
|
281
|
+
tokenId,
|
|
282
|
+
chainId: token.chainId
|
|
283
|
+
});
|
|
284
|
+
const record = await executePrivateRead(
|
|
285
|
+
() => client.updateOnRamp(transactionId, {
|
|
286
|
+
token_id: tokenId,
|
|
287
|
+
chain_id: token.chainId,
|
|
288
|
+
moonpay_transaction_id: transactionId === moonpayTransactionId ? void 0 : moonpayTransactionId
|
|
289
|
+
})
|
|
290
|
+
);
|
|
291
|
+
emitDebug("register-token-mapping:success", {
|
|
292
|
+
transactionId,
|
|
293
|
+
moonpayTransactionId,
|
|
294
|
+
record: summariseOnRampRecord(record)
|
|
295
|
+
});
|
|
296
|
+
} catch (err) {
|
|
297
|
+
emitDebug("register-token-mapping:error", {
|
|
298
|
+
transactionId,
|
|
299
|
+
moonpayTransactionId,
|
|
300
|
+
...errorPayload(err)
|
|
301
|
+
});
|
|
302
|
+
console.warn("Failed to register on-ramp token mapping:", err);
|
|
303
|
+
}
|
|
304
|
+
},
|
|
305
|
+
[client, emitDebug, enabledTokens, executePrivateRead, tokenId]
|
|
306
|
+
);
|
|
307
|
+
const handleTransactionCreated = useCallback(
|
|
308
|
+
async (props) => {
|
|
309
|
+
emitDebug("moonpay:onTransactionCreated", summariseMoonPayEventProps(props));
|
|
310
|
+
purchaseInitiatedRef.current = true;
|
|
311
|
+
await registerOnRampTokenMapping(props.id);
|
|
312
|
+
},
|
|
313
|
+
[emitDebug, registerOnRampTokenMapping]
|
|
314
|
+
);
|
|
315
|
+
const signUrl = useCallback(
|
|
316
|
+
async (url) => {
|
|
317
|
+
setError(null);
|
|
318
|
+
try {
|
|
319
|
+
emitDebug("moonpay:onUrlSignatureRequested", summariseMoonPayUrl(url));
|
|
320
|
+
const { signature } = await executePrivateRead(() => client.signOnRampUrl({ url }));
|
|
321
|
+
setStatus("awaiting-purchase");
|
|
322
|
+
emitDebug("sign-url:success", {
|
|
323
|
+
signatureLength: signature.length
|
|
324
|
+
});
|
|
325
|
+
return signature;
|
|
326
|
+
} catch (err) {
|
|
327
|
+
const e = err instanceof Error ? err : new Error("Failed to sign on-ramp URL");
|
|
328
|
+
setStatus("failed");
|
|
329
|
+
setError(e);
|
|
330
|
+
emitDebug("sign-url:error", errorPayload(e));
|
|
331
|
+
onErrorRef.current?.(e);
|
|
332
|
+
throw err;
|
|
333
|
+
}
|
|
334
|
+
},
|
|
335
|
+
[client, emitDebug, executePrivateRead]
|
|
336
|
+
);
|
|
337
|
+
const waitForOnChainHash = useCallback(
|
|
338
|
+
async (transactionId) => {
|
|
339
|
+
const startTime = Date.now();
|
|
340
|
+
emitDebug("delivery-poll:start", {
|
|
341
|
+
transactionId,
|
|
342
|
+
deliveryTimeout,
|
|
343
|
+
deliveryPollInterval
|
|
344
|
+
});
|
|
345
|
+
while (Date.now() - startTime < deliveryTimeout) {
|
|
346
|
+
try {
|
|
347
|
+
const { pending: rows } = await executePrivateRead(() => client.getPendingOnRamps());
|
|
348
|
+
setPending(rows);
|
|
349
|
+
const record = rows.find((r) => matchesOnRampTransaction(r, transactionId));
|
|
350
|
+
emitDebug("delivery-poll:tick", {
|
|
351
|
+
transactionId,
|
|
352
|
+
count: rows.length,
|
|
353
|
+
matchingRecord: record ? summariseOnRampRecord(record) : null
|
|
354
|
+
});
|
|
355
|
+
if (record?.on_chain_tx_hash && record.quote_currency_amount) {
|
|
356
|
+
emitDebug("delivery-poll:success", {
|
|
357
|
+
transactionId,
|
|
358
|
+
record: summariseOnRampRecord(record)
|
|
359
|
+
});
|
|
360
|
+
return record;
|
|
361
|
+
}
|
|
362
|
+
} catch (err) {
|
|
363
|
+
emitDebug("delivery-poll:error", {
|
|
364
|
+
transactionId,
|
|
365
|
+
...errorPayload(err)
|
|
366
|
+
});
|
|
367
|
+
console.warn("Polling pending on-ramps failed:", err);
|
|
368
|
+
}
|
|
369
|
+
await new Promise((r) => setTimeout(r, deliveryPollInterval));
|
|
370
|
+
}
|
|
371
|
+
emitDebug("delivery-poll:timeout", { transactionId });
|
|
372
|
+
return null;
|
|
373
|
+
},
|
|
374
|
+
[client, deliveryPollInterval, deliveryTimeout, emitDebug, executePrivateRead]
|
|
375
|
+
);
|
|
376
|
+
const triggerVerification = useCallback(
|
|
377
|
+
async (record) => {
|
|
378
|
+
const verificationKey = getOnRampVerificationKey(record);
|
|
379
|
+
if (triggeredVerificationKeysRef.current.has(verificationKey)) {
|
|
380
|
+
emitDebug("verification:skip-duplicate", {
|
|
381
|
+
verificationKey,
|
|
382
|
+
record: summariseOnRampRecord(record)
|
|
383
|
+
});
|
|
384
|
+
return;
|
|
385
|
+
}
|
|
386
|
+
triggeredVerificationKeysRef.current.add(verificationKey);
|
|
387
|
+
activeVerificationKeyRef.current = verificationKey;
|
|
388
|
+
activeVerificationRecordRef.current = record;
|
|
389
|
+
setFinalityProgress((prev) => {
|
|
390
|
+
if (!(record.transaction_id in prev)) return prev;
|
|
391
|
+
const next = { ...prev };
|
|
392
|
+
delete next[record.transaction_id];
|
|
393
|
+
return next;
|
|
394
|
+
});
|
|
395
|
+
emitDebug("verification:start", {
|
|
396
|
+
verificationKey,
|
|
397
|
+
record: summariseOnRampRecord(record)
|
|
398
|
+
});
|
|
399
|
+
try {
|
|
400
|
+
if (!record.on_chain_tx_hash || !record.quote_currency_amount) {
|
|
401
|
+
throw new Error("On-ramp record missing on-chain tx hash or delivered amount");
|
|
402
|
+
}
|
|
403
|
+
if (record.chain_id === void 0 || !record.wallet_address) {
|
|
404
|
+
throw new Error("On-ramp record missing chain id or wallet address");
|
|
405
|
+
}
|
|
406
|
+
const recordTokenId = record.token_id;
|
|
407
|
+
if (!recordTokenId) {
|
|
408
|
+
throw new Error("On-ramp record missing token id");
|
|
409
|
+
}
|
|
410
|
+
const token = enabledTokens.find((t) => t.id.toLowerCase() === recordTokenId.toLowerCase());
|
|
411
|
+
if (!token) throw new Error(`Unknown token: ${recordTokenId}`);
|
|
412
|
+
if (token.chainId !== record.chain_id) {
|
|
413
|
+
throw new Error(
|
|
414
|
+
`Token ${recordTokenId} is on chain ${token.chainId} but record is on chain ${record.chain_id}`
|
|
415
|
+
);
|
|
416
|
+
}
|
|
417
|
+
const amount = await resolveDeliveredAmount({
|
|
418
|
+
onChainTxHash: record.on_chain_tx_hash,
|
|
419
|
+
chainId: record.chain_id,
|
|
420
|
+
walletAddress: record.wallet_address,
|
|
421
|
+
token,
|
|
422
|
+
fallbackAmount: record.quote_currency_amount,
|
|
423
|
+
wagmiConfig,
|
|
424
|
+
emitDebug
|
|
425
|
+
});
|
|
426
|
+
if (minDepositBaseUnits !== void 0 && amount < minDepositBaseUnits) {
|
|
427
|
+
emitDebug("verification:below-minimum", {
|
|
428
|
+
quoteCurrencyAmount: record.quote_currency_amount,
|
|
429
|
+
minDepositBaseUnits: String(minDepositBaseUnits)
|
|
430
|
+
});
|
|
431
|
+
throw new Error(
|
|
432
|
+
`Delivered amount (${record.quote_currency_amount}) is below the minimum deposit.`
|
|
433
|
+
);
|
|
434
|
+
}
|
|
435
|
+
if (activeIntentIdRef.current === record.transaction_id) {
|
|
436
|
+
setStatus("verifying");
|
|
437
|
+
}
|
|
438
|
+
emitDebug("verification:check-deposit-request", {
|
|
439
|
+
hash: record.on_chain_tx_hash,
|
|
440
|
+
chainId: record.chain_id,
|
|
441
|
+
amount: amount.toString()
|
|
442
|
+
});
|
|
443
|
+
await verify({
|
|
444
|
+
hash: record.on_chain_tx_hash,
|
|
445
|
+
chainId: record.chain_id,
|
|
446
|
+
amount
|
|
447
|
+
});
|
|
448
|
+
} catch (err) {
|
|
449
|
+
triggeredVerificationKeysRef.current.delete(verificationKey);
|
|
450
|
+
if (activeVerificationKeyRef.current === verificationKey) {
|
|
451
|
+
activeVerificationKeyRef.current = null;
|
|
452
|
+
activeVerificationRecordRef.current = null;
|
|
453
|
+
}
|
|
454
|
+
throw err;
|
|
455
|
+
}
|
|
456
|
+
},
|
|
457
|
+
[emitDebug, enabledTokens, minDepositBaseUnits, verify, wagmiConfig]
|
|
458
|
+
);
|
|
459
|
+
const handleTransactionCompleted = useCallback(
|
|
460
|
+
async (props) => {
|
|
461
|
+
emitDebug("moonpay:onTransactionCompleted", summariseMoonPayEventProps(props));
|
|
462
|
+
try {
|
|
463
|
+
setStatus("awaiting-delivery");
|
|
464
|
+
await registerOnRampTokenMapping(props.id);
|
|
465
|
+
const transactionId = activeIntentIdRef.current ?? props.id;
|
|
466
|
+
const record = await waitForOnChainHash(transactionId);
|
|
467
|
+
if (!record) {
|
|
468
|
+
const err = new Error(
|
|
469
|
+
"Backend has not yet confirmed delivery. You can finish from the pending list."
|
|
470
|
+
);
|
|
471
|
+
emitDebug("moonpay:completed-without-backend-row", {
|
|
472
|
+
transactionId,
|
|
473
|
+
moonpayTransactionId: props.id,
|
|
474
|
+
message: err.message
|
|
475
|
+
});
|
|
476
|
+
setStatus("failed");
|
|
477
|
+
setError(err);
|
|
478
|
+
onErrorRef.current?.(err);
|
|
479
|
+
return;
|
|
480
|
+
}
|
|
481
|
+
await triggerVerification(record);
|
|
482
|
+
} catch (err) {
|
|
483
|
+
const e = err instanceof Error ? err : new Error("Verification failed");
|
|
484
|
+
emitDebug("moonpay:onTransactionCompleted-error", errorPayload(e));
|
|
485
|
+
setStatus("failed");
|
|
486
|
+
setError(e);
|
|
487
|
+
onErrorRef.current?.(e);
|
|
488
|
+
}
|
|
489
|
+
},
|
|
490
|
+
[emitDebug, registerOnRampTokenMapping, triggerVerification, waitForOnChainHash]
|
|
491
|
+
);
|
|
492
|
+
const handleWidgetClosed = useCallback(async () => {
|
|
493
|
+
if (closeReconcilePromiseRef.current) return closeReconcilePromiseRef.current;
|
|
494
|
+
closeReconcilePromiseRef.current = (async () => {
|
|
495
|
+
const previousStatus = statusRef.current;
|
|
496
|
+
const transactionId = activeIntentIdRef.current;
|
|
497
|
+
emitDebug("moonpay:widget-closed-reconcile", {
|
|
498
|
+
previousStatus,
|
|
499
|
+
transactionId
|
|
500
|
+
});
|
|
501
|
+
if (!transactionId) {
|
|
502
|
+
await refreshPending();
|
|
503
|
+
return;
|
|
504
|
+
}
|
|
505
|
+
if (!purchaseInitiatedRef.current) {
|
|
506
|
+
emitDebug("moonpay:widget-closed-without-purchase", {
|
|
507
|
+
previousStatus,
|
|
508
|
+
transactionId
|
|
509
|
+
});
|
|
510
|
+
await refreshPending();
|
|
511
|
+
if (previousStatus === "awaiting-purchase" || previousStatus === "awaiting-delivery") {
|
|
512
|
+
setStatus("idle");
|
|
513
|
+
}
|
|
514
|
+
return;
|
|
515
|
+
}
|
|
516
|
+
try {
|
|
517
|
+
setStatus("awaiting-delivery");
|
|
518
|
+
const record = await waitForOnChainHash(transactionId);
|
|
519
|
+
if (record) {
|
|
520
|
+
await triggerVerification(record);
|
|
521
|
+
return;
|
|
522
|
+
}
|
|
523
|
+
await refreshPending();
|
|
524
|
+
if (previousStatus === "awaiting-purchase" || previousStatus === "awaiting-delivery") {
|
|
525
|
+
setStatus("idle");
|
|
526
|
+
}
|
|
527
|
+
} catch (err) {
|
|
528
|
+
const e = err instanceof Error ? err : new Error("On-ramp reconciliation failed");
|
|
529
|
+
emitDebug("moonpay:widget-closed-reconcile-error", errorPayload(e));
|
|
530
|
+
setStatus("failed");
|
|
531
|
+
setError(e);
|
|
532
|
+
onErrorRef.current?.(e);
|
|
533
|
+
}
|
|
534
|
+
})();
|
|
535
|
+
try {
|
|
536
|
+
await closeReconcilePromiseRef.current;
|
|
537
|
+
} finally {
|
|
538
|
+
closeReconcilePromiseRef.current = null;
|
|
539
|
+
}
|
|
540
|
+
}, [emitDebug, refreshPending, triggerVerification, waitForOnChainHash]);
|
|
541
|
+
const finishPendingVerification = useCallback(
|
|
542
|
+
async (record) => {
|
|
543
|
+
try {
|
|
544
|
+
emitDebug("pending:finish-verification", {
|
|
545
|
+
record: summariseOnRampRecord(record)
|
|
546
|
+
});
|
|
547
|
+
await triggerVerification(record);
|
|
548
|
+
} catch (err) {
|
|
549
|
+
const e = err instanceof Error ? err : new Error("Verification failed");
|
|
550
|
+
emitDebug("pending:finish-verification-error", errorPayload(e));
|
|
551
|
+
setStatus("failed");
|
|
552
|
+
setError(e);
|
|
553
|
+
onErrorRef.current?.(e);
|
|
554
|
+
throw e;
|
|
555
|
+
}
|
|
556
|
+
},
|
|
557
|
+
[emitDebug, triggerVerification]
|
|
558
|
+
);
|
|
559
|
+
const triggerVerificationRef = useRef(triggerVerification);
|
|
560
|
+
useEffect(() => {
|
|
561
|
+
triggerVerificationRef.current = triggerVerification;
|
|
562
|
+
}, [triggerVerification]);
|
|
563
|
+
useEffect(() => {
|
|
564
|
+
let cancelled = false;
|
|
565
|
+
void (async () => {
|
|
566
|
+
for (const record of pending) {
|
|
567
|
+
if (cancelled) break;
|
|
568
|
+
if (!record.on_chain_tx_hash || !record.quote_currency_amount) continue;
|
|
569
|
+
const key = getOnRampVerificationKey(record);
|
|
570
|
+
if (triggeredVerificationKeysRef.current.has(key)) continue;
|
|
571
|
+
try {
|
|
572
|
+
await triggerVerificationRef.current(record);
|
|
573
|
+
} catch {
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
})();
|
|
577
|
+
return () => {
|
|
578
|
+
cancelled = true;
|
|
579
|
+
};
|
|
580
|
+
}, [pending]);
|
|
581
|
+
return {
|
|
582
|
+
status,
|
|
583
|
+
activeIntentId,
|
|
584
|
+
pending,
|
|
585
|
+
error,
|
|
586
|
+
finalityProgress,
|
|
587
|
+
depositAddress,
|
|
588
|
+
minDepositBaseUnits,
|
|
589
|
+
selectedToken,
|
|
590
|
+
prepareOnRampIntent,
|
|
591
|
+
signUrl,
|
|
592
|
+
handleTransactionCreated,
|
|
593
|
+
handleTransactionCompleted,
|
|
594
|
+
finishPendingVerification,
|
|
595
|
+
handleWidgetClosed,
|
|
596
|
+
refreshPending
|
|
597
|
+
};
|
|
598
|
+
}
|
|
599
|
+
function summariseToken(token) {
|
|
600
|
+
return {
|
|
601
|
+
tokenId: token.id,
|
|
602
|
+
chainId: token.chainId,
|
|
603
|
+
symbol: token.symbol ?? null,
|
|
604
|
+
decimals: token.decimals ?? null
|
|
605
|
+
};
|
|
606
|
+
}
|
|
607
|
+
function summariseOnRampRecord(record) {
|
|
608
|
+
return {
|
|
609
|
+
transaction_id: record.transaction_id,
|
|
610
|
+
external_transaction_id: record.external_transaction_id ?? null,
|
|
611
|
+
moonpay_transaction_id: record.moonpay_transaction_id ?? null,
|
|
612
|
+
status: record.status,
|
|
613
|
+
wallet_address: record.wallet_address,
|
|
614
|
+
token_id: record.token_id,
|
|
615
|
+
chain_id: record.chain_id,
|
|
616
|
+
moonpay_currency_code: record.moonpay_currency_code ?? null,
|
|
617
|
+
quote_currency_amount: record.quote_currency_amount ?? null,
|
|
618
|
+
on_chain_tx_hash: record.on_chain_tx_hash ?? null,
|
|
619
|
+
deposit_tx_hash: record.deposit_tx_hash ?? null,
|
|
620
|
+
deposit_triggered_at: record.deposit_triggered_at ?? null,
|
|
621
|
+
credited_at: record.credited_at ?? null
|
|
622
|
+
};
|
|
623
|
+
}
|
|
624
|
+
async function resolveDeliveredAmount({
|
|
625
|
+
onChainTxHash,
|
|
626
|
+
chainId,
|
|
627
|
+
walletAddress,
|
|
628
|
+
token,
|
|
629
|
+
fallbackAmount,
|
|
630
|
+
wagmiConfig,
|
|
631
|
+
emitDebug
|
|
632
|
+
}) {
|
|
633
|
+
if (token.contract === zeroAddress) {
|
|
634
|
+
return parseUnits(fallbackAmount, token.decimals);
|
|
635
|
+
}
|
|
636
|
+
let receiptError;
|
|
637
|
+
try {
|
|
638
|
+
const receipt = await waitForTransactionReceipt(wagmiConfig, {
|
|
639
|
+
hash: onChainTxHash,
|
|
640
|
+
chainId,
|
|
641
|
+
timeout: 6e4,
|
|
642
|
+
pollingInterval: 4e3
|
|
643
|
+
});
|
|
644
|
+
let delivered = 0n;
|
|
645
|
+
for (const log of receipt.logs) {
|
|
646
|
+
if (log.address.toLowerCase() !== token.contract.toLowerCase()) continue;
|
|
647
|
+
try {
|
|
648
|
+
const decoded = decodeEventLog({
|
|
649
|
+
abi: [ERC20_TRANSFER_EVENT],
|
|
650
|
+
data: log.data,
|
|
651
|
+
topics: log.topics
|
|
652
|
+
});
|
|
653
|
+
if (decoded.eventName !== "Transfer") continue;
|
|
654
|
+
const to = decoded.args.to.toLowerCase();
|
|
655
|
+
if (to !== walletAddress.toLowerCase()) continue;
|
|
656
|
+
delivered += decoded.args.value;
|
|
657
|
+
} catch {
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
if (delivered > 0n) {
|
|
661
|
+
emitDebug("verification:amount-from-receipt", {
|
|
662
|
+
amount: delivered.toString(),
|
|
663
|
+
tokenAddress: token.contract,
|
|
664
|
+
walletAddress,
|
|
665
|
+
moonpayQuoteCurrencyAmount: fallbackAmount
|
|
666
|
+
});
|
|
667
|
+
return delivered;
|
|
668
|
+
}
|
|
669
|
+
emitDebug("verification:amount-from-receipt-missing", {
|
|
670
|
+
tokenAddress: token.contract,
|
|
671
|
+
walletAddress,
|
|
672
|
+
moonpayQuoteCurrencyAmount: fallbackAmount
|
|
673
|
+
});
|
|
674
|
+
} catch (err) {
|
|
675
|
+
emitDebug("verification:amount-from-receipt-error", errorPayload(err));
|
|
676
|
+
receiptError = err;
|
|
677
|
+
}
|
|
678
|
+
const errorDetail = receiptError instanceof Error ? receiptError.message : receiptError === void 0 ? `no ${token.symbol} Transfer to ${walletAddress} found` : String(receiptError);
|
|
679
|
+
throw new Error(
|
|
680
|
+
`Unable to derive delivered ${token.symbol} amount from ${onChainTxHash}: ${errorDetail}`
|
|
681
|
+
);
|
|
682
|
+
}
|
|
683
|
+
function matchesOnRampTransaction(record, transactionId) {
|
|
684
|
+
return record.transaction_id === transactionId || record.external_transaction_id === transactionId || record.moonpay_transaction_id === transactionId;
|
|
685
|
+
}
|
|
686
|
+
function getOnRampVerificationKey(record) {
|
|
687
|
+
return record.on_chain_tx_hash ?? record.transaction_id;
|
|
688
|
+
}
|
|
689
|
+
function summariseMoonPayEventProps(props) {
|
|
690
|
+
return {
|
|
691
|
+
id: props.id,
|
|
692
|
+
externalTransactionId: props.externalTransactionId,
|
|
693
|
+
status: props.status,
|
|
694
|
+
walletAddress: props.walletAddress,
|
|
695
|
+
walletAddressTag: props.walletAddressTag,
|
|
696
|
+
baseCurrencyAmount: props.baseCurrencyAmount,
|
|
697
|
+
quoteCurrencyAmount: props.quoteCurrencyAmount,
|
|
698
|
+
baseCurrency: props.baseCurrency,
|
|
699
|
+
quoteCurrency: props.quoteCurrency,
|
|
700
|
+
createdAt: props.createdAt
|
|
701
|
+
};
|
|
702
|
+
}
|
|
703
|
+
function summariseMoonPayUrl(url) {
|
|
704
|
+
try {
|
|
705
|
+
const parsed = new URL(url);
|
|
706
|
+
const params = parsed.searchParams;
|
|
707
|
+
return {
|
|
708
|
+
origin: parsed.origin,
|
|
709
|
+
pathname: parsed.pathname,
|
|
710
|
+
apiKeyPrefix: params.get("apiKey")?.slice(0, 8) ?? null,
|
|
711
|
+
currencyCode: params.get("currencyCode"),
|
|
712
|
+
baseCurrencyCode: params.get("baseCurrencyCode"),
|
|
713
|
+
baseCurrencyAmount: params.get("baseCurrencyAmount"),
|
|
714
|
+
walletAddress: params.get("walletAddress"),
|
|
715
|
+
externalCustomerId: params.get("externalCustomerId"),
|
|
716
|
+
externalTransactionId: params.get("externalTransactionId"),
|
|
717
|
+
redirectURL: params.get("redirectURL"),
|
|
718
|
+
signaturePresent: params.has("signature")
|
|
719
|
+
};
|
|
720
|
+
} catch {
|
|
721
|
+
return { parseError: true, length: url.length };
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
function errorPayload(err) {
|
|
725
|
+
if (err instanceof Error) {
|
|
726
|
+
return {
|
|
727
|
+
name: err.name,
|
|
728
|
+
message: err.message,
|
|
729
|
+
stack: err.stack?.split("\n").slice(0, 4).join("\n")
|
|
730
|
+
};
|
|
731
|
+
}
|
|
732
|
+
return { message: String(err) };
|
|
733
|
+
}
|
|
734
|
+
function FiatOnRampForm({
|
|
735
|
+
tokenId,
|
|
736
|
+
currencyCode,
|
|
737
|
+
baseCurrencyCode = "usd",
|
|
738
|
+
defaultBaseCurrencyAmount = "100",
|
|
739
|
+
tokenSymbol,
|
|
740
|
+
onCredited,
|
|
741
|
+
onError,
|
|
742
|
+
onDebugEvent
|
|
743
|
+
}) {
|
|
744
|
+
const { address } = useAccount();
|
|
745
|
+
const [visible, setVisible] = useState(false);
|
|
746
|
+
const [isPreparing, setIsPreparing] = useState(false);
|
|
747
|
+
const [rowError, setRowError] = useState(null);
|
|
748
|
+
const {
|
|
749
|
+
status,
|
|
750
|
+
activeIntentId,
|
|
751
|
+
pending,
|
|
752
|
+
error,
|
|
753
|
+
finalityProgress,
|
|
754
|
+
depositAddress,
|
|
755
|
+
minDepositBaseUnits,
|
|
756
|
+
selectedToken,
|
|
757
|
+
prepareOnRampIntent,
|
|
758
|
+
signUrl,
|
|
759
|
+
handleTransactionCreated,
|
|
760
|
+
handleTransactionCompleted,
|
|
761
|
+
finishPendingVerification,
|
|
762
|
+
handleWidgetClosed
|
|
763
|
+
} = useFiatOnRamp({ tokenId, onCredited, onError, onDebugEvent });
|
|
764
|
+
const decimals = selectedToken?.decimals;
|
|
765
|
+
const displaySymbol = tokenSymbol ?? selectedToken?.symbol ?? currencyCode.toUpperCase();
|
|
766
|
+
const emitFormDebug = useCallback(
|
|
767
|
+
(event, payload) => {
|
|
768
|
+
onDebugEvent?.({
|
|
769
|
+
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
770
|
+
event,
|
|
771
|
+
status,
|
|
772
|
+
tokenId,
|
|
773
|
+
payload
|
|
774
|
+
});
|
|
775
|
+
},
|
|
776
|
+
[onDebugEvent, status, tokenId]
|
|
777
|
+
);
|
|
778
|
+
const minFiatGate = minDepositBaseUnits !== void 0 && decimals !== void 0 ? Number(formatUnits(minDepositBaseUnits, decimals)) * 1.05 : void 0;
|
|
779
|
+
const isBelowMin = minFiatGate !== void 0 && Number(defaultBaseCurrencyAmount) < minFiatGate;
|
|
780
|
+
const isBusy = isPreparing || status === "awaiting-purchase";
|
|
781
|
+
const isInitializing = !!address && !depositAddress;
|
|
782
|
+
const blockReasons = useMemo(
|
|
783
|
+
() => [
|
|
784
|
+
!address ? "wallet-not-connected" : null,
|
|
785
|
+
!depositAddress ? "deposit-address-not-loaded" : null,
|
|
786
|
+
isBusy ? `busy:${isPreparing ? "preparing" : status}` : null,
|
|
787
|
+
visible ? "widget-open" : null,
|
|
788
|
+
isBelowMin ? "below-minimum" : null
|
|
789
|
+
].filter((reason) => Boolean(reason)),
|
|
790
|
+
[address, depositAddress, isBelowMin, isBusy, isPreparing, status, visible]
|
|
791
|
+
);
|
|
792
|
+
const canBuy = blockReasons.length === 0;
|
|
793
|
+
const handleOpen = useCallback(async () => {
|
|
794
|
+
if (!canBuy) {
|
|
795
|
+
emitFormDebug("form:open-blocked", {
|
|
796
|
+
reasons: blockReasons,
|
|
797
|
+
currencyCode,
|
|
798
|
+
tokenSymbol: displaySymbol,
|
|
799
|
+
tokenDecimals: decimals ?? null,
|
|
800
|
+
baseCurrencyCode,
|
|
801
|
+
defaultBaseCurrencyAmount,
|
|
802
|
+
depositAddress: depositAddress ?? null,
|
|
803
|
+
walletAddress: address ?? null,
|
|
804
|
+
status
|
|
805
|
+
});
|
|
806
|
+
return;
|
|
807
|
+
}
|
|
808
|
+
setIsPreparing(true);
|
|
809
|
+
emitFormDebug("form:open-click", {
|
|
810
|
+
currencyCode,
|
|
811
|
+
tokenSymbol: displaySymbol,
|
|
812
|
+
tokenDecimals: decimals ?? null,
|
|
813
|
+
baseCurrencyCode,
|
|
814
|
+
defaultBaseCurrencyAmount,
|
|
815
|
+
depositAddress: depositAddress ?? null,
|
|
816
|
+
walletConnected: Boolean(address)
|
|
817
|
+
});
|
|
818
|
+
try {
|
|
819
|
+
const intent = await prepareOnRampIntent({
|
|
820
|
+
currencyCode,
|
|
821
|
+
baseCurrencyCode,
|
|
822
|
+
baseCurrencyAmount: defaultBaseCurrencyAmount
|
|
823
|
+
});
|
|
824
|
+
emitFormDebug("form:intent-ready", {
|
|
825
|
+
transactionId: intent.transaction_id,
|
|
826
|
+
externalTransactionId: intent.external_transaction_id ?? null
|
|
827
|
+
});
|
|
828
|
+
setVisible(true);
|
|
829
|
+
} catch (err) {
|
|
830
|
+
const error2 = err instanceof Error ? err : new Error("Failed to prepare MoonPay on-ramp");
|
|
831
|
+
emitFormDebug("form:intent-error", {
|
|
832
|
+
name: error2.name,
|
|
833
|
+
message: error2.message
|
|
834
|
+
});
|
|
835
|
+
} finally {
|
|
836
|
+
setIsPreparing(false);
|
|
837
|
+
}
|
|
838
|
+
}, [
|
|
839
|
+
address,
|
|
840
|
+
baseCurrencyCode,
|
|
841
|
+
blockReasons,
|
|
842
|
+
canBuy,
|
|
843
|
+
currencyCode,
|
|
844
|
+
decimals,
|
|
845
|
+
displaySymbol,
|
|
846
|
+
defaultBaseCurrencyAmount,
|
|
847
|
+
depositAddress,
|
|
848
|
+
emitFormDebug,
|
|
849
|
+
prepareOnRampIntent,
|
|
850
|
+
status
|
|
851
|
+
]);
|
|
852
|
+
const handleClose = useCallback(async () => {
|
|
853
|
+
emitFormDebug("moonpay:onClose");
|
|
854
|
+
setVisible(false);
|
|
855
|
+
await handleWidgetClosed();
|
|
856
|
+
}, [emitFormDebug, handleWidgetClosed]);
|
|
857
|
+
const handleCloseOverlay = useCallback(async () => {
|
|
858
|
+
emitFormDebug("moonpay:onCloseOverlay");
|
|
859
|
+
setVisible(false);
|
|
860
|
+
await handleWidgetClosed();
|
|
861
|
+
}, [emitFormDebug, handleWidgetClosed]);
|
|
862
|
+
const handleReady = useCallback(async () => {
|
|
863
|
+
emitFormDebug("moonpay:onReady");
|
|
864
|
+
}, [emitFormDebug]);
|
|
865
|
+
return /* @__PURE__ */ jsxs("div", { "data-privana": true, className: "flex flex-col gap-4", children: [
|
|
866
|
+
isInitializing ? /* @__PURE__ */ jsx(Skeleton, { className: "h-9 w-full rounded-md" }) : /* @__PURE__ */ jsxs(Button, { type: "button", onClick: handleOpen, disabled: !canBuy, children: [
|
|
867
|
+
(isBusy || visible) && /* @__PURE__ */ jsx(Loader2, { className: "animate-spin", "aria-hidden": true }),
|
|
868
|
+
"Buy"
|
|
869
|
+
] }),
|
|
870
|
+
error && /* @__PURE__ */ jsx("p", { className: "text-destructive text-sm", role: "alert", children: error.message }),
|
|
871
|
+
isBelowMin && minFiatGate !== void 0 && /* @__PURE__ */ jsxs("p", { className: "text-destructive text-sm", role: "alert", children: [
|
|
872
|
+
"Minimum purchase is ~$",
|
|
873
|
+
minFiatGate.toFixed(2),
|
|
874
|
+
"."
|
|
875
|
+
] }),
|
|
876
|
+
pending.length > 0 && /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-2 rounded-md border p-3", children: [
|
|
877
|
+
/* @__PURE__ */ jsx("p", { className: "text-sm font-medium", children: "Pending payments" }),
|
|
878
|
+
pending.map((record) => {
|
|
879
|
+
const progress = parseFinalityProgress(finalityProgress[record.transaction_id]);
|
|
880
|
+
const hasProgress = !!finalityProgress[record.transaction_id];
|
|
881
|
+
const isStalled = !hasProgress && Date.now() / 1e3 - (record.updated_at ?? 0) > 60;
|
|
882
|
+
const showRetry = rowError?.id === record.transaction_id || isStalled;
|
|
883
|
+
return /* @__PURE__ */ jsxs(
|
|
884
|
+
"div",
|
|
885
|
+
{
|
|
886
|
+
className: "border-border flex flex-col gap-1 rounded-md border p-2",
|
|
887
|
+
children: [
|
|
888
|
+
/* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-2", children: [
|
|
889
|
+
/* @__PURE__ */ jsxs("p", { className: "text-muted-foreground flex items-center gap-1 text-xs", children: [
|
|
890
|
+
/* @__PURE__ */ jsx(Loader2, { className: "size-3 animate-spin", "aria-hidden": true }),
|
|
891
|
+
progress ?? "Verifying\u2026"
|
|
892
|
+
] }),
|
|
893
|
+
/* @__PURE__ */ jsxs("p", { className: "text-muted-foreground text-xs", children: [
|
|
894
|
+
record.quote_currency_amount ?? "?",
|
|
895
|
+
" ",
|
|
896
|
+
displaySymbol
|
|
897
|
+
] })
|
|
898
|
+
] }),
|
|
899
|
+
rowError?.id === record.transaction_id && /* @__PURE__ */ jsx("p", { className: "text-destructive text-xs", children: rowError.message }),
|
|
900
|
+
showRetry && /* @__PURE__ */ jsx(
|
|
901
|
+
Button,
|
|
902
|
+
{
|
|
903
|
+
type: "button",
|
|
904
|
+
variant: "outline",
|
|
905
|
+
size: "sm",
|
|
906
|
+
onClick: async () => {
|
|
907
|
+
setRowError(null);
|
|
908
|
+
try {
|
|
909
|
+
await finishPendingVerification(record);
|
|
910
|
+
} catch (err) {
|
|
911
|
+
setRowError({
|
|
912
|
+
id: record.transaction_id,
|
|
913
|
+
message: err instanceof Error ? err.message : "Verification failed"
|
|
914
|
+
});
|
|
915
|
+
}
|
|
916
|
+
},
|
|
917
|
+
children: "Retry"
|
|
918
|
+
}
|
|
919
|
+
)
|
|
920
|
+
]
|
|
921
|
+
},
|
|
922
|
+
record.transaction_id
|
|
923
|
+
);
|
|
924
|
+
})
|
|
925
|
+
] }),
|
|
926
|
+
visible && depositAddress && activeIntentId && /* @__PURE__ */ jsx(
|
|
927
|
+
MoonPayBuyWidget,
|
|
928
|
+
{
|
|
929
|
+
variant: "overlay",
|
|
930
|
+
visible: true,
|
|
931
|
+
baseCurrencyCode,
|
|
932
|
+
baseCurrencyAmount: defaultBaseCurrencyAmount,
|
|
933
|
+
currencyCode,
|
|
934
|
+
walletAddress: depositAddress,
|
|
935
|
+
externalCustomerId: address?.toLowerCase(),
|
|
936
|
+
externalTransactionId: activeIntentId,
|
|
937
|
+
onClose: handleClose,
|
|
938
|
+
onCloseOverlay: handleCloseOverlay,
|
|
939
|
+
onReady: handleReady,
|
|
940
|
+
onUrlSignatureRequested: signUrl,
|
|
941
|
+
onTransactionCreated: handleTransactionCreated,
|
|
942
|
+
onTransactionCompleted: handleTransactionCompleted
|
|
943
|
+
}
|
|
944
|
+
)
|
|
945
|
+
] });
|
|
946
|
+
}
|
|
947
|
+
function parseFinalityProgress(message) {
|
|
948
|
+
if (!message) return null;
|
|
949
|
+
const match = message.match(/(\d+\/\d+)\s+confirmations/i);
|
|
950
|
+
return match ? `${match[1]} confirmations` : null;
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
export { FiatOnRampForm, useFiatOnRamp };
|
|
954
|
+
//# sourceMappingURL=on-ramp.js.map
|
|
955
|
+
//# sourceMappingURL=on-ramp.js.map
|