@pollar/react 0.12.1-rc.25 → 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.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  'use client';
2
- import { AUTH_ERROR_CODES, authErrorMessage, rampLegTitle, rampRequirementCopy, rampTrustlineAsset, rampWalletStep, rampResolutionText, rampRailLabel, describeRampAction, rampStepTitle, rampLegStatus, rampOrderStopped, rampOrderReceive, rampLegNote, countryName, rampNoRouteText, rampFieldError, rampFieldValid, rampFailureReason, rampLegTimeLeft, rampStepStatusText, rampOrderResolutionText, rampFailureNeedsSupport, rampSupportCopy, rampCountries, rampQuoteFields, isPollarApiError, rampNextApproval, rampSupportContact, transactionErrorMessage, WalletType, bridgeSourceChains, bridgeTargetChains, isBridgeSettled, isPollarNetworkError, isPollarClient, PollarClient, isInteractiveAuthAdapter, isAuthEntryAdapterStep, completeAuthEntryStep, isKycSettled, rampTrustlineErrorText, toBaseUnits, resolveLanguage, languageFromTag, localizedText, appUnavailableMessage, fromBaseUnits, cosignRefusalMessage, assertRampStellarSigner } from '@pollar/core';
2
+ import { AUTH_ERROR_CODES, authErrorMessage, rampLegTitle, rampRequirementCopy, rampTrustlineAsset, rampWalletStep, rampResolutionText, rampRailLabel, describeRampAction, rampStepTitle, rampLegStatus, rampOrderStopped, rampOrderReceive, rampLegNote, countryName, rampNoRouteText, rampFieldError, rampFieldValid, rampFailureReason, rampLegTimeLeft, rampStepStatusText, rampOrderResolutionText, rampFailureNeedsSupport, rampSupportCopy, startBackoffPoll, isPollarNetworkError, transactionErrorMessage, isPollarApiError, isTransientApiError, rampCountries, rampQuoteFields, rampNextApproval, rampSupportContact, WalletType, bridgeSourceChains, bridgeTargetChains, isBridgeSettled, isPollarClient, PollarClient, isInteractiveAuthAdapter, isTransientFailure, isAuthEntryAdapterStep, completeAuthEntryStep, isKycSettled, rampTrustlineErrorText, toBaseUnits, resolveLanguage, languageFromTag, localizedText, appUnavailableMessage, fromBaseUnits, cosignRefusalMessage, assertRampStellarSigner } from '@pollar/core';
3
3
  import { createContext, forwardRef, useState, useCallback, useEffect, useMemo, useRef, useContext, useSyncExternalStore, useId, useLayoutEffect, Component } from 'react';
4
4
  import { jsxs, jsx, Fragment } from 'react/jsx-runtime';
5
5
  import { createPortal } from 'react-dom';
@@ -1309,7 +1309,7 @@ var PollarModalFooter = ({ language: languageProp }) => {
1309
1309
  /* @__PURE__ */ jsx("img", { src: LOGO_POLLAR_WORDMARK_ON_DARK, alt: "Pollar", className: "pollar-footer-logo pollar-logo-on-dark" }),
1310
1310
  /* @__PURE__ */ jsxs("span", { className: "pollar-footer-version", children: [
1311
1311
  "v",
1312
- "0.12.1-rc.25"
1312
+ "0.12.1-rc.27"
1313
1313
  ] })
1314
1314
  ] });
1315
1315
  };
