@oasisprotocol/privana-sdk 0.2.1 → 0.4.0

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