@pollar/react 0.12.1-rc.26 → 0.12.1-rc.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1311,7 +1311,7 @@ var PollarModalFooter = ({ language: languageProp }) => {
1311
1311
  /* @__PURE__ */ jsxRuntime.jsx("img", { src: LOGO_POLLAR_WORDMARK_ON_DARK, alt: "Pollar", className: "pollar-footer-logo pollar-logo-on-dark" }),
1312
1312
  /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "pollar-footer-version", children: [
1313
1313
  "v",
1314
- "0.12.1-rc.26"
1314
+ "0.12.1-rc.27"
1315
1315
  ] })
1316
1316
  ] });
1317
1317
  };
@@ -4985,7 +4985,8 @@ function LoginModalTemplate({
4985
4985
  const cssVars = buildModalCssVars(theme, accentColor, styleOverrides, "hero");
4986
4986
  const status = authStateToStatus(authState.step);
4987
4987
  const isLoading = status === "LOADING";
4988
- const isEmailCodeError = authState.step === "error" && (authState.errorCode === core.AUTH_ERROR_CODES.EMAIL_CODE_EXPIRED || authState.errorCode === core.AUTH_ERROR_CODES.EMAIL_CODE_INVALID);
4988
+ const isEmailCodeError = authState.step === "error" && (authState.errorCode === core.AUTH_ERROR_CODES.EMAIL_CODE_EXPIRED || authState.errorCode === core.AUTH_ERROR_CODES.EMAIL_CODE_INVALID || // A rate limit or a server error on verify: the same code can go again.
4989
+ authState.errorCode === core.AUTH_ERROR_CODES.EMAIL_VERIFY_FAILED);
4989
4990
  const awaitingEmailCode = authState.step === "entering_code" || authState.step === "verifying_email_code" || isEmailCodeError;
4990
4991
  const statusMessage = authState.step === "error" ? core.authErrorMessage(authState.code, language) ?? authState.message : copy.status[authState.step];
4991
4992
  const BackButton = ({ onClick }) => /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", className: "pollar-back-btn", onClick, "aria-label": copy.back, children: /* @__PURE__ */ jsxRuntime.jsx(
@@ -5408,6 +5409,10 @@ function LoginModal({ onClose, inline = false }) {
5408
5409
  getClient().cancelLogin();
5409
5410
  }
5410
5411
  function handleRetry() {
5412
+ if (authState.step === "error" && authState.errorCode === core.AUTH_ERROR_CODES.EMAIL_SEND_FAILED && authState.code === "RATE_LIMITED" && authState.clientSessionId && authState.email) {
5413
+ getClient().sendEmailCode(authState.email);
5414
+ return;
5415
+ }
5411
5416
  getClient().logout();
5412
5417
  if (styles.emailEnabled) {
5413
5418
  getClient().beginEmailLogin();
@@ -5645,7 +5650,9 @@ var RAMP_COPY = {
5645
5650
  send: (amount, code) => `Send ${amount} ${code}`,
5646
5651
  delivering: (code) => `Your ${code} is on its way`,
5647
5652
  payingOut: (currency) => `Your ${currency} is on its way to your account`,
5648
- next: "Next step",
5653
+ stepLabel: (position, total, title) => `Step ${position} of ${total}: ${title}`,
5654
+ finalStep: "Done",
5655
+ paidAt: "Paid",
5649
5656
  paidDone: (amount, currency) => `You paid ${amount} ${currency}.`,
5650
5657
  sentDone: (amount, code) => `You sent ${amount} ${code}.`,
5651
5658
  receivedDone: (amount, code, chain) => `You received ${amount} ${code} on ${chain}.`,
@@ -5662,7 +5669,6 @@ var RAMP_COPY = {
5662
5669
  received: (amount) => `+${amount}`,
5663
5670
  arrived: (chain) => `It reached your wallet on ${chain}.`,
5664
5671
  paidOut: "It was sent to your account.",
5665
- finish: "Done",
5666
5672
  details: "Details"
5667
5673
  },
5668
5674
  somethingWrong: "Something went wrong.",
@@ -5811,7 +5817,9 @@ var RAMP_COPY = {
5811
5817
  send: (amount, code) => `Env\xEDa ${amount} ${code}`,
5812
5818
  delivering: (code) => `Tu ${code} est\xE1 en camino`,
5813
5819
  payingOut: (currency) => `Tus ${currency} van en camino a tu cuenta`,
5814
- next: "Paso siguiente",
5820
+ stepLabel: (position, total, title) => `Paso ${position} de ${total}: ${title}`,
5821
+ finalStep: "Listo",
5822
+ paidAt: "Pagado",
5815
5823
  paidDone: (amount, currency) => `Pagaste ${amount} ${currency}.`,
5816
5824
  sentDone: (amount, code) => `Enviaste ${amount} ${code}.`,
5817
5825
  receivedDone: (amount, code, chain) => `Recibiste ${amount} ${code} en ${chain}.`,
@@ -5828,7 +5836,6 @@ var RAMP_COPY = {
5828
5836
  received: (amount) => `+${amount}`,
5829
5837
  arrived: (chain) => `Lleg\xF3 a tu wallet en ${chain}.`,
5830
5838
  paidOut: "Se envi\xF3 a tu cuenta.",
5831
- finish: "Listo",
5832
5839
  details: "Detalles"
5833
5840
  },
5834
5841
  somethingWrong: "Algo sali\xF3 mal.",
@@ -5977,7 +5984,9 @@ var RAMP_COPY = {
5977
5984
  send: (amount, code) => `Envie ${amount} ${code}`,
5978
5985
  delivering: (code) => `Seu ${code} est\xE1 a caminho`,
5979
5986
  payingOut: (currency) => `Seus ${currency} est\xE3o a caminho da sua conta`,
5980
- next: "Pr\xF3xima etapa",
5987
+ stepLabel: (position, total, title) => `Etapa ${position} de ${total}: ${title}`,
5988
+ finalStep: "Pronto",
5989
+ paidAt: "Pago em",
5981
5990
  paidDone: (amount, currency) => `Voc\xEA pagou ${amount} ${currency}.`,
5982
5991
  sentDone: (amount, code) => `Voc\xEA enviou ${amount} ${code}.`,
5983
5992
  receivedDone: (amount, code, chain) => `Voc\xEA recebeu ${amount} ${code} na ${chain}.`,
@@ -5994,7 +6003,6 @@ var RAMP_COPY = {
5994
6003
  received: (amount) => `+${amount}`,
5995
6004
  arrived: (chain) => `Chegou \xE0 sua carteira na ${chain}.`,
5996
6005
  paidOut: "Foi enviado para a sua conta.",
5997
- finish: "Pronto",
5998
6006
  details: "Detalhes"
5999
6007
  },
6000
6008
  somethingWrong: "Algo deu errado.",
@@ -6456,6 +6464,7 @@ function RampWidgetTemplate({
6456
6464
  language: languageProp,
6457
6465
  confirmation = null,
6458
6466
  onCancelOrder,
6467
+ cosignPrompt = null,
6459
6468
  cancelling = false,
6460
6469
  cancelError = null
6461
6470
  }) {
@@ -6467,6 +6476,7 @@ function RampWidgetTemplate({
6467
6476
  const [detailsOpen, setDetailsOpen] = react.useState(false);
6468
6477
  const [viewing, setViewing] = react.useState(null);
6469
6478
  const [leaving, setLeaving] = react.useState(false);
6479
+ const [doneDetailsOpen, setDoneDetailsOpen] = react.useState(false);
6470
6480
  react.useEffect(() => {
6471
6481
  setViewing(null);
6472
6482
  setLeaving(false);
@@ -6576,7 +6586,25 @@ function RampWidgetTemplate({
6576
6586
  return screen.kind === "action" ? copy.screens.signedDone : copy.screens.ranDone;
6577
6587
  };
6578
6588
  const finalNote = order?.legs.map((leg) => core.rampLegNote(leg, language)).find((note) => note !== null) ?? null;
6579
- const screenRows = (screen) => screen.steps.length ? screen.steps.flatMap(
6589
+ const paidQr = (screen) => {
6590
+ if (!screen.key.endsWith(":pay")) return null;
6591
+ const instructions = screen.leg.paymentRequest?.instructions;
6592
+ return instructions?.kind === "qr" ? instructions.scannable?.image ?? null : null;
6593
+ };
6594
+ const paidRows = (screen) => {
6595
+ if (!screen.key.endsWith(":pay") || !order) return [];
6596
+ const at = screen.leg.paymentReceivedAt;
6597
+ return [
6598
+ ...at ? [
6599
+ {
6600
+ label: copy.screens.paidAt,
6601
+ value: new Date(at).toLocaleString(language, { dateStyle: "medium", timeStyle: "short" })
6602
+ }
6603
+ ] : [],
6604
+ { label: copy.order, value: `\u2026${order.id.slice(-8)}`, copyValue: order.id, mono: true }
6605
+ ];
6606
+ };
6607
+ const screenRowsOf = (screen) => screen.steps.length ? screen.steps.flatMap(
6580
6608
  (st) => st.hash ? [
6581
6609
  {
6582
6610
  label: core.rampStepTitle(st, screen.leg, language),
@@ -6593,6 +6621,7 @@ function RampWidgetTemplate({
6593
6621
  copyValue: screen.leg.onchainTxHash
6594
6622
  }
6595
6623
  ] : [];
6624
+ const screenRows = (screen) => [...paidRows(screen), ...screenRowsOf(screen)];
6596
6625
  const stepTitle = {
6597
6626
  input: onramp ? copy.title.buy : copy.title.sell,
6598
6627
  loading_quote: copy.title.finding,
@@ -6682,41 +6711,33 @@ function RampWidgetTemplate({
6682
6711
  }
6683
6712
  ) }, label)) })
6684
6713
  ] }),
6685
- step === "status" && screens.length > 0 && !(leaving && !settled) && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pollar-ramp-screens-nav", children: [
6686
- /* @__PURE__ */ jsxRuntime.jsx(
6714
+ step === "status" && screens.length > 0 && !(leaving && !settled) && /* @__PURE__ */ jsxRuntime.jsx("ol", { className: "pollar-ramp-stepper", "aria-label": copy.progress, children: [...screens, null].map((screen, i) => {
6715
+ const state = i < currentScreen || completed && i === screens.length ? "done" : screen?.status === "failed" ? "failed" : i === currentScreen ? "current" : "upcoming";
6716
+ const busy = state === "current" && !settled && !(screen?.kind === "action" && order?.pendingAction);
6717
+ return /* @__PURE__ */ jsxRuntime.jsx("li", { children: /* @__PURE__ */ jsxRuntime.jsx(
6687
6718
  "button",
6688
6719
  {
6689
6720
  type: "button",
6690
- className: "pollar-ramp-screens-arrow",
6691
- "data-hidden": shownScreen === 0 || void 0,
6692
- disabled: shownScreen === 0,
6693
- onClick: () => setViewing(shownScreen - 1),
6694
- "aria-label": copy.back,
6695
- children: /* @__PURE__ */ jsxRuntime.jsx("svg", { width: "16", height: "16", viewBox: "0 0 16 16", fill: "none", "aria-hidden": true, children: /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M10 3 5 8l5 5", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }) })
6696
- }
6697
- ),
6698
- /* @__PURE__ */ jsxRuntime.jsx("ol", { className: "pollar-ramp-screens-bar", "aria-label": copy.progress, children: [...screens.map((s) => s.key), "final"].map((key, i) => /* @__PURE__ */ jsxRuntime.jsx(
6699
- "li",
6700
- {
6701
- "data-done": i < currentScreen || completed && i === screens.length || void 0,
6721
+ className: "pollar-ramp-stepper-step",
6722
+ "data-state": state,
6702
6723
  "data-shown": i === shownScreen || void 0,
6703
- "data-failed": screens[i]?.status === "failed" || void 0
6704
- },
6705
- key
6706
- )) }),
6707
- /* @__PURE__ */ jsxRuntime.jsx(
6708
- "button",
6709
- {
6710
- type: "button",
6711
- className: "pollar-ramp-screens-arrow",
6712
- "data-hidden": shownScreen >= currentScreen || void 0,
6713
- disabled: shownScreen >= currentScreen,
6714
- onClick: () => setViewing(shownScreen + 1 >= currentScreen ? null : shownScreen + 1),
6715
- "aria-label": copy.screens.next,
6716
- children: /* @__PURE__ */ jsxRuntime.jsx("svg", { width: "16", height: "16", viewBox: "0 0 16 16", fill: "none", "aria-hidden": true, children: /* @__PURE__ */ jsxRuntime.jsx("path", { d: "m6 3 5 5-5 5", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }) })
6724
+ "aria-current": i === shownScreen ? "step" : void 0,
6725
+ "aria-label": copy.screens.stepLabel(i + 1, screens.length + 1, screen?.title ?? copy.screens.finalStep),
6726
+ disabled: i > currentScreen,
6727
+ onClick: () => setViewing(i >= currentScreen ? null : i),
6728
+ children: state === "done" ? /* @__PURE__ */ jsxRuntime.jsx("svg", { width: "14", height: "14", viewBox: "0 0 16 16", fill: "none", "aria-hidden": true, children: /* @__PURE__ */ jsxRuntime.jsx(
6729
+ "path",
6730
+ {
6731
+ d: "M3 8.5 6.5 12 13 4.5",
6732
+ stroke: "currentColor",
6733
+ strokeWidth: "2.2",
6734
+ strokeLinecap: "round",
6735
+ strokeLinejoin: "round"
6736
+ }
6737
+ ) }) : state === "failed" ? /* @__PURE__ */ jsxRuntime.jsx("svg", { width: "12", height: "12", viewBox: "0 0 16 16", fill: "none", "aria-hidden": true, children: /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M3 3l10 10M13 3 3 13", stroke: "currentColor", strokeWidth: "2.2", strokeLinecap: "round" }) }) : busy ? /* @__PURE__ */ jsxRuntime.jsx("span", { className: "pollar-spinner pollar-spinner-sm", "aria-hidden": true }) : i + 1
6717
6738
  }
6718
- )
6719
- ] }),
6739
+ ) }, screen?.key ?? "final");
6740
+ }) }),
6720
6741
  step === "input" && pendingOrders.length > 0 && /* @__PURE__ */ jsxRuntime.jsxs("section", { className: "pollar-ramp-payment pollar-ramp-saved", "aria-label": copy.pendingAria, children: [
6721
6742
  /* @__PURE__ */ jsxRuntime.jsx("p", { className: "pollar-ramp-payment-note", children: copy.pendingNote }),
6722
6743
  pendingOrders.map((pending) => /* @__PURE__ */ jsxRuntime.jsx("div", { className: "pollar-ramp-saved-row", children: /* @__PURE__ */ jsxRuntime.jsx(
@@ -7043,7 +7064,6 @@ function RampWidgetTemplate({
7043
7064
  /* @__PURE__ */ jsxRuntime.jsx("p", { className: "pollar-ramp-payment-note", children: arrivedText }),
7044
7065
  finalNote && /* @__PURE__ */ jsxRuntime.jsx("p", { className: "pollar-ramp-payment-note", children: finalNote })
7045
7066
  ] }),
7046
- /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", className: "pollar-btn-primary", onClick: onClose, children: copy.screens.finish }),
7047
7067
  /* @__PURE__ */ jsxRuntime.jsx(TxReview, { data: { title: "", kind: "other", rows: orderRows }, language })
7048
7068
  ] }) : shownScreen < currentScreen ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
7049
7069
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pollar-ramp-done", children: [
@@ -7060,7 +7080,26 @@ function RampWidgetTemplate({
7060
7080
  /* @__PURE__ */ jsxRuntime.jsx("h3", { className: "pollar-ramp-done-title", children: screens[shownScreen].title }),
7061
7081
  /* @__PURE__ */ jsxRuntime.jsx("p", { className: "pollar-ramp-payment-note", children: doneText(screens[shownScreen]) })
7062
7082
  ] }),
7063
- screenRows(screens[shownScreen]).length > 0 && /* @__PURE__ */ jsxRuntime.jsx(TxReview, { data: { title: "", kind: "other", rows: screenRows(screens[shownScreen]) }, language })
7083
+ screenRows(screens[shownScreen]).length > 0 && /* @__PURE__ */ jsxRuntime.jsx(
7084
+ TxReview,
7085
+ {
7086
+ data: { title: "", kind: "other", rows: screenRows(screens[shownScreen]) },
7087
+ open: doneDetailsOpen,
7088
+ onToggle: () => setDoneDetailsOpen((open) => !open),
7089
+ language
7090
+ }
7091
+ ),
7092
+ doneDetailsOpen && paidQr(screens[shownScreen]) && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pollar-ramp-paid-qr", children: [
7093
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "pollar-ramp-payment-label", children: copy.paymentQr }),
7094
+ paidQr(screens[shownScreen]).inlineSafe ? /* @__PURE__ */ jsxRuntime.jsx(
7095
+ "div",
7096
+ {
7097
+ className: "pollar-ramp-qr",
7098
+ "aria-label": copy.paymentQr,
7099
+ dangerouslySetInnerHTML: { __html: paidQr(screens[shownScreen]).data }
7100
+ }
7101
+ ) : /* @__PURE__ */ jsxRuntime.jsx("img", { src: scannableImageSrc(paidQr(screens[shownScreen])), alt: copy.paymentQr })
7102
+ ] })
7064
7103
  ] }) : /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
7065
7104
  shown && /* @__PURE__ */ jsxRuntime.jsx("h3", { className: "pollar-ramp-screen-title", "data-status": shown.status, children: askedInstead ? view.title : shown.title }),
7066
7105
  shown?.status === "failed" && shown.leg.failure && /* @__PURE__ */ jsxRuntime.jsx("p", { className: "pollar-ramp-field-error", children: core.rampFailureReason(shown.leg.failure, language) }),
@@ -7082,6 +7121,7 @@ function RampWidgetTemplate({
7082
7121
  ] })
7083
7122
  ] }, s.kind)) }),
7084
7123
  confirmation && /* @__PURE__ */ jsxRuntime.jsx(InlineConfirm, { confirmation, language, network }),
7124
+ cosignPrompt,
7085
7125
  order.failure && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pollar-ramp-payment-field", children: [
7086
7126
  /* @__PURE__ */ jsxRuntime.jsx("span", { className: "pollar-ramp-payment-label", children: copy.whatToDo }),
7087
7127
  /* @__PURE__ */ jsxRuntime.jsx("p", { className: "pollar-ramp-payment-note", children: core.rampOrderResolutionText(order, language) }),
@@ -7180,7 +7220,7 @@ function RampWidgetTemplate({
7180
7220
  ] }) : copy.paid }),
7181
7221
  !settled && view.canSign && /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", className: "pollar-btn-primary", disabled: signing, onClick: onSign, children: signing ? copy.waitingWallet : copy.authorize }),
7182
7222
  !settled && view.action?.kind === "SIGNATURE" && !view.canSign && /* @__PURE__ */ jsxRuntime.jsx("p", { className: "pollar-ramp-payment-note", children: copy.preparingSignature }),
7183
- !settled && view.canApprove && /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", className: "pollar-btn-primary", onClick: onApprove, children: copy.approveOnDevice }),
7223
+ !settled && view.canApprove && !cosignPrompt && /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", className: "pollar-btn-primary", onClick: onApprove, children: copy.approveOnDevice }),
7184
7224
  !settled && view.link && /* @__PURE__ */ jsxRuntime.jsx(
7185
7225
  "a",
7186
7226
  {
@@ -7804,637 +7844,1226 @@ function ProviderRegistrationModal({
7804
7844
  }
7805
7845
  ) });
7806
7846
  }