@@ -4983,7 +4983,8 @@ function LoginModalTemplate({
4983
4983
  const cssVars = buildModalCssVars(theme, accentColor, styleOverrides, "hero");
4984
4984
  const status = authStateToStatus(authState.step);
4985
4985
  const isLoading = status === "LOADING";
4986
- const isEmailCodeError = authState.step === "error" && (authState.errorCode === AUTH_ERROR_CODES.EMAIL_CODE_EXPIRED || authState.errorCode === AUTH_ERROR_CODES.EMAIL_CODE_INVALID);
4986
+ const isEmailCodeError = authState.step === "error" && (authState.errorCode === AUTH_ERROR_CODES.EMAIL_CODE_EXPIRED || authState.errorCode === AUTH_ERROR_CODES.EMAIL_CODE_INVALID || // A rate limit or a server error on verify: the same code can go again.
4987
+ authState.errorCode === AUTH_ERROR_CODES.EMAIL_VERIFY_FAILED);
4987
4988
  const awaitingEmailCode = authState.step === "entering_code" || authState.step === "verifying_email_code" || isEmailCodeError;
4988
4989
  const statusMessage = authState.step === "error" ? authErrorMessage(authState.code, language) ?? authState.message : copy.status[authState.step];
4989
4990
  const BackButton = ({ onClick }) => /* @__PURE__ */ jsx("button", { type: "button", className: "pollar-back-btn", onClick, "aria-label": copy.back, children: /* @__PURE__ */ jsx(
@@ -5406,6 +5407,10 @@ function LoginModal({ onClose, inline = false }) {
5406
5407
  getClient().cancelLogin();
5407
5408
  }
5408
5409
  function handleRetry() {
5410
+ if (authState.step === "error" && authState.errorCode === AUTH_ERROR_CODES.EMAIL_SEND_FAILED && authState.code === "RATE_LIMITED" && authState.clientSessionId && authState.email) {
5411
+ getClient().sendEmailCode(authState.email);
5412
+ return;
5413
+ }
5409
5414
  getClient().logout();
5410
5415
  if (styles.emailEnabled) {
5411
5416
  getClient().beginEmailLogin();
@@ -5511,6 +5516,7 @@ var RAMP_COPY = {
5511
5516
  SDK_RAMPS_QUOTE_EXPIRED: "This quote expired. Find a route again.",
5512
5517
  SDK_RAMPS_QUOTE_NOT_FOUND: "This quote is no longer available. Find a route again.",
5513
5518
  SDK_RAMPS_ACTION_STALE: "This step changed. It was refreshed; try again.",
5519
+ SDK_RAMPS_ORDER_NOT_CANCELLABLE: "This order can no longer be cancelled: its funds are already moving.",
5514
5520
  SDK_RAMPS_TX_NOT_FOUND: "This operation was not found.",
5515
5521
  SDK_RAMPS_WALLET_NOT_READY: "Approve the new wallet account on your device, then try again."
5516
5522
  },
@@ -5531,6 +5537,7 @@ var RAMP_COPY = {
5531
5537
  resumeOrderFailed: "Could not resume the operation.",
5532
5538
  checkPaymentFailed: "Could not check the payment. Please try again.",
5533
5539
  retryOrderFailed: "Could not try again. Please try again.",
5540
+ cancelOrderFailed: "Could not cancel the order. Please try again.",
5534
5541
  refreshFailed: "Could not refresh.",
5535
5542
  copyFailed: "Could not copy.",
5536
5543
  awaitingAccount: "Approve the new account on your device. The order starts once it is approved.",
@@ -5628,19 +5635,38 @@ var RAMP_COPY = {
5628
5635
  startAnother: "Start another operation",
5629
5636
  newQuote: "Get a new quote",
5630
5637
  keepsGoing: "This one keeps going; you can resume it later.",
5638
+ leave: {
5639
+ title: "Leave this purchase?",
5640
+ note: "Your order keeps going. You can come back to it from Buy.",
5641
+ stay: "Stay here",
5642
+ exit: "Leave, keep the order",
5643
+ cancel: "Cancel the order",
5644
+ cancelling: "Cancelling\u2026"
5645
+ },
5631
5646
  screens: {
5632
5647
  pay: (amount, currency) => `Pay ${amount} ${currency}`,
5633
5648
  send: (amount, code) => `Send ${amount} ${code}`,
5634
5649
  delivering: (code) => `Your ${code} is on its way`,
5635
5650
  payingOut: (currency) => `Your ${currency} is on its way to your account`,
5636
- done: "Done",
5637
- toCurrent: "Go to the current step",
5651
+ stepLabel: (position, total, title) => `Step ${position} of ${total}: ${title}`,
5652
+ finalStep: "Done",
5653
+ paidAt: "Paid",
5654
+ paidDone: (amount, currency) => `You paid ${amount} ${currency}.`,
5655
+ sentDone: (amount, code) => `You sent ${amount} ${code}.`,
5656
+ receivedDone: (amount, code, chain) => `You received ${amount} ${code} on ${chain}.`,
5657
+ payoutDone: (amount, currency) => `${amount} ${currency} were sent to your account.`,
5658
+ signedDone: "You approved this step.",
5659
+ ranDone: "This step is complete.",
5638
5660
  updatesItself: "This screen updates on its own.",
5639
5661
  preparing: "Preparing your payment\u2026",
5662
+ saveQr: "Save QR",
5663
+ savingQr: "Saving\u2026",
5664
+ savedQr: "QR saved",
5665
+ saveQrFailed: "Could not save the QR",
5666
+ qrFile: "payment",
5640
5667
  received: (amount) => `+${amount}`,
5641
5668
  arrived: (chain) => `It reached your wallet on ${chain}.`,
5642
5669
  paidOut: "It was sent to your account.",
5643
- finish: "Done",
5644
5670
  details: "Details"
5645
5671
  },
5646
5672
  somethingWrong: "Something went wrong.",
@@ -5657,6 +5683,7 @@ var RAMP_COPY = {
5657
5683
  SDK_RAMPS_QUOTE_EXPIRED: "Esta cotizaci\xF3n venci\xF3. Busca una ruta de nuevo.",
5658
5684
  SDK_RAMPS_QUOTE_NOT_FOUND: "Esta cotizaci\xF3n ya no est\xE1 disponible. Busca una ruta de nuevo.",
5659
5685
  SDK_RAMPS_ACTION_STALE: "Este paso cambi\xF3 y se actualiz\xF3. Intenta de nuevo.",
5686
+ SDK_RAMPS_ORDER_NOT_CANCELLABLE: "Esta orden ya no se puede cancelar: sus fondos ya est\xE1n en movimiento.",
5660
5687
  SDK_RAMPS_TX_NOT_FOUND: "No se encontr\xF3 esta operaci\xF3n.",
5661
5688
  SDK_RAMPS_WALLET_NOT_READY: "Aprueba la nueva cuenta de la billetera en tu dispositivo e intenta de nuevo."
5662
5689
  },
@@ -5677,6 +5704,7 @@ var RAMP_COPY = {
5677
5704
  resumeOrderFailed: "No se pudo retomar la operaci\xF3n.",
5678
5705
  checkPaymentFailed: "No se pudo verificar el pago. Intenta de nuevo.",
5679
5706
  retryOrderFailed: "No se pudo reintentar. Intenta de nuevo.",
5707
+ cancelOrderFailed: "No se pudo cancelar la orden. Intenta de nuevo.",
5680
5708
  refreshFailed: "No se pudo actualizar.",
5681
5709
  copyFailed: "No se pudo copiar.",
5682
5710
  awaitingAccount: "Aprueba la nueva cuenta en tu dispositivo. La orden comienza cuando la apruebes.",
@@ -5774,19 +5802,38 @@ var RAMP_COPY = {
5774
5802
  startAnother: "Iniciar otra operaci\xF3n",
5775
5803
  newQuote: "Pedir nueva cotizaci\xF3n",
5776
5804
  keepsGoing: "Esta sigue en curso; puedes retomarla m\xE1s tarde.",
5805
+ leave: {
5806
+ title: "\xBFSalir de esta compra?",
5807
+ note: "Tu orden sigue activa. Puedes retomarla desde Comprar.",
5808
+ stay: "Seguir aqu\xED",
5809
+ exit: "Salir, la orden sigue",
5810
+ cancel: "Cancelar la orden",
5811
+ cancelling: "Cancelando\u2026"
5812
+ },
5777
5813
  screens: {
5778
5814
  pay: (amount, currency) => `Paga ${amount} ${currency}`,
5779
5815
  send: (amount, code) => `Env\xEDa ${amount} ${code}`,
5780
5816
  delivering: (code) => `Tu ${code} est\xE1 en camino`,
5781
5817
  payingOut: (currency) => `Tus ${currency} van en camino a tu cuenta`,
5782
- done: "Hecho",
5783
- toCurrent: "Ir al paso actual",
5818
+ stepLabel: (position, total, title) => `Paso ${position} de ${total}: ${title}`,
5819
+ finalStep: "Listo",
5820
+ paidAt: "Pagado",
5821
+ paidDone: (amount, currency) => `Pagaste ${amount} ${currency}.`,
5822
+ sentDone: (amount, code) => `Enviaste ${amount} ${code}.`,
5823
+ receivedDone: (amount, code, chain) => `Recibiste ${amount} ${code} en ${chain}.`,
5824
+ payoutDone: (amount, currency) => `Se enviaron ${amount} ${currency} a tu cuenta.`,
5825
+ signedDone: "Aprobaste este paso.",
5826
+ ranDone: "Este paso est\xE1 completo.",
5784
5827
  updatesItself: "Esta pantalla se actualiza sola.",
5785
5828
  preparing: "Preparando tu pago\u2026",
5829
+ saveQr: "Guardar QR",
5830
+ savingQr: "Guardando\u2026",
5831
+ savedQr: "QR guardado",
5832
+ saveQrFailed: "No se pudo guardar el QR",
5833
+ qrFile: "pago",
5786
5834
  received: (amount) => `+${amount}`,
5787
5835
  arrived: (chain) => `Lleg\xF3 a tu wallet en ${chain}.`,
5788
5836
  paidOut: "Se envi\xF3 a tu cuenta.",
5789
- finish: "Listo",
5790
5837
  details: "Detalles"
5791
5838
  },
5792
5839
  somethingWrong: "Algo sali\xF3 mal.",
@@ -5803,6 +5850,7 @@ var RAMP_COPY = {
5803
5850
  SDK_RAMPS_QUOTE_EXPIRED: "Esta cota\xE7\xE3o expirou. Busque uma rota de novo.",
5804
5851
  SDK_RAMPS_QUOTE_NOT_FOUND: "Esta cota\xE7\xE3o n\xE3o est\xE1 mais dispon\xEDvel. Busque uma rota de novo.",
5805
5852
  SDK_RAMPS_ACTION_STALE: "Esta etapa mudou e foi atualizada. Tente de novo.",
5853
+ SDK_RAMPS_ORDER_NOT_CANCELLABLE: "Esta ordem n\xE3o pode mais ser cancelada: os fundos j\xE1 est\xE3o em movimento.",
5806
5854
  SDK_RAMPS_TX_NOT_FOUND: "Esta opera\xE7\xE3o n\xE3o foi encontrada.",
5807
5855
  SDK_RAMPS_WALLET_NOT_READY: "Aprove a nova conta da carteira no seu dispositivo e tente de novo."
5808
5856
  },
@@ -5823,6 +5871,7 @@ var RAMP_COPY = {
5823
5871
  resumeOrderFailed: "N\xE3o foi poss\xEDvel retomar a opera\xE7\xE3o.",
5824
5872
  checkPaymentFailed: "N\xE3o foi poss\xEDvel verificar o pagamento. Tente de novo.",
5825
5873
  retryOrderFailed: "N\xE3o foi poss\xEDvel tentar de novo. Tente de novo.",
5874
+ cancelOrderFailed: "N\xE3o foi poss\xEDvel cancelar a ordem. Tente de novo.",
5826
5875
  refreshFailed: "N\xE3o foi poss\xEDvel atualizar.",
5827
5876
  copyFailed: "N\xE3o foi poss\xEDvel copiar.",
5828
5877
  awaitingAccount: "Aprove a nova conta no seu dispositivo. A ordem come\xE7a assim que voc\xEA aprovar.",
@@ -5920,19 +5969,38 @@ var RAMP_COPY = {
5920
5969
  startAnother: "Iniciar outra opera\xE7\xE3o",
5921
5970
  newQuote: "Pedir nova cota\xE7\xE3o",
5922
5971
  keepsGoing: "Esta continua em andamento; voc\xEA pode retom\xE1-la depois.",
5972
+ leave: {
5973
+ title: "Sair desta compra?",
5974
+ note: "Sua ordem continua ativa. Voc\xEA pode retom\xE1-la em Comprar.",
5975
+ stay: "Ficar aqui",
5976
+ exit: "Sair, manter a ordem",
5977
+ cancel: "Cancelar a ordem",
5978
+ cancelling: "Cancelando\u2026"
5979
+ },
5923
5980
  screens: {
5924
5981
  pay: (amount, currency) => `Pague ${amount} ${currency}`,
5925
5982
  send: (amount, code) => `Envie ${amount} ${code}`,
5926
5983
  delivering: (code) => `Seu ${code} est\xE1 a caminho`,
5927
5984
  payingOut: (currency) => `Seus ${currency} est\xE3o a caminho da sua conta`,
5928
- done: "Conclu\xEDdo",
5929
- toCurrent: "Ir para a etapa atual",
5985
+ stepLabel: (position, total, title) => `Etapa ${position} de ${total}: ${title}`,
5986
+ finalStep: "Pronto",
5987
+ paidAt: "Pago em",
5988
+ paidDone: (amount, currency) => `Voc\xEA pagou ${amount} ${currency}.`,
5989
+ sentDone: (amount, code) => `Voc\xEA enviou ${amount} ${code}.`,
5990
+ receivedDone: (amount, code, chain) => `Voc\xEA recebeu ${amount} ${code} na ${chain}.`,
5991
+ payoutDone: (amount, currency) => `${amount} ${currency} foram enviados para a sua conta.`,
5992
+ signedDone: "Voc\xEA aprovou esta etapa.",
5993
+ ranDone: "Esta etapa est\xE1 conclu\xEDda.",
5930
5994
  updatesItself: "Esta tela se atualiza sozinha.",
5931
5995
  preparing: "Preparando o seu pagamento\u2026",
5996
+ saveQr: "Salvar QR",
5997
+ savingQr: "Salvando\u2026",
5998
+ savedQr: "QR salvo",
5999
+ saveQrFailed: "N\xE3o foi poss\xEDvel salvar o QR",
6000
+ qrFile: "pagamento",
5932
6001
  received: (amount) => `+${amount}`,
5933
6002
  arrived: (chain) => `Chegou \xE0 sua carteira na ${chain}.`,
5934
6003
  paidOut: "Foi enviado para a sua conta.",
5935
- finish: "Pronto",
5936
6004
  details: "Detalhes"
5937
6005
  },
5938
6006
  somethingWrong: "Algo deu errado.",
@@ -6170,6 +6238,97 @@ function rampOrderScreens(order, language) {
6170
6238
  return { ...screen, status: stopped || rampLegStatus(screen.leg) === "failed" ? "failed" : "current" };
6171
6239
  });
6172
6240
  }
6241
+ var SVG_SIDE = 1024;
6242
+ function imageSrc(image) {
6243
+ return image.encoding === "base64" ? `data:${image.mediaType};base64,${image.data}` : `data:${image.mediaType};charset=utf-8,${encodeURIComponent(image.data)}`;
6244
+ }
6245
+ function base64Blob(data, type) {
6246
+ const bytes = Uint8Array.from(atob(data), (c) => c.charCodeAt(0));
6247
+ return new Blob([bytes], { type });
6248
+ }
6249
+ async function scannableFile(image) {
6250
+ if (image.encoding === "base64" && (image.mediaType === "image/png" || image.mediaType === "image/jpeg"))
6251
+ return base64Blob(image.data, image.mediaType);
6252
+ const element = new Image();
6253
+ element.decoding = "async";
6254
+ element.src = imageSrc(image);
6255
+ await element.decode();
6256
+ const svg = image.mediaType === "image/svg+xml";
6257
+ const width = svg ? SVG_SIDE : element.naturalWidth;
6258
+ const height = svg ? Math.round(SVG_SIDE * (element.naturalHeight || 1) / (element.naturalWidth || 1)) : element.naturalHeight;
6259
+ const canvas = document.createElement("canvas");
6260
+ canvas.width = width;
6261
+ canvas.height = height;
6262
+ const context = canvas.getContext("2d");
6263
+ if (!context) throw new Error("canvas unavailable");
6264
+ context.fillStyle = "#ffffff";
6265
+ context.fillRect(0, 0, width, height);
6266
+ context.drawImage(element, 0, 0, width, height);
6267
+ return new Promise(
6268
+ (resolve, reject) => canvas.toBlob((blob) => blob ? resolve(blob) : reject(new Error("png encoding failed")), "image/png")
6269
+ );
6270
+ }
6271
+ async function saveFile(blob, name) {
6272
+ const file = new File([blob], name, { type: blob.type });
6273
+ const touch = typeof window.matchMedia === "function" && window.matchMedia("(pointer: coarse)").matches;
6274
+ if (touch && navigator.canShare?.({ files: [file] })) {
6275
+ try {
6276
+ await navigator.share({ files: [file] });
6277
+ return "saved";
6278
+ } catch (error) {
6279
+ if (error.name === "AbortError") return "dismissed";
6280
+ }
6281
+ }
6282
+ const url = URL.createObjectURL(blob);
6283
+ const link = document.createElement("a");
6284
+ link.href = url;
6285
+ link.download = name;
6286
+ document.body.appendChild(link);
6287
+ link.click();
6288
+ link.remove();
6289
+ setTimeout(() => URL.revokeObjectURL(url), 1e4);
6290
+ return "saved";
6291
+ }
6292
+ function SaveQrButton({
6293
+ image,
6294
+ fileName,
6295
+ labels
6296
+ }) {
6297
+ const [state, setState] = useState("idle");
6298
+ const timer = useRef(null);
6299
+ useEffect(
6300
+ () => () => {
6301
+ if (timer.current) clearTimeout(timer.current);
6302
+ },
6303
+ []
6304
+ );
6305
+ async function save() {
6306
+ setState("saving");
6307
+ try {
6308
+ const blob = await scannableFile(image);
6309
+ const extension = blob.type === "image/jpeg" ? "jpg" : "png";
6310
+ const outcome = await saveFile(blob, `${fileName}.${extension}`);
6311
+ setState(outcome === "saved" ? "saved" : "idle");
6312
+ } catch {
6313
+ setState("failed");
6314
+ }
6315
+ if (timer.current) clearTimeout(timer.current);
6316
+ timer.current = setTimeout(() => setState("idle"), 2500);
6317
+ }
6318
+ return /* @__PURE__ */ jsxs("button", { type: "button", className: "pollar-btn-secondary pollar-ramp-save-qr", disabled: state === "saving", onClick: save, children: [
6319
+ /* @__PURE__ */ jsx("svg", { width: "16", height: "16", viewBox: "0 0 16 16", fill: "none", "aria-hidden": true, children: /* @__PURE__ */ jsx(
6320
+ "path",
6321
+ {
6322
+ d: "M8 2v8m0 0 3-3m-3 3L5 7M3 12.5h10",
6323
+ stroke: "currentColor",
6324
+ strokeWidth: "1.6",
6325
+ strokeLinecap: "round",
6326
+ strokeLinejoin: "round"
6327
+ }
6328
+ ) }),
6329
+ state === "saving" ? labels.saving : state === "saved" ? labels.saved : state === "failed" ? labels.failed : labels.save
6330
+ ] });
6331
+ }
6173
6332
  function scannableImageSrc(image) {
6174
6333
  return image.encoding === "base64" ? `data:${image.mediaType};base64,${image.data}` : `data:${image.mediaType};charset=utf-8,${encodeURIComponent(image.data)}`;
6175
6334
  }
@@ -6301,7 +6460,11 @@ function RampWidgetTemplate({
6301
6460
  onRefresh,
6302
6461
  onClose,
6303
6462
  language: languageProp,
6304
- confirmation = null
6463
+ confirmation = null,
6464
+ onCancelOrder,
6465
+ cosignPrompt = null,
6466
+ cancelling = false,
6467
+ cancelError = null
6305
6468
  }) {
6306
6469
  const language = useInheritedLanguage(languageProp);
6307
6470
  const cssVars = buildModalCssVars(theme, accentColor, styleOverrides, "hero");
@@ -6310,7 +6473,12 @@ function RampWidgetTemplate({
6310
6473
  const sendUnit = onramp ? fiat?.currency : asset?.code;
6311
6474
  const [detailsOpen, setDetailsOpen] = useState(false);
6312
6475
  const [viewing, setViewing] = useState(null);
6313
- useEffect(() => setViewing(null), [order?.id]);
6476
+ const [leaving, setLeaving] = useState(false);
6477
+ const [doneDetailsOpen, setDoneDetailsOpen] = useState(false);
6478
+ useEffect(() => {
6479
+ setViewing(null);
6480
+ setLeaving(false);
6481
+ }, [order?.id]);
6314
6482
  const routeName = (quote) => quote.legs.map((leg) => rampLegTitle(leg, language)).join(" \xB7 ");
6315
6483
  const rate = (() => {
6316
6484
  if (!chosenQuote) return null;
@@ -6397,11 +6565,44 @@ function RampWidgetTemplate({
6397
6565
  const shown = screens[shownScreen];
6398
6566
  const askedInstead = order?.pendingAction?.kind === "KYC" || !!shown?.key.endsWith(":pay") && order?.pendingAction?.legIndex === shown.leg.index && !["FIAT_PAYMENT", "NONE"].includes(order.pendingAction.kind);
6399
6567
  const firstLeg = order?.legs[0];
6568
+ const payment = order?.pendingAction?.kind === "FIAT_PAYMENT" ? order.pendingAction.instructions : null;
6569
+ const qrFileName = [copy.screens.qrFile, payment?.amount, payment?.currency, order?.id.slice(-8)].filter(Boolean).join("-");
6400
6570
  const orderSummary = firstLeg && receive ? `${amountText(firstLeg.amountInPlanned, language)} ${firstLeg.from.kind === "fiat" ? firstLeg.from.currency : firstLeg.from.code} \u2192 ${receive.estimated ? "~" : ""}${amountText(receive.amount, language)} ${receive.unit}` : null;
6401
6571
  const lastLeg = order?.legs[order.legs.length - 1];
6402
6572
  const arrivedText = lastLeg?.to.kind === "asset" ? copy.screens.arrived(CHAIN_NAME[lastLeg.to.chain] ?? lastLeg.to.chain) : copy.screens.paidOut;
6573
+ const requestClose = () => step === "status" && order && !settled ? setLeaving(true) : onClose();
6574
+ const cancellable = !!order && !settled && order.pendingAction?.kind !== "COSIGN_APPROVAL" && order.legs.every((leg) => leg.status !== "COMPLETED" && leg.status !== "HELD" && leg.paymentStatus !== "received");
6575
+ const doneText = (screen) => {
6576
+ const leg = screen.leg;
6577
+ const unit = (node) => node.kind === "fiat" ? node.currency : node.code;
6578
+ const inAmount = amountText(leg.amountInActual ?? leg.amountInPlanned, language);
6579
+ const outAmount = amountText(leg.amountOutActual ?? leg.amountOutPlanned, language);
6580
+ if (screen.key.endsWith(":pay"))
6581
+ return leg.kind === "PROVIDER_ONRAMP" ? copy.screens.paidDone(inAmount, unit(leg.from)) : copy.screens.sentDone(inAmount, unit(leg.from));
6582
+ if (screen.key.endsWith(":deliver"))
6583
+ return leg.to.kind === "asset" ? copy.screens.receivedDone(outAmount, leg.to.code, CHAIN_NAME[leg.to.chain] ?? leg.to.chain) : copy.screens.payoutDone(outAmount, leg.to.currency);
6584
+ return screen.kind === "action" ? copy.screens.signedDone : copy.screens.ranDone;
6585
+ };
6403
6586
  const finalNote = order?.legs.map((leg) => rampLegNote(leg, language)).find((note) => note !== null) ?? null;
6404
- const screenRows = (screen) => screen.steps.length ? screen.steps.flatMap(
6587
+ const paidQr = (screen) => {
6588
+ if (!screen.key.endsWith(":pay")) return null;
6589
+ const instructions = screen.leg.paymentRequest?.instructions;
6590
+ return instructions?.kind === "qr" ? instructions.scannable?.image ?? null : null;
6591
+ };
6592
+ const paidRows = (screen) => {
6593
+ if (!screen.key.endsWith(":pay") || !order) return [];
6594
+ const at = screen.leg.paymentReceivedAt;
6595
+ return [
6596
+ ...at ? [
6597
+ {
6598
+ label: copy.screens.paidAt,
6599
+ value: new Date(at).toLocaleString(language, { dateStyle: "medium", timeStyle: "short" })
6600
+ }
6601
+ ] : [],
6602
+ { label: copy.order, value: `\u2026${order.id.slice(-8)}`, copyValue: order.id, mono: true }
6603
+ ];
6604
+ };
6605
+ const screenRowsOf = (screen) => screen.steps.length ? screen.steps.flatMap(
6405
6606
  (st) => st.hash ? [
6406
6607
  {
6407
6608
  label: rampStepTitle(st, screen.leg, language),
@@ -6418,6 +6619,7 @@ function RampWidgetTemplate({
6418
6619
  copyValue: screen.leg.onchainTxHash
6419
6620
  }
6420
6621
  ] : [];
6622
+ const screenRows = (screen) => [...paidRows(screen), ...screenRowsOf(screen)];
6421
6623
  const stepTitle = {
6422
6624
  input: onramp ? copy.title.buy : copy.title.sell,
6423
6625
  loading_quote: copy.title.finding,
@@ -6451,16 +6653,6 @@ function RampWidgetTemplate({
6451
6653
  children: /* @__PURE__ */ jsx("svg", { width: "16", height: "16", viewBox: "0 0 16 16", fill: "none", "aria-hidden": true, children: /* @__PURE__ */ jsx("path", { d: "M10 3 5 8l5 5", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }) })
6452
6654
  }
6453
6655
  ),
6454
- step === "status" && shownScreen > 0 && shownScreen <= currentScreen && /* @__PURE__ */ jsx(
6455
- "button",
6456
- {
6457
- type: "button",
6458
- className: "pollar-back-btn pollar-ramp-back",
6459
- onClick: () => setViewing(shownScreen - 1),
6460
- "aria-label": copy.back,
6461
- children: /* @__PURE__ */ jsx("svg", { width: "16", height: "16", viewBox: "0 0 16 16", fill: "none", "aria-hidden": true, children: /* @__PURE__ */ jsx("path", { d: "M10 3 5 8l5 5", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }) })
6462
- }
6463
- ),
6464
6656
  /* @__PURE__ */ jsxs("div", { className: "pollar-ramp-header-text", children: [
6465
6657
  /* @__PURE__ */ jsx("h2", { className: "pollar-modal-title", children: stepTitle[step] }),
6466
6658
  /* @__PURE__ */ jsx("p", { className: "pollar-ramp-subtitle", children: stepSubtitle[step] })
@@ -6497,7 +6689,7 @@ function RampWidgetTemplate({
6497
6689
  )
6498
6690
  }
6499
6691
  ),
6500
- /* @__PURE__ */ jsx("button", { type: "button", className: "pollar-modal-close", onClick: onClose, "aria-label": copy.close, children: /* @__PURE__ */ jsx("svg", { width: "16", height: "16", viewBox: "0 0 16 16", fill: "none", "aria-hidden": true, children: /* @__PURE__ */ jsx("path", { d: "M2 2l12 12M14 2L2 14", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round" }) }) })
6692
+ /* @__PURE__ */ jsx("button", { type: "button", className: "pollar-modal-close", onClick: requestClose, "aria-label": copy.close, children: /* @__PURE__ */ jsx("svg", { width: "16", height: "16", viewBox: "0 0 16 16", fill: "none", "aria-hidden": true, children: /* @__PURE__ */ jsx("path", { d: "M2 2l12 12M14 2L2 14", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round" }) }) })
6501
6693
  ] })
6502
6694
  ] }),
6503
6695
  flowStepIndex >= 0 && flowSteps.length > 0 && /* @__PURE__ */ jsxs("div", { className: "pollar-ramp-steps", children: [
@@ -6517,15 +6709,33 @@ function RampWidgetTemplate({
6517
6709
  }
6518
6710
  ) }, label)) })
6519
6711
  ] }),
6520
- step === "status" && screens.length > 0 && /* @__PURE__ */ jsx("ol", { className: "pollar-ramp-screens-bar", "aria-label": copy.progress, children: [...screens.map((s) => s.key), "final"].map((key, i) => /* @__PURE__ */ jsx(
6521
- "li",
6522
- {
6523
- "data-done": i < currentScreen || completed && i === screens.length || void 0,
6524
- "data-shown": i === shownScreen || void 0,
6525
- "data-failed": screens[i]?.status === "failed" || void 0
6526
- },
6527
- key
6528
- )) }),
6712
+ step === "status" && screens.length > 0 && !(leaving && !settled) && /* @__PURE__ */ jsx("ol", { className: "pollar-ramp-stepper", "aria-label": copy.progress, children: [...screens, null].map((screen, i) => {
6713
+ const state = i < currentScreen || completed && i === screens.length ? "done" : screen?.status === "failed" ? "failed" : i === currentScreen ? "current" : "upcoming";
6714
+ const busy = state === "current" && !settled && !(screen?.kind === "action" && order?.pendingAction);
6715
+ return /* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsx(
6716
+ "button",
6717
+ {
6718
+ type: "button",
6719
+ className: "pollar-ramp-stepper-step",
6720
+ "data-state": state,
6721
+ "data-shown": i === shownScreen || void 0,
6722
+ "aria-current": i === shownScreen ? "step" : void 0,
6723
+ "aria-label": copy.screens.stepLabel(i + 1, screens.length + 1, screen?.title ?? copy.screens.finalStep),
6724
+ disabled: i > currentScreen,
6725
+ onClick: () => setViewing(i >= currentScreen ? null : i),
6726
+ children: state === "done" ? /* @__PURE__ */ jsx("svg", { width: "14", height: "14", viewBox: "0 0 16 16", fill: "none", "aria-hidden": true, children: /* @__PURE__ */ jsx(
6727
+ "path",
6728
+ {
6729
+ d: "M3 8.5 6.5 12 13 4.5",
6730
+ stroke: "currentColor",
6731
+ strokeWidth: "2.2",
6732
+ strokeLinecap: "round",
6733
+ strokeLinejoin: "round"
6734
+ }
6735
+ ) }) : state === "failed" ? /* @__PURE__ */ jsx("svg", { width: "12", height: "12", viewBox: "0 0 16 16", fill: "none", "aria-hidden": true, children: /* @__PURE__ */ jsx("path", { d: "M3 3l10 10M13 3 3 13", stroke: "currentColor", strokeWidth: "2.2", strokeLinecap: "round" }) }) : busy ? /* @__PURE__ */ jsx("span", { className: "pollar-spinner pollar-spinner-sm", "aria-hidden": true }) : i + 1
6736
+ }
6737
+ ) }, screen?.key ?? "final");
6738
+ }) }),
6529
6739
  step === "input" && pendingOrders.length > 0 && /* @__PURE__ */ jsxs("section", { className: "pollar-ramp-payment pollar-ramp-saved", "aria-label": copy.pendingAria, children: [
6530
6740
  /* @__PURE__ */ jsx("p", { className: "pollar-ramp-payment-note", children: copy.pendingNote }),
6531
6741
  pendingOrders.map((pending) => /* @__PURE__ */ jsx("div", { className: "pollar-ramp-saved-row", children: /* @__PURE__ */ jsx(
@@ -6813,7 +7023,30 @@ function RampWidgetTemplate({
6813
7023
  }
6814
7024
  ) })
6815
7025
  ] }),
6816
- step === "status" && order && view && /* @__PURE__ */ jsx("div", { className: "pollar-ramp-payment", children: shownScreen === screens.length ? /* @__PURE__ */ jsxs(Fragment, { children: [
7026
+ step === "status" && order && view && /* @__PURE__ */ jsx("div", { className: "pollar-ramp-payment", children: leaving && !settled ? /* @__PURE__ */ jsxs("div", { className: "pollar-ramp-leave", children: [
7027
+ /* @__PURE__ */ jsx("h3", { className: "pollar-ramp-screen-title", children: copy.leave.title }),
7028
+ /* @__PURE__ */ jsx("p", { className: "pollar-ramp-payment-note", children: copy.leave.note }),
7029
+ cancelError && /* @__PURE__ */ jsx("p", { className: "pollar-ramp-field-error", children: cancelError }),
7030
+ /* @__PURE__ */ jsx("button", { type: "button", className: "pollar-btn-primary", onClick: () => setLeaving(false), children: copy.leave.stay }),
7031
+ /* @__PURE__ */ jsx("button", { type: "button", className: "pollar-btn-secondary", onClick: onClose, children: copy.leave.exit }),
7032
+ /* @__PURE__ */ jsx(
7033
+ "button",
7034
+ {
7035
+ type: "button",
7036
+ className: "pollar-ramp-leave-link",
7037
+ onClick: () => {
7038
+ setLeaving(false);
7039
+ onNewOrder();
7040
+ },
7041
+ children: copy.startAnother
7042
+ }
7043
+ ),
7044
+ onCancelOrder && cancellable && /* @__PURE__ */ jsx("button", { type: "button", className: "pollar-ramp-leave-cancel", disabled: cancelling, onClick: onCancelOrder, children: cancelling ? /* @__PURE__ */ jsxs(Fragment, { children: [
7045
+ /* @__PURE__ */ jsx("span", { className: "pollar-spinner pollar-spinner-sm" }),
7046
+ " ",
7047
+ copy.leave.cancelling
7048
+ ] }) : copy.leave.cancel })
7049
+ ] }) : shownScreen === screens.length ? /* @__PURE__ */ jsxs(Fragment, { children: [
6817
7050
  /* @__PURE__ */ jsxs("div", { className: "pollar-ramp-final", children: [
6818
7051
  /* @__PURE__ */ jsx("span", { className: "pollar-ramp-final-mark", "aria-hidden": true, children: /* @__PURE__ */ jsx("svg", { width: "28", height: "28", viewBox: "0 0 16 16", fill: "none", children: /* @__PURE__ */ jsx(
6819
7052
  "path",
@@ -6829,12 +7062,10 @@ function RampWidgetTemplate({
6829
7062
  /* @__PURE__ */ jsx("p", { className: "pollar-ramp-payment-note", children: arrivedText }),
6830
7063
  finalNote && /* @__PURE__ */ jsx("p", { className: "pollar-ramp-payment-note", children: finalNote })
6831
7064
  ] }),
6832
- /* @__PURE__ */ jsx("button", { type: "button", className: "pollar-btn-primary", onClick: onClose, children: copy.screens.finish }),
6833
7065
  /* @__PURE__ */ jsx(TxReview, { data: { title: "", kind: "other", rows: orderRows }, language })
6834
7066
  ] }) : shownScreen < currentScreen ? /* @__PURE__ */ jsxs(Fragment, { children: [
6835
- /* @__PURE__ */ jsx("h3", { className: "pollar-ramp-screen-title", children: screens[shownScreen].title }),
6836
- /* @__PURE__ */ jsxs("p", { className: "pollar-ramp-screen-state", children: [
6837
- /* @__PURE__ */ jsx("svg", { width: "14", height: "14", viewBox: "0 0 16 16", fill: "none", "aria-hidden": true, children: /* @__PURE__ */ jsx(
7067
+ /* @__PURE__ */ jsxs("div", { className: "pollar-ramp-done", children: [
7068
+ /* @__PURE__ */ jsx("span", { className: "pollar-ramp-done-mark", "aria-hidden": true, children: /* @__PURE__ */ jsx("svg", { width: "30", height: "30", viewBox: "0 0 16 16", fill: "none", children: /* @__PURE__ */ jsx(
6838
7069
  "path",
6839
7070
  {
6840
7071
  d: "M3 8.5 6.5 12 13 4.5",
@@ -6843,11 +7074,30 @@ function RampWidgetTemplate({
6843
7074
  strokeLinecap: "round",
6844
7075
  strokeLinejoin: "round"
6845
7076
  }
6846
- ) }),
6847
- copy.screens.done
7077
+ ) }) }),
7078
+ /* @__PURE__ */ jsx("h3", { className: "pollar-ramp-done-title", children: screens[shownScreen].title }),
7079
+ /* @__PURE__ */ jsx("p", { className: "pollar-ramp-payment-note", children: doneText(screens[shownScreen]) })
6848
7080
  ] }),
6849
- screenRows(screens[shownScreen]).length > 0 && /* @__PURE__ */ jsx(TxReview, { data: { title: "", kind: "other", rows: screenRows(screens[shownScreen]) }, language }),
6850
- /* @__PURE__ */ jsx("button", { type: "button", className: "pollar-btn-secondary", onClick: () => setViewing(null), children: copy.screens.toCurrent })
7081
+ screenRows(screens[shownScreen]).length > 0 && /* @__PURE__ */ jsx(
7082
+ TxReview,
7083
+ {
7084
+ data: { title: "", kind: "other", rows: screenRows(screens[shownScreen]) },
7085
+ open: doneDetailsOpen,
7086
+ onToggle: () => setDoneDetailsOpen((open) => !open),
7087
+ language
7088
+ }
7089
+ ),
7090
+ doneDetailsOpen && paidQr(screens[shownScreen]) && /* @__PURE__ */ jsxs("div", { className: "pollar-ramp-paid-qr", children: [
7091
+ /* @__PURE__ */ jsx("span", { className: "pollar-ramp-payment-label", children: copy.paymentQr }),
7092
+ paidQr(screens[shownScreen]).inlineSafe ? /* @__PURE__ */ jsx(
7093
+ "div",
7094
+ {
7095
+ className: "pollar-ramp-qr",
7096
+ "aria-label": copy.paymentQr,
7097
+ dangerouslySetInnerHTML: { __html: paidQr(screens[shownScreen]).data }
7098
+ }
7099
+ ) : /* @__PURE__ */ jsx("img", { src: scannableImageSrc(paidQr(screens[shownScreen])), alt: copy.paymentQr })
7100
+ ] })
6851
7101
  ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
6852
7102
  shown && /* @__PURE__ */ jsx("h3", { className: "pollar-ramp-screen-title", "data-status": shown.status, children: askedInstead ? view.title : shown.title }),
6853
7103
  shown?.status === "failed" && shown.leg.failure && /* @__PURE__ */ jsx("p", { className: "pollar-ramp-field-error", children: rampFailureReason(shown.leg.failure, language) }),
@@ -6869,6 +7119,7 @@ function RampWidgetTemplate({
6869
7119
  ] })
6870
7120
  ] }, s.kind)) }),
6871
7121
  confirmation && /* @__PURE__ */ jsx(InlineConfirm, { confirmation, language, network }),
7122
+ cosignPrompt,
6872
7123
  order.failure && /* @__PURE__ */ jsxs("div", { className: "pollar-ramp-payment-field", children: [
6873
7124
  /* @__PURE__ */ jsx("span", { className: "pollar-ramp-payment-label", children: copy.whatToDo }),
6874
7125
  /* @__PURE__ */ jsx("p", { className: "pollar-ramp-payment-note", children: rampOrderResolutionText(order, language) }),
@@ -6908,7 +7159,20 @@ function RampWidgetTemplate({
6908
7159
  alt: copy.paymentQr,
6909
7160
  style: { width: "100%", maxWidth: 220, height: "auto", display: "block", margin: "0 auto" }
6910
7161
  }
6911
- ) })
7162
+ ) }),
7163
+ /* @__PURE__ */ jsx(
7164
+ SaveQrButton,
7165
+ {
7166
+ image: view.scannable.image,
7167
+ fileName: qrFileName,
7168
+ labels: {
7169
+ save: copy.screens.saveQr,
7170
+ saving: copy.screens.savingQr,
7171
+ saved: copy.screens.savedQr,
7172
+ failed: copy.screens.saveQrFailed
7173
+ }
7174
+ }
7175
+ )
6912
7176
  ] }),
6913
7177
  !settled && view.codeMissing && /* @__PURE__ */ jsx("p", { className: "pollar-ramp-payment-note", style: { color: "var(--pollar-error-text)" }, children: copy.codeMissing }),
6914
7178
  !settled && view.scannable?.payload && view.scannable.payloadLabel && /* @__PURE__ */ jsxs("div", { className: "pollar-ramp-payment-field", children: [
@@ -6954,7 +7218,7 @@ function RampWidgetTemplate({
6954
7218
  ] }) : copy.paid }),
6955
7219
  !settled && view.canSign && /* @__PURE__ */ jsx("button", { type: "button", className: "pollar-btn-primary", disabled: signing, onClick: onSign, children: signing ? copy.waitingWallet : copy.authorize }),
6956
7220
  !settled && view.action?.kind === "SIGNATURE" && !view.canSign && /* @__PURE__ */ jsx("p", { className: "pollar-ramp-payment-note", children: copy.preparingSignature }),
6957
- !settled && view.canApprove && /* @__PURE__ */ jsx("button", { type: "button", className: "pollar-btn-primary", onClick: onApprove, children: copy.approveOnDevice }),
7221
+ !settled && view.canApprove && !cosignPrompt && /* @__PURE__ */ jsx("button", { type: "button", className: "pollar-btn-primary", onClick: onApprove, children: copy.approveOnDevice }),
6958
7222
  !settled && view.link && /* @__PURE__ */ jsx(
6959
7223
  "a",
6960
7224
  {
@@ -6967,8 +7231,7 @@ function RampWidgetTemplate({
6967
7231
  ),
6968
7232
  !settled && order.pendingAction?.kind === "KYC" && !view.link && /* @__PURE__ */ jsx("p", { className: "pollar-ramp-payment-note", children: view.note ?? copy.providerReviewing }),
6969
7233
  pollTrouble && !settled && /* @__PURE__ */ jsx("p", { className: "pollar-ramp-payment-note", children: copy.serverTrouble }),
6970
- errorMsg && /* @__PURE__ */ jsx("p", { className: "pollar-ramp-field-error", children: errorMsg }),
6971
- !settled && /* @__PURE__ */ jsx("div", { className: "pollar-ramp-explore", children: /* @__PURE__ */ jsx("button", { type: "button", className: "pollar-btn-secondary", onClick: onNewOrder, children: copy.startAnother }) })
7234
+ errorMsg && /* @__PURE__ */ jsx("p", { className: "pollar-ramp-field-error", children: errorMsg })
6972
7235
  ] }) }),
6973
7236
  step === "error" && /* @__PURE__ */ jsxs(Fragment, { children: [
6974
7237
  /* @__PURE__ */ jsx("div", { className: "pollar-modal-error", children: errorMsg ?? copy.somethingWrong }),
@@ -7579,243 +7842,831 @@ function ProviderRegistrationModal({
7579
7842
  }
7580
7843
  ) });
7581
7844
  }
7582
- var PAYMENT_CHECK_EVERY_MS = 1e4;
7583
- var PAYMENT_CHECK_WINDOW_MS = 2 * 6e4;
7584
- function rampErrorMessage(error, fallback, copy, language) {
7585
- const unavailable = appUnavailableMessage(error, language);
7586
- if (unavailable) return unavailable;
7587
- if (isPollarApiError(error)) {
7588
- const known = copy.errors[error.code];
7589
- if (known) return known;
7590
- const message = error.body.message;
7591
- if (typeof message === "string" && message && !/^[A-Z0-9_]+$/.test(message)) return message;
7592
- }
7593
- return fallback;
7594
- }
7595
- var DECIMAL = /^\d+(\.\d+)?$/;
7596
- var QUOTE_DEBOUNCE_MS = 600;
7597
- function seededSelection(routes, seed) {
7598
- const countries = rampCountries(routes);
7599
- const wanted = seed.country?.trim().toUpperCase();
7600
- const country = wanted ? countries.find((c) => c.country === wanted) : countries[0];
7601
- if (!country) return null;
7602
- const fiat = country.fiats.find((f) => f.currency === seed.fiat?.trim().toUpperCase()) ?? null;
7603
- const resolvedFiat = fiat ?? country.fiats[0];
7604
- const asset = routes.find(
7605
- (r) => r.fiat.country === country.country && resolvedFiat !== void 0 && fiatKey(r.fiat) === fiatKey(resolvedFiat) && r.asset.code.toUpperCase() === seed.asset?.trim().toUpperCase()
7606
- )?.asset;
7607
- const amount = seed.amount?.trim() ?? "";
7608
- return {
7609
- country: country.country,
7610
- fiatChoice: fiat ? fiatKey(fiat) : "",
7611
- assetChoice: asset ? assetKey3(asset) : "",
7612
- amount: DECIMAL.test(amount) ? amount : ""
7613
- };
7614
- }
7615
- async function signLegWithWallet(client, orderId, actionId, copy) {
7616
- const lent = [];
7617
- const lend = (chain, encoding, handler) => {
7845
+ function useCosign() {
7846
+ const { getClient, isAuthenticated } = usePollar();
7847
+ const [state, setState] = useState({ pending: [] });
7848
+ const [loaded, setLoaded] = useState(false);
7849
+ useEffect(() => getClient().onCosignStateChange(setState), [getClient]);
7850
+ const refresh = useCallback(async () => {
7851
+ if (!isAuthenticated) return;
7618
7852
  try {
7619
- lent.push(client.registerRampSigningHandler(chain, encoding, handler));
7620
- } catch {
7853
+ await getClient().cosign.pending();
7854
+ } finally {
7855
+ setLoaded(true);
7621
7856
  }
7857
+ }, [getClient, isAuthenticated]);
7858
+ useEffect(() => {
7859
+ void refresh();
7860
+ }, [refresh]);
7861
+ return {
7862
+ pending: state.pending,
7863
+ ...state.lastResolved ? { lastResolved: state.lastResolved } : {},
7864
+ loaded,
7865
+ refresh,
7866
+ approve: useCallback((request) => getClient().cosign.approve(request), [getClient]),
7867
+ reject: useCallback((request) => getClient().cosign.reject(request), [getClient]),
7868
+ verify: useCallback((request) => getClient().cosign.verify(request), [getClient]),
7869
+ inspectQuorum: useCallback(() => getClient().cosign.inspectQuorum(), [getClient]),
7870
+ devices: useCallback(() => getClient().cosign.devices(), [getClient]),
7871
+ revokeDevice: useCallback(
7872
+ (deviceId, options) => getClient().cosign.revokeDevice(deviceId, options),
7873
+ [getClient]
7874
+ ),
7875
+ switchCustody: useCallback((to) => getClient().cosign.switchCustody(to), [getClient])
7622
7876
  };
7623
- lend("STELLAR", "xdr", async (action) => {
7624
- const wallet = client.getWallet();
7625
- if (!wallet) throw new Error(copy.connectStellarWallet);
7626
- assertRampStellarSigner(action, wallet.address);
7627
- const outcome = await client.signTx(action.payload.value);
7628
- if (client.getWallet()?.address !== wallet.address) throw new Error(copy.walletChanged);
7629
- if (outcome.status === "signed") return outcome.signedXdr;
7630
- throw new Error(
7631
- outcome.status === "error" ? outcome.message ?? outcome.details ?? copy.signingCancelled : copy.signingCancelled
7632
- );
7633
- });
7634
- lend("SOLANA", "solana-v0-json", async (action) => {
7635
- const payload = JSON.parse(action.payload.value);
7636
- const solanaWallet = () => client.getWallets().find((w) => w.chain === "SOLANA" && w.custody === "external");
7637
- const wallet = solanaWallet();
7638
- if (!wallet || payload.from !== wallet.address || !payload.unsignedTransaction) throw new Error(copy.solanaWalletMismatch);
7639
- const signed = await client.signSolanaTransaction(payload.unsignedTransaction);
7640
- if (solanaWallet()?.address !== wallet.address) throw new Error(copy.walletChanged);
7641
- return signed;
7642
- });
7643
- try {
7644
- return await client.signRampLeg(orderId, actionId);
7645
- } finally {
7646
- for (const release of lent) release();
7647
- }
7648
7877
  }
7649
- function RampWidget({ onClose, language: languageProp, initial }) {
7650
- const {
7651
- getClient,
7652
- styles,
7653
- network,
7654
- openCosignModal,
7655
- setCosignNextStep,
7656
- openRecoveryModal,
7657
- recovery,
7658
- recoveryLocked,
7659
- appConfig,
7660
- cosign,
7661
- refreshWalletBalance
7662
- } = usePollar();
7663
- const client = getClient();
7664
- const language = useModalLanguage(languageProp);
7665
- const copy = RAMP_COPY[language];
7666
- const { theme, accentColor, styleOverrides, overlayStyle } = modalChrome(styles);
7667
- const [step, setStep] = useState("input");
7668
- const confirmation = useInlineConfirmation(step === "status");
7669
- const [direction, setDirection] = useState(initial?.direction === "sell" ? "OFFRAMP" : "ONRAMP");
7670
- const seedRef = useRef(
7671
- initial ? { direction: initial.direction === "sell" ? "OFFRAMP" : "ONRAMP", options: initial } : null
7672
- );
7673
- const [routes, setRoutes] = useState([]);
7674
- const [routesLoading, setRoutesLoading] = useState(true);
7675
- const [country, setCountry] = useState("");
7676
- const [fiatChoice, setFiatChoice] = useState("");
7677
- const [assetChoice, setAssetChoice] = useState("");
7678
- const [amount, setAmount] = useState("");
7679
- const [quotes, setQuotes] = useState([]);
7680
- const [rejected, setRejected] = useState([]);
7681
- const [selected, setSelected] = useState(null);
7682
- const [startingQuoteId, setStartingQuoteId] = useState(null);
7683
- const [fieldValues, setFieldValues] = useState({});
7684
- const [order, setOrder] = useState(null);
7685
- const [pendingOrders, setPendingOrders] = useState([]);
7686
- const [isLoading, setIsLoading] = useState(false);
7687
- const [refreshing, setRefreshing] = useState(false);
7688
- const [signing, setSigning] = useState(false);
7689
- const [errorMsg, setErrorMsg] = useState(null);
7690
- const [verifying, setVerifying] = useState(null);
7691
- const [trustingAsset, setTrustingAsset] = useState(null);
7692
- const [walletBusy, setWalletBusy] = useState(null);
7693
- const [retrying, setRetrying] = useState(false);
7694
- const [awaitingAccount, setAwaitingAccount] = useState(null);
7695
- const [pollTrouble, setPollTrouble] = useState(false);
7696
- const [pollKey, setPollKey] = useState(0);
7697
- const [paymentCheckUntil, setPaymentCheckUntil] = useState(null);
7698
- const checkErrorRef = useRef(null);
7699
- const promptedApproval = useRef(null);
7700
- const custodyChoice = appConfig.application?.walletCustodyMode === "USER_CHOICE";
7701
- const appChains = appConfig.application?.chains;
7702
- const verifyAttempt = useRef(null);
7703
- const countries = useMemo(() => rampCountries(routes), [routes]);
7704
- const fiats = countries.find((c) => c.country === country)?.fiats ?? [];
7705
- const fiat = fiats.find((f) => fiatKey(f) === fiatChoice) ?? fiats[0] ?? null;
7706
- const assets = useMemo(() => {
7707
- const seen = /* @__PURE__ */ new Map();
7708
- for (const route of routes)
7709
- if (fiat && route.fiat.country === country && fiatKey(route.fiat) === fiatKey(fiat))
7710
- seen.set(assetKey3(route.asset), route.asset);
7711
- return [...seen.values()];
7712
- }, [routes, country, fiat]);
7713
- const asset = assets.find((a) => assetKey3(a) === assetChoice) ?? assets[0] ?? null;
7714
- const fields = selected ? rampQuoteFields(selected, language) : [];
7715
- const sellAvailable = useWalletAvailable(
7716
- direction === "OFFRAMP" && asset ? { chain: asset.chain, code: asset.code, issuer: asset.identifier } : null
7717
- );
7718
- const [quoting, setQuoting] = useState(false);
7719
- const [routeChoice, setRouteChoice] = useState(BEST_ROUTE);
7720
- const quoteRun = useRef(0);
7721
- const quoteInput = step === "input" && fiat && asset && DECIMAL.test(amount.trim()) && Number(amount) > 0;
7722
- const quoteKey = quoteInput ? `${direction}|${fiatKey(fiat)}|${assetKey3(asset)}|${amount.trim()}` : null;
7723
- useEffect(() => {
7724
- const run = ++quoteRun.current;
7725
- if (!quoteKey || !fiat || !asset) {
7726
- setQuoting(false);
7727
- if (step === "input") {
7728
- setQuotes([]);
7729
- setRejected([]);
7730
- }
7731
- return;
7878
+
7879
+ // src/components/cosign-modal/cosign-copy.ts
7880
+ var COSIGN_COPY = {
7881
+ en: {
7882
+ title: "Approvals",
7883
+ manyPending: (count) => `${count} approvals waiting`,
7884
+ close: "Close",
7885
+ whyTitle: "Why am I seeing this?",
7886
+ whyBody: "Your wallet needs this device's signature. Neither the app nor Pollar can approve this without you.",
7887
+ rejectRequest: "Reject this request",
7888
+ closeTitle: "Close without signing?",
7889
+ closeBody: "The request stays pending. The app can't continue until you approve it.",
7890
+ backToSign: "Go back and sign",
7891
+ closeAnyway: "Close anyway",
7892
+ activateWallet: "Activate wallet",
7893
+ status: { APPROVED: "Approved", REJECTED: "Rejected", EXPIRED: "Expired", FAILED: "Failed", PENDING: "Pending" },
7894
+ signedAppSends: "Signed. The app will send it.",
7895
+ signedSent: "Signed and sent",
7896
+ signed: "Signed",
7897
+ nothingSigned: "Nothing was signed.",
7898
+ nothingWaiting: "Nothing waits for your approval.",
7899
+ next: (step) => `Next: ${step}. It appears here in a few seconds.`,
7900
+ closingIn: (seconds) => `Closing in ${seconds}s`,
7901
+ expired: "expired",
7902
+ expiresIn: "Expires in",
7903
+ checking: "Checking...",
7904
+ verified: "Checked",
7905
+ checkedExact: "We checked this is exactly what you're approving.",
7906
+ notVerified: "Not verified:",
7907
+ reject: "Reject",
7908
+ rejecting: "Rejecting...",
7909
+ approve: "Approve",
7910
+ approving: "Approving...",
7911
+ genericError: "Something went wrong. Please try again.",
7912
+ unreachable: "We could not reach Pollar, so nothing was approved. Check your connection and approve again.",
7913
+ 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.",
7914
+ linkDevice: "Link this device",
7915
+ transaction: "Transaction",
7916
+ operations: {
7917
+ payment: "Send",
7918
+ path_payment_strict_send: "Swap",
7919
+ change_trust: "Add asset",
7920
+ create_account: "Create account",
7921
+ invoke_contract: "Contract call",
7922
+ soroban_auth: "Authorize a contract call",
7923
+ manage_data: "Manage data",
7924
+ transfer: "Send",
7925
+ ramp_payment: "Ramp payment",
7926
+ cctp_burn: "Move USDC",
7927
+ swap: "Swap",
7928
+ earn_deposit: "Deposit",
7929
+ earn_withdraw: "Withdraw",
7930
+ evm_delegation: "Enable atomic transactions",
7931
+ provider_sign_in: "Confirm it's you",
7932
+ sep10: "Confirm it's you"
7732
7933
  }
7733
- setQuoting(true);
7734
- const timer = setTimeout(() => {
7735
- client.quoteRamp({
7736
- direction,
7737
- fiat: { currency: fiat.currency, rail: fiat.rail, country: fiat.country },
7738
- asset: { code: asset.code, identifier: asset.identifier, chain: asset.chain },
7739
- amount: { value: amount.trim(), denomination: "in" }
7740
- }).then((result) => {
7741
- if (run !== quoteRun.current) return;
7742
- setQuotes(result.quotes);
7743
- setRejected(result.rejected);
7744
- setErrorMsg(null);
7745
- }).catch((error) => {
7746
- if (run !== quoteRun.current) return;
7747
- setQuotes([]);
7748
- if (isPollarApiError(error) && error.code === "SDK_RAMPS_NO_ROUTE") {
7749
- setRejected(Array.isArray(error.body.rejected) ? error.body.rejected : []);
7750
- } else {
7751
- setRejected([]);
7752
- setErrorMsg(rampErrorMessage(error, copy.findRouteFailed, copy, language));
7753
- }
7754
- }).finally(() => {
7755
- if (run === quoteRun.current) setQuoting(false);
7756
- });
7757
- }, QUOTE_DEBOUNCE_MS);
7758
- return () => clearTimeout(timer);
7759
- }, [quoteKey]);
7760
- const chosenQuote = (routeChoice !== BEST_ROUTE ? quotes.find((q) => routeKey(q) === routeChoice) : void 0) ?? quotes[0] ?? null;
7761
- useEffect(() => {
7762
- if (direction === "OFFRAMP") void refreshWalletBalance();
7763
- }, [direction, refreshWalletBalance]);
7764
- async function loadRoutes(next) {
7765
- setRoutesLoading(true);
7766
- try {
7767
- const { routes: found } = await client.getRampRoutes(next);
7768
- setRoutes(found);
7769
- const seed = seedRef.current?.direction === next ? seedRef.current.options : null;
7770
- if (seed) seedRef.current = null;
7771
- const seeded = seed ? seededSelection(found, seed) : null;
7772
- if (seeded) {
7773
- setCountry(seeded.country);
7774
- setFiatChoice(seeded.fiatChoice);
7775
- setAssetChoice(seeded.assetChoice);
7776
- setAmount(seeded.amount);
7777
- return;
7778
- }
7779
- const first = rampCountries(found)[0]?.country ?? "";
7780
- setCountry((current) => found.some((r) => r.fiat.country === current) ? current : first);
7781
- } catch (error) {
7782
- setRoutes([]);
7783
- setErrorMsg(rampErrorMessage(error, copy.loadRoutesFailed, copy, language));
7784
- } finally {
7785
- setRoutesLoading(false);
7934
+ },
7935
+ es: {
7936
+ title: "Aprobaciones",
7937
+ manyPending: (count) => `${count} aprobaciones pendientes`,
7938
+ close: "Cerrar",
7939
+ whyTitle: "\xBFPor qu\xE9 ves esto?",
7940
+ whyBody: "Tu billetera necesita la firma de este dispositivo. Ni la app ni Pollar pueden aprobar esto sin ti.",
7941
+ rejectRequest: "Rechazar esta solicitud",
7942
+ closeTitle: "\xBFCerrar sin firmar?",
7943
+ closeBody: "La solicitud queda pendiente. La app no puede seguir hasta que la apruebes.",
7944
+ backToSign: "Volver y firmar",
7945
+ closeAnyway: "Cerrar igual",
7946
+ activateWallet: "Activar billetera",
7947
+ status: { APPROVED: "Aprobada", REJECTED: "Rechazada", EXPIRED: "Vencida", FAILED: "Fallida", PENDING: "Pendiente" },
7948
+ signedAppSends: "Firmada. La app la enviar\xE1.",
7949
+ signedSent: "Firmada y enviada",
7950
+ signed: "Firmada",
7951
+ nothingSigned: "No se firm\xF3 nada.",
7952
+ nothingWaiting: "No hay nada esperando tu aprobaci\xF3n.",
7953
+ next: (step) => `Siguiente: ${step}. Aparecer\xE1 aqu\xED en unos segundos.`,
7954
+ closingIn: (seconds) => `Se cierra en ${seconds}s`,
7955
+ expired: "vencida",
7956
+ expiresIn: "Vence en",
7957
+ checking: "Verificando...",
7958
+ verified: "Comprobada",
7959
+ checkedExact: "Comprobamos que esto es exactamente lo que est\xE1s aprobando.",
7960
+ notVerified: "Sin verificar:",
7961
+ reject: "Rechazar",
7962
+ rejecting: "Rechazando...",
7963
+ approve: "Aprobar",
7964
+ approving: "Aprobando...",
7965
+ genericError: "Algo sali\xF3 mal. Intenta de nuevo.",
7966
+ unreachable: "No pudimos conectar con Pollar, as\xED que no se aprob\xF3 nada. Revisa tu conexi\xF3n y aprueba de nuevo.",
7967
+ 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.",
7968
+ linkDevice: "Vincular este dispositivo",
7969
+ transaction: "Transacci\xF3n",
7970
+ operations: {
7971
+ payment: "Enviar",
7972
+ path_payment_strict_send: "Intercambiar",
7973
+ change_trust: "Agregar activo",
7974
+ create_account: "Crear cuenta",
7975
+ invoke_contract: "Llamada a contrato",
7976
+ soroban_auth: "Autorizar una llamada a contrato",
7977
+ manage_data: "Gestionar datos",
7978
+ transfer: "Enviar",
7979
+ ramp_payment: "Pago de rampa",
7980
+ cctp_burn: "Mover USDC",
7981
+ swap: "Intercambiar",
7982
+ earn_deposit: "Depositar",
7983
+ earn_withdraw: "Retirar",
7984
+ evm_delegation: "Activar transacciones at\xF3micas",
7985
+ provider_sign_in: "Confirma que eres t\xFA",
7986
+ sep10: "Confirma que eres t\xFA"
7786
7987
  }
7787
- }
7788
- async function loadPendingOrders() {
7789
- try {
7790
- const page = await client.listRampOrders({ open: "true", limit: 5 });
7791
- setPendingOrders(page.orders);
7792
- } catch {
7793
- setPendingOrders([]);
7988
+ },
7989
+ pt: {
7990
+ title: "Aprova\xE7\xF5es",
7991
+ manyPending: (count) => `${count} aprova\xE7\xF5es pendentes`,
7992
+ close: "Fechar",
7993
+ whyTitle: "Por que estou vendo isto?",
7994
+ whyBody: "Sua carteira precisa da assinatura deste dispositivo. Nem o app nem a Pollar podem aprovar isto sem voc\xEA.",
7995
+ rejectRequest: "Rejeitar esta solicita\xE7\xE3o",
7996
+ closeTitle: "Fechar sem assinar?",
7997
+ closeBody: "A solicita\xE7\xE3o fica pendente. O app n\xE3o pode continuar at\xE9 voc\xEA aprov\xE1-la.",
7998
+ backToSign: "Voltar e assinar",
7999
+ closeAnyway: "Fechar mesmo assim",
8000
+ activateWallet: "Ativar carteira",
8001
+ status: { APPROVED: "Aprovada", REJECTED: "Rejeitada", EXPIRED: "Expirada", FAILED: "Falhou", PENDING: "Pendente" },
8002
+ signedAppSends: "Assinada. O app vai envi\xE1-la.",
8003
+ signedSent: "Assinada e enviada",
8004
+ signed: "Assinada",
8005
+ nothingSigned: "Nada foi assinado.",
8006
+ nothingWaiting: "Nada aguarda a sua aprova\xE7\xE3o.",
8007
+ next: (step) => `Pr\xF3ximo: ${step}. Aparece aqui em alguns segundos.`,
8008
+ closingIn: (seconds) => `Fechando em ${seconds}s`,
8009
+ expired: "expirada",
8010
+ expiresIn: "Expira em",
8011
+ checking: "Verificando...",
8012
+ verified: "Conferida",
8013
+ checkedExact: "Conferimos que isto \xE9 exatamente o que voc\xEA est\xE1 aprovando.",
8014
+ notVerified: "N\xE3o verificada:",
8015
+ reject: "Rejeitar",
8016
+ rejecting: "Rejeitando...",
8017
+ approve: "Aprovar",
8018
+ approving: "Aprovando...",
8019
+ genericError: "Algo deu errado. Tente novamente.",
8020
+ unreachable: "N\xE3o conseguimos conectar \xE0 Pollar, ent\xE3o nada foi aprovado. Verifique sua conex\xE3o e aprove novamente.",
8021
+ 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.",
8022
+ linkDevice: "Vincular este dispositivo",
8023
+ transaction: "Transa\xE7\xE3o",
8024
+ operations: {
8025
+ payment: "Enviar",
8026
+ path_payment_strict_send: "Trocar",
8027
+ change_trust: "Adicionar ativo",
8028
+ create_account: "Criar conta",
8029
+ invoke_contract: "Chamada de contrato",
8030
+ soroban_auth: "Autorizar uma chamada de contrato",
8031
+ manage_data: "Gerenciar dados",
8032
+ transfer: "Enviar",
8033
+ ramp_payment: "Pagamento de rampa",
8034
+ cctp_burn: "Mover USDC",
8035
+ swap: "Trocar",
8036
+ earn_deposit: "Depositar",
8037
+ earn_withdraw: "Sacar",
8038
+ evm_delegation: "Ativar transa\xE7\xF5es at\xF4micas",
8039
+ provider_sign_in: "Confirme que \xE9 voc\xEA",
8040
+ sep10: "Confirme que \xE9 voc\xEA"
7794
8041
  }
7795
8042
  }
7796
- useEffect(() => {
7797
- void loadRoutes(direction);
7798
- }, [client, direction]);
7799
- useEffect(() => {
7800
- void loadPendingOrders();
7801
- }, [client]);
7802
- const orderId = order?.id ?? null;
7803
- useEffect(() => {
7804
- if (step !== "status" || !orderId) return;
7805
- const controller = new AbortController();
7806
- client.pollRampOrder(orderId, {
7807
- signal: controller.signal,
7808
- onUpdate: (next) => {
7809
- setOrder(next);
7810
- setPollTrouble(false);
7811
- },
7812
- onError: () => setPollTrouble(true)
7813
- }).catch((error) => {
7814
- if (!controller.signal.aborted) setErrorMsg(rampErrorMessage(error, copy.readOrderFailed, copy, language));
7815
- });
7816
- return () => controller.abort();
7817
- }, [client, step, orderId, pollKey]);
7818
- const awaitingPayment = step === "status" && order?.pendingAction?.kind === "FIAT_PAYMENT";
8043
+ };
8044
+ function labelOf2(request, copy) {
8045
+ const op = request.operation ?? "";
8046
+ return copy.operations[op] ?? (op ? op.replace(/_/g, " ") : copy.transaction);
8047
+ }
8048
+ function expiresIn(request, copy) {
8049
+ const ms = new Date(request.expiresAt).getTime() - Date.now();
8050
+ if (!Number.isFinite(ms) || ms <= 0) return copy.expired;
8051
+ const h = Math.floor(ms / 36e5);
8052
+ const m = Math.floor(ms % 36e5 / 6e4);
8053
+ return h > 0 ? `${h}h ${m}m` : `${m}m`;
8054
+ }
8055
+ function outcomeText(request, copy) {
8056
+ if (request.status !== "APPROVED")
8057
+ return `${copy.status[request.status] ?? request.status.toLowerCase()}. ${copy.nothingSigned}`;
8058
+ if (request.submit?.hash) return copy.signedSent;
8059
+ if (request.signedXdr) return copy.signedAppSends;
8060
+ return copy.status.APPROVED ?? "Approved";
8061
+ }
8062
+ function StepRow({
8063
+ request,
8064
+ review,
8065
+ copy,
8066
+ language
8067
+ }) {
8068
+ const [open, setOpen] = useState(false);
8069
+ const ok = request.status === "APPROVED";
8070
+ return /* @__PURE__ */ jsxs("div", { className: `pollar-cosign-step${ok ? "" : " pollar-cosign-step-bad"}`, children: [
8071
+ /* @__PURE__ */ jsxs("button", { type: "button", className: "pollar-cosign-step-head", "aria-expanded": open, onClick: () => setOpen((v) => !v), children: [
8072
+ /* @__PURE__ */ jsx(OutcomeIcon, { ok }),
8073
+ /* @__PURE__ */ jsx("span", { className: "pollar-cosign-step-title", children: review.title }),
8074
+ /* @__PURE__ */ jsx("span", { className: "pollar-cosign-step-status", children: ok ? copy.signed : copy.status[request.status] ?? request.status }),
8075
+ /* @__PURE__ */ jsx(
8076
+ "svg",
8077
+ {
8078
+ width: "10",
8079
+ height: "10",
8080
+ viewBox: "0 0 12 12",
8081
+ fill: "none",
8082
+ "aria-hidden": true,
8083
+ style: { transform: open ? "rotate(180deg)" : "none", transition: "transform 150ms" },
8084
+ children: /* @__PURE__ */ jsx("path", { d: "M2 4l4 4 4-4", stroke: "currentColor", strokeWidth: "1.6", strokeLinecap: "round", strokeLinejoin: "round" })
8085
+ }
8086
+ )
8087
+ ] }),
8088
+ open && /* @__PURE__ */ jsx(TxReview, { data: review, language, detailsOnly: true })
8089
+ ] });
8090
+ }
8091
+ function CloseIcon() {
8092
+ return /* @__PURE__ */ jsx("svg", { width: "14", height: "14", viewBox: "0 0 14 14", fill: "none", "aria-hidden": true, children: /* @__PURE__ */ jsx("path", { d: "m3 3 8 8M11 3l-8 8", stroke: "currentColor", strokeWidth: "1.7", strokeLinecap: "round" }) });
8093
+ }
8094
+ function VerifiedIcon() {
8095
+ return /* @__PURE__ */ jsxs("svg", { width: "14", height: "14", viewBox: "0 0 14 14", fill: "none", "aria-hidden": true, children: [
8096
+ /* @__PURE__ */ jsx("circle", { cx: "7", cy: "7", r: "7", fill: "currentColor" }),
8097
+ /* @__PURE__ */ jsx("path", { d: "M3.5 7l2.5 2.5 4.5-5", stroke: "white", strokeWidth: "1.4", strokeLinecap: "round", strokeLinejoin: "round" })
8098
+ ] });
8099
+ }
8100
+ function CosignModalTemplate({
8101
+ theme,
8102
+ accentColor,
8103
+ styleOverrides,
8104
+ pending,
8105
+ current,
8106
+ verification,
8107
+ busy,
8108
+ error,
8109
+ approveBlocked = false,
8110
+ deviceNotLinked = false,
8111
+ onLinkDevice,
8112
+ lastResolved,
8113
+ history = [],
8114
+ explorerUrlOf,
8115
+ closesIn = null,
8116
+ nextStep = null,
8117
+ language: languageProp,
8118
+ network,
8119
+ onSelect,
8120
+ onApprove,
8121
+ onReject,
8122
+ onClose,
8123
+ confirmingClose = false,
8124
+ onKeepOpen,
8125
+ onCloseAnyway,
8126
+ inline = false
8127
+ }) {
8128
+ const language = useInheritedLanguage(languageProp);
8129
+ const copy = COSIGN_COPY[language];
8130
+ const cssVars = buildModalCssVars(theme, accentColor, styleOverrides);
8131
+ const verified = verification?.ok === true && !deviceNotLinked;
8132
+ const canVote = !!current && verified && !busy && !approveBlocked;
8133
+ const [verifiedOpenFor, setVerifiedOpenFor] = useState(null);
8134
+ const verifiedOpen = !!current && verifiedOpenFor === current.id;
8135
+ const reviewOf = (request) => reviewFromRequest(
8136
+ {
8137
+ chain: request.network,
8138
+ network,
8139
+ operation: request.operation,
8140
+ summary: request.summary,
8141
+ details: request.details,
8142
+ signWith: request.account ?? request.signWith,
8143
+ raw: request.unsignedPayload,
8144
+ fallbackTitle: labelOf2(request, copy),
8145
+ ...request.status === "PENDING" ? { extraRows: [{ label: copy.expiresIn, value: expiresIn(request, copy) }] } : {},
8146
+ appPaysFee: request.submit?.sponsored ?? request.appPaysFee,
8147
+ ...request.submit?.hash ? { hash: { value: request.submit.hash, explorerUrl: explorerUrlOf?.(request) ?? null } } : {}
8148
+ },
8149
+ TX_REVIEW_COPY[language]
8150
+ );
8151
+ const review = current ? reviewOf(current) : null;
8152
+ const grouped = pending.length > 1;
8153
+ const shown = grouped ? null : current ?? (pending.length === 0 ? lastResolved : void 0) ?? null;
8154
+ const shownReview = shown ? shown === current ? review : reviewOf(shown) : null;
8155
+ const doneSteps = history.filter((r) => !(pending.length === 0 && r.id === lastResolved?.id));
8156
+ const heading = confirmingClose ? copy.closeTitle : grouped ? copy.manyPending(pending.length) : shownReview?.title ?? copy.title;
8157
+ const chip = current && !confirmingClose && /* @__PURE__ */ jsxs(Fragment, { children: [
8158
+ !verification && !deviceNotLinked && /* @__PURE__ */ jsxs("span", { className: "pollar-cosign-chip", children: [
8159
+ /* @__PURE__ */ jsx("span", { className: "pollar-spinner pollar-spinner-sm", "aria-hidden": true }),
8160
+ copy.checking
8161
+ ] }),
8162
+ verified && /* @__PURE__ */ jsxs(
8163
+ "button",
8164
+ {
8165
+ type: "button",
8166
+ className: "pollar-cosign-chip pollar-cosign-chip-ok",
8167
+ "aria-expanded": verifiedOpen,
8168
+ onClick: () => setVerifiedOpenFor(verifiedOpen ? null : current.id),
8169
+ children: [
8170
+ /* @__PURE__ */ jsx(VerifiedIcon, {}),
8171
+ copy.verified
8172
+ ]
8173
+ }
8174
+ )
8175
+ ] });
8176
+ return /* @__PURE__ */ jsxs(
8177
+ "div",
8178
+ {
8179
+ className: inline ? "pollar-cosign-modal pollar-cosign-inline" : "pollar-modal-card pollar-cosign-modal",
8180
+ "data-theme": theme,
8181
+ style: cssVars,
8182
+ onClick: (e) => e.stopPropagation(),
8183
+ children: [
8184
+ /* @__PURE__ */ jsxs("div", { className: "pollar-modal-header", children: [
8185
+ /* @__PURE__ */ jsxs("h2", { className: "pollar-modal-title pollar-cosign-heading", children: [
8186
+ !confirmingClose && /* @__PURE__ */ jsx(TitleMark, { chain: shown?.network, asset: shownReview ? headlineAsset(shownReview) : void 0 }),
8187
+ /* @__PURE__ */ jsx("span", { children: heading })
8188
+ ] }),
8189
+ /* @__PURE__ */ jsxs("div", { className: "pollar-modal-header-actions", children: [
8190
+ !grouped && chip,
8191
+ !confirmingClose && !inline && /* @__PURE__ */ jsx("button", { type: "button", className: "pollar-modal-close", onClick: onClose, "aria-label": copy.close, title: copy.close, children: /* @__PURE__ */ jsx(CloseIcon, {}) })
8192
+ ] })
8193
+ ] }),
8194
+ confirmingClose ? /* @__PURE__ */ jsxs("div", { className: "pollar-cosign-leave", children: [
8195
+ /* @__PURE__ */ jsx("p", { className: "pollar-cosign-muted", children: copy.closeBody }),
8196
+ /* @__PURE__ */ jsx("button", { type: "button", className: "pollar-cosign-btn pollar-cosign-btn-primary", onClick: onKeepOpen, children: copy.backToSign }),
8197
+ /* @__PURE__ */ jsx("button", { type: "button", className: "pollar-cosign-text-btn", onClick: onCloseAnyway, children: copy.closeAnyway })
8198
+ ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
8199
+ doneSteps.map((r) => /* @__PURE__ */ jsx(StepRow, { request: r, review: reviewOf(r), copy, language }, r.id)),
8200
+ pending.length === 0 && (lastResolved && shownReview ? /* @__PURE__ */ jsxs("div", { className: "pollar-cosign-detail", children: [
8201
+ /* @__PURE__ */ jsx(TxReview, { data: shownReview, language }, lastResolved.id),
8202
+ /* @__PURE__ */ jsxs("div", { className: `pollar-outcome${lastResolved.status === "APPROVED" ? "" : " pollar-outcome-bad"}`, children: [
8203
+ /* @__PURE__ */ jsxs("p", { className: "pollar-outcome-main", children: [
8204
+ /* @__PURE__ */ jsx(OutcomeIcon, { ok: lastResolved.status === "APPROVED" }),
8205
+ outcomeText(lastResolved, copy)
8206
+ ] }),
8207
+ nextStep && /* @__PURE__ */ jsxs("p", { className: "pollar-outcome-note", children: [
8208
+ /* @__PURE__ */ jsx("span", { className: "pollar-spinner pollar-spinner-sm", "aria-hidden": true }),
8209
+ " ",
8210
+ copy.next(nextStep)
8211
+ ] }),
8212
+ closesIn !== null && /* @__PURE__ */ jsx("p", { className: "pollar-outcome-note", children: copy.closingIn(closesIn) })
8213
+ ] })
8214
+ ] }) : /* @__PURE__ */ jsxs("div", { className: "pollar-cosign-empty", children: [
8215
+ /* @__PURE__ */ jsx("p", { className: "pollar-cosign-muted", children: copy.nothingWaiting }),
8216
+ closesIn !== null && /* @__PURE__ */ jsx("p", { className: "pollar-cosign-muted pollar-cosign-closing", children: copy.closingIn(closesIn) })
8217
+ ] })),
8218
+ grouped && /* @__PURE__ */ jsx("ul", { className: "pollar-cosign-list", children: pending.map((r) => /* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsxs(
8219
+ "button",
8220
+ {
8221
+ type: "button",
8222
+ className: `pollar-cosign-item${current?.id === r.id ? " pollar-cosign-item-active" : ""}`,
8223
+ onClick: () => onSelect(r),
8224
+ children: [
8225
+ /* @__PURE__ */ jsxs("span", { className: "pollar-cosign-heading", children: [
8226
+ /* @__PURE__ */ jsx(TitleMark, { chain: r.network, asset: headlineAsset(reviewOf(r)) }),
8227
+ reviewOf(r).title
8228
+ ] }),
8229
+ /* @__PURE__ */ jsx("span", { className: "pollar-cosign-muted", children: expiresIn(r, copy) })
8230
+ ]
8231
+ }
8232
+ ) }, r.id)) }),
8233
+ current && review && /* @__PURE__ */ jsxs("div", { className: `pollar-cosign-detail${grouped ? " pollar-cosign-detail-grouped" : ""}`, children: [
8234
+ grouped && /* @__PURE__ */ jsxs("div", { className: "pollar-cosign-detail-head", children: [
8235
+ /* @__PURE__ */ jsx("p", { className: "pollar-cosign-detail-title", children: review.title }),
8236
+ chip
8237
+ ] }),
8238
+ /* @__PURE__ */ jsx(
8239
+ TxReview,
8240
+ {
8241
+ data: review,
8242
+ language,
8243
+ detailsIntro: { title: copy.whyTitle, body: copy.whyBody },
8244
+ detailsAction: {
8245
+ label: busy === "rejecting" ? copy.rejecting : copy.rejectRequest,
8246
+ onClick: () => onReject(current),
8247
+ disabled: !!busy
8248
+ }
8249
+ },
8250
+ current.id
8251
+ ),
8252
+ verified && verifiedOpen && /* @__PURE__ */ jsx("div", { className: "pollar-cosign-verify pollar-cosign-verify-ok", children: copy.checkedExact }),
8253
+ deviceNotLinked ? /* @__PURE__ */ jsxs("div", { className: "pollar-cosign-verify pollar-cosign-verify-bad", children: [
8254
+ copy.deviceNotLinked,
8255
+ onLinkDevice && /* @__PURE__ */ jsx("button", { type: "button", className: "pollar-cosign-link", onClick: onLinkDevice, children: copy.linkDevice })
8256
+ ] }) : verification && !verification.ok && /* @__PURE__ */ jsxs("div", { className: "pollar-cosign-verify pollar-cosign-verify-bad", children: [
8257
+ copy.notVerified,
8258
+ " ",
8259
+ verification.reason
8260
+ ] }),
8261
+ error && /* @__PURE__ */ jsx("div", { className: "pollar-cosign-error", children: error }),
8262
+ /* @__PURE__ */ jsx(
8263
+ "button",
8264
+ {
8265
+ type: "button",
8266
+ className: "pollar-cosign-btn pollar-cosign-btn-primary",
8267
+ disabled: !canVote,
8268
+ onClick: () => onApprove(current),
8269
+ children: busy === "approving" ? copy.approving : review.kind === "activate_wallet" ? copy.activateWallet : copy.approve
8270
+ }
8271
+ )
8272
+ ] })
8273
+ ] }),
8274
+ !inline && /* @__PURE__ */ jsx(PollarModalFooter, {})
8275
+ ]
8276
+ }
8277
+ );
8278
+ }
8279
+ var CLOSE_AFTER_SECONDS = 3;
8280
+ var CLOSE_AFTER_SENT_SECONDS = 5;
8281
+ var NEXT_REQUEST_EVERY_MS = 2e3;
8282
+ function CosignModal(props) {
8283
+ const { styles } = usePollar();
8284
+ const { overlayStyle } = modalChrome(styles);
8285
+ return /* @__PURE__ */ jsx(PollarOverlay, { style: overlayStyle, children: /* @__PURE__ */ jsx(CosignPrompt, { ...props }) });
8286
+ }
8287
+ function CosignPrompt({ nextStep = null, onClose, inline = false }) {
8288
+ const { getClient, styles, network, openRecoveryModal } = usePollar();
8289
+ const { theme, accentColor, styleOverrides } = modalChrome(styles);
8290
+ const { pending, lastResolved, loaded, refresh, approve, reject, verify, inspectQuorum } = useCosign();
8291
+ const language = useModalLanguage();
8292
+ const [selectedId, setSelectedId] = useState(null);
8293
+ const [verification, setVerification] = useState(null);
8294
+ const [busy, setBusy] = useState(null);
8295
+ const [error, setError] = useState(null);
8296
+ const [approveFailedFor, setApproveFailedFor] = useState(null);
8297
+ const [quorumFailure, setQuorumFailure] = useState(null);
8298
+ const [deviceNotLinked, setDeviceNotLinked] = useState(false);
8299
+ useEffect(() => {
8300
+ let cancelled = false;
8301
+ inspectQuorum().then((q) => {
8302
+ if (cancelled || q.ok) return;
8303
+ if (q.code === "DEVICE_NOT_ENROLLED") setDeviceNotLinked(true);
8304
+ else setQuorumFailure(q.reason);
8305
+ }).catch(() => void 0);
8306
+ return () => {
8307
+ cancelled = true;
8308
+ };
8309
+ }, [inspectQuorum]);
8310
+ const current = pending.find((r) => r.id === selectedId) ?? pending[0] ?? null;
8311
+ const [history, setHistory] = useState([]);
8312
+ const resolvedBeforeOpen = useRef(lastResolved?.id);
8313
+ useEffect(() => {
8314
+ if (!lastResolved || lastResolved.id === resolvedBeforeOpen.current) return;
8315
+ setHistory((list) => [...list.filter((r) => r.id !== lastResolved.id), lastResolved]);
8316
+ }, [lastResolved]);
8317
+ const [askedToClose, setAskedToClose] = useState(false);
8318
+ const confirmingClose = askedToClose && pending.length > 0;
8319
+ const requestClose = () => pending.length > 0 ? setAskedToClose(true) : onClose();
8320
+ const currentRef = useRef(current);
8321
+ currentRef.current = current;
8322
+ const currentId = current?.id ?? null;
8323
+ useEffect(() => {
8324
+ const request = currentRef.current;
8325
+ if (!request) return;
8326
+ setVerification(null);
8327
+ setError(null);
8328
+ setApproveFailedFor(null);
8329
+ let cancelled = false;
8330
+ verify(request).then((v) => {
8331
+ if (!cancelled) setVerification(v);
8332
+ }).catch((err) => {
8333
+ if (!cancelled) setVerification({ ok: false, reason: err instanceof Error ? err.message : String(err) });
8334
+ });
8335
+ return () => {
8336
+ cancelled = true;
8337
+ };
8338
+ }, [currentId, verify]);
8339
+ const onCloseRef = useRef(onClose);
8340
+ onCloseRef.current = onClose;
8341
+ useEffect(() => {
8342
+ return getClient().onAuthStateChange((authState) => {
8343
+ if (authState.step === "idle") onCloseRef.current();
8344
+ });
8345
+ }, [getClient]);
8346
+ const silent = pending.length === 0 && (lastResolved ? lastResolved.status === "APPROVED" && !lastResolved.submit?.hash && !lastResolved.signedXdr : loaded);
8347
+ const sent = pending.length === 0 && lastResolved?.status === "APPROVED" && !!lastResolved.submit?.hash;
8348
+ const awaitingNext = sent && !!nextStep;
8349
+ const closeAfter = awaitingNext ? null : sent ? CLOSE_AFTER_SENT_SECONDS : silent ? CLOSE_AFTER_SECONDS : null;
8350
+ useEffect(() => {
8351
+ if (!awaitingNext) return;
8352
+ return startBackoffPoll(refresh, NEXT_REQUEST_EVERY_MS);
8353
+ }, [awaitingNext, refresh]);
8354
+ const [closesIn, setClosesIn] = useState(null);
8355
+ useEffect(() => {
8356
+ if (closeAfter === null) {
8357
+ setClosesIn(null);
8358
+ return;
8359
+ }
8360
+ let left = closeAfter;
8361
+ setClosesIn(left);
8362
+ const timer = setInterval(() => {
8363
+ left -= 1;
8364
+ if (left > 0) setClosesIn(left);
8365
+ else {
8366
+ clearInterval(timer);
8367
+ onCloseRef.current();
8368
+ }
8369
+ }, 1e3);
8370
+ return () => clearInterval(timer);
8371
+ }, [closeAfter, lastResolved?.id]);
8372
+ const run = useCallback(
8373
+ async (kind, request, action) => {
8374
+ setBusy(kind);
8375
+ setError(null);
8376
+ try {
8377
+ await action(request);
8378
+ } catch (err) {
8379
+ if (isPollarNetworkError(err) || err instanceof TypeError) {
8380
+ setError(COSIGN_COPY[language].unreachable);
8381
+ void refresh().catch(() => void 0);
8382
+ return;
8383
+ }
8384
+ setError(
8385
+ transactionErrorMessage(isPollarApiError(err) ? err.code : null, err instanceof Error ? err.message : null, language)
8386
+ );
8387
+ const retryable = isTransientApiError(err) || isPollarApiError(err) && err.code === "SDK_COSIGN_GAS_PENDING";
8388
+ if (kind === "approving" && !retryable) setApproveFailedFor(request.id);
8389
+ } finally {
8390
+ setBusy(null);
8391
+ }
8392
+ },
8393
+ [language, refresh]
8394
+ );
8395
+ return /* @__PURE__ */ jsx(
8396
+ CosignModalTemplate,
8397
+ {
8398
+ inline,
8399
+ theme,
8400
+ accentColor,
8401
+ styleOverrides,
8402
+ pending,
8403
+ current,
8404
+ verification: current ? quorumFailure ? { ok: false, reason: quorumFailure } : verification : null,
8405
+ busy,
8406
+ error,
8407
+ approveBlocked: !!current && approveFailedFor === current.id,
8408
+ deviceNotLinked,
8409
+ onLinkDevice: () => {
8410
+ onClose();
8411
+ openRecoveryModal();
8412
+ },
8413
+ ...lastResolved ? { lastResolved } : {},
8414
+ closesIn,
8415
+ nextStep: awaitingNext ? nextStep : null,
8416
+ language,
8417
+ network,
8418
+ history,
8419
+ explorerUrlOf: (r) => r.submit?.hash ? explorerTxUrl(r.network, r.submit.hash, network) : null,
8420
+ onSelect: (r) => setSelectedId(r.id),
8421
+ onApprove: (r) => void run("approving", r, approve),
8422
+ onReject: (r) => void run("rejecting", r, reject),
8423
+ onClose: requestClose,
8424
+ confirmingClose,
8425
+ onKeepOpen: () => setAskedToClose(false),
8426
+ onCloseAnyway: onClose
8427
+ }
8428
+ );
8429
+ }
8430
+ var PAYMENT_CHECK_EVERY_MS = 1e4;
8431
+ var PAYMENT_CHECK_WINDOW_MS = 2 * 6e4;
8432
+ function rampErrorMessage(error, fallback, copy, language) {
8433
+ const unavailable = appUnavailableMessage(error, language);
8434
+ if (unavailable) return unavailable;
8435
+ if (isPollarApiError(error)) {
8436
+ const known = copy.errors[error.code];
8437
+ if (known) return known;
8438
+ const message = error.body.message;
8439
+ if (typeof message === "string" && message && !/^[A-Z0-9_]+$/.test(message)) return message;
8440
+ }
8441
+ return fallback;
8442
+ }
8443
+ var DECIMAL = /^\d+(\.\d+)?$/;
8444
+ var QUOTE_DEBOUNCE_MS = 600;
8445
+ function seededSelection(routes, seed) {
8446
+ const countries = rampCountries(routes);
8447
+ const wanted = seed.country?.trim().toUpperCase();
8448
+ const country = wanted ? countries.find((c) => c.country === wanted) : countries[0];
8449
+ if (!country) return null;
8450
+ const fiat = country.fiats.find((f) => f.currency === seed.fiat?.trim().toUpperCase()) ?? null;
8451
+ const resolvedFiat = fiat ?? country.fiats[0];
8452
+ const asset = routes.find(
8453
+ (r) => r.fiat.country === country.country && resolvedFiat !== void 0 && fiatKey(r.fiat) === fiatKey(resolvedFiat) && r.asset.code.toUpperCase() === seed.asset?.trim().toUpperCase()
8454
+ )?.asset;
8455
+ const amount = seed.amount?.trim() ?? "";
8456
+ return {
8457
+ country: country.country,
8458
+ fiatChoice: fiat ? fiatKey(fiat) : "",
8459
+ assetChoice: asset ? assetKey3(asset) : "",
8460
+ amount: DECIMAL.test(amount) ? amount : ""
8461
+ };
8462
+ }
8463
+ async function signLegWithWallet(client, orderId, actionId, copy) {
8464
+ const lent = [];
8465
+ const lend = (chain, encoding, handler) => {
8466
+ try {
8467
+ lent.push(client.registerRampSigningHandler(chain, encoding, handler));
8468
+ } catch {
8469
+ }
8470
+ };
8471
+ lend("STELLAR", "xdr", async (action) => {
8472
+ const wallet = client.getWallet();
8473
+ if (!wallet) throw new Error(copy.connectStellarWallet);
8474
+ assertRampStellarSigner(action, wallet.address);
8475
+ const outcome = await client.signTx(action.payload.value);
8476
+ if (client.getWallet()?.address !== wallet.address) throw new Error(copy.walletChanged);
8477
+ if (outcome.status === "signed") return outcome.signedXdr;
8478
+ throw new Error(
8479
+ outcome.status === "error" ? outcome.message ?? outcome.details ?? copy.signingCancelled : copy.signingCancelled
8480
+ );
8481
+ });
8482
+ lend("SOLANA", "solana-v0-json", async (action) => {
8483
+ const payload = JSON.parse(action.payload.value);
8484
+ const solanaWallet = () => client.getWallets().find((w) => w.chain === "SOLANA" && w.custody === "external");
8485
+ const wallet = solanaWallet();
8486
+ if (!wallet || payload.from !== wallet.address || !payload.unsignedTransaction) throw new Error(copy.solanaWalletMismatch);
8487
+ const signed = await client.signSolanaTransaction(payload.unsignedTransaction);
8488
+ if (solanaWallet()?.address !== wallet.address) throw new Error(copy.walletChanged);
8489
+ return signed;
8490
+ });
8491
+ try {
8492
+ return await client.signRampLeg(orderId, actionId);
8493
+ } finally {
8494
+ for (const release of lent) release();
8495
+ }
8496
+ }
8497
+ function RampWidget({ onClose, language: languageProp, initial }) {
8498
+ const {
8499
+ getClient,
8500
+ styles,
8501
+ network,
8502
+ openCosignModal,
8503
+ setCosignNextStep,
8504
+ openRecoveryModal,
8505
+ recovery,
8506
+ recoveryLocked,
8507
+ appConfig,
8508
+ cosign,
8509
+ refreshWalletBalance,
8510
+ registerCosignHost
8511
+ } = usePollar();
8512
+ const client = getClient();
8513
+ const language = useModalLanguage(languageProp);
8514
+ const copy = RAMP_COPY[language];
8515
+ const { theme, accentColor, styleOverrides, overlayStyle } = modalChrome(styles);
8516
+ const [step, setStep] = useState("input");
8517
+ const confirmation = useInlineConfirmation(step === "status");
8518
+ const [direction, setDirection] = useState(initial?.direction === "sell" ? "OFFRAMP" : "ONRAMP");
8519
+ const seedRef = useRef(
8520
+ initial ? { direction: initial.direction === "sell" ? "OFFRAMP" : "ONRAMP", options: initial } : null
8521
+ );
8522
+ const [routes, setRoutes] = useState([]);
8523
+ const [routesLoading, setRoutesLoading] = useState(true);
8524
+ const [country, setCountry] = useState("");
8525
+ const [fiatChoice, setFiatChoice] = useState("");
8526
+ const [assetChoice, setAssetChoice] = useState("");
8527
+ const [amount, setAmount] = useState("");
8528
+ const [quotes, setQuotes] = useState([]);
8529
+ const [rejected, setRejected] = useState([]);
8530
+ const [selected, setSelected] = useState(null);
8531
+ const [startingQuoteId, setStartingQuoteId] = useState(null);
8532
+ const [fieldValues, setFieldValues] = useState({});
8533
+ const [order, setOrder] = useState(null);
8534
+ const [pendingOrders, setPendingOrders] = useState([]);
8535
+ const [isLoading, setIsLoading] = useState(false);
8536
+ const [refreshing, setRefreshing] = useState(false);
8537
+ const [signing, setSigning] = useState(false);
8538
+ const [errorMsg, setErrorMsg] = useState(null);
8539
+ const [verifying, setVerifying] = useState(null);
8540
+ const [trustingAsset, setTrustingAsset] = useState(null);
8541
+ const [walletBusy, setWalletBusy] = useState(null);
8542
+ const [retrying, setRetrying] = useState(false);
8543
+ const [cancelling, setCancelling] = useState(false);
8544
+ const [cancelError, setCancelError] = useState(null);
8545
+ const [awaitingAccount, setAwaitingAccount] = useState(null);
8546
+ const [pollTrouble, setPollTrouble] = useState(false);
8547
+ const [pollKey, setPollKey] = useState(0);
8548
+ const [paymentCheckUntil, setPaymentCheckUntil] = useState(null);
8549
+ const checkErrorRef = useRef(null);
8550
+ const promptedApproval = useRef(null);
8551
+ const custodyChoice = appConfig.application?.walletCustodyMode === "USER_CHOICE";
8552
+ const appChains = appConfig.application?.chains;
8553
+ const verifyAttempt = useRef(null);
8554
+ const countries = useMemo(() => rampCountries(routes), [routes]);
8555
+ const fiats = countries.find((c) => c.country === country)?.fiats ?? [];
8556
+ const fiat = fiats.find((f) => fiatKey(f) === fiatChoice) ?? fiats[0] ?? null;
8557
+ const assets = useMemo(() => {
8558
+ const seen = /* @__PURE__ */ new Map();
8559
+ for (const route of routes)
8560
+ if (fiat && route.fiat.country === country && fiatKey(route.fiat) === fiatKey(fiat))
8561
+ seen.set(assetKey3(route.asset), route.asset);
8562
+ return [...seen.values()];
8563
+ }, [routes, country, fiat]);
8564
+ const asset = assets.find((a) => assetKey3(a) === assetChoice) ?? assets[0] ?? null;
8565
+ const fields = selected ? rampQuoteFields(selected, language) : [];
8566
+ const sellAvailable = useWalletAvailable(
8567
+ direction === "OFFRAMP" && asset ? { chain: asset.chain, code: asset.code, issuer: asset.identifier } : null
8568
+ );
8569
+ const [quoting, setQuoting] = useState(false);
8570
+ const [routeChoice, setRouteChoice] = useState(BEST_ROUTE);
8571
+ const quoteRun = useRef(0);
8572
+ const quoteInput = step === "input" && fiat && asset && DECIMAL.test(amount.trim()) && Number(amount) > 0;
8573
+ const quoteKey = quoteInput ? `${direction}|${fiatKey(fiat)}|${assetKey3(asset)}|${amount.trim()}` : null;
8574
+ useEffect(() => {
8575
+ const run = ++quoteRun.current;
8576
+ if (!quoteKey || !fiat || !asset) {
8577
+ setQuoting(false);
8578
+ if (step === "input") {
8579
+ setQuotes([]);
8580
+ setRejected([]);
8581
+ }
8582
+ return;
8583
+ }
8584
+ setQuoting(true);
8585
+ const timer = setTimeout(() => {
8586
+ client.quoteRamp({
8587
+ direction,
8588
+ fiat: { currency: fiat.currency, rail: fiat.rail, country: fiat.country },
8589
+ asset: { code: asset.code, identifier: asset.identifier, chain: asset.chain },
8590
+ amount: { value: amount.trim(), denomination: "in" }
8591
+ }).then((result) => {
8592
+ if (run !== quoteRun.current) return;
8593
+ setQuotes(result.quotes);
8594
+ setRejected(result.rejected);
8595
+ setErrorMsg(null);
8596
+ }).catch((error) => {
8597
+ if (run !== quoteRun.current) return;
8598
+ setQuotes([]);
8599
+ if (isPollarApiError(error) && error.code === "SDK_RAMPS_NO_ROUTE") {
8600
+ setRejected(Array.isArray(error.body.rejected) ? error.body.rejected : []);
8601
+ } else {
8602
+ setRejected([]);
8603
+ setErrorMsg(rampErrorMessage(error, copy.findRouteFailed, copy, language));
8604
+ }
8605
+ }).finally(() => {
8606
+ if (run === quoteRun.current) setQuoting(false);
8607
+ });
8608
+ }, QUOTE_DEBOUNCE_MS);
8609
+ return () => clearTimeout(timer);
8610
+ }, [quoteKey]);
8611
+ const chosenQuote = (routeChoice !== BEST_ROUTE ? quotes.find((q) => routeKey(q) === routeChoice) : void 0) ?? quotes[0] ?? null;
8612
+ useEffect(() => {
8613
+ if (direction === "OFFRAMP") void refreshWalletBalance();
8614
+ }, [direction, refreshWalletBalance]);
8615
+ async function loadRoutes(next) {
8616
+ setRoutesLoading(true);
8617
+ try {
8618
+ const { routes: found } = await client.getRampRoutes(next);
8619
+ setRoutes(found);
8620
+ const seed = seedRef.current?.direction === next ? seedRef.current.options : null;
8621
+ if (seed) seedRef.current = null;
8622
+ const seeded = seed ? seededSelection(found, seed) : null;
8623
+ if (seeded) {
8624
+ setCountry(seeded.country);
8625
+ setFiatChoice(seeded.fiatChoice);
8626
+ setAssetChoice(seeded.assetChoice);
8627
+ setAmount(seeded.amount);
8628
+ return;
8629
+ }
8630
+ const first = rampCountries(found)[0]?.country ?? "";
8631
+ setCountry((current) => found.some((r) => r.fiat.country === current) ? current : first);
8632
+ } catch (error) {
8633
+ setRoutes([]);
8634
+ setErrorMsg(rampErrorMessage(error, copy.loadRoutesFailed, copy, language));
8635
+ } finally {
8636
+ setRoutesLoading(false);
8637
+ }
8638
+ }
8639
+ async function loadPendingOrders() {
8640
+ try {
8641
+ const page = await client.listRampOrders({ open: "true", limit: 5 });
8642
+ setPendingOrders(page.orders);
8643
+ } catch {
8644
+ setPendingOrders([]);
8645
+ }
8646
+ }
8647
+ useEffect(() => {
8648
+ void loadRoutes(direction);
8649
+ }, [client, direction]);
8650
+ useEffect(() => {
8651
+ void loadPendingOrders();
8652
+ }, [client]);
8653
+ const orderId = order?.id ?? null;
8654
+ useEffect(() => {
8655
+ if (step !== "status" || !orderId) return;
8656
+ const controller = new AbortController();
8657
+ client.pollRampOrder(orderId, {
8658
+ signal: controller.signal,
8659
+ onUpdate: (next) => {
8660
+ setOrder(next);
8661
+ setPollTrouble(false);
8662
+ },
8663
+ onError: () => setPollTrouble(true)
8664
+ }).catch((error) => {
8665
+ if (!controller.signal.aborted) setErrorMsg(rampErrorMessage(error, copy.readOrderFailed, copy, language));
8666
+ });
8667
+ return () => controller.abort();
8668
+ }, [client, step, orderId, pollKey]);
8669
+ const awaitingPayment = step === "status" && order?.pendingAction?.kind === "FIAT_PAYMENT";
7819
8670
  useEffect(() => {
7820
8671
  if (paymentCheckUntil === null || !orderId) return;
7821
8672
  if (!awaitingPayment) {
@@ -7823,14 +8674,13 @@ function RampWidget({ onClose, language: languageProp, initial }) {
7823
8674
  setPollKey((key) => key + 1);
7824
8675
  return;
7825
8676
  }
7826
- const timer = setInterval(() => {
8677
+ return startBackoffPoll(async () => {
7827
8678
  if (Date.now() >= paymentCheckUntil) {
7828
8679
  setPaymentCheckUntil(null);
7829
8680
  return;
7830
8681
  }
7831
- client.checkRampOrder(orderId).then(setOrder).catch(() => void 0);
8682
+ setOrder(await client.checkRampOrder(orderId));
7832
8683
  }, PAYMENT_CHECK_EVERY_MS);
7833
- return () => clearInterval(timer);
7834
8684
  }, [client, orderId, awaitingPayment, paymentCheckUntil]);
7835
8685
  useEffect(() => {
7836
8686
  if (awaitingPayment || checkErrorRef.current === null) return;
@@ -7838,6 +8688,10 @@ function RampWidget({ onClose, language: languageProp, initial }) {
7838
8688
  checkErrorRef.current = null;
7839
8689
  setErrorMsg((current) => current === shown ? null : current);
7840
8690
  }, [awaitingPayment]);
8691
+ const hostsCosign = step === "status" && !!order && !["completed", "failed", "refunded"].includes(order.state);
8692
+ const hostsCosignRef = useRef(hostsCosign);
8693
+ hostsCosignRef.current = hostsCosign;
8694
+ useEffect(() => hostsCosign ? registerCosignHost() : void 0, [hostsCosign, registerCosignHost]);
7841
8695
  const approval = order?.pendingAction?.kind === "COSIGN_APPROVAL" ? order.pendingAction.actionId : null;
7842
8696
  const approvalRequest = order?.pendingAction?.kind === "COSIGN_APPROVAL" ? order.pendingAction.cosignRequestId : null;
7843
8697
  useEffect(() => {
@@ -7846,7 +8700,7 @@ function RampWidget({ onClose, language: languageProp, initial }) {
7846
8700
  void client.cosign.pending().catch(() => []).then(async (requests) => {
7847
8701
  const request = requests.find((r) => r.id === approvalRequest);
7848
8702
  if (request && await client.autoApproveSignIn(request)) return;
7849
- openCosignModal();
8703
+ if (!hostsCosignRef.current) openCosignModal();
7850
8704
  });
7851
8705
  }, [approval, approvalRequest, client, openCosignModal]);
7852
8706
  const nextApproval = step === "status" && order ? rampNextApproval(order, language) : null;
@@ -8102,6 +8956,19 @@ function RampWidget({ onClose, language: languageProp, initial }) {
8102
8956
  setRetrying(false);
8103
8957
  }
8104
8958
  }
8959
+ async function handleCancelOrder() {
8960
+ if (!order || cancelling) return;
8961
+ setCancelling(true);
8962
+ setCancelError(null);
8963
+ try {
8964
+ setOrder(await client.cancelRampOrder(order.id));
8965
+ void loadPendingOrders();
8966
+ } catch (error) {
8967
+ setCancelError(rampErrorMessage(error, copy.cancelOrderFailed, copy, language));
8968
+ } finally {
8969
+ setCancelling(false);
8970
+ }
8971
+ }
8105
8972
  async function handleRequote() {
8106
8973
  setOrder(null);
8107
8974
  await handleFindRoute();
@@ -8253,6 +9120,7 @@ function RampWidget({ onClose, language: languageProp, initial }) {
8253
9120
  },
8254
9121
  onSign: () => void handleSign(),
8255
9122
  onApprove: openCosignModal,
9123
+ cosignPrompt: hostsCosign && cosign.pending.length > 0 ? /* @__PURE__ */ jsx(CosignPrompt, { inline: true, onClose: () => void 0 }) : null,
8256
9124
  retrying,
8257
9125
  onRetryOrder: () => void handleRetryOrder(),
8258
9126
  onRequote: () => void handleRequote(),
@@ -8272,7 +9140,10 @@ function RampWidget({ onClose, language: languageProp, initial }) {
8272
9140
  },
8273
9141
  onRefresh: () => void handleRefresh(),
8274
9142
  onClose,
8275
- confirmation
9143
+ confirmation,
9144
+ onCancelOrder: () => void handleCancelOrder(),
9145
+ cancelling,
9146
+ cancelError
8276
9147
  }
8277
9148
  ) });
8278
9149
  }
@@ -10841,16 +11712,16 @@ function SwapModal({ onClose, initial }) {
10841
11712
  useEffect(() => {
10842
11713
  if (!settlementKey || settlementDone || !originLanded) return;
10843
11714
  let cancelled = false;
10844
- const read = () => getSwapStatus(settlementKey).then((status) => {
10845
- if (!cancelled)
10846
- setSettlement((cur) => cur && cur.key === settlementKey ? { ...cur, value: status.settlement } : cur);
10847
- }).catch(() => {
11715
+ const read = async () => {
11716
+ const status = await getSwapStatus(settlementKey);
11717
+ if (!cancelled) setSettlement((cur) => cur && cur.key === settlementKey ? { ...cur, value: status.settlement } : cur);
11718
+ };
11719
+ void read().catch(() => {
10848
11720
  });
10849
- void read();
10850
- const id = setInterval(read, SETTLEMENT_POLL_MS);
11721
+ const stop = startBackoffPoll(read, SETTLEMENT_POLL_MS);
10851
11722
  return () => {
10852
11723
  cancelled = true;
10853
- clearInterval(id);
11724
+ stop();
10854
11725
  };
10855
11726
  }, [settlementKey, settlementDone, originLanded, getSwapStatus]);
10856
11727
  const hash = transaction.step === "success" ? transaction.hash : null;
@@ -12036,8 +12907,7 @@ function EarnModal({ onClose, initial }) {
12036
12907
  }, [refreshPosition]);
12037
12908
  useEffect(() => {
12038
12909
  if (step !== "form" || !onSolana && !provider || !opportunityId) return;
12039
- const id = setInterval(refreshPosition, POSITION_POLL_MS);
12040
- return () => clearInterval(id);
12910
+ return startBackoffPoll(async () => refreshPosition(), POSITION_POLL_MS);
12041
12911
  }, [step, onSolana, provider, opportunityId, refreshPosition]);
12042
12912
  useEffect(
12043
12913
  () => () => {
@@ -13179,13 +14049,10 @@ function CardModal({ onClose, initial }) {
13179
14049
  const kycPending = holder ? KYC_PENDING.has(holder.kycStatus) : false;
13180
14050
  useEffect(() => {
13181
14051
  if (!kycPending) return;
13182
- const id = setInterval(() => {
13183
- loadHolder().then((h) => {
13184
- if (h?.kycStatus === "APPROVED") void loadCardData();
13185
- }).catch(() => {
13186
- });
14052
+ return startBackoffPoll(async () => {
14053
+ const h = await loadHolder();
14054
+ if (h?.kycStatus === "APPROVED") void loadCardData();
13187
14055
  }, KYC_POLL_MS);
13188
- return () => clearInterval(id);
13189
14056
  }, [kycPending, loadHolder, loadCardData]);
13190
14057
  useEffect(
13191
14058
  () => () => {
@@ -13320,20 +14187,17 @@ function CardModal({ onClose, initial }) {
13320
14187
  const fundingsInflight = (fundings ?? []).some((f) => FUNDING_INFLIGHT.has(f.status));
13321
14188
  useEffect(() => {
13322
14189
  if (panel !== "fund" || !fundingsInflight) return;
13323
- const id = setInterval(() => {
13324
- getClient().listCardFundings().then((next) => {
13325
- setFundings((previous) => {
13326
- const credited = next.some(
13327
- (f) => f.status === "CREDITED" && previous?.find((p) => p.id === f.id)?.status !== "CREDITED"
13328
- );
13329
- if (credited) void loadCardData().catch(() => {
13330
- });
13331
- return next;
14190
+ return startBackoffPoll(async () => {
14191
+ const next = await getClient().listCardFundings();
14192
+ setFundings((previous) => {
14193
+ const credited = next.some(
14194
+ (f) => f.status === "CREDITED" && previous?.find((p) => p.id === f.id)?.status !== "CREDITED"
14195
+ );
14196
+ if (credited) void loadCardData().catch(() => {
13332
14197
  });
13333
- }).catch(() => {
14198
+ return next;
13334
14199
  });
13335
14200
  }, FUNDING_POLL_MS);
13336
- return () => clearInterval(id);
13337
14201
  }, [panel, fundingsInflight, getClient, loadCardData]);
13338
14202
  const field = (key, label, extra = {}) => /* @__PURE__ */ jsxs("label", { className: "pollar-send-field", children: [
13339
14203
  /* @__PURE__ */ jsx("span", { className: "pollar-send-label", children: label }),
@@ -13639,997 +14503,460 @@ function CardModal({ onClose, initial }) {
13639
14503
  ] }),
13640
14504
  /* @__PURE__ */ jsxs("div", { children: [
13641
14505
  /* @__PURE__ */ jsx("span", { children: copy.toPay }),
13642
- /* @__PURE__ */ jsx("strong", { children: usd(balance?.balanceDueCents, language) })
13643
- ] })
13644
- ] }),
13645
- /* @__PURE__ */ jsxs("div", { className: "pollar-modal-actions", children: [
13646
- provider.supports.revealSecrets && (secrets ? /* @__PURE__ */ jsx("button", { type: "button", className: "pollar-btn-secondary", onClick: () => setSecrets(null), children: copy.hideDetails }) : /* @__PURE__ */ jsx("button", { type: "button", className: "pollar-btn-secondary", onClick: () => void reveal(), disabled: busy !== null, children: busy === "reveal" ? copy.loading : copy.showDetails })),
13647
- /* @__PURE__ */ jsx("button", { type: "button", className: "pollar-btn-primary", onClick: () => void openFund(), disabled: busy !== null, children: copy.addFunds })
13648
- ] }),
13649
- secrets && /* @__PURE__ */ jsx("p", { className: "pollar-card-note", children: copy.detailsHide }),
13650
- /* @__PURE__ */ jsx("p", { className: "pollar-card-section-title", children: copy.recentActivity }),
13651
- transactions === null && /* @__PURE__ */ jsx("p", { className: "pollar-card-note", children: copy.loading }),
13652
- transactions?.length === 0 && /* @__PURE__ */ jsx("p", { className: "pollar-card-note", children: copy.noMovements }),
13653
- transactions?.map((tx) => {
13654
- const localAmount = typeof tx.purchase?.localAmount === "number" ? tx.purchase.localAmount : null;
13655
- const localCurrency = typeof tx.purchase?.localCurrency === "string" ? tx.purchase.localCurrency : null;
13656
- const purchaseStatus = typeof tx.purchase?.status === "string" ? tx.purchase.status : null;
13657
- const local = localAmount && localCurrency && localCurrency !== "USD" ? money(String(localAmount), localCurrency, language) : null;
13658
- return /* @__PURE__ */ jsxs("div", { className: "pollar-card-tx", children: [
13659
- /* @__PURE__ */ jsxs("div", { children: [
13660
- tx.merchantName ?? copy.txLabels[tx.type] ?? tx.type,
13661
- /* @__PURE__ */ jsxs("span", { className: "pollar-card-tx-meta", children: [
13662
- new Date(tx.occurredAt).toLocaleDateString(),
13663
- tx.merchantName ? ` \xB7 ${copy.txLabels[tx.type] ?? tx.type}` : "",
13664
- purchaseStatus && purchaseStatus !== "completed" ? ` \xB7 ${purchaseStatus}` : ""
13665
- ] })
13666
- ] }),
13667
- /* @__PURE__ */ jsxs("div", { className: "pollar-card-tx-amount", "data-direction": tx.direction ?? void 0, children: [
13668
- tx.direction === "credit" ? "+" : tx.direction === "debit" ? "-" : "",
13669
- money(tx.amount, tx.currency, language),
13670
- local && /* @__PURE__ */ jsx("span", { className: "pollar-card-tx-meta", children: local })
13671
- ] })
13672
- ] }, tx.id);
13673
- })
13674
- ] }),
13675
- !loading && provider && card && panel === "fund" && /* @__PURE__ */ jsxs(Fragment, { children: [
13676
- /* @__PURE__ */ jsx("p", { children: copy.fundIntro(provider.fundingAssets.join(` ${copy.or} `) || "USDC") }),
13677
- /* @__PURE__ */ jsx(
13678
- ChainSelect,
13679
- {
13680
- value: selectedFundChain,
13681
- options: fundChains,
13682
- onChange: (chain) => setFundChain(chain),
13683
- disabled: busy !== null,
13684
- language
13685
- }
13686
- ),
13687
- fundRoutes?.length === 0 && /* @__PURE__ */ jsx("p", { className: "pollar-card-note", children: copy.fundingProblem.noRoute }),
13688
- selectedRoute?.route === "CCTP" && /* @__PURE__ */ jsx("p", { className: "pollar-card-note", children: copy.fundingProblem.crossing }),
13689
- /* @__PURE__ */ jsx(
13690
- AmountField,
13691
- {
13692
- id: "pollar-card-fund-amount",
13693
- label: copy.amount,
13694
- value: fundAmount,
13695
- onChange: (value) => setFundAmount(value.replace(/[^0-9.]/g, "")),
13696
- unit: fundingAsset,
13697
- available: fundAvailable,
13698
- placeholder: "10",
13699
- language
13700
- }
13701
- ),
13702
- /* @__PURE__ */ jsx("div", { className: "pollar-modal-actions", children: /* @__PURE__ */ jsx(
13703
- "button",
13704
- {
13705
- type: "button",
13706
- className: "pollar-btn-primary",
13707
- onClick: () => void fund(),
13708
- disabled: busy !== null || !selectedRoute || !(Number(fundAmount) >= 1),
13709
- children: busy === "fund-send" ? copy.sending : copy.fundFromWallet
13710
- }
13711
- ) }),
13712
- confirmation && /* @__PURE__ */ jsx(InlineConfirm, { confirmation, language }),
13713
- !confirmation && sentFunding && (() => {
13714
- const f = sentFunding;
13715
- const state = (f.route === "DIRECT" ? copy.fundingSolana[f.status] : void 0) ?? copy.funding[f.status];
13716
- const steps = FUNDING_STEPS[f.route];
13717
- const step = steps.indexOf(f.status) + 1;
13718
- const inflight = FUNDING_INFLIGHT.has(f.status);
13719
- const failed = f.status === "FAILED";
13720
- return /* @__PURE__ */ jsxs(
13721
- "div",
13722
- {
13723
- className: `pollar-outcome${failed ? " pollar-outcome-bad" : ""}${inflight ? " pollar-outcome-busy" : ""}`,
13724
- role: "status",
13725
- children: [
13726
- /* @__PURE__ */ jsxs("p", { className: "pollar-outcome-main", children: [
13727
- inflight ? /* @__PURE__ */ jsx("span", { className: "pollar-spinner pollar-spinner-sm", "aria-hidden": true }) : /* @__PURE__ */ jsx(OutcomeIcon, { ok: !failed }),
13728
- state?.title ?? f.status,
13729
- " \xB7 ",
13730
- money(f.amount, "USD", language)
13731
- ] }),
13732
- inflight && step > 0 && /* @__PURE__ */ jsxs("p", { className: "pollar-outcome-note", children: [
13733
- copy.stepOf(step, steps.length),
13734
- " \xB7",
13735
- " ",
13736
- f.error === CREDIT_DELAYED ? copy.fundingProblem.delayed : state?.hint
13737
- ] }),
13738
- failed && /* @__PURE__ */ jsx("p", { className: "pollar-outcome-note", children: fundingProblemText(f.error, copy) })
13739
- ]
13740
- }
13741
- );
13742
- })(),
13743
- earlierFundings.length > 0 && /* @__PURE__ */ jsxs(Fragment, { children: [
13744
- /* @__PURE__ */ jsx("p", { className: "pollar-card-section-title", children: copy.yourFundings }),
13745
- earlierFundings.map((f) => {
13746
- const state = (f.route === "DIRECT" ? copy.fundingSolana[f.status] : void 0) ?? copy.funding[f.status];
13747
- const steps = FUNDING_STEPS[f.route];
13748
- const step = steps.indexOf(f.status) + 1;
13749
- const inflight = FUNDING_INFLIGHT.has(f.status);
13750
- return /* @__PURE__ */ jsxs("div", { className: "pollar-card-tx", "aria-busy": inflight, children: [
13751
- /* @__PURE__ */ jsxs("div", { children: [
13752
- /* @__PURE__ */ jsxs("span", { className: "pollar-card-funding-title", children: [
13753
- inflight && /* @__PURE__ */ jsx("span", { className: "pollar-spinner pollar-spinner-sm", "aria-hidden": true }),
13754
- state?.title ?? f.status
13755
- ] }),
13756
- inflight && step > 0 && /* @__PURE__ */ jsxs("span", { className: "pollar-card-tx-meta", role: "status", children: [
13757
- copy.stepOf(step, steps.length),
13758
- " \xB7",
13759
- " ",
13760
- f.error === CREDIT_DELAYED ? copy.fundingProblem.delayed : state?.hint
13761
- ] }),
13762
- /* @__PURE__ */ jsxs("span", { className: "pollar-card-tx-meta", children: [
13763
- new Date(f.createdAt).toLocaleString(),
13764
- f.status === "FAILED" ? ` \xB7 ${fundingProblemText(f.error, copy)}` : ""
13765
- ] })
13766
- ] }),
13767
- /* @__PURE__ */ jsx("div", { className: "pollar-card-tx-amount", "data-direction": f.status === "CREDITED" ? "credit" : void 0, children: money(f.amount, "USD", language) })
13768
- ] }, f.id);
13769
- }),
13770
- fundingsInflight && /* @__PURE__ */ jsx("p", { className: "pollar-card-note", children: copy.canClose })
13771
- ] }),
13772
- !showManual && /* @__PURE__ */ jsxs("p", { className: "pollar-card-note", children: [
13773
- copy.preferOtherWallet,
13774
- " ",
13775
- /* @__PURE__ */ jsx(
13776
- "button",
13777
- {
13778
- type: "button",
13779
- className: "pollar-card-link",
13780
- onClick: () => void showManualAddress(),
13781
- disabled: busy !== null,
13782
- children: copy.showDeposit
13783
- }
13784
- )
13785
- ] }),
13786
- showManual && deposit?.map((d) => /* @__PURE__ */ jsxs("div", { className: "pollar-card-deposit", children: [
13787
- /* @__PURE__ */ jsx("strong", { children: d.network }),
13788
- " (",
13789
- copy.chain(d.chainId),
13790
- ")",
13791
- /* @__PURE__ */ jsx("code", { children: d.address }),
13792
- /* @__PURE__ */ jsx(CopyButton, { value: d.address, label: copy.copyAddress, language }),
13793
- /* @__PURE__ */ jsx("p", { className: "pollar-card-note", children: copy.sendOnly(d.tokens.map((t) => (t.currency ?? "token").toUpperCase()).join(` ${copy.or} `), d.network) })
13794
- ] }, d.network)),
13795
- showManual && deposit?.length === 0 && /* @__PURE__ */ jsx("div", { className: "pollar-modal-error", children: copy.noDeposit }),
13796
- showManual && /* @__PURE__ */ jsx("p", { className: "pollar-card-note", children: /* @__PURE__ */ jsx("button", { type: "button", className: "pollar-card-link", onClick: () => setShowManual(false), children: copy.hideDeposit }) })
14506
+ /* @__PURE__ */ jsx("strong", { children: usd(balance?.balanceDueCents, language) })
14507
+ ] })
14508
+ ] }),
14509
+ /* @__PURE__ */ jsxs("div", { className: "pollar-modal-actions", children: [
14510
+ provider.supports.revealSecrets && (secrets ? /* @__PURE__ */ jsx("button", { type: "button", className: "pollar-btn-secondary", onClick: () => setSecrets(null), children: copy.hideDetails }) : /* @__PURE__ */ jsx("button", { type: "button", className: "pollar-btn-secondary", onClick: () => void reveal(), disabled: busy !== null, children: busy === "reveal" ? copy.loading : copy.showDetails })),
14511
+ /* @__PURE__ */ jsx("button", { type: "button", className: "pollar-btn-primary", onClick: () => void openFund(), disabled: busy !== null, children: copy.addFunds })
14512
+ ] }),
14513
+ secrets && /* @__PURE__ */ jsx("p", { className: "pollar-card-note", children: copy.detailsHide }),
14514
+ /* @__PURE__ */ jsx("p", { className: "pollar-card-section-title", children: copy.recentActivity }),
14515
+ transactions === null && /* @__PURE__ */ jsx("p", { className: "pollar-card-note", children: copy.loading }),
14516
+ transactions?.length === 0 && /* @__PURE__ */ jsx("p", { className: "pollar-card-note", children: copy.noMovements }),
14517
+ transactions?.map((tx) => {
14518
+ const localAmount = typeof tx.purchase?.localAmount === "number" ? tx.purchase.localAmount : null;
14519
+ const localCurrency = typeof tx.purchase?.localCurrency === "string" ? tx.purchase.localCurrency : null;
14520
+ const purchaseStatus = typeof tx.purchase?.status === "string" ? tx.purchase.status : null;
14521
+ const local = localAmount && localCurrency && localCurrency !== "USD" ? money(String(localAmount), localCurrency, language) : null;
14522
+ return /* @__PURE__ */ jsxs("div", { className: "pollar-card-tx", children: [
14523
+ /* @__PURE__ */ jsxs("div", { children: [
14524
+ tx.merchantName ?? copy.txLabels[tx.type] ?? tx.type,
14525
+ /* @__PURE__ */ jsxs("span", { className: "pollar-card-tx-meta", children: [
14526
+ new Date(tx.occurredAt).toLocaleDateString(),
14527
+ tx.merchantName ? ` \xB7 ${copy.txLabels[tx.type] ?? tx.type}` : "",
14528
+ purchaseStatus && purchaseStatus !== "completed" ? ` \xB7 ${purchaseStatus}` : ""
14529
+ ] })
14530
+ ] }),
14531
+ /* @__PURE__ */ jsxs("div", { className: "pollar-card-tx-amount", "data-direction": tx.direction ?? void 0, children: [
14532
+ tx.direction === "credit" ? "+" : tx.direction === "debit" ? "-" : "",
14533
+ money(tx.amount, tx.currency, language),
14534
+ local && /* @__PURE__ */ jsx("span", { className: "pollar-card-tx-meta", children: local })
14535
+ ] })
14536
+ ] }, tx.id);
14537
+ })
13797
14538
  ] }),
13798
- error && /* @__PURE__ */ jsx("div", { className: "pollar-modal-error", children: error }),
13799
- loadFailed && /* @__PURE__ */ jsx("div", { className: "pollar-modal-actions", children: /* @__PURE__ */ jsx("button", { type: "button", className: "pollar-btn-primary", onClick: retryLoad, children: copy.retry }) }),
13800
- /* @__PURE__ */ jsx(PollarModalFooter, { language })
13801
- ]
13802
- }
13803
- ) });
13804
- }
13805
-
13806
- // src/components/sessions-modal/sessions-copy.ts
13807
- var SESSIONS_COPY = {
13808
- en: {
13809
- title: "Active sessions",
13810
- refresh: "Refresh",
13811
- close: "Close",
13812
- loading: "Loading\u2026",
13813
- empty: "No active sessions.",
13814
- thisDevice: "This device",
13815
- activeNow: "Active now",
13816
- otherDevices: "Other devices",
13817
- signOutDevice: (device) => `Sign out ${device}`,
13818
- signingOut: "Signing out\u2026",
13819
- signOutThisDevice: "Sign out this device",
13820
- noOtherDevices: "No other devices to sign out",
13821
- signOutEverywhere: "Sign out everywhere",
13822
- unknownDevice: "Unknown device",
13823
- revokeFailed: "Could not sign out that device. Please try again.",
13824
- justNow: "just now",
13825
- secondsAgo: (n) => `${n}s ago`,
13826
- minutesAgo: (n) => `${n}m ago`,
13827
- hoursAgo: (n) => `${n}h ago`,
13828
- daysAgo: (n) => `${n}d ago`
13829
- },
13830
- es: {
13831
- title: "Sesiones activas",
13832
- refresh: "Actualizar",
13833
- close: "Cerrar",
13834
- loading: "Cargando\u2026",
13835
- empty: "No hay sesiones activas.",
13836
- thisDevice: "Este dispositivo",
13837
- activeNow: "Activa ahora",
13838
- otherDevices: "Otros dispositivos",
13839
- signOutDevice: (device) => `Cerrar sesi\xF3n en ${device}`,
13840
- signingOut: "Cerrando sesi\xF3n\u2026",
13841
- signOutThisDevice: "Cerrar sesi\xF3n en este dispositivo",
13842
- noOtherDevices: "No hay otros dispositivos donde cerrar sesi\xF3n",
13843
- signOutEverywhere: "Cerrar sesi\xF3n en todas partes",
13844
- unknownDevice: "Dispositivo desconocido",
13845
- revokeFailed: "No se pudo cerrar sesi\xF3n en ese dispositivo. Intenta de nuevo.",
13846
- justNow: "justo ahora",
13847
- secondsAgo: (n) => `hace ${n} s`,
13848
- minutesAgo: (n) => `hace ${n} min`,
13849
- hoursAgo: (n) => `hace ${n} h`,
13850
- daysAgo: (n) => `hace ${n} d`
13851
- },
13852
- pt: {
13853
- title: "Sess\xF5es ativas",
13854
- refresh: "Atualizar",
13855
- close: "Fechar",
13856
- loading: "Carregando\u2026",
13857
- empty: "Nenhuma sess\xE3o ativa.",
13858
- thisDevice: "Este dispositivo",
13859
- activeNow: "Ativa agora",
13860
- otherDevices: "Outros dispositivos",
13861
- signOutDevice: (device) => `Sair de ${device}`,
13862
- signingOut: "Saindo\u2026",
13863
- signOutThisDevice: "Sair deste dispositivo",
13864
- noOtherDevices: "N\xE3o h\xE1 outros dispositivos para sair",
13865
- signOutEverywhere: "Sair de todos os dispositivos",
13866
- unknownDevice: "Dispositivo desconhecido",
13867
- revokeFailed: "N\xE3o foi poss\xEDvel sair desse dispositivo. Tente novamente.",
13868
- justNow: "agora mesmo",
13869
- secondsAgo: (n) => `h\xE1 ${n} s`,
13870
- minutesAgo: (n) => `h\xE1 ${n} min`,
13871
- hoursAgo: (n) => `h\xE1 ${n} h`,
13872
- daysAgo: (n) => `h\xE1 ${n} d`
13873
- }
13874
- };
13875
- function describeDevice(s, copy) {
13876
- if (s.deviceLabel) return normalizeDeviceLabel(s.deviceLabel);
13877
- if (!s.userAgent) return copy.unknownDevice;
13878
- return parseUserAgent(s.userAgent);
13879
- }
13880
- function normalizeDeviceLabel(label) {
13881
- const parts = label.replace(/\s+/g, " ").split(/ (?:[—–-]|·) /);
13882
- if (parts.length === 2 && parts[1] !== void 0) return `${parts[0]} \xB7 ${parts[1].toLowerCase()}`;
13883
- return label;
13884
- }
13885
- function detectBrowser(ua) {
13886
- if (/Edg\//.test(ua)) return "Edge";
13887
- if (/OPR\//.test(ua)) return "Opera";
13888
- if (/(Chrome|CriOS)\//.test(ua)) return "Chrome";
13889
- if (/(Firefox|FxiOS)\//.test(ua)) return "Firefox";
13890
- if (/Safari\//.test(ua)) return "Safari";
13891
- return null;
13892
- }
13893
- function detectOS(ua) {
13894
- if (/iPhone|iPad|iPod/.test(ua)) return "iOS";
13895
- if (/Android/.test(ua)) return "Android";
13896
- if (/Mac OS X/.test(ua)) return "macOS";
13897
- if (/Windows NT/.test(ua)) return "Windows";
13898
- if (/Linux/.test(ua)) return "Linux";
13899
- return null;
13900
- }
13901
- function parseUserAgent(ua) {
13902
- const browser = detectBrowser(ua);
13903
- const os = detectOS(ua);
13904
- if (browser && os) return `${os} \xB7 ${browser.toLowerCase()}`;
13905
- if (os) return os;
13906
- if (browser) return browser;
13907
- return ua.slice(0, 48);
13908
- }
13909
- function formatRelative(iso, copy) {
13910
- if (!iso) return "\u2014";
13911
- const ts = new Date(iso).getTime();
13912
- if (!Number.isFinite(ts)) return "\u2014";
13913
- const diffSec = Math.round((Date.now() - ts) / 1e3);
13914
- if (diffSec < 0) return copy.justNow;
13915
- if (diffSec < 60) return copy.secondsAgo(diffSec);
13916
- const diffMin = Math.round(diffSec / 60);
13917
- if (diffMin < 60) return copy.minutesAgo(diffMin);
13918
- const diffHr = Math.round(diffMin / 60);
13919
- if (diffHr < 24) return copy.hoursAgo(diffHr);
13920
- const diffDay = Math.round(diffHr / 24);
13921
- if (diffDay < 30) return copy.daysAgo(diffDay);
13922
- return new Date(iso).toLocaleDateString(void 0, { month: "short", day: "numeric", year: "numeric" });
13923
- }
13924
- function shortIp(hash) {
13925
- if (!hash) return "";
13926
- return hash.slice(0, 8);
13927
- }
13928
- function deviceKind(session) {
13929
- const value = `${session.deviceLabel ?? ""} ${session.userAgent ?? ""}`.toLowerCase();
13930
- if (/ipad|tablet/.test(value)) return "tablet";
13931
- if (/android|iphone|ipod|mobile|phone/.test(value)) return "phone";
13932
- return "desktop";
13933
- }
13934
- function DeviceIcon({ kind, size = "small" }) {
13935
- const dimensions = size === "large" ? 30 : 18;
13936
- if (kind === "phone") {
13937
- return /* @__PURE__ */ jsxs("svg", { width: dimensions, height: dimensions, viewBox: "0 0 24 24", fill: "none", "aria-hidden": true, children: [
13938
- /* @__PURE__ */ jsx("rect", { x: "7", y: "2.5", width: "10", height: "19", rx: "2.5", stroke: "currentColor", strokeWidth: "1.8" }),
13939
- /* @__PURE__ */ jsx("path", { d: "M10.5 5h3M11 18.5h2", stroke: "currentColor", strokeWidth: "1.6", strokeLinecap: "round" })
13940
- ] });
13941
- }
13942
- if (kind === "tablet") {
13943
- return /* @__PURE__ */ jsxs("svg", { width: dimensions, height: dimensions, viewBox: "0 0 24 24", fill: "none", "aria-hidden": true, children: [
13944
- /* @__PURE__ */ jsx("rect", { x: "4.5", y: "2.5", width: "15", height: "19", rx: "2", stroke: "currentColor", strokeWidth: "1.8" }),
13945
- /* @__PURE__ */ jsx("path", { d: "M11 18.5h2", stroke: "currentColor", strokeWidth: "1.6", strokeLinecap: "round" })
13946
- ] });
13947
- }
13948
- return /* @__PURE__ */ jsxs("svg", { width: dimensions, height: dimensions, viewBox: "0 0 24 24", fill: "none", "aria-hidden": true, children: [
13949
- /* @__PURE__ */ jsx("rect", { x: "3", y: "3.5", width: "18", height: "12", rx: "1.8", stroke: "currentColor", strokeWidth: "1.8" }),
13950
- /* @__PURE__ */ jsx("path", { d: "M8 20.5h8M12 15.5v5", stroke: "currentColor", strokeWidth: "1.8", strokeLinecap: "round" })
13951
- ] });
13952
- }
13953
- function CheckIcon() {
13954
- return /* @__PURE__ */ jsx("svg", { width: "12", height: "12", viewBox: "0 0 12 12", fill: "none", "aria-hidden": true, children: /* @__PURE__ */ jsx("path", { d: "m2.5 6.2 2.1 2.1L9.6 3.6", stroke: "currentColor", strokeWidth: "1.7", strokeLinecap: "round", strokeLinejoin: "round" }) });
13955
- }
13956
- function CloseIcon() {
13957
- return /* @__PURE__ */ jsx("svg", { width: "14", height: "14", viewBox: "0 0 14 14", fill: "none", "aria-hidden": true, children: /* @__PURE__ */ jsx("path", { d: "m3 3 8 8M11 3l-8 8", stroke: "currentColor", strokeWidth: "1.7", strokeLinecap: "round" }) });
13958
- }
13959
- function SessionsModalTemplate({
13960
- theme,
13961
- accentColor,
13962
- styleOverrides,
13963
- state,
13964
- revokingFamilyId,
13965
- signingOutEverywhere,
13966
- revokeError,
13967
- onRefresh,
13968
- onRevoke,
13969
- onLogoutEverywhere,
13970
- onClose,
13971
- language: languageProp
13972
- }) {
13973
- const language = useInheritedLanguage(languageProp);
13974
- const copy = SESSIONS_COPY[language];
13975
- const cssVars = buildModalCssVars(theme, accentColor, styleOverrides);
13976
- const isLoading = state.step === "loading";
13977
- const sessions = state.step === "loaded" ? state.sessions : [];
13978
- const currentSession = sessions.find((s) => s.current);
13979
- const otherSessions = sessions.filter((s) => !s.current);
13980
- const otherCount = otherSessions.length;
13981
- return /* @__PURE__ */ jsxs(
13982
- "div",
13983
- {
13984
- className: "pollar-modal-card pollar-sessions-modal",
13985
- "data-theme": theme,
13986
- style: cssVars,
13987
- onClick: (e) => e.stopPropagation(),
13988
- children: [
13989
- /* @__PURE__ */ jsxs("div", { className: "pollar-modal-header", children: [
13990
- /* @__PURE__ */ jsx("h2", { className: "pollar-modal-title", children: copy.title }),
13991
- /* @__PURE__ */ jsxs("div", { className: "pollar-modal-header-actions", children: [
14539
+ !loading && provider && card && panel === "fund" && /* @__PURE__ */ jsxs(Fragment, { children: [
14540
+ /* @__PURE__ */ jsx("p", { children: copy.fundIntro(provider.fundingAssets.join(` ${copy.or} `) || "USDC") }),
14541
+ /* @__PURE__ */ jsx(
14542
+ ChainSelect,
14543
+ {
14544
+ value: selectedFundChain,
14545
+ options: fundChains,
14546
+ onChange: (chain) => setFundChain(chain),
14547
+ disabled: busy !== null,
14548
+ language
14549
+ }
14550
+ ),
14551
+ fundRoutes?.length === 0 && /* @__PURE__ */ jsx("p", { className: "pollar-card-note", children: copy.fundingProblem.noRoute }),
14552
+ selectedRoute?.route === "CCTP" && /* @__PURE__ */ jsx("p", { className: "pollar-card-note", children: copy.fundingProblem.crossing }),
14553
+ /* @__PURE__ */ jsx(
14554
+ AmountField,
14555
+ {
14556
+ id: "pollar-card-fund-amount",
14557
+ label: copy.amount,
14558
+ value: fundAmount,
14559
+ onChange: (value) => setFundAmount(value.replace(/[^0-9.]/g, "")),
14560
+ unit: fundingAsset,
14561
+ available: fundAvailable,
14562
+ placeholder: "10",
14563
+ language
14564
+ }
14565
+ ),
14566
+ /* @__PURE__ */ jsx("div", { className: "pollar-modal-actions", children: /* @__PURE__ */ jsx(
14567
+ "button",
14568
+ {
14569
+ type: "button",
14570
+ className: "pollar-btn-primary",
14571
+ onClick: () => void fund(),
14572
+ disabled: busy !== null || !selectedRoute || !(Number(fundAmount) >= 1),
14573
+ children: busy === "fund-send" ? copy.sending : copy.fundFromWallet
14574
+ }
14575
+ ) }),
14576
+ confirmation && /* @__PURE__ */ jsx(InlineConfirm, { confirmation, language }),
14577
+ !confirmation && sentFunding && (() => {
14578
+ const f = sentFunding;
14579
+ const state = (f.route === "DIRECT" ? copy.fundingSolana[f.status] : void 0) ?? copy.funding[f.status];
14580
+ const steps = FUNDING_STEPS[f.route];
14581
+ const step = steps.indexOf(f.status) + 1;
14582
+ const inflight = FUNDING_INFLIGHT.has(f.status);
14583
+ const failed = f.status === "FAILED";
14584
+ return /* @__PURE__ */ jsxs(
14585
+ "div",
14586
+ {
14587
+ className: `pollar-outcome${failed ? " pollar-outcome-bad" : ""}${inflight ? " pollar-outcome-busy" : ""}`,
14588
+ role: "status",
14589
+ children: [
14590
+ /* @__PURE__ */ jsxs("p", { className: "pollar-outcome-main", children: [
14591
+ inflight ? /* @__PURE__ */ jsx("span", { className: "pollar-spinner pollar-spinner-sm", "aria-hidden": true }) : /* @__PURE__ */ jsx(OutcomeIcon, { ok: !failed }),
14592
+ state?.title ?? f.status,
14593
+ " \xB7 ",
14594
+ money(f.amount, "USD", language)
14595
+ ] }),
14596
+ inflight && step > 0 && /* @__PURE__ */ jsxs("p", { className: "pollar-outcome-note", children: [
14597
+ copy.stepOf(step, steps.length),
14598
+ " \xB7",
14599
+ " ",
14600
+ f.error === CREDIT_DELAYED ? copy.fundingProblem.delayed : state?.hint
14601
+ ] }),
14602
+ failed && /* @__PURE__ */ jsx("p", { className: "pollar-outcome-note", children: fundingProblemText(f.error, copy) })
14603
+ ]
14604
+ }
14605
+ );
14606
+ })(),
14607
+ earlierFundings.length > 0 && /* @__PURE__ */ jsxs(Fragment, { children: [
14608
+ /* @__PURE__ */ jsx("p", { className: "pollar-card-section-title", children: copy.yourFundings }),
14609
+ earlierFundings.map((f) => {
14610
+ const state = (f.route === "DIRECT" ? copy.fundingSolana[f.status] : void 0) ?? copy.funding[f.status];
14611
+ const steps = FUNDING_STEPS[f.route];
14612
+ const step = steps.indexOf(f.status) + 1;
14613
+ const inflight = FUNDING_INFLIGHT.has(f.status);
14614
+ return /* @__PURE__ */ jsxs("div", { className: "pollar-card-tx", "aria-busy": inflight, children: [
14615
+ /* @__PURE__ */ jsxs("div", { children: [
14616
+ /* @__PURE__ */ jsxs("span", { className: "pollar-card-funding-title", children: [
14617
+ inflight && /* @__PURE__ */ jsx("span", { className: "pollar-spinner pollar-spinner-sm", "aria-hidden": true }),
14618
+ state?.title ?? f.status
14619
+ ] }),
14620
+ inflight && step > 0 && /* @__PURE__ */ jsxs("span", { className: "pollar-card-tx-meta", role: "status", children: [
14621
+ copy.stepOf(step, steps.length),
14622
+ " \xB7",
14623
+ " ",
14624
+ f.error === CREDIT_DELAYED ? copy.fundingProblem.delayed : state?.hint
14625
+ ] }),
14626
+ /* @__PURE__ */ jsxs("span", { className: "pollar-card-tx-meta", children: [
14627
+ new Date(f.createdAt).toLocaleString(),
14628
+ f.status === "FAILED" ? ` \xB7 ${fundingProblemText(f.error, copy)}` : ""
14629
+ ] })
14630
+ ] }),
14631
+ /* @__PURE__ */ jsx("div", { className: "pollar-card-tx-amount", "data-direction": f.status === "CREDITED" ? "credit" : void 0, children: money(f.amount, "USD", language) })
14632
+ ] }, f.id);
14633
+ }),
14634
+ fundingsInflight && /* @__PURE__ */ jsx("p", { className: "pollar-card-note", children: copy.canClose })
14635
+ ] }),
14636
+ !showManual && /* @__PURE__ */ jsxs("p", { className: "pollar-card-note", children: [
14637
+ copy.preferOtherWallet,
14638
+ " ",
13992
14639
  /* @__PURE__ */ jsx(
13993
14640
  "button",
13994
14641
  {
13995
14642
  type: "button",
13996
- className: "pollar-modal-close",
13997
- onClick: onRefresh,
13998
- disabled: isLoading,
13999
- "aria-label": copy.refresh,
14000
- title: copy.refresh,
14001
- children: /* @__PURE__ */ jsx(RefreshIcon, { spinning: isLoading })
14643
+ className: "pollar-card-link",
14644
+ onClick: () => void showManualAddress(),
14645
+ disabled: busy !== null,
14646
+ children: copy.showDeposit
14002
14647
  }
14003
- ),
14004
- /* @__PURE__ */ jsx("button", { type: "button", className: "pollar-modal-close", onClick: onClose, "aria-label": copy.close, title: copy.close, children: /* @__PURE__ */ jsx(CloseIcon, {}) })
14005
- ] })
14006
- ] }),
14007
- /* @__PURE__ */ jsxs("div", { className: "pollar-sessions-list", children: [
14008
- (state.step === "idle" || isLoading) && /* @__PURE__ */ jsxs("div", { className: "pollar-loading-block", children: [
14009
- /* @__PURE__ */ jsx("div", { className: "pollar-spinner" }),
14010
- /* @__PURE__ */ jsx("span", { children: copy.loading })
14011
- ] }),
14012
- state.step === "error" && /* @__PURE__ */ jsx("div", { className: "pollar-modal-empty", children: state.message }),
14013
- state.step === "loaded" && sessions.length === 0 && /* @__PURE__ */ jsx("div", { className: "pollar-modal-empty", children: copy.empty }),
14014
- state.step === "loaded" && currentSession && /* @__PURE__ */ jsxs("div", { className: "pollar-sessions-current-card", children: [
14015
- /* @__PURE__ */ jsxs("div", { className: "pollar-sessions-current-icon-wrap", children: [
14016
- /* @__PURE__ */ jsx(DeviceIcon, { kind: deviceKind(currentSession), size: "large" }),
14017
- /* @__PURE__ */ jsx("span", { className: "pollar-sessions-current-check", children: /* @__PURE__ */ jsx(CheckIcon, {}) })
14018
- ] }),
14019
- /* @__PURE__ */ jsx("span", { className: "pollar-sessions-current-label", children: copy.thisDevice }),
14020
- /* @__PURE__ */ jsx("strong", { className: "pollar-sessions-current-device", children: describeDevice(currentSession, copy) }),
14021
- /* @__PURE__ */ jsxs("div", { className: "pollar-sessions-current-status", children: [
14022
- /* @__PURE__ */ jsx("span", { className: "pollar-sessions-status-dot" }),
14023
- /* @__PURE__ */ jsx("span", { children: copy.activeNow }),
14024
- currentSession.ipHash && /* @__PURE__ */ jsxs(Fragment, { children: [
14025
- /* @__PURE__ */ jsx("span", { children: "\xB7" }),
14026
- /* @__PURE__ */ jsxs("span", { title: `ip-hash ${currentSession.ipHash}`, children: [
14027
- "IP ",
14028
- shortIp(currentSession.ipHash)
14029
- ] })
14030
- ] })
14031
- ] })
14032
- ] }),
14033
- state.step === "loaded" && otherSessions.length > 0 && /* @__PURE__ */ jsxs("section", { className: "pollar-sessions-other-section", "aria-labelledby": "pollar-other-devices-heading", children: [
14034
- /* @__PURE__ */ jsxs("h3", { id: "pollar-other-devices-heading", className: "pollar-sessions-section-title", children: [
14035
- copy.otherDevices,
14036
- " ",
14037
- /* @__PURE__ */ jsx("span", { children: otherCount })
14038
- ] }),
14039
- /* @__PURE__ */ jsx("div", { className: "pollar-sessions-grid", children: otherSessions.map((s) => {
14040
- const isRevoking = revokingFamilyId === s.familyId;
14041
- return /* @__PURE__ */ jsxs("div", { className: "pollar-sessions-item", children: [
14042
- /* @__PURE__ */ jsxs("div", { className: "pollar-sessions-item-top", children: [
14043
- /* @__PURE__ */ jsx("span", { className: "pollar-sessions-item-icon", children: /* @__PURE__ */ jsx(DeviceIcon, { kind: deviceKind(s) }) }),
14044
- /* @__PURE__ */ jsx(
14045
- "button",
14046
- {
14047
- type: "button",
14048
- className: "pollar-sessions-item-revoke",
14049
- onClick: () => onRevoke(s.familyId),
14050
- disabled: isRevoking || signingOutEverywhere,
14051
- "aria-label": copy.signOutDevice(describeDevice(s, copy)),
14052
- title: isRevoking ? copy.signingOut : copy.signOutThisDevice,
14053
- children: isRevoking ? /* @__PURE__ */ jsx("span", { className: "pollar-spinner pollar-spinner-sm" }) : /* @__PURE__ */ jsx(CloseIcon, {})
14054
- }
14055
- )
14056
- ] }),
14057
- /* @__PURE__ */ jsx("strong", { className: "pollar-sessions-item-device", children: describeDevice(s, copy) }),
14058
- /* @__PURE__ */ jsx("span", { className: "pollar-sessions-item-meta", children: formatRelative(s.lastUsedAt ?? s.createdAt, copy) })
14059
- ] }, s.familyId);
14060
- }) })
14648
+ )
14061
14649
  ] }),
14062
- revokeError && /* @__PURE__ */ jsx("div", { className: "pollar-sessions-action-error", role: "alert", children: revokeError })
14063
- ] }),
14064
- state.step === "loaded" && sessions.length > 0 && /* @__PURE__ */ jsx("div", { className: "pollar-sessions-actions", children: /* @__PURE__ */ jsx(
14065
- "button",
14066
- {
14067
- className: "pollar-sessions-logout-all",
14068
- onClick: onLogoutEverywhere,
14069
- disabled: signingOutEverywhere || otherCount === 0,
14070
- title: otherCount === 0 ? copy.noOtherDevices : void 0,
14071
- children: signingOutEverywhere ? /* @__PURE__ */ jsxs(Fragment, { children: [
14072
- /* @__PURE__ */ jsx("span", { className: "pollar-spinner pollar-spinner-sm pollar-spinner-current" }),
14073
- copy.signingOut
14074
- ] }) : copy.signOutEverywhere
14075
- }
14076
- ) }),
14077
- /* @__PURE__ */ jsx(PollarModalFooter, {})
14078
- ]
14079
- }
14080
- );
14081
- }
14082
- function SessionsModal({ onClose }) {
14083
- const { getClient, styles, sessions } = usePollar();
14084
- const { theme, accentColor, styleOverrides, overlayStyle } = modalChrome(styles);
14085
- const language = useModalLanguage();
14086
- const copy = SESSIONS_COPY[language];
14087
- const [revokingFamilyId, setRevokingFamilyId] = useState(null);
14088
- const [signingOutEverywhere, setSigningOutEverywhere] = useState(false);
14089
- const [revokeError, setRevokeError] = useState(null);
14090
- const load = useCallback(() => {
14091
- void getClient().fetchSessions();
14092
- }, [getClient]);
14093
- useEffect(() => {
14094
- load();
14095
- }, [load]);
14096
- const onCloseRef = useRef(onClose);
14097
- onCloseRef.current = onClose;
14098
- useEffect(() => {
14099
- return getClient().onAuthStateChange((authState) => {
14100
- if (authState.step === "idle") onCloseRef.current();
14101
- });
14102
- }, [getClient]);
14103
- const handleRevoke = useCallback(
14104
- async (familyId) => {
14105
- setRevokingFamilyId(familyId);
14106
- setRevokeError(null);
14107
- try {
14108
- await getClient().revokeSession(familyId);
14109
- } catch {
14110
- setRevokeError(copy.revokeFailed);
14111
- } finally {
14112
- setRevokingFamilyId(null);
14113
- load();
14114
- }
14115
- },
14116
- [getClient, load, copy]
14117
- );
14118
- const handleLogoutEverywhere = useCallback(async () => {
14119
- setSigningOutEverywhere(true);
14120
- try {
14121
- await getClient().logoutEverywhere();
14122
- onClose();
14123
- } catch {
14124
- setSigningOutEverywhere(false);
14125
- }
14126
- }, [getClient, onClose]);
14127
- return /* @__PURE__ */ jsx(PollarOverlay, { style: overlayStyle, onClick: onClose, children: /* @__PURE__ */ jsx(
14128
- SessionsModalTemplate,
14129
- {
14130
- theme,
14131
- accentColor,
14132
- styleOverrides,
14133
- state: sessions,
14134
- revokingFamilyId,
14135
- signingOutEverywhere,
14136
- revokeError,
14137
- onRefresh: () => load(),
14138
- onRevoke: (familyId) => void handleRevoke(familyId),
14139
- onLogoutEverywhere: () => void handleLogoutEverywhere(),
14140
- onClose,
14141
- language
14142
- }
14143
- ) });
14144
- }
14145
- function useCosign() {
14146
- const { getClient, isAuthenticated } = usePollar();
14147
- const [state, setState] = useState({ pending: [] });
14148
- const [loaded, setLoaded] = useState(false);
14149
- useEffect(() => getClient().onCosignStateChange(setState), [getClient]);
14150
- const refresh = useCallback(async () => {
14151
- if (!isAuthenticated) return;
14152
- try {
14153
- await getClient().cosign.pending();
14154
- } finally {
14155
- setLoaded(true);
14156
- }
14157
- }, [getClient, isAuthenticated]);
14158
- useEffect(() => {
14159
- void refresh();
14160
- }, [refresh]);
14161
- return {
14162
- pending: state.pending,
14163
- ...state.lastResolved ? { lastResolved: state.lastResolved } : {},
14164
- loaded,
14165
- refresh,
14166
- approve: useCallback((request) => getClient().cosign.approve(request), [getClient]),
14167
- reject: useCallback((request) => getClient().cosign.reject(request), [getClient]),
14168
- verify: useCallback((request) => getClient().cosign.verify(request), [getClient]),
14169
- inspectQuorum: useCallback(() => getClient().cosign.inspectQuorum(), [getClient]),
14170
- devices: useCallback(() => getClient().cosign.devices(), [getClient]),
14171
- revokeDevice: useCallback(
14172
- (deviceId, options) => getClient().cosign.revokeDevice(deviceId, options),
14173
- [getClient]
14174
- ),
14175
- switchCustody: useCallback((to) => getClient().cosign.switchCustody(to), [getClient])
14176
- };
14650
+ showManual && deposit?.map((d) => /* @__PURE__ */ jsxs("div", { className: "pollar-card-deposit", children: [
14651
+ /* @__PURE__ */ jsx("strong", { children: d.network }),
14652
+ " (",
14653
+ copy.chain(d.chainId),
14654
+ ")",
14655
+ /* @__PURE__ */ jsx("code", { children: d.address }),
14656
+ /* @__PURE__ */ jsx(CopyButton, { value: d.address, label: copy.copyAddress, language }),
14657
+ /* @__PURE__ */ jsx("p", { className: "pollar-card-note", children: copy.sendOnly(d.tokens.map((t) => (t.currency ?? "token").toUpperCase()).join(` ${copy.or} `), d.network) })
14658
+ ] }, d.network)),
14659
+ showManual && deposit?.length === 0 && /* @__PURE__ */ jsx("div", { className: "pollar-modal-error", children: copy.noDeposit }),
14660
+ showManual && /* @__PURE__ */ jsx("p", { className: "pollar-card-note", children: /* @__PURE__ */ jsx("button", { type: "button", className: "pollar-card-link", onClick: () => setShowManual(false), children: copy.hideDeposit }) })
14661
+ ] }),
14662
+ error && /* @__PURE__ */ jsx("div", { className: "pollar-modal-error", children: error }),
14663
+ loadFailed && /* @__PURE__ */ jsx("div", { className: "pollar-modal-actions", children: /* @__PURE__ */ jsx("button", { type: "button", className: "pollar-btn-primary", onClick: retryLoad, children: copy.retry }) }),
14664
+ /* @__PURE__ */ jsx(PollarModalFooter, { language })
14665
+ ]
14666
+ }
14667
+ ) });
14177
14668
  }
14178
14669
 
14179
- // src/components/cosign-modal/cosign-copy.ts
14180
- var COSIGN_COPY = {
14670
+ // src/components/sessions-modal/sessions-copy.ts
14671
+ var SESSIONS_COPY = {
14181
14672
  en: {
14182
- title: "Approvals",
14183
- manyPending: (count) => `${count} approvals waiting`,
14673
+ title: "Active sessions",
14674
+ refresh: "Refresh",
14184
14675
  close: "Close",
14185
- whyTitle: "Why am I seeing this?",
14186
- whyBody: "Your wallet needs this device's signature. Neither the app nor Pollar can approve this without you.",
14187
- rejectRequest: "Reject this request",
14188
- closeTitle: "Close without signing?",
14189
- closeBody: "The request stays pending. The app can't continue until you approve it.",
14190
- backToSign: "Go back and sign",
14191
- closeAnyway: "Close anyway",
14192
- activateWallet: "Activate wallet",
14193
- status: { APPROVED: "Approved", REJECTED: "Rejected", EXPIRED: "Expired", FAILED: "Failed", PENDING: "Pending" },
14194
- signedAppSends: "Signed. The app will send it.",
14195
- signedSent: "Signed and sent",
14196
- signed: "Signed",
14197
- nothingSigned: "Nothing was signed.",
14198
- nothingWaiting: "Nothing waits for your approval.",
14199
- next: (step) => `Next: ${step}. It appears here in a few seconds.`,
14200
- closingIn: (seconds) => `Closing in ${seconds}s`,
14201
- expired: "expired",
14202
- expiresIn: "Expires in",
14203
- checking: "Checking...",
14204
- verified: "Checked",
14205
- checkedExact: "We checked this is exactly what you're approving.",
14206
- notVerified: "Not verified:",
14207
- reject: "Reject",
14208
- rejecting: "Rejecting...",
14209
- approve: "Approve",
14210
- approving: "Approving...",
14211
- genericError: "Something went wrong. Please try again.",
14212
- unreachable: "We could not reach Pollar, so nothing was approved. Check your connection and approve again.",
14213
- 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.",
14214
- linkDevice: "Link this device",
14215
- transaction: "Transaction",
14216
- operations: {
14217
- payment: "Send",
14218
- path_payment_strict_send: "Swap",
14219
- change_trust: "Add asset",
14220
- create_account: "Create account",
14221
- invoke_contract: "Contract call",
14222
- soroban_auth: "Authorize a contract call",
14223
- manage_data: "Manage data",
14224
- transfer: "Send",
14225
- ramp_payment: "Ramp payment",
14226
- cctp_burn: "Move USDC",
14227
- swap: "Swap",
14228
- earn_deposit: "Deposit",
14229
- earn_withdraw: "Withdraw",
14230
- evm_delegation: "Enable atomic transactions",
14231
- provider_sign_in: "Confirm it's you",
14232
- sep10: "Confirm it's you"
14233
- }
14676
+ loading: "Loading\u2026",
14677
+ empty: "No active sessions.",
14678
+ thisDevice: "This device",
14679
+ activeNow: "Active now",
14680
+ otherDevices: "Other devices",
14681
+ signOutDevice: (device) => `Sign out ${device}`,
14682
+ signingOut: "Signing out\u2026",
14683
+ signOutThisDevice: "Sign out this device",
14684
+ noOtherDevices: "No other devices to sign out",
14685
+ signOutEverywhere: "Sign out everywhere",
14686
+ unknownDevice: "Unknown device",
14687
+ revokeFailed: "Could not sign out that device. Please try again.",
14688
+ justNow: "just now",
14689
+ secondsAgo: (n) => `${n}s ago`,
14690
+ minutesAgo: (n) => `${n}m ago`,
14691
+ hoursAgo: (n) => `${n}h ago`,
14692
+ daysAgo: (n) => `${n}d ago`
14234
14693
  },
14235
14694
  es: {
14236
- title: "Aprobaciones",
14237
- manyPending: (count) => `${count} aprobaciones pendientes`,
14695
+ title: "Sesiones activas",
14696
+ refresh: "Actualizar",
14238
14697
  close: "Cerrar",
14239
- whyTitle: "\xBFPor qu\xE9 ves esto?",
14240
- whyBody: "Tu billetera necesita la firma de este dispositivo. Ni la app ni Pollar pueden aprobar esto sin ti.",
14241
- rejectRequest: "Rechazar esta solicitud",
14242
- closeTitle: "\xBFCerrar sin firmar?",
14243
- closeBody: "La solicitud queda pendiente. La app no puede seguir hasta que la apruebes.",
14244
- backToSign: "Volver y firmar",
14245
- closeAnyway: "Cerrar igual",
14246
- activateWallet: "Activar billetera",
14247
- status: { APPROVED: "Aprobada", REJECTED: "Rechazada", EXPIRED: "Vencida", FAILED: "Fallida", PENDING: "Pendiente" },
14248
- signedAppSends: "Firmada. La app la enviar\xE1.",
14249
- signedSent: "Firmada y enviada",
14250
- signed: "Firmada",
14251
- nothingSigned: "No se firm\xF3 nada.",
14252
- nothingWaiting: "No hay nada esperando tu aprobaci\xF3n.",
14253
- next: (step) => `Siguiente: ${step}. Aparecer\xE1 aqu\xED en unos segundos.`,
14254
- closingIn: (seconds) => `Se cierra en ${seconds}s`,
14255
- expired: "vencida",
14256
- expiresIn: "Vence en",
14257
- checking: "Verificando...",
14258
- verified: "Comprobada",
14259
- checkedExact: "Comprobamos que esto es exactamente lo que est\xE1s aprobando.",
14260
- notVerified: "Sin verificar:",
14261
- reject: "Rechazar",
14262
- rejecting: "Rechazando...",
14263
- approve: "Aprobar",
14264
- approving: "Aprobando...",
14265
- genericError: "Algo sali\xF3 mal. Intenta de nuevo.",
14266
- unreachable: "No pudimos conectar con Pollar, as\xED que no se aprob\xF3 nada. Revisa tu conexi\xF3n y aprueba de nuevo.",
14267
- 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.",
14268
- linkDevice: "Vincular este dispositivo",
14269
- transaction: "Transacci\xF3n",
14270
- operations: {
14271
- payment: "Enviar",
14272
- path_payment_strict_send: "Intercambiar",
14273
- change_trust: "Agregar activo",
14274
- create_account: "Crear cuenta",
14275
- invoke_contract: "Llamada a contrato",
14276
- soroban_auth: "Autorizar una llamada a contrato",
14277
- manage_data: "Gestionar datos",
14278
- transfer: "Enviar",
14279
- ramp_payment: "Pago de rampa",
14280
- cctp_burn: "Mover USDC",
14281
- swap: "Intercambiar",
14282
- earn_deposit: "Depositar",
14283
- earn_withdraw: "Retirar",
14284
- evm_delegation: "Activar transacciones at\xF3micas",
14285
- provider_sign_in: "Confirma que eres t\xFA",
14286
- sep10: "Confirma que eres t\xFA"
14287
- }
14698
+ loading: "Cargando\u2026",
14699
+ empty: "No hay sesiones activas.",
14700
+ thisDevice: "Este dispositivo",
14701
+ activeNow: "Activa ahora",
14702
+ otherDevices: "Otros dispositivos",
14703
+ signOutDevice: (device) => `Cerrar sesi\xF3n en ${device}`,
14704
+ signingOut: "Cerrando sesi\xF3n\u2026",
14705
+ signOutThisDevice: "Cerrar sesi\xF3n en este dispositivo",
14706
+ noOtherDevices: "No hay otros dispositivos donde cerrar sesi\xF3n",
14707
+ signOutEverywhere: "Cerrar sesi\xF3n en todas partes",
14708
+ unknownDevice: "Dispositivo desconocido",
14709
+ revokeFailed: "No se pudo cerrar sesi\xF3n en ese dispositivo. Intenta de nuevo.",
14710
+ justNow: "justo ahora",
14711
+ secondsAgo: (n) => `hace ${n} s`,
14712
+ minutesAgo: (n) => `hace ${n} min`,
14713
+ hoursAgo: (n) => `hace ${n} h`,
14714
+ daysAgo: (n) => `hace ${n} d`
14288
14715
  },
14289
14716
  pt: {
14290
- title: "Aprova\xE7\xF5es",
14291
- manyPending: (count) => `${count} aprova\xE7\xF5es pendentes`,
14717
+ title: "Sess\xF5es ativas",
14718
+ refresh: "Atualizar",
14292
14719
  close: "Fechar",
14293
- whyTitle: "Por que estou vendo isto?",
14294
- whyBody: "Sua carteira precisa da assinatura deste dispositivo. Nem o app nem a Pollar podem aprovar isto sem voc\xEA.",
14295
- rejectRequest: "Rejeitar esta solicita\xE7\xE3o",
14296
- closeTitle: "Fechar sem assinar?",
14297
- closeBody: "A solicita\xE7\xE3o fica pendente. O app n\xE3o pode continuar at\xE9 voc\xEA aprov\xE1-la.",
14298
- backToSign: "Voltar e assinar",
14299
- closeAnyway: "Fechar mesmo assim",
14300
- activateWallet: "Ativar carteira",
14301
- status: { APPROVED: "Aprovada", REJECTED: "Rejeitada", EXPIRED: "Expirada", FAILED: "Falhou", PENDING: "Pendente" },
14302
- signedAppSends: "Assinada. O app vai envi\xE1-la.",
14303
- signedSent: "Assinada e enviada",
14304
- signed: "Assinada",
14305
- nothingSigned: "Nada foi assinado.",
14306
- nothingWaiting: "Nada aguarda a sua aprova\xE7\xE3o.",
14307
- next: (step) => `Pr\xF3ximo: ${step}. Aparece aqui em alguns segundos.`,
14308
- closingIn: (seconds) => `Fechando em ${seconds}s`,
14309
- expired: "expirada",
14310
- expiresIn: "Expira em",
14311
- checking: "Verificando...",
14312
- verified: "Conferida",
14313
- checkedExact: "Conferimos que isto \xE9 exatamente o que voc\xEA est\xE1 aprovando.",
14314
- notVerified: "N\xE3o verificada:",
14315
- reject: "Rejeitar",
14316
- rejecting: "Rejeitando...",
14317
- approve: "Aprovar",
14318
- approving: "Aprovando...",
14319
- genericError: "Algo deu errado. Tente novamente.",
14320
- unreachable: "N\xE3o conseguimos conectar \xE0 Pollar, ent\xE3o nada foi aprovado. Verifique sua conex\xE3o e aprove novamente.",
14321
- 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.",
14322
- linkDevice: "Vincular este dispositivo",
14323
- transaction: "Transa\xE7\xE3o",
14324
- operations: {
14325
- payment: "Enviar",
14326
- path_payment_strict_send: "Trocar",
14327
- change_trust: "Adicionar ativo",
14328
- create_account: "Criar conta",
14329
- invoke_contract: "Chamada de contrato",
14330
- soroban_auth: "Autorizar uma chamada de contrato",
14331
- manage_data: "Gerenciar dados",
14332
- transfer: "Enviar",
14333
- ramp_payment: "Pagamento de rampa",
14334
- cctp_burn: "Mover USDC",
14335
- swap: "Trocar",
14336
- earn_deposit: "Depositar",
14337
- earn_withdraw: "Sacar",
14338
- evm_delegation: "Ativar transa\xE7\xF5es at\xF4micas",
14339
- provider_sign_in: "Confirme que \xE9 voc\xEA",
14340
- sep10: "Confirme que \xE9 voc\xEA"
14341
- }
14720
+ loading: "Carregando\u2026",
14721
+ empty: "Nenhuma sess\xE3o ativa.",
14722
+ thisDevice: "Este dispositivo",
14723
+ activeNow: "Ativa agora",
14724
+ otherDevices: "Outros dispositivos",
14725
+ signOutDevice: (device) => `Sair de ${device}`,
14726
+ signingOut: "Saindo\u2026",
14727
+ signOutThisDevice: "Sair deste dispositivo",
14728
+ noOtherDevices: "N\xE3o h\xE1 outros dispositivos para sair",
14729
+ signOutEverywhere: "Sair de todos os dispositivos",
14730
+ unknownDevice: "Dispositivo desconhecido",
14731
+ revokeFailed: "N\xE3o foi poss\xEDvel sair desse dispositivo. Tente novamente.",
14732
+ justNow: "agora mesmo",
14733
+ secondsAgo: (n) => `h\xE1 ${n} s`,
14734
+ minutesAgo: (n) => `h\xE1 ${n} min`,
14735
+ hoursAgo: (n) => `h\xE1 ${n} h`,
14736
+ daysAgo: (n) => `h\xE1 ${n} d`
14342
14737
  }
14343
14738
  };
14344
- function labelOf2(request, copy) {
14345
- const op = request.operation ?? "";
14346
- return copy.operations[op] ?? (op ? op.replace(/_/g, " ") : copy.transaction);
14739
+ function describeDevice(s, copy) {
14740
+ if (s.deviceLabel) return normalizeDeviceLabel(s.deviceLabel);
14741
+ if (!s.userAgent) return copy.unknownDevice;
14742
+ return parseUserAgent(s.userAgent);
14743
+ }
14744
+ function normalizeDeviceLabel(label) {
14745
+ const parts = label.replace(/\s+/g, " ").split(/ (?:[—–-]|·) /);
14746
+ if (parts.length === 2 && parts[1] !== void 0) return `${parts[0]} \xB7 ${parts[1].toLowerCase()}`;
14747
+ return label;
14748
+ }
14749
+ function detectBrowser(ua) {
14750
+ if (/Edg\//.test(ua)) return "Edge";
14751
+ if (/OPR\//.test(ua)) return "Opera";
14752
+ if (/(Chrome|CriOS)\//.test(ua)) return "Chrome";
14753
+ if (/(Firefox|FxiOS)\//.test(ua)) return "Firefox";
14754
+ if (/Safari\//.test(ua)) return "Safari";
14755
+ return null;
14756
+ }
14757
+ function detectOS(ua) {
14758
+ if (/iPhone|iPad|iPod/.test(ua)) return "iOS";
14759
+ if (/Android/.test(ua)) return "Android";
14760
+ if (/Mac OS X/.test(ua)) return "macOS";
14761
+ if (/Windows NT/.test(ua)) return "Windows";
14762
+ if (/Linux/.test(ua)) return "Linux";
14763
+ return null;
14347
14764
  }
14348
- function expiresIn(request, copy) {
14349
- const ms = new Date(request.expiresAt).getTime() - Date.now();
14350
- if (!Number.isFinite(ms) || ms <= 0) return copy.expired;
14351
- const h = Math.floor(ms / 36e5);
14352
- const m = Math.floor(ms % 36e5 / 6e4);
14353
- return h > 0 ? `${h}h ${m}m` : `${m}m`;
14765
+ function parseUserAgent(ua) {
14766
+ const browser = detectBrowser(ua);
14767
+ const os = detectOS(ua);
14768
+ if (browser && os) return `${os} \xB7 ${browser.toLowerCase()}`;
14769
+ if (os) return os;
14770
+ if (browser) return browser;
14771
+ return ua.slice(0, 48);
14354
14772
  }
14355
- function outcomeText(request, copy) {
14356
- if (request.status !== "APPROVED")
14357
- return `${copy.status[request.status] ?? request.status.toLowerCase()}. ${copy.nothingSigned}`;
14358
- if (request.submit?.hash) return copy.signedSent;
14359
- if (request.signedXdr) return copy.signedAppSends;
14360
- return copy.status.APPROVED ?? "Approved";
14773
+ function formatRelative(iso, copy) {
14774
+ if (!iso) return "\u2014";
14775
+ const ts = new Date(iso).getTime();
14776
+ if (!Number.isFinite(ts)) return "\u2014";
14777
+ const diffSec = Math.round((Date.now() - ts) / 1e3);
14778
+ if (diffSec < 0) return copy.justNow;
14779
+ if (diffSec < 60) return copy.secondsAgo(diffSec);
14780
+ const diffMin = Math.round(diffSec / 60);
14781
+ if (diffMin < 60) return copy.minutesAgo(diffMin);
14782
+ const diffHr = Math.round(diffMin / 60);
14783
+ if (diffHr < 24) return copy.hoursAgo(diffHr);
14784
+ const diffDay = Math.round(diffHr / 24);
14785
+ if (diffDay < 30) return copy.daysAgo(diffDay);
14786
+ return new Date(iso).toLocaleDateString(void 0, { month: "short", day: "numeric", year: "numeric" });
14361
14787
  }
14362
- function StepRow({
14363
- request,
14364
- review,
14365
- copy,
14366
- language
14367
- }) {
14368
- const [open, setOpen] = useState(false);
14369
- const ok = request.status === "APPROVED";
14370
- return /* @__PURE__ */ jsxs("div", { className: `pollar-cosign-step${ok ? "" : " pollar-cosign-step-bad"}`, children: [
14371
- /* @__PURE__ */ jsxs("button", { type: "button", className: "pollar-cosign-step-head", "aria-expanded": open, onClick: () => setOpen((v) => !v), children: [
14372
- /* @__PURE__ */ jsx(OutcomeIcon, { ok }),
14373
- /* @__PURE__ */ jsx("span", { className: "pollar-cosign-step-title", children: review.title }),
14374
- /* @__PURE__ */ jsx("span", { className: "pollar-cosign-step-status", children: ok ? copy.signed : copy.status[request.status] ?? request.status }),
14375
- /* @__PURE__ */ jsx(
14376
- "svg",
14377
- {
14378
- width: "10",
14379
- height: "10",
14380
- viewBox: "0 0 12 12",
14381
- fill: "none",
14382
- "aria-hidden": true,
14383
- style: { transform: open ? "rotate(180deg)" : "none", transition: "transform 150ms" },
14384
- children: /* @__PURE__ */ jsx("path", { d: "M2 4l4 4 4-4", stroke: "currentColor", strokeWidth: "1.6", strokeLinecap: "round", strokeLinejoin: "round" })
14385
- }
14386
- )
14387
- ] }),
14388
- open && /* @__PURE__ */ jsx(TxReview, { data: review, language, detailsOnly: true })
14788
+ function shortIp(hash) {
14789
+ if (!hash) return "";
14790
+ return hash.slice(0, 8);
14791
+ }
14792
+ function deviceKind(session) {
14793
+ const value = `${session.deviceLabel ?? ""} ${session.userAgent ?? ""}`.toLowerCase();
14794
+ if (/ipad|tablet/.test(value)) return "tablet";
14795
+ if (/android|iphone|ipod|mobile|phone/.test(value)) return "phone";
14796
+ return "desktop";
14797
+ }
14798
+ function DeviceIcon({ kind, size = "small" }) {
14799
+ const dimensions = size === "large" ? 30 : 18;
14800
+ if (kind === "phone") {
14801
+ return /* @__PURE__ */ jsxs("svg", { width: dimensions, height: dimensions, viewBox: "0 0 24 24", fill: "none", "aria-hidden": true, children: [
14802
+ /* @__PURE__ */ jsx("rect", { x: "7", y: "2.5", width: "10", height: "19", rx: "2.5", stroke: "currentColor", strokeWidth: "1.8" }),
14803
+ /* @__PURE__ */ jsx("path", { d: "M10.5 5h3M11 18.5h2", stroke: "currentColor", strokeWidth: "1.6", strokeLinecap: "round" })
14804
+ ] });
14805
+ }
14806
+ if (kind === "tablet") {
14807
+ return /* @__PURE__ */ jsxs("svg", { width: dimensions, height: dimensions, viewBox: "0 0 24 24", fill: "none", "aria-hidden": true, children: [
14808
+ /* @__PURE__ */ jsx("rect", { x: "4.5", y: "2.5", width: "15", height: "19", rx: "2", stroke: "currentColor", strokeWidth: "1.8" }),
14809
+ /* @__PURE__ */ jsx("path", { d: "M11 18.5h2", stroke: "currentColor", strokeWidth: "1.6", strokeLinecap: "round" })
14810
+ ] });
14811
+ }
14812
+ return /* @__PURE__ */ jsxs("svg", { width: dimensions, height: dimensions, viewBox: "0 0 24 24", fill: "none", "aria-hidden": true, children: [
14813
+ /* @__PURE__ */ jsx("rect", { x: "3", y: "3.5", width: "18", height: "12", rx: "1.8", stroke: "currentColor", strokeWidth: "1.8" }),
14814
+ /* @__PURE__ */ jsx("path", { d: "M8 20.5h8M12 15.5v5", stroke: "currentColor", strokeWidth: "1.8", strokeLinecap: "round" })
14389
14815
  ] });
14390
14816
  }
14817
+ function CheckIcon() {
14818
+ return /* @__PURE__ */ jsx("svg", { width: "12", height: "12", viewBox: "0 0 12 12", fill: "none", "aria-hidden": true, children: /* @__PURE__ */ jsx("path", { d: "m2.5 6.2 2.1 2.1L9.6 3.6", stroke: "currentColor", strokeWidth: "1.7", strokeLinecap: "round", strokeLinejoin: "round" }) });
14819
+ }
14391
14820
  function CloseIcon2() {
14392
14821
  return /* @__PURE__ */ jsx("svg", { width: "14", height: "14", viewBox: "0 0 14 14", fill: "none", "aria-hidden": true, children: /* @__PURE__ */ jsx("path", { d: "m3 3 8 8M11 3l-8 8", stroke: "currentColor", strokeWidth: "1.7", strokeLinecap: "round" }) });
14393
14822
  }
14394
- function VerifiedIcon() {
14395
- return /* @__PURE__ */ jsxs("svg", { width: "14", height: "14", viewBox: "0 0 14 14", fill: "none", "aria-hidden": true, children: [
14396
- /* @__PURE__ */ jsx("circle", { cx: "7", cy: "7", r: "7", fill: "currentColor" }),
14397
- /* @__PURE__ */ jsx("path", { d: "M3.5 7l2.5 2.5 4.5-5", stroke: "white", strokeWidth: "1.4", strokeLinecap: "round", strokeLinejoin: "round" })
14398
- ] });
14399
- }
14400
- function CosignModalTemplate({
14823
+ function SessionsModalTemplate({
14401
14824
  theme,
14402
14825
  accentColor,
14403
14826
  styleOverrides,
14404
- pending,
14405
- current,
14406
- verification,
14407
- busy,
14408
- error,
14409
- approveBlocked = false,
14410
- deviceNotLinked = false,
14411
- onLinkDevice,
14412
- lastResolved,
14413
- history = [],
14414
- explorerUrlOf,
14415
- closesIn = null,
14416
- nextStep = null,
14417
- language: languageProp,
14418
- network,
14419
- onSelect,
14420
- onApprove,
14421
- onReject,
14827
+ state,
14828
+ revokingFamilyId,
14829
+ signingOutEverywhere,
14830
+ revokeError,
14831
+ onRefresh,
14832
+ onRevoke,
14833
+ onLogoutEverywhere,
14422
14834
  onClose,
14423
- confirmingClose = false,
14424
- onKeepOpen,
14425
- onCloseAnyway
14835
+ language: languageProp
14426
14836
  }) {
14427
14837
  const language = useInheritedLanguage(languageProp);
14428
- const copy = COSIGN_COPY[language];
14838
+ const copy = SESSIONS_COPY[language];
14429
14839
  const cssVars = buildModalCssVars(theme, accentColor, styleOverrides);
14430
- const verified = verification?.ok === true && !deviceNotLinked;
14431
- const canVote = !!current && verified && !busy && !approveBlocked;
14432
- const [verifiedOpenFor, setVerifiedOpenFor] = useState(null);
14433
- const verifiedOpen = !!current && verifiedOpenFor === current.id;
14434
- const reviewOf = (request) => reviewFromRequest(
14435
- {
14436
- chain: request.network,
14437
- network,
14438
- operation: request.operation,
14439
- summary: request.summary,
14440
- details: request.details,
14441
- signWith: request.account ?? request.signWith,
14442
- raw: request.unsignedPayload,
14443
- fallbackTitle: labelOf2(request, copy),
14444
- ...request.status === "PENDING" ? { extraRows: [{ label: copy.expiresIn, value: expiresIn(request, copy) }] } : {},
14445
- appPaysFee: request.submit?.sponsored ?? request.appPaysFee,
14446
- ...request.submit?.hash ? { hash: { value: request.submit.hash, explorerUrl: explorerUrlOf?.(request) ?? null } } : {}
14447
- },
14448
- TX_REVIEW_COPY[language]
14449
- );
14450
- const review = current ? reviewOf(current) : null;
14451
- const grouped = pending.length > 1;
14452
- const shown = grouped ? null : current ?? (pending.length === 0 ? lastResolved : void 0) ?? null;
14453
- const shownReview = shown ? shown === current ? review : reviewOf(shown) : null;
14454
- const doneSteps = history.filter((r) => !(pending.length === 0 && r.id === lastResolved?.id));
14455
- const heading = confirmingClose ? copy.closeTitle : grouped ? copy.manyPending(pending.length) : shownReview?.title ?? copy.title;
14456
- const chip = current && !confirmingClose && /* @__PURE__ */ jsxs(Fragment, { children: [
14457
- !verification && !deviceNotLinked && /* @__PURE__ */ jsxs("span", { className: "pollar-cosign-chip", children: [
14458
- /* @__PURE__ */ jsx("span", { className: "pollar-spinner pollar-spinner-sm", "aria-hidden": true }),
14459
- copy.checking
14460
- ] }),
14461
- verified && /* @__PURE__ */ jsxs(
14462
- "button",
14463
- {
14464
- type: "button",
14465
- className: "pollar-cosign-chip pollar-cosign-chip-ok",
14466
- "aria-expanded": verifiedOpen,
14467
- onClick: () => setVerifiedOpenFor(verifiedOpen ? null : current.id),
14468
- children: [
14469
- /* @__PURE__ */ jsx(VerifiedIcon, {}),
14470
- copy.verified
14471
- ]
14472
- }
14473
- )
14474
- ] });
14840
+ const isLoading = state.step === "loading";
14841
+ const sessions = state.step === "loaded" ? state.sessions : [];
14842
+ const currentSession = sessions.find((s) => s.current);
14843
+ const otherSessions = sessions.filter((s) => !s.current);
14844
+ const otherCount = otherSessions.length;
14475
14845
  return /* @__PURE__ */ jsxs(
14476
14846
  "div",
14477
14847
  {
14478
- className: "pollar-modal-card pollar-cosign-modal",
14848
+ className: "pollar-modal-card pollar-sessions-modal",
14479
14849
  "data-theme": theme,
14480
14850
  style: cssVars,
14481
14851
  onClick: (e) => e.stopPropagation(),
14482
14852
  children: [
14483
14853
  /* @__PURE__ */ jsxs("div", { className: "pollar-modal-header", children: [
14484
- /* @__PURE__ */ jsxs("h2", { className: "pollar-modal-title pollar-cosign-heading", children: [
14485
- !confirmingClose && /* @__PURE__ */ jsx(TitleMark, { chain: shown?.network, asset: shownReview ? headlineAsset(shownReview) : void 0 }),
14486
- /* @__PURE__ */ jsx("span", { children: heading })
14487
- ] }),
14488
- /* @__PURE__ */ jsxs("div", { className: "pollar-modal-header-actions", children: [
14489
- !grouped && chip,
14490
- !confirmingClose && /* @__PURE__ */ jsx("button", { type: "button", className: "pollar-modal-close", onClick: onClose, "aria-label": copy.close, title: copy.close, children: /* @__PURE__ */ jsx(CloseIcon2, {}) })
14491
- ] })
14492
- ] }),
14493
- confirmingClose ? /* @__PURE__ */ jsxs("div", { className: "pollar-cosign-leave", children: [
14494
- /* @__PURE__ */ jsx("p", { className: "pollar-cosign-muted", children: copy.closeBody }),
14495
- /* @__PURE__ */ jsx("button", { type: "button", className: "pollar-cosign-btn pollar-cosign-btn-primary", onClick: onKeepOpen, children: copy.backToSign }),
14496
- /* @__PURE__ */ jsx("button", { type: "button", className: "pollar-cosign-text-btn", onClick: onCloseAnyway, children: copy.closeAnyway })
14497
- ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
14498
- doneSteps.map((r) => /* @__PURE__ */ jsx(StepRow, { request: r, review: reviewOf(r), copy, language }, r.id)),
14499
- pending.length === 0 && (lastResolved && shownReview ? /* @__PURE__ */ jsxs("div", { className: "pollar-cosign-detail", children: [
14500
- /* @__PURE__ */ jsx(TxReview, { data: shownReview, language }, lastResolved.id),
14501
- /* @__PURE__ */ jsxs("div", { className: `pollar-outcome${lastResolved.status === "APPROVED" ? "" : " pollar-outcome-bad"}`, children: [
14502
- /* @__PURE__ */ jsxs("p", { className: "pollar-outcome-main", children: [
14503
- /* @__PURE__ */ jsx(OutcomeIcon, { ok: lastResolved.status === "APPROVED" }),
14504
- outcomeText(lastResolved, copy)
14505
- ] }),
14506
- nextStep && /* @__PURE__ */ jsxs("p", { className: "pollar-outcome-note", children: [
14507
- /* @__PURE__ */ jsx("span", { className: "pollar-spinner pollar-spinner-sm", "aria-hidden": true }),
14508
- " ",
14509
- copy.next(nextStep)
14510
- ] }),
14511
- closesIn !== null && /* @__PURE__ */ jsx("p", { className: "pollar-outcome-note", children: copy.closingIn(closesIn) })
14512
- ] })
14513
- ] }) : /* @__PURE__ */ jsxs("div", { className: "pollar-cosign-empty", children: [
14514
- /* @__PURE__ */ jsx("p", { className: "pollar-cosign-muted", children: copy.nothingWaiting }),
14515
- closesIn !== null && /* @__PURE__ */ jsx("p", { className: "pollar-cosign-muted pollar-cosign-closing", children: copy.closingIn(closesIn) })
14516
- ] })),
14517
- grouped && /* @__PURE__ */ jsx("ul", { className: "pollar-cosign-list", children: pending.map((r) => /* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsxs(
14518
- "button",
14519
- {
14520
- type: "button",
14521
- className: `pollar-cosign-item${current?.id === r.id ? " pollar-cosign-item-active" : ""}`,
14522
- onClick: () => onSelect(r),
14523
- children: [
14524
- /* @__PURE__ */ jsxs("span", { className: "pollar-cosign-heading", children: [
14525
- /* @__PURE__ */ jsx(TitleMark, { chain: r.network, asset: headlineAsset(reviewOf(r)) }),
14526
- reviewOf(r).title
14527
- ] }),
14528
- /* @__PURE__ */ jsx("span", { className: "pollar-cosign-muted", children: expiresIn(r, copy) })
14529
- ]
14530
- }
14531
- ) }, r.id)) }),
14532
- current && review && /* @__PURE__ */ jsxs("div", { className: `pollar-cosign-detail${grouped ? " pollar-cosign-detail-grouped" : ""}`, children: [
14533
- grouped && /* @__PURE__ */ jsxs("div", { className: "pollar-cosign-detail-head", children: [
14534
- /* @__PURE__ */ jsx("p", { className: "pollar-cosign-detail-title", children: review.title }),
14535
- chip
14536
- ] }),
14537
- /* @__PURE__ */ jsx(
14538
- TxReview,
14539
- {
14540
- data: review,
14541
- language,
14542
- detailsIntro: { title: copy.whyTitle, body: copy.whyBody },
14543
- detailsAction: {
14544
- label: busy === "rejecting" ? copy.rejecting : copy.rejectRequest,
14545
- onClick: () => onReject(current),
14546
- disabled: !!busy
14547
- }
14548
- },
14549
- current.id
14550
- ),
14551
- verified && verifiedOpen && /* @__PURE__ */ jsx("div", { className: "pollar-cosign-verify pollar-cosign-verify-ok", children: copy.checkedExact }),
14552
- deviceNotLinked ? /* @__PURE__ */ jsxs("div", { className: "pollar-cosign-verify pollar-cosign-verify-bad", children: [
14553
- copy.deviceNotLinked,
14554
- onLinkDevice && /* @__PURE__ */ jsx("button", { type: "button", className: "pollar-cosign-link", onClick: onLinkDevice, children: copy.linkDevice })
14555
- ] }) : verification && !verification.ok && /* @__PURE__ */ jsxs("div", { className: "pollar-cosign-verify pollar-cosign-verify-bad", children: [
14556
- copy.notVerified,
14557
- " ",
14558
- verification.reason
14559
- ] }),
14560
- error && /* @__PURE__ */ jsx("div", { className: "pollar-cosign-error", children: error }),
14854
+ /* @__PURE__ */ jsx("h2", { className: "pollar-modal-title", children: copy.title }),
14855
+ /* @__PURE__ */ jsxs("div", { className: "pollar-modal-header-actions", children: [
14561
14856
  /* @__PURE__ */ jsx(
14562
14857
  "button",
14563
14858
  {
14564
14859
  type: "button",
14565
- className: "pollar-cosign-btn pollar-cosign-btn-primary",
14566
- disabled: !canVote,
14567
- onClick: () => onApprove(current),
14568
- children: busy === "approving" ? copy.approving : review.kind === "activate_wallet" ? copy.activateWallet : copy.approve
14860
+ className: "pollar-modal-close",
14861
+ onClick: onRefresh,
14862
+ disabled: isLoading,
14863
+ "aria-label": copy.refresh,
14864
+ title: copy.refresh,
14865
+ children: /* @__PURE__ */ jsx(RefreshIcon, { spinning: isLoading })
14569
14866
  }
14570
- )
14867
+ ),
14868
+ /* @__PURE__ */ jsx("button", { type: "button", className: "pollar-modal-close", onClick: onClose, "aria-label": copy.close, title: copy.close, children: /* @__PURE__ */ jsx(CloseIcon2, {}) })
14571
14869
  ] })
14572
14870
  ] }),
14871
+ /* @__PURE__ */ jsxs("div", { className: "pollar-sessions-list", children: [
14872
+ (state.step === "idle" || isLoading) && /* @__PURE__ */ jsxs("div", { className: "pollar-loading-block", children: [
14873
+ /* @__PURE__ */ jsx("div", { className: "pollar-spinner" }),
14874
+ /* @__PURE__ */ jsx("span", { children: copy.loading })
14875
+ ] }),
14876
+ state.step === "error" && /* @__PURE__ */ jsx("div", { className: "pollar-modal-empty", children: state.message }),
14877
+ state.step === "loaded" && sessions.length === 0 && /* @__PURE__ */ jsx("div", { className: "pollar-modal-empty", children: copy.empty }),
14878
+ state.step === "loaded" && currentSession && /* @__PURE__ */ jsxs("div", { className: "pollar-sessions-current-card", children: [
14879
+ /* @__PURE__ */ jsxs("div", { className: "pollar-sessions-current-icon-wrap", children: [
14880
+ /* @__PURE__ */ jsx(DeviceIcon, { kind: deviceKind(currentSession), size: "large" }),
14881
+ /* @__PURE__ */ jsx("span", { className: "pollar-sessions-current-check", children: /* @__PURE__ */ jsx(CheckIcon, {}) })
14882
+ ] }),
14883
+ /* @__PURE__ */ jsx("span", { className: "pollar-sessions-current-label", children: copy.thisDevice }),
14884
+ /* @__PURE__ */ jsx("strong", { className: "pollar-sessions-current-device", children: describeDevice(currentSession, copy) }),
14885
+ /* @__PURE__ */ jsxs("div", { className: "pollar-sessions-current-status", children: [
14886
+ /* @__PURE__ */ jsx("span", { className: "pollar-sessions-status-dot" }),
14887
+ /* @__PURE__ */ jsx("span", { children: copy.activeNow }),
14888
+ currentSession.ipHash && /* @__PURE__ */ jsxs(Fragment, { children: [
14889
+ /* @__PURE__ */ jsx("span", { children: "\xB7" }),
14890
+ /* @__PURE__ */ jsxs("span", { title: `ip-hash ${currentSession.ipHash}`, children: [
14891
+ "IP ",
14892
+ shortIp(currentSession.ipHash)
14893
+ ] })
14894
+ ] })
14895
+ ] })
14896
+ ] }),
14897
+ state.step === "loaded" && otherSessions.length > 0 && /* @__PURE__ */ jsxs("section", { className: "pollar-sessions-other-section", "aria-labelledby": "pollar-other-devices-heading", children: [
14898
+ /* @__PURE__ */ jsxs("h3", { id: "pollar-other-devices-heading", className: "pollar-sessions-section-title", children: [
14899
+ copy.otherDevices,
14900
+ " ",
14901
+ /* @__PURE__ */ jsx("span", { children: otherCount })
14902
+ ] }),
14903
+ /* @__PURE__ */ jsx("div", { className: "pollar-sessions-grid", children: otherSessions.map((s) => {
14904
+ const isRevoking = revokingFamilyId === s.familyId;
14905
+ return /* @__PURE__ */ jsxs("div", { className: "pollar-sessions-item", children: [
14906
+ /* @__PURE__ */ jsxs("div", { className: "pollar-sessions-item-top", children: [
14907
+ /* @__PURE__ */ jsx("span", { className: "pollar-sessions-item-icon", children: /* @__PURE__ */ jsx(DeviceIcon, { kind: deviceKind(s) }) }),
14908
+ /* @__PURE__ */ jsx(
14909
+ "button",
14910
+ {
14911
+ type: "button",
14912
+ className: "pollar-sessions-item-revoke",
14913
+ onClick: () => onRevoke(s.familyId),
14914
+ disabled: isRevoking || signingOutEverywhere,
14915
+ "aria-label": copy.signOutDevice(describeDevice(s, copy)),
14916
+ title: isRevoking ? copy.signingOut : copy.signOutThisDevice,
14917
+ children: isRevoking ? /* @__PURE__ */ jsx("span", { className: "pollar-spinner pollar-spinner-sm" }) : /* @__PURE__ */ jsx(CloseIcon2, {})
14918
+ }
14919
+ )
14920
+ ] }),
14921
+ /* @__PURE__ */ jsx("strong", { className: "pollar-sessions-item-device", children: describeDevice(s, copy) }),
14922
+ /* @__PURE__ */ jsx("span", { className: "pollar-sessions-item-meta", children: formatRelative(s.lastUsedAt ?? s.createdAt, copy) })
14923
+ ] }, s.familyId);
14924
+ }) })
14925
+ ] }),
14926
+ revokeError && /* @__PURE__ */ jsx("div", { className: "pollar-sessions-action-error", role: "alert", children: revokeError })
14927
+ ] }),
14928
+ state.step === "loaded" && sessions.length > 0 && /* @__PURE__ */ jsx("div", { className: "pollar-sessions-actions", children: /* @__PURE__ */ jsx(
14929
+ "button",
14930
+ {
14931
+ className: "pollar-sessions-logout-all",
14932
+ onClick: onLogoutEverywhere,
14933
+ disabled: signingOutEverywhere || otherCount === 0,
14934
+ title: otherCount === 0 ? copy.noOtherDevices : void 0,
14935
+ children: signingOutEverywhere ? /* @__PURE__ */ jsxs(Fragment, { children: [
14936
+ /* @__PURE__ */ jsx("span", { className: "pollar-spinner pollar-spinner-sm pollar-spinner-current" }),
14937
+ copy.signingOut
14938
+ ] }) : copy.signOutEverywhere
14939
+ }
14940
+ ) }),
14573
14941
  /* @__PURE__ */ jsx(PollarModalFooter, {})
14574
14942
  ]
14575
14943
  }
14576
14944
  );
14577
14945
  }
14578
- var CLOSE_AFTER_SECONDS = 3;
14579
- var CLOSE_AFTER_SENT_SECONDS = 5;
14580
- var NEXT_REQUEST_EVERY_MS = 2e3;
14581
- function CosignModal({ nextStep = null, onClose }) {
14582
- const { getClient, styles, network, openRecoveryModal } = usePollar();
14946
+ function SessionsModal({ onClose }) {
14947
+ const { getClient, styles, sessions } = usePollar();
14583
14948
  const { theme, accentColor, styleOverrides, overlayStyle } = modalChrome(styles);
14584
- const { pending, lastResolved, loaded, refresh, approve, reject, verify, inspectQuorum } = useCosign();
14585
14949
  const language = useModalLanguage();
14586
- const [selectedId, setSelectedId] = useState(null);
14587
- const [verification, setVerification] = useState(null);
14588
- const [busy, setBusy] = useState(null);
14589
- const [error, setError] = useState(null);
14590
- const [approveFailedFor, setApproveFailedFor] = useState(null);
14591
- const [quorumFailure, setQuorumFailure] = useState(null);
14592
- const [deviceNotLinked, setDeviceNotLinked] = useState(false);
14593
- useEffect(() => {
14594
- let cancelled = false;
14595
- inspectQuorum().then((q) => {
14596
- if (cancelled || q.ok) return;
14597
- if (q.code === "DEVICE_NOT_ENROLLED") setDeviceNotLinked(true);
14598
- else setQuorumFailure(q.reason);
14599
- }).catch(() => void 0);
14600
- return () => {
14601
- cancelled = true;
14602
- };
14603
- }, [inspectQuorum]);
14604
- const current = pending.find((r) => r.id === selectedId) ?? pending[0] ?? null;
14605
- const [history, setHistory] = useState([]);
14606
- const resolvedBeforeOpen = useRef(lastResolved?.id);
14607
- useEffect(() => {
14608
- if (!lastResolved || lastResolved.id === resolvedBeforeOpen.current) return;
14609
- setHistory((list) => [...list.filter((r) => r.id !== lastResolved.id), lastResolved]);
14610
- }, [lastResolved]);
14611
- const [askedToClose, setAskedToClose] = useState(false);
14612
- const confirmingClose = askedToClose && pending.length > 0;
14613
- const requestClose = () => pending.length > 0 ? setAskedToClose(true) : onClose();
14614
- const currentRef = useRef(current);
14615
- currentRef.current = current;
14616
- const currentId = current?.id ?? null;
14950
+ const copy = SESSIONS_COPY[language];
14951
+ const [revokingFamilyId, setRevokingFamilyId] = useState(null);
14952
+ const [signingOutEverywhere, setSigningOutEverywhere] = useState(false);
14953
+ const [revokeError, setRevokeError] = useState(null);
14954
+ const load = useCallback(() => {
14955
+ void getClient().fetchSessions();
14956
+ }, [getClient]);
14617
14957
  useEffect(() => {
14618
- const request = currentRef.current;
14619
- if (!request) return;
14620
- setVerification(null);
14621
- setError(null);
14622
- setApproveFailedFor(null);
14623
- let cancelled = false;
14624
- verify(request).then((v) => {
14625
- if (!cancelled) setVerification(v);
14626
- }).catch((err) => {
14627
- if (!cancelled) setVerification({ ok: false, reason: err instanceof Error ? err.message : String(err) });
14628
- });
14629
- return () => {
14630
- cancelled = true;
14631
- };
14632
- }, [currentId, verify]);
14958
+ load();
14959
+ }, [load]);
14633
14960
  const onCloseRef = useRef(onClose);
14634
14961
  onCloseRef.current = onClose;
14635
14962
  useEffect(() => {
@@ -14637,87 +14964,45 @@ function CosignModal({ nextStep = null, onClose }) {
14637
14964
  if (authState.step === "idle") onCloseRef.current();
14638
14965
  });
14639
14966
  }, [getClient]);
14640
- const silent = pending.length === 0 && (lastResolved ? lastResolved.status === "APPROVED" && !lastResolved.submit?.hash && !lastResolved.signedXdr : loaded);
14641
- const sent = pending.length === 0 && lastResolved?.status === "APPROVED" && !!lastResolved.submit?.hash;
14642
- const awaitingNext = sent && !!nextStep;
14643
- const closeAfter = awaitingNext ? null : sent ? CLOSE_AFTER_SENT_SECONDS : silent ? CLOSE_AFTER_SECONDS : null;
14644
- useEffect(() => {
14645
- if (!awaitingNext) return;
14646
- const timer = setInterval(() => void refresh().catch(() => void 0), NEXT_REQUEST_EVERY_MS);
14647
- return () => clearInterval(timer);
14648
- }, [awaitingNext, refresh]);
14649
- const [closesIn, setClosesIn] = useState(null);
14650
- useEffect(() => {
14651
- if (closeAfter === null) {
14652
- setClosesIn(null);
14653
- return;
14654
- }
14655
- let left = closeAfter;
14656
- setClosesIn(left);
14657
- const timer = setInterval(() => {
14658
- left -= 1;
14659
- if (left > 0) setClosesIn(left);
14660
- else {
14661
- clearInterval(timer);
14662
- onCloseRef.current();
14663
- }
14664
- }, 1e3);
14665
- return () => clearInterval(timer);
14666
- }, [closeAfter, lastResolved?.id]);
14667
- const run = useCallback(
14668
- async (kind, request, action) => {
14669
- setBusy(kind);
14670
- setError(null);
14967
+ const handleRevoke = useCallback(
14968
+ async (familyId) => {
14969
+ setRevokingFamilyId(familyId);
14970
+ setRevokeError(null);
14671
14971
  try {
14672
- await action(request);
14673
- } catch (err) {
14674
- if (isPollarNetworkError(err) || err instanceof TypeError) {
14675
- setError(COSIGN_COPY[language].unreachable);
14676
- void refresh().catch(() => void 0);
14677
- return;
14678
- }
14679
- setError(
14680
- transactionErrorMessage(isPollarApiError(err) ? err.code : null, err instanceof Error ? err.message : null, language)
14681
- );
14682
- if (kind === "approving" && !(isPollarApiError(err) && err.code === "SDK_COSIGN_GAS_PENDING"))
14683
- setApproveFailedFor(request.id);
14972
+ await getClient().revokeSession(familyId);
14973
+ } catch {
14974
+ setRevokeError(copy.revokeFailed);
14684
14975
  } finally {
14685
- setBusy(null);
14976
+ setRevokingFamilyId(null);
14977
+ load();
14686
14978
  }
14687
14979
  },
14688
- [language, refresh]
14980
+ [getClient, load, copy]
14689
14981
  );
14690
- return /* @__PURE__ */ jsx(PollarOverlay, { style: overlayStyle, children: /* @__PURE__ */ jsx(
14691
- CosignModalTemplate,
14982
+ const handleLogoutEverywhere = useCallback(async () => {
14983
+ setSigningOutEverywhere(true);
14984
+ try {
14985
+ await getClient().logoutEverywhere();
14986
+ onClose();
14987
+ } catch {
14988
+ setSigningOutEverywhere(false);
14989
+ }
14990
+ }, [getClient, onClose]);
14991
+ return /* @__PURE__ */ jsx(PollarOverlay, { style: overlayStyle, onClick: onClose, children: /* @__PURE__ */ jsx(
14992
+ SessionsModalTemplate,
14692
14993
  {
14693
14994
  theme,
14694
14995
  accentColor,
14695
14996
  styleOverrides,
14696
- pending,
14697
- current,
14698
- verification: current ? quorumFailure ? { ok: false, reason: quorumFailure } : verification : null,
14699
- busy,
14700
- error,
14701
- approveBlocked: !!current && approveFailedFor === current.id,
14702
- deviceNotLinked,
14703
- onLinkDevice: () => {
14704
- onClose();
14705
- openRecoveryModal();
14706
- },
14707
- ...lastResolved ? { lastResolved } : {},
14708
- closesIn,
14709
- nextStep: awaitingNext ? nextStep : null,
14710
- language,
14711
- network,
14712
- history,
14713
- explorerUrlOf: (r) => r.submit?.hash ? explorerTxUrl(r.network, r.submit.hash, network) : null,
14714
- onSelect: (r) => setSelectedId(r.id),
14715
- onApprove: (r) => void run("approving", r, approve),
14716
- onReject: (r) => void run("rejecting", r, reject),
14717
- onClose: requestClose,
14718
- confirmingClose,
14719
- onKeepOpen: () => setAskedToClose(false),
14720
- onCloseAnyway: onClose
14997
+ state: sessions,
14998
+ revokingFamilyId,
14999
+ signingOutEverywhere,
15000
+ revokeError,
15001
+ onRefresh: () => load(),
15002
+ onRevoke: (familyId) => void handleRevoke(familyId),
15003
+ onLogoutEverywhere: () => void handleLogoutEverywhere(),
15004
+ onClose,
15005
+ language
14721
15006
  }
14722
15007
  ) });
14723
15008
  }
@@ -15378,6 +15663,7 @@ function RecoveryModalTemplate(p) {
15378
15663
  );
15379
15664
  }
15380
15665
  var APPROVAL_POLL_MS = 3e3;
15666
+ var RELOAD_AFTER_FAILURE_MS = 5e3;
15381
15667
  var APPROVAL_WINDOW_MS = 15 * 6e4;
15382
15668
  function errorText3(err, language) {
15383
15669
  return cosignRefusalMessage(err, language) ?? transactionErrorMessage(isPollarApiError(err) ? err.code : null, err instanceof Error ? err.message : null, language);
@@ -15429,12 +15715,17 @@ function RecoveryModal({ onClose }) {
15429
15715
  setError(null);
15430
15716
  setNotice(null);
15431
15717
  try {
15432
- await action();
15433
- await load();
15718
+ try {
15719
+ await action();
15720
+ } catch (err) {
15721
+ setError(errorText3(err, language));
15722
+ return;
15723
+ }
15724
+ await load().catch(() => {
15725
+ setTimeout(() => void load().catch(() => void 0), RELOAD_AFTER_FAILURE_MS);
15726
+ });
15434
15727
  if (after?.notice) setNotice(after.notice);
15435
15728
  if (after?.view) setView(after.view);
15436
- } catch (err) {
15437
- setError(errorText3(err, language));
15438
15729
  } finally {
15439
15730
  setBusy(null);
15440
15731
  }
@@ -15458,10 +15749,10 @@ function RecoveryModal({ onClose }) {
15458
15749
  setNotice(copy.deviceAdded);
15459
15750
  return;
15460
15751
  }
15461
- const timer = setInterval(() => void load().catch(() => void 0), APPROVAL_POLL_MS);
15752
+ const stopPoll = startBackoffPoll(load, APPROVAL_POLL_MS);
15462
15753
  const stop = setTimeout(() => setAwaitingApproval(false), APPROVAL_WINDOW_MS);
15463
15754
  return () => {
15464
- clearInterval(timer);
15755
+ stopPoll();
15465
15756
  clearTimeout(stop);
15466
15757
  };
15467
15758
  }, [awaitingApproval, enrolled, load, copy]);
@@ -16670,12 +16961,17 @@ function PollarProvider({
16670
16961
  const [sessionsModalOpen, setSessionsModalOpen] = useState(false);
16671
16962
  const [cosignModalOpen, setCosignModalOpen] = useState(false);
16672
16963
  const [cosignNextStep, setCosignNextStep] = useState(null);
16964
+ const [cosignHosts, setCosignHosts] = useState(0);
16965
+ const registerCosignHost = useCallback(() => {
16966
+ setCosignHosts((n) => n + 1);
16967
+ return () => setCosignHosts((n) => n - 1);
16968
+ }, []);
16673
16969
  const [recoveryModalOpen, setRecoveryModalOpen] = useState(false);
16674
16970
  const cosignPendingCount = useRef(0);
16675
16971
  useEffect(() => {
16676
- if (cosign.pending.length > cosignPendingCount.current) setCosignModalOpen(true);
16972
+ if (cosign.pending.length > cosignPendingCount.current && cosignHosts === 0) setCosignModalOpen(true);
16677
16973
  cosignPendingCount.current = cosign.pending.length;
16678
- }, [cosign.pending.length]);
16974
+ }, [cosign.pending.length, cosignHosts]);
16679
16975
  useEffect(() => pollarClient.onCosignDeviceNotEnrolled(() => setRecoveryModalOpen(true)), [pollarClient]);
16680
16976
  useEffect(() => pollarClient.onWalletRecoveryRequired(() => setRecoveryModalOpen(true)), [pollarClient]);
16681
16977
  const [distributionRulesModalOpen, setDistributionRulesModalOpen] = useState(false);
@@ -16714,13 +17010,17 @@ function PollarProvider({
16714
17010
  return;
16715
17011
  }
16716
17012
  let cancelled = false;
17013
+ let retry = null;
16717
17014
  pollarClient.cosign.recovery.status().then((next) => {
16718
17015
  if (!cancelled) setRecovery(next);
16719
- }).catch(() => {
16720
- if (!cancelled) setRecovery(null);
17016
+ }).catch((err) => {
17017
+ if (cancelled) return;
17018
+ if (isTransientFailure(err)) retry = setTimeout(() => setRecoveryTick((t) => t + 1), 5e3 + Math.random() * 5e3);
17019
+ else setRecovery(null);
16721
17020
  });
16722
17021
  return () => {
16723
17022
  cancelled = true;
17023
+ if (retry) clearTimeout(retry);
16724
17024
  };
16725
17025
  }, [pollarClient, hasSession, walletAddress, recoveryTick]);
16726
17026
  const recoveryLocked = !!recovery && recovery.required && !recovery.configured;
@@ -16735,13 +17035,18 @@ function PollarProvider({
16735
17035
  return;
16736
17036
  }
16737
17037
  let cancelled = false;
17038
+ let retry = null;
16738
17039
  pollarClient.cosign.custodyMigration().then((next) => {
16739
17040
  if (!cancelled) setCustodyMigration(next);
16740
- }).catch(() => {
16741
- if (!cancelled) setCustodyMigration(null);
17041
+ }).catch((err) => {
17042
+ if (cancelled) return;
17043
+ if (isTransientFailure(err))
17044
+ retry = setTimeout(() => setCustodyMigrationTick((t) => t + 1), 5e3 + Math.random() * 5e3);
17045
+ else setCustodyMigration(null);
16742
17046
  });
16743
17047
  return () => {
16744
17048
  cancelled = true;
17049
+ if (retry) clearTimeout(retry);
16745
17050
  };
16746
17051
  }, [pollarClient, hasSession, walletAddress, custodyMigrationTick]);
16747
17052
  const refreshWalletBalance = useCallback(() => pollarClient.refreshBalance(), [pollarClient, walletAddress]);
@@ -16864,6 +17169,7 @@ function PollarProvider({
16864
17169
  refreshCustodyMigration,
16865
17170
  confirmations,
16866
17171
  registerConfirmationHost,
17172
+ registerCosignHost,
16867
17173
  // distribution
16868
17174
  openDistributionRulesModal: () => setDistributionRulesModalOpen(true),
16869
17175
  // network
@@ -16904,6 +17210,7 @@ function PollarProvider({
16904
17210
  cosign,
16905
17211
  confirmations,
16906
17212
  registerConfirmationHost,
17213
+ registerCosignHost,
16907
17214
  walletBalance,
16908
17215
  refreshWalletBalance,
16909
17216
  enabledAssets,
@@ -16953,7 +17260,7 @@ function PollarProvider({
16953
17260
  /* @__PURE__ */ jsx(ModalErrorBoundary, { onClose: () => setCardModalOpen(false), children: /* @__PURE__ */ jsx(CardModal, { onClose: () => setCardModalOpen(false), initial: cardModalOptions }) }, `${cardModalKey}:${walletAddress}`),
16954
17261
  receiveModalOpen && /* @__PURE__ */ jsx(ModalErrorBoundary, { onClose: () => setReceiveModalOpen(false), children: /* @__PURE__ */ jsx(ReceiveModal, { onClose: () => setReceiveModalOpen(false), initial: receiveSeed.options }) }, `receive:${receiveSeed.key}`),
16955
17262
  sessionsModalOpen && /* @__PURE__ */ jsx(ModalErrorBoundary, { onClose: () => setSessionsModalOpen(false), children: /* @__PURE__ */ jsx(SessionsModal, { onClose: () => setSessionsModalOpen(false) }) }),
16956
- cosignModalOpen && /* @__PURE__ */ jsx(ModalErrorBoundary, { onClose: () => setCosignModalOpen(false), children: /* @__PURE__ */ jsx(CosignModal, { nextStep: cosignNextStep, onClose: () => setCosignModalOpen(false) }) }),
17263
+ cosignModalOpen && cosignHosts === 0 && /* @__PURE__ */ jsx(ModalErrorBoundary, { onClose: () => setCosignModalOpen(false), children: /* @__PURE__ */ jsx(CosignModal, { nextStep: cosignNextStep, onClose: () => setCosignModalOpen(false) }) }),
16957
17264
  custodyMigration?.required && !custodyMigrationLater && /* @__PURE__ */ jsx(ModalErrorBoundary, { onClose: refreshCustodyMigration, children: /* @__PURE__ */ jsx(
16958
17265
  CustodyMigrationModal,
16959
17266
  {