@mintmoney/react 0.1.0-alpha.32 → 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 (158) 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 +22 -18
  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 +941 -102
  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 +684 -226
  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 +1 -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/wallet-selector/component.js +3 -5
  59. package/dist/esm/components/wallet-selector/component.js.map +1 -1
  60. package/dist/esm/components/wallet-selector/wallets/wagmi/index.js.map +1 -1
  61. package/dist/esm/config.js.map +1 -1
  62. package/dist/esm/index.js +2 -1
  63. package/dist/esm/index.js.map +1 -1
  64. package/dist/esm/integrations/lifi.js +52 -34
  65. package/dist/esm/integrations/lifi.js.map +1 -1
  66. package/dist/esm/refund/index.js +791 -0
  67. package/dist/esm/refund/index.js.map +1 -0
  68. package/dist/esm/state/checkout/payment-attempt.js +3 -0
  69. package/dist/esm/state/checkout/payment-attempt.js.map +1 -1
  70. package/dist/esm/state/checkout/payment-lifecycle.js +43 -35
  71. package/dist/esm/state/checkout/payment-lifecycle.js.map +1 -1
  72. package/dist/esm/state/checkout/store.js +318 -198
  73. package/dist/esm/state/checkout/store.js.map +1 -1
  74. package/dist/esm/state/checkout/wallet-payment-options.js +30 -0
  75. package/dist/esm/state/checkout/wallet-payment-options.js.map +1 -0
  76. package/dist/esm/themes/default.js +6 -0
  77. package/dist/esm/themes/default.js.map +1 -1
  78. package/dist/esm/utils/string.js +1 -0
  79. package/dist/esm/utils/string.js.map +1 -1
  80. package/dist/esm/utils/wallet-errors.js +15 -0
  81. package/dist/esm/utils/wallet-errors.js.map +1 -0
  82. package/dist/types/api/generated.d.ts +207 -4
  83. package/dist/types/api/generated.d.ts.map +1 -1
  84. package/dist/types/api/index.d.ts +2 -1
  85. package/dist/types/api/index.d.ts.map +1 -1
  86. package/dist/types/api/payments.d.ts +36 -1
  87. package/dist/types/api/payments.d.ts.map +1 -1
  88. package/dist/types/api/types.d.ts +4 -0
  89. package/dist/types/api/types.d.ts.map +1 -1
  90. package/dist/types/checkout/index.d.ts +4 -1
  91. package/dist/types/checkout/index.d.ts.map +1 -1
  92. package/dist/types/checkout/modal.d.ts.map +1 -1
  93. package/dist/types/checkout/providers/wagmi-config.d.ts +12 -0
  94. package/dist/types/checkout/providers/wagmi-config.d.ts.map +1 -0
  95. package/dist/types/checkout/surplus-refund.d.ts +10 -0
  96. package/dist/types/checkout/surplus-refund.d.ts.map +1 -0
  97. package/dist/types/checkout/views/back.d.ts +2 -1
  98. package/dist/types/checkout/views/back.d.ts.map +1 -1
  99. package/dist/types/checkout/views/crypto-intent/direct-details.d.ts +10 -1
  100. package/dist/types/checkout/views/crypto-intent/direct-details.d.ts.map +1 -1
  101. package/dist/types/checkout/views/crypto-intent/methods.d.ts.map +1 -1
  102. package/dist/types/checkout/views/crypto-intent/processing.d.ts.map +1 -1
  103. package/dist/types/checkout/views/crypto-intent/success.d.ts.map +1 -1
  104. package/dist/types/checkout/views/crypto-intent/wallet-payment-options.d.ts.map +1 -1
  105. package/dist/types/checkout/views/crypto-intent/wallet-select.d.ts.map +1 -1
  106. package/dist/types/checkout/views/failed.d.ts.map +1 -1
  107. package/dist/types/checkout/views/initial.d.ts +2 -0
  108. package/dist/types/checkout/views/initial.d.ts.map +1 -1
  109. package/dist/types/checkout/views/method-select.d.ts +2 -0
  110. package/dist/types/checkout/views/method-select.d.ts.map +1 -1
  111. package/dist/types/components/buttons/index.d.ts.map +1 -1
  112. package/dist/types/components/icons/clock.d.ts +6 -0
  113. package/dist/types/components/icons/clock.d.ts.map +1 -0
  114. package/dist/types/components/icons/edit.d.ts +6 -0
  115. package/dist/types/components/icons/edit.d.ts.map +1 -0
  116. package/dist/types/components/icons/index.d.ts +3 -0
  117. package/dist/types/components/icons/index.d.ts.map +1 -1
  118. package/dist/types/components/icons/send.d.ts +6 -0
  119. package/dist/types/components/icons/send.d.ts.map +1 -0
  120. package/dist/types/components/index.d.ts +1 -0
  121. package/dist/types/components/index.d.ts.map +1 -1
  122. package/dist/types/components/quote-expiry/index.d.ts +2 -0
  123. package/dist/types/components/quote-expiry/index.d.ts.map +1 -0
  124. package/dist/types/components/quote-expiry/quote-expiry-countdown.d.ts +15 -0
  125. package/dist/types/components/quote-expiry/quote-expiry-countdown.d.ts.map +1 -0
  126. package/dist/types/components/quote-expiry/styles.d.ts +22 -0
  127. package/dist/types/components/quote-expiry/styles.d.ts.map +1 -0
  128. package/dist/types/components/quote-expiry/tiers.d.ts +10 -0
  129. package/dist/types/components/quote-expiry/tiers.d.ts.map +1 -0
  130. package/dist/types/components/wallet-selector/component.d.ts +1 -2
  131. package/dist/types/components/wallet-selector/component.d.ts.map +1 -1
  132. package/dist/types/components/wallet-selector/domain.d.ts +3 -2
  133. package/dist/types/components/wallet-selector/domain.d.ts.map +1 -1
  134. package/dist/types/components/wallet-selector/wallets/wagmi/index.d.ts +41 -5
  135. package/dist/types/components/wallet-selector/wallets/wagmi/index.d.ts.map +1 -1
  136. package/dist/types/config.d.ts +3 -0
  137. package/dist/types/config.d.ts.map +1 -1
  138. package/dist/types/index.d.ts +2 -1
  139. package/dist/types/index.d.ts.map +1 -1
  140. package/dist/types/integrations/lifi.d.ts.map +1 -1
  141. package/dist/types/refund/index.d.ts +82 -0
  142. package/dist/types/refund/index.d.ts.map +1 -0
  143. package/dist/types/state/checkout/payment-attempt.d.ts.map +1 -1
  144. package/dist/types/state/checkout/payment-lifecycle.d.ts +27 -10
  145. package/dist/types/state/checkout/payment-lifecycle.d.ts.map +1 -1
  146. package/dist/types/state/checkout/store.d.ts +35 -16
  147. package/dist/types/state/checkout/store.d.ts.map +1 -1
  148. package/dist/types/state/checkout/wallet-payment-options.d.ts +18 -0
  149. package/dist/types/state/checkout/wallet-payment-options.d.ts.map +1 -0
  150. package/dist/types/themes/default.d.ts.map +1 -1
  151. package/dist/types/themes/types.d.ts +11 -0
  152. package/dist/types/themes/types.d.ts.map +1 -1
  153. package/dist/types/utils/string.d.ts +1 -0
  154. package/dist/types/utils/string.d.ts.map +1 -1
  155. package/dist/types/utils/wallet-errors.d.ts +2 -0
  156. package/dist/types/utils/wallet-errors.d.ts.map +1 -0
  157. package/package.json +25 -18
  158. package/LICENSE +0 -21