7807
- var PAYMENT_CHECK_EVERY_MS = 1e4;
7808
- var PAYMENT_CHECK_WINDOW_MS = 2 * 6e4;
7809
- function rampErrorMessage(error, fallback, copy, language) {
7810
- const unavailable = core.appUnavailableMessage(error, language);
7811
- if (unavailable) return unavailable;
7812
- if (core.isPollarApiError(error)) {
7813
- const known = copy.errors[error.code];
7814
- if (known) return known;
7815
- const message = error.body.message;
7816
- if (typeof message === "string" && message && !/^[A-Z0-9_]+$/.test(message)) return message;
7817
- }
7818
- return fallback;
7819
- }
7820
- var DECIMAL = /^\d+(\.\d+)?$/;
7821
- var QUOTE_DEBOUNCE_MS = 600;
7822
- function seededSelection(routes, seed) {
7823
- const countries = core.rampCountries(routes);
7824
- const wanted = seed.country?.trim().toUpperCase();
7825
- const country = wanted ? countries.find((c) => c.country === wanted) : countries[0];
7826
- if (!country) return null;
7827
- const fiat = country.fiats.find((f) => f.currency === seed.fiat?.trim().toUpperCase()) ?? null;
7828
- const resolvedFiat = fiat ?? country.fiats[0];
7829
- const asset = routes.find(
7830
- (r) => r.fiat.country === country.country && resolvedFiat !== void 0 && fiatKey(r.fiat) === fiatKey(resolvedFiat) && r.asset.code.toUpperCase() === seed.asset?.trim().toUpperCase()
7831
- )?.asset;
7832
- const amount = seed.amount?.trim() ?? "";
7833
- return {
7834
- country: country.country,
7835
- fiatChoice: fiat ? fiatKey(fiat) : "",
7836
- assetChoice: asset ? assetKey3(asset) : "",
7837
- amount: DECIMAL.test(amount) ? amount : ""
7838
- };
7839
- }
7840
- async function signLegWithWallet(client, orderId, actionId, copy) {
7841
- const lent = [];
7842
- const lend = (chain, encoding, handler) => {
7847
+ function useCosign() {
7848
+ const { getClient, isAuthenticated } = usePollar();
7849
+ const [state, setState] = react.useState({ pending: [] });
7850
+ const [loaded, setLoaded] = react.useState(false);
7851
+ react.useEffect(() => getClient().onCosignStateChange(setState), [getClient]);
7852
+ const refresh = react.useCallback(async () => {
7853
+ if (!isAuthenticated) return;
7843
7854
  try {
7844
- lent.push(client.registerRampSigningHandler(chain, encoding, handler));
7845
- } catch {
7855
+ await getClient().cosign.pending();
7856
+ } finally {
7857
+ setLoaded(true);
7846
7858
  }
7859
+ }, [getClient, isAuthenticated]);
7860
+ react.useEffect(() => {
7861
+ void refresh();
7862
+ }, [refresh]);
7863
+ return {
7864
+ pending: state.pending,
7865
+ ...state.lastResolved ? { lastResolved: state.lastResolved } : {},
7866
+ loaded,
7867
+ refresh,
7868
+ approve: react.useCallback((request) => getClient().cosign.approve(request), [getClient]),
7869
+ reject: react.useCallback((request) => getClient().cosign.reject(request), [getClient]),
7870
+ verify: react.useCallback((request) => getClient().cosign.verify(request), [getClient]),
7871
+ inspectQuorum: react.useCallback(() => getClient().cosign.inspectQuorum(), [getClient]),
7872
+ devices: react.useCallback(() => getClient().cosign.devices(), [getClient]),
7873
+ revokeDevice: react.useCallback(
7874
+ (deviceId, options) => getClient().cosign.revokeDevice(deviceId, options),
7875
+ [getClient]
7876
+ ),
7877
+ switchCustody: react.useCallback((to) => getClient().cosign.switchCustody(to), [getClient])
7847
7878
  };
7848
- lend("STELLAR", "xdr", async (action) => {
7849
- const wallet = client.getWallet();
7850
- if (!wallet) throw new Error(copy.connectStellarWallet);
7851
- core.assertRampStellarSigner(action, wallet.address);
7852
- const outcome = await client.signTx(action.payload.value);
7853
- if (client.getWallet()?.address !== wallet.address) throw new Error(copy.walletChanged);
7854
- if (outcome.status === "signed") return outcome.signedXdr;
7855
- throw new Error(
7856
- outcome.status === "error" ? outcome.message ?? outcome.details ?? copy.signingCancelled : copy.signingCancelled
7857
- );
7858
- });
7859
- lend("SOLANA", "solana-v0-json", async (action) => {
7860
- const payload = JSON.parse(action.payload.value);
7861
- const solanaWallet = () => client.getWallets().find((w) => w.chain === "SOLANA" && w.custody === "external");
7862
- const wallet = solanaWallet();
7863
- if (!wallet || payload.from !== wallet.address || !payload.unsignedTransaction) throw new Error(copy.solanaWalletMismatch);
7864
- const signed = await client.signSolanaTransaction(payload.unsignedTransaction);
7865
- if (solanaWallet()?.address !== wallet.address) throw new Error(copy.walletChanged);
7866
- return signed;
7867
- });
7868
- try {
7869
- return await client.signRampLeg(orderId, actionId);
7870
- } finally {
7871
- for (const release of lent) release();
7872
- }
7873
7879
  }
7874
- function RampWidget({ onClose, language: languageProp, initial }) {
7875
- const {
7876
- getClient,
7877
- styles,
7878
- network,
7879
- openCosignModal,
7880
- setCosignNextStep,
7881
- openRecoveryModal,
7882
- recovery,
7883
- recoveryLocked,
7884
- appConfig,
7885
- cosign,
7886
- refreshWalletBalance
7887
- } = usePollar();
7888
- const client = getClient();
7889
- const language = useModalLanguage(languageProp);
7890
- const copy = RAMP_COPY[language];
7891
- const { theme, accentColor, styleOverrides, overlayStyle } = modalChrome(styles);
7892
- const [step, setStep] = react.useState("input");
7893
- const confirmation = useInlineConfirmation(step === "status");
7894
- const [direction, setDirection] = react.useState(initial?.direction === "sell" ? "OFFRAMP" : "ONRAMP");
7895
- const seedRef = react.useRef(
7896
- initial ? { direction: initial.direction === "sell" ? "OFFRAMP" : "ONRAMP", options: initial } : null
7897
- );
7898
- const [routes, setRoutes] = react.useState([]);
7899
- const [routesLoading, setRoutesLoading] = react.useState(true);
7900
- const [country, setCountry] = react.useState("");
7901
- const [fiatChoice, setFiatChoice] = react.useState("");
7902
- const [assetChoice, setAssetChoice] = react.useState("");
7903
- const [amount, setAmount] = react.useState("");
7904
- const [quotes, setQuotes] = react.useState([]);
7905
- const [rejected, setRejected] = react.useState([]);
7906
- const [selected, setSelected] = react.useState(null);
7907
- const [startingQuoteId, setStartingQuoteId] = react.useState(null);
7908
- const [fieldValues, setFieldValues] = react.useState({});
7909
- const [order, setOrder] = react.useState(null);
7910
- const [pendingOrders, setPendingOrders] = react.useState([]);
7911
- const [isLoading, setIsLoading] = react.useState(false);
7912
- const [refreshing, setRefreshing] = react.useState(false);
7913
- const [signing, setSigning] = react.useState(false);
7914
- const [errorMsg, setErrorMsg] = react.useState(null);
7915
- const [verifying, setVerifying] = react.useState(null);
7916
- const [trustingAsset, setTrustingAsset] = react.useState(null);
7917
- const [walletBusy, setWalletBusy] = react.useState(null);
7918
- const [retrying, setRetrying] = react.useState(false);
7919
- const [cancelling, setCancelling] = react.useState(false);
7920
- const [cancelError, setCancelError] = react.useState(null);
7921
- const [awaitingAccount, setAwaitingAccount] = react.useState(null);
7922
- const [pollTrouble, setPollTrouble] = react.useState(false);
7923
- const [pollKey, setPollKey] = react.useState(0);
7924
- const [paymentCheckUntil, setPaymentCheckUntil] = react.useState(null);
7925
- const checkErrorRef = react.useRef(null);
7926
- const promptedApproval = react.useRef(null);
7927
- const custodyChoice = appConfig.application?.walletCustodyMode === "USER_CHOICE";
7928
- const appChains = appConfig.application?.chains;
7929
- const verifyAttempt = react.useRef(null);
7930
- const countries = react.useMemo(() => core.rampCountries(routes), [routes]);
7931
- const fiats = countries.find((c) => c.country === country)?.fiats ?? [];
7932
- const fiat = fiats.find((f) => fiatKey(f) === fiatChoice) ?? fiats[0] ?? null;
7933
- const assets = react.useMemo(() => {
7934
- const seen = /* @__PURE__ */ new Map();
7935
- for (const route of routes)
7936
- if (fiat && route.fiat.country === country && fiatKey(route.fiat) === fiatKey(fiat))
7937
- seen.set(assetKey3(route.asset), route.asset);
7938
- return [...seen.values()];
7939
- }, [routes, country, fiat]);
7940
- const asset = assets.find((a) => assetKey3(a) === assetChoice) ?? assets[0] ?? null;
7941
- const fields = selected ? core.rampQuoteFields(selected, language) : [];
7942
- const sellAvailable = useWalletAvailable(
7943
- direction === "OFFRAMP" && asset ? { chain: asset.chain, code: asset.code, issuer: asset.identifier } : null
7944
- );
7945
- const [quoting, setQuoting] = react.useState(false);
7946
- const [routeChoice, setRouteChoice] = react.useState(BEST_ROUTE);
7947
- const quoteRun = react.useRef(0);
7948
- const quoteInput = step === "input" && fiat && asset && DECIMAL.test(amount.trim()) && Number(amount) > 0;
7949
- const quoteKey = quoteInput ? `${direction}|${fiatKey(fiat)}|${assetKey3(asset)}|${amount.trim()}` : null;
7950
- react.useEffect(() => {
7951
- const run = ++quoteRun.current;
7952
- if (!quoteKey || !fiat || !asset) {
7953
- setQuoting(false);
7954
- if (step === "input") {
7955
- setQuotes([]);
7956
- setRejected([]);
7957
- }
7958
- return;
7959
- }
7960
- setQuoting(true);
7961
- const timer = setTimeout(() => {
7962
- client.quoteRamp({
7963
- direction,
7964
- fiat: { currency: fiat.currency, rail: fiat.rail, country: fiat.country },
7965
- asset: { code: asset.code, identifier: asset.identifier, chain: asset.chain },
7966
- amount: { value: amount.trim(), denomination: "in" }
7967
- }).then((result) => {
7968
- if (run !== quoteRun.current) return;
7969
- setQuotes(result.quotes);
7970
- setRejected(result.rejected);
7971
- setErrorMsg(null);
7972
- }).catch((error) => {
7973
- if (run !== quoteRun.current) return;
7974
- setQuotes([]);
7975
- if (core.isPollarApiError(error) && error.code === "SDK_RAMPS_NO_ROUTE") {
7976
- setRejected(Array.isArray(error.body.rejected) ? error.body.rejected : []);
7977
- } else {
7978
- setRejected([]);
7979
- setErrorMsg(rampErrorMessage(error, copy.findRouteFailed, copy, language));
7980
- }
7981
- }).finally(() => {
7982
- if (run === quoteRun.current) setQuoting(false);
7983
- });
7984
- }, QUOTE_DEBOUNCE_MS);
7985
- return () => clearTimeout(timer);
7986
- }, [quoteKey]);
7987
- const chosenQuote = (routeChoice !== BEST_ROUTE ? quotes.find((q) => routeKey(q) === routeChoice) : void 0) ?? quotes[0] ?? null;
7988
- react.useEffect(() => {
7989
- if (direction === "OFFRAMP") void refreshWalletBalance();
7990
- }, [direction, refreshWalletBalance]);
7991
- async function loadRoutes(next) {
7992
- setRoutesLoading(true);
7993
- try {
7994
- const { routes: found } = await client.getRampRoutes(next);
7995
- setRoutes(found);
7996
- const seed = seedRef.current?.direction === next ? seedRef.current.options : null;
7997
- if (seed) seedRef.current = null;
7998
- const seeded = seed ? seededSelection(found, seed) : null;
7999
- if (seeded) {
8000
- setCountry(seeded.country);
8001
- setFiatChoice(seeded.fiatChoice);
8002
- setAssetChoice(seeded.assetChoice);
8003
- setAmount(seeded.amount);
8004
- return;
8005
- }
8006
- const first = core.rampCountries(found)[0]?.country ?? "";
8007
- setCountry((current) => found.some((r) => r.fiat.country === current) ? current : first);
8008
- } catch (error) {
8009
- setRoutes([]);
8010
- setErrorMsg(rampErrorMessage(error, copy.loadRoutesFailed, copy, language));
8011
- } finally {
8012
- setRoutesLoading(false);
8013
- }
8014
- }
8015
- async function loadPendingOrders() {
8016
- try {
8017
- const page = await client.listRampOrders({ open: "true", limit: 5 });
8018
- setPendingOrders(page.orders);
8019
- } catch {
8020
- setPendingOrders([]);
7880
+
7881
+ // src/components/cosign-modal/cosign-copy.ts
7882
+ var COSIGN_COPY = {
7883
+ en: {
7884
+ title: "Approvals",
7885
+ manyPending: (count) => `${count} approvals waiting`,
7886
+ close: "Close",
7887
+ whyTitle: "Why am I seeing this?",
7888
+ whyBody: "Your wallet needs this device's signature. Neither the app nor Pollar can approve this without you.",
7889
+ rejectRequest: "Reject this request",
7890
+ closeTitle: "Close without signing?",
7891
+ closeBody: "The request stays pending. The app can't continue until you approve it.",
7892
+ backToSign: "Go back and sign",
7893
+ closeAnyway: "Close anyway",
7894
+ activateWallet: "Activate wallet",
7895
+ status: { APPROVED: "Approved", REJECTED: "Rejected", EXPIRED: "Expired", FAILED: "Failed", PENDING: "Pending" },
7896
+ signedAppSends: "Signed. The app will send it.",
7897
+ signedSent: "Signed and sent",
7898
+ signed: "Signed",
7899
+ nothingSigned: "Nothing was signed.",
7900
+ nothingWaiting: "Nothing waits for your approval.",
7901
+ next: (step) => `Next: ${step}. It appears here in a few seconds.`,
7902
+ closingIn: (seconds) => `Closing in ${seconds}s`,
7903
+ expired: "expired",
7904
+ expiresIn: "Expires in",
7905
+ checking: "Checking...",
7906
+ verified: "Checked",
7907
+ checkedExact: "We checked this is exactly what you're approving.",
7908
+ notVerified: "Not verified:",
7909
+ reject: "Reject",
7910
+ rejecting: "Rejecting...",
7911
+ approve: "Approve",
7912
+ approving: "Approving...",
7913
+ genericError: "Something went wrong. Please try again.",
7914
+ unreachable: "We could not reach Pollar, so nothing was approved. Check your connection and approve again.",
7915
+ deviceNotLinked: "This device isn't linked to your wallet yet, so it can't approve. Add it with a device that already is, your passkey or your email.",
7916
+ linkDevice: "Link this device",
7917
+ transaction: "Transaction",
7918
+ operations: {
7919
+ payment: "Send",
7920
+ path_payment_strict_send: "Swap",
7921
+ change_trust: "Add asset",
7922
+ create_account: "Create account",
7923
+ invoke_contract: "Contract call",
7924
+ soroban_auth: "Authorize a contract call",
7925
+ manage_data: "Manage data",
7926
+ transfer: "Send",
7927
+ ramp_payment: "Ramp payment",
7928
+ cctp_burn: "Move USDC",
7929
+ swap: "Swap",
7930
+ earn_deposit: "Deposit",
7931
+ earn_withdraw: "Withdraw",
7932
+ evm_delegation: "Enable atomic transactions",
7933
+ provider_sign_in: "Confirm it's you",
7934
+ sep10: "Confirm it's you"
8021
7935
  }
8022
- }
8023
- react.useEffect(() => {
8024
- void loadRoutes(direction);
8025
- }, [client, direction]);
8026
- react.useEffect(() => {
8027
- void loadPendingOrders();
8028
- }, [client]);
8029
- const orderId = order?.id ?? null;
8030
- react.useEffect(() => {
8031
- if (step !== "status" || !orderId) return;
8032
- const controller = new AbortController();
8033
- client.pollRampOrder(orderId, {
8034
- signal: controller.signal,
8035
- onUpdate: (next) => {
8036
- setOrder(next);
8037
- setPollTrouble(false);
8038
- },
8039
- onError: () => setPollTrouble(true)
8040
- }).catch((error) => {
8041
- if (!controller.signal.aborted) setErrorMsg(rampErrorMessage(error, copy.readOrderFailed, copy, language));
8042
- });
8043
- return () => controller.abort();
8044
- }, [client, step, orderId, pollKey]);
8045
- const awaitingPayment = step === "status" && order?.pendingAction?.kind === "FIAT_PAYMENT";
8046
- react.useEffect(() => {
8047
- if (paymentCheckUntil === null || !orderId) return;
8048
- if (!awaitingPayment) {
8049
- setPaymentCheckUntil(null);
8050
- setPollKey((key) => key + 1);
8051
- return;
7936
+ },
7937
+ es: {
7938
+ title: "Aprobaciones",
7939
+ manyPending: (count) => `${count} aprobaciones pendientes`,
7940
+ close: "Cerrar",
7941
+ whyTitle: "\xBFPor qu\xE9 ves esto?",
7942
+ whyBody: "Tu billetera necesita la firma de este dispositivo. Ni la app ni Pollar pueden aprobar esto sin ti.",
7943
+ rejectRequest: "Rechazar esta solicitud",
7944
+ closeTitle: "\xBFCerrar sin firmar?",
7945
+ closeBody: "La solicitud queda pendiente. La app no puede seguir hasta que la apruebes.",
7946
+ backToSign: "Volver y firmar",
7947
+ closeAnyway: "Cerrar igual",
7948
+ activateWallet: "Activar billetera",
7949
+ status: { APPROVED: "Aprobada", REJECTED: "Rechazada", EXPIRED: "Vencida", FAILED: "Fallida", PENDING: "Pendiente" },
7950
+ signedAppSends: "Firmada. La app la enviar\xE1.",
7951
+ signedSent: "Firmada y enviada",
7952
+ signed: "Firmada",
7953
+ nothingSigned: "No se firm\xF3 nada.",
7954
+ nothingWaiting: "No hay nada esperando tu aprobaci\xF3n.",
7955
+ next: (step) => `Siguiente: ${step}. Aparecer\xE1 aqu\xED en unos segundos.`,
7956
+ closingIn: (seconds) => `Se cierra en ${seconds}s`,
7957
+ expired: "vencida",
7958
+ expiresIn: "Vence en",
7959
+ checking: "Verificando...",
7960
+ verified: "Comprobada",
7961
+ checkedExact: "Comprobamos que esto es exactamente lo que est\xE1s aprobando.",
7962
+ notVerified: "Sin verificar:",
7963
+ reject: "Rechazar",
7964
+ rejecting: "Rechazando...",
7965
+ approve: "Aprobar",
7966
+ approving: "Aprobando...",
7967
+ genericError: "Algo sali\xF3 mal. Intenta de nuevo.",
7968
+ unreachable: "No pudimos conectar con Pollar, as\xED que no se aprob\xF3 nada. Revisa tu conexi\xF3n y aprueba de nuevo.",
7969
+ deviceNotLinked: "Este dispositivo a\xFAn no est\xE1 vinculado a tu billetera, as\xED que no puede aprobar. Agr\xE9galo con un dispositivo que ya lo est\xE9, tu passkey o tu email.",
7970
+ linkDevice: "Vincular este dispositivo",
7971
+ transaction: "Transacci\xF3n",
7972
+ operations: {
7973
+ payment: "Enviar",
7974
+ path_payment_strict_send: "Intercambiar",
7975
+ change_trust: "Agregar activo",
7976
+ create_account: "Crear cuenta",
7977
+ invoke_contract: "Llamada a contrato",
7978
+ soroban_auth: "Autorizar una llamada a contrato",
7979
+ manage_data: "Gestionar datos",
7980
+ transfer: "Enviar",
7981
+ ramp_payment: "Pago de rampa",
7982
+ cctp_burn: "Mover USDC",
7983
+ swap: "Intercambiar",
7984
+ earn_deposit: "Depositar",
7985
+ earn_withdraw: "Retirar",
7986
+ evm_delegation: "Activar transacciones at\xF3micas",
7987
+ provider_sign_in: "Confirma que eres t\xFA",
7988
+ sep10: "Confirma que eres t\xFA"
8052
7989
  }
8053
- const timer = setInterval(() => {
8054
- if (Date.now() >= paymentCheckUntil) {
8055
- setPaymentCheckUntil(null);
8056
- return;
8057
- }
8058
- client.checkRampOrder(orderId).then(setOrder).catch(() => void 0);
8059
- }, PAYMENT_CHECK_EVERY_MS);
8060
- return () => clearInterval(timer);
8061
- }, [client, orderId, awaitingPayment, paymentCheckUntil]);
8062
- react.useEffect(() => {
8063
- if (awaitingPayment || checkErrorRef.current === null) return;
8064
- const shown = checkErrorRef.current;
8065
- checkErrorRef.current = null;
8066
- setErrorMsg((current) => current === shown ? null : current);
8067
- }, [awaitingPayment]);
8068
- const approval = order?.pendingAction?.kind === "COSIGN_APPROVAL" ? order.pendingAction.actionId : null;
8069
- const approvalRequest = order?.pendingAction?.kind === "COSIGN_APPROVAL" ? order.pendingAction.cosignRequestId : null;
8070
- react.useEffect(() => {
8071
- if (!approval || promptedApproval.current === approval) return;
8072
- promptedApproval.current = approval;
8073
- void client.cosign.pending().catch(() => []).then(async (requests) => {
8074
- const request = requests.find((r) => r.id === approvalRequest);
8075
- if (request && await client.autoApproveSignIn(request)) return;
8076
- openCosignModal();
8077
- });
8078
- }, [approval, approvalRequest, client, openCosignModal]);
8079
- const nextApproval = step === "status" && order ? core.rampNextApproval(order, language) : null;
8080
- react.useEffect(() => {
8081
- setCosignNextStep(nextApproval);
8082
- }, [nextApproval, setCosignNextStep]);
8083
- react.useEffect(() => () => setCosignNextStep(null), [setCosignNextStep]);
8084
- const resolvedRequest = cosign.lastResolved;
8085
- react.useEffect(() => {
8086
- if (!awaitingAccount || resolvedRequest?.id !== awaitingAccount.requestId) return;
8087
- setAwaitingAccount(null);
8088
- if (resolvedRequest.status !== "APPROVED") {
8089
- setErrorMsg(copy.accountNotApproved);
8090
- return;
7990
+ },
7991
+ pt: {
7992
+ title: "Aprova\xE7\xF5es",
7993
+ manyPending: (count) => `${count} aprova\xE7\xF5es pendentes`,
7994
+ close: "Fechar",
7995
+ whyTitle: "Por que estou vendo isto?",
7996
+ whyBody: "Sua carteira precisa da assinatura deste dispositivo. Nem o app nem a Pollar podem aprovar isto sem voc\xEA.",
7997
+ rejectRequest: "Rejeitar esta solicita\xE7\xE3o",
7998
+ closeTitle: "Fechar sem assinar?",
7999
+ closeBody: "A solicita\xE7\xE3o fica pendente. O app n\xE3o pode continuar at\xE9 voc\xEA aprov\xE1-la.",
8000
+ backToSign: "Voltar e assinar",
8001
+ closeAnyway: "Fechar mesmo assim",
8002
+ activateWallet: "Ativar carteira",
8003
+ status: { APPROVED: "Aprovada", REJECTED: "Rejeitada", EXPIRED: "Expirada", FAILED: "Falhou", PENDING: "Pendente" },
8004
+ signedAppSends: "Assinada. O app vai envi\xE1-la.",
8005
+ signedSent: "Assinada e enviada",
8006
+ signed: "Assinada",
8007
+ nothingSigned: "Nada foi assinado.",
8008
+ nothingWaiting: "Nada aguarda a sua aprova\xE7\xE3o.",
8009
+ next: (step) => `Pr\xF3ximo: ${step}. Aparece aqui em alguns segundos.`,
8010
+ closingIn: (seconds) => `Fechando em ${seconds}s`,
8011
+ expired: "expirada",
8012
+ expiresIn: "Expira em",
8013
+ checking: "Verificando...",
8014
+ verified: "Conferida",
8015
+ checkedExact: "Conferimos que isto \xE9 exatamente o que voc\xEA est\xE1 aprovando.",
8016
+ notVerified: "N\xE3o verificada:",
8017
+ reject: "Rejeitar",
8018
+ rejecting: "Rejeitando...",
8019
+ approve: "Aprovar",
8020
+ approving: "Aprovando...",
8021
+ genericError: "Algo deu errado. Tente novamente.",
8022
+ unreachable: "N\xE3o conseguimos conectar \xE0 Pollar, ent\xE3o nada foi aprovado. Verifique sua conex\xE3o e aprove novamente.",
8023
+ deviceNotLinked: "Este dispositivo ainda n\xE3o est\xE1 vinculado \xE0 sua carteira, ent\xE3o n\xE3o pode aprovar. Adicione-o com um dispositivo que j\xE1 esteja, sua passkey ou seu email.",
8024
+ linkDevice: "Vincular este dispositivo",
8025
+ transaction: "Transa\xE7\xE3o",
8026
+ operations: {
8027
+ payment: "Enviar",
8028
+ path_payment_strict_send: "Trocar",
8029
+ change_trust: "Adicionar ativo",
8030
+ create_account: "Criar conta",
8031
+ invoke_contract: "Chamada de contrato",
8032
+ soroban_auth: "Autorizar uma chamada de contrato",
8033
+ manage_data: "Gerenciar dados",
8034
+ transfer: "Enviar",
8035
+ ramp_payment: "Pagamento de rampa",
8036
+ cctp_burn: "Mover USDC",
8037
+ swap: "Trocar",
8038
+ earn_deposit: "Depositar",
8039
+ earn_withdraw: "Sacar",
8040
+ evm_delegation: "Ativar transa\xE7\xF5es at\xF4micas",
8041
+ provider_sign_in: "Confirme que \xE9 voc\xEA",
8042
+ sep10: "Confirme que \xE9 voc\xEA"
8091
8043
  }
8092
- void resumeRoute(awaitingAccount.routeKey);
8093
- }, [awaitingAccount, resolvedRequest]);
8094
- function handleDirectionChange(next) {
8095
- seedRef.current = null;
8096
- setDirection(next);
8097
- setErrorMsg(null);
8098
- setAwaitingAccount(null);
8099
8044
  }
8100
- async function handleFindRoute() {
8101
- if (!fiat || !asset) return [];
8102
- if (!DECIMAL.test(amount.trim()) || Number(amount) <= 0) {
8103
- setErrorMsg(copy.amountInvalid);
8104
- return [];
8105
- }
8106
- setStep("loading_quote");
8107
- setErrorMsg(null);
8108
- setSelected(null);
8109
- try {
8110
- const result = await client.quoteRamp({
8111
- direction,
8112
- fiat: { currency: fiat.currency, rail: fiat.rail, country: fiat.country },
8113
- asset: { code: asset.code, identifier: asset.identifier, chain: asset.chain },
8114
- amount: { value: amount.trim(), denomination: "in" }
8115
- });
8116
- setQuotes(result.quotes);
8117
- setRejected(result.rejected);
8118
- setStep("select_route");
8119
- return result.quotes;
8120
- } catch (error) {
8121
- if (core.isPollarApiError(error) && error.code === "SDK_RAMPS_NO_ROUTE") {
8122
- setQuotes([]);
8123
- setRejected(Array.isArray(error.body.rejected) ? error.body.rejected : []);
8124
- setStep("select_route");
8125
- return [];
8045
+ };
8046
+ function labelOf2(request, copy) {
8047
+ const op = request.operation ?? "";
8048
+ return copy.operations[op] ?? (op ? op.replace(/_/g, " ") : copy.transaction);
8049
+ }
8050
+ function expiresIn(request, copy) {
8051
+ const ms = new Date(request.expiresAt).getTime() - Date.now();
8052
+ if (!Number.isFinite(ms) || ms <= 0) return copy.expired;
8053
+ const h = Math.floor(ms / 36e5);
8054
+ const m = Math.floor(ms % 36e5 / 6e4);
8055
+ return h > 0 ? `${h}h ${m}m` : `${m}m`;
8056
+ }
8057
+ function outcomeText(request, copy) {
8058
+ if (request.status !== "APPROVED")
8059
+ return `${copy.status[request.status] ?? request.status.toLowerCase()}. ${copy.nothingSigned}`;
8060
+ if (request.submit?.hash) return copy.signedSent;
8061
+ if (request.signedXdr) return copy.signedAppSends;
8062
+ return copy.status.APPROVED ?? "Approved";
8063
+ }
8064
+ function StepRow({
8065
+ request,
8066
+ review,
8067
+ copy,
8068
+ language
8069
+ }) {
8070
+ const [open, setOpen] = react.useState(false);
8071
+ const ok = request.status === "APPROVED";
8072
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: `pollar-cosign-step${ok ? "" : " pollar-cosign-step-bad"}`, children: [
8073
+ /* @__PURE__ */ jsxRuntime.jsxs("button", { type: "button", className: "pollar-cosign-step-head", "aria-expanded": open, onClick: () => setOpen((v) => !v), children: [
8074
+ /* @__PURE__ */ jsxRuntime.jsx(OutcomeIcon, { ok }),
8075
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "pollar-cosign-step-title", children: review.title }),
8076
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "pollar-cosign-step-status", children: ok ? copy.signed : copy.status[request.status] ?? request.status }),
8077
+ /* @__PURE__ */ jsxRuntime.jsx(
8078
+ "svg",
8079
+ {
8080
+ width: "10",
8081
+ height: "10",
8082
+ viewBox: "0 0 12 12",
8083
+ fill: "none",
8084
+ "aria-hidden": true,
8085
+ style: { transform: open ? "rotate(180deg)" : "none", transition: "transform 150ms" },
8086
+ children: /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M2 4l4 4 4-4", stroke: "currentColor", strokeWidth: "1.6", strokeLinecap: "round", strokeLinejoin: "round" })
8087
+ }
8088
+ )
8089
+ ] }),
8090
+ open && /* @__PURE__ */ jsxRuntime.jsx(TxReview, { data: review, language, detailsOnly: true })
8091
+ ] });
8092
+ }
8093
+ function CloseIcon() {
8094
+ return /* @__PURE__ */ jsxRuntime.jsx("svg", { width: "14", height: "14", viewBox: "0 0 14 14", fill: "none", "aria-hidden": true, children: /* @__PURE__ */ jsxRuntime.jsx("path", { d: "m3 3 8 8M11 3l-8 8", stroke: "currentColor", strokeWidth: "1.7", strokeLinecap: "round" }) });
8095
+ }
8096
+ function VerifiedIcon() {
8097
+ return /* @__PURE__ */ jsxRuntime.jsxs("svg", { width: "14", height: "14", viewBox: "0 0 14 14", fill: "none", "aria-hidden": true, children: [
8098
+ /* @__PURE__ */ jsxRuntime.jsx("circle", { cx: "7", cy: "7", r: "7", fill: "currentColor" }),
8099
+ /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M3.5 7l2.5 2.5 4.5-5", stroke: "white", strokeWidth: "1.4", strokeLinecap: "round", strokeLinejoin: "round" })
8100
+ ] });
8101
+ }
8102
+ function CosignModalTemplate({
8103
+ theme,
8104
+ accentColor,
8105
+ styleOverrides,
8106
+ pending,
8107
+ current,
8108
+ verification,
8109
+ busy,
8110
+ error,
8111
+ approveBlocked = false,
8112
+ deviceNotLinked = false,
8113
+ onLinkDevice,
8114
+ lastResolved,
8115
+ history = [],
8116
+ explorerUrlOf,
8117
+ closesIn = null,
8118
+ nextStep = null,
8119
+ language: languageProp,
8120
+ network,
8121
+ onSelect,
8122
+ onApprove,
8123
+ onReject,
8124
+ onClose,
8125
+ confirmingClose = false,
8126
+ onKeepOpen,
8127
+ onCloseAnyway,
8128
+ inline = false
8129
+ }) {
8130
+ const language = useInheritedLanguage(languageProp);
8131
+ const copy = COSIGN_COPY[language];
8132
+ const cssVars = buildModalCssVars(theme, accentColor, styleOverrides);
8133
+ const verified = verification?.ok === true && !deviceNotLinked;
8134
+ const canVote = !!current && verified && !busy && !approveBlocked;
8135
+ const [verifiedOpenFor, setVerifiedOpenFor] = react.useState(null);
8136
+ const verifiedOpen = !!current && verifiedOpenFor === current.id;
8137
+ const reviewOf = (request) => reviewFromRequest(
8138
+ {
8139
+ chain: request.network,
8140
+ network,
8141
+ operation: request.operation,
8142
+ summary: request.summary,
8143
+ details: request.details,
8144
+ signWith: request.account ?? request.signWith,
8145
+ raw: request.unsignedPayload,
8146
+ fallbackTitle: labelOf2(request, copy),
8147
+ ...request.status === "PENDING" ? { extraRows: [{ label: copy.expiresIn, value: expiresIn(request, copy) }] } : {},
8148
+ appPaysFee: request.submit?.sponsored ?? request.appPaysFee,
8149
+ ...request.submit?.hash ? { hash: { value: request.submit.hash, explorerUrl: explorerUrlOf?.(request) ?? null } } : {}
8150
+ },
8151
+ TX_REVIEW_COPY[language]
8152
+ );
8153
+ const review = current ? reviewOf(current) : null;
8154
+ const grouped = pending.length > 1;
8155
+ const shown = grouped ? null : current ?? (pending.length === 0 ? lastResolved : void 0) ?? null;
8156
+ const shownReview = shown ? shown === current ? review : reviewOf(shown) : null;
8157
+ const doneSteps = history.filter((r) => !(pending.length === 0 && r.id === lastResolved?.id));
8158
+ const heading = confirmingClose ? copy.closeTitle : grouped ? copy.manyPending(pending.length) : shownReview?.title ?? copy.title;
8159
+ const chip = current && !confirmingClose && /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
8160
+ !verification && !deviceNotLinked && /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "pollar-cosign-chip", children: [
8161
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "pollar-spinner pollar-spinner-sm", "aria-hidden": true }),
8162
+ copy.checking
8163
+ ] }),
8164
+ verified && /* @__PURE__ */ jsxRuntime.jsxs(
8165
+ "button",
8166
+ {
8167
+ type: "button",
8168
+ className: "pollar-cosign-chip pollar-cosign-chip-ok",
8169
+ "aria-expanded": verifiedOpen,
8170
+ onClick: () => setVerifiedOpenFor(verifiedOpen ? null : current.id),
8171
+ children: [
8172
+ /* @__PURE__ */ jsxRuntime.jsx(VerifiedIcon, {}),
8173
+ copy.verified
8174
+ ]
8126
8175
  }
8127
- setErrorMsg(rampErrorMessage(error, copy.findRouteFailed, copy, language));
8128
- setStep("error");
8129
- return [];
8176
+ )
8177
+ ] });
8178
+ return /* @__PURE__ */ jsxRuntime.jsxs(
8179
+ "div",
8180
+ {
8181
+ className: inline ? "pollar-cosign-modal pollar-cosign-inline" : "pollar-modal-card pollar-cosign-modal",
8182
+ "data-theme": theme,
8183
+ style: cssVars,
8184
+ onClick: (e) => e.stopPropagation(),
8185
+ children: [
8186
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pollar-modal-header", children: [
8187
+ /* @__PURE__ */ jsxRuntime.jsxs("h2", { className: "pollar-modal-title pollar-cosign-heading", children: [
8188
+ !confirmingClose && /* @__PURE__ */ jsxRuntime.jsx(TitleMark, { chain: shown?.network, asset: shownReview ? headlineAsset(shownReview) : void 0 }),
8189
+ /* @__PURE__ */ jsxRuntime.jsx("span", { children: heading })
8190
+ ] }),
8191
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pollar-modal-header-actions", children: [
8192
+ !grouped && chip,
8193
+ !confirmingClose && !inline && /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", className: "pollar-modal-close", onClick: onClose, "aria-label": copy.close, title: copy.close, children: /* @__PURE__ */ jsxRuntime.jsx(CloseIcon, {}) })
8194
+ ] })
8195
+ ] }),
8196
+ confirmingClose ? /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pollar-cosign-leave", children: [
8197
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "pollar-cosign-muted", children: copy.closeBody }),
8198
+ /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", className: "pollar-cosign-btn pollar-cosign-btn-primary", onClick: onKeepOpen, children: copy.backToSign }),
8199
+ /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", className: "pollar-cosign-text-btn", onClick: onCloseAnyway, children: copy.closeAnyway })
8200
+ ] }) : /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
8201
+ doneSteps.map((r) => /* @__PURE__ */ jsxRuntime.jsx(StepRow, { request: r, review: reviewOf(r), copy, language }, r.id)),
8202
+ pending.length === 0 && (lastResolved && shownReview ? /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pollar-cosign-detail", children: [
8203
+ /* @__PURE__ */ jsxRuntime.jsx(TxReview, { data: shownReview, language }, lastResolved.id),
8204
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: `pollar-outcome${lastResolved.status === "APPROVED" ? "" : " pollar-outcome-bad"}`, children: [
8205
+ /* @__PURE__ */ jsxRuntime.jsxs("p", { className: "pollar-outcome-main", children: [
8206
+ /* @__PURE__ */ jsxRuntime.jsx(OutcomeIcon, { ok: lastResolved.status === "APPROVED" }),
8207
+ outcomeText(lastResolved, copy)
8208
+ ] }),
8209
+ nextStep && /* @__PURE__ */ jsxRuntime.jsxs("p", { className: "pollar-outcome-note", children: [
8210
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "pollar-spinner pollar-spinner-sm", "aria-hidden": true }),
8211
+ " ",
8212
+ copy.next(nextStep)
8213
+ ] }),
8214
+ closesIn !== null && /* @__PURE__ */ jsxRuntime.jsx("p", { className: "pollar-outcome-note", children: copy.closingIn(closesIn) })
8215
+ ] })
8216
+ ] }) : /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pollar-cosign-empty", children: [
8217
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "pollar-cosign-muted", children: copy.nothingWaiting }),
8218
+ closesIn !== null && /* @__PURE__ */ jsxRuntime.jsx("p", { className: "pollar-cosign-muted pollar-cosign-closing", children: copy.closingIn(closesIn) })
8219
+ ] })),
8220
+ grouped && /* @__PURE__ */ jsxRuntime.jsx("ul", { className: "pollar-cosign-list", children: pending.map((r) => /* @__PURE__ */ jsxRuntime.jsx("li", { children: /* @__PURE__ */ jsxRuntime.jsxs(
8221
+ "button",
8222
+ {
8223
+ type: "button",
8224
+ className: `pollar-cosign-item${current?.id === r.id ? " pollar-cosign-item-active" : ""}`,
8225
+ onClick: () => onSelect(r),
8226
+ children: [
8227
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "pollar-cosign-heading", children: [
8228
+ /* @__PURE__ */ jsxRuntime.jsx(TitleMark, { chain: r.network, asset: headlineAsset(reviewOf(r)) }),
8229
+ reviewOf(r).title
8230
+ ] }),
8231
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "pollar-cosign-muted", children: expiresIn(r, copy) })
8232
+ ]
8233
+ }
8234
+ ) }, r.id)) }),
8235
+ current && review && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: `pollar-cosign-detail${grouped ? " pollar-cosign-detail-grouped" : ""}`, children: [
8236
+ grouped && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pollar-cosign-detail-head", children: [
8237
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "pollar-cosign-detail-title", children: review.title }),
8238
+ chip
8239
+ ] }),
8240
+ /* @__PURE__ */ jsxRuntime.jsx(
8241
+ TxReview,
8242
+ {
8243
+ data: review,
8244
+ language,
8245
+ detailsIntro: { title: copy.whyTitle, body: copy.whyBody },
8246
+ detailsAction: {
8247
+ label: busy === "rejecting" ? copy.rejecting : copy.rejectRequest,
8248
+ onClick: () => onReject(current),
8249
+ disabled: !!busy
8250
+ }
8251
+ },
8252
+ current.id
8253
+ ),
8254
+ verified && verifiedOpen && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "pollar-cosign-verify pollar-cosign-verify-ok", children: copy.checkedExact }),
8255
+ deviceNotLinked ? /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pollar-cosign-verify pollar-cosign-verify-bad", children: [
8256
+ copy.deviceNotLinked,
8257
+ onLinkDevice && /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", className: "pollar-cosign-link", onClick: onLinkDevice, children: copy.linkDevice })
8258
+ ] }) : verification && !verification.ok && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pollar-cosign-verify pollar-cosign-verify-bad", children: [
8259
+ copy.notVerified,
8260
+ " ",
8261
+ verification.reason
8262
+ ] }),
8263
+ error && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "pollar-cosign-error", children: error }),
8264
+ /* @__PURE__ */ jsxRuntime.jsx(
8265
+ "button",
8266
+ {
8267
+ type: "button",
8268
+ className: "pollar-cosign-btn pollar-cosign-btn-primary",
8269
+ disabled: !canVote,
8270
+ onClick: () => onApprove(current),
8271
+ children: busy === "approving" ? copy.approving : review.kind === "activate_wallet" ? copy.activateWallet : copy.approve
8272
+ }
8273
+ )
8274
+ ] })
8275
+ ] }),
8276
+ !inline && /* @__PURE__ */ jsxRuntime.jsx(PollarModalFooter, {})
8277
+ ]
8130
8278
  }
