@mintmoney/react 0.1.0-alpha.31 → 0.1.0-alpha.33

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.
Files changed (162) hide show
  1. package/dist/css/styles.css +8 -6
  2. package/dist/esm/api/generated.js +31 -0
  3. package/dist/esm/api/generated.js.map +1 -1
  4. package/dist/esm/api/index.js +1 -0
  5. package/dist/esm/api/index.js.map +1 -1
  6. package/dist/esm/api/payments.js +39 -0
  7. package/dist/esm/api/payments.js.map +1 -1
  8. package/dist/esm/checkout/index.js +41 -19
  9. package/dist/esm/checkout/index.js.map +1 -1
  10. package/dist/esm/checkout/modal.js +4 -3
  11. package/dist/esm/checkout/modal.js.map +1 -1
  12. package/dist/esm/checkout/providers/wagmi-config.js +82 -0
  13. package/dist/esm/checkout/providers/wagmi-config.js.map +1 -0
  14. package/dist/esm/checkout/surplus-refund.js +38 -0
  15. package/dist/esm/checkout/surplus-refund.js.map +1 -0
  16. package/dist/esm/checkout/views/back.js +2 -2
  17. package/dist/esm/checkout/views/back.js.map +1 -1
  18. package/dist/esm/checkout/views/crypto-intent/direct-details.js +945 -96
  19. package/dist/esm/checkout/views/crypto-intent/direct-details.js.map +1 -1
  20. package/dist/esm/checkout/views/crypto-intent/methods.js +84 -31
  21. package/dist/esm/checkout/views/crypto-intent/methods.js.map +1 -1
  22. package/dist/esm/checkout/views/crypto-intent/processing.js +51 -3
  23. package/dist/esm/checkout/views/crypto-intent/processing.js.map +1 -1
  24. package/dist/esm/checkout/views/crypto-intent/success.js +58 -9
  25. package/dist/esm/checkout/views/crypto-intent/success.js.map +1 -1
  26. package/dist/esm/checkout/views/crypto-intent/wallet-payment-options.js +641 -282
  27. package/dist/esm/checkout/views/crypto-intent/wallet-payment-options.js.map +1 -1
  28. package/dist/esm/checkout/views/crypto-intent/wallet-select.js +104 -20
  29. package/dist/esm/checkout/views/crypto-intent/wallet-select.js.map +1 -1
  30. package/dist/esm/checkout/views/failed.js +83 -1
  31. package/dist/esm/checkout/views/failed.js.map +1 -1
  32. package/dist/esm/checkout/views/initial.js +46 -6
  33. package/dist/esm/checkout/views/initial.js.map +1 -1
  34. package/dist/esm/checkout/views/method-select.js +16 -4
  35. package/dist/esm/checkout/views/method-select.js.map +1 -1
  36. package/dist/esm/checkout/views/restart.js +3 -1
  37. package/dist/esm/checkout/views/restart.js.map +1 -1
  38. package/dist/esm/components/buttons/index.js +4 -1
  39. package/dist/esm/components/buttons/index.js.map +1 -1
  40. package/dist/esm/components/icons/clock.js +4 -0
  41. package/dist/esm/components/icons/clock.js.map +1 -0
  42. package/dist/esm/components/icons/edit.js +6 -0
  43. package/dist/esm/components/icons/edit.js.map +1 -0
  44. package/dist/esm/components/icons/index.js +3 -0
  45. package/dist/esm/components/icons/index.js.map +1 -1
  46. package/dist/esm/components/icons/send.js +6 -0
  47. package/dist/esm/components/icons/send.js.map +1 -0
  48. package/dist/esm/components/index.js +1 -0
  49. package/dist/esm/components/index.js.map +1 -1
  50. package/dist/esm/components/quote-expiry/index.js +2 -0
  51. package/dist/esm/components/quote-expiry/index.js.map +1 -0
  52. package/dist/esm/components/quote-expiry/quote-expiry-countdown.js +35 -0
  53. package/dist/esm/components/quote-expiry/quote-expiry-countdown.js.map +1 -0
  54. package/dist/esm/components/quote-expiry/styles.js +109 -0
  55. package/dist/esm/components/quote-expiry/styles.js.map +1 -0
  56. package/dist/esm/components/quote-expiry/tiers.js +31 -0
  57. package/dist/esm/components/quote-expiry/tiers.js.map +1 -0
  58. package/dist/esm/components/text/index.js +1 -0
  59. package/dist/esm/components/text/index.js.map +1 -1
  60. package/dist/esm/components/wallet-selector/component.js +3 -5
  61. package/dist/esm/components/wallet-selector/component.js.map +1 -1
  62. package/dist/esm/components/wallet-selector/wallets/wagmi/index.js.map +1 -1
  63. package/dist/esm/config.js.map +1 -1
  64. package/dist/esm/index.js +2 -1
  65. package/dist/esm/index.js.map +1 -1
  66. package/dist/esm/integrations/lifi.js +52 -34
  67. package/dist/esm/integrations/lifi.js.map +1 -1
  68. package/dist/esm/refund/index.js +791 -0
  69. package/dist/esm/refund/index.js.map +1 -0
  70. package/dist/esm/state/checkout/payment-attempt.js +3 -0
  71. package/dist/esm/state/checkout/payment-attempt.js.map +1 -1
  72. package/dist/esm/state/checkout/payment-lifecycle.js +66 -0
  73. package/dist/esm/state/checkout/payment-lifecycle.js.map +1 -0
  74. package/dist/esm/state/checkout/store.js +508 -55
  75. package/dist/esm/state/checkout/store.js.map +1 -1
  76. package/dist/esm/state/checkout/wallet-payment-options.js +30 -0
  77. package/dist/esm/state/checkout/wallet-payment-options.js.map +1 -0
  78. package/dist/esm/themes/default.js +6 -0
  79. package/dist/esm/themes/default.js.map +1 -1
  80. package/dist/esm/utils/string.js +1 -0
  81. package/dist/esm/utils/string.js.map +1 -1
  82. package/dist/esm/utils/wallet-errors.js +15 -0
  83. package/dist/esm/utils/wallet-errors.js.map +1 -0
  84. package/dist/types/api/generated.d.ts +207 -4
  85. package/dist/types/api/generated.d.ts.map +1 -1
  86. package/dist/types/api/index.d.ts +2 -1
  87. package/dist/types/api/index.d.ts.map +1 -1
  88. package/dist/types/api/payments.d.ts +36 -1
  89. package/dist/types/api/payments.d.ts.map +1 -1
  90. package/dist/types/api/types.d.ts +4 -0
  91. package/dist/types/api/types.d.ts.map +1 -1
  92. package/dist/types/checkout/index.d.ts +4 -1
  93. package/dist/types/checkout/index.d.ts.map +1 -1
  94. package/dist/types/checkout/modal.d.ts.map +1 -1
  95. package/dist/types/checkout/providers/wagmi-config.d.ts +12 -0
  96. package/dist/types/checkout/providers/wagmi-config.d.ts.map +1 -0
  97. package/dist/types/checkout/surplus-refund.d.ts +10 -0
  98. package/dist/types/checkout/surplus-refund.d.ts.map +1 -0
  99. package/dist/types/checkout/views/back.d.ts +2 -1
  100. package/dist/types/checkout/views/back.d.ts.map +1 -1
  101. package/dist/types/checkout/views/crypto-intent/direct-details.d.ts +10 -1
  102. package/dist/types/checkout/views/crypto-intent/direct-details.d.ts.map +1 -1
  103. package/dist/types/checkout/views/crypto-intent/methods.d.ts.map +1 -1
  104. package/dist/types/checkout/views/crypto-intent/processing.d.ts.map +1 -1
  105. package/dist/types/checkout/views/crypto-intent/success.d.ts.map +1 -1
  106. package/dist/types/checkout/views/crypto-intent/wallet-payment-options.d.ts.map +1 -1
  107. package/dist/types/checkout/views/crypto-intent/wallet-select.d.ts.map +1 -1
  108. package/dist/types/checkout/views/failed.d.ts.map +1 -1
  109. package/dist/types/checkout/views/initial.d.ts +2 -0
  110. package/dist/types/checkout/views/initial.d.ts.map +1 -1
  111. package/dist/types/checkout/views/method-select.d.ts +2 -0
  112. package/dist/types/checkout/views/method-select.d.ts.map +1 -1
  113. package/dist/types/checkout/views/restart.d.ts.map +1 -1
  114. package/dist/types/components/buttons/index.d.ts.map +1 -1
  115. package/dist/types/components/icons/clock.d.ts +6 -0
  116. package/dist/types/components/icons/clock.d.ts.map +1 -0
  117. package/dist/types/components/icons/edit.d.ts +6 -0
  118. package/dist/types/components/icons/edit.d.ts.map +1 -0
  119. package/dist/types/components/icons/index.d.ts +3 -0
  120. package/dist/types/components/icons/index.d.ts.map +1 -1
  121. package/dist/types/components/icons/send.d.ts +6 -0
  122. package/dist/types/components/icons/send.d.ts.map +1 -0
  123. package/dist/types/components/index.d.ts +1 -0
  124. package/dist/types/components/index.d.ts.map +1 -1
  125. package/dist/types/components/quote-expiry/index.d.ts +2 -0
  126. package/dist/types/components/quote-expiry/index.d.ts.map +1 -0
  127. package/dist/types/components/quote-expiry/quote-expiry-countdown.d.ts +15 -0
  128. package/dist/types/components/quote-expiry/quote-expiry-countdown.d.ts.map +1 -0
  129. package/dist/types/components/quote-expiry/styles.d.ts +22 -0
  130. package/dist/types/components/quote-expiry/styles.d.ts.map +1 -0
  131. package/dist/types/components/quote-expiry/tiers.d.ts +10 -0
  132. package/dist/types/components/quote-expiry/tiers.d.ts.map +1 -0
  133. package/dist/types/components/text/index.d.ts.map +1 -1
  134. package/dist/types/components/wallet-selector/component.d.ts +1 -2
  135. package/dist/types/components/wallet-selector/component.d.ts.map +1 -1
  136. package/dist/types/components/wallet-selector/domain.d.ts +3 -2
  137. package/dist/types/components/wallet-selector/domain.d.ts.map +1 -1
  138. package/dist/types/components/wallet-selector/wallets/wagmi/index.d.ts +41 -5
  139. package/dist/types/components/wallet-selector/wallets/wagmi/index.d.ts.map +1 -1
  140. package/dist/types/config.d.ts +4 -0
  141. package/dist/types/config.d.ts.map +1 -1
  142. package/dist/types/index.d.ts +2 -1
  143. package/dist/types/index.d.ts.map +1 -1
  144. package/dist/types/integrations/lifi.d.ts.map +1 -1
  145. package/dist/types/refund/index.d.ts +82 -0
  146. package/dist/types/refund/index.d.ts.map +1 -0
  147. package/dist/types/state/checkout/payment-attempt.d.ts.map +1 -1
  148. package/dist/types/state/checkout/payment-lifecycle.d.ts +37 -0
  149. package/dist/types/state/checkout/payment-lifecycle.d.ts.map +1 -0
  150. package/dist/types/state/checkout/store.d.ts +40 -2
  151. package/dist/types/state/checkout/store.d.ts.map +1 -1
  152. package/dist/types/state/checkout/wallet-payment-options.d.ts +18 -0
  153. package/dist/types/state/checkout/wallet-payment-options.d.ts.map +1 -0
  154. package/dist/types/themes/default.d.ts.map +1 -1
  155. package/dist/types/themes/types.d.ts +11 -0
  156. package/dist/types/themes/types.d.ts.map +1 -1
  157. package/dist/types/utils/string.d.ts +1 -0
  158. package/dist/types/utils/string.d.ts.map +1 -1
  159. package/dist/types/utils/wallet-errors.d.ts +2 -0
  160. package/dist/types/utils/wallet-errors.d.ts.map +1 -0
  161. package/package.json +25 -18
  162. package/LICENSE +0 -21
