@pollar/react 0.12.1-rc.6 → 0.12.1-rc.8

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,7 +1,8 @@
1
1
  'use client';
2
- import { AUTH_ERROR_CODES, rampLegTitle, rampRequirementCopy, rampTrustlineAsset, rampWalletStep, rampResolutionText, describeRampAction, rampLegStatus, rampNextApproval, rampOrderStopped, rampOrderReceive, rampRailLabel, rampNoRouteText, rampFieldError, rampFieldValid, rampLegNote, rampStepTitle, rampStepStatusText, rampLegTimeLeft, rampOrderResolutionText, rampCountries, rampQuoteFields, isPollarApiError, transactionErrorMessage, WalletType, isPollarClient, PollarClient, isInteractiveAuthAdapter, isAuthEntryAdapterStep, completeAuthEntryStep, rampTrustlineErrorText, isPollarNetworkError, toBaseUnits, resolveLanguage, languageFromTag, localizedText, appUnavailableMessage, cosignRefusalMessage, fromBaseUnits, assertRampStellarSigner } from '@pollar/core';
3
- import { createContext, forwardRef, useState, useCallback, useEffect, useMemo, useRef, useContext, Component } from 'react';
2
+ import { AUTH_ERROR_CODES, rampLegTitle, rampRequirementCopy, rampTrustlineAsset, rampWalletStep, rampResolutionText, describeRampAction, rampLegStatus, rampNextApproval, rampOrderStopped, rampOrderReceive, countryName, rampRailLabel, rampNoRouteText, rampFieldError, rampFieldValid, rampLegNote, rampStepTitle, rampStepStatusText, rampLegTimeLeft, rampOrderResolutionText, rampCountries, rampQuoteFields, isPollarApiError, transactionErrorMessage, WalletType, bridgeSourceChains, bridgeTargetChains, isBridgeSettled, isPollarClient, PollarClient, isInteractiveAuthAdapter, isAuthEntryAdapterStep, completeAuthEntryStep, rampTrustlineErrorText, isPollarNetworkError, toBaseUnits, resolveLanguage, languageFromTag, localizedText, appUnavailableMessage, cosignRefusalMessage, fromBaseUnits, assertRampStellarSigner } from '@pollar/core';
3
+ import { createContext, forwardRef, useState, useCallback, useEffect, useMemo, useRef, useContext, useSyncExternalStore, Component } from 'react';
4
4
  import { jsxs, jsx, Fragment } from 'react/jsx-runtime';
5
+ import { createPortal } from 'react-dom';
5
6
  import { startAuthentication, startRegistration } from '@simplewebauthn/browser';
6
7
 
7
8
  var __create = Object.create;
@@ -1203,9 +1204,18 @@ var COMMONS_COPY = {
1203
1204
 
1204
1205
  // src/language-context.ts
1205
1206
  var ModalLanguageContext = createContext(null);
1206
- function useProviderLanguage(client, dashboard) {
1207
- const locale = typeof client.getLocale === "function" ? client.getLocale() : void 0;
1208
- return useMemo(() => resolveLanguage({ dashboard, code: [locale], device: deviceLanguageTag() }), [dashboard, locale]);
1207
+ function useProviderLanguage(client, dashboard, language) {
1208
+ const subscribe = useCallback(
1209
+ (onChange) => typeof client.onLocaleChange === "function" ? client.onLocaleChange(onChange) : () => {
1210
+ },
1211
+ [client]
1212
+ );
1213
+ const getLocale = () => typeof client.getLocale === "function" ? client.getLocale() : void 0;
1214
+ const locale = useSyncExternalStore(subscribe, getLocale, getLocale);
1215
+ return useMemo(
1216
+ () => resolveLanguage({ dashboard, code: [language, locale], device: deviceLanguageTag() }),
1217
+ [dashboard, language, locale]
1218
+ );
1209
1219
  }
1210
1220
  function useInheritedLanguage(language) {
1211
1221
  const inherited = useContext(ModalLanguageContext);
@@ -1270,7 +1280,7 @@ var PollarModalFooter = ({ language: languageProp }) => {
1270
1280
  /* @__PURE__ */ jsx("img", { src: LOGO_POLLAR_WORDMARK_ON_DARK, alt: "Pollar", className: "pollar-footer-logo pollar-logo-on-dark" }),
1271
1281
  /* @__PURE__ */ jsxs("span", { className: "pollar-footer-version", children: [
1272
1282
  "v",
1273
- "0.12.1-rc.6"
1283
+ "0.12.1-rc.8"
1274
1284
  ] })
1275
1285
  ] });
1276
1286
  };
@@ -1434,13 +1444,12 @@ function Toggle({ checked, onChange, disabled = false, busy = false, label }) {
1434
1444
  );
1435
1445
  }
1436
1446
  function useModalLanguage(language) {
1437
- const { getClient, styles } = usePollar();
1438
- const client = getClient();
1439
- const locale = typeof client.getLocale === "function" ? client.getLocale() : void 0;
1447
+ const { styles } = usePollar();
1448
+ const provider = useContext(ModalLanguageContext);
1440
1449
  const dashboard = styles?.language;
1441
1450
  return useMemo(
1442
- () => resolveLanguage({ dashboard, code: [language, locale], device: deviceLanguageTag() }),
1443
- [dashboard, language, locale]
1451
+ () => resolveLanguage({ dashboard, code: [language, provider], device: deviceLanguageTag() }),
1452
+ [dashboard, language, provider]
1444
1453
  );
1445
1454
  }
1446
1455
 
@@ -1788,6 +1797,20 @@ function DistributionRulesModalTemplate({
1788
1797
  }
1789
1798
  );
1790
1799
  }
1800
+ var noSubscription = () => () => {
1801
+ };
1802
+ function PollarOverlay({ style, onClick, children }) {
1803
+ const canPortal = useSyncExternalStore(
1804
+ noSubscription,
1805
+ () => true,
1806
+ () => false
1807
+ );
1808
+ if (!canPortal) return null;
1809
+ return createPortal(
1810
+ /* @__PURE__ */ jsx("div", { className: "pollar-overlay", "data-react-aria-top-layer": "true", style, onClick, children }),
1811
+ document.body
1812
+ );
1813
+ }
1791
1814
  function DistributionRulesModal({ onClose }) {
1792
1815
  const { getClient, styles } = usePollar();
1793
1816
  const { theme, accentColor, styleOverrides, overlayStyle } = modalChrome(styles);
@@ -1835,7 +1858,7 @@ function DistributionRulesModal({ onClose }) {
1835
1858
  },
1836
1859
  [getClient, copy]
1837
1860
  );