@@ -7,7 +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, getAttemptFreshnessStatus, } from "./payment-lifecycle.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.";
11
13
  export var ACTIONS;
12
14
  (function (ACTIONS) {
13
15
  ACTIONS["GET_CHECKOUT_CONFIG"] = "GET_CHECKOUT_CONFIG";
@@ -64,15 +66,12 @@ export const useCheckoutStore = create()(immer((_set, _get) => ({
64
66
  pollCount: 0,
65
67
  lastPollTime: null,
66
68
  },
67
- attemptFreshness: {
69
+ quote: {
68
70
  status: "idle",
71
+ error: null,
69
72
  expiresAt: null,
70
73
  remainingMs: null,
71
- },
72
- attemptRefresh: {
73
- mode: "none",
74
- status: "idle",
75
- error: null,
74
+ totalDurationMs: null,
76
75
  },
77
76
  walletPayment: initialWalletPaymentState(),
78
77
  })));
@@ -80,16 +79,94 @@ const set = (fn) => {
80
79
  useCheckoutStore.setState(fn);
81
80
  };
82
81
  const get = () => useCheckoutStore.getState();
83
- let attemptFreshnessTimer = null;
84
- let attemptFreshnessInterval = null;
85
- const clearAttemptFreshnessTimer = () => {
86
- if (attemptFreshnessTimer) {
87
- clearTimeout(attemptFreshnessTimer);
88
- attemptFreshnessTimer = null;
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;
89
158
  }
90
- if (attemptFreshnessInterval) {
91
- clearInterval(attemptFreshnessInterval);
92
- attemptFreshnessInterval = null;
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);
93
170
  }
94
171
  };
95
172
  const buildDirectWalletQuote = (option, attempt) => {
@@ -105,14 +182,26 @@ const buildDirectWalletQuote = (option, attempt) => {
105
182
  estimatedDurationMinutes: 1,
106
183
  };
107
184
  };
108
- const setAttemptRefreshState = (update, walletUpdate) => {
185
+ const setQuote = (update, walletUpdate) => {
109
186
  set((state) => {
110
- Object.assign(state.attemptRefresh, update);
187
+ Object.assign(state.quote, update);
111
188
  if (walletUpdate) {
112
189
  Object.assign(state.walletPayment, walletUpdate);
113
190
  }
114
191
  });
115
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
+ };
116
205
  const getWalletQuoteLoadingState = () => ({
117
206
  quoteStatus: "loading",
118
207
  quote: null,
@@ -132,27 +221,6 @@ const getWalletQuoteFailedState = (message) => ({
132
221
  quote: null,
133
222
  quoteError: message,
134
223
  });
135
- const beginAttemptRefresh = (walletUpdate) => {
136
- setAttemptRefreshState({
137
- status: "refreshing",
138
- error: null,
139
- }, walletUpdate);
140
- };
141
- const finishAttemptRefresh = (walletUpdate) => {
142
- setAttemptRefreshState({
143
- status: "idle",
144
- error: null,
145
- }, walletUpdate);
146
- };
147
- const failAttemptRefresh = (message) => {
148
- const { attemptRefresh } = get();
149
- setAttemptRefreshState({
150
- status: "failed",
151
- error: message,
152
- }, attemptRefresh.mode === "wallet"
153
- ? getWalletQuoteFailedState(message)
154
- : undefined);
155
- };
156
224
  const getWalletAttemptRefreshContext = () => {
157
225
  const state = get();
158
226
  const payment = state.payment;
@@ -194,149 +262,186 @@ const resolveRefreshedWalletQuote = async ({ selectedOption, checkout, payment,
194
262
  };
195
263
  const refreshWalletPaymentAttempt = async () => {
196
264
  const context = getWalletAttemptRefreshContext();
197
- beginAttemptRefresh(getWalletQuoteLoadingState());
198
265
  const attempt = await createWalletOptionPaymentAttempt(context.selectedOption, context.walletAddress, null);
199
266
  const quote = await resolveRefreshedWalletQuote({
200
267
  ...context,
201
268
  attempt,
202
269
  });
203
- finishAttemptRefresh(getWalletQuoteReadyState(quote));
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));
204
273
  };
205
- const refreshCurrentAttempt = async () => {
206
- const state = get();
207
- if (state.attemptRefresh.status === "refreshing") {
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() });
208
317
  return;
209
318
  }
210
- if (!canCreateFreshAttempt(state.payment)) {
319
+ if (!canCreateFreshAttempt(get().payment)) {
320
+ setQuote({
321
+ status: "failed",
322
+ error: PAYMENT_NO_LONGER_PAYABLE_MESSAGE,
323
+ ...clearQuoteTiming(),
324
+ });
211
325
  return;
212
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);
213
336
  try {
214
- if (state.attemptRefresh.mode === "wallet") {
337
+ if (refreshMode === "wallet") {
215
338
  await refreshWalletPaymentAttempt();
216
- return;
217
339
  }
218
- if (state.attemptRefresh.mode === "manual") {
219
- beginAttemptRefresh();
220
- await createManualDirectPaymentAttempt();
221
- finishAttemptRefresh();
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
+ : {});
222
354
  }
223
355
  }
224
356
  catch (error) {
357
+ isRefreshing = false;
225
358
  const message = error instanceof Error
226
359
  ? error.message
227
360
  : "Failed to refresh payment quote";
228
- failAttemptRefresh(message);
229
- }
230
- };
231
- const scheduleAttemptFreshness = (payment, attempt) => {
232
- clearAttemptFreshnessTimer();
233
- const freshness = getAttemptFreshnessStatus(payment, attempt ?? null);
234
- set((state) => {
235
- state.attemptFreshness = freshness;
236
- });
237
- if (freshness.status !== "fresh" || !freshness.expiresAt) {
361
+ setQuote({ status: "failed", error: message, ...clearQuoteTiming() }, refreshMode === "wallet" ? getWalletQuoteFailedState(message) : undefined);
238
362
  return;
239
363
  }
240
- // The one-shot timer is the authoritative expiry transition. When the
241
- // current attempt crosses its `expires_at`, we recompute freshness against the
242
- // latest payment snapshot and kick off a single refresh if the attempt is now
243
- // stale.
244
- const delay = Math.max(0, freshness.expiresAt - Date.now());
245
- attemptFreshnessTimer = setTimeout(() => {
246
- const state = get();
247
- const currentAttempt = state.cryptoPaymentAttempt ?? state.payment?.payment_attempt;
248
- const currentFreshness = getAttemptFreshnessStatus(state.payment, currentAttempt);
249
- set((draft) => {
250
- draft.attemptFreshness = currentFreshness;
251
- });
252
- if (currentFreshness.status === "stale") {
253
- void refreshCurrentAttempt();
254
- }
255
- }, delay);
256
- // The interval is only for UI countdown updates while an attempt is still
257
- // fresh. It keeps `remainingMs` moving without waiting for the expiry timer to
258
- // fire, and stops itself once the attempt is no longer usable.
259
- attemptFreshnessInterval = setInterval(() => {
260
- const currentState = get();
261
- const currentAttempt = currentState.cryptoPaymentAttempt ??
262
- currentState.payment?.payment_attempt;
263
- const currentFreshness = getAttemptFreshnessStatus(currentState.payment, currentAttempt);
264
- if (currentFreshness.status !== "fresh" || !currentFreshness.expiresAt) {
265
- clearAttemptFreshnessTimer();
266
- set((state) => {
267
- state.attemptFreshness = {
268
- status: currentFreshness.status,
269
- expiresAt: currentFreshness.expiresAt,
270
- remainingMs: currentFreshness.expiresAt !== null
271
- ? 0
272
- : currentFreshness.remainingMs,
273
- };
274
- });
275
- return;
276
- }
277
- set((state) => {
278
- state.attemptFreshness = {
279
- ...currentFreshness,
280
- remainingMs: currentFreshness.remainingMs,
281
- };
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(),
282
371
  });
283
- }, 1000);
372
+ }
284
373
  };
285
- export const syncCheckoutAttemptFreshness = (payment, attempt) => {
286
- // Re-sync the freshness timers whenever the payment snapshot or active
287
- // attempt changes. This is the single entrypoint used after loading a
288
- // payment, creating a fresh attempt, or resetting session state.
289
- scheduleAttemptFreshness(payment, attempt);
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
+ }
290
388
  };
291
- export const configureWalletAttemptRefresh = (walletAddress) => {
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";
292
393
  set((state) => {
293
- // Wallet refresh mode means stale attempts should be replaced by creating a
294
- // fresh crypto payment attempt and reloading wallet quote state for the
295
- // currently selected wallet route.
296
- state.attemptRefresh.mode = "wallet";
297
- state.attemptRefresh.error = null;
298
- if (state.attemptRefresh.status !== "refreshing") {
299
- state.attemptRefresh.status = "idle";
300
- }
394
+ state.quote.error = null;
301
395
  state.walletPayment.walletAddress = walletAddress;
302
396
  });
397
+ syncQuote(get().payment, get().cryptoPaymentAttempt);
303
398
  };
304
- export const configureManualAttemptRefresh = () => {
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();
305
405
  set((state) => {
306
- // Manual refresh mode reuses the same stale-attempt lifecycle, but the
307
- // refresh path only needs a new direct/manual attempt and not any wallet
308
- // quote metadata.
309
- state.attemptRefresh.mode = "manual";
310
- state.attemptRefresh.error = null;
311
- if (state.attemptRefresh.status !== "refreshing") {
312
- state.attemptRefresh.status = "idle";
313
- }
406
+ state.quote.error = null;
407
+ state.walletPayment.walletAddress =
408
+ walletAddress ?? state.walletPayment.walletAddress;
314
409
  });
315
410
  };
316
- export const clearAttemptRefreshContext = () => {
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";
317
415
  set((state) => {
318
- // Clear any stale refresh mode before returning to method selection or
319
- // closing the checkout so future expiry events do not try to reuse old
320
- // wallet/manual context.
321
- state.attemptRefresh = {
322
- mode: "none",
323
- status: "idle",
324
- error: null,
325
- };
326
- state.walletPayment.walletAddress = null;
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
+ }
327
431
  });
328
432
  };