8131
- }
8132
- function handleVerifyRoute(requirement) {
8133
- setErrorMsg(null);
8134
- verifyAttempt.current = requirement;
8135
- setVerifying(requirement);
8136
- }
8137
- function closeVerification() {
8138
- verifyAttempt.current = null;
8139
- setVerifying(null);
8140
- }
8141
- function verificationDone(requirement) {
8142
- if (verifyAttempt.current !== requirement) return;
8143
- closeVerification();
8144
- void handleFindRoute();
8145
- }
8146
- async function handleTrustAsset(asset2) {
8147
- if (trustingAsset) return;
8148
- setTrustingAsset(`${asset2.code}:${asset2.issuer}`);
8149
- setErrorMsg(null);
8150
- try {
8151
- const outcome = await client.setTrustline(asset2);
8152
- if (outcome.status === "error") {
8153
- setErrorMsg(core.rampTrustlineErrorText(outcome, asset2.code, language));
8154
- return;
8155
- }
8156
- if (outcome.status === "cosign_pending") {
8157
- setErrorMsg(copy.approveTrustline(asset2.code));
8158
- openCosignModal();
8159
- return;
8160
- }
8161
- await client.refreshAssets().catch(() => {
8162
- });
8163
- await handleFindRoute();
8164
- } catch (error) {
8165
- setErrorMsg(rampErrorMessage(error, copy.addTrustlineFailed(asset2.code), copy, language));
8166
- } finally {
8167
- setTrustingAsset(null);
8279
+ );
8280
+ }
8281
+ var CLOSE_AFTER_SECONDS = 3;
8282
+ var CLOSE_AFTER_SENT_SECONDS = 5;
8283
+ var NEXT_REQUEST_EVERY_MS = 2e3;
8284
+ function CosignModal(props) {
8285
+ const { styles } = usePollar();
8286
+ const { overlayStyle } = modalChrome(styles);
8287
+ return /* @__PURE__ */ jsxRuntime.jsx(PollarOverlay, { style: overlayStyle, children: /* @__PURE__ */ jsxRuntime.jsx(CosignPrompt, { ...props }) });
8288
+ }
8289
+ function CosignPrompt({ nextStep = null, onClose, inline = false }) {
8290
+ const { getClient, styles, network, openRecoveryModal } = usePollar();
8291
+ const { theme, accentColor, styleOverrides } = modalChrome(styles);
8292
+ const { pending, lastResolved, loaded, refresh, approve, reject, verify, inspectQuorum } = useCosign();
8293
+ const language = useModalLanguage();
8294
+ const [selectedId, setSelectedId] = react.useState(null);
8295
+ const [verification, setVerification] = react.useState(null);
8296
+ const [busy, setBusy] = react.useState(null);
8297
+ const [error, setError] = react.useState(null);
8298
+ const [approveFailedFor, setApproveFailedFor] = react.useState(null);
8299
+ const [quorumFailure, setQuorumFailure] = react.useState(null);
8300
+ const [deviceNotLinked, setDeviceNotLinked] = react.useState(false);
8301
+ react.useEffect(() => {
8302
+ let cancelled = false;
8303
+ inspectQuorum().then((q) => {
8304
+ if (cancelled || q.ok) return;
8305
+ if (q.code === "DEVICE_NOT_ENROLLED") setDeviceNotLinked(true);
8306
+ else setQuorumFailure(q.reason);
8307
+ }).catch(() => void 0);
8308
+ return () => {
8309
+ cancelled = true;
8310
+ };
8311
+ }, [inspectQuorum]);
8312
+ const current = pending.find((r) => r.id === selectedId) ?? pending[0] ?? null;
8313
+ const [history, setHistory] = react.useState([]);
8314
+ const resolvedBeforeOpen = react.useRef(lastResolved?.id);
8315
+ react.useEffect(() => {
8316
+ if (!lastResolved || lastResolved.id === resolvedBeforeOpen.current) return;
8317
+ setHistory((list) => [...list.filter((r) => r.id !== lastResolved.id), lastResolved]);
8318
+ }, [lastResolved]);
8319
+ const [askedToClose, setAskedToClose] = react.useState(false);
8320
+ const confirmingClose = askedToClose && pending.length > 0;
8321
+ const requestClose = () => pending.length > 0 ? setAskedToClose(true) : onClose();
8322
+ const currentRef = react.useRef(current);
8323
+ currentRef.current = current;
8324
+ const currentId = current?.id ?? null;
8325
+ react.useEffect(() => {
8326
+ const request = currentRef.current;
8327
+ if (!request) return;
8328
+ setVerification(null);
8329
+ setError(null);
8330
+ setApproveFailedFor(null);
8331
+ let cancelled = false;
8332
+ verify(request).then((v) => {
8333
+ if (!cancelled) setVerification(v);
8334
+ }).catch((err) => {
8335
+ if (!cancelled) setVerification({ ok: false, reason: err instanceof Error ? err.message : String(err) });
8336
+ });
8337
+ return () => {
8338
+ cancelled = true;
8339
+ };
8340
+ }, [currentId, verify]);
8341
+ const onCloseRef = react.useRef(onClose);
8342
+ onCloseRef.current = onClose;
8343
+ react.useEffect(() => {
8344
+ return getClient().onAuthStateChange((authState) => {
8345
+ if (authState.step === "idle") onCloseRef.current();
8346
+ });
8347
+ }, [getClient]);
8348
+ const silent = pending.length === 0 && (lastResolved ? lastResolved.status === "APPROVED" && !lastResolved.submit?.hash && !lastResolved.signedXdr : loaded);
8349
+ const sent = pending.length === 0 && lastResolved?.status === "APPROVED" && !!lastResolved.submit?.hash;
8350
+ const awaitingNext = sent && !!nextStep;
8351
+ const closeAfter = awaitingNext ? null : sent ? CLOSE_AFTER_SENT_SECONDS : silent ? CLOSE_AFTER_SECONDS : null;
8352
+ react.useEffect(() => {
8353
+ if (!awaitingNext) return;
8354
+ return core.startBackoffPoll(refresh, NEXT_REQUEST_EVERY_MS);
8355
+ }, [awaitingNext, refresh]);
8356
+ const [closesIn, setClosesIn] = react.useState(null);
8357
+ react.useEffect(() => {
8358
+ if (closeAfter === null) {
8359
+ setClosesIn(null);
8360
+ return;
8168
8361
  }
8169
- }
8170
- async function handleWalletStep(walletStep, index, custody) {
8171
- if (walletBusy !== null) return;
8172
- setWalletBusy(index);
8173
- setErrorMsg(null);
8174
- try {
8175
- const { recoveryRequired } = await client.runRampWalletStep(walletStep, custody);
8176
- if (recoveryRequired) {
8177
- setErrorMsg(copy.addRecovery);
8178
- openRecoveryModal();
8179
- return;
8362
+ let left = closeAfter;
8363
+ setClosesIn(left);
8364
+ const timer = setInterval(() => {
8365
+ left -= 1;
8366
+ if (left > 0) setClosesIn(left);
8367
+ else {
8368
+ clearInterval(timer);
8369
+ onCloseRef.current();
8180
8370
  }
8181
- await handleFindRoute();
8182
- } catch (error) {
8183
- const code = core.isPollarApiError(error) ? error.code : null;
8184
- if (code === "SDK_RAMPS_WALLET_NOT_READY") {
8185
- setErrorMsg(copy.approveAccount);
8186
- openCosignModal();
8187
- return;
8371
+ }, 1e3);
8372
+ return () => clearInterval(timer);
8373
+ }, [closeAfter, lastResolved?.id]);
8374
+ const run = react.useCallback(
8375
+ async (kind, request, action) => {
8376
+ setBusy(kind);
8377
+ setError(null);
8378
+ try {
8379
+ await action(request);
8380
+ } catch (err) {
8381
+ if (core.isPollarNetworkError(err) || err instanceof TypeError) {
8382
+ setError(COSIGN_COPY[language].unreachable);
8383
+ void refresh().catch(() => void 0);
8384
+ return;
8385
+ }
8386
+ setError(
8387
+ core.transactionErrorMessage(core.isPollarApiError(err) ? err.code : null, err instanceof Error ? err.message : null, language)
8388
+ );
8389
+ const retryable = core.isTransientApiError(err) || core.isPollarApiError(err) && err.code === "SDK_COSIGN_GAS_PENDING";
8390
+ if (kind === "approving" && !retryable) setApproveFailedFor(request.id);
8391
+ } finally {
8392
+ setBusy(null);
8188
8393
  }
8189
- setErrorMsg(
8190
- code === "SDK_WALLET_PROVISIONING_DISABLED" ? copy.noWalletCreation : rampErrorMessage(error, copy.prepareWalletFailed, copy, language)
8191
- );
8192
- } finally {
8193
- setWalletBusy(null);
8394
+ },
8395
+ [language, refresh]
8396
+ );
8397
+ return /* @__PURE__ */ jsxRuntime.jsx(
8398
+ CosignModalTemplate,
8399
+ {
8400
+ inline,
8401
+ theme,
8402
+ accentColor,
8403
+ styleOverrides,
8404
+ pending,
8405
+ current,
8406
+ verification: current ? quorumFailure ? { ok: false, reason: quorumFailure } : verification : null,
8407
+ busy,
8408
+ error,
8409
+ approveBlocked: !!current && approveFailedFor === current.id,
8410
+ deviceNotLinked,
8411
+ onLinkDevice: () => {
8412
+ onClose();
8413
+ openRecoveryModal();
8414
+ },
8415
+ ...lastResolved ? { lastResolved } : {},
8416
+ closesIn,
8417
+ nextStep: awaitingNext ? nextStep : null,
8418
+ language,
8419
+ network,
8420
+ history,
8421
+ explorerUrlOf: (r) => r.submit?.hash ? explorerTxUrl(r.network, r.submit.hash, network) : null,
8422
+ onSelect: (r) => setSelectedId(r.id),
8423
+ onApprove: (r) => void run("approving", r, approve),
8424
+ onReject: (r) => void run("rejecting", r, reject),
8425
+ onClose: requestClose,
8426
+ confirmingClose,
8427
+ onKeepOpen: () => setAskedToClose(false),
8428
+ onCloseAnyway: onClose
8194
8429
  }
8430
+ );
8431
+ }
8432
+ var PAYMENT_CHECK_EVERY_MS = 1e4;
8433
+ var PAYMENT_CHECK_WINDOW_MS = 2 * 6e4;
8434
+ function rampErrorMessage(error, fallback, copy, language) {
8435
+ const unavailable = core.appUnavailableMessage(error, language);
8436
+ if (unavailable) return unavailable;
8437
+ if (core.isPollarApiError(error)) {
8438
+ const known = copy.errors[error.code];
8439
+ if (known) return known;
8440
+ const message = error.body.message;
8441
+ if (typeof message === "string" && message && !/^[A-Z0-9_]+$/.test(message)) return message;
8195
8442
  }
8196
- async function resumeRoute(key) {
8197
- const same = (await handleFindRoute()).find((q) => routeKey(q) === key);
8198
- if (same) handleSelectQuote(same, true);
8199
- else setErrorMsg(copy.routeGone);
8200
- }
8201
- function handleSelectQuote(quote, fresh = false) {
8202
- if (!fresh && Date.parse(quote.expiresAt) <= Date.now()) {
8203
- void resumeRoute(routeKey(quote));
8204
- return;
8443
+ return fallback;
8444
+ }
8445
+ var DECIMAL = /^\d+(\.\d+)?$/;
8446
+ var QUOTE_DEBOUNCE_MS = 600;
8447
+ function seededSelection(routes, seed) {
8448
+ const countries = core.rampCountries(routes);
8449
+ const wanted = seed.country?.trim().toUpperCase();
8450
+ const country = wanted ? countries.find((c) => c.country === wanted) : countries[0];
8451
+ if (!country) return null;
8452
+ const fiat = country.fiats.find((f) => f.currency === seed.fiat?.trim().toUpperCase()) ?? null;
8453
+ const resolvedFiat = fiat ?? country.fiats[0];
8454
+ const asset = routes.find(
8455
+ (r) => r.fiat.country === country.country && resolvedFiat !== void 0 && fiatKey(r.fiat) === fiatKey(resolvedFiat) && r.asset.code.toUpperCase() === seed.asset?.trim().toUpperCase()
8456
+ )?.asset;
8457
+ const amount = seed.amount?.trim() ?? "";
8458
+ return {
8459
+ country: country.country,
8460
+ fiatChoice: fiat ? fiatKey(fiat) : "",
8461
+ assetChoice: asset ? assetKey3(asset) : "",
8462
+ amount: DECIMAL.test(amount) ? amount : ""
8463
+ };
8464
+ }
8465
+ async function signLegWithWallet(client, orderId, actionId, copy) {
8466
+ const lent = [];
8467
+ const lend = (chain, encoding, handler) => {
8468
+ try {
8469
+ lent.push(client.registerRampSigningHandler(chain, encoding, handler));
8470
+ } catch {
8205
8471
  }
8206
- setSelected(quote);
8207
- setErrorMsg(null);
8208
- const missing = core.rampQuoteFields(quote).some((f) => !f.optional && !(fieldValues[f.key] ?? "").trim());
8209
- if (missing) setStep("contact");
8210
- else void startOrder(quote, fresh);
8211
- }
8212
- async function startOrder(quote, fresh = false) {
8213
- setIsLoading(true);
8214
- setStartingQuoteId(quote.quoteId);
8215
- setErrorMsg(null);
8216
- setAwaitingAccount(null);
8217
- try {
8218
- const payee = Object.fromEntries(
8219
- core.rampQuoteFields(quote).map((f) => [f.key, (fieldValues[f.key] ?? "").trim()]).filter(([, value]) => value)
8220
- );
8221
- const created = await client.createRampOrder({
8222
- quoteId: quote.quoteId,
8223
- ...Object.keys(payee).length ? { payee } : {}
8224
- });
8225
- setOrder(created);
8226
- setStep("status");
8227
- } catch (error) {
8228
- if (core.isPollarApiError(error) && error.code === "SDK_RAMPS_WALLET_NOT_READY") {
8229
- const pending = await client.cosign.pending().catch(() => []);
8230
- const request = pending.find((r) => r.intent === "add_accounts");
8231
- if (request) setAwaitingAccount({ routeKey: routeKey(quote), requestId: request.id });
8232
- else setErrorMsg(rampErrorMessage(error, copy.startOrderFailed, copy, language));
8233
- openCosignModal();
8234
- setStep("select_route");
8235
- return;
8236
- }
8237
- if (core.isPollarApiError(error) && error.code === "SDK_RAMPS_QUOTE_EXPIRED" && !fresh) {
8238
- void resumeRoute(routeKey(quote));
8239
- return;
8472
+ };
8473
+ lend("STELLAR", "xdr", async (action) => {
8474
+ const wallet = client.getWallet();
8475
+ if (!wallet) throw new Error(copy.connectStellarWallet);
8476
+ core.assertRampStellarSigner(action, wallet.address);
8477
+ const outcome = await client.signTx(action.payload.value);
8478
+ if (client.getWallet()?.address !== wallet.address) throw new Error(copy.walletChanged);
8479
+ if (outcome.status === "signed") return outcome.signedXdr;
8480
+ throw new Error(
8481
+ outcome.status === "error" ? outcome.message ?? outcome.details ?? copy.signingCancelled : copy.signingCancelled
8482
+ );
8483
+ });
8484
+ lend("SOLANA", "solana-v0-json", async (action) => {
8485
+ const payload = JSON.parse(action.payload.value);
8486
+ const solanaWallet = () => client.getWallets().find((w) => w.chain === "SOLANA" && w.custody === "external");
8487
+ const wallet = solanaWallet();
8488
+ if (!wallet || payload.from !== wallet.address || !payload.unsignedTransaction) throw new Error(copy.solanaWalletMismatch);
8489
+ const signed = await client.signSolanaTransaction(payload.unsignedTransaction);
8490
+ if (solanaWallet()?.address !== wallet.address) throw new Error(copy.walletChanged);
8491
+ return signed;
8492
+ });
8493
+ try {
8494
+ return await client.signRampLeg(orderId, actionId);
8495
+ } finally {
8496
+ for (const release of lent) release();
8497
+ }
8498
+ }
8499
+ function RampWidget({ onClose, language: languageProp, initial }) {
8500
+ const {
8501
+ getClient,
8502
+ styles,
8503
+ network,
8504
+ openCosignModal,
8505
+ setCosignNextStep,
8506
+ openRecoveryModal,
8507
+ recovery,
8508
+ recoveryLocked,
8509
+ appConfig,
8510
+ cosign,
8511
+ refreshWalletBalance,
8512
+ registerCosignHost
8513
+ } = usePollar();
8514
+ const client = getClient();
8515
+ const language = useModalLanguage(languageProp);
8516
+ const copy = RAMP_COPY[language];
8517
+ const { theme, accentColor, styleOverrides, overlayStyle } = modalChrome(styles);
8518
+ const [step, setStep] = react.useState("input");
8519
+ const confirmation = useInlineConfirmation(step === "status");
8520
+ const [direction, setDirection] = react.useState(initial?.direction === "sell" ? "OFFRAMP" : "ONRAMP");
8521
+ const seedRef = react.useRef(
8522
+ initial ? { direction: initial.direction === "sell" ? "OFFRAMP" : "ONRAMP", options: initial } : null
8523
+ );
8524
+ const [routes, setRoutes] = react.useState([]);
8525
+ const [routesLoading, setRoutesLoading] = react.useState(true);
8526
+ const [country, setCountry] = react.useState("");
8527
+ const [fiatChoice, setFiatChoice] = react.useState("");
8528
+ const [assetChoice, setAssetChoice] = react.useState("");
8529
+ const [amount, setAmount] = react.useState("");
8530
+ const [quotes, setQuotes] = react.useState([]);
8531
+ const [rejected, setRejected] = react.useState([]);
8532
+ const [selected, setSelected] = react.useState(null);
8533
+ const [startingQuoteId, setStartingQuoteId] = react.useState(null);
8534
+ const [fieldValues, setFieldValues] = react.useState({});
8535
+ const [order, setOrder] = react.useState(null);
8536
+ const [pendingOrders, setPendingOrders] = react.useState([]);
8537
+ const [isLoading, setIsLoading] = react.useState(false);
8538
+ const [refreshing, setRefreshing] = react.useState(false);
8539
+ const [signing, setSigning] = react.useState(false);
8540
+ const [errorMsg, setErrorMsg] = react.useState(null);
8541
+ const [verifying, setVerifying] = react.useState(null);
8542
+ const [trustingAsset, setTrustingAsset] = react.useState(null);
8543
+ const [walletBusy, setWalletBusy] = react.useState(null);
8544
+ const [retrying, setRetrying] = react.useState(false);
8545
+ const [cancelling, setCancelling] = react.useState(false);
8546
+ const [cancelError, setCancelError] = react.useState(null);
8547
+ const [awaitingAccount, setAwaitingAccount] = react.useState(null);
8548
+ const [pollTrouble, setPollTrouble] = react.useState(false);
8549
+ const [pollKey, setPollKey] = react.useState(0);
8550
+ const [paymentCheckUntil, setPaymentCheckUntil] = react.useState(null);
8551
+ const checkErrorRef = react.useRef(null);
8552
+ const promptedApproval = react.useRef(null);
8553
+ const custodyChoice = appConfig.application?.walletCustodyMode === "USER_CHOICE";
8554
+ const appChains = appConfig.application?.chains;
8555
+ const verifyAttempt = react.useRef(null);
8556
+ const countries = react.useMemo(() => core.rampCountries(routes), [routes]);
8557
+ const fiats = countries.find((c) => c.country === country)?.fiats ?? [];
8558
+ const fiat = fiats.find((f) => fiatKey(f) === fiatChoice) ?? fiats[0] ?? null;
8559
+ const assets = react.useMemo(() => {
8560
+ const seen = /* @__PURE__ */ new Map();
8561
+ for (const route of routes)
8562
+ if (fiat && route.fiat.country === country && fiatKey(route.fiat) === fiatKey(fiat))
8563
+ seen.set(assetKey3(route.asset), route.asset);
8564
+ return [...seen.values()];
8565
+ }, [routes, country, fiat]);
8566
+ const asset = assets.find((a) => assetKey3(a) === assetChoice) ?? assets[0] ?? null;
8567
+ const fields = selected ? core.rampQuoteFields(selected, language) : [];
8568
+ const sellAvailable = useWalletAvailable(
8569
+ direction === "OFFRAMP" && asset ? { chain: asset.chain, code: asset.code, issuer: asset.identifier } : null
8570
+ );
8571
+ const [quoting, setQuoting] = react.useState(false);
8572
+ const [routeChoice, setRouteChoice] = react.useState(BEST_ROUTE);
8573
+ const quoteRun = react.useRef(0);
8574
+ const quoteInput = step === "input" && fiat && asset && DECIMAL.test(amount.trim()) && Number(amount) > 0;
8575
+ const quoteKey = quoteInput ? `${direction}|${fiatKey(fiat)}|${assetKey3(asset)}|${amount.trim()}` : null;
8576
+ react.useEffect(() => {
8577
+ const run = ++quoteRun.current;
8578
+ if (!quoteKey || !fiat || !asset) {
8579
+ setQuoting(false);
8580
+ if (step === "input") {
8581
+ setQuotes([]);
8582
+ setRejected([]);
8240
8583
  }
8241
- setErrorMsg(rampErrorMessage(error, copy.startOrderFailed, copy, language));
8242
- if (core.isPollarApiError(error) && error.code === "VALIDATION_ERROR" && core.rampQuoteFields(quote).length) setStep("contact");
8243
- else setStep("select_route");
8244
- } finally {
8245
- setIsLoading(false);
8246
- setStartingQuoteId(null);
8584
+ return;
8247
8585
  }
8248
- }
8249
- async function handleSign() {
8250
- const action = order?.pendingAction;
8251
- if (!order || action?.kind !== "SIGNATURE" || signing) return;
8252
- setSigning(true);
8253
- setErrorMsg(null);
8586
+ setQuoting(true);
8587
+ const timer = setTimeout(() => {
8588
+ client.quoteRamp({
8589
+ direction,
8590
+ fiat: { currency: fiat.currency, rail: fiat.rail, country: fiat.country },
8591
+ asset: { code: asset.code, identifier: asset.identifier, chain: asset.chain },
8592
+ amount: { value: amount.trim(), denomination: "in" }
8593
+ }).then((result) => {
8594
+ if (run !== quoteRun.current) return;
8595
+ setQuotes(result.quotes);
8596
+ setRejected(result.rejected);
8597
+ setErrorMsg(null);
8598
+ }).catch((error) => {
8599
+ if (run !== quoteRun.current) return;
8600
+ setQuotes([]);
8601
+ if (core.isPollarApiError(error) && error.code === "SDK_RAMPS_NO_ROUTE") {
8602
+ setRejected(Array.isArray(error.body.rejected) ? error.body.rejected : []);
8603
+ } else {
8604
+ setRejected([]);
8605
+ setErrorMsg(rampErrorMessage(error, copy.findRouteFailed, copy, language));
8606
+ }
8607
+ }).finally(() => {
8608
+ if (run === quoteRun.current) setQuoting(false);
8609
+ });
8610
+ }, QUOTE_DEBOUNCE_MS);
8611
+ return () => clearTimeout(timer);
8612
+ }, [quoteKey]);
8613
+ const chosenQuote = (routeChoice !== BEST_ROUTE ? quotes.find((q) => routeKey(q) === routeChoice) : void 0) ?? quotes[0] ?? null;
8614
+ react.useEffect(() => {
8615
+ if (direction === "OFFRAMP") void refreshWalletBalance();
8616
+ }, [direction, refreshWalletBalance]);
8617
+ async function loadRoutes(next) {
8618
+ setRoutesLoading(true);
8254
8619
  try {
8255
- setOrder(await signLegWithWallet(client, order.id, action.actionId, copy));
8620
+ const { routes: found } = await client.getRampRoutes(next);
8621
+ setRoutes(found);
8622
+ const seed = seedRef.current?.direction === next ? seedRef.current.options : null;
8623
+ if (seed) seedRef.current = null;
8624
+ const seeded = seed ? seededSelection(found, seed) : null;
8625
+ if (seeded) {
8626
+ setCountry(seeded.country);
8627
+ setFiatChoice(seeded.fiatChoice);
8628
+ setAssetChoice(seeded.assetChoice);
8629
+ setAmount(seeded.amount);
8630
+ return;
8631
+ }
8632
+ const first = core.rampCountries(found)[0]?.country ?? "";
8633
+ setCountry((current) => found.some((r) => r.fiat.country === current) ? current : first);
8256
8634
  } catch (error) {
8257
- setErrorMsg(
8258
- rampErrorMessage(
8259
- error,
8260
- error instanceof Error && error.message ? error.message : copy.signingCancelled,
8261
- copy,
8262
- language
8263
- )
8264
- );
8265
- setOrder(await client.getRampOrder(order.id).catch(() => order));
8635
+ setRoutes([]);
8636
+ setErrorMsg(rampErrorMessage(error, copy.loadRoutesFailed, copy, language));
8266
8637
  } finally {
8267
- setSigning(false);
8638
+ setRoutesLoading(false);
8268
8639
  }
8269
8640
  }
8270
- async function handleResumeOrder(id) {
8271
- setIsLoading(true);
8272
- setErrorMsg(null);
8641
+ async function loadPendingOrders() {
8273
8642
  try {
8274
- const found = await client.getRampOrder(id);
8275
- seedRef.current = null;
8276
- setDirection(found.direction);
8277
- setOrder(found);
8278
- setStep("status");
8279
- } catch (error) {
8280
- setErrorMsg(rampErrorMessage(error, copy.resumeOrderFailed, copy, language));
8281
- } finally {
8282
- setIsLoading(false);
8643
+ const page = await client.listRampOrders({ open: "true", limit: 5 });
8644
+ setPendingOrders(page.orders);
8645
+ } catch {
8646
+ setPendingOrders([]);
8283
8647
  }
8284
8648
  }
8285
- function handleNewOrder() {
8286
- setAwaitingAccount(null);
8287
- setOrder(null);
8288
- setSelected(null);
8289
- setQuotes([]);
8290
- setRejected([]);
8291
- setErrorMsg(null);
8292
- setStep("input");
8649
+ react.useEffect(() => {
8650
+ void loadRoutes(direction);
8651
+ }, [client, direction]);
8652
+ react.useEffect(() => {
8293
8653
  void loadPendingOrders();
8294
- }
8295
- function handleBack() {
8296
- setErrorMsg(null);
8297
- setAwaitingAccount(null);
8298
- setStep(step === "contact" ? "select_route" : "input");
8299
- }
8300
- function handleStepSelect(target) {
8301
- setErrorMsg(null);
8302
- setAwaitingAccount(null);
8303
- setStep(target === copy.steps.route ? "select_route" : "input");
8304
- }
8305
- async function handleCheckPayment() {
8306
- if (!order || paymentCheckUntil !== null) return;
8307
- setErrorMsg(null);
8308
- setPaymentCheckUntil(Date.now() + PAYMENT_CHECK_WINDOW_MS);
8309
- try {
8310
- setOrder(await client.checkRampOrder(order.id));
8311
- } catch (error) {
8312
- if (core.isPollarNetworkError(error)) return;
8654
+ }, [client]);
8655
+ const orderId = order?.id ?? null;
8656
+ react.useEffect(() => {
8657
+ if (step !== "status" || !orderId) return;
8658
+ const controller = new AbortController();
8659
+ client.pollRampOrder(orderId, {
8660
+ signal: controller.signal,
8661
+ onUpdate: (next) => {
8662
+ setOrder(next);
8663
+ setPollTrouble(false);
8664
+ },
8665
+ onError: () => setPollTrouble(true)
8666
+ }).catch((error) => {
8667
+ if (!controller.signal.aborted) setErrorMsg(rampErrorMessage(error, copy.readOrderFailed, copy, language));
8668
+ });
8669
+ return () => controller.abort();
8670
+ }, [client, step, orderId, pollKey]);
8671
+ const awaitingPayment = step === "status" && order?.pendingAction?.kind === "FIAT_PAYMENT";
8672
+ react.useEffect(() => {
8673
+ if (paymentCheckUntil === null || !orderId) return;
8674
+ if (!awaitingPayment) {
8313
8675
  setPaymentCheckUntil(null);
8314
- const message = rampErrorMessage(error, copy.checkPaymentFailed, copy, language);
8315
- checkErrorRef.current = message;
8316
- setErrorMsg(message);
8676
+ setPollKey((key) => key + 1);
8677
+ return;
8678
+ }
8679
+ return core.startBackoffPoll(async () => {
8680
+ if (Date.now() >= paymentCheckUntil) {
8681
+ setPaymentCheckUntil(null);
8682
+ return;
8683
+ }
8684
+ setOrder(await client.checkRampOrder(orderId));
8685
+ }, PAYMENT_CHECK_EVERY_MS);
8686
+ }, [client, orderId, awaitingPayment, paymentCheckUntil]);
8687
+ react.useEffect(() => {
8688
+ if (awaitingPayment || checkErrorRef.current === null) return;
8689
+ const shown = checkErrorRef.current;
8690
+ checkErrorRef.current = null;
8691
+ setErrorMsg((current) => current === shown ? null : current);
8692
+ }, [awaitingPayment]);
8693
+ const hostsCosign = step === "status" && !!order && !["completed", "failed", "refunded"].includes(order.state);
8694
+ const hostsCosignRef = react.useRef(hostsCosign);
8695
+ hostsCosignRef.current = hostsCosign;
8696
+ react.useEffect(() => hostsCosign ? registerCosignHost() : void 0, [hostsCosign, registerCosignHost]);
8697
+ const approval = order?.pendingAction?.kind === "COSIGN_APPROVAL" ? order.pendingAction.actionId : null;
8698
+ const approvalRequest = order?.pendingAction?.kind === "COSIGN_APPROVAL" ? order.pendingAction.cosignRequestId : null;
8699
+ react.useEffect(() => {
8700
+ if (!approval || promptedApproval.current === approval) return;
8701
+ promptedApproval.current = approval;
8702
+ void client.cosign.pending().catch(() => []).then(async (requests) => {
8703
+ const request = requests.find((r) => r.id === approvalRequest);
8704
+ if (request && await client.autoApproveSignIn(request)) return;
8705
+ if (!hostsCosignRef.current) openCosignModal();
8706
+ });
8707
+ }, [approval, approvalRequest, client, openCosignModal]);
8708
+ const nextApproval = step === "status" && order ? core.rampNextApproval(order, language) : null;
8709
+ react.useEffect(() => {
8710
+ setCosignNextStep(nextApproval);
8711
+ }, [nextApproval, setCosignNextStep]);
8712
+ react.useEffect(() => () => setCosignNextStep(null), [setCosignNextStep]);
8713
+ const resolvedRequest = cosign.lastResolved;
8714
+ react.useEffect(() => {
8715
+ if (!awaitingAccount || resolvedRequest?.id !== awaitingAccount.requestId) return;
8716
+ setAwaitingAccount(null);
8717
+ if (resolvedRequest.status !== "APPROVED") {
8718
+ setErrorMsg(copy.accountNotApproved);
8719
+ return;
8317
8720
  }
8721
+ void resumeRoute(awaitingAccount.routeKey);
8722
+ }, [awaitingAccount, resolvedRequest]);
8723
+ function handleDirectionChange(next) {
8724
+ seedRef.current = null;
8725
+ setDirection(next);
8726
+ setErrorMsg(null);
8727
+ setAwaitingAccount(null);
8318
8728
  }
8319
- async function handleRetryOrder() {
8320
- if (!order || retrying) return;
8321
- setRetrying(true);
8729
+ async function handleFindRoute() {
8730
+ if (!fiat || !asset) return [];
8731
+ if (!DECIMAL.test(amount.trim()) || Number(amount) <= 0) {
8732
+ setErrorMsg(copy.amountInvalid);
8733
+ return [];
8734
+ }
8735
+ setStep("loading_quote");
8322
8736
  setErrorMsg(null);
8737
+ setSelected(null);
8323
8738
  try {
8324
- setOrder(await client.retryRampOrder(order.id));
8325
- setPollKey((key) => key + 1);
8739
+ const result = await client.quoteRamp({
8740
+ direction,
8741
+ fiat: { currency: fiat.currency, rail: fiat.rail, country: fiat.country },
8742
+ asset: { code: asset.code, identifier: asset.identifier, chain: asset.chain },
8743
+ amount: { value: amount.trim(), denomination: "in" }
8744
+ });
8745
+ setQuotes(result.quotes);
8746
+ setRejected(result.rejected);
8747
+ setStep("select_route");
8748
+ return result.quotes;
8326
8749
  } catch (error) {
8327
- setErrorMsg(rampErrorMessage(error, copy.retryOrderFailed, copy, language));
8328
- } finally {
8329
- setRetrying(false);
8750
+ if (core.isPollarApiError(error) && error.code === "SDK_RAMPS_NO_ROUTE") {
8751
+ setQuotes([]);
8752
+ setRejected(Array.isArray(error.body.rejected) ? error.body.rejected : []);
8753
+ setStep("select_route");
8754
+ return [];
8755
+ }
8756
+ setErrorMsg(rampErrorMessage(error, copy.findRouteFailed, copy, language));
8757
+ setStep("error");
8758
+ return [];
8330
8759
  }
8331
8760
  }
8332
- async function handleCancelOrder() {
8333
- if (!order || cancelling) return;
8334
- setCancelling(true);
8335
- setCancelError(null);
8761
+ function handleVerifyRoute(requirement) {
8762
+ setErrorMsg(null);
8763
+ verifyAttempt.current = requirement;
8764
+ setVerifying(requirement);
8765
+ }
8766
+ function closeVerification() {
8767
+ verifyAttempt.current = null;
8768
+ setVerifying(null);
8769
+ }
8770
+ function verificationDone(requirement) {
8771
+ if (verifyAttempt.current !== requirement) return;
8772
+ closeVerification();
8773
+ void handleFindRoute();
8774
+ }
8775
+ async function handleTrustAsset(asset2) {
8776
+ if (trustingAsset) return;
8777
+ setTrustingAsset(`${asset2.code}:${asset2.issuer}`);
8778
+ setErrorMsg(null);
8336
8779
  try {
8337
- setOrder(await client.cancelRampOrder(order.id));
8338
- void loadPendingOrders();
8780
+ const outcome = await client.setTrustline(asset2);
8781
+ if (outcome.status === "error") {
8782
+ setErrorMsg(core.rampTrustlineErrorText(outcome, asset2.code, language));
8783
+ return;
8784
+ }
8785
+ if (outcome.status === "cosign_pending") {
8786
+ setErrorMsg(copy.approveTrustline(asset2.code));
8787
+ openCosignModal();
8788
+ return;
8789
+ }
8790
+ await client.refreshAssets().catch(() => {
8791
+ });
8792
+ await handleFindRoute();
8339
8793
  } catch (error) {
8340
- setCancelError(rampErrorMessage(error, copy.cancelOrderFailed, copy, language));
8794
+ setErrorMsg(rampErrorMessage(error, copy.addTrustlineFailed(asset2.code), copy, language));
8341
8795
  } finally {
8342
- setCancelling(false);
8796
+ setTrustingAsset(null);
8343
8797
  }
8344
8798
  }
8345
- async function handleRequote() {
8346
- setOrder(null);
8347
- await handleFindRoute();
8348
- }
8349
- const heldForRecovery = step === "status" && order?.failure?.resolutionAction === "set_up_recovery";
8350
- const wasRecoveryLocked = react.useRef(recoveryLocked);
8351
- react.useEffect(() => {
8352
- if (heldForRecovery && wasRecoveryLocked.current && !recoveryLocked && recovery) void handleRetryOrder();
8353
- wasRecoveryLocked.current = recoveryLocked;
8354
- }, [heldForRecovery, recoveryLocked, recovery]);
8355
- async function handleRefresh() {
8356
- if (refreshing) return;
8357
- setRefreshing(true);
8799
+ async function handleWalletStep(walletStep, index, custody) {
8800
+ if (walletBusy !== null) return;
8801
+ setWalletBusy(index);
8802
+ setErrorMsg(null);
8358
8803
  try {
8359
- if (step === "status" && order) {
8360
- setOrder(await client.getRampOrder(order.id));
8361
- setPollKey((key) => key + 1);
8362
- } else if (step === "select_route") await handleFindRoute();
8363
- else {
8364
- await loadRoutes(direction);
8365
- await loadPendingOrders();
8366
- if (direction === "OFFRAMP") await refreshWalletBalance();
8804
+ const { recoveryRequired } = await client.runRampWalletStep(walletStep, custody);
8805
+ if (recoveryRequired) {
8806
+ setErrorMsg(copy.addRecovery);
8807
+ openRecoveryModal();
8808
+ return;
8367
8809
  }
8810
+ await handleFindRoute();
8368
8811
  } catch (error) {
8369
- setErrorMsg(rampErrorMessage(error, copy.refreshFailed, copy, language));
8812
+ const code = core.isPollarApiError(error) ? error.code : null;
8813
+ if (code === "SDK_RAMPS_WALLET_NOT_READY") {
8814
+ setErrorMsg(copy.approveAccount);
8815
+ openCosignModal();
8816
+ return;
8817
+ }
8818
+ setErrorMsg(
8819
+ code === "SDK_WALLET_PROVISIONING_DISABLED" ? copy.noWalletCreation : rampErrorMessage(error, copy.prepareWalletFailed, copy, language)
8820
+ );
8370
8821
  } finally {
8371
- setRefreshing(false);
8822
+ setWalletBusy(null);
8372
8823
  }
8373
8824
  }
8374
- const flowSteps = fields.length || quotes.some((q) => core.rampQuoteFields(q).length) ? [copy.steps.route, copy.steps.details, copy.steps.complete] : [copy.steps.route, copy.steps.complete];
8375
- const stepLabel = {
8376
- select_route: copy.steps.route,
8377
- contact: copy.steps.details
8378
- };
8379
- const label = stepLabel[step];
8380
- if (verifying) {
8381
- const progress = { progress: { position: verifying.completed + 1, total: verifying.total } };
8382
- const done = () => verificationDone(verifying);
8383
- if (verifying.type === "FORM")
8384
- return /* @__PURE__ */ jsxRuntime.jsx(
8385
- RequirementFormModal,
8386
- {
8387
- formId: verifying.optionId,
8388
- ...progress,
8389
- language: languageProp,
8390
- onClose: closeVerification,
8391
- onSubmitted: done
8392
- }
8393
- );
8394
- if (verifying.type === "REGISTRY_CHECK")
8395
- return /* @__PURE__ */ jsxRuntime.jsx(
8396
- RegistryCheckModal,
8397
- {
8398
- optionId: verifying.optionId,
8399
- ...progress,
8400
- language: languageProp,
8401
- onClose: closeVerification,
8402
- onApproved: done
8403
- }
8404
- );
8405
- if (verifying.type === "PROVIDER_REGISTRATION")
8406
- return /* @__PURE__ */ jsxRuntime.jsx(
8407
- ProviderRegistrationModal,
8408
- {
8409
- corridorId: verifying.corridorId,
8410
- ...progress,
8411
- language: languageProp,
8412
- onClose: closeVerification,
8413
- onRegistered: done
8414
- }
8415
- );
8416
- return /* @__PURE__ */ jsxRuntime.jsx(
8417
- KycModal,
8418
- {
8419
- country,
8420
- corridorId: verifying.corridorId,
8421
- providerId: verifying.optionId,
8422
- language: languageProp,
8423
- onClose: closeVerification,
8424
- onApproved: done
8425
- }
8426
- );
8825
+ async function resumeRoute(key) {
8826
+ const same = (await handleFindRoute()).find((q) => routeKey(q) === key);
8827
+ if (same) handleSelectQuote(same, true);
8828
+ else setErrorMsg(copy.routeGone);
8427
8829
  }
8428
- return /* @__PURE__ */ jsxRuntime.jsx(PollarOverlay, { style: overlayStyle, onClick: step === "status" ? void 0 : onClose, children: /* @__PURE__ */ jsxRuntime.jsx(
8429
- RampWidgetTemplate,
8430
- {
8431
- language,
8432
- theme,
8433
- accentColor,
8434
- ...styleOverrides ? { styleOverrides } : {},
8435
- network,
8436
- step,
8437
- flowSteps,
8830
+ function handleSelectQuote(quote, fresh = false) {
8831
+ if (!fresh && Date.parse(quote.expiresAt) <= Date.now()) {
8832
+ void resumeRoute(routeKey(quote));
8833
+ return;
8834
+ }
8835
+ setSelected(quote);
8836
+ setErrorMsg(null);
8837
+ const missing = core.rampQuoteFields(quote).some((f) => !f.optional && !(fieldValues[f.key] ?? "").trim());
8838
+ if (missing) setStep("contact");
8839
+ else void startOrder(quote, fresh);
8840
+ }
8841
+ async function startOrder(quote, fresh = false) {
8842
+ setIsLoading(true);
8843
+ setStartingQuoteId(quote.quoteId);
8844
+ setErrorMsg(null);
8845
+ setAwaitingAccount(null);
8846
+ try {
8847
+ const payee = Object.fromEntries(
8848
+ core.rampQuoteFields(quote).map((f) => [f.key, (fieldValues[f.key] ?? "").trim()]).filter(([, value]) => value)
8849
+ );
8850
+ const created = await client.createRampOrder({
8851
+ quoteId: quote.quoteId,
8852
+ ...Object.keys(payee).length ? { payee } : {}
8853
+ });
8854
+ setOrder(created);
8855
+ setStep("status");
8856
+ } catch (error) {
8857
+ if (core.isPollarApiError(error) && error.code === "SDK_RAMPS_WALLET_NOT_READY") {
8858
+ const pending = await client.cosign.pending().catch(() => []);
8859
+ const request = pending.find((r) => r.intent === "add_accounts");
8860
+ if (request) setAwaitingAccount({ routeKey: routeKey(quote), requestId: request.id });
8861
+ else setErrorMsg(rampErrorMessage(error, copy.startOrderFailed, copy, language));
8862
+ openCosignModal();
8863
+ setStep("select_route");
8864
+ return;
8865
+ }
8866
+ if (core.isPollarApiError(error) && error.code === "SDK_RAMPS_QUOTE_EXPIRED" && !fresh) {
8867
+ void resumeRoute(routeKey(quote));
8868
+ return;
8869
+ }
8870
+ setErrorMsg(rampErrorMessage(error, copy.startOrderFailed, copy, language));
8871
+ if (core.isPollarApiError(error) && error.code === "VALIDATION_ERROR" && core.rampQuoteFields(quote).length) setStep("contact");
8872
+ else setStep("select_route");
8873
+ } finally {
8874
+ setIsLoading(false);
8875
+ setStartingQuoteId(null);
8876
+ }
8877
+ }
8878
+ async function handleSign() {
8879
+ const action = order?.pendingAction;
8880
+ if (!order || action?.kind !== "SIGNATURE" || signing) return;
8881
+ setSigning(true);
8882
+ setErrorMsg(null);
8883
+ try {
8884
+ setOrder(await signLegWithWallet(client, order.id, action.actionId, copy));
8885
+ } catch (error) {
8886
+ setErrorMsg(
8887
+ rampErrorMessage(
8888
+ error,
8889
+ error instanceof Error && error.message ? error.message : copy.signingCancelled,
8890
+ copy,
8891
+ language
8892
+ )
8893
+ );
8894
+ setOrder(await client.getRampOrder(order.id).catch(() => order));
8895
+ } finally {
8896
+ setSigning(false);
8897
+ }
8898
+ }
8899
+ async function handleResumeOrder(id) {
8900
+ setIsLoading(true);
8901
+ setErrorMsg(null);
8902
+ try {
8903
+ const found = await client.getRampOrder(id);
8904
+ seedRef.current = null;
8905
+ setDirection(found.direction);
8906
+ setOrder(found);
8907
+ setStep("status");
8908
+ } catch (error) {
8909
+ setErrorMsg(rampErrorMessage(error, copy.resumeOrderFailed, copy, language));
8910
+ } finally {
8911
+ setIsLoading(false);
8912
+ }
8913
+ }
8914
+ function handleNewOrder() {
8915
+ setAwaitingAccount(null);
8916
+ setOrder(null);
8917
+ setSelected(null);
8918
+ setQuotes([]);
8919
+ setRejected([]);
8920
+ setErrorMsg(null);
8921
+ setStep("input");
8922
+ void loadPendingOrders();
8923
+ }
8924
+ function handleBack() {
8925
+ setErrorMsg(null);
8926
+ setAwaitingAccount(null);
8927
+ setStep(step === "contact" ? "select_route" : "input");
8928
+ }
8929
+ function handleStepSelect(target) {
8930
+ setErrorMsg(null);
8931
+ setAwaitingAccount(null);
8932
+ setStep(target === copy.steps.route ? "select_route" : "input");
8933
+ }
8934
+ async function handleCheckPayment() {
8935
+ if (!order || paymentCheckUntil !== null) return;
8936
+ setErrorMsg(null);
8937
+ setPaymentCheckUntil(Date.now() + PAYMENT_CHECK_WINDOW_MS);
8938
+ try {
8939
+ setOrder(await client.checkRampOrder(order.id));
8940
+ } catch (error) {
8941
+ if (core.isPollarNetworkError(error)) return;
8942
+ setPaymentCheckUntil(null);
8943
+ const message = rampErrorMessage(error, copy.checkPaymentFailed, copy, language);
8944
+ checkErrorRef.current = message;
8945
+ setErrorMsg(message);
8946
+ }
8947
+ }
8948
+ async function handleRetryOrder() {
8949
+ if (!order || retrying) return;
8950
+ setRetrying(true);
8951
+ setErrorMsg(null);
8952
+ try {
8953
+ setOrder(await client.retryRampOrder(order.id));
8954
+ setPollKey((key) => key + 1);
8955
+ } catch (error) {
8956
+ setErrorMsg(rampErrorMessage(error, copy.retryOrderFailed, copy, language));
8957
+ } finally {
8958
+ setRetrying(false);
8959
+ }
8960
+ }
8961
+ async function handleCancelOrder() {
8962
+ if (!order || cancelling) return;
8963
+ setCancelling(true);
8964
+ setCancelError(null);
8965
+ try {
8966
+ setOrder(await client.cancelRampOrder(order.id));
8967
+ void loadPendingOrders();
8968
+ } catch (error) {
8969
+ setCancelError(rampErrorMessage(error, copy.cancelOrderFailed, copy, language));
8970
+ } finally {
8971
+ setCancelling(false);
8972
+ }
8973
+ }
8974
+ async function handleRequote() {
8975
+ setOrder(null);
8976
+ await handleFindRoute();
8977
+ }
8978
+ const heldForRecovery = step === "status" && order?.failure?.resolutionAction === "set_up_recovery";
8979
+ const wasRecoveryLocked = react.useRef(recoveryLocked);
8980
+ react.useEffect(() => {
8981
+ if (heldForRecovery && wasRecoveryLocked.current && !recoveryLocked && recovery) void handleRetryOrder();
8982
+ wasRecoveryLocked.current = recoveryLocked;
8983
+ }, [heldForRecovery, recoveryLocked, recovery]);
8984
+ async function handleRefresh() {
8985
+ if (refreshing) return;
8986
+ setRefreshing(true);
8987
+ try {
8988
+ if (step === "status" && order) {
8989
+ setOrder(await client.getRampOrder(order.id));
8990
+ setPollKey((key) => key + 1);
8991
+ } else if (step === "select_route") await handleFindRoute();
8992
+ else {
8993
+ await loadRoutes(direction);
8994
+ await loadPendingOrders();
8995
+ if (direction === "OFFRAMP") await refreshWalletBalance();
8996
+ }
8997
+ } catch (error) {
8998
+ setErrorMsg(rampErrorMessage(error, copy.refreshFailed, copy, language));
8999
+ } finally {
9000
+ setRefreshing(false);
9001
+ }
9002
+ }
9003
+ const flowSteps = fields.length || quotes.some((q) => core.rampQuoteFields(q).length) ? [copy.steps.route, copy.steps.details, copy.steps.complete] : [copy.steps.route, copy.steps.complete];
9004
+ const stepLabel = {
9005
+ select_route: copy.steps.route,
9006
+ contact: copy.steps.details
9007
+ };
9008
+ const label = stepLabel[step];
9009
+ if (verifying) {
9010
+ const progress = { progress: { position: verifying.completed + 1, total: verifying.total } };
9011
+ const done = () => verificationDone(verifying);
9012
+ if (verifying.type === "FORM")
9013
+ return /* @__PURE__ */ jsxRuntime.jsx(
9014
+ RequirementFormModal,
9015
+ {
9016
+ formId: verifying.optionId,
9017
+ ...progress,
9018
+ language: languageProp,
9019
+ onClose: closeVerification,
9020
+ onSubmitted: done
9021
+ }
9022
+ );
9023
+ if (verifying.type === "REGISTRY_CHECK")
9024
+ return /* @__PURE__ */ jsxRuntime.jsx(
9025
+ RegistryCheckModal,
9026
+ {
9027
+ optionId: verifying.optionId,
9028
+ ...progress,
9029
+ language: languageProp,
9030
+ onClose: closeVerification,
9031
+ onApproved: done
9032
+ }
9033
+ );
9034
+ if (verifying.type === "PROVIDER_REGISTRATION")
9035
+ return /* @__PURE__ */ jsxRuntime.jsx(
9036
+ ProviderRegistrationModal,
9037
+ {
9038
+ corridorId: verifying.corridorId,
9039
+ ...progress,
9040
+ language: languageProp,
9041
+ onClose: closeVerification,
9042
+ onRegistered: done
9043
+ }
9044
+ );
9045
+ return /* @__PURE__ */ jsxRuntime.jsx(
9046
+ KycModal,
9047
+ {
9048
+ country,
9049
+ corridorId: verifying.corridorId,
9050
+ providerId: verifying.optionId,
9051
+ language: languageProp,
9052
+ onClose: closeVerification,
9053
+ onApproved: done
9054
+ }
9055
+ );
9056
+ }
9057
+ return /* @__PURE__ */ jsxRuntime.jsx(PollarOverlay, { style: overlayStyle, onClick: step === "status" ? void 0 : onClose, children: /* @__PURE__ */ jsxRuntime.jsx(
9058
+ RampWidgetTemplate,
9059
+ {
9060
+ language,
9061
+ theme,
9062
+ accentColor,
9063
+ ...styleOverrides ? { styleOverrides } : {},
9064
+ network,
9065
+ step,
9066
+ flowSteps,
8438
9067
  flowStepIndex: label ? flowSteps.indexOf(label) : -1,
8439
9068
  direction,
8440
9069
  routesLoading,
@@ -8493,6 +9122,7 @@ function RampWidget({ onClose, language: languageProp, initial }) {
8493
9122
  },
8494
9123
  onSign: () => void handleSign(),
8495
9124
  onApprove: openCosignModal,
9125
+ cosignPrompt: hostsCosign && cosign.pending.length > 0 ? /* @__PURE__ */ jsxRuntime.jsx(CosignPrompt, { inline: true, onClose: () => void 0 }) : null,
8496
9126
  retrying,
8497
9127
  onRetryOrder: () => void handleRetryOrder(),
8498
9128
  onRequote: () => void handleRequote(),
@@ -11084,16 +11714,16 @@ function SwapModal({ onClose, initial }) {
11084
11714
  react.useEffect(() => {
11085
11715
  if (!settlementKey || settlementDone || !originLanded) return;
11086
11716
  let cancelled = false;
11087
- const read = () => getSwapStatus(settlementKey).then((status) => {
11088
- if (!cancelled)
11089
- setSettlement((cur) => cur && cur.key === settlementKey ? { ...cur, value: status.settlement } : cur);
11090
- }).catch(() => {
11717
+ const read = async () => {
11718
+ const status = await getSwapStatus(settlementKey);
11719
+ if (!cancelled) setSettlement((cur) => cur && cur.key === settlementKey ? { ...cur, value: status.settlement } : cur);
11720
+ };
11721
+ void read().catch(() => {
11091
11722
  });
11092
- void read();
11093
- const id = setInterval(read, SETTLEMENT_POLL_MS);
11723
+ const stop = core.startBackoffPoll(read, SETTLEMENT_POLL_MS);
11094
11724
  return () => {
11095
11725
  cancelled = true;
11096
- clearInterval(id);
11726
+ stop();
11097
11727
  };
11098
11728
  }, [settlementKey, settlementDone, originLanded, getSwapStatus]);
11099
11729
  const hash = transaction.step === "success" ? transaction.hash : null;
@@ -12279,8 +12909,7 @@ function EarnModal({ onClose, initial }) {
12279
12909
  }, [refreshPosition]);
12280
12910
  react.useEffect(() => {
12281
12911
  if (step !== "form" || !onSolana && !provider || !opportunityId) return;
12282
- const id = setInterval(refreshPosition, POSITION_POLL_MS);
12283
- return () => clearInterval(id);
12912
+ return core.startBackoffPoll(async () => refreshPosition(), POSITION_POLL_MS);
12284
12913
  }, [step, onSolana, provider, opportunityId, refreshPosition]);
12285
12914
  react.useEffect(
12286
12915
  () => () => {
@@ -13422,13 +14051,10 @@ function CardModal({ onClose, initial }) {
13422
14051
  const kycPending = holder ? KYC_PENDING.has(holder.kycStatus) : false;
13423
14052
  react.useEffect(() => {
13424
14053
  if (!kycPending) return;
13425
- const id = setInterval(() => {
13426
- loadHolder().then((h) => {
13427
- if (h?.kycStatus === "APPROVED") void loadCardData();
13428
- }).catch(() => {
13429
- });
14054
+ return core.startBackoffPoll(async () => {
14055
+ const h = await loadHolder();
14056
+ if (h?.kycStatus === "APPROVED") void loadCardData();
13430
14057
  }, KYC_POLL_MS);
13431
- return () => clearInterval(id);
13432
14058
  }, [kycPending, loadHolder, loadCardData]);
13433
14059
  react.useEffect(
13434
14060
  () => () => {
@@ -13563,20 +14189,17 @@ function CardModal({ onClose, initial }) {
13563
14189
  const fundingsInflight = (fundings ?? []).some((f) => FUNDING_INFLIGHT.has(f.status));
13564
14190
  react.useEffect(() => {
13565
14191
  if (panel !== "fund" || !fundingsInflight) return;
13566
- const id = setInterval(() => {
13567
- getClient().listCardFundings().then((next) => {
13568
- setFundings((previous) => {
13569
- const credited = next.some(
13570
- (f) => f.status === "CREDITED" && previous?.find((p) => p.id === f.id)?.status !== "CREDITED"
13571
- );
13572
- if (credited) void loadCardData().catch(() => {
13573
- });
13574
- return next;
14192
+ return core.startBackoffPoll(async () => {
14193
+ const next = await getClient().listCardFundings();
14194
+ setFundings((previous) => {
14195
+ const credited = next.some(
14196
+ (f) => f.status === "CREDITED" && previous?.find((p) => p.id === f.id)?.status !== "CREDITED"
14197
+ );
14198
+ if (credited) void loadCardData().catch(() => {
13575
14199
  });
13576
- }).catch(() => {
14200
+ return next;
13577
14201
  });
13578
14202
  }, FUNDING_POLL_MS);
13579
- return () => clearInterval(id);
13580
14203
  }, [panel, fundingsInflight, getClient, loadCardData]);
13581
14204
  const field = (key, label, extra = {}) => /* @__PURE__ */ jsxRuntime.jsxs("label", { className: "pollar-send-field", children: [
13582
14205
  /* @__PURE__ */ jsxRuntime.jsx("span", { className: "pollar-send-label", children: label }),
@@ -13945,934 +14568,397 @@ function CardModal({ onClose, initial }) {
13945
14568
  /* @__PURE__ */ jsxRuntime.jsx("div", { className: "pollar-modal-actions", children: /* @__PURE__ */ jsxRuntime.jsx(
13946
14569
  "button",
13947
14570
  {
13948
- type: "button",
13949
- className: "pollar-btn-primary",
13950
- onClick: () => void fund(),
13951
- disabled: busy !== null || !selectedRoute || !(Number(fundAmount) >= 1),
13952
- children: busy === "fund-send" ? copy.sending : copy.fundFromWallet
13953
- }
13954
- ) }),
13955
- confirmation && /* @__PURE__ */ jsxRuntime.jsx(InlineConfirm, { confirmation, language }),
13956
- !confirmation && sentFunding && (() => {
13957
- const f = sentFunding;
13958
- const state = (f.route === "DIRECT" ? copy.fundingSolana[f.status] : void 0) ?? copy.funding[f.status];
13959
- const steps = FUNDING_STEPS[f.route];
13960
- const step = steps.indexOf(f.status) + 1;
13961
- const inflight = FUNDING_INFLIGHT.has(f.status);
13962
- const failed = f.status === "FAILED";
13963
- return /* @__PURE__ */ jsxRuntime.jsxs(
13964
- "div",
13965
- {
13966
- className: `pollar-outcome${failed ? " pollar-outcome-bad" : ""}${inflight ? " pollar-outcome-busy" : ""}`,
13967
- role: "status",
13968
- children: [
13969
- /* @__PURE__ */ jsxRuntime.jsxs("p", { className: "pollar-outcome-main", children: [
13970
- inflight ? /* @__PURE__ */ jsxRuntime.jsx("span", { className: "pollar-spinner pollar-spinner-sm", "aria-hidden": true }) : /* @__PURE__ */ jsxRuntime.jsx(OutcomeIcon, { ok: !failed }),
13971
- state?.title ?? f.status,
13972
- " \xB7 ",
13973
- money(f.amount, "USD", language)
13974
- ] }),
13975
- inflight && step > 0 && /* @__PURE__ */ jsxRuntime.jsxs("p", { className: "pollar-outcome-note", children: [
13976
- copy.stepOf(step, steps.length),
13977
- " \xB7",
13978
- " ",
13979
- f.error === CREDIT_DELAYED ? copy.fundingProblem.delayed : state?.hint
13980
- ] }),
13981
- failed && /* @__PURE__ */ jsxRuntime.jsx("p", { className: "pollar-outcome-note", children: fundingProblemText(f.error, copy) })
13982
- ]
13983
- }
13984
- );
13985
- })(),
13986
- earlierFundings.length > 0 && /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
13987
- /* @__PURE__ */ jsxRuntime.jsx("p", { className: "pollar-card-section-title", children: copy.yourFundings }),
13988
- earlierFundings.map((f) => {
13989
- const state = (f.route === "DIRECT" ? copy.fundingSolana[f.status] : void 0) ?? copy.funding[f.status];
13990
- const steps = FUNDING_STEPS[f.route];
13991
- const step = steps.indexOf(f.status) + 1;
13992
- const inflight = FUNDING_INFLIGHT.has(f.status);
13993
- return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pollar-card-tx", "aria-busy": inflight, children: [
13994
- /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
13995
- /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "pollar-card-funding-title", children: [
13996
- inflight && /* @__PURE__ */ jsxRuntime.jsx("span", { className: "pollar-spinner pollar-spinner-sm", "aria-hidden": true }),
13997
- state?.title ?? f.status
13998
- ] }),
13999
- inflight && step > 0 && /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "pollar-card-tx-meta", role: "status", children: [
14000
- copy.stepOf(step, steps.length),
14001
- " \xB7",
14002
- " ",
14003
- f.error === CREDIT_DELAYED ? copy.fundingProblem.delayed : state?.hint
14004
- ] }),
14005
- /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "pollar-card-tx-meta", children: [
14006
- new Date(f.createdAt).toLocaleString(),
14007
- f.status === "FAILED" ? ` \xB7 ${fundingProblemText(f.error, copy)}` : ""
14008
- ] })
14009
- ] }),
14010
- /* @__PURE__ */ jsxRuntime.jsx("div", { className: "pollar-card-tx-amount", "data-direction": f.status === "CREDITED" ? "credit" : void 0, children: money(f.amount, "USD", language) })
14011
- ] }, f.id);
14012
- }),
14013
- fundingsInflight && /* @__PURE__ */ jsxRuntime.jsx("p", { className: "pollar-card-note", children: copy.canClose })
14014
- ] }),
14015
- !showManual && /* @__PURE__ */ jsxRuntime.jsxs("p", { className: "pollar-card-note", children: [
14016
- copy.preferOtherWallet,
14017
- " ",
14018
- /* @__PURE__ */ jsxRuntime.jsx(
14019
- "button",
14020
- {
14021
- type: "button",
14022
- className: "pollar-card-link",
14023
- onClick: () => void showManualAddress(),
14024
- disabled: busy !== null,
14025
- children: copy.showDeposit
14026
- }
14027
- )
14028
- ] }),
14029
- showManual && deposit?.map((d) => /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pollar-card-deposit", children: [
14030
- /* @__PURE__ */ jsxRuntime.jsx("strong", { children: d.network }),
14031
- " (",
14032
- copy.chain(d.chainId),
14033
- ")",
14034
- /* @__PURE__ */ jsxRuntime.jsx("code", { children: d.address }),
14035
- /* @__PURE__ */ jsxRuntime.jsx(CopyButton, { value: d.address, label: copy.copyAddress, language }),
14036
- /* @__PURE__ */ jsxRuntime.jsx("p", { className: "pollar-card-note", children: copy.sendOnly(d.tokens.map((t) => (t.currency ?? "token").toUpperCase()).join(` ${copy.or} `), d.network) })
14037
- ] }, d.network)),
14038
- showManual && deposit?.length === 0 && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "pollar-modal-error", children: copy.noDeposit }),
14039
- showManual && /* @__PURE__ */ jsxRuntime.jsx("p", { className: "pollar-card-note", children: /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", className: "pollar-card-link", onClick: () => setShowManual(false), children: copy.hideDeposit }) })
14040
- ] }),
14041
- error && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "pollar-modal-error", children: error }),
14042
- loadFailed && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "pollar-modal-actions", children: /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", className: "pollar-btn-primary", onClick: retryLoad, children: copy.retry }) }),
14043
- /* @__PURE__ */ jsxRuntime.jsx(PollarModalFooter, { language })
14044
- ]
14045
- }
14046
- ) });
14047
- }
14048
-
14049
- // src/components/sessions-modal/sessions-copy.ts
14050
- var SESSIONS_COPY = {
14051
- en: {
14052
- title: "Active sessions",
14053
- refresh: "Refresh",
14054
- close: "Close",
14055
- loading: "Loading\u2026",
14056
- empty: "No active sessions.",
14057
- thisDevice: "This device",
14058
- activeNow: "Active now",
14059
- otherDevices: "Other devices",
14060
- signOutDevice: (device) => `Sign out ${device}`,
14061
- signingOut: "Signing out\u2026",
14062
- signOutThisDevice: "Sign out this device",
14063
- noOtherDevices: "No other devices to sign out",
14064
- signOutEverywhere: "Sign out everywhere",
14065
- unknownDevice: "Unknown device",
14066
- revokeFailed: "Could not sign out that device. Please try again.",
14067
- justNow: "just now",
14068
- secondsAgo: (n) => `${n}s ago`,
14069
- minutesAgo: (n) => `${n}m ago`,
14070
- hoursAgo: (n) => `${n}h ago`,
14071
- daysAgo: (n) => `${n}d ago`
14072
- },
14073
- es: {
14074
- title: "Sesiones activas",
14075
- refresh: "Actualizar",
14076
- close: "Cerrar",
14077
- loading: "Cargando\u2026",
14078
- empty: "No hay sesiones activas.",
14079
- thisDevice: "Este dispositivo",
14080
- activeNow: "Activa ahora",
14081
- otherDevices: "Otros dispositivos",
14082
- signOutDevice: (device) => `Cerrar sesi\xF3n en ${device}`,
14083
- signingOut: "Cerrando sesi\xF3n\u2026",
14084
- signOutThisDevice: "Cerrar sesi\xF3n en este dispositivo",
14085
- noOtherDevices: "No hay otros dispositivos donde cerrar sesi\xF3n",
14086
- signOutEverywhere: "Cerrar sesi\xF3n en todas partes",
14087
- unknownDevice: "Dispositivo desconocido",
14088
- revokeFailed: "No se pudo cerrar sesi\xF3n en ese dispositivo. Intenta de nuevo.",
14089
- justNow: "justo ahora",
14090
- secondsAgo: (n) => `hace ${n} s`,
14091
- minutesAgo: (n) => `hace ${n} min`,
14092
- hoursAgo: (n) => `hace ${n} h`,
14093
- daysAgo: (n) => `hace ${n} d`
14094
- },
14095
- pt: {
14096
- title: "Sess\xF5es ativas",
14097
- refresh: "Atualizar",
14098
- close: "Fechar",
14099
- loading: "Carregando\u2026",
14100
- empty: "Nenhuma sess\xE3o ativa.",
14101
- thisDevice: "Este dispositivo",
14102
- activeNow: "Ativa agora",
14103
- otherDevices: "Outros dispositivos",
14104
- signOutDevice: (device) => `Sair de ${device}`,
14105
- signingOut: "Saindo\u2026",
14106
- signOutThisDevice: "Sair deste dispositivo",
14107
- noOtherDevices: "N\xE3o h\xE1 outros dispositivos para sair",
14108
- signOutEverywhere: "Sair de todos os dispositivos",
14109
- unknownDevice: "Dispositivo desconhecido",
14110
- revokeFailed: "N\xE3o foi poss\xEDvel sair desse dispositivo. Tente novamente.",
14111
- justNow: "agora mesmo",
14112
- secondsAgo: (n) => `h\xE1 ${n} s`,
14113
- minutesAgo: (n) => `h\xE1 ${n} min`,
14114
- hoursAgo: (n) => `h\xE1 ${n} h`,
14115
- daysAgo: (n) => `h\xE1 ${n} d`
14116
- }
14117
- };
14118
- function describeDevice(s, copy) {
14119
- if (s.deviceLabel) return normalizeDeviceLabel(s.deviceLabel);
14120
- if (!s.userAgent) return copy.unknownDevice;
14121
- return parseUserAgent(s.userAgent);
14122
- }
14123
- function normalizeDeviceLabel(label) {
14124
- const parts = label.replace(/\s+/g, " ").split(/ (?:[—–-]|·) /);
14125
- if (parts.length === 2 && parts[1] !== void 0) return `${parts[0]} \xB7 ${parts[1].toLowerCase()}`;
14126
- return label;
14127
- }
14128
- function detectBrowser(ua) {
14129
- if (/Edg\//.test(ua)) return "Edge";
14130
- if (/OPR\//.test(ua)) return "Opera";
14131
- if (/(Chrome|CriOS)\//.test(ua)) return "Chrome";
14132
- if (/(Firefox|FxiOS)\//.test(ua)) return "Firefox";
14133
- if (/Safari\//.test(ua)) return "Safari";
14134
- return null;
14135
- }
14136
- function detectOS(ua) {
14137
- if (/iPhone|iPad|iPod/.test(ua)) return "iOS";
14138
- if (/Android/.test(ua)) return "Android";
14139
- if (/Mac OS X/.test(ua)) return "macOS";
14140
- if (/Windows NT/.test(ua)) return "Windows";
14141
- if (/Linux/.test(ua)) return "Linux";
14142
- return null;
14143
- }
14144
- function parseUserAgent(ua) {
14145
- const browser = detectBrowser(ua);
14146
- const os = detectOS(ua);
14147
- if (browser && os) return `${os} \xB7 ${browser.toLowerCase()}`;
14148
- if (os) return os;
14149
- if (browser) return browser;
14150
- return ua.slice(0, 48);
14151
- }
14152
- function formatRelative(iso, copy) {
14153
- if (!iso) return "\u2014";
14154
- const ts = new Date(iso).getTime();
14155
- if (!Number.isFinite(ts)) return "\u2014";
14156
- const diffSec = Math.round((Date.now() - ts) / 1e3);
14157
- if (diffSec < 0) return copy.justNow;
14158
- if (diffSec < 60) return copy.secondsAgo(diffSec);
14159
- const diffMin = Math.round(diffSec / 60);
14160
- if (diffMin < 60) return copy.minutesAgo(diffMin);
14161
- const diffHr = Math.round(diffMin / 60);
14162
- if (diffHr < 24) return copy.hoursAgo(diffHr);
14163
- const diffDay = Math.round(diffHr / 24);
14164
- if (diffDay < 30) return copy.daysAgo(diffDay);
14165
- return new Date(iso).toLocaleDateString(void 0, { month: "short", day: "numeric", year: "numeric" });
14166
- }
14167
- function shortIp(hash) {
14168
- if (!hash) return "";
14169
- return hash.slice(0, 8);
14170
- }
14171
- function deviceKind(session) {
14172
- const value = `${session.deviceLabel ?? ""} ${session.userAgent ?? ""}`.toLowerCase();
14173
- if (/ipad|tablet/.test(value)) return "tablet";
14174
- if (/android|iphone|ipod|mobile|phone/.test(value)) return "phone";
14175
- return "desktop";
14176
- }
14177
- function DeviceIcon({ kind, size = "small" }) {
14178
- const dimensions = size === "large" ? 30 : 18;
14179
- if (kind === "phone") {
14180
- return /* @__PURE__ */ jsxRuntime.jsxs("svg", { width: dimensions, height: dimensions, viewBox: "0 0 24 24", fill: "none", "aria-hidden": true, children: [
14181
- /* @__PURE__ */ jsxRuntime.jsx("rect", { x: "7", y: "2.5", width: "10", height: "19", rx: "2.5", stroke: "currentColor", strokeWidth: "1.8" }),
14182
- /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M10.5 5h3M11 18.5h2", stroke: "currentColor", strokeWidth: "1.6", strokeLinecap: "round" })
14183
- ] });
14184
- }
14185
- if (kind === "tablet") {
14186
- return /* @__PURE__ */ jsxRuntime.jsxs("svg", { width: dimensions, height: dimensions, viewBox: "0 0 24 24", fill: "none", "aria-hidden": true, children: [
14187
- /* @__PURE__ */ jsxRuntime.jsx("rect", { x: "4.5", y: "2.5", width: "15", height: "19", rx: "2", stroke: "currentColor", strokeWidth: "1.8" }),
14188
- /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M11 18.5h2", stroke: "currentColor", strokeWidth: "1.6", strokeLinecap: "round" })
14189
- ] });
14190
- }
14191
- return /* @__PURE__ */ jsxRuntime.jsxs("svg", { width: dimensions, height: dimensions, viewBox: "0 0 24 24", fill: "none", "aria-hidden": true, children: [
14192
- /* @__PURE__ */ jsxRuntime.jsx("rect", { x: "3", y: "3.5", width: "18", height: "12", rx: "1.8", stroke: "currentColor", strokeWidth: "1.8" }),
14193
- /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M8 20.5h8M12 15.5v5", stroke: "currentColor", strokeWidth: "1.8", strokeLinecap: "round" })
14194
- ] });
14195
- }
14196
- function CheckIcon() {
14197
- return /* @__PURE__ */ jsxRuntime.jsx("svg", { width: "12", height: "12", viewBox: "0 0 12 12", fill: "none", "aria-hidden": true, children: /* @__PURE__ */ jsxRuntime.jsx("path", { d: "m2.5 6.2 2.1 2.1L9.6 3.6", stroke: "currentColor", strokeWidth: "1.7", strokeLinecap: "round", strokeLinejoin: "round" }) });
14198
- }
14199
- function CloseIcon() {
14200
- return /* @__PURE__ */ jsxRuntime.jsx("svg", { width: "14", height: "14", viewBox: "0 0 14 14", fill: "none", "aria-hidden": true, children: /* @__PURE__ */ jsxRuntime.jsx("path", { d: "m3 3 8 8M11 3l-8 8", stroke: "currentColor", strokeWidth: "1.7", strokeLinecap: "round" }) });
14201
- }
14202
- function SessionsModalTemplate({
14203
- theme,
14204
- accentColor,
14205
- styleOverrides,
14206
- state,
14207
- revokingFamilyId,
14208
- signingOutEverywhere,
14209
- revokeError,
14210
- onRefresh,
14211
- onRevoke,
14212
- onLogoutEverywhere,
14213
- onClose,
14214
- language: languageProp
14215
- }) {
14216
- const language = useInheritedLanguage(languageProp);
14217
- const copy = SESSIONS_COPY[language];
14218
- const cssVars = buildModalCssVars(theme, accentColor, styleOverrides);
14219
- const isLoading = state.step === "loading";
14220
- const sessions = state.step === "loaded" ? state.sessions : [];
14221
- const currentSession = sessions.find((s) => s.current);
14222
- const otherSessions = sessions.filter((s) => !s.current);
14223
- const otherCount = otherSessions.length;
14224
- return /* @__PURE__ */ jsxRuntime.jsxs(
14225
- "div",
14226
- {
14227
- className: "pollar-modal-card pollar-sessions-modal",
14228
- "data-theme": theme,
14229
- style: cssVars,
14230
- onClick: (e) => e.stopPropagation(),
14231
- children: [
14232
- /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pollar-modal-header", children: [
14233
- /* @__PURE__ */ jsxRuntime.jsx("h2", { className: "pollar-modal-title", children: copy.title }),
14234
- /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pollar-modal-header-actions", children: [
14571
+ type: "button",
14572
+ className: "pollar-btn-primary",
14573
+ onClick: () => void fund(),
14574
+ disabled: busy !== null || !selectedRoute || !(Number(fundAmount) >= 1),
14575
+ children: busy === "fund-send" ? copy.sending : copy.fundFromWallet
14576
+ }
14577
+ ) }),
14578
+ confirmation && /* @__PURE__ */ jsxRuntime.jsx(InlineConfirm, { confirmation, language }),
14579
+ !confirmation && sentFunding && (() => {
14580
+ const f = sentFunding;
14581
+ const state = (f.route === "DIRECT" ? copy.fundingSolana[f.status] : void 0) ?? copy.funding[f.status];
14582
+ const steps = FUNDING_STEPS[f.route];
14583
+ const step = steps.indexOf(f.status) + 1;
14584
+ const inflight = FUNDING_INFLIGHT.has(f.status);
14585
+ const failed = f.status === "FAILED";
14586
+ return /* @__PURE__ */ jsxRuntime.jsxs(
14587
+ "div",
14588
+ {
14589
+ className: `pollar-outcome${failed ? " pollar-outcome-bad" : ""}${inflight ? " pollar-outcome-busy" : ""}`,
14590
+ role: "status",
14591
+ children: [
14592
+ /* @__PURE__ */ jsxRuntime.jsxs("p", { className: "pollar-outcome-main", children: [
14593
+ inflight ? /* @__PURE__ */ jsxRuntime.jsx("span", { className: "pollar-spinner pollar-spinner-sm", "aria-hidden": true }) : /* @__PURE__ */ jsxRuntime.jsx(OutcomeIcon, { ok: !failed }),
14594
+ state?.title ?? f.status,
14595
+ " \xB7 ",
14596
+ money(f.amount, "USD", language)
14597
+ ] }),
14598
+ inflight && step > 0 && /* @__PURE__ */ jsxRuntime.jsxs("p", { className: "pollar-outcome-note", children: [
14599
+ copy.stepOf(step, steps.length),
14600
+ " \xB7",
14601
+ " ",
14602
+ f.error === CREDIT_DELAYED ? copy.fundingProblem.delayed : state?.hint
14603
+ ] }),
14604
+ failed && /* @__PURE__ */ jsxRuntime.jsx("p", { className: "pollar-outcome-note", children: fundingProblemText(f.error, copy) })
14605
+ ]
14606
+ }
14607
+ );
14608
+ })(),
14609
+ earlierFundings.length > 0 && /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
14610
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "pollar-card-section-title", children: copy.yourFundings }),
14611
+ earlierFundings.map((f) => {
14612
+ const state = (f.route === "DIRECT" ? copy.fundingSolana[f.status] : void 0) ?? copy.funding[f.status];
14613
+ const steps = FUNDING_STEPS[f.route];
14614
+ const step = steps.indexOf(f.status) + 1;
14615
+ const inflight = FUNDING_INFLIGHT.has(f.status);
14616
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pollar-card-tx", "aria-busy": inflight, children: [
14617
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
14618
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "pollar-card-funding-title", children: [
14619
+ inflight && /* @__PURE__ */ jsxRuntime.jsx("span", { className: "pollar-spinner pollar-spinner-sm", "aria-hidden": true }),
14620
+ state?.title ?? f.status
14621
+ ] }),
14622
+ inflight && step > 0 && /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "pollar-card-tx-meta", role: "status", children: [
14623
+ copy.stepOf(step, steps.length),
14624
+ " \xB7",
14625
+ " ",
14626
+ f.error === CREDIT_DELAYED ? copy.fundingProblem.delayed : state?.hint
14627
+ ] }),
14628
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "pollar-card-tx-meta", children: [
14629
+ new Date(f.createdAt).toLocaleString(),
14630
+ f.status === "FAILED" ? ` \xB7 ${fundingProblemText(f.error, copy)}` : ""
14631
+ ] })
14632
+ ] }),
14633
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "pollar-card-tx-amount", "data-direction": f.status === "CREDITED" ? "credit" : void 0, children: money(f.amount, "USD", language) })
14634
+ ] }, f.id);
14635
+ }),
14636
+ fundingsInflight && /* @__PURE__ */ jsxRuntime.jsx("p", { className: "pollar-card-note", children: copy.canClose })
14637
+ ] }),
14638
+ !showManual && /* @__PURE__ */ jsxRuntime.jsxs("p", { className: "pollar-card-note", children: [
14639
+ copy.preferOtherWallet,
14640
+ " ",
14235
14641
  /* @__PURE__ */ jsxRuntime.jsx(
14236
14642
  "button",
14237
14643
  {
14238
14644
  type: "button",
14239
- className: "pollar-modal-close",
14240
- onClick: onRefresh,
14241
- disabled: isLoading,
14242
- "aria-label": copy.refresh,
14243
- title: copy.refresh,
14244
- children: /* @__PURE__ */ jsxRuntime.jsx(RefreshIcon, { spinning: isLoading })
14645
+ className: "pollar-card-link",
14646
+ onClick: () => void showManualAddress(),
14647
+ disabled: busy !== null,
14648
+ children: copy.showDeposit
14245
14649
  }
14246
- ),
14247
- /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", className: "pollar-modal-close", onClick: onClose, "aria-label": copy.close, title: copy.close, children: /* @__PURE__ */ jsxRuntime.jsx(CloseIcon, {}) })
14248
- ] })
14249
- ] }),
14250
- /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pollar-sessions-list", children: [
14251
- (state.step === "idle" || isLoading) && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pollar-loading-block", children: [
14252
- /* @__PURE__ */ jsxRuntime.jsx("div", { className: "pollar-spinner" }),
14253
- /* @__PURE__ */ jsxRuntime.jsx("span", { children: copy.loading })
14254
- ] }),
14255
- state.step === "error" && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "pollar-modal-empty", children: state.message }),
14256
- state.step === "loaded" && sessions.length === 0 && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "pollar-modal-empty", children: copy.empty }),
14257
- state.step === "loaded" && currentSession && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pollar-sessions-current-card", children: [
14258
- /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pollar-sessions-current-icon-wrap", children: [
14259
- /* @__PURE__ */ jsxRuntime.jsx(DeviceIcon, { kind: deviceKind(currentSession), size: "large" }),
14260
- /* @__PURE__ */ jsxRuntime.jsx("span", { className: "pollar-sessions-current-check", children: /* @__PURE__ */ jsxRuntime.jsx(CheckIcon, {}) })
14261
- ] }),
14262
- /* @__PURE__ */ jsxRuntime.jsx("span", { className: "pollar-sessions-current-label", children: copy.thisDevice }),
14263
- /* @__PURE__ */ jsxRuntime.jsx("strong", { className: "pollar-sessions-current-device", children: describeDevice(currentSession, copy) }),
14264
- /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pollar-sessions-current-status", children: [
14265
- /* @__PURE__ */ jsxRuntime.jsx("span", { className: "pollar-sessions-status-dot" }),
14266
- /* @__PURE__ */ jsxRuntime.jsx("span", { children: copy.activeNow }),
14267
- currentSession.ipHash && /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
14268
- /* @__PURE__ */ jsxRuntime.jsx("span", { children: "\xB7" }),
14269
- /* @__PURE__ */ jsxRuntime.jsxs("span", { title: `ip-hash ${currentSession.ipHash}`, children: [
14270
- "IP ",
14271
- shortIp(currentSession.ipHash)
14272
- ] })
14273
- ] })
14274
- ] })
14275
- ] }),
14276
- state.step === "loaded" && otherSessions.length > 0 && /* @__PURE__ */ jsxRuntime.jsxs("section", { className: "pollar-sessions-other-section", "aria-labelledby": "pollar-other-devices-heading", children: [
14277
- /* @__PURE__ */ jsxRuntime.jsxs("h3", { id: "pollar-other-devices-heading", className: "pollar-sessions-section-title", children: [
14278
- copy.otherDevices,
14279
- " ",
14280
- /* @__PURE__ */ jsxRuntime.jsx("span", { children: otherCount })
14281
- ] }),
14282
- /* @__PURE__ */ jsxRuntime.jsx("div", { className: "pollar-sessions-grid", children: otherSessions.map((s) => {
14283
- const isRevoking = revokingFamilyId === s.familyId;
14284
- return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pollar-sessions-item", children: [
14285
- /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pollar-sessions-item-top", children: [
14286
- /* @__PURE__ */ jsxRuntime.jsx("span", { className: "pollar-sessions-item-icon", children: /* @__PURE__ */ jsxRuntime.jsx(DeviceIcon, { kind: deviceKind(s) }) }),
14287
- /* @__PURE__ */ jsxRuntime.jsx(
14288
- "button",
14289
- {
14290
- type: "button",
14291
- className: "pollar-sessions-item-revoke",
14292
- onClick: () => onRevoke(s.familyId),
14293
- disabled: isRevoking || signingOutEverywhere,
14294
- "aria-label": copy.signOutDevice(describeDevice(s, copy)),
14295
- title: isRevoking ? copy.signingOut : copy.signOutThisDevice,
14296
- children: isRevoking ? /* @__PURE__ */ jsxRuntime.jsx("span", { className: "pollar-spinner pollar-spinner-sm" }) : /* @__PURE__ */ jsxRuntime.jsx(CloseIcon, {})
14297
- }
14298
- )
14299
- ] }),
14300
- /* @__PURE__ */ jsxRuntime.jsx("strong", { className: "pollar-sessions-item-device", children: describeDevice(s, copy) }),
14301
- /* @__PURE__ */ jsxRuntime.jsx("span", { className: "pollar-sessions-item-meta", children: formatRelative(s.lastUsedAt ?? s.createdAt, copy) })
14302
- ] }, s.familyId);
14303
- }) })
14650
+ )
14304
14651
  ] }),