1838
- return /* @__PURE__ */ jsx("div", { className: "pollar-overlay", style: overlayStyle, onClick: onClose, children: /* @__PURE__ */ jsx(
1861
+ return /* @__PURE__ */ jsx(PollarOverlay, { style: overlayStyle, onClick: onClose, children: /* @__PURE__ */ jsx(
1839
1862
  DistributionRulesModalTemplate,
1840
1863
  {
1841
1864
  theme,
@@ -2333,7 +2356,7 @@ function EnabledAssetsModal({ onClose }) {
2333
2356
  },
2334
2357
  [runAction]
2335
2358
  );
2336
- return /* @__PURE__ */ jsx("div", { className: "pollar-overlay", style: overlayStyle, onClick: onClose, children: view === "list" ? /* @__PURE__ */ jsx(
2359
+ return /* @__PURE__ */ jsx(PollarOverlay, { style: overlayStyle, onClick: onClose, children: view === "list" ? /* @__PURE__ */ jsx(
2337
2360
  EnabledAssetsModalTemplate,
2338
2361
  {
2339
2362
  theme,
@@ -2922,7 +2945,7 @@ function KycModal({
2922
2945
  if (selectedProvider) void handleSelectProvider(selectedProvider);
2923
2946
  else setStep("select_provider");
2924
2947
  }
2925
- return /* @__PURE__ */ jsx("div", { className: "pollar-overlay", style: overlayStyle, onClick: onClose, children: /* @__PURE__ */ jsx(
2948
+ return /* @__PURE__ */ jsx(PollarOverlay, { style: overlayStyle, onClick: onClose, children: /* @__PURE__ */ jsx(
2926
2949
  KycModalTemplate,
2927
2950
  {
2928
2951
  theme,
@@ -3081,7 +3104,7 @@ function RequirementFormModal({
3081
3104
  if (mounted.current) setSubmitting(false);
3082
3105
  }
3083
3106
  }
3084
- return /* @__PURE__ */ jsx("div", { className: "pollar-overlay", style: overlayStyle, onClick: onClose, children: /* @__PURE__ */ jsxs(
3107
+ return /* @__PURE__ */ jsx(PollarOverlay, { style: overlayStyle, onClick: onClose, children: /* @__PURE__ */ jsxs(
3085
3108
  "div",
3086
3109
  {
3087
3110
  className: "pollar-modal-card pollar-form-modal",
@@ -3310,6 +3333,7 @@ var LOGIN_COPY = {
3310
3333
  genericError: "Something went wrong. Please try again.",
3311
3334
  codeLabel: "Enter the 6-digit code sent to",
3312
3335
  yourEmail: "your email",
3336
+ codeDigit: (position, total) => `Digit ${position} of ${total}`,
3313
3337
  codePlaceholder: "Enter verification code",
3314
3338
  verifyCode: "Verify Code",
3315
3339
  status: {
@@ -3347,6 +3371,7 @@ var LOGIN_COPY = {
3347
3371
  genericError: "Algo sali\xF3 mal. Intenta de nuevo.",
3348
3372
  codeLabel: "Ingresa el c\xF3digo de 6 d\xEDgitos que enviamos a",
3349
3373
  yourEmail: "tu correo",
3374
+ codeDigit: (position, total) => `D\xEDgito ${position} de ${total}`,
3350
3375
  codePlaceholder: "Ingresa el c\xF3digo de verificaci\xF3n",
3351
3376
  verifyCode: "Verificar c\xF3digo",
3352
3377
  status: {
@@ -3384,6 +3409,7 @@ var LOGIN_COPY = {
3384
3409
  genericError: "Algo deu errado. Tente novamente.",
3385
3410
  codeLabel: "Digite o c\xF3digo de 6 d\xEDgitos enviado para",
3386
3411
  yourEmail: "seu e-mail",
3412
+ codeDigit: (position, total) => `D\xEDgito ${position} de ${total}`,
3387
3413
  codePlaceholder: "Digite o c\xF3digo de verifica\xE7\xE3o",
3388
3414
  verifyCode: "Verificar c\xF3digo",
3389
3415
  status: {
@@ -3439,7 +3465,7 @@ function EmailCodeInput({ email, onSubmit, language }) {
3439
3465
  type: "text",
3440
3466
  inputMode: "numeric",
3441
3467
  autoComplete: i === 0 ? "one-time-code" : "off",
3442
- "aria-label": `Digit ${i + 1} of ${EMAIL_CODE_LENGTH}`,
3468
+ "aria-label": copy.codeDigit(i + 1, EMAIL_CODE_LENGTH),
3443
3469
  value: digit,
3444
3470
  className: "pollar-code-input",
3445
3471
  onChange: (e) => apply(applyEmailCodeInput(digits, i, e.target.value, e.target.selectionStart)),
@@ -4051,7 +4077,7 @@ function LoginModal({ onClose }) {
4051
4077
  getClient().login({ provider });
4052
4078
  }
4053
4079
  }
4054
- return /* @__PURE__ */ jsx("div", { className: "pollar-overlay", style: overlayStyle, onClick: handleClose, children: configStatus !== "ready" ? /* @__PURE__ */ jsx(
4080
+ return /* @__PURE__ */ jsx(PollarOverlay, { style: overlayStyle, onClick: handleClose, children: configStatus !== "ready" ? /* @__PURE__ */ jsx(
4055
4081
  LoginModalStatus,
4056
4082
  {
4057
4083
  status: configStatus === "error" ? "error" : "loading",
@@ -4953,11 +4979,11 @@ function RampWidgetTemplate({
4953
4979
  className: "pollar-ramp-input",
4954
4980
  value: country,
4955
4981
  onChange: (e) => onCountryChange(e.target.value),
4956
- children: countries.map((c) => /* @__PURE__ */ jsxs("option", { value: c.country, children: [
4957
- flagEmoji(c.country),
4982
+ children: countries.map((c) => ({ code: c.country, name: countryName(c.country, language) })).sort((a, b) => a.name.localeCompare(b.name, language)).map((c) => /* @__PURE__ */ jsxs("option", { value: c.code, children: [
4983
+ flagEmoji(c.code),
4958
4984
  " ",
4959
- c.country
4960
- ] }, c.country))
4985
+ c.name
4986
+ ] }, c.code))
4961
4987
  }
4962
4988
  )
4963
4989
  ] }),
@@ -5604,7 +5630,7 @@ function RegistryCheckModal({
5604
5630
  /* @__PURE__ */ jsx("span", { className: "pollar-form-label", children: label }),
5605
5631
  /* @__PURE__ */ jsx("input", { className: "pollar-input", value, readOnly: true, disabled: true })
5606
5632
  ] });
5607
- return /* @__PURE__ */ jsx("div", { className: "pollar-overlay", style: overlayStyle, onClick: onClose, children: /* @__PURE__ */ jsxs(
5633
+ return /* @__PURE__ */ jsx(PollarOverlay, { style: overlayStyle, onClick: onClose, children: /* @__PURE__ */ jsxs(
5608
5634
  "div",
5609
5635
  {
5610
5636
  className: "pollar-modal-card pollar-form-modal",
@@ -5784,7 +5810,7 @@ function ProviderRegistrationModal({
5784
5810
  }
5785
5811
  );
5786
5812
  }
5787
- return /* @__PURE__ */ jsx("div", { className: "pollar-overlay", style: overlayStyle, onClick: onClose, children: /* @__PURE__ */ jsxs(
5813
+ return /* @__PURE__ */ jsx(PollarOverlay, { style: overlayStyle, onClick: onClose, children: /* @__PURE__ */ jsxs(
5788
5814
  "div",
5789
5815
  {
5790
5816
  className: "pollar-modal-card pollar-form-modal",
@@ -5861,6 +5887,24 @@ function routeKey(quote) {
5861
5887
  return quote.legs.map((leg) => `${leg.kind}:${node(leg.from)}>${node(leg.to)}`).join("|");
5862
5888
  }
5863
5889
  var DECIMAL = /^\d+(\.\d+)?$/;
5890
+ function seededSelection(routes, seed) {
5891
+ const countries = rampCountries(routes);
5892
+ const wanted = seed.country?.trim().toUpperCase();
5893
+ const country = wanted ? countries.find((c) => c.country === wanted) : countries[0];
5894
+ if (!country) return null;
5895
+ const fiat = country.fiats.find((f) => f.currency === seed.fiat?.trim().toUpperCase()) ?? null;
5896
+ const resolvedFiat = fiat ?? country.fiats[0];
5897
+ const asset = routes.find(
5898
+ (r) => r.fiat.country === country.country && resolvedFiat !== void 0 && fiatKey(r.fiat) === fiatKey(resolvedFiat) && r.asset.code.toUpperCase() === seed.asset?.trim().toUpperCase()
5899
+ )?.asset;
5900
+ const amount = seed.amount?.trim() ?? "";
5901
+ return {
5902
+ country: country.country,
5903
+ fiatChoice: fiat ? fiatKey(fiat) : "",
5904
+ assetChoice: asset ? assetKey3(asset) : "",
5905
+ amount: DECIMAL.test(amount) ? amount : ""
5906
+ };
5907
+ }
5864
5908
  async function signLegWithWallet(client, orderId, actionId, copy) {
5865
5909
  const lent = [];
5866
5910
  const lend = (chain, encoding, handler) => {
@@ -5895,7 +5939,7 @@ async function signLegWithWallet(client, orderId, actionId, copy) {
5895
5939
  for (const release of lent) release();
5896
5940
  }
5897
5941
  }
5898
- function RampWidget({ onClose, language: languageProp }) {
5942
+ function RampWidget({ onClose, language: languageProp, initial }) {
5899
5943
  const {
5900
5944
  getClient,
5901
5945
  styles,
@@ -5914,7 +5958,10 @@ function RampWidget({ onClose, language: languageProp }) {
5914
5958
  const copy = RAMP_COPY[language];
5915
5959
  const { theme, accentColor, styleOverrides, overlayStyle } = modalChrome(styles);
5916
5960
  const [step, setStep] = useState("input");
5917
- const [direction, setDirection] = useState("ONRAMP");
5961
+ const [direction, setDirection] = useState(initial?.direction === "sell" ? "OFFRAMP" : "ONRAMP");
5962
+ const seedRef = useRef(
5963
+ initial ? { direction: initial.direction === "sell" ? "OFFRAMP" : "ONRAMP", options: initial } : null
5964
+ );
5918
5965
  const [routes, setRoutes] = useState([]);
5919
5966
  const [routesLoading, setRoutesLoading] = useState(true);
5920
5967
  const [country, setCountry] = useState("");
@@ -5968,6 +6015,16 @@ function RampWidget({ onClose, language: languageProp }) {
5968
6015
  try {
5969
6016
  const { routes: found } = await client.getRampRoutes(next);
5970
6017
  setRoutes(found);
6018
+ const seed = seedRef.current?.direction === next ? seedRef.current.options : null;
6019
+ if (seed) seedRef.current = null;
6020
+ const seeded = seed ? seededSelection(found, seed) : null;
6021
+ if (seeded) {
6022
+ setCountry(seeded.country);
6023
+ setFiatChoice(seeded.fiatChoice);
6024
+ setAssetChoice(seeded.assetChoice);
6025
+ setAmount(seeded.amount);
6026
+ return;
6027
+ }
5971
6028
  const first = rampCountries(found)[0]?.country ?? "";
5972
6029
  setCountry((current) => found.some((r) => r.fiat.country === current) ? current : first);
5973
6030
  } catch (error) {
@@ -6052,6 +6109,7 @@ function RampWidget({ onClose, language: languageProp }) {
6052
6109
  void resumeRoute(awaitingAccount.routeKey);
6053
6110
  }, [awaitingAccount, resolvedRequest]);
6054
6111
  function handleDirectionChange(next) {
6112
+ seedRef.current = null;
6055
6113
  setDirection(next);
6056
6114
  setErrorMsg(null);
6057
6115
  setAwaitingAccount(null);
@@ -6231,6 +6289,7 @@ function RampWidget({ onClose, language: languageProp }) {
6231
6289
  setErrorMsg(null);
6232
6290
  try {
6233
6291
  const found = await client.getRampOrder(id);
6292
+ seedRef.current = null;
6234
6293
  setDirection(found.direction);
6235
6294
  setOrder(found);
6236
6295
  setStep("status");
@@ -6373,7 +6432,7 @@ function RampWidget({ onClose, language: languageProp }) {
6373
6432
  }
6374
6433
  );
6375
6434
  }
6376
- return /* @__PURE__ */ jsx("div", { className: "pollar-overlay", style: overlayStyle, onClick: onClose, children: /* @__PURE__ */ jsx(
6435
+ return /* @__PURE__ */ jsx(PollarOverlay, { style: overlayStyle, onClick: onClose, children: /* @__PURE__ */ jsx(
6377
6436
  RampWidgetTemplate,
6378
6437
  {
6379
6438
  language,
@@ -6483,6 +6542,37 @@ function walletNotReadyReason(wallet, chain, language = "en") {
6483
6542
  }
6484
6543
  return null;
6485
6544
  }
6545
+ function seededAmount(amount) {
6546
+ const value = amount?.trim() ?? "";
6547
+ return /^\d+(\.\d+)?$/.test(value) ? value : "";
6548
+ }
6549
+ function byCode(options, code) {
6550
+ const wanted = code?.trim().toUpperCase();
6551
+ return wanted ? options.find((o) => o.code.toUpperCase() === wanted) : void 0;
6552
+ }
6553
+ function oneOf(allowed, value) {
6554
+ return value !== void 0 && allowed.includes(value) ? value : void 0;
6555
+ }
6556
+ function useSuccessReport(transaction, active, onSuccess) {
6557
+ const reported = useRef(null);
6558
+ const hash = active && transaction.step === "success" ? transaction.hash : null;
6559
+ useEffect(() => {
6560
+ if (!hash || reported.current === hash) return;
6561
+ reported.current = hash;
6562
+ onSuccess?.({ hash });
6563
+ }, [hash, onSuccess]);
6564
+ }
6565
+ function useModalOptions() {
6566
+ const [state, setState] = useState({ options: void 0, key: 0 });
6567
+ const seeded = useRef(false);
6568
+ const open = useCallback((options) => {
6569
+ const given = options !== void 0 && Object.keys(options).length > 0;
6570
+ const remount = given || seeded.current;
6571
+ seeded.current = given;
6572
+ setState((current) => ({ options: given ? options : void 0, key: remount ? current.key + 1 : current.key }));
6573
+ }, []);
6574
+ return [state, open];
6575
+ }
6486
6576
 
6487
6577
  // src/lib/qr-code/index.tsx
6488
6578
  var import_ErrorCorrectLevel = __toESM(require_ErrorCorrectLevel());
@@ -6709,7 +6799,7 @@ function ReceiveModalTemplate({
6709
6799
  }
6710
6800
  );
6711
6801
  }
6712
- function ReceiveModal({ onClose }) {
6802
+ function ReceiveModal({ onClose, initial }) {
6713
6803
  const { wallet, wallets, styles, recoveryLocked, openRecoveryModal } = usePollar();
6714
6804
  const { theme, accentColor, styleOverrides, overlayStyle } = modalChrome(styles);
6715
6805
  const language = useModalLanguage();
@@ -6718,8 +6808,8 @@ function ReceiveModal({ onClose }) {
6718
6808
  const { chains } = useChains();
6719
6809
  const [selectedChain, setSelectedChain] = useState(null);
6720
6810
  useEffect(() => {
6721
- if (selectedChain === null && chains.length > 0) setSelectedChain(chains[0]);
6722
- }, [chains, selectedChain]);
6811
+ if (selectedChain === null && chains.length > 0) setSelectedChain(oneOf(chains, initial?.chain) ?? chains[0]);
6812
+ }, [chains, selectedChain, initial?.chain]);
6723
6813
  const walletAddress = addressForChain(wallets, selectedChain);
6724
6814
  const notReadyReason = walletNotReadyReason(wallet, selectedChain, language);
6725
6815
  useEffect(
@@ -6739,7 +6829,7 @@ function ReceiveModal({ onClose }) {
6739
6829
  }, 2e3);
6740
6830
  });
6741
6831
  }
6742
- return /* @__PURE__ */ jsx("div", { className: "pollar-overlay", style: overlayStyle, onClick: onClose, children: /* @__PURE__ */ jsx(
6832
+ return /* @__PURE__ */ jsx(PollarOverlay, { style: overlayStyle, onClick: onClose, children: /* @__PURE__ */ jsx(
6743
6833
  ReceiveModalTemplate,
6744
6834
  {
6745
6835
  theme,
@@ -7966,7 +8056,7 @@ function assetParam(record) {
7966
8056
  }
7967
8057
  return { type: "credit_alphanum12", code: record.code, issuer: record.issuer };
7968
8058
  }
7969
- function SendModal({ onClose }) {
8059
+ function SendModal({ onClose, initial }) {
7970
8060
  const {
7971
8061
  walletBalance,
7972
8062
  refreshWalletBalance,
@@ -7986,10 +8076,13 @@ function SendModal({ onClose }) {
7986
8076
  const [step, setStep] = useState("form");
7987
8077
  const [createsAccount, setCreatesAccount] = useState(false);
7988
8078
  const [checkingDestination, setCheckingDestination] = useState(false);
7989
- const [amount, setAmount] = useState("");
7990
- const [destination, setDestination] = useState("");
7991
- const [memo, setMemo] = useState("");
7992
- const [memoType, setMemoType] = useState("text");
8079
+ const [amount, setAmount] = useState(() => seededAmount(initial?.amount));
8080
+ const [destination, setDestination] = useState(() => initial?.destination?.trim() ?? "");
8081
+ const [memo, setMemo] = useState(() => initial?.memo ?? "");
8082
+ const [memoType, setMemoType] = useState(
8083
+ () => oneOf(["text", "id", "hash"], initial?.memoType) ?? "text"
8084
+ );
8085
+ const assetSeed = useRef(initial?.asset);
7993
8086
  const [selectedAsset, setSelectedAsset] = useState(null);
7994
8087
  const [showXdr, setShowXdr] = useState(false);
7995
8088
  const [copied, setCopied] = useState(false);
@@ -7998,8 +8091,8 @@ function SendModal({ onClose }) {
7998
8091
  const { chains } = useChains();
7999
8092
  const [selectedChain, setSelectedChain] = useState(null);
8000
8093
  useEffect(() => {
8001
- if (selectedChain === null && chains.length > 0) setSelectedChain(chains[0]);
8002
- }, [chains, selectedChain]);
8094
+ if (selectedChain === null && chains.length > 0) setSelectedChain(oneOf(chains, initial?.chain) ?? chains[0]);
8095
+ }, [chains, selectedChain, initial?.chain]);
8003
8096
  const canSendOnChain = selectedChain === "STELLAR" || selectedChain === "SOLANA" || selectedChain === "POLYGON";
8004
8097
  const notReadyReason = walletNotReadyReason(wallet, selectedChain, language);
8005
8098
  const isBaseUnitChain = selectedChain === "SOLANA" || selectedChain === "POLYGON";
@@ -8026,9 +8119,13 @@ function SendModal({ onClose }) {
8026
8119
  setSelectedAsset(sortedAssets[0] ?? null);
8027
8120
  return;
8028
8121
  }
8029
- if (!selectedAsset && sortedAssets.length > 0) setSelectedAsset(sortedAssets[0]);
8122
+ if (!selectedAsset && sortedAssets.length > 0) {
8123
+ setSelectedAsset(byCode(sortedAssets, assetSeed.current) ?? sortedAssets[0]);
8124
+ assetSeed.current = void 0;
8125
+ }
8030
8126
  }, [sortedAssets, selectedAsset, selectedChain]);
8031
8127
  const hash = transaction.step === "success" ? transaction.hash : null;
8128
+ useSuccessReport(transaction, step === "tx", initial?.onSuccess);
8032
8129
  const buildData = "buildData" in transaction ? transaction.buildData : null;
8033
8130
  const explorerNetwork = buildData?.summary.network?.toLowerCase().includes("testnet") ? "testnet" : buildData ? "public" : network === "testnet" ? "testnet" : "public";
8034
8131
  const explorerUrl = !hash ? null : selectedChain === "SOLANA" ? `https://explorer.solana.com/tx/${hash}${explorerNetwork === "testnet" ? "?cluster=devnet" : ""}` : selectedChain === "POLYGON" ? `https://${explorerNetwork === "testnet" ? "amoy." : ""}polygonscan.com/tx/${hash}` : `https://stellar.expert/explorer/${explorerNetwork}/tx/${hash}`;
@@ -8193,7 +8290,7 @@ function SendModal({ onClose }) {
8193
8290
  setShowXdr(false);
8194
8291
  setCopied(false);
8195
8292
  }
8196
- return /* @__PURE__ */ jsx("div", { className: "pollar-overlay", style: overlayStyle, onClick: !isInProgress ? onClose : void 0, children: /* @__PURE__ */ jsx(
8293
+ return /* @__PURE__ */ jsx(PollarOverlay, { style: overlayStyle, onClick: !isInProgress ? onClose : void 0, children: /* @__PURE__ */ jsx(
8197
8294
  SendModalTemplate,
8198
8295
  {
8199
8296
  theme,
@@ -8848,7 +8945,7 @@ function fromBaseUnits3(units, decimals) {
8848
8945
  function catalogRef(code, issuer) {
8849
8946
  return code.length <= 4 ? { type: "credit_alphanum4", code, issuer } : { type: "credit_alphanum12", code, issuer };
8850
8947
  }
8851
- function SwapModal({ onClose }) {
8948
+ function SwapModal({ onClose, initial }) {
8852
8949
  const {
8853
8950
  getSwapConfig,
8854
8951
  getSwapTokens,
@@ -8869,13 +8966,15 @@ function SwapModal({ onClose }) {
8869
8966
  const language = useModalLanguage();
8870
8967
  const copy = SWAP_COPY[language];
8871
8968
  const walletType = wallet?.custody === "external" ? wallet.provider : null;
8872
- const [chain, setChain] = useState("STELLAR");
8969
+ const [chain, setChain] = useState(() => oneOf(["STELLAR", "SOLANA"], initial?.chain) ?? "STELLAR");
8970
+ const sellSeed = useRef(initial?.sell);
8971
+ const buySeed = useRef(initial?.buy);
8873
8972
  const smartUnsupported = chain === "STELLAR" && wallet?.custody === "smart";
8874
8973
  const { theme, accentColor, styleOverrides, overlayStyle } = modalChrome(styles);
8875
8974
  const [step, setStep] = useState("form");
8876
8975
  const [selectedSell, setSelectedSell] = useState(null);
8877
8976
  const [selectedBuy, setSelectedBuy] = useState(null);
8878
- const [amount, setAmount] = useState("");
8977
+ const [amount, setAmount] = useState(() => seededAmount(initial?.amount));
8879
8978
  const [provider, setProvider] = useState("auto");
8880
8979
  const [venues, setVenues] = useState(null);
8881
8980
  const [solanaVenues, setSolanaVenues] = useState(null);
@@ -8990,12 +9089,24 @@ function SwapModal({ onClose }) {
8990
9089
  );
8991
9090
  useEffect(() => {
8992
9091
  if (sellOptions.length === 0) return;
9092
+ const seeded = byCode(sellOptions, sellSeed.current);
9093
+ if (seeded) {
9094
+ sellSeed.current = void 0;
9095
+ setSelectedSell(seeded);
9096
+ return;
9097
+ }
8993
9098
  if (!selectedSell || !sellOptions.some((o) => optKey(o) === optKey(selectedSell))) {
8994
9099
  setSelectedSell(sellOptions[0]);
8995
9100
  }
8996
9101
  }, [sellOptions, selectedSell]);
8997
9102
  useEffect(() => {
8998
9103
  if (buyOptions.length === 0) return;
9104
+ const seeded = byCode(buyOptions, buySeed.current);
9105
+ if (seeded) {
9106
+ buySeed.current = void 0;
9107
+ setSelectedBuy(seeded);
9108
+ return;
9109
+ }
8999
9110
  if (!selectedBuy || !buyOptions.some((o) => optKey(o) === optKey(selectedBuy))) {
9000
9111
  setSelectedBuy(buyOptions[0]);
9001
9112
  }
@@ -9007,6 +9118,7 @@ function SwapModal({ onClose }) {
9007
9118
  if (i.length !== 56 || !i.startsWith("G")) return copy.issuerFormat;
9008
9119
  const opt = { ref: catalogRef(c, i), code: c, issuer: i, enabledInApp: false };
9009
9120
  setCustomTokens((prev) => prev.some((o) => optKey(o) === optKey(opt)) ? prev : [...prev, opt]);
9121
+ buySeed.current = void 0;
9010
9122
  setSelectedBuy(opt);
9011
9123
  return null;
9012
9124
  }
@@ -9039,6 +9151,8 @@ function SwapModal({ onClose }) {
9039
9151
  if (chains.length > 0 && !chains.includes(chain)) setChain(chains[0]);
9040
9152
  }, [chains, chain]);
9041
9153
  function handleChainChange(next) {
9154
+ sellSeed.current = void 0;
9155
+ buySeed.current = void 0;
9042
9156
  setChain(next);
9043
9157
  setSelectedSell(null);
9044
9158
  setSelectedBuy(null);
@@ -9111,6 +9225,7 @@ function SwapModal({ onClose }) {
9111
9225
  copy
9112
9226
  ]);
9113
9227
  const hash = transaction.step === "success" ? transaction.hash : null;
9228
+ useSuccessReport(transaction, step === "tx", initial?.onSuccess);
9114
9229
  const buildData = "buildData" in transaction ? transaction.buildData : null;
9115
9230
  const explorerNetwork = buildData?.summary.network?.toLowerCase().includes("testnet") ? "testnet" : buildData ? "public" : network === "testnet" ? "testnet" : "public";
9116
9231
  const explorerUrl = !hash ? null : chain === "SOLANA" ? `https://solscan.io/tx/${hash}${network === "testnet" ? "?cluster=devnet" : ""}` : `https://stellar.expert/explorer/${explorerNetwork}/tx/${hash}`;
@@ -9173,6 +9288,8 @@ function SwapModal({ onClose }) {
9173
9288
  }
9174
9289
  function handleReverse() {
9175
9290
  if (!selectedSell || !selectedBuy) return;
9291
+ sellSeed.current = void 0;
9292
+ buySeed.current = void 0;
9176
9293
  const previousSell = selectedSell;
9177
9294
  setSelectedSell(selectedBuy);
9178
9295
  setSelectedBuy(previousSell);
@@ -9193,7 +9310,7 @@ function SwapModal({ onClose }) {
9193
9310
  setShowXdr(false);
9194
9311
  setCopied(false);
9195
9312
  }
9196
- return /* @__PURE__ */ jsx("div", { className: "pollar-overlay", style: overlayStyle, onClick: !isInProgress ? onClose : void 0, children: /* @__PURE__ */ jsx(
9313
+ return /* @__PURE__ */ jsx(PollarOverlay, { style: overlayStyle, onClick: !isInProgress ? onClose : void 0, children: /* @__PURE__ */ jsx(
9197
9314
  SwapModalTemplate,
9198
9315
  {
9199
9316
  theme,
@@ -9230,8 +9347,14 @@ function SwapModal({ onClose }) {
9230
9347
  onClose,
9231
9348
  onBack: handleBack,
9232
9349
  onRefresh: handleRefresh,
9233
- onSelectSell: setSelectedSell,
9234
- onSelectBuy: setSelectedBuy,
9350
+ onSelectSell: (option) => {
9351
+ sellSeed.current = void 0;
9352
+ setSelectedSell(option);
9353
+ },
9354
+ onSelectBuy: (option) => {
9355
+ buySeed.current = void 0;
9356
+ setSelectedBuy(option);
9357
+ },
9235
9358
  onReverse: handleReverse,
9236
9359
  onMax: handleMax,
9237
9360
  onAddCustomToken: addCustomToken,
@@ -9247,6 +9370,621 @@ function SwapModal({ onClose }) {
9247
9370
  ) });
9248
9371
  }
9249
9372
 
9373
+ // src/components/bridge-modal/bridge-copy.ts
9374
+ var BRIDGE_COPY = {
9375
+ en: {
9376
+ title: "Move USDC between networks",
9377
+ close: "Close",
9378
+ back: "Back",
9379
+ loading: "Loading\u2026",
9380
+ mainnetOnly: "Moving USDC between networks works on mainnet only.",
9381
+ noDirections: "You need a wallet on at least two networks of this app to move USDC between them.",
9382
+ from: "From",
9383
+ to: "To",
9384
+ amount: "Amount (USDC)",
9385
+ balance: "Balance",
9386
+ max: "Max",
9387
+ youReceive: "You receive",
9388
+ fee: "Fee",
9389
+ noFee: "No fee",
9390
+ eta: "Estimated time",
9391
+ etaValue: "about {minutes} min",
9392
+ signingInternal: "Your wallet sends it right away.",
9393
+ signingCosigned: "You approve it on your device.",
9394
+ signingExternal: "You sign it in your wallet.",
9395
+ quoting: "Getting a quote\u2026",
9396
+ bridgeButton: "Move USDC",
9397
+ starting: "Starting\u2026",
9398
+ invalidAmount: "Enter an amount with up to 6 decimals.",
9399
+ overBalance: "The amount is more than your balance.",
9400
+ statusTitle: {
9401
+ PENDING: "Sending",
9402
+ AWAITING_ACTION: "Your approval is needed",
9403
+ BURNED: "On its way",
9404
+ ATTESTED: "Arriving",
9405
+ COMPLETED: "Done",
9406
+ FAILED: "It did not go through",
9407
+ HELD: "Under review"
9408
+ },
9409
+ statusBody: {
9410
+ PENDING: "Your USDC is leaving your {from} wallet.",
9411
+ AWAITING_ACTION: "Approve the step below to continue.",
9412
+ BURNED: "Circle is confirming the transfer. This takes a few minutes.",
9413
+ ATTESTED: "Your USDC is being delivered to your {to} wallet.",
9414
+ COMPLETED: "{amount} USDC arrived in your {to} wallet.",
9415
+ FAILED: "Nothing left your wallet. You can try again.",
9416
+ HELD: "Your USDC left your {from} wallet but did not arrive yet. Our team is on it; no action is needed from you."
9417
+ },
9418
+ steps: { burn: "Leaves {from}", attest: "Confirmed by Circle", mint: "Arrives on {to}" },
9419
+ authorize: "Authorize",
9420
+ waitingWallet: "Waiting for your wallet\u2026",
9421
+ approveOnDevice: "Approve on your device",
9422
+ viewBurn: "View on {chain}",
9423
+ viewMint: "View on {chain}",
9424
+ done: "Done",
9425
+ newBridge: "Move more",
9426
+ pollTrouble: "We could not refresh the status. Retrying\u2026",
9427
+ errors: {
9428
+ mainnetOnly: "Moving USDC between networks works on mainnet only.",
9429
+ chainNotEnabled: "This app does not use one of these networks.",
9430
+ noGasWallet: "This app cannot pay the network fees for this move right now.",
9431
+ noWallet: (chain) => `You do not have a wallet on ${chain} yet.`,
9432
+ noTrustline: "Your Stellar wallet needs to accept USDC first.",
9433
+ connectSolanaWallet: "Connect the Solana wallet this move leaves from to sign.",
9434
+ unsupportedWallet: "This wallet cannot move USDC between networks.",
9435
+ credits: "This app cannot cover this operation right now.",
9436
+ actionChanged: "The step changed. Review it and authorize again.",
9437
+ connectStellarWallet: "Connect your Stellar wallet to sign.",
9438
+ walletChanged: "The connected wallet changed. Try again.",
9439
+ signingCancelled: "The signature was cancelled.",
9440
+ generic: "Something went wrong. Try again."
9441
+ }
9442
+ },
9443
+ es: {
9444
+ title: "Mover USDC entre redes",
9445
+ close: "Cerrar",
9446
+ back: "Volver",
9447
+ loading: "Cargando\u2026",
9448
+ mainnetOnly: "Mover USDC entre redes solo funciona en mainnet.",
9449
+ noDirections: "Necesitas una wallet en al menos dos redes de esta app para mover USDC entre ellas.",
9450
+ from: "Desde",
9451
+ to: "Hacia",
9452
+ amount: "Monto (USDC)",
9453
+ balance: "Saldo",
9454
+ max: "M\xE1x",
9455
+ youReceive: "Recibes",
9456
+ fee: "Comisi\xF3n",
9457
+ noFee: "Sin comisi\xF3n",
9458
+ eta: "Tiempo estimado",
9459
+ etaValue: "unos {minutes} min",
9460
+ signingInternal: "Tu wallet lo env\xEDa de inmediato.",
9461
+ signingCosigned: "Lo apruebas en tu dispositivo.",
9462
+ signingExternal: "Lo firmas en tu wallet.",
9463
+ quoting: "Cotizando\u2026",
9464
+ bridgeButton: "Mover USDC",
9465
+ starting: "Iniciando\u2026",
9466
+ invalidAmount: "Ingresa un monto con hasta 6 decimales.",
9467
+ overBalance: "El monto es mayor que tu saldo.",
9468
+ statusTitle: {
9469
+ PENDING: "Enviando",
9470
+ AWAITING_ACTION: "Falta tu aprobaci\xF3n",
9471
+ BURNED: "En camino",
9472
+ ATTESTED: "Llegando",
9473
+ COMPLETED: "Listo",
9474
+ FAILED: "No se complet\xF3",
9475
+ HELD: "En revisi\xF3n"
9476
+ },
9477
+ statusBody: {
9478
+ PENDING: "Tu USDC est\xE1 saliendo de tu wallet de {from}.",
9479
+ AWAITING_ACTION: "Aprueba el paso de abajo para continuar.",
9480
+ BURNED: "Circle est\xE1 confirmando la transferencia. Tarda unos minutos.",
9481
+ ATTESTED: "Tu USDC se est\xE1 entregando en tu wallet de {to}.",
9482
+ COMPLETED: "Llegaron {amount} USDC a tu wallet de {to}.",
9483
+ FAILED: "No sali\xF3 nada de tu wallet. Puedes intentarlo de nuevo.",
9484
+ HELD: "Tu USDC sali\xF3 de tu wallet de {from} pero todav\xEDa no lleg\xF3. Nuestro equipo ya lo est\xE1 revisando; no tienes que hacer nada."
9485
+ },
9486
+ steps: { burn: "Sale de {from}", attest: "Confirmado por Circle", mint: "Llega a {to}" },
9487
+ authorize: "Autorizar",
9488
+ waitingWallet: "Esperando a tu wallet\u2026",
9489
+ approveOnDevice: "Aprobar en tu dispositivo",
9490
+ viewBurn: "Ver en {chain}",
9491
+ viewMint: "Ver en {chain}",
9492
+ done: "Listo",
9493
+ newBridge: "Mover m\xE1s",
9494
+ pollTrouble: "No pudimos actualizar el estado. Reintentando\u2026",
9495
+ errors: {
9496
+ mainnetOnly: "Mover USDC entre redes solo funciona en mainnet.",
9497
+ chainNotEnabled: "Esta app no usa una de estas redes.",
9498
+ noGasWallet: "Esta app no puede pagar ahora las comisiones de red de este movimiento.",
9499
+ noWallet: (chain) => `Todav\xEDa no tienes una wallet en ${chain}.`,
9500
+ noTrustline: "Tu wallet de Stellar primero tiene que aceptar USDC.",
9501
+ connectSolanaWallet: "Conecta la wallet de Solana desde la que sale este movimiento para firmar.",
9502
+ unsupportedWallet: "Esta wallet no puede mover USDC entre redes.",
9503
+ credits: "Esta app no puede cubrir esta operaci\xF3n ahora.",
9504
+ actionChanged: "El paso cambi\xF3. Rev\xEDsalo y autoriza de nuevo.",
9505
+ connectStellarWallet: "Conecta tu wallet de Stellar para firmar.",
9506
+ walletChanged: "Cambi\xF3 la wallet conectada. Int\xE9ntalo de nuevo.",
9507
+ signingCancelled: "Se cancel\xF3 la firma.",
9508
+ generic: "Algo sali\xF3 mal. Int\xE9ntalo de nuevo."
9509
+ }
9510
+ },
9511
+ pt: {
9512
+ title: "Mover USDC entre redes",
9513
+ close: "Fechar",
9514
+ back: "Voltar",
9515
+ loading: "Carregando\u2026",
9516
+ mainnetOnly: "Mover USDC entre redes funciona s\xF3 na mainnet.",
9517
+ noDirections: "Voc\xEA precisa de uma carteira em pelo menos duas redes deste app para mover USDC entre elas.",
9518
+ from: "De",
9519
+ to: "Para",
9520
+ amount: "Valor (USDC)",
9521
+ balance: "Saldo",
9522
+ max: "M\xE1x",
9523
+ youReceive: "Voc\xEA recebe",
9524
+ fee: "Taxa",
9525
+ noFee: "Sem taxa",
9526
+ eta: "Tempo estimado",
9527
+ etaValue: "cerca de {minutes} min",
9528
+ signingInternal: "Sua carteira envia na hora.",
9529
+ signingCosigned: "Voc\xEA aprova no seu dispositivo.",
9530
+ signingExternal: "Voc\xEA assina na sua carteira.",
9531
+ quoting: "Cotando\u2026",
9532
+ bridgeButton: "Mover USDC",
9533
+ starting: "Iniciando\u2026",
9534
+ invalidAmount: "Informe um valor com at\xE9 6 casas decimais.",
9535
+ overBalance: "O valor \xE9 maior que o seu saldo.",
9536
+ statusTitle: {
9537
+ PENDING: "Enviando",
9538
+ AWAITING_ACTION: "Falta a sua aprova\xE7\xE3o",
9539
+ BURNED: "A caminho",
9540
+ ATTESTED: "Chegando",
9541
+ COMPLETED: "Pronto",
9542
+ FAILED: "N\xE3o foi conclu\xEDdo",
9543
+ HELD: "Em an\xE1lise"
9544
+ },
9545
+ statusBody: {
9546
+ PENDING: "Seu USDC est\xE1 saindo da sua carteira na {from}.",
9547
+ AWAITING_ACTION: "Aprove o passo abaixo para continuar.",
9548
+ BURNED: "A Circle est\xE1 confirmando a transfer\xEAncia. Leva alguns minutos.",
9549
+ ATTESTED: "Seu USDC est\xE1 sendo entregue na sua carteira na {to}.",
9550
+ COMPLETED: "{amount} USDC chegaram na sua carteira na {to}.",
9551
+ FAILED: "Nada saiu da sua carteira. Voc\xEA pode tentar de novo.",
9552
+ HELD: "Seu USDC saiu da sua carteira na {from} mas ainda n\xE3o chegou. Nossa equipe j\xE1 est\xE1 cuidando disso; voc\xEA n\xE3o precisa fazer nada."
9553
+ },
9554
+ steps: { burn: "Sai da {from}", attest: "Confirmado pela Circle", mint: "Chega na {to}" },
9555
+ authorize: "Autorizar",
9556
+ waitingWallet: "Aguardando sua carteira\u2026",
9557
+ approveOnDevice: "Aprovar no dispositivo",
9558
+ viewBurn: "Ver na {chain}",
9559
+ viewMint: "Ver na {chain}",
9560
+ done: "Pronto",
9561
+ newBridge: "Mover mais",
9562
+ pollTrouble: "N\xE3o conseguimos atualizar o status. Tentando de novo\u2026",
9563
+ errors: {
9564
+ mainnetOnly: "Mover USDC entre redes funciona s\xF3 na mainnet.",
9565
+ chainNotEnabled: "Este app n\xE3o usa uma dessas redes.",
9566
+ noGasWallet: "Este app n\xE3o consegue pagar agora as taxas de rede deste movimento.",
9567
+ noWallet: (chain) => `Voc\xEA ainda n\xE3o tem uma carteira na ${chain}.`,
9568
+ noTrustline: "Sua carteira Stellar precisa aceitar USDC primeiro.",
9569
+ connectSolanaWallet: "Conecte a carteira Solana de onde sai este movimento para assinar.",
9570
+ unsupportedWallet: "Esta carteira n\xE3o pode mover USDC entre redes.",
9571
+ credits: "Este app n\xE3o consegue cobrir esta opera\xE7\xE3o agora.",
9572
+ actionChanged: "O passo mudou. Revise e autorize de novo.",
9573
+ connectStellarWallet: "Conecte sua carteira Stellar para assinar.",
9574
+ walletChanged: "A carteira conectada mudou. Tente de novo.",
9575
+ signingCancelled: "A assinatura foi cancelada.",
9576
+ generic: "Algo deu errado. Tente de novo."
9577
+ }
9578
+ }
9579
+ };
9580
+ var BRIDGE_CHAIN_LABEL = {
9581
+ STELLAR: "Stellar",
9582
+ SOLANA: "Solana",
9583
+ POLYGON: "Polygon"
9584
+ };
9585
+ var EXPLORER = {
9586
+ STELLAR: (hash) => `https://stellar.expert/explorer/public/tx/${hash}`,
9587
+ SOLANA: (hash) => `https://solscan.io/tx/${hash}`,
9588
+ POLYGON: (hash) => `https://polygonscan.com/tx/${hash}`
9589
+ };
9590
+ var fill = (text, values) => text.replace(/\{(\w+)\}/g, (_, key) => values[key] ?? `{${key}}`);
9591
+ function ChainPicker({
9592
+ label,
9593
+ value,
9594
+ options,
9595
+ onChange,
9596
+ disabled
9597
+ }) {
9598
+ return /* @__PURE__ */ jsxs("label", { className: "pollar-bridge-field", children: [
9599
+ /* @__PURE__ */ jsx("span", { className: "pollar-bridge-label", children: label }),
9600
+ /* @__PURE__ */ jsx(
9601
+ "select",
9602
+ {
9603
+ className: "pollar-input",
9604
+ value: value ?? "",
9605
+ disabled: disabled || options.length === 0,
9606
+ onChange: (event) => onChange(event.target.value),
9607
+ children: options.map((chain) => /* @__PURE__ */ jsx("option", { value: chain, children: BRIDGE_CHAIN_LABEL[chain] }, chain))
9608
+ }
9609
+ )
9610
+ ] });
9611
+ }
9612
+ function Progress({ transfer, labels }) {
9613
+ const reached = {
9614
+ burn: !!transfer.burnTxHash,
9615
+ attest: transfer.status === "ATTESTED" || transfer.status === "COMPLETED" || !!transfer.mintTxHash,
9616
+ mint: transfer.status === "COMPLETED"
9617
+ };
9618
+ return /* @__PURE__ */ jsx("ol", { className: "pollar-bridge-steps", children: ["burn", "attest", "mint"].map((key) => /* @__PURE__ */ jsxs("li", { className: reached[key] ? "pollar-bridge-step pollar-bridge-step-done" : "pollar-bridge-step", children: [
9619
+ /* @__PURE__ */ jsx("span", { className: "pollar-bridge-step-dot", "aria-hidden": true }),
9620
+ labels[key]
9621
+ ] }, key)) });
9622
+ }
9623
+ function BridgeModalTemplate(props) {
9624
+ const language = useInheritedLanguage(props.language);
9625
+ const copy = BRIDGE_COPY[language];
9626
+ const cssVars = buildModalCssVars(props.theme, props.accentColor, props.styleOverrides);
9627
+ const { transfer, quote } = props;
9628
+ const busy = props.submitting || props.quoting;
9629
+ const toName = props.toChain ? BRIDGE_CHAIN_LABEL[props.toChain] : "";
9630
+ const signingNote = quote?.signing === "EXTERNAL" ? copy.signingExternal : quote?.signing === "COSIGNED" || quote?.signing === "SELF_CUSTODY" ? copy.signingCosigned : copy.signingInternal;
9631
+ return /* @__PURE__ */ jsxs(
9632
+ "div",
9633
+ {
9634
+ className: "pollar-modal-card pollar-bridge-modal",
9635
+ "data-theme": props.theme,
9636
+ style: cssVars,
9637
+ onClick: (event) => event.stopPropagation(),
9638
+ children: [
9639
+ /* @__PURE__ */ jsxs("div", { className: "pollar-modal-header", children: [
9640
+ /* @__PURE__ */ jsx("h2", { className: "pollar-modal-title", children: copy.title }),
9641
+ /* @__PURE__ */ jsx("div", { className: "pollar-modal-header-actions", children: /* @__PURE__ */ jsx("button", { type: "button", className: "pollar-modal-close", onClick: props.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" }) }) }) })
9642
+ ] }),
9643
+ props.step === "loading" && /* @__PURE__ */ jsx("div", { className: "pollar-modal-empty", children: copy.loading }),
9644
+ props.step === "unavailable" && /* @__PURE__ */ jsx("div", { className: "pollar-modal-empty", children: props.unavailableReason === "mainnet_only" ? copy.mainnetOnly : copy.noDirections }),
9645
+ props.step === "form" && /* @__PURE__ */ jsxs("div", { className: "pollar-bridge-form", children: [
9646
+ /* @__PURE__ */ jsxs("div", { className: "pollar-bridge-chains", children: [
9647
+ /* @__PURE__ */ jsx(
9648
+ ChainPicker,
9649
+ {
9650
+ label: copy.from,
9651
+ value: props.fromChain,
9652
+ options: props.sources,
9653
+ onChange: props.onFromChange,
9654
+ disabled: busy
9655
+ }
9656
+ ),
9657
+ /* @__PURE__ */ jsx("span", { className: "pollar-bridge-arrow", "aria-hidden": true, children: "\u2192" }),
9658
+ /* @__PURE__ */ jsx(
9659
+ ChainPicker,
9660
+ {
9661
+ label: copy.to,
9662
+ value: props.toChain,
9663
+ options: props.targets,
9664
+ onChange: props.onToChange,
9665
+ disabled: busy
9666
+ }
9667
+ )
9668
+ ] }),
9669
+ /* @__PURE__ */ jsxs("label", { className: "pollar-bridge-field", children: [
9670
+ /* @__PURE__ */ jsxs("span", { className: "pollar-bridge-label-row", children: [
9671
+ /* @__PURE__ */ jsx("span", { className: "pollar-bridge-label", children: copy.amount }),
9672
+ /* @__PURE__ */ jsxs("span", { className: "pollar-bridge-balance", children: [
9673
+ copy.balance,
9674
+ " ",
9675
+ props.balance ?? "\u2014",
9676
+ props.balance !== null && /* @__PURE__ */ jsx("button", { type: "button", className: "pollar-bridge-max", onClick: props.onMax, disabled: busy, children: copy.max })
9677
+ ] })
9678
+ ] }),
9679
+ /* @__PURE__ */ jsx(
9680
+ "input",
9681
+ {
9682
+ className: "pollar-input",
9683
+ type: "text",
9684
+ inputMode: "decimal",
9685
+ placeholder: "0.00",
9686
+ value: props.amount,
9687
+ disabled: props.submitting,
9688
+ onChange: (event) => props.onAmountChange(event.target.value)
9689
+ }
9690
+ )
9691
+ ] }),
9692
+ props.quoting && /* @__PURE__ */ jsx("div", { className: "pollar-bridge-note", children: copy.quoting }),
9693
+ quote && !props.quoting && /* @__PURE__ */ jsxs("dl", { className: "pollar-bridge-quote", children: [
9694
+ /* @__PURE__ */ jsxs("div", { children: [
9695
+ /* @__PURE__ */ jsx("dt", { children: copy.youReceive }),
9696
+ /* @__PURE__ */ jsxs("dd", { children: [
9697
+ quote.amountOut,
9698
+ " USDC \xB7 ",
9699
+ toName
9700
+ ] })
9701
+ ] }),
9702
+ /* @__PURE__ */ jsxs("div", { children: [
9703
+ /* @__PURE__ */ jsx("dt", { children: copy.fee }),
9704
+ /* @__PURE__ */ jsx("dd", { children: quote.fee ? `${quote.fee.amount} USD` : copy.noFee })
9705
+ ] }),
9706
+ /* @__PURE__ */ jsxs("div", { children: [
9707
+ /* @__PURE__ */ jsx("dt", { children: copy.eta }),
9708
+ /* @__PURE__ */ jsx("dd", { children: fill(copy.etaValue, { minutes: String(Math.max(1, Math.round(quote.etaSeconds / 60))) }) })
9709
+ ] }),
9710
+ /* @__PURE__ */ jsx("p", { className: "pollar-bridge-note", children: signingNote })
9711
+ ] }),
9712
+ props.formError && /* @__PURE__ */ jsx("div", { className: "pollar-modal-error", children: props.formError }),
9713
+ /* @__PURE__ */ jsx("div", { className: "pollar-modal-actions", children: /* @__PURE__ */ jsx(
9714
+ "button",
9715
+ {
9716
+ type: "button",
9717
+ className: "pollar-btn-primary",
9718
+ disabled: !props.canSubmit || props.submitting,
9719
+ onClick: props.onSubmit,
9720
+ children: props.submitting ? copy.starting : copy.bridgeButton
9721
+ }
9722
+ ) })
9723
+ ] }),
9724
+ props.step === "transfer" && transfer && /* @__PURE__ */ jsxs("div", { className: "pollar-bridge-transfer", children: [
9725
+ /* @__PURE__ */ jsxs("div", { className: `pollar-bridge-status pollar-bridge-status-${transfer.status.toLowerCase()}`, children: [
9726
+ /* @__PURE__ */ jsx("strong", { children: copy.statusTitle[transfer.status] }),
9727
+ /* @__PURE__ */ jsx("p", { children: fill(copy.statusBody[transfer.status], {
9728
+ from: BRIDGE_CHAIN_LABEL[transfer.fromChain],
9729
+ to: BRIDGE_CHAIN_LABEL[transfer.toChain],
9730
+ amount: transfer.amountOut ?? transfer.amount
9731
+ }) })
9732
+ ] }),
9733
+ /* @__PURE__ */ jsx(
9734
+ Progress,
9735
+ {
9736
+ transfer,
9737
+ labels: {
9738
+ burn: fill(copy.steps.burn, { from: BRIDGE_CHAIN_LABEL[transfer.fromChain] }),
9739
+ attest: copy.steps.attest,
9740
+ mint: fill(copy.steps.mint, { to: BRIDGE_CHAIN_LABEL[transfer.toChain] })
9741
+ }
9742
+ }
9743
+ ),
9744
+ transfer.pendingAction?.kind === "SIGNATURE" && /* @__PURE__ */ jsx("button", { type: "button", className: "pollar-btn-primary", disabled: props.signing, onClick: props.onAuthorize, children: props.signing ? copy.waitingWallet : copy.authorize }),
9745
+ transfer.pendingAction?.kind === "COSIGN_APPROVAL" && /* @__PURE__ */ jsx("button", { type: "button", className: "pollar-btn-primary", onClick: props.onApprove, children: copy.approveOnDevice }),
9746
+ props.actionError && /* @__PURE__ */ jsx("div", { className: "pollar-modal-error", children: props.actionError }),
9747
+ props.pollTrouble && /* @__PURE__ */ jsx("div", { className: "pollar-bridge-note", children: copy.pollTrouble }),
9748
+ /* @__PURE__ */ jsxs("div", { className: "pollar-bridge-links", children: [
9749
+ transfer.burnTxHash && /* @__PURE__ */ jsx("a", { href: EXPLORER[transfer.fromChain](transfer.burnTxHash), target: "_blank", rel: "noopener noreferrer", children: fill(copy.viewBurn, { chain: BRIDGE_CHAIN_LABEL[transfer.fromChain] }) }),
9750
+ transfer.mintTxHash && /* @__PURE__ */ jsx("a", { href: EXPLORER[transfer.toChain](transfer.mintTxHash), target: "_blank", rel: "noopener noreferrer", children: fill(copy.viewMint, { chain: BRIDGE_CHAIN_LABEL[transfer.toChain] }) })
9751
+ ] }),
9752
+ (transfer.status === "COMPLETED" || transfer.status === "FAILED") && /* @__PURE__ */ jsxs("div", { className: "pollar-modal-actions", children: [
9753
+ /* @__PURE__ */ jsx("button", { type: "button", className: "pollar-btn-secondary", onClick: props.onNewBridge, children: copy.newBridge }),
9754
+ /* @__PURE__ */ jsx("button", { type: "button", className: "pollar-btn-primary", onClick: props.onClose, children: copy.done })
9755
+ ] })
9756
+ ] }),
9757
+ /* @__PURE__ */ jsx(PollarModalFooter, {})
9758
+ ]
9759
+ }
9760
+ );
9761
+ }
9762
+ var AMOUNT = /^(?:0|[1-9]\d{0,11})(?:\.\d{1,6})?$/;
9763
+ var QUOTE_DEBOUNCE_MS2 = 400;
9764
+ function errorText(error, copy) {
9765
+ if (!isPollarApiError(error)) return copy.errors.generic;
9766
+ const reason = typeof error.body.reason === "string" ? error.body.reason : null;
9767
+ const chain = typeof error.body.chain === "string" ? BRIDGE_CHAIN_LABEL[error.body.chain] ?? "" : "";
9768
+ switch (error.code) {
9769
+ case "SDK_BRIDGE_UNAVAILABLE":
9770
+ if (reason === "mainnet_only") return copy.errors.mainnetOnly;
9771
+ if (reason === "chain_not_enabled") return copy.errors.chainNotEnabled;
9772
+ return copy.errors.noGasWallet;
9773
+ case "SDK_BRIDGE_WALLET_NOT_READY":
9774
+ if (reason === "no_usdc_trustline") return copy.errors.noTrustline;
9775
+ if (reason === "no_wallet") return copy.errors.noWallet(chain);
9776
+ return copy.errors.unsupportedWallet;
9777
+ case "SDK_CREDITS_INSUFFICIENT":
9778
+ case "SDK_BILLING_OVERDUE":
9779
+ return copy.errors.credits;
9780
+ case "SDK_BRIDGE_ACTION_CHANGED":
9781
+ return copy.errors.actionChanged;
9782
+ default:
9783
+ return copy.errors.generic;
9784
+ }
9785
+ }
9786
+ function solanaBurnSigner(client, copy) {
9787
+ return async (action) => {
9788
+ const payload = JSON.parse(action.payload.value);
9789
+ const solanaWallet = () => client.getWallets().find((w) => w.chain === "SOLANA" && w.custody === "external");
9790
+ const wallet = solanaWallet();
9791
+ if (!wallet || payload.from !== wallet.address || !payload.unsignedTransaction)
9792
+ throw new Error(copy.errors.connectSolanaWallet);
9793
+ const signed = await client.signSolanaTransaction(payload.unsignedTransaction);
9794
+ if (solanaWallet()?.address !== wallet.address) throw new Error(copy.errors.walletChanged);
9795
+ return signed;
9796
+ };
9797
+ }
9798
+ async function signStepWithWallet(client, transferId, actionId, copy) {
9799
+ const lent = [];
9800
+ const lend = (chain, encoding, handler) => {
9801
+ try {
9802
+ lent.push(client.registerRampSigningHandler(chain, encoding, handler));
9803
+ } catch {
9804
+ }
9805
+ };
9806
+ lend("SOLANA", "solana-cctp-json", solanaBurnSigner(client, copy));
9807
+ lend("STELLAR", "xdr", async (action) => {
9808
+ const wallet = client.getWallet();
9809
+ if (!wallet) throw new Error(copy.errors.connectStellarWallet);
9810
+ assertRampStellarSigner(action, wallet.address);
9811
+ const outcome = await client.signTx(action.payload.value);
9812
+ if (client.getWallet()?.address !== wallet.address) throw new Error(copy.errors.walletChanged);
9813
+ if (outcome.status === "signed") return outcome.signedXdr;
9814
+ throw new Error(
9815
+ outcome.status === "error" ? outcome.message ?? outcome.details ?? copy.errors.signingCancelled : copy.errors.signingCancelled
9816
+ );
9817
+ });
9818
+ try {
9819
+ return await client.signBridgeStep(transferId, actionId);
9820
+ } finally {
9821
+ for (const release of lent) release();
9822
+ }
9823
+ }
9824
+ function newIntentKey() {
9825
+ return typeof crypto !== "undefined" && "randomUUID" in crypto ? crypto.randomUUID() : `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
9826
+ }
9827
+ function BridgeModal({ onClose, initial }) {
9828
+ const { getClient, styles, walletBalance, refreshWalletBalance, openCosignModal } = usePollar();
9829
+ const language = useModalLanguage();
9830
+ const copy = BRIDGE_COPY[language];
9831
+ const { theme, accentColor, styleOverrides, overlayStyle } = modalChrome(styles);
9832
+ const client = getClient();
9833
+ const [config, setConfig] = useState(null);
9834
+ const [configError, setConfigError] = useState(null);
9835
+ const [fromChain, setFromChain] = useState(null);
9836
+ const [toChain, setToChain] = useState(null);
9837
+ const [amount, setAmount] = useState(() => seededAmount(initial?.amount));
9838
+ const [quote, setQuote] = useState(null);
9839
+ const [quoting, setQuoting] = useState(false);
9840
+ const [quoteError, setQuoteError] = useState(null);
9841
+ const [submitting, setSubmitting] = useState(false);
9842
+ const [transfer, setTransfer] = useState(null);
9843
+ const [signing, setSigning] = useState(false);
9844
+ const [actionError, setActionError] = useState(null);
9845
+ const [pollTrouble, setPollTrouble] = useState(false);
9846
+ const intentKey = useRef(newIntentKey());
9847
+ useEffect(() => {
9848
+ let cancelled = false;
9849
+ client.getBridgeConfig().then((loaded) => {
9850
+ if (cancelled) return;
9851
+ setConfig(loaded);
9852
+ const sources2 = bridgeSourceChains(loaded);
9853
+ const from = oneOf(sources2, initial?.fromChain) ?? sources2[0] ?? null;
9854
+ const targets2 = from ? bridgeTargetChains(loaded, from) : [];
9855
+ setFromChain(from);
9856
+ setToChain(oneOf(targets2, initial?.toChain) ?? targets2[0] ?? null);
9857
+ }).catch((error) => !cancelled && setConfigError(errorText(error, copy)));
9858
+ return () => {
9859
+ cancelled = true;
9860
+ };
9861
+ }, [client]);
9862
+ const sources = useMemo(() => config ? bridgeSourceChains(config) : [], [config]);
9863
+ const targets = useMemo(() => config && fromChain ? bridgeTargetChains(config, fromChain) : [], [config, fromChain]);
9864
+ const balance = useMemo(() => {
9865
+ if (walletBalance.step !== "loaded" || !fromChain) return null;
9866
+ const usdc = walletBalance.data.balances.find((b) => (b.chain ?? "STELLAR") === fromChain && b.code === "USDC");
9867
+ return usdc ? usdc.available ?? usdc.balance : "0";
9868
+ }, [walletBalance, fromChain]);
9869
+ const amountValid = AMOUNT.test(amount) && Number(amount) > 0;
9870
+ const overBalance = amountValid && balance !== null && Number(amount) > Number(balance);
9871
+ const formError = configError ?? quoteError ?? (amount && !amountValid ? copy.invalidAmount : null) ?? (overBalance ? copy.overBalance : null);
9872
+ useEffect(() => {
9873
+ setQuote(null);
9874
+ setQuoteError(null);
9875
+ if (!fromChain || !toChain || !amountValid) return;
9876
+ let cancelled = false;
9877
+ const timer = setTimeout(() => {
9878
+ setQuoting(true);
9879
+ client.quoteBridge({ fromChain, toChain, amount }).then((next) => !cancelled && setQuote(next)).catch((error) => !cancelled && setQuoteError(errorText(error, copy))).finally(() => !cancelled && setQuoting(false));
9880
+ }, QUOTE_DEBOUNCE_MS2);
9881
+ return () => {
9882
+ cancelled = true;
9883
+ clearTimeout(timer);
9884
+ };
9885
+ }, [client, fromChain, toChain, amount, amountValid]);
9886
+ useEffect(() => {
9887
+ if (!transfer || isBridgeSettled(transfer)) return;
9888
+ const controller = new AbortController();
9889
+ client.pollBridgeTransfer(transfer.id, {
9890
+ signal: controller.signal,
9891
+ onUpdate: (next) => {
9892
+ setPollTrouble(false);
9893
+ setTransfer(next);
9894
+ },
9895
+ onError: () => setPollTrouble(true),
9896
+ // A co-signed step moves once the device approves: keep reading through it.
9897
+ until: (next) => next.status === "AWAITING_ACTION" && next.pendingAction?.kind === "SIGNATURE"
9898
+ }).then((settled) => {
9899
+ if (settled.status === "COMPLETED") void refreshWalletBalance();
9900
+ }).catch(() => {
9901
+ });
9902
+ return () => controller.abort();
9903
+ }, [client, transfer?.id, transfer?.pendingAction?.actionId]);
9904
+ const reported = useRef(null);
9905
+ const onSuccess = initial?.onSuccess;
9906
+ useEffect(() => {
9907
+ if (transfer?.status !== "COMPLETED" || reported.current === transfer.id) return;
9908
+ reported.current = transfer.id;
9909
+ onSuccess?.(transfer);
9910
+ }, [transfer, onSuccess]);
9911
+ async function submit() {
9912
+ if (!fromChain || !toChain || !amountValid || overBalance) return;
9913
+ setSubmitting(true);
9914
+ setQuoteError(null);
9915
+ try {
9916
+ const started = await client.bridge({ fromChain, toChain, amount, idempotencyKey: intentKey.current });
9917
+ setTransfer(started);
9918
+ } catch (error) {
9919
+ setQuoteError(errorText(error, copy));
9920
+ } finally {
9921
+ setSubmitting(false);
9922
+ }
9923
+ }
9924
+ async function authorize() {
9925
+ const action = transfer?.pendingAction;
9926
+ if (!transfer || action?.kind !== "SIGNATURE") return;
9927
+ setSigning(true);
9928
+ setActionError(null);
9929
+ try {
9930
+ setTransfer(await signStepWithWallet(client, transfer.id, action.actionId, copy));
9931
+ } catch (error) {
9932
+ setActionError(error instanceof Error && !isPollarApiError(error) ? error.message : errorText(error, copy));
9933
+ client.getBridgeTransfer(transfer.id).then(setTransfer).catch(() => {
9934
+ });
9935
+ } finally {
9936
+ setSigning(false);
9937
+ }
9938
+ }
9939
+ function newBridge() {
9940
+ intentKey.current = newIntentKey();
9941
+ setTransfer(null);
9942
+ setAmount("");
9943
+ setActionError(null);
9944
+ void refreshWalletBalance();
9945
+ }
9946
+ const step = transfer ? "transfer" : !config && !configError ? "loading" : config && (!config.available || sources.length === 0) ? "unavailable" : "form";
9947
+ return /* @__PURE__ */ jsx(PollarOverlay, { style: overlayStyle, onClick: onClose, children: /* @__PURE__ */ jsx(
9948
+ BridgeModalTemplate,
9949
+ {
9950
+ theme,
9951
+ accentColor,
9952
+ styleOverrides,
9953
+ step,
9954
+ unavailableReason: config?.reason === "mainnet_only" ? "mainnet_only" : config ? "no_directions" : null,
9955
+ sources,
9956
+ targets,
9957
+ fromChain,
9958
+ toChain,
9959
+ onFromChange: (chain) => {
9960
+ setFromChain(chain);
9961
+ const next = config ? bridgeTargetChains(config, chain) : [];
9962
+ if (!toChain || !next.includes(toChain)) setToChain(next[0] ?? null);
9963
+ },
9964
+ onToChange: setToChain,
9965
+ amount,
9966
+ onAmountChange: (value) => setAmount(value.replace(",", ".").trim()),
9967
+ balance,
9968
+ onMax: () => balance !== null && setAmount(balance.replace(/(\.\d{6})\d+$/, "$1")),
9969
+ quote,
9970
+ quoting,
9971
+ formError,
9972
+ canSubmit: !!quote && !quoting && amountValid && !overBalance,
9973
+ submitting,
9974
+ onSubmit: () => void submit(),
9975
+ transfer,
9976
+ signing,
9977
+ onAuthorize: () => void authorize(),
9978
+ onApprove: openCosignModal,
9979
+ actionError,
9980
+ pollTrouble,
9981
+ onNewBridge: newBridge,
9982
+ onClose,
9983
+ language
9984
+ }
9985
+ ) });
9986
+ }
9987
+
9250
9988
  // src/components/earn-modal/earn-copy.ts
9251
9989
  var EARN_COPY = {
9252
9990
  en: {
@@ -9372,7 +10110,7 @@ function formatAmount3(value) {
9372
10110
  const n = parseFloat(value);
9373
10111
  return isNaN(n) ? value : n.toLocaleString(void 0, { maximumFractionDigits: 7 });
9374
10112
  }
9375
- function EarnModal({ onClose }) {
10113
+ function EarnModal({ onClose, initial }) {
9376
10114
  const {
9377
10115
  getEarnProviders,
9378
10116
  getEarnOpportunities,
@@ -9393,13 +10131,15 @@ function EarnModal({ onClose }) {
9393
10131
  const smartUnsupported = wallet?.custody === "smart";
9394
10132
  const { theme, accentColor, styleOverrides, overlayStyle } = modalChrome(styles);
9395
10133
  const [step, setStep] = useState("form");
9396
- const [tab, setTab] = useState("deposit");
10134
+ const [tab, setTab] = useState(
10135
+ () => oneOf(["deposit", "withdraw"], initial?.tab) ?? "deposit"
10136
+ );
9397
10137
  const [providers, setProviders] = useState(null);
9398
10138
  const [provider, setProvider] = useState(null);
9399
10139
  const [opportunities, setOpportunities] = useState([]);
9400
- const [opportunityId, setOpportunityId] = useState("");
10140
+ const [opportunityId, setOpportunityId] = useState(() => initial?.opportunityId ?? "");
9401
10141
  const [position, setPosition] = useState(null);
9402
- const [amount, setAmount] = useState("");
10142
+ const [amount, setAmount] = useState(() => seededAmount(initial?.amount));
9403
10143
  const [loadingOpps, setLoadingOpps] = useState(false);
9404
10144
  const [formError, setFormError] = useState("");
9405
10145
  const [refreshing, setRefreshing] = useState(false);
@@ -9410,9 +10150,9 @@ function EarnModal({ onClose }) {
9410
10150
  setProviders(null);
9411
10151
  return getEarnProviders().then((ps) => {
9412
10152
  setProviders(ps);
9413
- setProvider((cur) => cur ?? ps[0] ?? null);
10153
+ setProvider((cur) => cur ?? oneOf(ps, initial?.provider) ?? ps[0] ?? null);
9414
10154
  }).catch(() => setProviders([]));
9415
- }, [getEarnProviders]);
10155
+ }, [getEarnProviders, initial?.provider]);
9416
10156
  useEffect(() => {
9417
10157
  void loadProviders();
9418
10158
  }, [loadProviders]);
@@ -9474,6 +10214,7 @@ function EarnModal({ onClose }) {
9474
10214
  })();
9475
10215
  const depositNeedsTrustline = tab === "deposit" && !smartUnsupported && !!selectedOpportunity?.asset.issuer && !depositAssetRecord?.trustlineEstablished;
9476
10216
  const hash = transaction.step === "success" ? transaction.hash : null;
10217
+ useSuccessReport(transaction, step === "tx", initial?.onSuccess);
9477
10218
  const buildData = "buildData" in transaction ? transaction.buildData : null;
9478
10219
  const explorerNetwork = buildData?.summary.network?.toLowerCase().includes("testnet") ? "testnet" : buildData ? "public" : network === "testnet" ? "testnet" : "public";
9479
10220
  const explorerUrl = hash ? `https://stellar.expert/explorer/${explorerNetwork}/tx/${hash}` : null;
@@ -9562,7 +10303,7 @@ function EarnModal({ onClose }) {
9562
10303
  }
9563
10304
  }
9564
10305
  const title = step === "form" ? copy.title : txTitle;
9565
- return /* @__PURE__ */ jsx("div", { className: "pollar-overlay", style: overlayStyle, onClick: !isInProgress ? onClose : void 0, children: /* @__PURE__ */ jsxs(
10306
+ return /* @__PURE__ */ jsx(PollarOverlay, { style: overlayStyle, onClick: !isInProgress ? onClose : void 0, children: /* @__PURE__ */ jsxs(
9566
10307
  "div",
9567
10308
  {
9568
10309
  className: "pollar-modal-card pollar-send-modal",
@@ -9894,7 +10635,15 @@ var CARD_COPY = {
9894
10635
  chain: (id) => `chain ${id}`,
9895
10636
  sendOnly: (tokens, network) => `Send only ${tokens} on ${network}; anything else can be lost.`,
9896
10637
  noDeposit: "The provider returned no deposit address.",
9897
- hideDeposit: "Hide the deposit address"
10638
+ hideDeposit: "Hide the deposit address",
10639
+ fundingProblem: {
10640
+ noGas: "Your wallet does not have enough to pay the network fee.",
10641
+ sponsorNoGas: "The network fee cannot be covered right now. Please try again later.",
10642
+ noBalance: "Your wallet does not have enough USDC for this amount.",
10643
+ notPaid: "The payment was not sent.",
10644
+ failed: "The payment could not be completed. Please try again.",
10645
+ delayed: "Taking longer than usual. We are following up with the card provider."
10646
+ }
9898
10647
  },
9899
10648
  es: {
9900
10649
  funding: {
@@ -10052,7 +10801,15 @@ var CARD_COPY = {
10052
10801
  chain: (id) => `cadena ${id}`,
10053
10802
  sendOnly: (tokens, network) => `Env\xEDa solo ${tokens} en ${network}; cualquier otra cosa puede perderse.`,
10054
10803
  noDeposit: "El proveedor no devolvi\xF3 ninguna direcci\xF3n de dep\xF3sito.",
10055
- hideDeposit: "Ocultar la direcci\xF3n de dep\xF3sito"
10804
+ hideDeposit: "Ocultar la direcci\xF3n de dep\xF3sito",
10805
+ fundingProblem: {
10806
+ noGas: "Tu wallet no tiene saldo suficiente para pagar la comisi\xF3n de red.",
10807
+ sponsorNoGas: "Ahora no se puede cubrir la comisi\xF3n de red. Intenta de nuevo m\xE1s tarde.",
10808
+ noBalance: "Tu wallet no tiene suficiente USDC para este monto.",
10809
+ notPaid: "El pago no se envi\xF3.",
10810
+ failed: "No se pudo completar el pago. Intenta de nuevo.",
10811
+ delayed: "Est\xE1 tardando m\xE1s de lo normal. Estamos haciendo seguimiento con el emisor de la tarjeta."
10812
+ }
10056
10813
  },
10057
10814
  pt: {
10058
10815
  funding: {
@@ -10210,9 +10967,28 @@ var CARD_COPY = {
10210
10967
  chain: (id) => `rede ${id}`,
10211
10968
  sendOnly: (tokens, network) => `Envie apenas ${tokens} na ${network}; qualquer outra coisa pode ser perdida.`,
10212
10969
  noDeposit: "O provedor n\xE3o retornou nenhum endere\xE7o de dep\xF3sito.",
10213
- hideDeposit: "Ocultar o endere\xE7o de dep\xF3sito"
10970
+ hideDeposit: "Ocultar o endere\xE7o de dep\xF3sito",
10971
+ fundingProblem: {
10972
+ noGas: "Sua carteira n\xE3o tem saldo suficiente para pagar a taxa de rede.",
10973
+ sponsorNoGas: "A taxa de rede n\xE3o pode ser coberta agora. Tente novamente mais tarde.",
10974
+ noBalance: "Sua carteira n\xE3o tem USDC suficiente para este valor.",
10975
+ notPaid: "O pagamento n\xE3o foi enviado.",
10976
+ failed: "N\xE3o foi poss\xEDvel concluir o pagamento. Tente novamente.",
10977
+ delayed: "Est\xE1 demorando mais que o normal. Estamos acompanhando com o emissor do cart\xE3o."
10978
+ }
10214
10979
  }
10215
10980
  };
10981
+ var CREDIT_DELAYED = "provider_credit_delayed";
10982
+ function fundingProblemText(error, copy) {
10983
+ const raw = error ?? "";
10984
+ if (/^TX_INSUFFICIENT_BALANCE|needed \(fee/.test(raw)) {
10985
+ if (/sponsor/i.test(raw)) return copy.fundingProblem.sponsorNoGas;
10986
+ return /token balance/i.test(raw) ? copy.fundingProblem.noBalance : copy.fundingProblem.noGas;
10987
+ }
10988
+ if (/insufficient_usdc/.test(raw)) return copy.fundingProblem.noBalance;
10989
+ if (/^(payment_not_received|cosign_rejected|cosign_expired)/.test(raw)) return copy.fundingProblem.notPaid;
10990
+ return copy.fundingProblem.failed;
10991
+ }
10216
10992
 
10217
10993
  // src/components/card-modal/card-kyc.ts
10218
10994
  var nonEmpty = (value) => typeof value === "string" && !!value.trim();
@@ -10297,10 +11073,20 @@ function money(amount, currency, language) {
10297
11073
  function groupPan(pan) {
10298
11074
  return pan.replace(/\s+/g, "").replace(/(.{4})/g, "$1 ").trim();
10299
11075
  }
10300
- function errorText(e, fallback, copy) {
11076
+ function errorText2(e, fallback, copy) {
10301
11077
  if (isPollarApiError(e)) {
10302
11078
  const known = copy.errors[e.code];
10303
11079
  if (known) return known;
11080
+ if (e.code === "SDK_CARDS_FUNDING_WALLET_NOT_READY") {
11081
+ const { reason, code, message: message2 } = e.body;
11082
+ if (reason === "insufficient_usdc") return copy.fundingProblem.noBalance;
11083
+ if (reason === "build_failed" || reason === "payment_rejected") {
11084
+ return fundingProblemText(
11085
+ `${typeof code === "string" ? code : ""}: ${typeof message2 === "string" ? message2 : ""}`,
11086
+ copy
11087
+ );
11088
+ }
11089
+ }
10304
11090
  const providerMessage = e.body.providerMessage;
10305
11091
  if (typeof providerMessage === "string" && providerMessage) return providerMessage;
10306
11092
  const message = e.body.message;
@@ -10309,7 +11095,7 @@ function errorText(e, fallback, copy) {
10309
11095
  }
10310
11096
  return e instanceof Error && e.message ? e.message : fallback;
10311
11097
  }
10312
- function CardModal({ onClose }) {
11098
+ function CardModal({ onClose, initial }) {
10313
11099
  const { getClient, styles, wallet } = usePollar();
10314
11100
  const language = useModalLanguage();
10315
11101
  const copy = CARD_COPY[language];
@@ -10325,9 +11111,10 @@ function CardModal({ onClose }) {
10325
11111
  const [transactions, setTransactions] = useState(null);
10326
11112
  const [deposit, setDeposit] = useState(null);
10327
11113
  const [fundings, setFundings] = useState(null);
10328
- const [fundAmount, setFundAmount] = useState("");
11114
+ const [fundAmount, setFundAmount] = useState(() => seededAmount(initial?.amount));
10329
11115
  const fundKey = useRef(null);
10330
- const [fundChain, setFundChain] = useState(null);
11116
+ const [fundChain, setFundChain] = useState(initial?.chain ?? null);
11117
+ const fundPanelSeed = useRef(initial?.panel === "fund");
10331
11118
  const [showManual, setShowManual] = useState(false);
10332
11119
  const [occupations, setOccupations] = useState([]);
10333
11120
  const [kyc, setKyc] = useState(emptyKyc);
@@ -10341,7 +11128,7 @@ function CardModal({ onClose }) {
10341
11128
  const provider = providers?.[0] ?? null;
10342
11129
  const fundingAsset = provider?.fundingAssets[0] ?? "USDC";
10343
11130
  const fundChains = useChains().chains.filter(isFundingChain);
10344
- const selectedFundChain = fundChain ?? fundChains[0] ?? "STELLAR";
11131
+ const selectedFundChain = (fundChain && fundChains.includes(fundChain) ? fundChain : null) ?? fundChains[0] ?? "STELLAR";
10345
11132
  const fundAvailable = useWalletAvailable(panel === "fund" ? { chain: selectedFundChain, code: fundingAsset } : null);
10346
11133
  const card = cards?.[0] ?? null;
10347
11134
  const expiry = card?.expMonth && card.expYear ? `${card.expMonth}/${card.expYear.slice(-2)}` : null;
@@ -10389,7 +11176,7 @@ function CardModal({ onClose }) {
10389
11176
  } catch (e) {
10390
11177
  if (!cancelled) {
10391
11178
  setProviders((cur) => cur ?? []);
10392
- setError(errorText(e, copy.failed.load, copy));
11179
+ setError(errorText2(e, copy.failed.load, copy));
10393
11180
  }
10394
11181
  }
10395
11182
  })();
@@ -10438,7 +11225,7 @@ function CardModal({ onClose }) {
10438
11225
  } catch (e) {
10439
11226
  const step = requiredCardStep(e);
10440
11227
  if (step) openStep(step);
10441
- else setError(errorText(e, fallback, copy));
11228
+ else setError(errorText2(e, fallback, copy));
10442
11229
  } finally {
10443
11230
  setBusy(null);
10444
11231
  }
@@ -10505,6 +11292,11 @@ function CardModal({ onClose }) {
10505
11292
  },
10506
11293
  copy.failed.loadFundings
10507
11294
  );
11295
+ useEffect(() => {
11296
+ if (!card || !fundPanelSeed.current) return;
11297
+ fundPanelSeed.current = false;
11298
+ void openFund();
11299
+ }, [card]);
10508
11300
  const fund = () => run(
10509
11301
  "fund-send",
10510
11302
  async () => {
@@ -10527,6 +11319,7 @@ function CardModal({ onClose }) {
10527
11319
  }
10528
11320
  setFundings((cur) => [outcome.funding, ...(cur ?? []).filter((f) => f.id !== outcome.funding.id)]);
10529
11321
  setFundAmount("");
11322
+ initial?.onFunded?.(outcome.funding);
10530
11323
  },
10531
11324
  copy.failed.fund
10532
11325
  );
@@ -10635,7 +11428,7 @@ function CardModal({ onClose }) {
10635
11428
  const blocked = requirements?.next ? blockedStepMessage(requirements.next, copy.blocked) : null;
10636
11429
  const stepsPending = !!requirements?.next;
10637
11430
  const title = panel === "fund" ? copy.title.addFunds : card ? card.nickname ?? copy.title.yourCard : copy.title.getCard;
10638
- return /* @__PURE__ */ jsx("div", { className: "pollar-overlay", style: overlayStyle, onClick: onClose, children: /* @__PURE__ */ jsxs(
11431
+ return /* @__PURE__ */ jsx(PollarOverlay, { style: overlayStyle, onClick: onClose, children: /* @__PURE__ */ jsxs(
10639
11432
  "div",
10640
11433
  {
10641
11434
  className: "pollar-modal-card pollar-card-modal",
@@ -10943,12 +11736,13 @@ function CardModal({ onClose }) {
10943
11736
  ] }),
10944
11737
  inflight && step > 0 && /* @__PURE__ */ jsxs("span", { className: "pollar-card-tx-meta", role: "status", children: [
10945
11738
  copy.stepOf(step, steps.length),
10946
- " \xB7 ",
10947
- state?.hint
11739
+ " \xB7",
11740
+ " ",
11741
+ f.error === CREDIT_DELAYED ? copy.fundingProblem.delayed : state?.hint
10948
11742
  ] }),
10949
11743
  /* @__PURE__ */ jsxs("span", { className: "pollar-card-tx-meta", children: [
10950
11744
  new Date(f.createdAt).toLocaleString(),
10951
- f.status === "FAILED" && f.error ? ` \xB7 ${f.error}` : ""
11745
+ f.status === "FAILED" ? ` \xB7 ${fundingProblemText(f.error, copy)}` : ""
10952
11746
  ] })
10953
11747
  ] }),
10954
11748
  /* @__PURE__ */ jsx("div", { className: "pollar-card-tx-amount", "data-direction": f.status === "CREDITED" ? "credit" : void 0, children: money(f.amount, "USD", language) })
@@ -11310,7 +12104,7 @@ function SessionsModal({ onClose }) {
11310
12104
  setSigningOutEverywhere(false);
11311
12105
  }
11312
12106
  }, [getClient, onClose]);
11313
- return /* @__PURE__ */ jsx("div", { className: "pollar-overlay", style: overlayStyle, onClick: onClose, children: /* @__PURE__ */ jsx(
12107
+ return /* @__PURE__ */ jsx(PollarOverlay, { style: overlayStyle, onClick: onClose, children: /* @__PURE__ */ jsx(
11314
12108
  SessionsModalTemplate,
11315
12109
  {
11316
12110
  theme,
@@ -11389,6 +12183,8 @@ var COSIGN_COPY = {
11389
12183
  approve: "Approve",
11390
12184
  approving: "Approving...",
11391
12185
  genericError: "Something went wrong. Please try again.",
12186
+ 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.",
12187
+ linkDevice: "Link this device",
11392
12188
  transaction: "Transaction",
11393
12189
  operations: {
11394
12190
  payment: "Send",
@@ -11428,6 +12224,8 @@ var COSIGN_COPY = {
11428
12224
  approve: "Aprobar",
11429
12225
  approving: "Aprobando...",
11430
12226
  genericError: "Algo sali\xF3 mal. Intenta de nuevo.",
12227
+ 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.",
12228
+ linkDevice: "Vincular este dispositivo",
11431
12229
  transaction: "Transacci\xF3n",
11432
12230
  operations: {
11433
12231
  payment: "Enviar",
@@ -11467,6 +12265,8 @@ var COSIGN_COPY = {
11467
12265
  approve: "Aprovar",
11468
12266
  approving: "Aprovando...",
11469
12267
  genericError: "Algo deu errado. Tente novamente.",
12268
+ 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.",
12269
+ linkDevice: "Vincular este dispositivo",
11470
12270
  transaction: "Transa\xE7\xE3o",
11471
12271
  operations: {
11472
12272
  payment: "Enviar",
@@ -11512,6 +12312,8 @@ function CosignModalTemplate({
11512
12312
  busy,
11513
12313
  error,
11514
12314
  approveBlocked = false,
12315
+ deviceNotLinked = false,
12316
+ onLinkDevice,
11515
12317
  lastResolved,
11516
12318
  explorerUrl,
11517
12319
  closesIn = null,
@@ -11526,7 +12328,7 @@ function CosignModalTemplate({
11526
12328
  const language = useInheritedLanguage(languageProp);
11527
12329
  const copy = COSIGN_COPY[language];
11528
12330
  const cssVars = buildModalCssVars(theme, accentColor, styleOverrides);
11529
- const verified = verification?.ok === true;
12331
+ const verified = verification?.ok === true && !deviceNotLinked;
11530
12332
  const canVote = !!current && verified && !busy && !approveBlocked;
11531
12333
  const [verifiedOpenFor, setVerifiedOpenFor] = useState(null);
11532
12334
  const verifiedOpen = !!current && verifiedOpenFor === current.id;
@@ -11611,11 +12413,11 @@ function CosignModalTemplate({
11611
12413
  current && review && /* @__PURE__ */ jsxs("div", { className: `pollar-cosign-detail${pending.length > 1 ? " pollar-cosign-detail-grouped" : ""}`, children: [
11612
12414
  /* @__PURE__ */ jsxs("div", { className: "pollar-cosign-detail-head", children: [
11613
12415
  /* @__PURE__ */ jsx("p", { className: "pollar-cosign-detail-title", children: review.title }),
11614
- !verification && /* @__PURE__ */ jsxs("span", { className: "pollar-cosign-chip", children: [
12416
+ !verification && !deviceNotLinked && /* @__PURE__ */ jsxs("span", { className: "pollar-cosign-chip", children: [
11615
12417
  /* @__PURE__ */ jsx("span", { className: "pollar-spinner pollar-spinner-sm", "aria-hidden": true }),
11616
12418
  copy.checking
11617
12419
  ] }),
11618
- verification?.ok && /* @__PURE__ */ jsxs(
12420
+ verified && /* @__PURE__ */ jsxs(
11619
12421
  "button",
11620
12422
  {
11621
12423
  type: "button",
@@ -11630,8 +12432,11 @@ function CosignModalTemplate({
11630
12432
  )
11631
12433
  ] }),
11632
12434
  /* @__PURE__ */ jsx(TxReview, { data: review, language }, current.id),
11633
- verification?.ok && verifiedOpen && /* @__PURE__ */ jsx("div", { className: "pollar-cosign-verify pollar-cosign-verify-ok", children: copy.checkedAgainstTurnkey }),
11634
- verification && !verification.ok && /* @__PURE__ */ jsxs("div", { className: "pollar-cosign-verify pollar-cosign-verify-bad", children: [
12435
+ verified && verifiedOpen && /* @__PURE__ */ jsx("div", { className: "pollar-cosign-verify pollar-cosign-verify-ok", children: copy.checkedAgainstTurnkey }),
12436
+ deviceNotLinked ? /* @__PURE__ */ jsxs("div", { className: "pollar-cosign-verify pollar-cosign-verify-bad", children: [
12437
+ copy.deviceNotLinked,
12438
+ onLinkDevice && /* @__PURE__ */ jsx("button", { type: "button", className: "pollar-cosign-link", onClick: onLinkDevice, children: copy.linkDevice })
12439
+ ] }) : verification && !verification.ok && /* @__PURE__ */ jsxs("div", { className: "pollar-cosign-verify pollar-cosign-verify-bad", children: [
11635
12440
  copy.notVerified,
11636
12441
  " ",
11637
12442
  verification.reason
@@ -11669,7 +12474,7 @@ var CLOSE_AFTER_SECONDS = 3;
11669
12474
  var CLOSE_AFTER_SENT_SECONDS = 5;
11670
12475
  var NEXT_REQUEST_EVERY_MS = 2e3;
11671
12476
  function CosignModal({ nextStep = null, onClose }) {
11672
- const { getClient, styles, network } = usePollar();
12477
+ const { getClient, styles, network, openRecoveryModal } = usePollar();
11673
12478
  const { theme, accentColor, styleOverrides, overlayStyle } = modalChrome(styles);
11674
12479
  const { pending, lastResolved, loaded, refresh, approve, reject, verify, inspectQuorum } = useCosign();
11675
12480
  const language = useModalLanguage();
@@ -11679,10 +12484,13 @@ function CosignModal({ nextStep = null, onClose }) {
11679
12484
  const [error, setError] = useState(null);
11680
12485
  const [approveFailedFor, setApproveFailedFor] = useState(null);
11681
12486
  const [quorumFailure, setQuorumFailure] = useState(null);
12487
+ const [deviceNotLinked, setDeviceNotLinked] = useState(false);
11682
12488
  useEffect(() => {
11683
12489
  let cancelled = false;
11684
12490
  inspectQuorum().then((q) => {
11685
- if (!cancelled && !q.ok) setQuorumFailure(q.reason);
12491
+ if (cancelled || q.ok) return;
12492
+ if (q.code === "DEVICE_NOT_ENROLLED") setDeviceNotLinked(true);
12493
+ else setQuorumFailure(q.reason);
11686
12494
  }).catch(() => void 0);
11687
12495
  return () => {
11688
12496
  cancelled = true;
@@ -11752,14 +12560,15 @@ function CosignModal({ nextStep = null, onClose }) {
11752
12560
  setError(
11753
12561
  transactionErrorMessage(isPollarApiError(err) ? err.code : null, err instanceof Error ? err.message : null, language)
11754
12562
  );
11755
- if (kind === "approving") setApproveFailedFor(request.id);
12563
+ if (kind === "approving" && !(isPollarApiError(err) && err.code === "SDK_COSIGN_GAS_PENDING"))
12564
+ setApproveFailedFor(request.id);
11756
12565
  } finally {
11757
12566
  setBusy(null);
11758
12567
  }
11759
12568
  },
11760
12569
  []
11761
12570
  );
11762
- return /* @__PURE__ */ jsx("div", { className: "pollar-overlay", style: overlayStyle, onClick: onClose, children: /* @__PURE__ */ jsx(
12571
+ return /* @__PURE__ */ jsx(PollarOverlay, { style: overlayStyle, onClick: onClose, children: /* @__PURE__ */ jsx(
11763
12572
  CosignModalTemplate,
11764
12573
  {
11765
12574
  theme,
@@ -11771,6 +12580,11 @@ function CosignModal({ nextStep = null, onClose }) {
11771
12580
  busy,
11772
12581
  error,
11773
12582
  approveBlocked: !!current && approveFailedFor === current.id,
12583
+ deviceNotLinked,
12584
+ onLinkDevice: () => {
12585
+ onClose();
12586
+ openRecoveryModal();
12587
+ },
11774
12588
  ...lastResolved ? { lastResolved } : {},
11775
12589
  closesIn,
11776
12590
  nextStep: awaitingNext ? nextStep : null,
@@ -11943,7 +12757,7 @@ function CustodyMigrationModal({ state, onMoved, onLater }) {
11943
12757
  setBusy(false);
11944
12758
  }
11945
12759
  }
11946
- return /* @__PURE__ */ jsx("div", { className: "pollar-overlay", style: overlayStyle, children: /* @__PURE__ */ jsx(
12760
+ return /* @__PURE__ */ jsx(PollarOverlay, { style: overlayStyle, children: /* @__PURE__ */ jsx(
11947
12761
  CustodyMigrationModalTemplate,
11948
12762
  {
11949
12763
  theme,
@@ -12404,7 +13218,7 @@ function RecoveryModalTemplate(p) {
12404
13218
  }
12405
13219
  );
12406
13220
  }
12407
- function errorText2(err, language) {
13221
+ function errorText3(err, language) {
12408
13222
  return cosignRefusalMessage(err, language) ?? transactionErrorMessage(isPollarApiError(err) ? err.code : null, err instanceof Error ? err.message : null, language);
12409
13223
  }
12410
13224
  function RecoveryModal({ onClose }) {
@@ -12437,7 +13251,7 @@ function RecoveryModal({ onClose }) {
12437
13251
  refreshRecovery();
12438
13252
  }, [getClient, refreshRecovery]);
12439
13253
  useEffect(() => {
12440
- load().catch((err) => setError(errorText2(err, language)));
13254
+ load().catch((err) => setError(errorText3(err, language)));
12441
13255
  }, [load]);
12442
13256
  const onCloseRef = useRef(onClose);
12443
13257
  onCloseRef.current = onClose;
@@ -12458,7 +13272,7 @@ function RecoveryModal({ onClose }) {
12458
13272
  if (after?.notice) setNotice(after.notice);
12459
13273
  if (after?.view) setView(after.view);
12460
13274
  } catch (err) {
12461
- setError(errorText2(err, language));
13275
+ setError(errorText3(err, language));
12462
13276
  } finally {
12463
13277
  setBusy(null);
12464
13278
  }
@@ -12466,7 +13280,7 @@ function RecoveryModal({ onClose }) {
12466
13280
  [load]
12467
13281
  );
12468
13282
  const enrolled = !!thisDeviceKey && !!devices?.devices.some((d) => d.publicKey.toLowerCase() === thisDeviceKey);
12469
- return /* @__PURE__ */ jsx("div", { className: "pollar-overlay", style: overlayStyle, onClick: onClose, children: /* @__PURE__ */ jsx(
13283
+ return /* @__PURE__ */ jsx(PollarOverlay, { style: overlayStyle, onClick: onClose, children: /* @__PURE__ */ jsx(
12470
13284
  RecoveryModalTemplate,
12471
13285
  {
12472
13286
  theme,
@@ -12612,7 +13426,7 @@ function ConfirmModal({ confirmation }) {
12612
13426
  if (authState.step === "idle") rejectRef.current();
12613
13427
  });
12614
13428
  }, [getClient]);
12615
- return /* @__PURE__ */ jsx("div", { className: "pollar-overlay", style: overlayStyle, onClick: confirmation.reject, children: /* @__PURE__ */ jsxs(
13429
+ return /* @__PURE__ */ jsx(PollarOverlay, { style: overlayStyle, onClick: confirmation.reject, children: /* @__PURE__ */ jsxs(
12616
13430
  "div",
12617
13431
  {
12618
13432
  className: "pollar-modal-card pollar-cosign-modal",
@@ -12742,7 +13556,7 @@ function TransactionModal({ onClose }) {
12742
13556
  await getClient().signAndSubmitTx(transaction.buildData.unsignedXdr);
12743
13557
  }
12744
13558
  }
12745
- return /* @__PURE__ */ jsx("div", { className: "pollar-overlay", style: overlayStyle, onClick: onClose, children: /* @__PURE__ */ jsx(
13559
+ return /* @__PURE__ */ jsx(PollarOverlay, { style: overlayStyle, onClick: onClose, children: /* @__PURE__ */ jsx(
12746
13560
  TransactionModalTemplate,
12747
13561
  {
12748
13562
  theme,
@@ -13099,7 +13913,7 @@ function TxHistoryModalTemplate({
13099
13913
  );
13100
13914
  }
13101
13915
  var PAGE_SIZE2 = 10;
13102
- function TxHistoryModal({ onClose }) {
13916
+ function TxHistoryModal({ onClose, initial }) {
13103
13917
  const { getClient, styles, txHistory, wallets } = usePollar();
13104
13918
  const { theme, accentColor, styleOverrides, overlayStyle } = modalChrome(styles);
13105
13919
  const language = useModalLanguage();
@@ -13107,8 +13921,8 @@ function TxHistoryModal({ onClose }) {
13107
13921
  const { chains } = useChains();
13108
13922
  const [selectedChain, setSelectedChain] = useState(null);
13109
13923
  useEffect(() => {
13110
- if (selectedChain === null && chains.length > 0) setSelectedChain(chains[0]);
13111
- }, [chains, selectedChain]);
13924
+ if (selectedChain === null && chains.length > 0) setSelectedChain(oneOf(chains, initial?.chain) ?? chains[0]);
13925
+ }, [chains, selectedChain, initial?.chain]);
13112
13926
  const walletAddress = addressForChain(wallets, selectedChain);
13113
13927
  const load = useCallback(
13114
13928
  (nextOffset, chain) => {
@@ -13124,7 +13938,7 @@ function TxHistoryModal({ onClose }) {
13124
13938
  const paged = (nextOffset) => {
13125
13939
  if (selectedChain) load(nextOffset, selectedChain);
13126
13940
  };
13127
- return /* @__PURE__ */ jsx("div", { className: "pollar-overlay", style: overlayStyle, onClick: onClose, children: /* @__PURE__ */ jsx(
13941
+ return /* @__PURE__ */ jsx(PollarOverlay, { style: overlayStyle, onClick: onClose, children: /* @__PURE__ */ jsx(
13128
13942
  TxHistoryModalTemplate,
13129
13943
  {
13130
13944
  theme,
@@ -13355,7 +14169,7 @@ function WalletBalanceModal({ onClose }) {
13355
14169
  useEffect(() => {
13356
14170
  void refreshWalletBalance();
13357
14171
  }, [refreshWalletBalance]);
13358
- return /* @__PURE__ */ jsx("div", { className: "pollar-overlay", style: overlayStyle, onClick: onClose, children: /* @__PURE__ */ jsx(
14172
+ return /* @__PURE__ */ jsx(PollarOverlay, { style: overlayStyle, onClick: onClose, children: /* @__PURE__ */ jsx(
13359
14173
  WalletBalanceModalTemplate,
13360
14174
  {
13361
14175
  theme,
@@ -13486,6 +14300,7 @@ var PollarContext = createContext(null);
13486
14300
  var clientByConfig = /* @__PURE__ */ new WeakMap();
13487
14301
  function PollarProvider({
13488
14302
  client,
14303
+ language,
13489
14304
  appConfig: appConfigProp,
13490
14305
  adapters,
13491
14306
  onStorageDegrade,
@@ -13647,6 +14462,13 @@ function PollarProvider({
13647
14462
  const [kycModalOpen, setKycModalOpen] = useState(false);
13648
14463
  const [kycModalOptions, setKycModalOptions] = useState({});
13649
14464
  const [rampModalOpen, setRampModalOpen] = useState(false);
14465
+ const [rampSeed, seedRamp] = useModalOptions();
14466
+ const [receiveSeed, seedReceive] = useModalOptions();
14467
+ const [txHistorySeed, seedTxHistory] = useModalOptions();
14468
+ const [sendModalOptions, setSendModalOptions] = useState(void 0);
14469
+ const [swapModalOptions, setSwapModalOptions] = useState(void 0);
14470
+ const [earnModalOptions, setEarnModalOptions] = useState(void 0);
14471
+ const [cardModalOptions, setCardModalOptions] = useState(void 0);
13650
14472
  const [txHistoryModalOpen, setTxHistoryModalOpen] = useState(false);
13651
14473
  const [walletBalanceModalOpen, setWalletBalanceModalOpen] = useState(false);
13652
14474
  const [enabledAssetsModalOpen, setEnabledAssetsModalOpen] = useState(false);
@@ -13655,6 +14477,9 @@ function PollarProvider({
13655
14477
  const [earnModalOpen, setEarnModalOpen] = useState(false);
13656
14478
  const [sendModalKey, setSendModalKey] = useState(0);
13657
14479
  const [swapModalKey, setSwapModalKey] = useState(0);
14480
+ const [bridgeModalOpen, setBridgeModalOpen] = useState(false);
14481
+ const [bridgeModalKey, setBridgeModalKey] = useState(0);
14482
+ const [bridgeModalOptions, setBridgeModalOptions] = useState(void 0);
13658
14483
  const [earnModalKey, setEarnModalKey] = useState(0);
13659
14484
  const [cardModalOpen, setCardModalOpen] = useState(false);
13660
14485
  const [cardModalKey, setCardModalKey] = useState(0);
@@ -13668,6 +14493,7 @@ function PollarProvider({
13668
14493
  if (cosign.pending.length > cosignPendingCount.current) setCosignModalOpen(true);
13669
14494
  cosignPendingCount.current = cosign.pending.length;
13670
14495
  }, [cosign.pending.length]);
14496
+ useEffect(() => pollarClient.onCosignDeviceNotEnrolled(() => setRecoveryModalOpen(true)), [pollarClient]);
13671
14497
  const [distributionRulesModalOpen, setDistributionRulesModalOpen] = useState(false);
13672
14498
  useEffect(
13673
14499
  () => pollarClient.onAuthStateChange((authState) => {
@@ -13680,6 +14506,7 @@ function PollarProvider({
13680
14506
  setEnabledAssetsModalOpen(false);
13681
14507
  setSendModalOpen(false);
13682
14508
  setSwapModalOpen(false);
14509
+ setBridgeModalOpen(false);
13683
14510
  setEarnModalOpen(false);
13684
14511
  setCardModalOpen(false);
13685
14512
  setReceiveModalOpen(false);
@@ -13763,7 +14590,10 @@ function PollarProvider({
13763
14590
  openTxModal: () => setTransactionModalOpen(true),
13764
14591
  // tx history
13765
14592
  txHistory,
13766
- openTxHistoryModal: () => setTxHistoryModalOpen(true),
14593
+ openTxHistoryModal: (options) => {
14594
+ seedTxHistory(options);
14595
+ setTxHistoryModalOpen(true);
14596
+ },
13767
14597
  // wallet balance
13768
14598
  walletBalance,
13769
14599
  refreshWalletBalance,
@@ -13774,12 +14604,16 @@ function PollarProvider({
13774
14604
  setTrustline: (asset, opts) => pollarClient.setTrustline(asset, opts),
13775
14605
  openEnabledAssetsModal: () => setEnabledAssetsModalOpen(true),
13776
14606
  // send / receive
13777
- openSendModal: () => {
14607
+ openSendModal: (options) => {
14608
+ setSendModalOptions(options);
13778
14609
  pollarClient.resetTransactionState();
13779
14610
  setSendModalKey((k) => k + 1);
13780
14611
  setSendModalOpen(true);
13781
14612
  },
13782
- openReceiveModal: () => setReceiveModalOpen(true),
14613
+ openReceiveModal: (options) => {
14614
+ seedReceive(options);
14615
+ setReceiveModalOpen(true);
14616
+ },
13783
14617
  // swap
13784
14618
  getSwapConfig: () => pollarClient.getSwapConfig(),
13785
14619
  getSwapTokens: () => pollarClient.getSwapTokens(),
@@ -13788,24 +14622,32 @@ function PollarProvider({
13788
14622
  getSolanaSwapConfig: () => pollarClient.getSolanaSwapConfig(),
13789
14623
  getSolanaSwapQuote: (params) => pollarClient.getSolanaSwapQuote(params),
13790
14624
  swapSolana: (quote, opts) => pollarClient.swapSolana(quote, opts),
13791
- openSwapModal: () => {
14625
+ openSwapModal: (options) => {
14626
+ setSwapModalOptions(options);
13792
14627
  pollarClient.resetTransactionState();
13793
14628
  setSwapModalKey((k) => k + 1);
13794
14629
  setSwapModalOpen(true);
13795
14630
  },
14631
+ openBridgeModal: (options) => {
14632
+ setBridgeModalOptions(options);
14633
+ setBridgeModalKey((k) => k + 1);
14634
+ setBridgeModalOpen(true);
14635
+ },
13796
14636
  // earn
13797
14637
  getEarnProviders: () => pollarClient.getEarnProviders(),
13798
14638
  getEarnOpportunities: (provider) => pollarClient.getEarnOpportunities(provider),
13799
14639
  getEarnPosition: (params) => pollarClient.getEarnPosition(params),
13800
14640
  earnDeposit: (params) => pollarClient.earnDeposit(params),
13801
14641
  earnWithdraw: (params) => pollarClient.earnWithdraw(params),
13802
- openEarnModal: () => {
14642
+ openEarnModal: (options) => {
14643
+ setEarnModalOptions(options);
13803
14644
  pollarClient.resetTransactionState();
13804
14645
  setEarnModalKey((k) => k + 1);
13805
14646
  setEarnModalOpen(true);
13806
14647
  },
13807
14648
  // cards
13808
- openCardModal: () => {
14649
+ openCardModal: (options) => {
14650
+ setCardModalOptions(options);
13809
14651
  setCardModalKey((k) => k + 1);
13810
14652
  setCardModalOpen(true);
13811
14653
  },
@@ -13834,7 +14676,10 @@ function PollarProvider({
13834
14676
  setKycModalOpen(true);
13835
14677
  },
13836
14678
  // ramp
13837
- openRampModal: () => setRampModalOpen(true),
14679
+ openRampModal: (options) => {
14680
+ seedRamp(options);
14681
+ setRampModalOpen(true);
14682
+ },
13838
14683
  // config
13839
14684
  appConfig: resolvedConfig,
13840
14685
  styles,
@@ -13869,7 +14714,7 @@ function PollarProvider({
13869
14714
  retryConfig,
13870
14715
  adapters
13871
14716
  ]);
13872
- const modalLanguage = useProviderLanguage(pollarClient, contextValue.styles?.language);
14717
+ const modalLanguage = useProviderLanguage(pollarClient, contextValue.styles?.language, language);
13873
14718
  return /* @__PURE__ */ jsx(PollarContext.Provider, { value: contextValue, children: /* @__PURE__ */ jsxs(ModalLanguageContext.Provider, { value: modalLanguage, children: [
13874
14719
  children,
13875
14720
  loginModalOpen && /* @__PURE__ */ jsx(ModalErrorBoundary, { onClose: () => setLoginModalOpen(false), children: /* @__PURE__ */ jsx(LoginModal, { onClose: () => setLoginModalOpen(false) }) }),
@@ -13896,16 +14741,17 @@ function PollarProvider({
13896
14741
  ...kycModalOptions.onApproved !== void 0 && { onApproved: kycModalOptions.onApproved }
13897
14742
  }
13898
14743
  ) }),
13899
- rampModalOpen && /* @__PURE__ */ jsx(ModalErrorBoundary, { onClose: () => setRampModalOpen(false), children: /* @__PURE__ */ jsx(RampWidget, { onClose: () => setRampModalOpen(false) }) }),
13900
- txHistoryModalOpen && /* @__PURE__ */ jsx(ModalErrorBoundary, { onClose: () => setTxHistoryModalOpen(false), children: /* @__PURE__ */ jsx(TxHistoryModal, { onClose: () => setTxHistoryModalOpen(false) }) }),
14744
+ rampModalOpen && /* @__PURE__ */ jsx(ModalErrorBoundary, { onClose: () => setRampModalOpen(false), children: /* @__PURE__ */ jsx(RampWidget, { onClose: () => setRampModalOpen(false), initial: rampSeed.options }) }, `ramp:${rampSeed.key}`),
14745
+ txHistoryModalOpen && /* @__PURE__ */ jsx(ModalErrorBoundary, { onClose: () => setTxHistoryModalOpen(false), children: /* @__PURE__ */ jsx(TxHistoryModal, { onClose: () => setTxHistoryModalOpen(false), initial: txHistorySeed.options }) }, `history:${txHistorySeed.key}`),
13901
14746
  walletBalanceModalOpen && /* @__PURE__ */ jsx(ModalErrorBoundary, { onClose: () => setWalletBalanceModalOpen(false), children: /* @__PURE__ */ jsx(WalletBalanceModal, { onClose: () => setWalletBalanceModalOpen(false) }) }),
13902
14747
  enabledAssetsModalOpen && /* @__PURE__ */ jsx(ModalErrorBoundary, { onClose: () => setEnabledAssetsModalOpen(false), children: /* @__PURE__ */ jsx(EnabledAssetsModal, { onClose: () => setEnabledAssetsModalOpen(false) }) }),
13903
- sendModalOpen && /* @__PURE__ */ jsx(ModalErrorBoundary, { onClose: () => setSendModalOpen(false), children: /* @__PURE__ */ jsx(SendModal, { onClose: () => setSendModalOpen(false) }) }, sendModalKey),
13904
- swapModalOpen && /* @__PURE__ */ jsx(ModalErrorBoundary, { onClose: () => setSwapModalOpen(false), children: /* @__PURE__ */ jsx(SwapModal, { onClose: () => setSwapModalOpen(false) }) }, swapModalKey),
13905
- earnModalOpen && /* @__PURE__ */ jsx(ModalErrorBoundary, { onClose: () => setEarnModalOpen(false), children: /* @__PURE__ */ jsx(EarnModal, { onClose: () => setEarnModalOpen(false) }) }, earnModalKey),
14748
+ sendModalOpen && /* @__PURE__ */ jsx(ModalErrorBoundary, { onClose: () => setSendModalOpen(false), children: /* @__PURE__ */ jsx(SendModal, { onClose: () => setSendModalOpen(false), initial: sendModalOptions }) }, `send:${sendModalKey}`),
14749
+ swapModalOpen && /* @__PURE__ */ jsx(ModalErrorBoundary, { onClose: () => setSwapModalOpen(false), children: /* @__PURE__ */ jsx(SwapModal, { onClose: () => setSwapModalOpen(false), initial: swapModalOptions }) }, `swap:${swapModalKey}`),
14750
+ bridgeModalOpen && /* @__PURE__ */ jsx(ModalErrorBoundary, { onClose: () => setBridgeModalOpen(false), children: /* @__PURE__ */ jsx(BridgeModal, { onClose: () => setBridgeModalOpen(false), initial: bridgeModalOptions }) }, bridgeModalKey),
14751
+ earnModalOpen && /* @__PURE__ */ jsx(ModalErrorBoundary, { onClose: () => setEarnModalOpen(false), children: /* @__PURE__ */ jsx(EarnModal, { onClose: () => setEarnModalOpen(false), initial: earnModalOptions }) }, `earn:${earnModalKey}`),
13906
14752
  cardModalOpen && // Keyed by the wallet too: a different user, or signing in with it open, starts it from scratch.
13907
- /* @__PURE__ */ jsx(ModalErrorBoundary, { onClose: () => setCardModalOpen(false), children: /* @__PURE__ */ jsx(CardModal, { onClose: () => setCardModalOpen(false) }) }, `${cardModalKey}:${walletAddress}`),
13908
- receiveModalOpen && /* @__PURE__ */ jsx(ModalErrorBoundary, { onClose: () => setReceiveModalOpen(false), children: /* @__PURE__ */ jsx(ReceiveModal, { onClose: () => setReceiveModalOpen(false) }) }),
14753
+ /* @__PURE__ */ jsx(ModalErrorBoundary, { onClose: () => setCardModalOpen(false), children: /* @__PURE__ */ jsx(CardModal, { onClose: () => setCardModalOpen(false), initial: cardModalOptions }) }, `${cardModalKey}:${walletAddress}`),
14754
+ receiveModalOpen && /* @__PURE__ */ jsx(ModalErrorBoundary, { onClose: () => setReceiveModalOpen(false), children: /* @__PURE__ */ jsx(ReceiveModal, { onClose: () => setReceiveModalOpen(false), initial: receiveSeed.options }) }, `receive:${receiveSeed.key}`),
13909
14755
  sessionsModalOpen && /* @__PURE__ */ jsx(ModalErrorBoundary, { onClose: () => setSessionsModalOpen(false), children: /* @__PURE__ */ jsx(SessionsModal, { onClose: () => setSessionsModalOpen(false) }) }),
13910
14756
  cosignModalOpen && /* @__PURE__ */ jsx(ModalErrorBoundary, { onClose: () => setCosignModalOpen(false), children: /* @__PURE__ */ jsx(CosignModal, { nextStep: cosignNextStep, onClose: () => setCosignModalOpen(false) }) }),
13911
14757
  custodyMigration?.required && !custodyMigrationLater && /* @__PURE__ */ jsx(ModalErrorBoundary, { onClose: refreshCustodyMigration, children: /* @__PURE__ */ jsx(
@@ -14719,6 +15565,6 @@ function WalletButton() {
14719
15565
  );
14720
15566
  }
14721
15567
 
14722
- export { CardModal, ChainSelect, CosignModal, CosignModalTemplate, CustodyMigrationModal, CustodyMigrationModalTemplate, DistributionRulesModal, DistributionRulesModalTemplate, EarnModal, EnabledAssetsModal, EnabledAssetsModalTemplate, KycModal, KycModalTemplate, KycStatus, LoginModalTemplate, PollarProvider, ProviderRegistrationModal, RampWidget, RampWidgetTemplate, ReceiveModal, ReceiveModalTemplate, RecoveryModal, RecoveryModalTemplate, RegistryCheckModal, RejectedRouteDisplay, RequirementFormModal, RouteDisplay, SendModal, SendModalTemplate, SessionsModal, SessionsModalTemplate, SwapModal, SwapModalTemplate, TransactionModalTemplate, TxHistoryModalTemplate, TxStatusView, WalletBalanceModal, WalletBalanceModalTemplate, WalletButton, WalletButtonTemplate, addressForChain, browserPasskeyCeremony, browserPasskeySigner, browserRecoveryPasskey, buildModalCssVars, chainsOf, createPollarAdapterHook, modalChrome, readableTextOn, resolveChain, useChains, useCosign, usePollar, walletNotReadyReason };
15568
+ export { BridgeModal, BridgeModalTemplate, CardModal, ChainSelect, CosignModal, CosignModalTemplate, CustodyMigrationModal, CustodyMigrationModalTemplate, DistributionRulesModal, DistributionRulesModalTemplate, EarnModal, EnabledAssetsModal, EnabledAssetsModalTemplate, KycModal, KycModalTemplate, KycStatus, LoginModalTemplate, PollarProvider, ProviderRegistrationModal, RampWidget, RampWidgetTemplate, ReceiveModal, ReceiveModalTemplate, RecoveryModal, RecoveryModalTemplate, RegistryCheckModal, RejectedRouteDisplay, RequirementFormModal, RouteDisplay, SendModal, SendModalTemplate, SessionsModal, SessionsModalTemplate, SwapModal, SwapModalTemplate, TransactionModalTemplate, TxHistoryModalTemplate, TxStatusView, WalletBalanceModal, WalletBalanceModalTemplate, WalletButton, WalletButtonTemplate, addressForChain, browserPasskeyCeremony, browserPasskeySigner, browserRecoveryPasskey, buildModalCssVars, chainsOf, createPollarAdapterHook, modalChrome, readableTextOn, resolveChain, useChains, useCosign, usePollar, walletNotReadyReason };
14723
15569
  //# sourceMappingURL=index.mjs.map
14724
15570
  //# sourceMappingURL=index.mjs.map