329
433
  const updatePaymentSnapshot = (payment, attempt, extra) => {
330
434
  set((state) => {
331
435
  state.payment = payment;
332
- if (attempt !== undefined) {
333
- state.cryptoPaymentAttempt = attempt;
334
- }
436
+ state.cryptoPaymentAttempt =
437
+ attempt !== undefined ? attempt : (payment?.payment_attempt ?? null);
335
438
  if (extra) {
336
439
  extra(state);
337
440
  }
338
441
  });
339
- syncCheckoutAttemptFreshness(payment, attempt ?? payment?.payment_attempt);
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);
340
445
  };
341
446
  export const clearErrors = () => {
342
447
  set((state) => {
@@ -369,7 +474,17 @@ option, sendingAddress, quote) => {
369
474
  throw Error("Cannot create payment attempt without payment object.");
370
475
  }
371
476
  if (!canCreateFreshAttempt(payment)) {
372
- throw Error("This payment is no longer payable.");
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
+ }
373
488
  }
374
489
  try {
375
490
  set((state) => {
@@ -383,11 +498,9 @@ option, sendingAddress, quote) => {
383
498
  requiredConfirmations: 1,
384
499
  });
385
500
  const attempt = await createPaymentAttempt(paymentId, attemptPayload, 1);
386
- const refreshedPayment = await getPaymentById(paymentId);
501
+ const refreshedPayment = await getPaymentSnapshotAfterAttempt(paymentId, attempt, payment);
387
502
  updatePaymentSnapshot(refreshedPayment, attempt, (state) => {
388
503
  state.retrySession = false;
389
- state.attemptRefresh.status = "idle";
390
- state.attemptRefresh.error = null;
391
504
  state.error[ACTIONS.CREATE_PAYMENT_ATTEMPT] = null;
392
505
  state.loading[ACTIONS.CREATE_PAYMENT_ATTEMPT] = false;
393
506
  });
@@ -402,29 +515,50 @@ option, sendingAddress, quote) => {
402
515
  throw error;
403
516
  }
404
517
  };