14305
- revokeError && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "pollar-sessions-action-error", role: "alert", children: revokeError })
14306
- ] }),
14307
- state.step === "loaded" && sessions.length > 0 && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "pollar-sessions-actions", children: /* @__PURE__ */ jsxRuntime.jsx(
14308
- "button",
14309
- {
14310
- className: "pollar-sessions-logout-all",
14311
- onClick: onLogoutEverywhere,
14312
- disabled: signingOutEverywhere || otherCount === 0,
14313
- title: otherCount === 0 ? copy.noOtherDevices : void 0,
14314
- children: signingOutEverywhere ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
14315
- /* @__PURE__ */ jsxRuntime.jsx("span", { className: "pollar-spinner pollar-spinner-sm pollar-spinner-current" }),
14316
- copy.signingOut
14317
- ] }) : copy.signOutEverywhere
14318
- }
14319
- ) }),
14320
- /* @__PURE__ */ jsxRuntime.jsx(PollarModalFooter, {})
14321
- ]
14322
- }
14323
- );
14324
- }
14325
- function SessionsModal({ onClose }) {
14326
- const { getClient, styles, sessions } = usePollar();
14327
- const { theme, accentColor, styleOverrides, overlayStyle } = modalChrome(styles);
14328
- const language = useModalLanguage();
14329
- const copy = SESSIONS_COPY[language];
14330
- const [revokingFamilyId, setRevokingFamilyId] = react.useState(null);
14331
- const [signingOutEverywhere, setSigningOutEverywhere] = react.useState(false);
14332
- const [revokeError, setRevokeError] = react.useState(null);
14333
- const load = react.useCallback(() => {
14334
- void getClient().fetchSessions();
14335
- }, [getClient]);
14336
- react.useEffect(() => {
14337
- load();
14338
- }, [load]);
14339
- const onCloseRef = react.useRef(onClose);
14340
- onCloseRef.current = onClose;
14341
- react.useEffect(() => {
14342
- return getClient().onAuthStateChange((authState) => {
14343
- if (authState.step === "idle") onCloseRef.current();
14344
- });
14345
- }, [getClient]);
14346
- const handleRevoke = react.useCallback(
14347
- async (familyId) => {
14348
- setRevokingFamilyId(familyId);
14349
- setRevokeError(null);
14350
- try {
14351
- await getClient().revokeSession(familyId);
14352
- } catch {
14353
- setRevokeError(copy.revokeFailed);
14354
- } finally {
14355
- setRevokingFamilyId(null);
14356
- load();
14357
- }
14358
- },
14359
- [getClient, load, copy]
14360
- );
14361
- const handleLogoutEverywhere = react.useCallback(async () => {
14362
- setSigningOutEverywhere(true);
14363
- try {
14364
- await getClient().logoutEverywhere();
14365
- onClose();
14366
- } catch {
14367
- setSigningOutEverywhere(false);
14368
- }
14369
- }, [getClient, onClose]);
14370
- return /* @__PURE__ */ jsxRuntime.jsx(PollarOverlay, { style: overlayStyle, onClick: onClose, children: /* @__PURE__ */ jsxRuntime.jsx(
14371
- SessionsModalTemplate,
14372
- {
14373
- theme,
14374
- accentColor,
14375
- styleOverrides,
14376
- state: sessions,
14377
- revokingFamilyId,
14378
- signingOutEverywhere,
14379
- revokeError,
14380
- onRefresh: () => load(),
14381
- onRevoke: (familyId) => void handleRevoke(familyId),
14382
- onLogoutEverywhere: () => void handleLogoutEverywhere(),
14383
- onClose,
14384
- language
14385
- }
14386
- ) });
14387
- }
14388
- function useCosign() {
14389
- const { getClient, isAuthenticated } = usePollar();
14390
- const [state, setState] = react.useState({ pending: [] });
14391
- const [loaded, setLoaded] = react.useState(false);
14392
- react.useEffect(() => getClient().onCosignStateChange(setState), [getClient]);
14393
- const refresh = react.useCallback(async () => {
14394
- if (!isAuthenticated) return;
14395
- try {
14396
- await getClient().cosign.pending();
14397
- } finally {
14398
- setLoaded(true);
14399
- }
14400
- }, [getClient, isAuthenticated]);
14401
- react.useEffect(() => {
14402
- void refresh();
14403
- }, [refresh]);
14404
- return {
14405
- pending: state.pending,
14406
- ...state.lastResolved ? { lastResolved: state.lastResolved } : {},
14407
- loaded,
14408
- refresh,
14409
- approve: react.useCallback((request) => getClient().cosign.approve(request), [getClient]),
14410
- reject: react.useCallback((request) => getClient().cosign.reject(request), [getClient]),
14411
- verify: react.useCallback((request) => getClient().cosign.verify(request), [getClient]),
14412
- inspectQuorum: react.useCallback(() => getClient().cosign.inspectQuorum(), [getClient]),
14413
- devices: react.useCallback(() => getClient().cosign.devices(), [getClient]),
14414
- revokeDevice: react.useCallback(
14415
- (deviceId, options) => getClient().cosign.revokeDevice(deviceId, options),
14416
- [getClient]
14417
- ),
14418
- switchCustody: react.useCallback((to) => getClient().cosign.switchCustody(to), [getClient])
14419
- };
14652
+ showManual && deposit?.map((d) => /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pollar-card-deposit", children: [
14653
+ /* @__PURE__ */ jsxRuntime.jsx("strong", { children: d.network }),
14654
+ " (",
14655
+ copy.chain(d.chainId),
14656
+ ")",
14657
+ /* @__PURE__ */ jsxRuntime.jsx("code", { children: d.address }),
14658
+ /* @__PURE__ */ jsxRuntime.jsx(CopyButton, { value: d.address, label: copy.copyAddress, language }),
14659
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "pollar-card-note", children: copy.sendOnly(d.tokens.map((t) => (t.currency ?? "token").toUpperCase()).join(` ${copy.or} `), d.network) })
14660
+ ] }, d.network)),
14661
+ showManual && deposit?.length === 0 && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "pollar-modal-error", children: copy.noDeposit }),
14662
+ showManual && /* @__PURE__ */ jsxRuntime.jsx("p", { className: "pollar-card-note", children: /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", className: "pollar-card-link", onClick: () => setShowManual(false), children: copy.hideDeposit }) })
14663
+ ] }),
14664
+ error && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "pollar-modal-error", children: error }),
14665
+ loadFailed && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "pollar-modal-actions", children: /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", className: "pollar-btn-primary", onClick: retryLoad, children: copy.retry }) }),
14666
+ /* @__PURE__ */ jsxRuntime.jsx(PollarModalFooter, { language })
14667
+ ]
14668
+ }
14669
+ ) });
14420
14670
  }