@@ -7,6 +7,9 @@ import { PaymentStatus, } from "../../api/types.js";
7
7
  import { WagmiWalletInterface } from "../../components/wallet-selector/wallets/wagmi/index.js";
8
8
  import { resolveEvmChainId, switchEvmWalletChain, } from "../../integrations/evm-chain.js";
9
9
  import { buildWalletPaymentAttemptPayload } from "./payment-attempt.js";
10
+ import { canCreateFreshAttempt, getAttemptExpiry, getAttemptQuoteTiming, isAttemptStale, } from "./payment-lifecycle.js";
11
+ const PAYMENT_NO_LONGER_PAYABLE_MESSAGE = "This payment is no longer payable.";
12
+ const STALE_REPLACEMENT_QUOTE_MESSAGE = "The refreshed quote expired before it could be used. Please try again.";
10
13
  export var ACTIONS;
11
14
  (function (ACTIONS) {
12
15
  ACTIONS["GET_CHECKOUT_CONFIG"] = "GET_CHECKOUT_CONFIG";
@@ -23,6 +26,7 @@ export var ACTIONS;
23
26
  const initialWalletPaymentState = () => ({
24
27
  status: "idle",
25
28
  options: [],
29
+ walletAddress: null,
26
30
  selectedOptionId: null,
27
31
  quoteId: null,
28
32
  routeId: null,
@@ -41,6 +45,7 @@ export const useCheckoutStore = create()(immer((_set, _get) => ({
41
45
  checkoutId: null,
42
46
  selectedMethod: null,
43
47
  selectedCurrency: null,
48
+ retrySession: false,
44
49
  methods: null,
45
50
  cryptoCurrency: null,
46
51
  checkout: null,
@@ -61,12 +66,383 @@ export const useCheckoutStore = create()(immer((_set, _get) => ({
61
66
  pollCount: 0,
62
67
  lastPollTime: null,
63
68
  },
69
+ quote: {
70
+ status: "idle",
71
+ error: null,
72
+ expiresAt: null,
73
+ remainingMs: null,
74
+ totalDurationMs: null,
75
+ },
64
76
  walletPayment: initialWalletPaymentState(),
65
77
  })));
66
78
  const set = (fn) => {
67
79
  useCheckoutStore.setState(fn);
68
80
  };
69
81
  const get = () => useCheckoutStore.getState();
82
+ // Quote refresh is mode-agnostic from a view's perspective: the store remembers
83
+ // how to rebuild (wallet route vs manual address) while views only read
84
+ // `quote.status`. A one-shot timer refreshes the live quote at expiry, while a
85
+ // lightweight interval updates the visible countdown.
86
+ let refreshMode = "none";
87
+ let quoteExpiryTimer = null;
88
+ let quoteCountdownInterval = null;
89
+ // True only while refreshQuote() is rebuilding the attempt. This is the
90
+ // re-entrancy guard (not quote.status): intermediate snapshots emitted during
91
+ // the rebuild are ignored, and refreshQuote settles the final state itself when
92
+ // it returns — so a freshly created attempt can never leave the UI stuck on the
93
+ // "refreshing" spinner, and a stale rebuild can never tight-loop.
94
+ let isRefreshing = false;
95
+ const clearQuoteExpiryTimer = () => {
96
+ if (quoteExpiryTimer) {
97
+ clearTimeout(quoteExpiryTimer);
98
+ quoteExpiryTimer = null;
99
+ }
100
+ if (quoteCountdownInterval) {
101
+ clearInterval(quoteCountdownInterval);
102
+ quoteCountdownInterval = null;
103
+ }
104
+ };
105
+ const clearQuoteAutoRefreshTimer = () => {
106
+ if (quoteExpiryTimer) {
107
+ clearTimeout(quoteExpiryTimer);
108
+ quoteExpiryTimer = null;
109
+ }
110
+ };
111
+ const getPreservedRefreshingQuoteState = () => {
112
+ const currentQuote = get().quote;
113
+ if (currentQuote.remainingMs === null) {
114
+ return { status: "refreshing", error: null, ...clearQuoteTiming() };
115
+ }
116
+ return {
117
+ status: "refreshing",
118
+ error: null,
119
+ expiresAt: currentQuote.expiresAt,
120
+ remainingMs: currentQuote.expiresAt !== null
121
+ ? Math.max(0, currentQuote.expiresAt - Date.now())
122
+ : currentQuote.remainingMs,
123
+ totalDurationMs: currentQuote.totalDurationMs,
124
+ };
125
+ };
126
+ const getCurrentCheckoutAttempt = (state = get()) => {
127
+ return state.cryptoPaymentAttempt ?? state.payment?.payment_attempt ?? null;
128
+ };
129
+ const normalizeWalletAddress = (value) => value?.trim().toLowerCase() || null;
130
+ const attemptMatchesSource = (attempt, source) => {
131
+ const attemptSource = attempt?.routing?.source;
132
+ return (attemptSource?.token?.toLowerCase() === source.token.toLowerCase() &&
133
+ attemptSource?.chain?.toLowerCase() === source.chain.toLowerCase());
134
+ };
135
+ const getReusableCurrentAttemptForSource = (source) => {
136
+ const attempt = getCurrentCheckoutAttempt();
137
+ if (!attempt || isAttemptStale(attempt))
138
+ return null;
139
+ if (!attemptMatchesSource(attempt, source))
140
+ return null;
141
+ return normalizeWalletAddress(attempt.refund_to) ===
142
+ normalizeWalletAddress(source.sendingAddress)
143
+ ? attempt
144
+ : null;
145
+ };
146
+ const reuseCurrentAttempt = (attempt) => {
147
+ set((state) => {
148
+ state.cryptoPaymentAttempt = attempt;
149
+ state.error[ACTIONS.CREATE_PAYMENT_ATTEMPT] = null;
150
+ state.loading[ACTIONS.CREATE_PAYMENT_ATTEMPT] = false;
151
+ });
152
+ syncQuote(get().payment, attempt);
153
+ return attempt;
154
+ };
155
+ const withFreshAttempt = (payment, attempt) => {
156
+ if (!payment) {
157
+ return payment;
158
+ }
159
+ return {
160
+ ...payment,
161
+ payment_attempt: attempt,
162
+ };
163
+ };
164
+ const getPaymentSnapshotAfterAttempt = async (paymentId, attempt, fallbackPayment) => {
165
+ try {
166
+ return await getPaymentById(paymentId);
167
+ }
168
+ catch {
169
+ return withFreshAttempt(get().payment ?? fallbackPayment, attempt);
170
+ }
171
+ };
172
+ const buildDirectWalletQuote = (option, attempt) => {
173
+ const amount = String(attempt.amount_formatted);
174
+ return {
175
+ quoteId: option.quoteId,
176
+ routeId: option.routeId,
177
+ toolName: "Direct transfer",
178
+ fromAmount: amount,
179
+ fromAmountDisplay: amount,
180
+ toAmount: amount,
181
+ toAmountDisplay: amount,
182
+ estimatedDurationMinutes: 1,
183
+ };
184
+ };
185
+ const setQuote = (update, walletUpdate) => {
186
+ set((state) => {
187
+ Object.assign(state.quote, update);
188
+ if (walletUpdate) {
189
+ Object.assign(state.walletPayment, walletUpdate);
190
+ }
191
+ });
192
+ };
193
+ const clearQuoteTiming = () => ({
194
+ expiresAt: null,
195
+ remainingMs: null,
196
+ totalDurationMs: null,
197
+ });
198
+ const refreshQuoteCountdown = (expiresAt) => {
199
+ if (expiresAt === null)
200
+ return;
201
+ setQuote({
202
+ remainingMs: Math.max(0, expiresAt - Date.now()),
203
+ });
204
+ };
205
+ const getWalletQuoteLoadingState = () => ({
206
+ quoteStatus: "loading",
207
+ quote: null,
208
+ quoteError: null,
209
+ quoteId: null,
210
+ routeId: null,
211
+ });
212
+ const getWalletQuoteReadyState = (quote) => ({
213
+ quoteStatus: "ready",
214
+ quote,
215
+ quoteId: quote.quoteId,
216
+ routeId: quote.routeId,
217
+ quoteError: null,
218
+ });
219
+ const getWalletQuoteFailedState = (message) => ({
220
+ quoteStatus: "failed",
221
+ quote: null,
222
+ quoteError: message,
223
+ });
224
+ const getWalletAttemptRefreshContext = () => {
225
+ const state = get();
226
+ const payment = state.payment;
227
+ const checkout = state.checkout;
228
+ const settlementCurrency = state.cryptoCurrency;
229
+ const selectedOption = state.walletPayment.options.find((option) => option.id === state.walletPayment.selectedOptionId);
230
+ const walletAddress = state.walletPayment.walletAddress;
231
+ if (!payment || !checkout || !settlementCurrency) {
232
+ throw new Error("Wallet payment context is not ready");
233
+ }
234
+ if (!selectedOption || !walletAddress) {
235
+ throw new Error("Missing wallet payment selection for quote refresh");
236
+ }
237
+ return {
238
+ payment,
239
+ checkout,
240
+ settlementCurrency,
241
+ selectedOption,
242
+ walletAddress,
243
+ };
244
+ };
245
+ const resolveRefreshedWalletQuote = async ({ selectedOption, checkout, payment, settlementCurrency, walletAddress, attempt, }) => {
246
+ if (selectedOption.kind === "direct") {
247
+ return buildDirectWalletQuote(selectedOption, attempt);
248
+ }
249
+ // Keep routed-quote loading behind a dynamic import so the checkout store
250
+ // does not eagerly pull the LI.FI integration path into manual-only flows.
251
+ const { fetchWalletPaymentQuote } = await import("../../integrations/index.js");
252
+ return fetchWalletPaymentQuote({
253
+ option: selectedOption,
254
+ context: {
255
+ checkout,
256
+ payment: get().payment ?? payment,
257
+ settlementCurrency,
258
+ walletAddress,
259
+ cryptoPaymentAttempt: attempt,
260
+ },
261
+ });
262
+ };
263
+ const refreshWalletPaymentAttempt = async () => {
264
+ const context = getWalletAttemptRefreshContext();
265
+ const attempt = await createWalletOptionPaymentAttempt(context.selectedOption, context.walletAddress, null);
266
+ const quote = await resolveRefreshedWalletQuote({
267
+ ...context,
268
+ attempt,
269
+ });
270
+ // Only the wallet-quote payload is set here; refreshQuote settles quote.status
271
+ // (ready + expiry timer) from the freshly created attempt once the rebuild ends.
272
+ setWalletPaymentState(getWalletQuoteReadyState(quote));
273
+ };
274
+ /**
275
+ * Settle the displayed quote state from the active attempt and arm a single
276
+ * expiry timer for a live quote. It never triggers a refresh — the caller
277
+ * decides what to do with a "stale" result — so it is safe to reuse mid-refresh
278
+ * without recursion.
279
+ */
280
+ const settleQuoteFromAttempt = (payment, attempt) => {
281
+ clearQuoteExpiryTimer();
282
+ if (refreshMode === "none" || !attempt || !canCreateFreshAttempt(payment)) {
283
+ setQuote({ status: "idle", error: null, ...clearQuoteTiming() });
284
+ return "idle";
285
+ }
286
+ if (isAttemptStale(attempt)) {
287
+ return "stale";
288
+ }
289
+ const timing = getAttemptQuoteTiming(attempt);
290
+ setQuote({ status: "ready", error: null, ...timing });
291
+ // One-shot timer: when the live quote crosses its window we refresh
292
+ // so the payer always sees a payable amount instead of an expiry dead-end.
293
+ const expiresAt = timing.expiresAt ?? getAttemptExpiry(attempt);
294
+ if (expiresAt !== null) {
295
+ quoteExpiryTimer = setTimeout(() => {
296
+ void refreshQuote();
297
+ }, Math.max(0, expiresAt - Date.now()));
298
+ quoteCountdownInterval = setInterval(() => {
299
+ refreshQuoteCountdown(expiresAt);
300
+ }, 1000);
301
+ }
302
+ return "ready";
303
+ };
304
+ /**
305
+ * Fetch a fresh payable amount for the active flow. Driven both by the silent
306
+ * expiry timer and by the payer's explicit "Try again" — a stale or missing
307
+ * quote is always recoverable, never terminal.
308
+ */
309
+ export const refreshQuote = async () => {
310
+ if (refreshMode === "none" || isRefreshing)
311
+ return;
312
+ if (refreshMode === "wallet" && !get().walletPayment.selectedOptionId) {
313
+ // Wallet refresh needs a chosen option to know which quote to rebuild, so
314
+ // skip ticks that land before the payer picked one (or after returning to
315
+ // the option list).
316
+ setQuote({ status: "idle", error: null, ...clearQuoteTiming() });
317
+ return;
318
+ }
319
+ if (!canCreateFreshAttempt(get().payment)) {
320
+ setQuote({
321
+ status: "failed",
322
+ error: PAYMENT_NO_LONGER_PAYABLE_MESSAGE,
323
+ ...clearQuoteTiming(),
324
+ });
325
+ return;
326
+ }
327
+ // Never refresh out from under an in-flight payment: the execution already
328
+ // captured the quote it is paying, so swapping the attempt would churn the UI
329
+ // and orphan an extra attempt. The view tears down the refresh context when it
330
+ // leaves the pay screen.
331
+ if (get().processing)
332
+ return;
333
+ isRefreshing = true;
334
+ clearQuoteExpiryTimer();
335
+ setQuote(getPreservedRefreshingQuoteState(), refreshMode === "wallet" ? getWalletQuoteLoadingState() : undefined);
336
+ try {
337
+ if (refreshMode === "wallet") {
338
+ await refreshWalletPaymentAttempt();
339
+ }
340
+ else {
341
+ // The replacement attempt must keep the refund recipient the payer bound
342
+ // to the expiring attempt: refund_to exists precisely for the expiry case,
343
+ // and an automatic refresh gives the payer no chance to re-enter it.
344
+ const currentAttempt = get().cryptoPaymentAttempt;
345
+ await createManualDirectPaymentAttempt("", 1, currentAttempt?.refund_to ?? null, currentAttempt?.payment_provider === "relay"
346
+ ? {
347
+ mode: "relay_deposit",
348
+ source: {
349
+ asset: currentAttempt.routing.source.token,
350
+ chain: currentAttempt.routing.source.chain,
351
+ },
352
+ }
353
+ : {});
354
+ }
355
+ }
356
+ catch (error) {
357
+ isRefreshing = false;
358
+ const message = error instanceof Error
359
+ ? error.message
360
+ : "Failed to refresh payment quote";
361
+ setQuote({ status: "failed", error: message, ...clearQuoteTiming() }, refreshMode === "wallet" ? getWalletQuoteFailedState(message) : undefined);
362
+ return;
363
+ }
364
+ isRefreshing = false;
365
+ if (settleQuoteFromAttempt(get().payment, get().cryptoPaymentAttempt) ===
366
+ "stale") {
367
+ setQuote({
368
+ status: "failed",
369
+ error: STALE_REPLACEMENT_QUOTE_MESSAGE,
370
+ ...clearQuoteTiming(),
371
+ });
372
+ }
373
+ };
374
+ /**
375
+ * Re-sync the quote lifecycle whenever the payment snapshot or active attempt
376
+ * changes. A fresh attempt arms the expiry refresh timer; a stale or missing
377
+ * one triggers an immediate refresh. This is the only entrypoint used
378
+ * after loading a payment, creating an attempt, or configuring a refresh mode.
379
+ */
380
+ export const syncQuote = (payment, attempt) => {
381
+ // A refresh in flight settles the final state itself; ignore the intermediate
382
+ // snapshot it emits while rebuilding the attempt.
383
+ if (isRefreshing)
384
+ return;
385
+ if (settleQuoteFromAttempt(payment, attempt ?? null) === "stale") {
386
+ void refreshQuote();
387
+ }
388
+ };
389
+ export const configureWalletQuoteRefresh = (walletAddress) => {
390
+ // Wallet refresh replaces a stale attempt by creating a fresh crypto payment
391
+ // attempt and reloading the wallet quote for the selected route.
392
+ refreshMode = "wallet";
393
+ set((state) => {
394
+ state.quote.error = null;
395
+ state.walletPayment.walletAddress = walletAddress;
396
+ });
397
+ syncQuote(get().payment, get().cryptoPaymentAttempt);
398
+ };
399
+ export const prepareWalletQuoteReplacement = (walletAddress = null) => {
400
+ // A payer-triggered wallet quote replacement is already fetching a new
401
+ // attempt/route, so pause only the automatic expiry refresh. Keep the
402
+ // countdown visible until the replacement quote is ready or fails.
403
+ refreshMode = "wallet";
404
+ clearQuoteAutoRefreshTimer();
405
+ set((state) => {
406
+ state.quote.error = null;
407
+ state.walletPayment.walletAddress =
408
+ walletAddress ?? state.walletPayment.walletAddress;
409
+ });
410
+ };
411
+ export const configureManualQuoteRefresh = () => {
412
+ // Manual refresh reuses the same lifecycle but only needs a fresh direct/relay
413
+ // address — no wallet quote metadata.
414
+ refreshMode = "manual";
415
+ set((state) => {
416
+ state.quote.error = null;
417
+ });
418
+ syncQuote(get().payment, get().cryptoPaymentAttempt);
419
+ };
420
+ export const clearQuoteRefresh = (options = {}) => {
421
+ // Drop the refresh mode before returning to method selection or closing the
422
+ // checkout so future expiry events do not reuse stale wallet/manual context.
423
+ refreshMode = "none";
424
+ isRefreshing = false;
425
+ clearQuoteExpiryTimer();
426
+ set((state) => {
427
+ state.quote = { status: "idle", error: null, ...clearQuoteTiming() };
428
+ if (!options.preserveWalletAddress) {
429
+ state.walletPayment.walletAddress = null;
430
+ }
431
+ });
432
+ };
433
+ const updatePaymentSnapshot = (payment, attempt, extra) => {
434
+ set((state) => {
435
+ state.payment = payment;
436
+ state.cryptoPaymentAttempt =
437
+ attempt !== undefined ? attempt : (payment?.payment_attempt ?? null);
438
+ if (extra) {
439
+ extra(state);
440
+ }
441
+ });
442
+ // Hydrate the current attempt from the payment snapshot so retry can resume
443
+ // the existing quote context and refresh it instead of restarting selection.
444
+ syncQuote(payment, get().cryptoPaymentAttempt);
445
+ };
70
446
  export const clearErrors = () => {
71
447
  set((state) => {
72
448
  Object.values(ACTIONS).forEach((action) => {
@@ -76,14 +452,10 @@ export const clearErrors = () => {
76
452
  };
77
453
  export const initialiseStore = async (payment) => {
78
454
  resetCheckoutStore();
79
- set((state) => {
80
- state.payment = payment;
81
- });
455
+ updatePaymentSnapshot(payment);
82
456
  try {
83
457
  const refreshedPayment = await getPaymentById(payment.id);
84
- set((state) => {
85
- state.payment = refreshedPayment;
86
- });
458
+ updatePaymentSnapshot(refreshedPayment);
87
459
  hydrateCheckoutFromPayment(refreshedPayment);
88
460
  }
89
461
  catch (err) {
@@ -101,6 +473,19 @@ option, sendingAddress, quote) => {
101
473
  if (!paymentId) {
102
474
  throw Error("Cannot create payment attempt without payment object.");
103
475
  }
476
+ if (!canCreateFreshAttempt(payment)) {
477
+ throw Error(PAYMENT_NO_LONGER_PAYABLE_MESSAGE);
478
+ }
479
+ if (option.kind === "direct") {
480
+ const reusableAttempt = getReusableCurrentAttemptForSource({
481
+ token: option.fromToken,
482
+ chain: option.fromChain,
483
+ sendingAddress,
484
+ });
485
+ if (reusableAttempt) {
486
+ return reuseCurrentAttempt(reusableAttempt);
487
+ }
488
+ }
104
489
  try {
105
490
  set((state) => {
106
491
  state.error[ACTIONS.CREATE_PAYMENT_ATTEMPT] = null;
@@ -113,8 +498,9 @@ option, sendingAddress, quote) => {
113
498
  requiredConfirmations: 1,
114
499
  });
115
500
  const attempt = await createPaymentAttempt(paymentId, attemptPayload, 1);
116
- set((state) => {
117
- state.cryptoPaymentAttempt = attempt;
501
+ const refreshedPayment = await getPaymentSnapshotAfterAttempt(paymentId, attempt, payment);
502
+ updatePaymentSnapshot(refreshedPayment, attempt, (state) => {
503
+ state.retrySession = false;
118
504
  state.error[ACTIONS.CREATE_PAYMENT_ATTEMPT] = null;
119
505
  state.loading[ACTIONS.CREATE_PAYMENT_ATTEMPT] = false;
120
506
  });
@@ -129,28 +515,50 @@ option, sendingAddress, quote) => {
129
515
  throw error;
130
516
  }
131
517
  };
132
- export const createManualDirectPaymentAttempt = async (sendingAddress = "", confirmations = 1) => {
518
+ export const createManualDirectPaymentAttempt = async (sendingAddress = "", confirmations = 1, refundTo, options = {}) => {
133
519
  const payment = useCheckoutStore.getState().payment;
134
520
  const paymentId = payment?.id;
135
521
  if (!paymentId) {
136
522
  throw Error("Cannot create payment attempt without payment object.");
137
523
  }
524
+ if (!canCreateFreshAttempt(payment)) {
525
+ throw Error(PAYMENT_NO_LONGER_PAYABLE_MESSAGE);
526
+ }
138
527
  const settlementConfig = getRequiredSettlementConfig(payment);
528
+ const source = options.source ?? {
529
+ asset: settlementConfig.asset,
530
+ chain: settlementConfig.chain,
531
+ };
532
+ const normalizedSendingAddress = sendingAddress.trim();
533
+ const effectiveRefundTo = refundTo?.trim() || normalizedSendingAddress || null;
139
534
  const attempt = await createPaymentAttempt(paymentId, {
140
- sendingAddress,
535
+ mode: options.mode,
536
+ ...(normalizedSendingAddress
537
+ ? { sendingAddress: normalizedSendingAddress }
538
+ : {}),
539
+ refund_to: effectiveRefundTo,
141
540
  required_confirmations: confirmations,
541
+ source: options.mode === "relay_deposit"
542
+ ? {
543
+ token: source.asset,
544
+ chain: source.chain,
545
+ }
546
+ : undefined,
142
547
  routing: {
143
- type: "direct",
548
+ type: source.chain !== settlementConfig.chain
549
+ ? "bridge"
550
+ : source.asset !== settlementConfig.asset
551
+ ? "swap"
552
+ : "direct",
144
553
  source: {
145
- token: settlementConfig.asset,
146
- chain: settlementConfig.chain,
554
+ token: source.asset,
555
+ chain: source.chain,
147
556
  },
148
557
  },
149
558
  });
150
- const refreshedPayment = await getPaymentById(paymentId);
151
- set((state) => {
152
- state.payment = refreshedPayment;
153
- state.cryptoPaymentAttempt = attempt;
559
+ const refreshedPayment = await getPaymentSnapshotAfterAttempt(paymentId, attempt, payment);
560
+ updatePaymentSnapshot(refreshedPayment, attempt, (state) => {
561
+ state.retrySession = false;
154
562
  });
155
563
  return attempt;
156
564
  };
@@ -170,9 +578,8 @@ export const createSuccessfulTestPaymentAttempt = async () => {
170
578
  }
171
579
  const attempt = await createTestPaymentAttempt(paymentId, "0xsuccess", currentPayment);
172
580
  const payment = await getPaymentById(paymentId);
173
- set((state) => {
174
- state.payment = payment;
175
- state.cryptoPaymentAttempt = attempt;
581
+ updatePaymentSnapshot(payment, attempt, (state) => {
582
+ state.retrySession = false;
176
583
  state.error[ACTIONS.CREATE_TEST_PAYMENT_ATTEMPT] = null;
177
584
  state.loading[ACTIONS.CREATE_TEST_PAYMENT_ATTEMPT] = false;
178
585
  });
@@ -202,9 +609,8 @@ export const createFailedTestPaymentAttempt = async () => {
202
609
  }
203
610
  const attempt = await createTestPaymentAttempt(paymentId, "0xfail", currentPayment);
204
611
  const payment = await getPaymentById(paymentId);
205
- set((state) => {
206
- state.payment = payment;
207
- state.cryptoPaymentAttempt = attempt;
612
+ updatePaymentSnapshot(payment, attempt, (state) => {
613
+ state.retrySession = false;
208
614
  state.error[ACTIONS.CREATE_TEST_PAYMENT_ATTEMPT] = null;
209
615
  state.loading[ACTIONS.CREATE_TEST_PAYMENT_ATTEMPT] = false;
210
616
  });
@@ -301,8 +707,8 @@ export const getPayment = async () => {
301
707
  try {
302
708
  const resp = await getPaymentById(payment.id);
303
709
  if (resp) {
710
+ updatePaymentSnapshot(resp);
304
711
  set((state) => {
305
- state.payment = resp;
306
712
  state.loading[ACTION] = false;
307
713
  state.error[ACTION] = null;
308
714
  });
@@ -328,7 +734,6 @@ export const getPayment = async () => {
328
734
  export const executeTransfer = async (wallet) => {
329
735
  const ACTION = ACTIONS.EXECUTE_TRANSFER;
330
736
  const state = get();
331
- console.log("[Execute Transfer] State:", state);
332
737
  if (!state.cryptoPaymentAttempt) {
333
738
  throw new Error("Missing required data for payment execution");
334
739
  }
@@ -337,6 +742,8 @@ export const executeTransfer = async (wallet) => {
337
742
  state.error[ACTION] = null;
338
743
  state.transfer.status = "pending";
339
744
  state.transfer.error = null;
745
+ state.transfer.transactionHash = null;
746
+ state.transfer.chainStatus = "pending";
340
747
  });
341
748
  try {
342
749
  const settlementChainHex = state.cryptoPaymentAttempt.settlement_config.chain_hex;
@@ -354,7 +761,7 @@ export const executeTransfer = async (wallet) => {
354
761
  const transfer = {
355
762
  sendingAddress: address,
356
763
  destinationAddress: state.cryptoPaymentAttempt.destination_address,
357
- amount: Number(state.cryptoPaymentAttempt.amount),
764
+ amount: state.cryptoPaymentAttempt.amount,
358
765
  evm: {
359
766
  implementationAddress: state.cryptoPaymentAttempt.settlement_token_address,
360
767
  assetName: state.cryptoPaymentAttempt.settlement_config.asset_name,
@@ -380,7 +787,7 @@ export const executeTransfer = async (wallet) => {
380
787
  state.loading[ACTION] = false;
381
788
  state.error[ACTION] = errorMessage;
382
789
  });
383
- throw error;
790
+ throw error instanceof Error ? error : new Error(errorMessage);
384
791
  }
385
792
  };
386
793
  export const checkChainStatus = async (wallet) => {
@@ -391,22 +798,28 @@ export const checkChainStatus = async (wallet) => {
391
798
  }
392
799
  // Check if the wallet is a WagmiWalletInterface
393
800
  if (!(wallet instanceof WagmiWalletInterface)) {
394
- console.error("Wallet does not support chain status checks");
801
+ const error = new Error("Wallet does not support chain status checks");
802
+ console.error(error.message);
395
803
  set((state) => {
804
+ state.transfer.status = "failed";
805
+ state.transfer.error = error.message;
396
806
  state.transfer.chainStatus = "failed";
397
- state.error[ACTION] = "Wallet does not support chain status checks";
807
+ state.error[ACTION] = error.message;
398
808
  });
399
- return;
809
+ throw error;
400
810
  }
401
811
  set((state) => {
402
812
  state.loading[ACTION] = true;
403
813
  state.error[ACTION] = null;
404
814
  });
405
815
  try {
406
- await waitForTransactionReceipt(wallet.wagmiConfig, {
816
+ const receipt = await waitForTransactionReceipt(wallet.wagmiConfig, {
407
817
  hash: state.transfer.transactionHash,
408
818
  confirmations: 1,
409
819
  });
820
+ if (receipt.status === "reverted") {
821
+ throw new Error("Transaction reverted before confirmation");
822
+ }
410
823
  set((state) => {
411
824
  state.transfer.chainStatus = "confirmed";
412
825
  state.loading[ACTION] = false;
@@ -415,12 +828,15 @@ export const checkChainStatus = async (wallet) => {
415
828
  }
416
829
  catch (error) {
417
830
  console.error("Error checking transaction status:", error);
831
+ const errorMessage = error instanceof Error ? error.message : "Failed to check chain status";
418
832
  set((state) => {
833
+ state.transfer.status = "failed";
834
+ state.transfer.error = errorMessage;
419
835
  state.transfer.chainStatus = "failed";
420
836
  state.loading[ACTION] = false;
421
- state.error[ACTION] =
422
- error instanceof Error ? error.message : "Failed to check chain status";
837
+ state.error[ACTION] = errorMessage;
423
838
  });
839
+ throw error instanceof Error ? error : new Error(errorMessage);
424
840
  }
425
841
  };
426
842
  export const resetTransfer = () => {
@@ -433,25 +849,6 @@ export const resetTransfer = () => {
433
849
  };
434
850
  });
435
851
  };
436
- export const executeConnectedWalletPayment = async (wallet) => {
437
- await executeTransfer(wallet);
438
- void checkChainStatus(wallet);
439
- await waitForTransferSuccess();
440
- };
441
- function waitForTransferSuccess() {
442
- return new Promise((resolve, reject) => {
443
- const unsubscribe = useCheckoutStore.subscribe((state) => {
444
- if (state.transfer.chainStatus === "confirmed") {
445
- unsubscribe();
446
- resolve();
447
- }
448
- else if (state.transfer.chainStatus === "failed") {
449
- unsubscribe();
450
- reject(new Error(state.transfer.error || "Transaction failed on chain"));
451
- }
452
- });
453
- });
454
- }
455
852
  export const startPaymentPolling = (onPaymentStatusChange, confirmationStatus = PaymentStatus.PAID) => {
456
853
  const ACTION = ACTIONS.POLL_PAYMENT;
457
854
  const POLL_INTERVAL = 5000;
@@ -464,14 +861,11 @@ export const startPaymentPolling = (onPaymentStatusChange, confirmationStatus =
464
861
  state.polling.pollCount++;
465
862
  state.polling.lastPollTime = Date.now();
466
863
  });
467
- console.log(`[Payment Poll] Starting poll attempt #${state.polling.pollCount}`);
468
864
  try {
469
865
  const updatedPayment = await getPayment();
470
866
  if (!updatedPayment) {
471
- console.log(`[Payment Poll] No payment data, skipping poll #${state.polling.pollCount}`);
472
867
  return;
473
868
  }
474
- console.log(`[Payment Poll] Payment status: ${updatedPayment.status} (poll #${state.polling.pollCount})`);
475
869
  const successStatuses = confirmationStatus === PaymentStatus.PAID
476
870
  ? [PaymentStatus.PAID]
477
871
  : [confirmationStatus, PaymentStatus.PAID];
@@ -518,17 +912,28 @@ export const stopPaymentPolling = () => {
518
912
  });
519
913
  };
520
914
  export const resetCheckoutStore = () => {
915
+ refreshMode = "none";
916
+ isRefreshing = false;
917
+ clearQuoteExpiryTimer();
521
918
  set((state) => {
522
919
  Object.assign(state, {
523
920
  amount: null,
524
921
  checkoutId: null,
525
922
  selectedMethod: null,
526
923
  selectedCurrency: null,
924
+ retrySession: false,
527
925
  methods: null,
528
926
  cryptoCurrency: null,
529
927
  checkout: null,
530
928
  payment: null,
531
929
  cryptoPaymentAttempt: null,
930
+ quote: {
931
+ status: "idle",
932
+ error: null,
933
+ expiresAt: null,
934
+ remainingMs: null,
935
+ totalDurationMs: null,
936
+ },
532
937
  loading: initialActionState(false),
533
938
  error: initialActionState(null),
534
939
  transfer: {
@@ -546,6 +951,54 @@ export const resetCheckoutStore = () => {
546
951
  });
547
952
  });
548
953
  };
954
+ export const resetCheckoutSessionForRetry = () => {
955
+ refreshMode = "none";
956
+ isRefreshing = false;
957
+ clearQuoteExpiryTimer();
958
+ set((state) => {
959
+ // Retry keeps the same payment intent but discards all attempt-scoped UI
960
+ // state so the payer can choose a fresh route. The payment object itself is
961
+ // preserved elsewhere in the store; this reset only clears execution state
962
+ // that was tied to the previous attempt.
963
+ state.selectedMethod = null;
964
+ state.selectedCurrency = null;
965
+ state.retrySession = true;
966
+ state.cryptoPaymentAttempt = null;
967
+ state.fiatPaymentAttempt = null;
968
+ state.processing = false;
969
+ state.transfer = {
970
+ status: "idle",
971
+ error: null,
972
+ transactionHash: null,
973
+ chainStatus: "pending",
974
+ };
975
+ state.polling = {
976
+ isPolling: false,
977
+ pollCount: 0,
978
+ lastPollTime: null,
979
+ };
980
+ state.walletPayment = initialWalletPaymentState();
981
+ state.quote = {
982
+ status: "idle",
983
+ error: null,
984
+ expiresAt: null,
985
+ remainingMs: null,
986
+ totalDurationMs: null,
987
+ };
988
+ state.error[ACTIONS.CREATE_PAYMENT_ATTEMPT] = null;
989
+ state.error[ACTIONS.CREATE_FIAT_PAYMENT_ATTEMPT] = null;
990
+ state.error[ACTIONS.CREATE_TEST_PAYMENT_ATTEMPT] = null;
991
+ state.error[ACTIONS.EXECUTE_TRANSFER] = null;
992
+ state.error[ACTIONS.POLL_PAYMENT] = null;
993
+ state.error[ACTIONS.CHECK_CHAIN_STATUS] = null;
994
+ state.loading[ACTIONS.CREATE_PAYMENT_ATTEMPT] = false;
995
+ state.loading[ACTIONS.CREATE_FIAT_PAYMENT_ATTEMPT] = false;
996
+ state.loading[ACTIONS.CREATE_TEST_PAYMENT_ATTEMPT] = false;
997
+ state.loading[ACTIONS.EXECUTE_TRANSFER] = false;
998
+ state.loading[ACTIONS.POLL_PAYMENT] = false;
999
+ state.loading[ACTIONS.CHECK_CHAIN_STATUS] = false;
1000
+ });
1001
+ };
549
1002
  export const setCheckoutMethod = (method) => {
550
1003
  set((state) => {
551
1004
  state.selectedMethod = method;