405
- export const createManualDirectPaymentAttempt = async (sendingAddress = "", confirmations = 1) => {
518
+ export const createManualDirectPaymentAttempt = async (sendingAddress = "", confirmations = 1, refundTo, options = {}) => {
406
519
  const payment = useCheckoutStore.getState().payment;
407
520
  const paymentId = payment?.id;
408
521
  if (!paymentId) {
409
522
  throw Error("Cannot create payment attempt without payment object.");
410
523
  }
524
+ if (!canCreateFreshAttempt(payment)) {
525
+ throw Error(PAYMENT_NO_LONGER_PAYABLE_MESSAGE);
526
+ }
411
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;
412
534
  const attempt = await createPaymentAttempt(paymentId, {
413
- sendingAddress,
535
+ mode: options.mode,
536
+ ...(normalizedSendingAddress
537
+ ? { sendingAddress: normalizedSendingAddress }
538
+ : {}),
539
+ refund_to: effectiveRefundTo,
414
540
  required_confirmations: confirmations,
541
+ source: options.mode === "relay_deposit"
542
+ ? {
543
+ token: source.asset,
544
+ chain: source.chain,
545
+ }
546
+ : undefined,
415
547
  routing: {
416
- type: "direct",
548
+ type: source.chain !== settlementConfig.chain
549
+ ? "bridge"
550
+ : source.asset !== settlementConfig.asset
551
+ ? "swap"
552
+ : "direct",
417
553
  source: {
418
- token: settlementConfig.asset,
419
- chain: settlementConfig.chain,
554
+ token: source.asset,
555
+ chain: source.chain,
420
556
  },
421
557
  },
422
558
  });
423
- const refreshedPayment = await getPaymentById(paymentId);
559
+ const refreshedPayment = await getPaymentSnapshotAfterAttempt(paymentId, attempt, payment);
424
560
  updatePaymentSnapshot(refreshedPayment, attempt, (state) => {
425
561
  state.retrySession = false;
426
- state.attemptRefresh.status = "idle";
427
- state.attemptRefresh.error = null;
428
562
  });
429
563
  return attempt;
430
564
  };
@@ -600,7 +734,6 @@ export const getPayment = async () => {
600
734
  export const executeTransfer = async (wallet) => {
601
735
  const ACTION = ACTIONS.EXECUTE_TRANSFER;
602
736
  const state = get();
603
- console.log("[Execute Transfer] State:", state);
604
737
  if (!state.cryptoPaymentAttempt) {
605
738
  throw new Error("Missing required data for payment execution");
606
739
  }
@@ -609,6 +742,8 @@ export const executeTransfer = async (wallet) => {
609
742
  state.error[ACTION] = null;
610
743
  state.transfer.status = "pending";
611
744
  state.transfer.error = null;
745
+ state.transfer.transactionHash = null;
746
+ state.transfer.chainStatus = "pending";
612
747
  });
613
748
  try {
614
749
  const settlementChainHex = state.cryptoPaymentAttempt.settlement_config.chain_hex;
@@ -626,7 +761,7 @@ export const executeTransfer = async (wallet) => {
626
761
  const transfer = {
627
762
  sendingAddress: address,
628
763
  destinationAddress: state.cryptoPaymentAttempt.destination_address,
629
- amount: Number(state.cryptoPaymentAttempt.amount),
764
+ amount: state.cryptoPaymentAttempt.amount,
630
765
  evm: {
631
766
  implementationAddress: state.cryptoPaymentAttempt.settlement_token_address,
632
767
  assetName: state.cryptoPaymentAttempt.settlement_config.asset_name,
@@ -652,7 +787,7 @@ export const executeTransfer = async (wallet) => {
652
787
  state.loading[ACTION] = false;
653
788
  state.error[ACTION] = errorMessage;
654
789
  });
655
- throw error;
790
+ throw error instanceof Error ? error : new Error(errorMessage);
656
791
  }
657
792
  };
658
793
  export const checkChainStatus = async (wallet) => {
@@ -663,22 +798,28 @@ export const checkChainStatus = async (wallet) => {
663
798
  }
664
799
  // Check if the wallet is a WagmiWalletInterface
665
800
  if (!(wallet instanceof WagmiWalletInterface)) {
666
- 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);
667
803
  set((state) => {
804
+ state.transfer.status = "failed";
805
+ state.transfer.error = error.message;
668
806
  state.transfer.chainStatus = "failed";
669
- state.error[ACTION] = "Wallet does not support chain status checks";
807
+ state.error[ACTION] = error.message;
670
808
  });
671
- return;
809
+ throw error;
672
810
  }
673
811
  set((state) => {
674
812
  state.loading[ACTION] = true;
675
813
  state.error[ACTION] = null;
676
814
  });
677
815
  try {
678
- await waitForTransactionReceipt(wallet.wagmiConfig, {
816
+ const receipt = await waitForTransactionReceipt(wallet.wagmiConfig, {
679
817
  hash: state.transfer.transactionHash,
680
818
  confirmations: 1,
681
819
  });
820
+ if (receipt.status === "reverted") {
821
+ throw new Error("Transaction reverted before confirmation");
822
+ }
682
823
  set((state) => {
683
824
  state.transfer.chainStatus = "confirmed";
684
825
  state.loading[ACTION] = false;
@@ -687,12 +828,15 @@ export const checkChainStatus = async (wallet) => {
687
828
  }
688
829
  catch (error) {
689
830
  console.error("Error checking transaction status:", error);
831
+ const errorMessage = error instanceof Error ? error.message : "Failed to check chain status";
690
832
  set((state) => {
833
+ state.transfer.status = "failed";
834
+ state.transfer.error = errorMessage;
691
835
  state.transfer.chainStatus = "failed";
692
836
  state.loading[ACTION] = false;
693
- state.error[ACTION] =
694
- error instanceof Error ? error.message : "Failed to check chain status";
837
+ state.error[ACTION] = errorMessage;
695
838
  });
839
+ throw error instanceof Error ? error : new Error(errorMessage);
696
840
  }
697
841
  };
698
842
  export const resetTransfer = () => {
@@ -705,25 +849,6 @@ export const resetTransfer = () => {
705
849
  };
706
850
  });
707
851
  };
708
- export const executeConnectedWalletPayment = async (wallet) => {
709
- await executeTransfer(wallet);
710
- void checkChainStatus(wallet);
711
- await waitForTransferSuccess();
712
- };
713
- function waitForTransferSuccess() {
714
- return new Promise((resolve, reject) => {
715
- const unsubscribe = useCheckoutStore.subscribe((state) => {
716
- if (state.transfer.chainStatus === "confirmed") {
717
- unsubscribe();
718
- resolve();
719
- }
720
- else if (state.transfer.chainStatus === "failed") {
721
- unsubscribe();
722
- reject(new Error(state.transfer.error || "Transaction failed on chain"));
723
- }
724
- });
725
- });
726
- }
727
852
  export const startPaymentPolling = (onPaymentStatusChange, confirmationStatus = PaymentStatus.PAID) => {
728
853
  const ACTION = ACTIONS.POLL_PAYMENT;
729
854
  const POLL_INTERVAL = 5000;
@@ -736,14 +861,11 @@ export const startPaymentPolling = (onPaymentStatusChange, confirmationStatus =
736
861
  state.polling.pollCount++;
737
862
  state.polling.lastPollTime = Date.now();
738
863
  });
739
- console.log(`[Payment Poll] Starting poll attempt #${state.polling.pollCount}`);
740
864
  try {
741
865
  const updatedPayment = await getPayment();
742
866
  if (!updatedPayment) {
743
- console.log(`[Payment Poll] No payment data, skipping poll #${state.polling.pollCount}`);
744
867
  return;
745
868
  }
746
- console.log(`[Payment Poll] Payment status: ${updatedPayment.status} (poll #${state.polling.pollCount})`);
747
869
  const successStatuses = confirmationStatus === PaymentStatus.PAID
748
870
  ? [PaymentStatus.PAID]
749
871
  : [confirmationStatus, PaymentStatus.PAID];
@@ -790,7 +912,9 @@ export const stopPaymentPolling = () => {
790
912
  });
791
913
  };
792
914
  export const resetCheckoutStore = () => {
793
- clearAttemptFreshnessTimer();
915
+ refreshMode = "none";
916
+ isRefreshing = false;
917
+ clearQuoteExpiryTimer();
794
918
  set((state) => {
795
919
  Object.assign(state, {
796
920
  amount: null,
@@ -803,15 +927,12 @@ export const resetCheckoutStore = () => {
803
927
  checkout: null,
804
928
  payment: null,
805
929
  cryptoPaymentAttempt: null,
806
- attemptFreshness: {
930
+ quote: {
807
931
  status: "idle",
932
+ error: null,
808
933
  expiresAt: null,
809
934
  remainingMs: null,
810
- },
811
- attemptRefresh: {
812
- mode: "none",
813
- status: "idle",
814
- error: null,
935
+ totalDurationMs: null,
815
936
  },
816
937
  loading: initialActionState(false),
817
938
  error: initialActionState(null),
@@ -831,7 +952,9 @@ export const resetCheckoutStore = () => {
831
952
  });
832
953
  };
833
954
  export const resetCheckoutSessionForRetry = () => {
834
- clearAttemptFreshnessTimer();
955
+ refreshMode = "none";
956
+ isRefreshing = false;
957
+ clearQuoteExpiryTimer();
835
958
  set((state) => {
836
959
  // Retry keeps the same payment intent but discards all attempt-scoped UI
837
960
  // state so the payer can choose a fresh route. The payment object itself is
@@ -855,15 +978,12 @@ export const resetCheckoutSessionForRetry = () => {
855
978
  lastPollTime: null,
856
979
  };
857
980
  state.walletPayment = initialWalletPaymentState();
858
- state.attemptFreshness = {
981
+ state.quote = {
859
982
  status: "idle",
983
+ error: null,
860
984
  expiresAt: null,
861
985
  remainingMs: null,
862
- };
863
- state.attemptRefresh = {
864
- mode: "none",
865
- status: "idle",
866
- error: null,
986
+ totalDurationMs: null,
867
987
  };
868
988
  state.error[ACTIONS.CREATE_PAYMENT_ATTEMPT] = null;
869
989
  state.error[ACTIONS.CREATE_FIAT_PAYMENT_ATTEMPT] = null;