14421
14671
 
14422
- // src/components/cosign-modal/cosign-copy.ts
14423
- var COSIGN_COPY = {
14672
+ // src/components/sessions-modal/sessions-copy.ts
14673
+ var SESSIONS_COPY = {
14424
14674
  en: {
14425
- title: "Approvals",
14426
- manyPending: (count) => `${count} approvals waiting`,
14675
+ title: "Active sessions",
14676
+ refresh: "Refresh",
14427
14677
  close: "Close",
14428
- whyTitle: "Why am I seeing this?",
14429
- whyBody: "Your wallet needs this device's signature. Neither the app nor Pollar can approve this without you.",
14430
- rejectRequest: "Reject this request",
14431
- closeTitle: "Close without signing?",
14432
- closeBody: "The request stays pending. The app can't continue until you approve it.",
14433
- backToSign: "Go back and sign",
14434
- closeAnyway: "Close anyway",
14435
- activateWallet: "Activate wallet",
14436
- status: { APPROVED: "Approved", REJECTED: "Rejected", EXPIRED: "Expired", FAILED: "Failed", PENDING: "Pending" },
14437
- signedAppSends: "Signed. The app will send it.",
14438
- signedSent: "Signed and sent",
14439
- signed: "Signed",
14440
- nothingSigned: "Nothing was signed.",
14441
- nothingWaiting: "Nothing waits for your approval.",
14442
- next: (step) => `Next: ${step}. It appears here in a few seconds.`,
14443
- closingIn: (seconds) => `Closing in ${seconds}s`,
14444
- expired: "expired",
14445
- expiresIn: "Expires in",
14446
- checking: "Checking...",
14447
- verified: "Checked",
14448
- checkedExact: "We checked this is exactly what you're approving.",
14449
- notVerified: "Not verified:",
14450
- reject: "Reject",
14451
- rejecting: "Rejecting...",
14452
- approve: "Approve",
14453
- approving: "Approving...",
14454
- genericError: "Something went wrong. Please try again.",
14455
- unreachable: "We could not reach Pollar, so nothing was approved. Check your connection and approve again.",
14456
- deviceNotLinked: "This device isn't linked to your wallet yet, so it can't approve. Add it with a device that already is, your passkey or your email.",
14457
- linkDevice: "Link this device",
14458
- transaction: "Transaction",
14459
- operations: {
14460
- payment: "Send",
14461
- path_payment_strict_send: "Swap",
14462
- change_trust: "Add asset",
14463
- create_account: "Create account",
14464
- invoke_contract: "Contract call",
14465
- soroban_auth: "Authorize a contract call",
14466
- manage_data: "Manage data",
14467
- transfer: "Send",
14468
- ramp_payment: "Ramp payment",
14469
- cctp_burn: "Move USDC",
14470
- swap: "Swap",
14471
- earn_deposit: "Deposit",
14472
- earn_withdraw: "Withdraw",
14473
- evm_delegation: "Enable atomic transactions",
14474
- provider_sign_in: "Confirm it's you",
14475
- sep10: "Confirm it's you"
14476
- }
14678
+ loading: "Loading\u2026",
14679
+ empty: "No active sessions.",
14680
+ thisDevice: "This device",
14681
+ activeNow: "Active now",
14682
+ otherDevices: "Other devices",
14683
+ signOutDevice: (device) => `Sign out ${device}`,
14684
+ signingOut: "Signing out\u2026",
14685
+ signOutThisDevice: "Sign out this device",
14686
+ noOtherDevices: "No other devices to sign out",
14687
+ signOutEverywhere: "Sign out everywhere",
14688
+ unknownDevice: "Unknown device",
14689
+ revokeFailed: "Could not sign out that device. Please try again.",
14690
+ justNow: "just now",
14691
+ secondsAgo: (n) => `${n}s ago`,
14692
+ minutesAgo: (n) => `${n}m ago`,
14693
+ hoursAgo: (n) => `${n}h ago`,
14694
+ daysAgo: (n) => `${n}d ago`
14477
14695
  },
14478
14696
  es: {
14479
- title: "Aprobaciones",
14480
- manyPending: (count) => `${count} aprobaciones pendientes`,
14697
+ title: "Sesiones activas",
14698
+ refresh: "Actualizar",
14481
14699
  close: "Cerrar",
14482
- whyTitle: "\xBFPor qu\xE9 ves esto?",
14483
- whyBody: "Tu billetera necesita la firma de este dispositivo. Ni la app ni Pollar pueden aprobar esto sin ti.",
14484
- rejectRequest: "Rechazar esta solicitud",
14485
- closeTitle: "\xBFCerrar sin firmar?",
14486
- closeBody: "La solicitud queda pendiente. La app no puede seguir hasta que la apruebes.",
14487
- backToSign: "Volver y firmar",
14488
- closeAnyway: "Cerrar igual",
14489
- activateWallet: "Activar billetera",
14490
- status: { APPROVED: "Aprobada", REJECTED: "Rechazada", EXPIRED: "Vencida", FAILED: "Fallida", PENDING: "Pendiente" },
14491
- signedAppSends: "Firmada. La app la enviar\xE1.",
14492
- signedSent: "Firmada y enviada",
14493
- signed: "Firmada",
14494
- nothingSigned: "No se firm\xF3 nada.",
14495
- nothingWaiting: "No hay nada esperando tu aprobaci\xF3n.",
14496
- next: (step) => `Siguiente: ${step}. Aparecer\xE1 aqu\xED en unos segundos.`,
14497
- closingIn: (seconds) => `Se cierra en ${seconds}s`,
14498
- expired: "vencida",
14499
- expiresIn: "Vence en",
14500
- checking: "Verificando...",
14501
- verified: "Comprobada",
14502
- checkedExact: "Comprobamos que esto es exactamente lo que est\xE1s aprobando.",
14503
- notVerified: "Sin verificar:",
14504
- reject: "Rechazar",
14505
- rejecting: "Rechazando...",
14506
- approve: "Aprobar",
14507
- approving: "Aprobando...",
14508
- genericError: "Algo sali\xF3 mal. Intenta de nuevo.",
14509
- unreachable: "No pudimos conectar con Pollar, as\xED que no se aprob\xF3 nada. Revisa tu conexi\xF3n y aprueba de nuevo.",
14510
- deviceNotLinked: "Este dispositivo a\xFAn no est\xE1 vinculado a tu billetera, as\xED que no puede aprobar. Agr\xE9galo con un dispositivo que ya lo est\xE9, tu passkey o tu email.",
14511
- linkDevice: "Vincular este dispositivo",
14512
- transaction: "Transacci\xF3n",
14513
- operations: {
14514
- payment: "Enviar",
14515
- path_payment_strict_send: "Intercambiar",
14516
- change_trust: "Agregar activo",
14517
- create_account: "Crear cuenta",
14518
- invoke_contract: "Llamada a contrato",
14519
- soroban_auth: "Autorizar una llamada a contrato",
14520
- manage_data: "Gestionar datos",
14521
- transfer: "Enviar",
14522
- ramp_payment: "Pago de rampa",
14523
- cctp_burn: "Mover USDC",
14524
- swap: "Intercambiar",
14525
- earn_deposit: "Depositar",
14526
- earn_withdraw: "Retirar",
14527
- evm_delegation: "Activar transacciones at\xF3micas",
14528
- provider_sign_in: "Confirma que eres t\xFA",
14529
- sep10: "Confirma que eres t\xFA"
14530
- }
14700
+ loading: "Cargando\u2026",
14701
+ empty: "No hay sesiones activas.",
14702
+ thisDevice: "Este dispositivo",
14703
+ activeNow: "Activa ahora",
14704
+ otherDevices: "Otros dispositivos",
14705
+ signOutDevice: (device) => `Cerrar sesi\xF3n en ${device}`,
14706
+ signingOut: "Cerrando sesi\xF3n\u2026",
14707
+ signOutThisDevice: "Cerrar sesi\xF3n en este dispositivo",
14708
+ noOtherDevices: "No hay otros dispositivos donde cerrar sesi\xF3n",
14709
+ signOutEverywhere: "Cerrar sesi\xF3n en todas partes",
14710
+ unknownDevice: "Dispositivo desconocido",
14711
+ revokeFailed: "No se pudo cerrar sesi\xF3n en ese dispositivo. Intenta de nuevo.",
14712
+ justNow: "justo ahora",
14713
+ secondsAgo: (n) => `hace ${n} s`,
14714
+ minutesAgo: (n) => `hace ${n} min`,
14715
+ hoursAgo: (n) => `hace ${n} h`,
14716
+ daysAgo: (n) => `hace ${n} d`
14531
14717
  },
14532
14718
  pt: {
14533
- title: "Aprova\xE7\xF5es",
14534
- manyPending: (count) => `${count} aprova\xE7\xF5es pendentes`,
14719
+ title: "Sess\xF5es ativas",
14720
+ refresh: "Atualizar",
14535
14721
  close: "Fechar",
14536
- whyTitle: "Por que estou vendo isto?",
14537
- whyBody: "Sua carteira precisa da assinatura deste dispositivo. Nem o app nem a Pollar podem aprovar isto sem voc\xEA.",
14538
- rejectRequest: "Rejeitar esta solicita\xE7\xE3o",
14539
- closeTitle: "Fechar sem assinar?",
14540
- closeBody: "A solicita\xE7\xE3o fica pendente. O app n\xE3o pode continuar at\xE9 voc\xEA aprov\xE1-la.",
14541
- backToSign: "Voltar e assinar",
14542
- closeAnyway: "Fechar mesmo assim",
14543
- activateWallet: "Ativar carteira",
14544
- status: { APPROVED: "Aprovada", REJECTED: "Rejeitada", EXPIRED: "Expirada", FAILED: "Falhou", PENDING: "Pendente" },
14545
- signedAppSends: "Assinada. O app vai envi\xE1-la.",
14546
- signedSent: "Assinada e enviada",
14547
- signed: "Assinada",
14548
- nothingSigned: "Nada foi assinado.",
14549
- nothingWaiting: "Nada aguarda a sua aprova\xE7\xE3o.",
14550
- next: (step) => `Pr\xF3ximo: ${step}. Aparece aqui em alguns segundos.`,
14551
- closingIn: (seconds) => `Fechando em ${seconds}s`,
14552
- expired: "expirada",
14553
- expiresIn: "Expira em",
14554
- checking: "Verificando...",
14555
- verified: "Conferida",
14556
- checkedExact: "Conferimos que isto \xE9 exatamente o que voc\xEA est\xE1 aprovando.",
14557
- notVerified: "N\xE3o verificada:",
14558
- reject: "Rejeitar",
14559
- rejecting: "Rejeitando...",
14560
- approve: "Aprovar",
14561
- approving: "Aprovando...",
14562
- genericError: "Algo deu errado. Tente novamente.",
14563
- unreachable: "N\xE3o conseguimos conectar \xE0 Pollar, ent\xE3o nada foi aprovado. Verifique sua conex\xE3o e aprove novamente.",
14564
- deviceNotLinked: "Este dispositivo ainda n\xE3o est\xE1 vinculado \xE0 sua carteira, ent\xE3o n\xE3o pode aprovar. Adicione-o com um dispositivo que j\xE1 esteja, sua passkey ou seu email.",
14565
- linkDevice: "Vincular este dispositivo",
14566
- transaction: "Transa\xE7\xE3o",
14567
- operations: {
14568
- payment: "Enviar",
14569
- path_payment_strict_send: "Trocar",
14570
- change_trust: "Adicionar ativo",
14571
- create_account: "Criar conta",
14572
- invoke_contract: "Chamada de contrato",
14573
- soroban_auth: "Autorizar uma chamada de contrato",
14574
- manage_data: "Gerenciar dados",
14575
- transfer: "Enviar",
14576
- ramp_payment: "Pagamento de rampa",
14577
- cctp_burn: "Mover USDC",
14578
- swap: "Trocar",
14579
- earn_deposit: "Depositar",
14580
- earn_withdraw: "Sacar",
14581
- evm_delegation: "Ativar transa\xE7\xF5es at\xF4micas",
14582
- provider_sign_in: "Confirme que \xE9 voc\xEA",
14583
- sep10: "Confirme que \xE9 voc\xEA"
14584
- }
14722
+ loading: "Carregando\u2026",
14723
+ empty: "Nenhuma sess\xE3o ativa.",
14724
+ thisDevice: "Este dispositivo",
14725
+ activeNow: "Ativa agora",
14726
+ otherDevices: "Outros dispositivos",
14727
+ signOutDevice: (device) => `Sair de ${device}`,
14728
+ signingOut: "Saindo\u2026",
14729
+ signOutThisDevice: "Sair deste dispositivo",
14730
+ noOtherDevices: "N\xE3o h\xE1 outros dispositivos para sair",
14731
+ signOutEverywhere: "Sair de todos os dispositivos",
14732
+ unknownDevice: "Dispositivo desconhecido",
14733
+ revokeFailed: "N\xE3o foi poss\xEDvel sair desse dispositivo. Tente novamente.",
14734
+ justNow: "agora mesmo",
14735
+ secondsAgo: (n) => `h\xE1 ${n} s`,
14736
+ minutesAgo: (n) => `h\xE1 ${n} min`,
14737
+ hoursAgo: (n) => `h\xE1 ${n} h`,
14738
+ daysAgo: (n) => `h\xE1 ${n} d`
14585
14739
  }
14586
14740
  };
14587
- function labelOf2(request, copy) {
14588
- const op = request.operation ?? "";
14589
- return copy.operations[op] ?? (op ? op.replace(/_/g, " ") : copy.transaction);
14741
+ function describeDevice(s, copy) {
14742
+ if (s.deviceLabel) return normalizeDeviceLabel(s.deviceLabel);
14743
+ if (!s.userAgent) return copy.unknownDevice;
14744
+ return parseUserAgent(s.userAgent);
14745
+ }
14746
+ function normalizeDeviceLabel(label) {
14747
+ const parts = label.replace(/\s+/g, " ").split(/ (?:[—–-]|·) /);
14748
+ if (parts.length === 2 && parts[1] !== void 0) return `${parts[0]} \xB7 ${parts[1].toLowerCase()}`;
14749
+ return label;
14750
+ }
14751
+ function detectBrowser(ua) {
14752
+ if (/Edg\//.test(ua)) return "Edge";
14753
+ if (/OPR\//.test(ua)) return "Opera";
14754
+ if (/(Chrome|CriOS)\//.test(ua)) return "Chrome";
14755
+ if (/(Firefox|FxiOS)\//.test(ua)) return "Firefox";
14756
+ if (/Safari\//.test(ua)) return "Safari";
14757
+ return null;
14758
+ }
14759
+ function detectOS(ua) {
14760
+ if (/iPhone|iPad|iPod/.test(ua)) return "iOS";
14761
+ if (/Android/.test(ua)) return "Android";
14762
+ if (/Mac OS X/.test(ua)) return "macOS";
14763
+ if (/Windows NT/.test(ua)) return "Windows";
14764
+ if (/Linux/.test(ua)) return "Linux";
14765
+ return null;
14590
14766
  }
14591
- function expiresIn(request, copy) {
14592
- const ms = new Date(request.expiresAt).getTime() - Date.now();
14593
- if (!Number.isFinite(ms) || ms <= 0) return copy.expired;
14594
- const h = Math.floor(ms / 36e5);
14595
- const m = Math.floor(ms % 36e5 / 6e4);
14596
- return h > 0 ? `${h}h ${m}m` : `${m}m`;
14767
+ function parseUserAgent(ua) {
14768
+ const browser = detectBrowser(ua);
14769
+ const os = detectOS(ua);
14770
+ if (browser && os) return `${os} \xB7 ${browser.toLowerCase()}`;
14771
+ if (os) return os;
14772
+ if (browser) return browser;
14773
+ return ua.slice(0, 48);
14597
14774
  }
14598
- function outcomeText(request, copy) {
14599
- if (request.status !== "APPROVED")
14600
- return `${copy.status[request.status] ?? request.status.toLowerCase()}. ${copy.nothingSigned}`;
14601
- if (request.submit?.hash) return copy.signedSent;
14602
- if (request.signedXdr) return copy.signedAppSends;
14603
- return copy.status.APPROVED ?? "Approved";
14775
+ function formatRelative(iso, copy) {
14776
+ if (!iso) return "\u2014";
14777
+ const ts = new Date(iso).getTime();
14778
+ if (!Number.isFinite(ts)) return "\u2014";
14779
+ const diffSec = Math.round((Date.now() - ts) / 1e3);
14780
+ if (diffSec < 0) return copy.justNow;
14781
+ if (diffSec < 60) return copy.secondsAgo(diffSec);
14782
+ const diffMin = Math.round(diffSec / 60);
14783
+ if (diffMin < 60) return copy.minutesAgo(diffMin);
14784
+ const diffHr = Math.round(diffMin / 60);
14785
+ if (diffHr < 24) return copy.hoursAgo(diffHr);
14786
+ const diffDay = Math.round(diffHr / 24);
14787
+ if (diffDay < 30) return copy.daysAgo(diffDay);
14788
+ return new Date(iso).toLocaleDateString(void 0, { month: "short", day: "numeric", year: "numeric" });
14604
14789
  }
14605
- function StepRow({
14606
- request,
14607
- review,
14608
- copy,
14609
- language
14610
- }) {
14611
- const [open, setOpen] = react.useState(false);
14612
- const ok = request.status === "APPROVED";
14613
- return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: `pollar-cosign-step${ok ? "" : " pollar-cosign-step-bad"}`, children: [
14614
- /* @__PURE__ */ jsxRuntime.jsxs("button", { type: "button", className: "pollar-cosign-step-head", "aria-expanded": open, onClick: () => setOpen((v) => !v), children: [
14615
- /* @__PURE__ */ jsxRuntime.jsx(OutcomeIcon, { ok }),
14616
- /* @__PURE__ */ jsxRuntime.jsx("span", { className: "pollar-cosign-step-title", children: review.title }),
14617
- /* @__PURE__ */ jsxRuntime.jsx("span", { className: "pollar-cosign-step-status", children: ok ? copy.signed : copy.status[request.status] ?? request.status }),
14618
- /* @__PURE__ */ jsxRuntime.jsx(
14619
- "svg",
14620
- {
14621
- width: "10",
14622
- height: "10",
14623
- viewBox: "0 0 12 12",
14624
- fill: "none",
14625
- "aria-hidden": true,
14626
- style: { transform: open ? "rotate(180deg)" : "none", transition: "transform 150ms" },
14627
- children: /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M2 4l4 4 4-4", stroke: "currentColor", strokeWidth: "1.6", strokeLinecap: "round", strokeLinejoin: "round" })
14628
- }
14629
- )
14630
- ] }),
14631
- open && /* @__PURE__ */ jsxRuntime.jsx(TxReview, { data: review, language, detailsOnly: true })
14790
+ function shortIp(hash) {
14791
+ if (!hash) return "";
14792
+ return hash.slice(0, 8);
14793
+ }
14794
+ function deviceKind(session) {
14795
+ const value = `${session.deviceLabel ?? ""} ${session.userAgent ?? ""}`.toLowerCase();
14796
+ if (/ipad|tablet/.test(value)) return "tablet";
14797
+ if (/android|iphone|ipod|mobile|phone/.test(value)) return "phone";
14798
+ return "desktop";
14799
+ }
14800
+ function DeviceIcon({ kind, size = "small" }) {
14801
+ const dimensions = size === "large" ? 30 : 18;
14802
+ if (kind === "phone") {
14803
+ return /* @__PURE__ */ jsxRuntime.jsxs("svg", { width: dimensions, height: dimensions, viewBox: "0 0 24 24", fill: "none", "aria-hidden": true, children: [
14804
+ /* @__PURE__ */ jsxRuntime.jsx("rect", { x: "7", y: "2.5", width: "10", height: "19", rx: "2.5", stroke: "currentColor", strokeWidth: "1.8" }),
14805
+ /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M10.5 5h3M11 18.5h2", stroke: "currentColor", strokeWidth: "1.6", strokeLinecap: "round" })
14806
+ ] });
14807
+ }
14808
+ if (kind === "tablet") {
14809
+ return /* @__PURE__ */ jsxRuntime.jsxs("svg", { width: dimensions, height: dimensions, viewBox: "0 0 24 24", fill: "none", "aria-hidden": true, children: [
14810
+ /* @__PURE__ */ jsxRuntime.jsx("rect", { x: "4.5", y: "2.5", width: "15", height: "19", rx: "2", stroke: "currentColor", strokeWidth: "1.8" }),
14811
+ /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M11 18.5h2", stroke: "currentColor", strokeWidth: "1.6", strokeLinecap: "round" })
14812
+ ] });
14813
+ }
14814
+ return /* @__PURE__ */ jsxRuntime.jsxs("svg", { width: dimensions, height: dimensions, viewBox: "0 0 24 24", fill: "none", "aria-hidden": true, children: [
14815
+ /* @__PURE__ */ jsxRuntime.jsx("rect", { x: "3", y: "3.5", width: "18", height: "12", rx: "1.8", stroke: "currentColor", strokeWidth: "1.8" }),
14816
+ /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M8 20.5h8M12 15.5v5", stroke: "currentColor", strokeWidth: "1.8", strokeLinecap: "round" })
14632
14817
  ] });
14633
14818
  }
14819
+ function CheckIcon() {
14820
+ return /* @__PURE__ */ jsxRuntime.jsx("svg", { width: "12", height: "12", viewBox: "0 0 12 12", fill: "none", "aria-hidden": true, children: /* @__PURE__ */ jsxRuntime.jsx("path", { d: "m2.5 6.2 2.1 2.1L9.6 3.6", stroke: "currentColor", strokeWidth: "1.7", strokeLinecap: "round", strokeLinejoin: "round" }) });
14821
+ }
14634
14822
  function CloseIcon2() {
14635
14823
  return /* @__PURE__ */ jsxRuntime.jsx("svg", { width: "14", height: "14", viewBox: "0 0 14 14", fill: "none", "aria-hidden": true, children: /* @__PURE__ */ jsxRuntime.jsx("path", { d: "m3 3 8 8M11 3l-8 8", stroke: "currentColor", strokeWidth: "1.7", strokeLinecap: "round" }) });
14636
14824
  }
14637
- function VerifiedIcon() {
14638
- return /* @__PURE__ */ jsxRuntime.jsxs("svg", { width: "14", height: "14", viewBox: "0 0 14 14", fill: "none", "aria-hidden": true, children: [
14639
- /* @__PURE__ */ jsxRuntime.jsx("circle", { cx: "7", cy: "7", r: "7", fill: "currentColor" }),
14640
- /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M3.5 7l2.5 2.5 4.5-5", stroke: "white", strokeWidth: "1.4", strokeLinecap: "round", strokeLinejoin: "round" })
14641
- ] });
14642
- }
14643
- function CosignModalTemplate({
14825
+ function SessionsModalTemplate({
14644
14826
  theme,
14645
14827
  accentColor,
14646
14828
  styleOverrides,
14647
- pending,
14648
- current,
14649
- verification,
14650
- busy,
14651
- error,
14652
- approveBlocked = false,
14653
- deviceNotLinked = false,
14654
- onLinkDevice,
14655
- lastResolved,
14656
- history = [],
14657
- explorerUrlOf,
14658
- closesIn = null,
14659
- nextStep = null,
14660
- language: languageProp,
14661
- network,
14662
- onSelect,
14663
- onApprove,
14664
- onReject,
14829
+ state,
14830
+ revokingFamilyId,
14831
+ signingOutEverywhere,
14832
+ revokeError,
14833
+ onRefresh,
14834
+ onRevoke,
14835
+ onLogoutEverywhere,
14665
14836
  onClose,
14666
- confirmingClose = false,
14667
- onKeepOpen,
14668
- onCloseAnyway
14837
+ language: languageProp
14669
14838
  }) {
14670
14839
  const language = useInheritedLanguage(languageProp);
14671
- const copy = COSIGN_COPY[language];
14840
+ const copy = SESSIONS_COPY[language];
14672
14841
  const cssVars = buildModalCssVars(theme, accentColor, styleOverrides);
14673
- const verified = verification?.ok === true && !deviceNotLinked;
14674
- const canVote = !!current && verified && !busy && !approveBlocked;
14675
- const [verifiedOpenFor, setVerifiedOpenFor] = react.useState(null);
14676
- const verifiedOpen = !!current && verifiedOpenFor === current.id;
14677
- const reviewOf = (request) => reviewFromRequest(
14678
- {
14679
- chain: request.network,
14680
- network,
14681
- operation: request.operation,
14682
- summary: request.summary,
14683
- details: request.details,
14684
- signWith: request.account ?? request.signWith,
14685
- raw: request.unsignedPayload,
14686
- fallbackTitle: labelOf2(request, copy),
14687
- ...request.status === "PENDING" ? { extraRows: [{ label: copy.expiresIn, value: expiresIn(request, copy) }] } : {},
14688
- appPaysFee: request.submit?.sponsored ?? request.appPaysFee,
14689
- ...request.submit?.hash ? { hash: { value: request.submit.hash, explorerUrl: explorerUrlOf?.(request) ?? null } } : {}
14690
- },
14691
- TX_REVIEW_COPY[language]
14692
- );
14693
- const review = current ? reviewOf(current) : null;
14694
- const grouped = pending.length > 1;
14695
- const shown = grouped ? null : current ?? (pending.length === 0 ? lastResolved : void 0) ?? null;
14696
- const shownReview = shown ? shown === current ? review : reviewOf(shown) : null;
14697
- const doneSteps = history.filter((r) => !(pending.length === 0 && r.id === lastResolved?.id));
14698
- const heading = confirmingClose ? copy.closeTitle : grouped ? copy.manyPending(pending.length) : shownReview?.title ?? copy.title;
14699
- const chip = current && !confirmingClose && /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
14700
- !verification && !deviceNotLinked && /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "pollar-cosign-chip", children: [
14701
- /* @__PURE__ */ jsxRuntime.jsx("span", { className: "pollar-spinner pollar-spinner-sm", "aria-hidden": true }),
14702
- copy.checking
14703
- ] }),
14704
- verified && /* @__PURE__ */ jsxRuntime.jsxs(
14705
- "button",
14706
- {
14707
- type: "button",
14708
- className: "pollar-cosign-chip pollar-cosign-chip-ok",
14709
- "aria-expanded": verifiedOpen,
14710
- onClick: () => setVerifiedOpenFor(verifiedOpen ? null : current.id),
14711
- children: [
14712
- /* @__PURE__ */ jsxRuntime.jsx(VerifiedIcon, {}),
14713
- copy.verified
14714
- ]
14715
- }
14716
- )
14717
- ] });
14842
+ const isLoading = state.step === "loading";
14843
+ const sessions = state.step === "loaded" ? state.sessions : [];
14844
+ const currentSession = sessions.find((s) => s.current);
14845
+ const otherSessions = sessions.filter((s) => !s.current);
14846
+ const otherCount = otherSessions.length;
14718
14847
  return /* @__PURE__ */ jsxRuntime.jsxs(
14719
14848
  "div",
14720
14849
  {
14721
- className: "pollar-modal-card pollar-cosign-modal",
14850
+ className: "pollar-modal-card pollar-sessions-modal",
14722
14851
  "data-theme": theme,
14723
14852
  style: cssVars,
14724
14853
  onClick: (e) => e.stopPropagation(),
14725
14854
  children: [
14726
14855
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pollar-modal-header", children: [
14727
- /* @__PURE__ */ jsxRuntime.jsxs("h2", { className: "pollar-modal-title pollar-cosign-heading", children: [
14728
- !confirmingClose && /* @__PURE__ */ jsxRuntime.jsx(TitleMark, { chain: shown?.network, asset: shownReview ? headlineAsset(shownReview) : void 0 }),
14729
- /* @__PURE__ */ jsxRuntime.jsx("span", { children: heading })
14730
- ] }),
14731
- /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pollar-modal-header-actions", children: [
14732
- !grouped && chip,
14733
- !confirmingClose && /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", className: "pollar-modal-close", onClick: onClose, "aria-label": copy.close, title: copy.close, children: /* @__PURE__ */ jsxRuntime.jsx(CloseIcon2, {}) })
14734
- ] })
14735
- ] }),
14736
- confirmingClose ? /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pollar-cosign-leave", children: [
14737
- /* @__PURE__ */ jsxRuntime.jsx("p", { className: "pollar-cosign-muted", children: copy.closeBody }),
14738
- /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", className: "pollar-cosign-btn pollar-cosign-btn-primary", onClick: onKeepOpen, children: copy.backToSign }),
14739
- /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", className: "pollar-cosign-text-btn", onClick: onCloseAnyway, children: copy.closeAnyway })
14740
- ] }) : /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
14741
- doneSteps.map((r) => /* @__PURE__ */ jsxRuntime.jsx(StepRow, { request: r, review: reviewOf(r), copy, language }, r.id)),
14742
- pending.length === 0 && (lastResolved && shownReview ? /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pollar-cosign-detail", children: [
14743
- /* @__PURE__ */ jsxRuntime.jsx(TxReview, { data: shownReview, language }, lastResolved.id),
14744
- /* @__PURE__ */ jsxRuntime.jsxs("div", { className: `pollar-outcome${lastResolved.status === "APPROVED" ? "" : " pollar-outcome-bad"}`, children: [
14745
- /* @__PURE__ */ jsxRuntime.jsxs("p", { className: "pollar-outcome-main", children: [
14746
- /* @__PURE__ */ jsxRuntime.jsx(OutcomeIcon, { ok: lastResolved.status === "APPROVED" }),
14747
- outcomeText(lastResolved, copy)
14748
- ] }),
14749
- nextStep && /* @__PURE__ */ jsxRuntime.jsxs("p", { className: "pollar-outcome-note", children: [
14750
- /* @__PURE__ */ jsxRuntime.jsx("span", { className: "pollar-spinner pollar-spinner-sm", "aria-hidden": true }),
14751
- " ",
14752
- copy.next(nextStep)
14753
- ] }),
14754
- closesIn !== null && /* @__PURE__ */ jsxRuntime.jsx("p", { className: "pollar-outcome-note", children: copy.closingIn(closesIn) })
14755
- ] })
14756
- ] }) : /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pollar-cosign-empty", children: [
14757
- /* @__PURE__ */ jsxRuntime.jsx("p", { className: "pollar-cosign-muted", children: copy.nothingWaiting }),
14758
- closesIn !== null && /* @__PURE__ */ jsxRuntime.jsx("p", { className: "pollar-cosign-muted pollar-cosign-closing", children: copy.closingIn(closesIn) })
14759
- ] })),
14760
- grouped && /* @__PURE__ */ jsxRuntime.jsx("ul", { className: "pollar-cosign-list", children: pending.map((r) => /* @__PURE__ */ jsxRuntime.jsx("li", { children: /* @__PURE__ */ jsxRuntime.jsxs(
14761
- "button",
14762
- {
14763
- type: "button",
14764
- className: `pollar-cosign-item${current?.id === r.id ? " pollar-cosign-item-active" : ""}`,
14765
- onClick: () => onSelect(r),
14766
- children: [
14767
- /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "pollar-cosign-heading", children: [
14768
- /* @__PURE__ */ jsxRuntime.jsx(TitleMark, { chain: r.network, asset: headlineAsset(reviewOf(r)) }),
14769
- reviewOf(r).title
14770
- ] }),
14771
- /* @__PURE__ */ jsxRuntime.jsx("span", { className: "pollar-cosign-muted", children: expiresIn(r, copy) })
14772
- ]
14773
- }
14774
- ) }, r.id)) }),
14775
- current && review && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: `pollar-cosign-detail${grouped ? " pollar-cosign-detail-grouped" : ""}`, children: [
14776
- grouped && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pollar-cosign-detail-head", children: [
14777
- /* @__PURE__ */ jsxRuntime.jsx("p", { className: "pollar-cosign-detail-title", children: review.title }),
14778
- chip
14779
- ] }),
14780
- /* @__PURE__ */ jsxRuntime.jsx(
14781
- TxReview,
14782
- {
14783
- data: review,
14784
- language,
14785
- detailsIntro: { title: copy.whyTitle, body: copy.whyBody },
14786
- detailsAction: {
14787
- label: busy === "rejecting" ? copy.rejecting : copy.rejectRequest,
14788
- onClick: () => onReject(current),
14789
- disabled: !!busy
14790
- }
14791
- },
14792
- current.id
14793
- ),
14794
- verified && verifiedOpen && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "pollar-cosign-verify pollar-cosign-verify-ok", children: copy.checkedExact }),
14795
- deviceNotLinked ? /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pollar-cosign-verify pollar-cosign-verify-bad", children: [
14796
- copy.deviceNotLinked,
14797
- onLinkDevice && /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", className: "pollar-cosign-link", onClick: onLinkDevice, children: copy.linkDevice })
14798
- ] }) : verification && !verification.ok && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pollar-cosign-verify pollar-cosign-verify-bad", children: [
14799
- copy.notVerified,
14800
- " ",
14801
- verification.reason
14802
- ] }),
14803
- error && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "pollar-cosign-error", children: error }),
14856
+ /* @__PURE__ */ jsxRuntime.jsx("h2", { className: "pollar-modal-title", children: copy.title }),
14857
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pollar-modal-header-actions", children: [
14804
14858
  /* @__PURE__ */ jsxRuntime.jsx(
14805
14859
  "button",
14806
14860
  {
14807
14861
  type: "button",
14808
- className: "pollar-cosign-btn pollar-cosign-btn-primary",
14809
- disabled: !canVote,
14810
- onClick: () => onApprove(current),
14811
- children: busy === "approving" ? copy.approving : review.kind === "activate_wallet" ? copy.activateWallet : copy.approve
14862
+ className: "pollar-modal-close",
14863
+ onClick: onRefresh,
14864
+ disabled: isLoading,
14865
+ "aria-label": copy.refresh,
14866
+ title: copy.refresh,
14867
+ children: /* @__PURE__ */ jsxRuntime.jsx(RefreshIcon, { spinning: isLoading })
14812
14868
  }
14813
- )
14869
+ ),
14870
+ /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", className: "pollar-modal-close", onClick: onClose, "aria-label": copy.close, title: copy.close, children: /* @__PURE__ */ jsxRuntime.jsx(CloseIcon2, {}) })
14814
14871
  ] })
14815
14872
  ] }),
14873
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pollar-sessions-list", children: [
14874
+ (state.step === "idle" || isLoading) && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pollar-loading-block", children: [
14875
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "pollar-spinner" }),
14876
+ /* @__PURE__ */ jsxRuntime.jsx("span", { children: copy.loading })
14877
+ ] }),
14878
+ state.step === "error" && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "pollar-modal-empty", children: state.message }),
14879
+ state.step === "loaded" && sessions.length === 0 && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "pollar-modal-empty", children: copy.empty }),
14880
+ state.step === "loaded" && currentSession && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pollar-sessions-current-card", children: [
14881
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pollar-sessions-current-icon-wrap", children: [
14882
+ /* @__PURE__ */ jsxRuntime.jsx(DeviceIcon, { kind: deviceKind(currentSession), size: "large" }),
14883
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "pollar-sessions-current-check", children: /* @__PURE__ */ jsxRuntime.jsx(CheckIcon, {}) })
14884
+ ] }),
14885
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "pollar-sessions-current-label", children: copy.thisDevice }),
14886
+ /* @__PURE__ */ jsxRuntime.jsx("strong", { className: "pollar-sessions-current-device", children: describeDevice(currentSession, copy) }),
14887
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pollar-sessions-current-status", children: [
14888
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "pollar-sessions-status-dot" }),
14889
+ /* @__PURE__ */ jsxRuntime.jsx("span", { children: copy.activeNow }),
14890
+ currentSession.ipHash && /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
14891
+ /* @__PURE__ */ jsxRuntime.jsx("span", { children: "\xB7" }),
14892
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { title: `ip-hash ${currentSession.ipHash}`, children: [
14893
+ "IP ",
14894
+ shortIp(currentSession.ipHash)
14895
+ ] })
14896
+ ] })
14897
+ ] })
14898
+ ] }),
14899
+ state.step === "loaded" && otherSessions.length > 0 && /* @__PURE__ */ jsxRuntime.jsxs("section", { className: "pollar-sessions-other-section", "aria-labelledby": "pollar-other-devices-heading", children: [
14900
+ /* @__PURE__ */ jsxRuntime.jsxs("h3", { id: "pollar-other-devices-heading", className: "pollar-sessions-section-title", children: [
14901
+ copy.otherDevices,
14902
+ " ",
14903
+ /* @__PURE__ */ jsxRuntime.jsx("span", { children: otherCount })
14904
+ ] }),
14905
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "pollar-sessions-grid", children: otherSessions.map((s) => {
14906
+ const isRevoking = revokingFamilyId === s.familyId;
14907
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pollar-sessions-item", children: [
14908
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pollar-sessions-item-top", children: [
14909
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "pollar-sessions-item-icon", children: /* @__PURE__ */ jsxRuntime.jsx(DeviceIcon, { kind: deviceKind(s) }) }),
14910
+ /* @__PURE__ */ jsxRuntime.jsx(
14911
+ "button",
14912
+ {
14913
+ type: "button",
14914
+ className: "pollar-sessions-item-revoke",
14915
+ onClick: () => onRevoke(s.familyId),
14916
+ disabled: isRevoking || signingOutEverywhere,
14917
+ "aria-label": copy.signOutDevice(describeDevice(s, copy)),
14918
+ title: isRevoking ? copy.signingOut : copy.signOutThisDevice,
14919
+ children: isRevoking ? /* @__PURE__ */ jsxRuntime.jsx("span", { className: "pollar-spinner pollar-spinner-sm" }) : /* @__PURE__ */ jsxRuntime.jsx(CloseIcon2, {})
14920
+ }
14921
+ )
14922
+ ] }),
14923
+ /* @__PURE__ */ jsxRuntime.jsx("strong", { className: "pollar-sessions-item-device", children: describeDevice(s, copy) }),
14924
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "pollar-sessions-item-meta", children: formatRelative(s.lastUsedAt ?? s.createdAt, copy) })
14925
+ ] }, s.familyId);
14926
+ }) })
14927
+ ] }),
14928
+ revokeError && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "pollar-sessions-action-error", role: "alert", children: revokeError })
14929
+ ] }),
14930
+ state.step === "loaded" && sessions.length > 0 && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "pollar-sessions-actions", children: /* @__PURE__ */ jsxRuntime.jsx(
14931
+ "button",
14932
+ {
14933
+ className: "pollar-sessions-logout-all",
14934
+ onClick: onLogoutEverywhere,
14935
+ disabled: signingOutEverywhere || otherCount === 0,
14936
+ title: otherCount === 0 ? copy.noOtherDevices : void 0,
14937
+ children: signingOutEverywhere ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
14938
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "pollar-spinner pollar-spinner-sm pollar-spinner-current" }),
14939
+ copy.signingOut
14940
+ ] }) : copy.signOutEverywhere
14941
+ }
14942
+ ) }),
14816
14943
  /* @__PURE__ */ jsxRuntime.jsx(PollarModalFooter, {})
14817
14944
  ]
14818
14945
  }
14819
14946
  );
14820
14947
  }
14821
- var CLOSE_AFTER_SECONDS = 3;
14822
- var CLOSE_AFTER_SENT_SECONDS = 5;
14823
- var NEXT_REQUEST_EVERY_MS = 2e3;
14824
- function CosignModal({ nextStep = null, onClose }) {
14825
- const { getClient, styles, network, openRecoveryModal } = usePollar();
14948
+ function SessionsModal({ onClose }) {
14949
+ const { getClient, styles, sessions } = usePollar();
14826
14950
  const { theme, accentColor, styleOverrides, overlayStyle } = modalChrome(styles);
14827
- const { pending, lastResolved, loaded, refresh, approve, reject, verify, inspectQuorum } = useCosign();
14828
14951
  const language = useModalLanguage();
14829
- const [selectedId, setSelectedId] = react.useState(null);
14830
- const [verification, setVerification] = react.useState(null);
14831
- const [busy, setBusy] = react.useState(null);
14832
- const [error, setError] = react.useState(null);
14833
- const [approveFailedFor, setApproveFailedFor] = react.useState(null);
14834
- const [quorumFailure, setQuorumFailure] = react.useState(null);
14835
- const [deviceNotLinked, setDeviceNotLinked] = react.useState(false);
14836
- react.useEffect(() => {
14837
- let cancelled = false;
14838
- inspectQuorum().then((q) => {
14839
- if (cancelled || q.ok) return;
14840
- if (q.code === "DEVICE_NOT_ENROLLED") setDeviceNotLinked(true);
14841
- else setQuorumFailure(q.reason);
14842
- }).catch(() => void 0);
14843
- return () => {
14844
- cancelled = true;
14845
- };
14846
- }, [inspectQuorum]);
14847
- const current = pending.find((r) => r.id === selectedId) ?? pending[0] ?? null;
14848
- const [history, setHistory] = react.useState([]);
14849
- const resolvedBeforeOpen = react.useRef(lastResolved?.id);
14850
- react.useEffect(() => {
14851
- if (!lastResolved || lastResolved.id === resolvedBeforeOpen.current) return;
14852
- setHistory((list) => [...list.filter((r) => r.id !== lastResolved.id), lastResolved]);
14853
- }, [lastResolved]);
14854
- const [askedToClose, setAskedToClose] = react.useState(false);
14855
- const confirmingClose = askedToClose && pending.length > 0;
14856
- const requestClose = () => pending.length > 0 ? setAskedToClose(true) : onClose();
14857
- const currentRef = react.useRef(current);
14858
- currentRef.current = current;
14859
- const currentId = current?.id ?? null;
14952
+ const copy = SESSIONS_COPY[language];
14953
+ const [revokingFamilyId, setRevokingFamilyId] = react.useState(null);
14954
+ const [signingOutEverywhere, setSigningOutEverywhere] = react.useState(false);
14955
+ const [revokeError, setRevokeError] = react.useState(null);
14956
+ const load = react.useCallback(() => {
14957
+ void getClient().fetchSessions();
14958
+ }, [getClient]);
14860
14959
  react.useEffect(() => {
14861
- const request = currentRef.current;
14862
- if (!request) return;
14863
- setVerification(null);
14864
- setError(null);
14865
- setApproveFailedFor(null);
14866
- let cancelled = false;
14867
- verify(request).then((v) => {
14868
- if (!cancelled) setVerification(v);
14869
- }).catch((err) => {
14870
- if (!cancelled) setVerification({ ok: false, reason: err instanceof Error ? err.message : String(err) });
14871
- });
14872
- return () => {
14873
- cancelled = true;
14874
- };
14875
- }, [currentId, verify]);
14960
+ load();
14961
+ }, [load]);
14876
14962
  const onCloseRef = react.useRef(onClose);
14877
14963
  onCloseRef.current = onClose;
14878
14964
  react.useEffect(() => {
@@ -14880,87 +14966,45 @@ function CosignModal({ nextStep = null, onClose }) {
14880
14966
  if (authState.step === "idle") onCloseRef.current();
14881
14967
  });
14882
14968
  }, [getClient]);
14883
- const silent = pending.length === 0 && (lastResolved ? lastResolved.status === "APPROVED" && !lastResolved.submit?.hash && !lastResolved.signedXdr : loaded);
14884
- const sent = pending.length === 0 && lastResolved?.status === "APPROVED" && !!lastResolved.submit?.hash;
14885
- const awaitingNext = sent && !!nextStep;
14886
- const closeAfter = awaitingNext ? null : sent ? CLOSE_AFTER_SENT_SECONDS : silent ? CLOSE_AFTER_SECONDS : null;
14887
- react.useEffect(() => {
14888
- if (!awaitingNext) return;
14889
- const timer = setInterval(() => void refresh().catch(() => void 0), NEXT_REQUEST_EVERY_MS);
14890
- return () => clearInterval(timer);
14891
- }, [awaitingNext, refresh]);
14892
- const [closesIn, setClosesIn] = react.useState(null);
14893
- react.useEffect(() => {
14894
- if (closeAfter === null) {
14895
- setClosesIn(null);
14896
- return;
14897
- }
14898
- let left = closeAfter;
14899
- setClosesIn(left);
14900
- const timer = setInterval(() => {
14901
- left -= 1;
14902
- if (left > 0) setClosesIn(left);
14903
- else {
14904
- clearInterval(timer);
14905
- onCloseRef.current();
14906
- }
14907
- }, 1e3);
14908
- return () => clearInterval(timer);
14909
- }, [closeAfter, lastResolved?.id]);
14910
- const run = react.useCallback(
14911
- async (kind, request, action) => {
14912
- setBusy(kind);
14913
- setError(null);
14969
+ const handleRevoke = react.useCallback(
14970
+ async (familyId) => {
14971
+ setRevokingFamilyId(familyId);
14972
+ setRevokeError(null);
14914
14973
  try {
14915
- await action(request);
14916
- } catch (err) {
14917
- if (core.isPollarNetworkError(err) || err instanceof TypeError) {
14918
- setError(COSIGN_COPY[language].unreachable);
14919
- void refresh().catch(() => void 0);
14920
- return;
14921
- }
14922
- setError(
14923
- core.transactionErrorMessage(core.isPollarApiError(err) ? err.code : null, err instanceof Error ? err.message : null, language)
14924
- );
14925
- if (kind === "approving" && !(core.isPollarApiError(err) && err.code === "SDK_COSIGN_GAS_PENDING"))
14926
- setApproveFailedFor(request.id);
14974
+ await getClient().revokeSession(familyId);
14975
+ } catch {
14976
+ setRevokeError(copy.revokeFailed);
14927
14977
  } finally {
14928
- setBusy(null);
14978
+ setRevokingFamilyId(null);
14979
+ load();
14929
14980
  }
14930
14981
  },
14931
- [language, refresh]
14982
+ [getClient, load, copy]
14932
14983
  );
14933
- return /* @__PURE__ */ jsxRuntime.jsx(PollarOverlay, { style: overlayStyle, children: /* @__PURE__ */ jsxRuntime.jsx(
14934
- CosignModalTemplate,
14984
+ const handleLogoutEverywhere = react.useCallback(async () => {
14985
+ setSigningOutEverywhere(true);
14986
+ try {
14987
+ await getClient().logoutEverywhere();
14988
+ onClose();
14989
+ } catch {
14990
+ setSigningOutEverywhere(false);
14991
+ }
14992
+ }, [getClient, onClose]);
14993
+ return /* @__PURE__ */ jsxRuntime.jsx(PollarOverlay, { style: overlayStyle, onClick: onClose, children: /* @__PURE__ */ jsxRuntime.jsx(
14994
+ SessionsModalTemplate,
14935
14995
  {
14936
14996
  theme,
14937
14997
  accentColor,
14938
14998
  styleOverrides,
14939
- pending,
14940
- current,
14941
- verification: current ? quorumFailure ? { ok: false, reason: quorumFailure } : verification : null,
14942
- busy,
14943
- error,
14944
- approveBlocked: !!current && approveFailedFor === current.id,
14945
- deviceNotLinked,
14946
- onLinkDevice: () => {
14947
- onClose();
14948
- openRecoveryModal();
14949
- },
14950
- ...lastResolved ? { lastResolved } : {},
14951
- closesIn,
14952
- nextStep: awaitingNext ? nextStep : null,
14953
- language,
14954
- network,
14955
- history,
14956
- explorerUrlOf: (r) => r.submit?.hash ? explorerTxUrl(r.network, r.submit.hash, network) : null,
14957
- onSelect: (r) => setSelectedId(r.id),
14958
- onApprove: (r) => void run("approving", r, approve),
14959
- onReject: (r) => void run("rejecting", r, reject),
14960
- onClose: requestClose,
14961
- confirmingClose,
14962
- onKeepOpen: () => setAskedToClose(false),
14963
- onCloseAnyway: onClose
14999
+ state: sessions,
15000
+ revokingFamilyId,
15001
+ signingOutEverywhere,
15002
+ revokeError,
15003
+ onRefresh: () => load(),
15004
+ onRevoke: (familyId) => void handleRevoke(familyId),
15005
+ onLogoutEverywhere: () => void handleLogoutEverywhere(),
15006
+ onClose,
15007
+ language
14964
15008
  }
14965
15009
  ) });
14966
15010
  }
@@ -15621,6 +15665,7 @@ function RecoveryModalTemplate(p) {
15621
15665
  );
15622
15666
  }
15623
15667
  var APPROVAL_POLL_MS = 3e3;
15668
+ var RELOAD_AFTER_FAILURE_MS = 5e3;
15624
15669
  var APPROVAL_WINDOW_MS = 15 * 6e4;
15625
15670
  function errorText3(err, language) {
15626
15671
  return core.cosignRefusalMessage(err, language) ?? core.transactionErrorMessage(core.isPollarApiError(err) ? err.code : null, err instanceof Error ? err.message : null, language);
@@ -15672,12 +15717,17 @@ function RecoveryModal({ onClose }) {
15672
15717
  setError(null);
15673
15718
  setNotice(null);
15674
15719
  try {
15675
- await action();
15676
- await load();
15720
+ try {
15721
+ await action();
15722
+ } catch (err) {
15723
+ setError(errorText3(err, language));
15724
+ return;
15725
+ }
15726
+ await load().catch(() => {
15727
+ setTimeout(() => void load().catch(() => void 0), RELOAD_AFTER_FAILURE_MS);
15728
+ });
15677
15729
  if (after?.notice) setNotice(after.notice);
15678
15730
  if (after?.view) setView(after.view);
15679
- } catch (err) {
15680
- setError(errorText3(err, language));
15681
15731
  } finally {
15682
15732
  setBusy(null);
15683
15733
  }
@@ -15701,10 +15751,10 @@ function RecoveryModal({ onClose }) {
15701
15751
  setNotice(copy.deviceAdded);
15702
15752
  return;
15703
15753
  }
15704
- const timer = setInterval(() => void load().catch(() => void 0), APPROVAL_POLL_MS);
15754
+ const stopPoll = core.startBackoffPoll(load, APPROVAL_POLL_MS);
15705
15755
  const stop = setTimeout(() => setAwaitingApproval(false), APPROVAL_WINDOW_MS);
15706
15756
  return () => {
15707
- clearInterval(timer);
15757
+ stopPoll();
15708
15758
  clearTimeout(stop);
15709
15759
  };
15710
15760
  }, [awaitingApproval, enrolled, load, copy]);
@@ -16913,12 +16963,17 @@ function PollarProvider({
16913
16963
  const [sessionsModalOpen, setSessionsModalOpen] = react.useState(false);
16914
16964
  const [cosignModalOpen, setCosignModalOpen] = react.useState(false);
16915
16965
  const [cosignNextStep, setCosignNextStep] = react.useState(null);
16966
+ const [cosignHosts, setCosignHosts] = react.useState(0);
16967
+ const registerCosignHost = react.useCallback(() => {
16968
+ setCosignHosts((n) => n + 1);
16969
+ return () => setCosignHosts((n) => n - 1);
16970
+ }, []);
16916
16971
  const [recoveryModalOpen, setRecoveryModalOpen] = react.useState(false);
16917
16972
  const cosignPendingCount = react.useRef(0);
16918
16973
  react.useEffect(() => {
16919
- if (cosign.pending.length > cosignPendingCount.current) setCosignModalOpen(true);
16974
+ if (cosign.pending.length > cosignPendingCount.current && cosignHosts === 0) setCosignModalOpen(true);
16920
16975
  cosignPendingCount.current = cosign.pending.length;
16921
- }, [cosign.pending.length]);
16976
+ }, [cosign.pending.length, cosignHosts]);
16922
16977
  react.useEffect(() => pollarClient.onCosignDeviceNotEnrolled(() => setRecoveryModalOpen(true)), [pollarClient]);
16923
16978
  react.useEffect(() => pollarClient.onWalletRecoveryRequired(() => setRecoveryModalOpen(true)), [pollarClient]);
16924
16979
  const [distributionRulesModalOpen, setDistributionRulesModalOpen] = react.useState(false);
@@ -16957,13 +17012,17 @@ function PollarProvider({
16957
17012
  return;
16958
17013
  }
16959
17014
  let cancelled = false;
17015
+ let retry = null;
16960
17016
  pollarClient.cosign.recovery.status().then((next) => {
16961
17017
  if (!cancelled) setRecovery(next);
16962
- }).catch(() => {
16963
- if (!cancelled) setRecovery(null);
17018
+ }).catch((err) => {
17019
+ if (cancelled) return;
17020
+ if (core.isTransientFailure(err)) retry = setTimeout(() => setRecoveryTick((t) => t + 1), 5e3 + Math.random() * 5e3);
17021
+ else setRecovery(null);
16964
17022
  });
16965
17023
  return () => {
16966
17024
  cancelled = true;
17025
+ if (retry) clearTimeout(retry);
16967
17026
  };
16968
17027
  }, [pollarClient, hasSession, walletAddress, recoveryTick]);
16969
17028
  const recoveryLocked = !!recovery && recovery.required && !recovery.configured;
@@ -16978,13 +17037,18 @@ function PollarProvider({
16978
17037
  return;
16979
17038
  }
16980
17039
  let cancelled = false;
17040
+ let retry = null;
16981
17041
  pollarClient.cosign.custodyMigration().then((next) => {
16982
17042
  if (!cancelled) setCustodyMigration(next);
16983
- }).catch(() => {
16984
- if (!cancelled) setCustodyMigration(null);
17043
+ }).catch((err) => {
17044
+ if (cancelled) return;
17045
+ if (core.isTransientFailure(err))
17046
+ retry = setTimeout(() => setCustodyMigrationTick((t) => t + 1), 5e3 + Math.random() * 5e3);
17047
+ else setCustodyMigration(null);
16985
17048
  });
16986
17049
  return () => {
16987
17050
  cancelled = true;
17051
+ if (retry) clearTimeout(retry);
16988
17052
  };
16989
17053
  }, [pollarClient, hasSession, walletAddress, custodyMigrationTick]);
16990
17054
  const refreshWalletBalance = react.useCallback(() => pollarClient.refreshBalance(), [pollarClient, walletAddress]);
@@ -17107,6 +17171,7 @@ function PollarProvider({
17107
17171
  refreshCustodyMigration,
17108
17172
  confirmations,
17109
17173
  registerConfirmationHost,
17174
+ registerCosignHost,
17110
17175
  // distribution
17111
17176
  openDistributionRulesModal: () => setDistributionRulesModalOpen(true),
17112
17177
  // network
@@ -17147,6 +17212,7 @@ function PollarProvider({
17147
17212
  cosign,
17148
17213
  confirmations,
17149
17214
  registerConfirmationHost,
17215
+ registerCosignHost,
17150
17216
  walletBalance,
17151
17217
  refreshWalletBalance,
17152
17218
  enabledAssets,
@@ -17196,7 +17262,7 @@ function PollarProvider({
17196
17262
  /* @__PURE__ */ jsxRuntime.jsx(ModalErrorBoundary, { onClose: () => setCardModalOpen(false), children: /* @__PURE__ */ jsxRuntime.jsx(CardModal, { onClose: () => setCardModalOpen(false), initial: cardModalOptions }) }, `${cardModalKey}:${walletAddress}`),
17197
17263
  receiveModalOpen && /* @__PURE__ */ jsxRuntime.jsx(ModalErrorBoundary, { onClose: () => setReceiveModalOpen(false), children: /* @__PURE__ */ jsxRuntime.jsx(ReceiveModal, { onClose: () => setReceiveModalOpen(false), initial: receiveSeed.options }) }, `receive:${receiveSeed.key}`),
17198
17264
  sessionsModalOpen && /* @__PURE__ */ jsxRuntime.jsx(ModalErrorBoundary, { onClose: () => setSessionsModalOpen(false), children: /* @__PURE__ */ jsxRuntime.jsx(SessionsModal, { onClose: () => setSessionsModalOpen(false) }) }),
17199
- cosignModalOpen && /* @__PURE__ */ jsxRuntime.jsx(ModalErrorBoundary, { onClose: () => setCosignModalOpen(false), children: /* @__PURE__ */ jsxRuntime.jsx(CosignModal, { nextStep: cosignNextStep, onClose: () => setCosignModalOpen(false) }) }),
17265
+ cosignModalOpen && cosignHosts === 0 && /* @__PURE__ */ jsxRuntime.jsx(ModalErrorBoundary, { onClose: () => setCosignModalOpen(false), children: /* @__PURE__ */ jsxRuntime.jsx(CosignModal, { nextStep: cosignNextStep, onClose: () => setCosignModalOpen(false) }) }),
17200
17266
  custodyMigration?.required && !custodyMigrationLater && /* @__PURE__ */ jsxRuntime.jsx(ModalErrorBoundary, { onClose: refreshCustodyMigration, children: /* @__PURE__ */ jsxRuntime.jsx(
17201
17267
  CustodyMigrationModal,
17202
17268
  {