@glacislabs/stablegenie-zerodelta 4.11.0 → 4.13.0

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.
@@ -1,5 +1,5 @@
1
- import { CHAIN_DISPLAY_NAMES, EXECUTABLE_STABLE_ASSETS, STABLE_ASSETS, SUPPORTED_ASSETS, complianceView, complianceTagOf, symbolKey, normalizeDecimalText, findToken, laneLimitFor, laneLimitSymbol, tokenTicker, exceedsLaneLimit, assetDecimals, parseUnitsDecimal, counterpartTokens, assetClassOf, brokenLaneFor, brokenLaneReason, destinationAvailability, laneLimitHint, tickerOn, laneLimitError, routeNativeValue, formatNative, nativeSymbol, amountFieldError, SUPPORTED_CHAIN_IDS, formatUnits, complianceChecks, DIRECT_CHECK_IDS, createEngine, checkNativeFee, nativeFeeShortLabel, nativeFeeShortMessage, allowanceCovers, validatePlannedTransaction, foldTicker, unattributedComplianceReasons, distinctScreenedWallets, formatJurisdiction, humanizeComplianceReason, DIRECT_SCOPE_NOTE, categoryLabel, SCREENING_BUCKETS, BUNDLED_RPC } from './chunk-5WTRI2KO.js';
2
- import { createContext, useState, useRef, useMemo, useEffect, useCallback, useId, createElement, useContext, useSyncExternalStore, useLayoutEffect, useReducer } from 'react';
1
+ import { CHAIN_DISPLAY_NAMES, EXECUTABLE_STABLE_ASSETS, STABLE_ASSETS, SUPPORTED_ASSETS, complianceView, complianceTagOf, symbolKey, normalizeDecimalText, findToken, laneLimitFor, laneLimitSymbol, tokenTicker, exceedsLaneLimit, assetDecimals, parseUnitsDecimal, counterpartTokens, assetClassOf, brokenLaneFor, brokenLaneReason, destinationAvailability, laneLimitHint, tickerOn, laneLimitError, routeNativeValue, formatNative, nativeSymbol, isSolanaChainId, formatUnits, amountFieldError, SUPPORTED_CHAIN_IDS, complianceChecks, DIRECT_CHECK_IDS, isSolanaAddress, createEngine, isAddress, checkNativeFee, nativeFeeShortLabel, nativeFeeShortMessage, allowanceCovers, validatePlannedTransaction, solanaPlanNeedsPreparation, SOLANA_CHAIN_ID, unattributedComplianceReasons, distinctScreenedWallets, formatJurisdiction, humanizeComplianceReason, DIRECT_SCOPE_NOTE, categoryLabel, SCREENING_BUCKETS, BUNDLED_RPC, foldTicker } from './chunk-52MY5D3D.js';
2
+ import { createContext, useState, useRef, useMemo, useEffect, useCallback, useId, createElement, useContext, useLayoutEffect, useSyncExternalStore, useReducer } from 'react';
3
3
  import { createRoot } from 'react-dom/client';
4
4
  import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
5
5
 
@@ -952,46 +952,79 @@ img.sg-tok-badge{width:16px;padding:0;object-fit:cover;background:var(--sg-bg)}
952
952
  .sg-pct:hover:not(:disabled){color:var(--sg-accent)}
953
953
  .sg-pct:disabled{opacity:.55;cursor:not-allowed}
954
954
 
955
- /* full-panel token selector (Exchange from / Exchange to) */
955
+ /* full-panel takeover head (transaction history) */
956
956
  .sg-sel-head{display:flex;align-items:center;margin-bottom:14px}
957
957
  .sg-back{width:32px;height:32px;flex:0 0 auto;border:none;border-radius:999px;background:transparent;color:var(--sg-text);cursor:pointer;font:inherit;display:flex;align-items:center;justify-content:center;transition:background 120ms ease}
958
958
  .sg-back:hover{background:var(--sg-surface)}
959
959
  .sg-sel-title{flex:1 1 auto;min-width:0;text-align:center;font-size:15px;font-weight:600;margin-right:32px}
960
960
  /* Whose transactions these are \u2014 history is per wallet, and the takeover hides the header's pill. */
961
961
  .sg-sel-sub{display:block;font-size:11px;font-weight:600;color:var(--sg-text-muted);margin-top:1px}
962
- /* Scrolls at ~2.5 rows. The catalogue's destination chains outnumber its source chains three to one
963
- (9 escrow chains, ~37 total), so an ungated grid was eight rows tall and pushed the token list \u2014
964
- the thing the panel exists for \u2014 below the fold. The fade is a scroll affordance, not decoration. */
965
- .sg-chain-grid{display:grid;grid-template-columns:repeat(5,1fr);gap:8px;margin-bottom:12px;max-height:124px;overflow-y:auto;scrollbar-width:thin;padding-bottom:2px;mask-image:linear-gradient(to bottom,#000 calc(100% - 14px),transparent);-webkit-mask-image:linear-gradient(to bottom,#000 calc(100% - 14px),transparent)}
966
- /* No mask once everything fits \u2014 a fade under a grid with nothing below it reads as a rendering bug. */
967
- .sg-chain-grid[data-scroll="false"]{mask-image:none;-webkit-mask-image:none;overflow-y:visible;max-height:none}
968
- .sg-chain-chip{height:44px;border-radius:var(--sg-radius-control);border:1px solid var(--sg-border);background:var(--sg-surface);color:var(--sg-text);display:flex;align-items:center;justify-content:center;cursor:pointer;font:inherit;font-size:10px;font-weight:700;letter-spacing:.02em;transition:border-color 120ms ease,background 120ms ease;overflow:hidden}
969
- .sg-chain-chip img{width:22px;height:22px;border-radius:999px;display:block}
970
- .sg-chain-chip:hover{border-color:color-mix(in srgb,var(--sg-accent) 45%,var(--sg-border))}
971
- .sg-chain-chip[data-selected="true"]{border-color:var(--sg-accent);background:color-mix(in srgb,var(--sg-accent) 10%,var(--sg-surface))}
972
- .sg-search{position:relative;margin-bottom:10px}
973
- .sg-search svg{position:absolute;left:12px;top:50%;transform:translateY(-50%);color:var(--sg-text-muted);pointer-events:none}
974
- .sg-search input{width:100%;padding:11px 12px 11px 38px;background:var(--sg-surface);color:var(--sg-text);border:1px solid var(--sg-border);border-radius:var(--sg-radius-control);font:inherit;font-size:14px;outline:none;transition:border-color 120ms ease}
975
- .sg-search input:focus{border-color:var(--sg-accent)}
976
962
  .sg-toklist{display:flex;flex-direction:column;gap:2px;max-height:320px;overflow-y:auto;margin:0 -6px;padding:0 6px;scrollbar-width:thin}
977
- .sg-tokrow{display:flex;align-items:center;gap:12px;padding:10px 8px;border:none;border-radius:var(--sg-radius-control);background:transparent;color:var(--sg-text);cursor:pointer;font:inherit;text-align:left;transition:background 120ms ease}
978
- .sg-tokrow:hover{background:var(--sg-surface)}
979
- .sg-tokrow-main{flex:1 1 auto;min-width:0}
980
- .sg-tokrow-sym{display:block;font-size:15px;font-weight:700;line-height:1.2}
981
- .sg-tokrow-name{display:block;font-size:12px;color:var(--sg-text-muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
982
- .sg-tokrow-end{flex:0 0 auto;text-align:right}
983
- .sg-tokrow-bal{display:block;font-size:13px;font-weight:600;font-variant-numeric:tabular-nums}
984
- .sg-tokrow-chain{display:block;font-size:11px;color:var(--sg-text-muted)}
985
- /* funding rows the wallet can't cover (zero / insufficient): greyed, non-interactive, reason hint.
986
- Mirrors RouteList's data-short dim + warn tone; no hover lift. Theme-aware via --sg-* vars. */
987
- .sg-tokrow--off,.sg-tokrow[disabled]{opacity:.5;cursor:not-allowed}
988
- .sg-tokrow--off:hover,.sg-tokrow[disabled]:hover{background:transparent}
989
- .sg-tokrow--off .sg-tokrow-sym,.sg-tokrow--off .sg-tokrow-name,.sg-tokrow--off .sg-tokrow-bal{color:var(--sg-text-muted)}
990
- .sg-tokrow-hint{display:block;font-size:11px;font-weight:600;color:var(--sg-danger)}
991
- /* on a row that stays selectable (a limited lane): a caveat, not a refusal */
992
- .sg-tokrow-hint[data-tone="note"]{color:var(--sg-text-muted)}
993
963
  .sg-sel-empty{padding:26px 10px;text-align:center;font-size:13px;color:var(--sg-text-muted)}
994
964
 
965
+ /* Token picker, token first then network \u2014 the ZeroDelta dapp's TokenSelectModal (Figma 708:27430,
966
+ 2517:52576), drawn in the widget's own theme: the dapp's brand tint is the accent, its green the
967
+ success token. Geometry is the dapp's: 32px plates, 24px row plates, 16px chain marks, 20px gaps. The list keeps
968
+ the previous picker's 320px cap so opening it does not grow the card. */
969
+ .sg-pk{display:flex;flex-direction:column;gap:20px}
970
+ .sg-pk-head{display:flex;align-items:center;justify-content:space-between;gap:8px}
971
+ .sg-pk-title{font-family:var(--sg-font-display);font-size:16px;font-weight:600;line-height:1.2;letter-spacing:.32px;color:var(--sg-t90)}
972
+ .sg-pk-close,.sg-pk-clear{display:grid;place-items:center;flex:0 0 auto;padding:6px;border:none;border-radius:8px;background:transparent;color:var(--sg-text-muted);cursor:pointer}
973
+ .sg-pk-clear{padding:2px}
974
+ .sg-pk-close:hover,.sg-pk-clear:hover{color:var(--sg-text)}
975
+ .sg-pk-backlink{display:flex;align-items:center;gap:10px;padding:0;border:none;border-radius:8px;background:transparent;color:var(--sg-t60);font:inherit;font-size:16px;font-weight:500;line-height:1.2;cursor:pointer}
976
+ .sg-pk-backlink:hover{color:var(--sg-text)}
977
+ .sg-pk-intro{display:flex;flex-direction:column;gap:4px}
978
+ .sg-pk-lead{margin:0;font-size:14px;line-height:1.3;color:var(--sg-text-muted)}
979
+ .sg-pk-search{display:flex;align-items:center;gap:16px;width:100%;padding:16px;border:1px solid color-mix(in srgb,var(--sg-accent) 12%,transparent);border-radius:16px;background:var(--sg-surface);color:var(--sg-text-muted);cursor:text;transition:border-color 120ms ease}
980
+ .sg-pk-search:focus-within{border-color:var(--sg-accent);color:var(--sg-accent)}
981
+ .sg-pk-search input{flex:1 1 auto;min-width:0;padding:0;border:none;background:transparent;color:var(--sg-t90);font:inherit;font-size:15px;line-height:1.2;outline:none}
982
+ .sg-pk-search input::placeholder{color:var(--sg-text-muted)}
983
+ .sg-pk-body{display:flex;flex-direction:column;gap:8px}
984
+ .sg-pk-selected{display:flex;flex-direction:column;gap:8px;margin-bottom:8px}
985
+ .sg-pk-cap{margin:0;font-size:12px;line-height:1.2;color:var(--sg-text-muted)}
986
+ .sg-pk-list{display:flex;flex-direction:column;gap:4px;max-height:320px;overflow-y:auto;margin:-1px;padding:1px;scrollbar-width:thin}
987
+ .sg-pk-row{display:flex;align-items:center;justify-content:space-between;gap:12px;width:100%;padding:16px;border:none;border-radius:24px;background:color-mix(in srgb,var(--sg-accent) 4%,transparent);color:var(--sg-text);font:inherit;text-align:left;cursor:pointer;transition:background 120ms ease}
988
+ .sg-pk-row:hover{background:color-mix(in srgb,var(--sg-accent) 8%,transparent)}
989
+ .sg-pk-row--net{padding:20px 16px}
990
+ .sg-pk-row[data-zero]{background:color-mix(in srgb,var(--sg-text) 4%,transparent)}
991
+ .sg-pk-row[data-zero]:hover{background:color-mix(in srgb,var(--sg-accent) 4%,transparent)}
992
+ .sg-pk-row[data-selected]{background:color-mix(in srgb,var(--sg-success) 6%,transparent)}
993
+ .sg-pk-row[data-selected]:hover{background:color-mix(in srgb,var(--sg-success) 8%,transparent)}
994
+ .sg-pk-row--off{opacity:.6;cursor:default}
995
+ .sg-pk-row--off:hover{background:color-mix(in srgb,var(--sg-accent) 4%,transparent)}
996
+ .sg-pk-row:focus-visible,.sg-pk-close:focus-visible,.sg-pk-backlink:focus-visible,.sg-pk-clear:focus-visible{outline:2px solid color-mix(in srgb,var(--sg-accent) 30%,transparent);outline-offset:2px}
997
+ .sg-pk-left{display:flex;align-items:center;gap:12px;flex:1 1 auto;min-width:0}
998
+ .sg-pk-text{display:flex;flex-direction:column;align-items:flex-start;gap:2px;flex:1 1 auto;min-width:0;overflow:hidden}
999
+ .sg-pk-label{font-size:16px;font-weight:500;line-height:1.2;color:var(--sg-t90);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:100%}
1000
+ .sg-pk-alt{margin-left:8px;font-size:14px;font-weight:400;color:var(--sg-text-muted)}
1001
+ .sg-pk-line{display:flex;align-items:center;gap:4px;min-width:0;max-width:100%}
1002
+ .sg-pk-sub{flex:0 1 auto;font-size:14px;line-height:1.3;color:var(--sg-text-muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;min-width:0}
1003
+ .sg-pk-note{font-size:13px;line-height:1.3;color:var(--sg-text-muted)}
1004
+ .sg-pk-plate,.sg-pk-chainwrap{position:relative;display:grid;place-items:center;flex:0 0 auto;width:32px;height:32px}
1005
+ .sg-pk-plate-in{display:grid;place-items:center;width:32px;height:32px;overflow:hidden;border-radius:16px;background:var(--sg-surface)}
1006
+ .sg-pk-plate-in img{width:32px;height:32px;display:block;object-fit:cover}
1007
+ .sg-pk-plate-fb{font-size:10px;font-weight:700;color:var(--sg-accent)}
1008
+ .sg-pk-plate[data-muted] .sg-pk-plate-in{filter:grayscale(1)}
1009
+ .sg-pk-tick{position:absolute;right:-1px;bottom:-1px;display:grid;place-items:center;width:14px;height:14px;border-radius:999px;background:var(--sg-surface);color:var(--sg-success)}
1010
+ .sg-pk-chain{display:grid;place-items:center;width:32px;height:32px;overflow:hidden;border-radius:999px;background:var(--sg-surface);font-size:9px;font-weight:700;color:var(--sg-text-muted)}
1011
+ .sg-pk-chain img{width:32px;height:32px;display:block;object-fit:cover}
1012
+ .sg-pk-marks{display:flex;align-items:center;gap:4px;flex:0 0 auto}
1013
+ .sg-pk-stack{display:flex;align-items:center;height:18px}
1014
+ .sg-pk-markwrap{display:grid;flex:0 0 auto}
1015
+ .sg-pk-markwrap+.sg-pk-markwrap{margin-left:-2px}
1016
+ .sg-pk-mark{display:grid;place-items:center;width:16px;height:16px;overflow:hidden;border-radius:999px;background:var(--sg-surface);font-size:5px;font-weight:700;color:var(--sg-text-muted)}
1017
+ .sg-pk-mark img{width:16px;height:16px;display:block;object-fit:cover}
1018
+ .sg-pk-more{font-size:14px;line-height:1.3;color:var(--sg-text-muted)}
1019
+ .sg-pk-chev{display:grid;place-items:center;flex:0 0 auto;width:16px;height:16px;color:var(--sg-text-muted)}
1020
+ .sg-pk-chev svg{width:16px;height:16px}
1021
+ .sg-pk-chev--sm,.sg-pk-chev--sm svg{width:14px;height:14px}
1022
+ .sg-pk-bal{display:flex;flex-direction:column;align-items:flex-end;justify-content:center;gap:4px;min-height:36px;flex:0 0 auto;text-align:right}
1023
+ .sg-pk-bal-usd{font-size:16px;font-weight:500;line-height:1.2;color:var(--sg-t90)}
1024
+ .sg-pk-bal-amt{font-size:13px;line-height:1.4;color:var(--sg-text-muted)}
1025
+ .sg-pk-bal-zero{flex:0 0 auto;font-size:16px;font-weight:700;color:var(--sg-t35)}
1026
+ .sg-pk-empty{margin:0;padding:32px 0;text-align:center;font-size:14px;color:var(--sg-text-muted)}
1027
+
995
1028
  /* wide (duo) layout: main card + receive/routes side card. The collapse is keyed to the WIDGET'S
996
1029
  OWN available width (container query) \u2014 an embedded widget cannot infer the host layout from the
997
1030
  viewport. The viewport media query stays as a fallback for engines without container queries. */
@@ -1778,7 +1811,7 @@ function RouteList(props) {
1778
1811
  visible.map((r) => {
1779
1812
  const selected = props.selectedId === r.id;
1780
1813
  const bal = props.balances?.[routeBalanceKey(r)];
1781
- const short = props.shortIds?.has(r.id) ?? false;
1814
+ const short2 = props.shortIds?.has(r.id) ?? false;
1782
1815
  const held = props.heldIds?.has(r.id) ?? false;
1783
1816
  return (
1784
1817
  // a11y note: a native radio cannot contain the rich
@@ -1790,7 +1823,7 @@ function RouteList(props) {
1790
1823
  {
1791
1824
  className: "sg-route-item",
1792
1825
  "data-selected": selected,
1793
- "data-short": short || void 0,
1826
+ "data-short": short2 || void 0,
1794
1827
  "data-held": held || void 0,
1795
1828
  role: "radio",
1796
1829
  "aria-checked": selected,
@@ -1825,7 +1858,7 @@ function RouteList(props) {
1825
1858
  "bal ",
1826
1859
  bal.formatted
1827
1860
  ] }) : null,
1828
- short ? /* @__PURE__ */ jsx("span", { className: "sg-badge", "data-tone": "warn", children: "Short" }) : r.state === "DIRECT" ? /* @__PURE__ */ jsx("span", { className: "sg-badge", "data-tone": "ok", children: "Direct" }) : r.recommended ? /* @__PURE__ */ jsx("span", { className: "sg-badge", "data-tone": "accent", children: "Best" }) : null,
1861
+ short2 ? /* @__PURE__ */ jsx("span", { className: "sg-badge", "data-tone": "warn", children: "Short" }) : r.state === "DIRECT" ? /* @__PURE__ */ jsx("span", { className: "sg-badge", "data-tone": "ok", children: "Direct" }) : r.recommended ? /* @__PURE__ */ jsx("span", { className: "sg-badge", "data-tone": "accent", children: "Best" }) : null,
1829
1862
  /* @__PURE__ */ jsx("span", { className: "sg-radio", "aria-hidden": "true" })
1830
1863
  ] })
1831
1864
  ]
@@ -1938,6 +1971,200 @@ function chainLogoCandidates(chainId, logoUrl) {
1938
1971
  if (bundled) out.push(bundled);
1939
1972
  return out;
1940
1973
  }
1974
+
1975
+ // src/react/ui/tokenGroups.ts
1976
+ var rowKey = (t) => `${Number(t.chainId)}:${String(t.address || "").toLowerCase()}`;
1977
+ var CHAIN_TVL_ORDER = [
1978
+ 1,
1979
+ 1151111081099710,
1980
+ 8453,
1981
+ 56,
1982
+ 42161,
1983
+ 999,
1984
+ 143,
1985
+ 4663,
1986
+ 137,
1987
+ 9745,
1988
+ 43114,
1989
+ 10,
1990
+ 196,
1991
+ 57073,
1992
+ 14,
1993
+ 5e3,
1994
+ 2818,
1995
+ 30,
1996
+ 4217,
1997
+ 747474,
1998
+ 1672,
1999
+ 988,
2000
+ 480,
2001
+ 81457,
2002
+ 1329,
2003
+ 80094,
2004
+ 130,
2005
+ 4326,
2006
+ 59144,
2007
+ 2222,
2008
+ 252,
2009
+ 146,
2010
+ 324,
2011
+ 1776,
2012
+ 534352,
2013
+ 1030,
2014
+ 1868,
2015
+ 98866,
2016
+ 169,
2017
+ 1088,
2018
+ 50,
2019
+ 34443,
2020
+ 1135,
2021
+ 88,
2022
+ 48900,
2023
+ 151,
2024
+ 7777777,
2025
+ 1923,
2026
+ 3343,
2027
+ 81224,
2028
+ 21e6
2029
+ ];
2030
+ var TOKEN_MARKET_CAP_ORDER = ["USDT", "USDC", "USDS", "DAI", "USDE", "USD1", "USDG", "PYUSD", "XAUT", "RLUSD", "USDF", "GHO", "USD0", "USDTB", "AUSD", "WM"];
2031
+ var CHAIN_RANK = new Map(CHAIN_TVL_ORDER.map((chainId, index) => [chainId, index]));
2032
+ var TOKEN_RANK = new Map(TOKEN_MARKET_CAP_ORDER.map((symbol, index) => [symbol, index]));
2033
+ function chainTvlRank(chainId) {
2034
+ return CHAIN_RANK.get(Number(chainId)) ?? CHAIN_TVL_ORDER.length;
2035
+ }
2036
+ function tokenMarketCapRank(symbol) {
2037
+ return TOKEN_RANK.get(String(symbol).toUpperCase()) ?? TOKEN_MARKET_CAP_ORDER.length;
2038
+ }
2039
+ function dominantSymbol(tokens) {
2040
+ const counts = /* @__PURE__ */ new Map();
2041
+ for (const t of tokens) counts.set(t.symbol, (counts.get(t.symbol) ?? 0) + 1);
2042
+ let best = tokens[0].symbol;
2043
+ for (const [symbol, count] of counts) if (count > (counts.get(best) ?? 0)) best = symbol;
2044
+ return best;
2045
+ }
2046
+ function priceOf(prices, symbol) {
2047
+ const p = prices?.[String(symbol).toUpperCase()];
2048
+ return typeof p === "number" && Number.isFinite(p) ? p : void 0;
2049
+ }
2050
+ function buildGroup(key, members, prices) {
2051
+ const tokens = members.map((m) => m.token);
2052
+ let amount = null;
2053
+ let usd = null;
2054
+ for (const m of members) {
2055
+ if (m.balance == null) continue;
2056
+ amount = (amount ?? 0) + m.balance;
2057
+ const price = priceOf(prices, m.token.symbol);
2058
+ if (price !== void 0) usd = (usd ?? 0) + m.balance * price;
2059
+ }
2060
+ const first = members[0].token;
2061
+ return {
2062
+ key,
2063
+ symbol: dominantSymbol(tokens),
2064
+ name: String(first.name || first.symbol),
2065
+ logoUrl: first.logoUrl,
2066
+ deployments: members,
2067
+ unavailable: members.every((m) => m.disabled) ? { reason: members.find((m) => m.reason)?.reason } : null,
2068
+ amount,
2069
+ usd
2070
+ };
2071
+ }
2072
+ function byDeployment(a, b) {
2073
+ return Number(a.disabled) - Number(b.disabled) || (b.balance ?? 0) - (a.balance ?? 0) || chainTvlRank(a.token.chainId) - chainTvlRank(b.token.chainId);
2074
+ }
2075
+ function byPickability(a, b) {
2076
+ const zero = (g) => g.amount === 0 ? 1 : 0;
2077
+ return Number(!!a.unavailable) - Number(!!b.unavailable) || zero(a) - zero(b) || (b.usd ?? b.amount ?? 0) - (a.usd ?? a.amount ?? 0) || tokenMarketCapRank(a.symbol) - tokenMarketCapRank(b.symbol);
2078
+ }
2079
+ function groupDeployments(deployments, prices) {
2080
+ const order = [];
2081
+ const members = /* @__PURE__ */ new Map();
2082
+ for (const d of [...deployments].sort(byDeployment)) {
2083
+ const key = String(d.token.symbol).toUpperCase();
2084
+ const list = members.get(key);
2085
+ if (list) list.push(d);
2086
+ else {
2087
+ members.set(key, [d]);
2088
+ order.push(key);
2089
+ }
2090
+ }
2091
+ return order.map((key) => buildGroup(key, members.get(key), prices)).sort(byPickability);
2092
+ }
2093
+ var CHAIN_ALIASES = {
2094
+ 56: ["bsc", "binance"],
2095
+ 137: ["matic"],
2096
+ 43114: ["avax"]
2097
+ };
2098
+ function labelForms(label) {
2099
+ const lower = label.trim().toLowerCase();
2100
+ if (!lower) return [];
2101
+ const compact = lower.replace(/[^a-z0-9]/g, "");
2102
+ return compact && compact !== lower ? [lower, compact] : [lower];
2103
+ }
2104
+ function buildChainSearchTerms(chains) {
2105
+ const byId = /* @__PURE__ */ new Map();
2106
+ const ids = /* @__PURE__ */ new Set([...chains.map((c) => Number(c.chainId)), ...Object.keys(CHAIN_LABELS).map(Number)]);
2107
+ for (const id of ids) {
2108
+ const chain = chains.find((c) => Number(c.chainId) === id);
2109
+ const terms = /* @__PURE__ */ new Set();
2110
+ for (const label of [chain?.displayName, chain?.name, typeof chain?.slug === "string" ? chain.slug : void 0, CHAIN_LABELS[id]]) {
2111
+ if (label) for (const form of labelForms(label)) terms.add(form);
2112
+ }
2113
+ for (const alias of CHAIN_ALIASES[id] ?? []) terms.add(alias);
2114
+ byId.set(id, [...terms]);
2115
+ }
2116
+ return byId;
2117
+ }
2118
+ function splitSearchTerms(query) {
2119
+ return query.trim().toLowerCase().split(/\s+/).filter(Boolean);
2120
+ }
2121
+ function looksLikeAddress(term) {
2122
+ return /^(0x)?[0-9a-f]{4,}$/.test(term);
2123
+ }
2124
+ function chainMatches(term, token, chainTerms) {
2125
+ if (term === String(Number(token.chainId))) return true;
2126
+ return chainTerms.some((chainTerm) => chainTerm.includes(term));
2127
+ }
2128
+ function tokenMatches(term, token, asset) {
2129
+ return asset.symbol.toLowerCase().includes(term) || asset.name.toLowerCase().includes(term) || String(token.symbol || "").toLowerCase().includes(term) || // `₮` is not on a keyboard: both sides fold it to `T`, so "usdt0" finds USD₮0.
2130
+ foldTicker(tokenTicker(token)).includes(foldTicker(term)) || String(token.name || "").toLowerCase().includes(term) || looksLikeAddress(term) && String(token.address || "").toLowerCase().includes(term);
2131
+ }
2132
+ function matchingDeployments(terms, group, chainTerms) {
2133
+ if (terms.length === 0) return group.deployments;
2134
+ return group.deployments.filter((d) => {
2135
+ const ct = chainTerms.get(Number(d.token.chainId)) ?? [];
2136
+ return terms.every((term) => tokenMatches(term, d.token, group) || chainMatches(term, d.token, ct));
2137
+ });
2138
+ }
2139
+ function searchGroups(groups, query, chainTerms, prices) {
2140
+ const terms = splitSearchTerms(query);
2141
+ if (terms.length === 0) return groups;
2142
+ const rows = [];
2143
+ for (const g of groups) {
2144
+ const members = matchingDeployments(terms, g, chainTerms);
2145
+ if (members.length === 0) continue;
2146
+ rows.push(members.length === g.deployments.length ? g : buildGroup(g.key, members, prices));
2147
+ }
2148
+ return rows.sort(byPickability);
2149
+ }
2150
+ function groupDecimal2(value) {
2151
+ const match = value.match(/^([+-]?)(\d+)(\.\d+)?$/);
2152
+ if (!match) return value;
2153
+ return `${match[1]}${match[2].replace(/\B(?=(\d{3})+(?!\d))/g, ",")}${match[3] ?? ""}`;
2154
+ }
2155
+ function humanAmount(n, maxFrac = 6) {
2156
+ if (!Number.isFinite(n)) return String(n);
2157
+ if (n === 0) return "0";
2158
+ const digits = Math.min(Math.max(0, Math.trunc(maxFrac)), 8);
2159
+ const fixed = n.toFixed(digits);
2160
+ const out = fixed.includes(".") ? fixed.replace(/\.?0+$/, "") : fixed;
2161
+ if (Number(out) === 0) return `<${digits > 0 ? `0.${"0".repeat(digits - 1)}1` : "1"}`;
2162
+ return groupDecimal2(out);
2163
+ }
2164
+ function formatBalanceUsd(value) {
2165
+ if (!Number.isFinite(value) || value <= 0) return "$0.00";
2166
+ return value < 0.01 ? "<$0.01" : `$${value.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
2167
+ }
1941
2168
  var CHAIN_SHORT = {
1942
2169
  1: "ETH",
1943
2170
  10: "OP",
@@ -2019,103 +2246,280 @@ function FundingTile(props) {
2019
2246
  /* @__PURE__ */ jsx("span", { className: "sg-tile-main", children: main })
2020
2247
  ] });
2021
2248
  }
2022
- function ChainChip(props) {
2249
+ function ChainMark(props) {
2250
+ const [failed, setFailed] = useState([]);
2251
+ const src = chainLogoCandidates(props.chainId, props.chain?.logoUrl).find((u) => !failed.includes(u));
2252
+ return /* @__PURE__ */ jsx("span", { className: props.size === "row" ? "sg-pk-chain" : "sg-pk-mark", "aria-hidden": "true", children: src ? /* @__PURE__ */ jsx("img", { src, alt: "", loading: "lazy", onError: () => setFailed((f) => [...f, src]) }) : /* @__PURE__ */ jsx("span", { children: chainBadge(props.chainId) }) });
2253
+ }
2254
+ var MARK_LIMIT = 3;
2255
+ function ChainMarks(props) {
2256
+ const ids = props.chainIds;
2257
+ if (!ids.length) return null;
2258
+ const shown = ids.slice(0, MARK_LIMIT);
2259
+ const overflow = ids.length - shown.length;
2260
+ const marks = shown.map((id) => /* @__PURE__ */ jsx("span", { className: "sg-pk-markwrap", children: /* @__PURE__ */ jsx(ChainMark, { chainId: id, chain: props.chainById.get(id), size: "mini" }) }, id));
2261
+ return /* @__PURE__ */ jsxs("span", { className: "sg-pk-marks", children: [
2262
+ props.decorative ? /* @__PURE__ */ jsx("span", { className: "sg-pk-stack", "aria-hidden": "true", children: marks }) : /* @__PURE__ */ jsx("span", { className: "sg-pk-stack", role: "img", "aria-label": `${ids.length} ${ids.length === 1 ? "network" : "networks"}`, children: marks }),
2263
+ overflow > 0 ? /* @__PURE__ */ jsxs("span", { className: "sg-pk-more", "aria-hidden": "true", children: [
2264
+ "+",
2265
+ overflow
2266
+ ] }) : null
2267
+ ] });
2268
+ }
2269
+ function TokenPlate(props) {
2023
2270
  const [failed, setFailed] = useState([]);
2024
- const src = chainLogoCandidates(props.chain?.chainId, props.chain?.logoUrl).find((u) => !failed.includes(u));
2025
- const name = props.name ?? props.label;
2026
- return /* @__PURE__ */ jsx("button", { type: "button", className: "sg-chain-chip", "data-selected": props.selected, title: name, "aria-label": name, "aria-pressed": props.selected, onClick: props.onClick, children: src ? /* @__PURE__ */ jsx("img", { src, alt: "", loading: "lazy", onError: () => setFailed((f) => [...f, src]) }) : props.label });
2271
+ const src = tokenLogoCandidates(props.symbol, props.logoUrl).find((u) => !failed.includes(u));
2272
+ return /* @__PURE__ */ jsxs("span", { className: "sg-pk-plate", "data-muted": props.muted || void 0, children: [
2273
+ /* @__PURE__ */ jsx("span", { className: "sg-pk-plate-in", children: src ? /* @__PURE__ */ jsx("img", { src, alt: "", loading: "lazy", onError: () => setFailed((f) => [...f, src]) }) : /* @__PURE__ */ jsx("span", { className: "sg-pk-plate-fb", children: props.symbol.slice(0, 4) }) }),
2274
+ props.checked ? /* @__PURE__ */ jsx(TickBadge, {}) : null
2275
+ ] });
2276
+ }
2277
+ function TickBadge() {
2278
+ return /* @__PURE__ */ jsx("span", { className: "sg-pk-tick", "aria-hidden": "true", children: /* @__PURE__ */ jsxs("svg", { width: "12", height: "12", viewBox: "0 0 24 24", fill: "none", "aria-hidden": "true", children: [
2279
+ /* @__PURE__ */ jsx("circle", { cx: "12", cy: "12", r: "11", fill: "currentColor" }),
2280
+ /* @__PURE__ */ jsx("path", { d: "m7 12.5 3.2 3.2L17 9", stroke: "#fff", strokeWidth: "2.6", strokeLinecap: "round", strokeLinejoin: "round" })
2281
+ ] }) });
2282
+ }
2283
+ function BalanceColumn(props) {
2284
+ if (props.amount == null) return null;
2285
+ if (props.amount === 0) return /* @__PURE__ */ jsx("span", { className: "sg-pk-bal-zero", children: "0.00" });
2286
+ return /* @__PURE__ */ jsxs("span", { className: "sg-pk-bal", children: [
2287
+ /* @__PURE__ */ jsx("span", { className: "sg-pk-bal-usd sg-mono", children: props.usd == null ? "\u2014" : formatBalanceUsd(props.usd) }),
2288
+ /* @__PURE__ */ jsxs("span", { className: "sg-pk-bal-amt sg-mono", children: [
2289
+ humanAmount(props.amount, 6),
2290
+ " ",
2291
+ props.symbol
2292
+ ] })
2293
+ ] });
2294
+ }
2295
+ var WALLET_STATE_REASONS = /* @__PURE__ */ new Set(["no-balance", "insufficient"]);
2296
+ function isPick(sel, t) {
2297
+ return !!sel && Number(sel.chainId) === Number(t.chainId) && String(sel.symbol).toUpperCase() === String(t.symbol).toUpperCase();
2298
+ }
2299
+ function usdOf(balance, prices, symbol) {
2300
+ const price = priceOf(prices, symbol);
2301
+ return balance == null || price === void 0 ? null : balance * price;
2302
+ }
2303
+ function UnavailableRow(props) {
2304
+ return /* @__PURE__ */ jsx("div", { className: "sg-pk-row sg-pk-row--off", "data-testid": props.testId, "data-label": props.label, title: props.label, "aria-disabled": "true", children: /* @__PURE__ */ jsxs("span", { className: "sg-pk-left", children: [
2305
+ props.icon,
2306
+ /* @__PURE__ */ jsxs("span", { className: "sg-pk-text", children: [
2307
+ /* @__PURE__ */ jsx("span", { className: "sg-pk-label", children: props.label }),
2308
+ /* @__PURE__ */ jsx("span", { className: "sg-pk-sub", children: props.reason || "Not available right now" })
2309
+ ] })
2310
+ ] }) });
2027
2311
  }
2028
2312
  function SearchGlyph() {
2029
- return /* @__PURE__ */ jsxs("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2.4", strokeLinecap: "round", "aria-hidden": "true", children: [
2313
+ return /* @__PURE__ */ jsxs("svg", { width: "18", height: "18", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2.2", strokeLinecap: "round", "aria-hidden": "true", children: [
2030
2314
  /* @__PURE__ */ jsx("circle", { cx: "11", cy: "11", r: "7" }),
2031
2315
  /* @__PURE__ */ jsx("path", { d: "m20 20-3.5-3.5" })
2032
2316
  ] });
2033
2317
  }
2034
- function BackGlyph() {
2035
- return /* @__PURE__ */ jsxs("svg", { width: "17", height: "17", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2.4", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: [
2318
+ function CloseGlyph() {
2319
+ return /* @__PURE__ */ jsxs("svg", { width: "18", height: "18", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2.2", strokeLinecap: "round", "aria-hidden": "true", children: [
2320
+ /* @__PURE__ */ jsx("path", { d: "M18 6 6 18" }),
2321
+ /* @__PURE__ */ jsx("path", { d: "m6 6 12 12" })
2322
+ ] });
2323
+ }
2324
+ function ArrowLeftGlyph() {
2325
+ return /* @__PURE__ */ jsxs("svg", { width: "16", height: "16", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2.2", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: [
2036
2326
  /* @__PURE__ */ jsx("path", { d: "M19 12H5" }),
2037
2327
  /* @__PURE__ */ jsx("path", { d: "m12 19-7-7 7-7" })
2038
2328
  ] });
2039
2329
  }
2040
- var rowKey = (t) => `${Number(t.chainId)}:${String(t.address || "").toLowerCase()}`;
2041
2330
  function TokenSelect(props) {
2042
- const [chainFilter, setChainFilter] = useState(null);
2331
+ const side = props.side ?? "from";
2043
2332
  const [query, setQuery] = useState("");
2044
- const chains = useMemo(() => {
2045
- const listed = new Set(props.tokens.map((t) => Number(t.chainId)));
2046
- return props.chains.filter((c) => listed.has(Number(c.chainId)));
2047
- }, [props.chains, props.tokens]);
2048
- const activeFilter = chainFilter != null && chains.some((c) => Number(c.chainId) === chainFilter) ? chainFilter : null;
2049
- const rows = useMemo(() => {
2050
- const q = query.trim().toLowerCase();
2051
- const filtered = props.tokens.filter((t) => activeFilter == null ? true : Number(t.chainId) === activeFilter).filter((t) => {
2052
- if (!q) return true;
2053
- return String(t.symbol || "").toLowerCase().includes(q) || // The chain's own ticker too, with `₮` read as `T`: "usdt0" finds USD₮0.
2054
- foldTicker(tokenTicker(t)).includes(foldTicker(q)) || String(t.name || "").toLowerCase().includes(q) || String(t.address || "").toLowerCase().includes(q) || // Chain name too (2026-09-08): with ~37 destination chains most have no bundled mark and
2055
- // show a three-letter badge, so "Katana" or "Berachain" has to be findable by typing it.
2056
- String(CHAIN_LABELS[Number(t.chainId)] || "").toLowerCase().includes(q);
2057
- });
2058
- const off = (t) => props.optionStates?.[rowKey(t)]?.disabled ? 1 : 0;
2059
- const balNum = (t) => {
2060
- const n = Number(props.balances?.[rowKey(t)]?.formatted);
2061
- return Number.isFinite(n) ? n : 0;
2333
+ const [openKey, setOpenKey] = useState(null);
2334
+ const listRef = useRef(null);
2335
+ const savedScroll = useRef(0);
2336
+ const chainById = useMemo(() => new Map(props.chains.map((c) => [Number(c.chainId), c])), [props.chains]);
2337
+ const chainName3 = (chainId) => CHAIN_LABELS[chainId] || chainById.get(chainId)?.displayName || chainById.get(chainId)?.name || `Chain ${chainId}`;
2338
+ const showBalances = side === "from" && !!props.balances && Object.keys(props.balances).length > 0;
2339
+ const [prices, setPrices] = useState({});
2340
+ const symbolKey2 = useMemo(() => [...new Set(props.tokens.map((t) => String(t.symbol).toUpperCase()))].sort().join(","), [props.tokens]);
2341
+ const fetchPrices = props.fetchPrices;
2342
+ useEffect(() => {
2343
+ if (!showBalances || !fetchPrices || !symbolKey2) return;
2344
+ let alive = true;
2345
+ let timer2;
2346
+ const ask = (retriesLeft) => {
2347
+ fetchPrices(symbolKey2.split(",")).then((next) => {
2348
+ if (!alive) return;
2349
+ setPrices(next);
2350
+ if (!Object.keys(next).length && retriesLeft > 0) timer2 = setTimeout(() => ask(retriesLeft - 1), retriesLeft > 1 ? 5e3 : 2e4);
2351
+ }).catch(() => {
2352
+ });
2062
2353
  };
2063
- return [...filtered].sort((a, b) => off(a) - off(b) || balNum(b) - balNum(a));
2064
- }, [props.tokens, activeFilter, query, props.balances, props.optionStates]);
2065
- return /* @__PURE__ */ jsxs("div", { children: [
2066
- /* @__PURE__ */ jsxs("div", { className: "sg-sel-head", children: [
2067
- /* @__PURE__ */ jsx("button", { type: "button", className: "sg-back", onClick: props.onBack, "aria-label": "Back", children: /* @__PURE__ */ jsx(BackGlyph, {}) }),
2068
- /* @__PURE__ */ jsx("div", { className: "sg-sel-title", children: props.title })
2069
- ] }),
2070
- /* @__PURE__ */ jsxs("div", { className: "sg-chain-grid", "data-scroll": chains.length > 14 ? void 0 : "false", role: "group", "aria-label": "Filter by chain", children: [
2071
- /* @__PURE__ */ jsx(ChainChip, { label: "All", selected: activeFilter == null, onClick: () => setChainFilter(null) }),
2072
- chains.map((c) => /* @__PURE__ */ jsx(
2073
- ChainChip,
2074
- {
2075
- chain: c,
2076
- label: chainBadge(Number(c.chainId)),
2077
- name: CHAIN_LABELS[Number(c.chainId)] || c.displayName || c.name || `Chain ${c.chainId}`,
2078
- selected: activeFilter === Number(c.chainId),
2079
- onClick: () => setChainFilter(Number(c.chainId))
2080
- },
2081
- c.chainId
2082
- ))
2083
- ] }),
2084
- /* @__PURE__ */ jsxs("div", { className: "sg-search", children: [
2085
- /* @__PURE__ */ jsx(SearchGlyph, {}),
2086
- /* @__PURE__ */ jsx("input", { autoFocus: true, placeholder: "Search by token, network or address", value: query, onChange: (e) => setQuery(e.target.value), spellCheck: false, "aria-label": "Search by token, network or address" })
2087
- ] }),
2088
- /* @__PURE__ */ jsx("div", { className: "sg-toklist", role: "group", "aria-label": props.title, children: rows.length ? rows.map((t) => {
2089
- const chainId = Number(t.chainId);
2090
- const key = rowKey(t);
2091
- const bal = props.balances?.[key];
2354
+ ask(2);
2355
+ return () => {
2356
+ alive = false;
2357
+ if (timer2) clearTimeout(timer2);
2358
+ };
2359
+ }, [showBalances, fetchPrices, symbolKey2]);
2360
+ const groups = useMemo(() => {
2361
+ const deployments = [];
2362
+ for (const token of props.tokens) {
2363
+ const key = rowKey(token);
2364
+ const n = Number(props.balances?.[key]?.formatted);
2092
2365
  const st = props.optionStates?.[key];
2093
- const disabled = !!st?.disabled;
2094
- return /* @__PURE__ */ jsxs(
2095
- "button",
2096
- {
2097
- type: "button",
2098
- className: `sg-tokrow${disabled ? " sg-tokrow--off" : ""}`,
2099
- disabled,
2100
- "aria-disabled": disabled || void 0,
2101
- "data-disabled": disabled || void 0,
2102
- onClick: disabled ? void 0 : () => props.onPick({ chainId, symbol: t.symbol }),
2103
- children: [
2104
- /* @__PURE__ */ jsx(TokenGlyph, { symbol: t.symbol, logoUrl: t.logoUrl, chainId }),
2105
- /* @__PURE__ */ jsxs("span", { className: "sg-tokrow-main", children: [
2106
- /* @__PURE__ */ jsx("span", { className: "sg-tokrow-sym", children: tokenTicker(t) }),
2107
- /* @__PURE__ */ jsx("span", { className: "sg-tokrow-name", children: t.name || t.symbol })
2366
+ if (st?.disabled && !WALLET_STATE_REASONS.has(String(st.reason))) continue;
2367
+ deployments.push({
2368
+ token,
2369
+ key,
2370
+ balance: showBalances && props.balances?.[key] && Number.isFinite(n) ? n : null,
2371
+ disabled: !!st?.disabled,
2372
+ // The line under a greyed row says why. Callers send either a sentence in `reason` (the
2373
+ // exchange's "cannot be delivered on this chain") or a machine code there with the words in
2374
+ // `hint` (the deposit card's "no-balance" / "No balance on this chain").
2375
+ reason: st?.disabled ? st.reason && /\s/.test(st.reason) ? st.reason : st.hint || st.reason : void 0,
2376
+ hint: st?.disabled ? void 0 : st?.hint
2377
+ });
2378
+ }
2379
+ return groupDeployments(deployments, prices);
2380
+ }, [props.tokens, props.balances, props.optionStates, showBalances, prices]);
2381
+ const chainTerms = useMemo(() => buildChainSearchTerms(props.chains), [props.chains]);
2382
+ const visible = useMemo(() => searchGroups(groups, query, chainTerms, prices), [groups, query, chainTerms, prices]);
2383
+ const openGroup = openKey ? visible.find((g) => g.key === openKey) ?? null : null;
2384
+ useEffect(() => {
2385
+ if (openKey && !openGroup) setOpenKey(null);
2386
+ }, [openKey, openGroup]);
2387
+ useLayoutEffect(() => {
2388
+ if (!openKey && listRef.current) listRef.current.scrollTop = savedScroll.current;
2389
+ }, [openKey]);
2390
+ const selected = props.selected;
2391
+ const isSelected = (t) => isPick(selected, t);
2392
+ const pick = (t) => props.onPick({ chainId: Number(t.chainId), symbol: t.symbol });
2393
+ const selectedRow = useMemo(() => {
2394
+ if (!selected) return null;
2395
+ for (const g of groups) for (const d of g.deployments) if (!d.disabled && isPick(selected, d.token)) return d;
2396
+ return null;
2397
+ }, [groups, selected]);
2398
+ const head = /* @__PURE__ */ jsxs("div", { className: "sg-pk-head", children: [
2399
+ openGroup ? /* @__PURE__ */ jsxs("button", { type: "button", className: "sg-pk-backlink", onClick: () => setOpenKey(null), children: [
2400
+ /* @__PURE__ */ jsx(ArrowLeftGlyph, {}),
2401
+ "Tokens"
2402
+ ] }) : /* @__PURE__ */ jsx("div", { className: "sg-pk-title", children: props.title }),
2403
+ /* @__PURE__ */ jsx("button", { type: "button", className: "sg-pk-close", onClick: props.onBack, "aria-label": "Close", children: /* @__PURE__ */ jsx(CloseGlyph, {}) })
2404
+ ] });
2405
+ if (openGroup) {
2406
+ const sym = openGroup.symbol;
2407
+ return /* @__PURE__ */ jsxs("div", { className: "sg-pk", "data-step": "network", children: [
2408
+ head,
2409
+ /* @__PURE__ */ jsxs("div", { className: "sg-pk-intro", children: [
2410
+ /* @__PURE__ */ jsxs("div", { className: "sg-pk-title", children: [
2411
+ side === "from" ? "Pay with" : "Receive",
2412
+ " ",
2413
+ sym
2414
+ ] }),
2415
+ /* @__PURE__ */ jsx("p", { className: "sg-pk-lead", children: side === "from" ? "Choose the network to pay from" : `Choose the network to receive ${sym} on` })
2416
+ ] }),
2417
+ /* @__PURE__ */ jsx("div", { className: "sg-pk-list", role: "group", "aria-label": "Select network", children: openGroup.deployments.map((d) => {
2418
+ const id = Number(d.token.chainId);
2419
+ const name = chainName3(id);
2420
+ if (d.disabled) {
2421
+ return /* @__PURE__ */ jsx(UnavailableRow, { icon: /* @__PURE__ */ jsx(ChainMark, { chainId: id, chain: chainById.get(id), size: "row" }), label: name, reason: d.reason, testId: "network-row-unavailable" }, d.key);
2422
+ }
2423
+ const sel = isSelected(d.token);
2424
+ const ticker = tokenTicker(d.token);
2425
+ return /* @__PURE__ */ jsxs("button", { type: "button", className: "sg-pk-row sg-pk-row--net", "data-testid": "network-row", "data-selected": sel || void 0, "aria-pressed": sel, title: name, onClick: () => pick(d.token), children: [
2426
+ /* @__PURE__ */ jsxs("span", { className: "sg-pk-left", children: [
2427
+ /* @__PURE__ */ jsxs("span", { className: "sg-pk-chainwrap", children: [
2428
+ /* @__PURE__ */ jsx(ChainMark, { chainId: id, chain: chainById.get(id), size: "row" }),
2429
+ sel ? /* @__PURE__ */ jsx(TickBadge, {}) : null
2108
2430
  ] }),
2109
- /* @__PURE__ */ jsxs("span", { className: "sg-tokrow-end", children: [
2110
- bal ? /* @__PURE__ */ jsx("span", { className: "sg-tokrow-bal sg-mono", children: bal.formatted }) : null,
2111
- st?.hint ? /* @__PURE__ */ jsx("span", { className: "sg-tokrow-hint", "data-tone": disabled ? void 0 : "note", children: st.hint }) : null,
2112
- /* @__PURE__ */ jsx("span", { className: "sg-tokrow-chain", children: CHAIN_LABELS[chainId] || `Chain ${chainId}` })
2431
+ /* @__PURE__ */ jsxs("span", { className: "sg-pk-text", children: [
2432
+ /* @__PURE__ */ jsxs("span", { className: "sg-pk-label", children: [
2433
+ name,
2434
+ ticker !== sym ? /* @__PURE__ */ jsx("span", { className: "sg-pk-alt", children: ticker }) : null
2435
+ ] }),
2436
+ d.hint ? /* @__PURE__ */ jsx("span", { className: "sg-pk-note", "data-testid": "lane-limit", children: d.hint }) : null
2113
2437
  ] })
2114
- ]
2115
- },
2116
- `${chainId}:${t.address}`
2117
- );
2118
- }) : props.loading ? /* @__PURE__ */ jsx("div", { className: "sg-sel-empty", children: "Loading the token list\u2026" }) : /* @__PURE__ */ jsx("div", { className: "sg-sel-empty", children: "No tokens match \u2014 try another chain or search." }) })
2438
+ ] }),
2439
+ showBalances ? /* @__PURE__ */ jsx(BalanceColumn, { amount: d.balance, usd: usdOf(d.balance, prices, d.token.symbol), symbol: ticker }) : null
2440
+ ] }, d.key);
2441
+ }) })
2442
+ ] });
2443
+ }
2444
+ return /* @__PURE__ */ jsxs("div", { className: "sg-pk", "data-step": "token", children: [
2445
+ head,
2446
+ /* @__PURE__ */ jsxs("label", { className: "sg-pk-search", children: [
2447
+ /* @__PURE__ */ jsx(SearchGlyph, {}),
2448
+ /* @__PURE__ */ jsx("input", { autoFocus: true, placeholder: "Search by token or address", value: query, onChange: (e) => setQuery(e.target.value), spellCheck: false, "aria-label": "Search by token or address" }),
2449
+ query ? /* @__PURE__ */ jsx("button", { type: "button", className: "sg-pk-clear", onClick: () => setQuery(""), "aria-label": "Clear token search", children: /* @__PURE__ */ jsx(CloseGlyph, {}) }) : null
2450
+ ] }),
2451
+ /* @__PURE__ */ jsxs("div", { className: "sg-pk-body", children: [
2452
+ selectedRow ? /* @__PURE__ */ jsxs("div", { className: "sg-pk-selected", children: [
2453
+ /* @__PURE__ */ jsx("p", { className: "sg-pk-cap", children: "Selected" }),
2454
+ /* @__PURE__ */ jsxs("button", { type: "button", className: "sg-pk-row", "data-testid": "selected-row", "data-selected": "true", "aria-pressed": "true", onClick: () => pick(selectedRow.token), children: [
2455
+ /* @__PURE__ */ jsxs("span", { className: "sg-pk-left", children: [
2456
+ /* @__PURE__ */ jsx(TokenPlate, { symbol: selectedRow.token.symbol, logoUrl: selectedRow.token.logoUrl, checked: true }),
2457
+ /* @__PURE__ */ jsxs("span", { className: "sg-pk-text", children: [
2458
+ /* @__PURE__ */ jsx("span", { className: "sg-pk-label", children: tokenTicker(selectedRow.token) }),
2459
+ /* @__PURE__ */ jsxs("span", { className: "sg-pk-line", children: [
2460
+ /* @__PURE__ */ jsxs("span", { className: "sg-pk-sub", children: [
2461
+ "On ",
2462
+ chainName3(Number(selectedRow.token.chainId))
2463
+ ] }),
2464
+ /* @__PURE__ */ jsx(ChainMarks, { chainIds: [Number(selectedRow.token.chainId)], chainById, decorative: true })
2465
+ ] })
2466
+ ] })
2467
+ ] }),
2468
+ showBalances ? /* @__PURE__ */ jsx(
2469
+ BalanceColumn,
2470
+ {
2471
+ amount: selectedRow.balance,
2472
+ usd: usdOf(selectedRow.balance, prices, selectedRow.token.symbol),
2473
+ symbol: tokenTicker(selectedRow.token)
2474
+ }
2475
+ ) : null
2476
+ ] })
2477
+ ] }) : null,
2478
+ /* @__PURE__ */ jsx("p", { className: "sg-pk-cap", children: side === "from" ? "Your tokens \xB7 All networks" : "Popular tokens \xB7 All networks" }),
2479
+ /* @__PURE__ */ jsx("div", { className: "sg-pk-list", ref: listRef, role: "group", "aria-label": props.title, children: visible.length === 0 ? /* @__PURE__ */ jsx("p", { className: "sg-pk-empty", children: props.loading ? "Loading the token list\u2026" : "No tokens found." }) : visible.map((g) => {
2480
+ const members = g.deployments;
2481
+ const multi = members.length > 1;
2482
+ const single = members[0];
2483
+ const label = multi ? g.symbol : tokenTicker(single.token);
2484
+ const blocked = !!g.unavailable;
2485
+ const opensNetworks = multi || blocked;
2486
+ const zero = showBalances && g.amount === 0 || blocked;
2487
+ return /* @__PURE__ */ jsxs(
2488
+ "button",
2489
+ {
2490
+ type: "button",
2491
+ className: "sg-pk-row",
2492
+ "data-testid": "token-row",
2493
+ "data-symbol": g.symbol,
2494
+ "data-networks": members.length,
2495
+ "data-zero": zero || void 0,
2496
+ "data-unavailable": blocked || void 0,
2497
+ onClick: () => {
2498
+ if (opensNetworks) {
2499
+ savedScroll.current = listRef.current?.scrollTop ?? 0;
2500
+ setOpenKey(g.key);
2501
+ } else pick(single.token);
2502
+ },
2503
+ children: [
2504
+ /* @__PURE__ */ jsxs("span", { className: "sg-pk-left", children: [
2505
+ /* @__PURE__ */ jsx(TokenPlate, { symbol: g.symbol, logoUrl: g.logoUrl }),
2506
+ /* @__PURE__ */ jsxs("span", { className: "sg-pk-text", children: [
2507
+ /* @__PURE__ */ jsx("span", { className: "sg-pk-label", children: label }),
2508
+ /* @__PURE__ */ jsxs("span", { className: "sg-pk-line", children: [
2509
+ /* @__PURE__ */ jsx("span", { className: "sg-pk-sub", children: multi ? showBalances ? "Total across" : "Available on" : `On ${chainName3(Number(single.token.chainId))}` }),
2510
+ /* @__PURE__ */ jsx(ChainMarks, { chainIds: members.map((m) => Number(m.token.chainId)), chainById, decorative: !multi }),
2511
+ opensNetworks && showBalances ? /* @__PURE__ */ jsx("span", { className: "sg-pk-chev sg-pk-chev--sm", "aria-hidden": "true", children: /* @__PURE__ */ jsx(ChevronGlyph, {}) }) : null
2512
+ ] }),
2513
+ !multi && single.hint ? /* @__PURE__ */ jsx("span", { className: "sg-pk-note", "data-testid": "lane-limit", children: single.hint }) : null
2514
+ ] })
2515
+ ] }),
2516
+ showBalances ? /* @__PURE__ */ jsx(BalanceColumn, { amount: g.amount, usd: g.usd, symbol: label }) : opensNetworks ? /* @__PURE__ */ jsx("span", { className: "sg-pk-chev", "aria-hidden": "true", children: /* @__PURE__ */ jsx(ChevronGlyph, {}) }) : null
2517
+ ]
2518
+ },
2519
+ g.key
2520
+ );
2521
+ }) })
2522
+ ] })
2119
2523
  ] });
2120
2524
  }
2121
2525
  function ChevronRight({ size = 16 }) {
@@ -2133,7 +2537,7 @@ function ArrowDown({ size = 16 }) {
2133
2537
  /* @__PURE__ */ jsx("path", { d: "M12.667 8L8 12.667 3.333 8", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round" })
2134
2538
  ] });
2135
2539
  }
2136
- function CloseGlyph() {
2540
+ function CloseGlyph2() {
2137
2541
  return /* @__PURE__ */ jsx("svg", { width: "24", height: "24", viewBox: "0 0 24 24", fill: "none", "aria-hidden": "true", children: /* @__PURE__ */ jsx("path", { d: "M18 6L6 18M6 6l12 12", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round" }) });
2138
2542
  }
2139
2543
  function ShieldTickGlyph({ size = 16 }) {
@@ -2173,7 +2577,7 @@ function AmountText({ value, suffix, exact }) {
2173
2577
  suffix ? ` ${suffix}` : null
2174
2578
  ] });
2175
2579
  }
2176
- function usdOf(amount, price) {
2580
+ function usdOf2(amount, price) {
2177
2581
  const n = typeof amount === "number" ? amount : Number(amount);
2178
2582
  if (!Number.isFinite(n) || n <= 0 || price === void 0 || !Number.isFinite(price) || price <= 0) return null;
2179
2583
  const usd = n * price;
@@ -2303,7 +2707,7 @@ function WidgetShell(props) {
2303
2707
  ] }),
2304
2708
  props.onClose ? (
2305
2709
  // type="button": a host page may wrap the widget in a <form>.
2306
- /* @__PURE__ */ jsx("button", { type: "button", className: "sg-close", onClick: props.onClose, "aria-label": "Close", children: /* @__PURE__ */ jsx(CloseGlyph, {}) })
2710
+ /* @__PURE__ */ jsx("button", { type: "button", className: "sg-close", onClick: props.onClose, "aria-label": "Close", children: /* @__PURE__ */ jsx(CloseGlyph2, {}) })
2307
2711
  ) : null
2308
2712
  ] })
2309
2713
  ] }),
@@ -2599,7 +3003,7 @@ function useTxHistory(account) {
2599
3003
  }, [account]);
2600
3004
  return entries;
2601
3005
  }
2602
- function BackGlyph2() {
3006
+ function BackGlyph() {
2603
3007
  return /* @__PURE__ */ jsxs("svg", { width: "17", height: "17", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2.4", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: [
2604
3008
  /* @__PURE__ */ jsx("path", { d: "M19 12H5" }),
2605
3009
  /* @__PURE__ */ jsx("path", { d: "m12 19-7-7 7-7" })
@@ -2841,7 +3245,7 @@ function TxHistoryPanel(props) {
2841
3245
  };
2842
3246
  return /* @__PURE__ */ jsxs("div", { children: [
2843
3247
  /* @__PURE__ */ jsxs("div", { className: "sg-sel-head", children: [
2844
- /* @__PURE__ */ jsx("button", { type: "button", autoFocus: true, ref: backRef, className: "sg-back", onClick: selected ? () => setSelected(null) : props.onBack, "aria-label": "Back", children: /* @__PURE__ */ jsx(BackGlyph2, {}) }),
3248
+ /* @__PURE__ */ jsx("button", { type: "button", autoFocus: true, ref: backRef, className: "sg-back", onClick: selected ? () => setSelected(null) : props.onBack, "aria-label": "Back", children: /* @__PURE__ */ jsx(BackGlyph, {}) }),
2845
3249
  /* @__PURE__ */ jsxs("div", { className: "sg-sel-title", children: [
2846
3250
  selected ? "Transaction" : "Transaction history",
2847
3251
  account ? /* @__PURE__ */ jsx("span", { className: "sg-sel-sub sg-mono", children: shortAddress(account) }) : null
@@ -2850,6 +3254,444 @@ function TxHistoryPanel(props) {
2850
3254
  selected ? /* @__PURE__ */ jsx(TxDetail, { entry: selected, tokens: props.tokens, vaultIcons: props.vaultIcons }) : /* @__PURE__ */ jsx(TxHistoryList, { entries, tokens: props.tokens, vaultIcons: props.vaultIcons, onPick: pick })
2851
3255
  ] });
2852
3256
  }
3257
+
3258
+ // src/provider/solana-wallet.ts
3259
+ var sources = /* @__PURE__ */ new WeakMap();
3260
+ var infos = /* @__PURE__ */ new WeakMap();
3261
+ var connected = /* @__PURE__ */ new WeakMap();
3262
+ var registries = /* @__PURE__ */ new WeakMap();
3263
+ var EMPTY = Object.freeze([]);
3264
+ function normalizeSolanaWalletName(name) {
3265
+ return name.trim().toLowerCase().replace(/\s+(wallet|evm|solana)$/i, "");
3266
+ }
3267
+ function solanaWalletInfo(provider) {
3268
+ const standard = "features" in provider;
3269
+ if (standard ? !provider.chains?.some((chain) => chain.startsWith("solana:")) || typeof provider.features?.["standard:connect"]?.connect !== "function" : typeof provider.connect !== "function") return null;
3270
+ let info = infos.get(provider);
3271
+ if (!info) {
3272
+ const name = provider.name || (!standard && provider.isPhantom ? "Phantom" : !standard && provider.isSolflare ? "Solflare" : "Solana wallet");
3273
+ info = Object.freeze({ name, icon: standard ? provider.icon : void 0, kind: standard ? "standard" : "legacy" });
3274
+ infos.set(provider, info);
3275
+ sources.set(info, provider);
3276
+ }
3277
+ return info;
3278
+ }
3279
+ function targetWindow(win) {
3280
+ return win ?? (typeof window === "undefined" ? void 0 : window);
3281
+ }
3282
+ function registry(win) {
3283
+ const existing = registries.get(win);
3284
+ if (existing) return existing;
3285
+ const standard = /* @__PURE__ */ new Set();
3286
+ const listeners = /* @__PURE__ */ new Set();
3287
+ let snapshot = EMPTY;
3288
+ const read = () => {
3289
+ const candidates = [...standard].map(solanaWalletInfo);
3290
+ for (const [provider, name] of [[win.phantom?.solana, "Phantom"], [win.solflare, "Solflare"], [win.solana, void 0]]) {
3291
+ if (!provider || typeof provider.connect !== "function") continue;
3292
+ let info = solanaWalletInfo(provider);
3293
+ if (info && name && info.name === "Solana wallet") {
3294
+ info = Object.freeze({ ...info, name });
3295
+ infos.set(provider, info);
3296
+ sources.set(info, provider);
3297
+ }
3298
+ candidates.push(info);
3299
+ }
3300
+ const names = /* @__PURE__ */ new Set();
3301
+ const providers = /* @__PURE__ */ new Set();
3302
+ const next = candidates.filter((info) => {
3303
+ if (!info) return false;
3304
+ const name = normalizeSolanaWalletName(info.name);
3305
+ const provider = sources.get(info);
3306
+ if (names.has(name) || providers.has(provider)) return false;
3307
+ names.add(name);
3308
+ providers.add(provider);
3309
+ return true;
3310
+ });
3311
+ if (next.length !== snapshot.length || next.some((info) => !snapshot.includes(info))) snapshot = Object.freeze(next);
3312
+ return snapshot;
3313
+ };
3314
+ const refresh = () => {
3315
+ const previous = snapshot;
3316
+ read();
3317
+ if (previous !== snapshot) for (const cb of listeners) cb();
3318
+ };
3319
+ const api = {
3320
+ register(...wallets) {
3321
+ const added = wallets.filter((wallet) => !standard.has(wallet));
3322
+ for (const wallet of added) standard.add(wallet);
3323
+ refresh();
3324
+ return () => {
3325
+ for (const wallet of added) standard.delete(wallet);
3326
+ refresh();
3327
+ };
3328
+ }
3329
+ };
3330
+ const result = { read, watch: (cb) => {
3331
+ listeners.add(cb);
3332
+ return () => {
3333
+ listeners.delete(cb);
3334
+ };
3335
+ } };
3336
+ registries.set(win, result);
3337
+ win.addEventListener("wallet-standard:register-wallet", (event) => {
3338
+ const callback = event.detail;
3339
+ if (typeof callback === "function") callback(api);
3340
+ });
3341
+ win.addEventListener("focus", refresh);
3342
+ const EventClass = win.CustomEvent;
3343
+ win.dispatchEvent(new EventClass("wallet-standard:app-ready", { detail: api }));
3344
+ read();
3345
+ return result;
3346
+ }
3347
+ function discoverSolanaWallets(win) {
3348
+ const target = targetWindow(win);
3349
+ return target ? registry(target).read() : EMPTY;
3350
+ }
3351
+ function watchSolanaWallets(cb, win) {
3352
+ const target = targetWindow(win);
3353
+ if (!target) return () => {
3354
+ };
3355
+ const store = registry(target);
3356
+ const unsubscribe = store.watch(() => cb(store.read()));
3357
+ cb(store.read());
3358
+ return unsubscribe;
3359
+ }
3360
+ function source(info) {
3361
+ const provider = sources.get(info);
3362
+ if (!provider) throw new Error("Solana wallet is no longer available. Discover it before connecting.");
3363
+ return provider;
3364
+ }
3365
+ function validAddress(value) {
3366
+ const address = value?.toString().trim();
3367
+ return address && isSolanaAddress(address) ? address : null;
3368
+ }
3369
+ function accountAddress(accounts) {
3370
+ const account = accounts?.find((item) => !item.chains?.length || item.chains.some((chain) => chain.startsWith("solana:")));
3371
+ return validAddress(account?.address);
3372
+ }
3373
+ function connectedSolanaAddress(info) {
3374
+ const provider = source(info);
3375
+ return "features" in provider ? accountAddress(provider.accounts) : validAddress(provider.publicKey);
3376
+ }
3377
+ async function connectSolanaWallet(info, options = {}) {
3378
+ const provider = source(info);
3379
+ let address;
3380
+ if ("features" in provider) {
3381
+ const result = await provider.features["standard:connect"].connect(options.silent ? { silent: true } : void 0);
3382
+ const accounts = result?.accounts ?? provider.accounts;
3383
+ connected.set(provider, accounts ?? []);
3384
+ address = accountAddress(accounts);
3385
+ } else {
3386
+ const result = await provider.connect(options.silent ? { onlyIfTrusted: true } : void 0);
3387
+ address = validAddress(result?.publicKey ?? provider.publicKey);
3388
+ connected.set(provider, address ? [{ address }] : []);
3389
+ }
3390
+ if (!address) throw new Error("The wallet did not return a valid Solana address.");
3391
+ return address;
3392
+ }
3393
+ async function disconnectSolanaWallet(info) {
3394
+ const provider = source(info);
3395
+ if ("features" in provider) await provider.features["standard:disconnect"]?.disconnect();
3396
+ else await provider.disconnect?.();
3397
+ connected.delete(provider);
3398
+ }
3399
+ var CANNOT_PAY = "This wallet cannot pay from Solana here; use a Wallet Standard wallet (Phantom, Solflare, Backpack).";
3400
+ function solanaWalletSigner(info) {
3401
+ const provider = source(info);
3402
+ const accounts = "features" in provider ? provider.accounts?.length ? provider.accounts : connected.get(provider) : connected.get(provider);
3403
+ const address = accountAddress(accounts);
3404
+ if (!connected.has(provider) || !address) throw new Error("Connect a Solana wallet before paying.");
3405
+ if ("features" in provider ? typeof provider.features["solana:signTransaction"]?.signTransaction !== "function" : typeof provider.signTransactionBytes !== "function") throw new Error(CANNOT_PAY);
3406
+ return {
3407
+ publicKey: address,
3408
+ async signTransaction(bytes) {
3409
+ const current = "features" in provider ? provider.accounts?.length ? provider.accounts : connected.get(provider) : connected.get(provider);
3410
+ const account = current?.find((a) => a.address === address);
3411
+ if (!connected.has(provider) || !account || accountAddress(current) !== address) throw new Error("Solana wallet account changed; reconnect before paying.");
3412
+ let signed;
3413
+ if ("features" in provider) {
3414
+ if (!provider.chains.includes("solana:mainnet") || account.chains?.length && !account.chains.includes("solana:mainnet")) throw new Error("This wallet account cannot pay on Solana mainnet.");
3415
+ const result = await provider.features["solana:signTransaction"].signTransaction({ account, chain: "solana:mainnet", transaction: new Uint8Array(bytes) });
3416
+ if (result.length !== 1) throw new Error("Wallet returned an invalid Solana signing result.");
3417
+ signed = result[0]?.signedTransaction;
3418
+ } else signed = await provider.signTransactionBytes(new Uint8Array(bytes));
3419
+ if (!(signed instanceof Uint8Array)) throw new Error("Wallet did not return signed transaction bytes.");
3420
+ return new Uint8Array(signed);
3421
+ }
3422
+ };
3423
+ }
3424
+ function onSolanaAccountChange(info, cb) {
3425
+ const provider = source(info);
3426
+ if ("features" in provider) return provider.features["standard:events"]?.on("change", (change) => {
3427
+ if (change.accounts !== void 0) {
3428
+ connected.set(provider, change.accounts);
3429
+ cb(accountAddress(change.accounts));
3430
+ }
3431
+ }) ?? (() => {
3432
+ });
3433
+ const changed = (key) => {
3434
+ const address = validAddress(key);
3435
+ connected.set(provider, address ? [{ address }] : []);
3436
+ cb(address);
3437
+ };
3438
+ const disconnected = () => {
3439
+ connected.delete(provider);
3440
+ cb(null);
3441
+ };
3442
+ provider.on?.("accountChanged", changed);
3443
+ provider.on?.("connect", changed);
3444
+ provider.on?.("disconnect", disconnected);
3445
+ return () => {
3446
+ const off = provider.off ?? provider.removeListener;
3447
+ off?.call(provider, "accountChanged", changed);
3448
+ off?.call(provider, "connect", changed);
3449
+ off?.call(provider, "disconnect", disconnected);
3450
+ };
3451
+ }
3452
+
3453
+ // src/react/hooks/useSolanaWallet.ts
3454
+ var STORAGE_KEY = "sg-solana-wallet";
3455
+ function remember(name) {
3456
+ try {
3457
+ if (name) window.localStorage.setItem(STORAGE_KEY, name);
3458
+ else window.localStorage.removeItem(STORAGE_KEY);
3459
+ } catch {
3460
+ }
3461
+ }
3462
+ function remembered() {
3463
+ try {
3464
+ return window.localStorage.getItem(STORAGE_KEY);
3465
+ } catch {
3466
+ return null;
3467
+ }
3468
+ }
3469
+ var INITIAL = { address: null, walletName: null, status: "idle", error: null };
3470
+ function useSolanaWallet(provider) {
3471
+ const override = useMemo(() => provider ? solanaWalletInfo(provider) : null, [provider]);
3472
+ const [discovered, setDiscovered] = useState(discoverSolanaWallets);
3473
+ const wallets = useMemo(() => provider ? override ? [override] : [] : discovered, [provider, override, discovered]);
3474
+ const [state, setState] = useState(INITIAL);
3475
+ const active = useRef(null);
3476
+ const unsubscribe = useRef(() => {
3477
+ });
3478
+ const generation = useRef(0);
3479
+ const attempted = useRef(false);
3480
+ useEffect(() => {
3481
+ attempted.current = false;
3482
+ setState(INITIAL);
3483
+ return () => {
3484
+ generation.current += 1;
3485
+ unsubscribe.current();
3486
+ active.current = null;
3487
+ };
3488
+ }, [provider]);
3489
+ useEffect(() => provider ? void 0 : watchSolanaWallets(setDiscovered), [provider]);
3490
+ const runConnect = useCallback(async (info, silent = false) => {
3491
+ const request = ++generation.current;
3492
+ unsubscribe.current();
3493
+ active.current = null;
3494
+ setState({ ...INITIAL, status: "connecting" });
3495
+ try {
3496
+ const address = await connectSolanaWallet(info, { silent });
3497
+ if (request !== generation.current) return;
3498
+ active.current = info;
3499
+ unsubscribe.current = onSolanaAccountChange(info, (next) => {
3500
+ if (request !== generation.current) return;
3501
+ setState({ address: next, walletName: next ? info.name : null, status: next ? "connected" : "idle", error: null });
3502
+ if (!next) {
3503
+ generation.current += 1;
3504
+ unsubscribe.current();
3505
+ active.current = null;
3506
+ remember(null);
3507
+ }
3508
+ });
3509
+ setState({ address, walletName: info.name, status: "connected", error: null });
3510
+ remember(info.name);
3511
+ return address;
3512
+ } catch (error) {
3513
+ if (request === generation.current) setState(silent ? INITIAL : {
3514
+ ...INITIAL,
3515
+ status: "error",
3516
+ error: error instanceof Error ? error.message : "Could not connect a Solana wallet."
3517
+ });
3518
+ }
3519
+ }, []);
3520
+ useEffect(() => {
3521
+ if (attempted.current || active.current) return;
3522
+ const name = remembered();
3523
+ const info = wallets.find((wallet) => connectedSolanaAddress(wallet)) ?? (name ? wallets.find((wallet) => normalizeSolanaWalletName(wallet.name) === normalizeSolanaWalletName(name)) : void 0);
3524
+ if (!info) return;
3525
+ attempted.current = true;
3526
+ void runConnect(info, true);
3527
+ }, [wallets, runConnect]);
3528
+ const connect = useCallback(async (name) => {
3529
+ if (!name && wallets.length > 1) return wallets;
3530
+ attempted.current = true;
3531
+ const info = name ? wallets.find((wallet) => normalizeSolanaWalletName(wallet.name) === normalizeSolanaWalletName(name)) : wallets[0];
3532
+ if (!info) {
3533
+ setState({ ...INITIAL, status: "error", error: name ? "Solana wallet is not available." : "No Solana wallet found." });
3534
+ return;
3535
+ }
3536
+ return runConnect(info);
3537
+ }, [wallets, runConnect]);
3538
+ const disconnect = useCallback(async () => {
3539
+ attempted.current = true;
3540
+ generation.current += 1;
3541
+ unsubscribe.current();
3542
+ const info = active.current;
3543
+ active.current = null;
3544
+ setState(INITIAL);
3545
+ remember(null);
3546
+ if (info) {
3547
+ try {
3548
+ await disconnectSolanaWallet(info);
3549
+ } catch {
3550
+ }
3551
+ }
3552
+ }, []);
3553
+ return { ...state, wallets, connect, disconnect };
3554
+ }
3555
+
3556
+ // src/react/hooks/useRecipient.ts
3557
+ function useRecipient(destinationChainId, hostRecipient, opts = {}) {
3558
+ const recipientFamily = isSolanaChainId(destinationChainId) ? "solana" : "evm";
3559
+ const own = useSolanaWallet();
3560
+ const wallet = opts.solanaWallet ?? own;
3561
+ const [custom, setCustom] = useState({});
3562
+ const [open, setOpen] = useState(false);
3563
+ const triggerRef = useRef(null);
3564
+ const evmManaged = recipientFamily === "evm" && Boolean(opts.sourceIsSolana);
3565
+ const managed = hostRecipient === void 0 && (recipientFamily === "solana" || evmManaged);
3566
+ const error = hostRecipient === void 0 ? null : recipientFamily === "solana" && !isSolanaAddress(hostRecipient) ? "The configured recipient is not a Solana address." : evmManaged && !isAddress(hostRecipient) ? "The configured recipient is not an EVM address." : null;
3567
+ const recipient = hostRecipient !== void 0 ? hostRecipient : recipientFamily === "solana" ? custom.solana || wallet.address || void 0 : evmManaged ? custom.evm || opts.evm?.account || void 0 : void 0;
3568
+ const missing = managed && !recipient;
3569
+ const familyWallet = recipientFamily === "solana" ? { address: wallet.address, wallets: wallet.wallets, connecting: wallet.status === "connecting", error: wallet.error } : { address: opts.evm?.account ?? null, wallets: [], connecting: Boolean(opts.evm?.connecting), error: null };
3570
+ const close = () => {
3571
+ setOpen(false);
3572
+ requestAnimationFrame(() => triggerRef.current?.focus());
3573
+ };
3574
+ const selectAddress = (address) => {
3575
+ setCustom((prev) => ({ ...prev, [recipientFamily]: address }));
3576
+ close();
3577
+ };
3578
+ const connect = async (name) => {
3579
+ if (recipientFamily === "evm") {
3580
+ if (opts.evm?.account) selectAddress("");
3581
+ else opts.evm?.connect();
3582
+ return;
3583
+ }
3584
+ if (wallet.address && !name) {
3585
+ selectAddress("");
3586
+ return;
3587
+ }
3588
+ if (!name && wallet.wallets.length !== 1) {
3589
+ setOpen(true);
3590
+ return;
3591
+ }
3592
+ const address = await wallet.connect(name);
3593
+ if (typeof address === "string") selectAddress("");
3594
+ else setOpen(true);
3595
+ };
3596
+ const recipientFor = (account) => recipientFamily === "solana" || evmManaged ? recipient || "" : hostRecipient || account;
3597
+ return { recipientFamily, recipient, recipientFor, managed, missing, error, wallet, familyWallet, open: open && managed, show: () => setOpen(true), close, selectAddress, connect, triggerRef };
3598
+ }
3599
+ var short = (address) => `${address.slice(0, 4)}\u2026${address.slice(-4)}`;
3600
+ function RecipientNote({ state, disabled }) {
3601
+ if (state.error) return /* @__PURE__ */ jsx(StatusPanel, { tone: "error", children: state.error });
3602
+ if (!state.managed) return null;
3603
+ const family = state.recipientFamily === "solana" ? "Solana" : "EVM";
3604
+ return /* @__PURE__ */ jsxs("div", { style: { display: "flex", justifyContent: "center", gap: 6, marginTop: 10, fontSize: 13, color: "var(--sg-text-muted)", flexWrap: "wrap" }, children: [
3605
+ state.recipient ? /* @__PURE__ */ jsxs(Fragment, { children: [
3606
+ "To ",
3607
+ /* @__PURE__ */ jsx("b", { className: "sg-mono", title: state.recipient, style: { color: "var(--sg-text)" }, children: short(state.recipient) }),
3608
+ " on ",
3609
+ family,
3610
+ " \xB7 "
3611
+ ] }) : null,
3612
+ /* @__PURE__ */ jsx("button", { ref: state.triggerRef, type: "button", className: "sg-cp-link", onClick: state.show, disabled, "aria-haspopup": "dialog", children: state.recipient ? "Change" : "Send to a different address" })
3613
+ ] });
3614
+ }
3615
+ function RecipientSheet({ state, symbol }) {
3616
+ const [draft, setDraft] = useState(state.recipient ?? "");
3617
+ const id = useId();
3618
+ const inputRef = useRef(null);
3619
+ const sheetRef = useRef(null);
3620
+ const closeRef = useRef(state.close);
3621
+ closeRef.current = state.close;
3622
+ const family = state.recipientFamily === "solana" ? "Solana" : "EVM";
3623
+ const valid = state.recipientFamily === "solana" ? isSolanaAddress(draft) : /^0x[0-9a-fA-F]{40}$/.test(draft.trim());
3624
+ const invalid = Boolean(draft.trim()) && !valid;
3625
+ const noWallet = state.recipientFamily === "solana" && !state.familyWallet.address && !state.familyWallet.wallets.length;
3626
+ useEffect(() => {
3627
+ (noWallet ? inputRef : sheetRef).current?.focus();
3628
+ const onKey = (event) => {
3629
+ if (event.key === "Escape") {
3630
+ event.stopPropagation();
3631
+ closeRef.current();
3632
+ }
3633
+ };
3634
+ document.addEventListener("keydown", onKey, true);
3635
+ return () => document.removeEventListener("keydown", onKey, true);
3636
+ }, [noWallet]);
3637
+ return /* @__PURE__ */ jsxs("div", { className: "sg-cp-sheet", role: "dialog", "aria-modal": "true", "aria-label": `${family} recipient`, ref: sheetRef, tabIndex: -1, children: [
3638
+ /* @__PURE__ */ jsxs("div", { className: "sg-cp-sheet-head", children: [
3639
+ /* @__PURE__ */ jsxs("h4", { className: "sg-cp-sheet-title", children: [
3640
+ family,
3641
+ " recipient"
3642
+ ] }),
3643
+ /* @__PURE__ */ jsx("button", { type: "button", className: "sg-cp-close", onClick: state.close, "aria-label": "Close recipient", children: /* @__PURE__ */ jsx("svg", { width: "16", height: "16", viewBox: "0 0 24 24", fill: "none", "aria-hidden": "true", children: /* @__PURE__ */ jsx("path", { d: "m6 6 12 12M18 6 6 18", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round" }) }) })
3644
+ ] }),
3645
+ /* @__PURE__ */ jsxs("div", { className: "sg-cp-sheet-body", children: [
3646
+ /* @__PURE__ */ jsxs("section", { className: "sg-cp-card", children: [
3647
+ /* @__PURE__ */ jsxs("p", { className: "sg-cp-summary-sub", style: { margin: "0 0 12px" }, children: [
3648
+ symbol,
3649
+ " is delivered to a ",
3650
+ family,
3651
+ " wallet. Your EVM wallet stays the owner of the order and can cancel it."
3652
+ ] }),
3653
+ /* @__PURE__ */ jsx(Button, { onClick: () => noWallet ? inputRef.current?.focus() : void state.connect(), busy: state.familyWallet.connecting, children: state.familyWallet.address ? `Use ${short(state.familyWallet.address)}` : `Connect ${family} wallet` }),
3654
+ !state.familyWallet.address && state.familyWallet.wallets.length > 1 ? state.familyWallet.wallets.map((wallet) => /* @__PURE__ */ jsx(Button, { variant: "ghost", onClick: () => void state.connect(wallet.name), disabled: state.familyWallet.connecting, children: wallet.name }, wallet.name)) : null,
3655
+ noWallet ? /* @__PURE__ */ jsxs("p", { className: "sg-cp-summary-sub", children: [
3656
+ "No ",
3657
+ family,
3658
+ " wallet found. Enter a ",
3659
+ family,
3660
+ " address instead."
3661
+ ] }) : null,
3662
+ state.familyWallet.error ? /* @__PURE__ */ jsx(StatusPanel, { tone: "error", children: state.familyWallet.error }) : null
3663
+ ] }),
3664
+ /* @__PURE__ */ jsxs("section", { className: "sg-cp-card", children: [
3665
+ /* @__PURE__ */ jsxs("div", { className: "sg-field", style: { margin: 0 }, children: [
3666
+ /* @__PURE__ */ jsx("label", { className: "sg-label", htmlFor: id, children: "Send to a different address" }),
3667
+ /* @__PURE__ */ jsx(
3668
+ "input",
3669
+ {
3670
+ ref: inputRef,
3671
+ id,
3672
+ className: "sg-input sg-mono",
3673
+ style: { fontSize: 14, padding: "12px 14px", border: "1px solid var(--sg-border)", borderRadius: "var(--sg-radius-control)", width: "100%", boxSizing: "border-box", background: "var(--sg-bg)" },
3674
+ placeholder: `${family} recipient address`,
3675
+ "aria-label": `${family} recipient address`,
3676
+ "aria-invalid": invalid || void 0,
3677
+ "aria-describedby": `${id}-help${invalid ? ` ${id}-error` : ""}`,
3678
+ value: draft,
3679
+ onChange: (event) => setDraft(event.target.value),
3680
+ spellCheck: false
3681
+ }
3682
+ )
3683
+ ] }),
3684
+ invalid ? /* @__PURE__ */ jsx("div", { id: `${id}-error`, children: /* @__PURE__ */ jsxs(StatusPanel, { tone: "error", children: [
3685
+ "Not a valid ",
3686
+ family,
3687
+ " address."
3688
+ ] }) }) : null,
3689
+ /* @__PURE__ */ jsx("p", { id: `${id}-help`, className: "sg-cp-summary-sub", style: { margin: "8px 0 12px" }, children: "Double-check it: a payment sent to a wrong address cannot be recovered." }),
3690
+ /* @__PURE__ */ jsx(Button, { disabled: !valid, onClick: () => state.selectAddress(draft.trim()), children: "Use this address" })
3691
+ ] })
3692
+ ] })
3693
+ ] });
3694
+ }
2853
3695
  var IDENTITY_KEY_PREFIX = "sg:link:v1:";
2854
3696
  var LEGACY_IDENTITY_KEY = "zd-link-identity";
2855
3697
  var ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;
@@ -3207,14 +4049,17 @@ function PaymentIsland(props) {
3207
4049
  const exQuotable = !rampMode && exAmountValid && !exOverLimit && Boolean(exFromChainId && exFromAsset && exToChainId && exToAsset);
3208
4050
  const payFundingAssets = props.fundingAssets?.length ? props.fundingAssets : ["USDC", "USDT", "USDE"];
3209
4051
  const payParamsKey = `pay|${props.recipient}|${props.toChainId}|${props.toAsset}|${props.amount}|${payFundingAssets.join(",")}`;
3210
- const exParamsKey = `${kind}|${mode}|${exFromChainId}|${exFromAsset}|${exToChainId}|${exToAsset}|${normEx}|${props.recipient ?? ""}`;
4052
+ const recipientState = useRecipient(isPay ? null : exToChainId ?? null, props.recipient);
4053
+ const recipient = recipientState.recipient;
4054
+ const needsRecipient = !isPay && (recipientState.missing || !!recipientState.error);
4055
+ const exParamsKey = `${kind}|${mode}|${exFromChainId}|${exFromAsset}|${exToChainId}|${exToAsset}|${normEx}|${recipient ?? ""}`;
3211
4056
  const flow = useFlow({
3212
4057
  engine,
3213
4058
  wallet,
3214
4059
  kind: isPay ? "payment" : "swap",
3215
4060
  // Bank settlement parks the card, so gate the network work off too — otherwise the island would
3216
4061
  // quote (and fire onQuote) for a payment whose CTA it never shows.
3217
- enabled: isPay ? Boolean(props.recipient && props.amount) && !bankSettlement : exQuotable,
4062
+ enabled: isPay ? Boolean(props.recipient && props.amount) && !bankSettlement : exQuotable && !needsRecipient,
3218
4063
  paramsKey: isPay ? payParamsKey : exParamsKey,
3219
4064
  loadPlan: isPay ? (e, payer, chainId) => e.fetchPaymentPlan({ address: props.recipient, chainId: props.toChainId, asset: props.toAsset, amount: props.amount }, payer, {
3220
4065
  chainId,
@@ -3226,11 +4071,11 @@ function PaymentIsland(props) {
3226
4071
  fromToken: exFromAsset,
3227
4072
  toToken: exToAsset,
3228
4073
  amountIn: normEx,
3229
- recipient: props.recipient
4074
+ recipient
3230
4075
  },
3231
4076
  payer
3232
4077
  ),
3233
- recipientFor: (account) => isPay ? props.recipient : props.recipient || account,
4078
+ recipientFor: (account) => isPay ? props.recipient : recipientState.recipientFor(account),
3234
4079
  onQuote: config.onQuote,
3235
4080
  onSuccess: config.onSuccess,
3236
4081
  onError: config.onError
@@ -3548,7 +4393,7 @@ function PaymentIsland(props) {
3548
4393
  const activeStep = flow.steps.find((s) => s.state === "active");
3549
4394
  const liveMsg = flow.status === "loading" ? isPay ? "Finding the best way to pay." : "Finding the best route." : flow.status === "submitting" ? `${activeStep?.label ?? (isPay ? "Processing your payment" : `Processing your ${verb.present.toLowerCase()}`)} \u2014 in progress.` : flow.status === "success" || flow.status === "pending" ? flow.verdict?.status === "confirmed" ? isPay ? "Payment confirmed on-chain \u2014 the merchant has been settled." : `${verb.past} \u2014 confirmed on-chain.` : isPay ? "Payment sent \u2014 confirmation is still pending." : "Submitted \u2014 confirmation is still pending." : "";
3550
4395
  const loading = flow.status === "loading";
3551
- const payReady = isPay ? Boolean(sel && selectedVisible) : Boolean(sel);
4396
+ const payReady = isPay ? Boolean(sel && selectedVisible) : Boolean(sel) && !needsRecipient;
3552
4397
  const ctaLabel = submitting ? isPay ? "Paying\u2026" : kind === "swap" ? "Swapping\u2026" : "Exchanging\u2026" : flow.quoteStale ? flow.quotePaused ? "Refresh quote" : "Refreshing quote\u2026" : flow.insufficient ? "Insufficient balance" : flow.nativeShortfall ? flow.nativeShortfall : loading ? "Getting a price\u2026" : isPay ? sel && selectedVisible ? `Pay ${sel.source.payAmount} ${sel.source.ticker || sel.source.asset}` : "Pay" : kind === "swap" ? "Swap" : "Exchange";
3553
4398
  const exPct = (p) => {
3554
4399
  if (!exFromBal || !exFromToken) return;
@@ -3597,6 +4442,9 @@ function PaymentIsland(props) {
3597
4442
  TokenSelect,
3598
4443
  {
3599
4444
  title: "Pay with",
4445
+ side: "from",
4446
+ selected: sel ? { chainId: sel.source.chainId, symbol: sel.source.asset } : null,
4447
+ fetchPrices: engine.fetchPrices,
3600
4448
  chains: fundingChains,
3601
4449
  tokens: fundingTokens,
3602
4450
  balances: holdings.balances,
@@ -3612,6 +4460,9 @@ function PaymentIsland(props) {
3612
4460
  TokenSelect,
3613
4461
  {
3614
4462
  title: isFrom ? "Exchange from" : "Exchange to",
4463
+ side: isFrom ? "from" : "to",
4464
+ selected: isFrom ? exFrom : exTo,
4465
+ fetchPrices: engine.fetchPrices,
3615
4466
  chains,
3616
4467
  tokens: isFrom ? exFromPicker : exToPicker,
3617
4468
  balances: exBalances,
@@ -3624,6 +4475,8 @@ function PaymentIsland(props) {
3624
4475
  }
3625
4476
  }
3626
4477
  );
4478
+ } else if (recipientState.open && !isPay) {
4479
+ body = /* @__PURE__ */ jsx(RecipientSheet, { state: recipientState, symbol: destTicker });
3627
4480
  } else if (rampMode) {
3628
4481
  body = /* @__PURE__ */ jsxs("div", { className: "sg-soonpanel", children: [
3629
4482
  /* @__PURE__ */ jsx("div", { className: "sg-soonpanel-title", children: mode === "onramp" ? "Buying with fiat is coming soon" : "Cashing out to fiat is coming soon" }),
@@ -3674,7 +4527,7 @@ function PaymentIsland(props) {
3674
4527
  ] }),
3675
4528
  /* @__PURE__ */ jsxs("div", { className: "sg-receipt-sub", children: [
3676
4529
  confirmed ? "Confirmed on-chain" : "Confirmation pending",
3677
- isPay && props.recipient ? ` \xB7 ${shortAddress(props.recipient)}` : ""
4530
+ (flow.lastTxEntry?.recipient || recipient) && (isPay || recipientState.recipientFamily === "solana") ? ` \xB7 ${shortAddress(flow.lastTxEntry?.recipient || recipient)}` : ""
3678
4531
  ] })
3679
4532
  ] }),
3680
4533
  !identityMatchesWallet ? /* @__PURE__ */ jsxs("div", { className: "sg-remember", children: [
@@ -3790,16 +4643,23 @@ function PaymentIsland(props) {
3790
4643
  quoteError ? /* @__PURE__ */ jsx(StatusPanel, { tone: "error", children: flow.error || "Couldn't get a price right now." }) : null,
3791
4644
  walletError ? /* @__PURE__ */ jsx(StatusPanel, { tone: "error", children: flow.error || "The wallet could not complete this payment." }) : null,
3792
4645
  submitting || walletError ? /* @__PURE__ */ jsx(StepList, { variant: "rich", steps: flow.steps, verdict: flow.verdict }) : null,
3793
- /* @__PURE__ */ jsx("div", { className: "sg-cta-wrap", children: quoteError ? /* @__PURE__ */ jsx(Button, { onClick: flow.reload, children: "Try again" }) : walletError ? /* @__PURE__ */ jsx(Button, { onClick: payReady ? flow.submit : void 0, disabled: !payReady, children: "Try again" }) : /* @__PURE__ */ jsx(
3794
- Button,
3795
- {
3796
- onClick: payReady && !submitting && !flow.insufficient && !flow.nativeShortfall && !loading ? flow.submit : void 0,
3797
- busy: submitting || loading,
3798
- softDisabled: submitting,
3799
- disabled: !submitting && (!payReady || flow.insufficient || !!flow.nativeShortfall || loading),
3800
- children: ctaLabel
3801
- }
3802
- ) })
4646
+ /* @__PURE__ */ jsxs("div", { className: "sg-cta-wrap", children: [
4647
+ recipientState.missing && !isPay && !submitting ? /* @__PURE__ */ jsxs(Button, { onClick: () => void recipientState.connect(), busy: recipientState.wallet.status === "connecting", children: [
4648
+ "Connect ",
4649
+ recipientState.recipientFamily === "solana" ? "Solana" : "EVM",
4650
+ " wallet"
4651
+ ] }) : quoteError ? /* @__PURE__ */ jsx(Button, { onClick: flow.reload, children: "Try again" }) : walletError ? /* @__PURE__ */ jsx(Button, { onClick: payReady ? flow.submit : void 0, disabled: !payReady, children: "Try again" }) : /* @__PURE__ */ jsx(
4652
+ Button,
4653
+ {
4654
+ onClick: payReady && !submitting && !flow.insufficient && !flow.nativeShortfall && !loading ? flow.submit : void 0,
4655
+ busy: submitting || loading,
4656
+ softDisabled: submitting,
4657
+ disabled: !submitting && (!payReady || flow.insufficient || !!flow.nativeShortfall || loading),
4658
+ children: ctaLabel
4659
+ }
4660
+ ),
4661
+ !isPay ? /* @__PURE__ */ jsx(RecipientNote, { state: recipientState, disabled: submitting }) : null
4662
+ ] })
3803
4663
  ] })
3804
4664
  ] });
3805
4665
  }
@@ -4156,6 +5016,9 @@ function PayCard(props) {
4156
5016
  TokenSelect,
4157
5017
  {
4158
5018
  title: "Pay with",
5019
+ side: "from",
5020
+ selected: sel ? { chainId: sel.source.chainId, symbol: sel.source.asset } : null,
5021
+ fetchPrices: engine.fetchPrices,
4159
5022
  chains: fundingChains,
4160
5023
  tokens: fundingTokens,
4161
5024
  balances: listBalances,
@@ -4203,7 +5066,7 @@ function PayCard(props) {
4203
5066
  }
4204
5067
  )
4205
5068
  ] }),
4206
- /* @__PURE__ */ jsx(PaneFoot, { usd: sel && selectedVisible ? usdOf(sel.source.payAmount, prices[selSymbol]) : null, balance: selBal ? shortBalance(selBal.formatted) : null })
5069
+ /* @__PURE__ */ jsx(PaneFoot, { usd: sel && selectedVisible ? usdOf2(sel.source.payAmount, prices[selSymbol]) : null, balance: selBal ? shortBalance(selBal.formatted) : null })
4207
5070
  ] }),
4208
5071
  loadingPlan ? /* @__PURE__ */ jsxs("div", { className: "sg-pay-loading", "data-testid": "pay-loading", role: "status", children: [
4209
5072
  /* @__PURE__ */ jsx("div", { className: "sg-skel sg-skel--row" }),
@@ -4258,6 +5121,9 @@ function StableGenieSwap(props) {
4258
5121
  const [toChainId, setToChainId] = useState(props.defaultToChainId ?? 8453);
4259
5122
  const [toAsset, setToAsset] = useState(props.defaultToAsset ?? "USDC");
4260
5123
  const [amount, setAmount] = useState(props.defaultAmount ?? "");
5124
+ const recipientState = useRecipient(toChainId, props.recipient);
5125
+ const recipient = recipientState.recipient;
5126
+ const needsRecipient = recipientState.missing || !!recipientState.error;
4261
5127
  const [catalogue, setCatalogue] = useState(null);
4262
5128
  useEffect(() => {
4263
5129
  if (props.variant === "pill") return;
@@ -4287,15 +5153,15 @@ function StableGenieSwap(props) {
4287
5153
  }, [catalogue]);
4288
5154
  const amountValid = /^\d+(\.\d+)?$/.test(amount.replace(",", ".")) && Number(amount.replace(",", ".")) > 0;
4289
5155
  const enabled = amountValid && props.variant !== "pill";
4290
- const paramsKey = `${fromChainId}|${fromAsset}|${toChainId}|${toAsset}|${amount}|${props.recipient ?? ""}`;
5156
+ const paramsKey = `${fromChainId}|${fromAsset}|${toChainId}|${toAsset}|${amount}|${recipient ?? ""}`;
4291
5157
  const flow = useFlow({
4292
5158
  engine,
4293
5159
  wallet,
4294
5160
  kind: "swap",
4295
- enabled,
5161
+ enabled: enabled && !needsRecipient,
4296
5162
  paramsKey,
4297
- loadPlan: (e, payer) => e.buildSwapPlan({ fromChainId, toChainId, fromToken: fromAsset, toToken: toAsset, amountIn: amount, recipient: props.recipient }, payer),
4298
- recipientFor: (account) => props.recipient || account,
5163
+ loadPlan: (e, payer) => e.buildSwapPlan({ fromChainId, toChainId, fromToken: fromAsset, toToken: toAsset, amountIn: amount, recipient }, payer),
5164
+ recipientFor: recipientState.recipientFor,
4299
5165
  onQuote: config.onQuote,
4300
5166
  onSuccess: config.onSuccess,
4301
5167
  onError: config.onError
@@ -4338,6 +5204,7 @@ function StableGenieSwap(props) {
4338
5204
  if (hist && wallet.account) {
4339
5205
  return /* @__PURE__ */ jsx(WidgetShell, { title: config.title || "Swap", theme: config.theme, walletSlot, children: /* @__PURE__ */ jsx(TxHistoryPanel, { account: wallet.account, tokens: registryTokens, vaultIcons: catalogue?.vaultIcons, initialEntry: hist.entry ?? null, onBack: closeHistory }) });
4340
5206
  }
5207
+ if (recipientState.open) return /* @__PURE__ */ jsx(WidgetShell, { title: config.title || "Swap", theme: config.theme, walletSlot, children: /* @__PURE__ */ jsx(RecipientSheet, { state: recipientState, symbol: toAsset }) });
4341
5208
  if (flow.status === "success" || flow.status === "pending") {
4342
5209
  return /* @__PURE__ */ jsxs(WidgetShell, { title: config.title || "Swap", theme: config.theme, walletSlot, children: [
4343
5210
  /* @__PURE__ */ jsxs("div", { className: "sg-success", children: [
@@ -4349,7 +5216,7 @@ function StableGenieSwap(props) {
4349
5216
  ] }),
4350
5217
  /* @__PURE__ */ jsxs("div", { className: "sg-success-sub", children: [
4351
5218
  flow.verdict?.status === "confirmed" ? "Confirmed on-chain" : "Submitted \u2014 awaiting confirmation",
4352
- props.recipient ? ` \xB7 ${shortAddress(props.recipient)}` : ""
5219
+ recipientState.recipientFamily === "solana" ? ` \xB7 ${shortAddress(flow.lastTxEntry?.recipient || recipient)}` : props.recipient ? ` \xB7 ${shortAddress(props.recipient)}` : ""
4353
5220
  ] })
4354
5221
  ] }),
4355
5222
  lastTxOwned ? /* @__PURE__ */ jsx("div", { className: "sg-cta-wrap", children: /* @__PURE__ */ jsx(Button, { variant: "ghost", onClick: () => setHist({ entry: flow.lastTxEntry }), children: "View transaction" }) }) : null
@@ -4378,11 +5245,169 @@ function StableGenieSwap(props) {
4378
5245
  flow.selected && flow.status !== "loading" ? /* @__PURE__ */ jsx(CompliancePanel, { compliance: flow.selected.quote.compliance, direct: flow.selected.state === "DIRECT" }) : null,
4379
5246
  submitting ? /* @__PURE__ */ jsx(StepList, { steps: flow.steps }) : null,
4380
5247
  /* @__PURE__ */ jsxs("div", { className: "sg-cta-wrap", children: [
4381
- !wallet.account ? /* @__PURE__ */ jsx(Button, { onClick: wallet.connect, busy: wallet.connecting, children: "Connect wallet" }) : /* @__PURE__ */ jsx(Button, { onClick: flow.submit, busy: submitting, disabled: !flow.selected || flow.insufficient || !!flow.nativeShortfall || !enabled || flow.status === "loading", children: swapLabel }),
5248
+ !wallet.account ? /* @__PURE__ */ jsx(Button, { onClick: wallet.connect, busy: wallet.connecting, children: "Connect wallet" }) : recipientState.missing && !submitting ? /* @__PURE__ */ jsxs(Button, { onClick: () => void recipientState.connect(), busy: recipientState.wallet.status === "connecting", children: [
5249
+ "Connect ",
5250
+ recipientState.recipientFamily === "solana" ? "Solana" : "EVM",
5251
+ " wallet"
5252
+ ] }) : /* @__PURE__ */ jsx(Button, { onClick: flow.submit, busy: submitting, disabled: needsRecipient || !flow.selected || flow.insufficient || !!flow.nativeShortfall || !enabled || flow.status === "loading", children: swapLabel }),
5253
+ /* @__PURE__ */ jsx(RecipientNote, { state: recipientState, disabled: submitting }),
4382
5254
  wallet.error ? /* @__PURE__ */ jsx(StatusPanel, { tone: "error", children: wallet.error }) : null
4383
5255
  ] })
4384
5256
  ] });
4385
5257
  }
5258
+ function keyOf(a) {
5259
+ return `${a.fromSymbol}|${a.toChainId}|${a.toSymbol}|${a.amount}|${a.owner ?? ""}|${a.payer ?? ""}|${a.recipient ?? ""}`;
5260
+ }
5261
+ function useSolanaSourceFlow(args) {
5262
+ const { engine, enabled, fromSymbol, fromMint, toChainId, toSymbol, amount, owner, payer, recipient } = args;
5263
+ const [status, setStatus] = useState("idle");
5264
+ const [preview, setPreview] = useState(null);
5265
+ const [plan, setPlan] = useState(null);
5266
+ const [error, setError] = useState(null);
5267
+ const [balanceRaw, setBalanceRaw] = useState(void 0);
5268
+ const [cost, setCost] = useState(null);
5269
+ const [progress, setProgress] = useState(null);
5270
+ const [signature, setSignature] = useState(null);
5271
+ const [lastTxEntry, setLastTxEntry] = useState(null);
5272
+ const [sent, setSent] = useState(null);
5273
+ const [nonce, setNonce] = useState(0);
5274
+ const req = useRef(0);
5275
+ const busy = useRef(false);
5276
+ const latest = useRef(args);
5277
+ latest.current = args;
5278
+ const planKey = useRef(null);
5279
+ const planArgs = useRef(null);
5280
+ const changedWhileBusy = useRef(false);
5281
+ const addressed = Boolean(owner && payer && recipient);
5282
+ const key = keyOf(args);
5283
+ useEffect(() => {
5284
+ const id = ++req.current;
5285
+ if (!enabled || !fromSymbol || !toChainId || !toSymbol || !(Number(amount) > 0)) {
5286
+ setStatus("idle");
5287
+ setPreview(null);
5288
+ setPlan(null);
5289
+ setError(null);
5290
+ setCost(null);
5291
+ return;
5292
+ }
5293
+ if (busy.current) {
5294
+ changedWhileBusy.current = true;
5295
+ return;
5296
+ }
5297
+ setStatus("quoting");
5298
+ planKey.current = null;
5299
+ planArgs.current = null;
5300
+ setError(null);
5301
+ setPlan(null);
5302
+ setCost(null);
5303
+ const timer2 = setTimeout(async () => {
5304
+ try {
5305
+ if (!addressed) {
5306
+ const next = await engine.previewSolanaSource({ toChainId, fromToken: fromSymbol, toToken: toSymbol, amountIn: amount });
5307
+ if (id !== req.current) return;
5308
+ setPreview(next);
5309
+ setStatus("ready");
5310
+ return;
5311
+ }
5312
+ const input = { toChainId, fromToken: fromSymbol, toToken: toSymbol, amountIn: amount, owner, sender: payer, recipient };
5313
+ const quoted = await engine.quoteSolanaSource(input);
5314
+ const built = await engine.buildSolanaSourcePlan(input, quoted);
5315
+ if (id !== req.current) return;
5316
+ planKey.current = key;
5317
+ planArgs.current = { ...latest.current };
5318
+ setPreview(quoted);
5319
+ setPlan(built);
5320
+ setStatus("ready");
5321
+ engine.simulateSolanaCost(built).then(
5322
+ (c) => id === req.current && setCost(c),
5323
+ () => id === req.current && setCost(null)
5324
+ );
5325
+ } catch (e) {
5326
+ if (id !== req.current) return;
5327
+ setStatus("error");
5328
+ setError(e instanceof Error ? e.message : String(e));
5329
+ }
5330
+ }, 350);
5331
+ return () => clearTimeout(timer2);
5332
+ }, [engine, enabled, key, addressed, nonce]);
5333
+ useEffect(() => {
5334
+ let alive = true;
5335
+ setBalanceRaw(void 0);
5336
+ if (!enabled || !payer || !fromMint) return;
5337
+ engine.readSolanaBalance(payer, fromMint).then((b) => {
5338
+ if (alive) setBalanceRaw(b);
5339
+ });
5340
+ return () => {
5341
+ alive = false;
5342
+ };
5343
+ }, [engine, enabled, payer, fromMint]);
5344
+ const needsPreparation = plan ? solanaPlanNeedsPreparation(plan) : false;
5345
+ const run = useCallback(async () => {
5346
+ const current = plan;
5347
+ if (!current || busy.current) return;
5348
+ if (planKey.current !== keyOf(latest.current)) {
5349
+ setError("The order changed; review the new quote before signing.");
5350
+ setNonce((n) => n + 1);
5351
+ return;
5352
+ }
5353
+ busy.current = true;
5354
+ let broadcast = false;
5355
+ setError(null);
5356
+ setStatus(needsPreparation ? "preparing" : "submitting");
5357
+ try {
5358
+ const result = await engine.executeSolanaPlanStaged({ plan: current, signer: latest.current.signer(), onProgress: setProgress });
5359
+ if (result.status === "prepared") {
5360
+ setStatus("prepared");
5361
+ return;
5362
+ }
5363
+ const a = planArgs.current ?? latest.current;
5364
+ broadcast = true;
5365
+ setSent({ receive: current.preview.receive, toTicker: a.toTicker, recipient: a.recipient ?? "" });
5366
+ setSignature(result.signature);
5367
+ setStatus("sent");
5368
+ const entry = engine.recordTransaction({
5369
+ kind: "swap",
5370
+ hash: result.signature,
5371
+ txKind: "submitOrder",
5372
+ chainId: SOLANA_CHAIN_ID,
5373
+ chainName: a.chainName,
5374
+ fromAsset: a.fromSymbol ?? "",
5375
+ toAsset: a.toSymbol ?? "",
5376
+ fromTicker: a.fromTicker,
5377
+ toTicker: a.toTicker,
5378
+ payAmount: a.amount,
5379
+ receiveAmount: current.preview.receive,
5380
+ account: a.owner ?? "",
5381
+ recipient: a.recipient ?? "",
5382
+ settlement: "escrow",
5383
+ status: "submitted"
5384
+ });
5385
+ setLastTxEntry(entry.hash ? entry : null);
5386
+ appendTxHistory(a.owner, entry);
5387
+ } catch (e) {
5388
+ const err = e instanceof Error ? e : new Error(String(e));
5389
+ setStatus("failed");
5390
+ setError(err.message);
5391
+ latest.current.onError?.(err);
5392
+ } finally {
5393
+ busy.current = false;
5394
+ if (changedWhileBusy.current) {
5395
+ changedWhileBusy.current = false;
5396
+ if (!broadcast && planKey.current !== keyOf(latest.current)) setNonce((n) => n + 1);
5397
+ }
5398
+ }
5399
+ }, [engine, plan, needsPreparation]);
5400
+ const insufficient = balanceRaw !== void 0 && plan ? balanceRaw < BigInt(plan.expected.bidTokenAmount) : false;
5401
+ const solShort = cost ? !cost.sufficient : false;
5402
+ const reset = useCallback(() => {
5403
+ setSignature(null);
5404
+ setLastTxEntry(null);
5405
+ setSent(null);
5406
+ setProgress(null);
5407
+ setNonce((n) => n + 1);
5408
+ }, []);
5409
+ return { status, preview, plan, error, balanceRaw, cost, progress, signature, lastTxEntry, sent, addressed, needsPreparation, insufficient, solShort, run, reset };
5410
+ }
4386
5411
  function QuoteSheet(props) {
4387
5412
  const sheetRef = useRef(null);
4388
5413
  const onCloseRef = useRef(props.onClose);
@@ -4491,7 +5516,7 @@ function ExchangeCard(props) {
4491
5516
  useEffect(() => {
4492
5517
  if (isPill) return;
4493
5518
  let alive = true;
4494
- engine.fetchCatalogue(allowed, product).then((next) => {
5519
+ engine.fetchCatalogue(allowed, product, { solanaSources: true }).then((next) => {
4495
5520
  if (alive) setCatalogue(next);
4496
5521
  });
4497
5522
  return () => {
@@ -4524,6 +5549,16 @@ function ExchangeCard(props) {
4524
5549
  () => props.defaultToChainId && props.defaultToAsset ? { chainId: props.defaultToChainId, symbol: symbolKey(props.defaultToAsset) } : null
4525
5550
  );
4526
5551
  const [amount, setAmount] = useState(props.defaultAmount ?? "");
5552
+ const solanaWallet = useSolanaWallet();
5553
+ const [payerChooser, setPayerChooser] = useState(false);
5554
+ const sourceIsSolana = isSolanaChainId(from?.chainId);
5555
+ const recipientState = useRecipient(to?.chainId ?? null, props.recipient, {
5556
+ solanaWallet,
5557
+ sourceIsSolana,
5558
+ evm: { account: wallet.account, connect: wallet.connect, connecting: wallet.connecting }
5559
+ });
5560
+ const recipient = recipientState.recipient;
5561
+ const needsRecipient = recipientState.missing || !!recipientState.error;
4527
5562
  const onInputChange = useRef(props.onInputChange);
4528
5563
  onInputChange.current = props.onInputChange;
4529
5564
  const fromChainId = from?.chainId ?? null;
@@ -4619,7 +5654,7 @@ function ExchangeCard(props) {
4619
5654
  if (id === balReq.current) setBalances(res);
4620
5655
  });
4621
5656
  }, [engine, wallet.account, tokens]);
4622
- const fromBal = from && fromToken ? balances[balanceKey(from.chainId, fromToken.address)] : void 0;
5657
+ const evmFromBal = from && fromToken ? balances[balanceKey(from.chainId, fromToken.address)] : void 0;
4623
5658
  const [prices, setPrices] = useState({});
4624
5659
  useEffect(() => {
4625
5660
  if (isPill) return;
@@ -4633,24 +5668,47 @@ function ExchangeCard(props) {
4633
5668
  alive = false;
4634
5669
  };
4635
5670
  }, [engine, from?.symbol, to?.symbol, isPill]);
4636
- const paramsKey = `${mode}|${from?.chainId}|${from?.symbol}|${to?.chainId}|${toSymbol}|${normalizedAmount}|${props.recipient ?? ""}`;
5671
+ const paramsKey = `${mode}|${from?.chainId}|${from?.symbol}|${to?.chainId}|${toSymbol}|${normalizedAmount}|${recipient ?? ""}`;
4637
5672
  const flow = useFlow({
4638
5673
  engine,
4639
5674
  wallet,
4640
5675
  kind: "swap",
4641
- enabled: quotable && !isPill,
5676
+ enabled: quotable && !isPill && !needsRecipient && !sourceIsSolana,
4642
5677
  paramsKey,
4643
- loadPlan: (e, payer) => e.buildSwapPlan({ fromChainId: from.chainId, toChainId: to.chainId, fromToken: from.symbol, toToken: to.symbol, amountIn: normalizedAmount, recipient: props.recipient }, payer),
4644
- recipientFor: (account) => props.recipient || account,
5678
+ loadPlan: (e, payer) => e.buildSwapPlan({ fromChainId: from.chainId, toChainId: to.chainId, fromToken: from.symbol, toToken: to.symbol, amountIn: normalizedAmount, recipient }, payer),
5679
+ recipientFor: recipientState.recipientFor,
4645
5680
  onQuote: config.onQuote,
4646
5681
  onSuccess: config.onSuccess,
4647
5682
  onError: config.onError
4648
5683
  });
5684
+ const solActive = sourceIsSolana && !isPill && !rampMode;
5685
+ const solFlow = useSolanaSourceFlow({
5686
+ engine,
5687
+ enabled: solActive && quotable && !recipientState.error,
5688
+ fromSymbol: from?.symbol ?? null,
5689
+ fromMint: fromToken?.address ?? null,
5690
+ toChainId: to?.chainId ?? null,
5691
+ toSymbol: to ? toSymbol : null,
5692
+ amount: normalizedAmount,
5693
+ owner: wallet.account,
5694
+ payer: solanaWallet.address,
5695
+ recipient,
5696
+ signer: () => {
5697
+ const info = solanaWallet.wallets.find((w) => normalizeSolanaWalletName(w.name) === normalizeSolanaWalletName(solanaWallet.walletName ?? ""));
5698
+ if (!info) throw new Error("Connect a Solana wallet to pay from Solana.");
5699
+ return solanaWalletSigner(info);
5700
+ },
5701
+ chainName: "Solana",
5702
+ fromTicker,
5703
+ toTicker,
5704
+ onError: config.onError
5705
+ });
5706
+ const fromBal = solActive ? solFlow.balanceRaw !== void 0 && fromToken ? { ...evmFromBal, raw: solFlow.balanceRaw.toString(), formatted: formatUnits(solFlow.balanceRaw, assetDecimals(fromToken)) } : void 0 : evmFromBal;
4649
5707
  const [preview, setPreview] = useState({ status: "idle" });
4650
5708
  const { idle: idle2, returnedAt: returnedAt2 } = useUserPresence();
4651
5709
  const prevReq = useRef(0);
4652
5710
  useEffect(() => {
4653
- if (isPill || wallet.account || !quotable) {
5711
+ if (isPill || sourceIsSolana || wallet.account && !needsRecipient || !quotable) {
4654
5712
  prevReq.current += 1;
4655
5713
  setPreview({ status: "idle" });
4656
5714
  return;
@@ -4658,23 +5716,24 @@ function ExchangeCard(props) {
4658
5716
  const id = ++prevReq.current;
4659
5717
  setPreview({ status: "loading" });
4660
5718
  const timer2 = setTimeout(() => {
4661
- engine.quoteSwapPreview({ fromChainId: from.chainId, toChainId: to.chainId, fromToken: from.symbol, toToken: to.symbol, amountIn: normalizedAmount, recipient: props.recipient }).then((data) => {
5719
+ engine.quoteSwapPreview({ fromChainId: from.chainId, toChainId: to.chainId, fromToken: from.symbol, toToken: to.symbol, amountIn: normalizedAmount, recipient }, wallet.account ?? void 0).then((data) => {
4662
5720
  if (id === prevReq.current) setPreview({ status: "ready", data });
4663
5721
  }).catch((e) => {
4664
5722
  if (id === prevReq.current) setPreview({ status: "error", error: e instanceof Error ? e.message : String(e), fieldError: amountFieldError(e) });
4665
5723
  });
4666
5724
  }, 350);
4667
5725
  return () => clearTimeout(timer2);
4668
- }, [engine, wallet.account, quotable, paramsKey, returnedAt2]);
4669
- const connected = Boolean(wallet.account);
4670
- const submitting = flow.status === "submitting";
5726
+ }, [engine, wallet.account, quotable, paramsKey, returnedAt2, needsRecipient, sourceIsSolana]);
5727
+ const connected2 = Boolean(wallet.account);
5728
+ const addressed = connected2 && !needsRecipient;
5729
+ const submitting = solActive ? solFlow.status === "preparing" || solFlow.status === "submitting" : flow.status === "submitting";
4671
5730
  const lastTxOwned = Boolean(flow.lastTxEntry?.hash && wallet.account && flow.lastTxEntry.account === wallet.account.toLowerCase());
4672
- const quoting = connected ? flow.status === "loading" : preview.status === "loading";
4673
- const quoteError = !quotable ? null : connected ? flow.status === "error" ? flow.error : null : preview.status === "error" ? preview.error ?? "No route." : null;
4674
- const gatewayAmountError = !quoteError ? null : connected ? flow.fieldError : preview.fieldError ?? null;
5731
+ const quoting = solActive ? solFlow.status === "quoting" : addressed ? flow.status === "loading" : preview.status === "loading";
5732
+ const quoteError = !quotable ? null : solActive ? solFlow.status === "error" || solFlow.status === "failed" ? solFlow.error : null : addressed ? flow.status === "error" ? flow.error : null : preview.status === "error" ? preview.error ?? "No route." : null;
5733
+ const gatewayAmountError = !quoteError || solActive ? null : addressed ? flow.fieldError : preview.fieldError ?? null;
4675
5734
  const amountError = overLimit && laneLimit ? laneLimitError(laneLimit, limitSymbol) : gatewayAmountError;
4676
5735
  const amountNote = mode === "exchange" ? amountError || (laneLimit ? laneLimitHint(laneLimit, limitSymbol) : null) : null;
4677
- const receive = connected ? flow.selected?.receive.amount : preview.data?.receive;
5736
+ const receive = solActive ? solFlow.preview?.receive : addressed ? flow.selected?.receive.amount : preview.data?.receive;
4678
5737
  const receiveOutRef = useRef(null);
4679
5738
  const receiveSideRef = useRef(null);
4680
5739
  const receiveShown = `${receive ?? ""}|${quoting}|${toTicker}`;
@@ -4687,7 +5746,7 @@ function ExchangeCard(props) {
4687
5746
  return void 0;
4688
5747
  }
4689
5748
  }, [toToken]);
4690
- const meta = connected ? flow.selected ? { bridge: flow.selected.quote.bridge || "ZeroDelta", feeBps: Number(flow.selected.quote.feeBps || 0), duration: Number(flow.selected.quote.estimatedDuration || 0) } : null : preview.data ? { bridge: preview.data.bridge || "ZeroDelta", feeBps: preview.data.feeBps, duration: preview.data.estimatedDuration } : null;
5749
+ const meta = solActive ? solFlow.preview ? { bridge: solFlow.preview.bridge || "ZeroDelta", feeBps: solFlow.preview.feeBps, duration: solFlow.preview.estimatedDuration } : null : addressed ? flow.selected ? { bridge: flow.selected.quote.bridge || "ZeroDelta", feeBps: Number(flow.selected.quote.feeBps || 0), duration: Number(flow.selected.quote.estimatedDuration || 0) } : null : preview.data ? { bridge: preview.data.bridge || "ZeroDelta", feeBps: preview.data.feeBps, duration: preview.data.estimatedDuration } : null;
4691
5750
  const pct = (p) => {
4692
5751
  if (!fromBal || !fromToken) return;
4693
5752
  const raw = BigInt(fromBal.raw);
@@ -4695,9 +5754,9 @@ function ExchangeCard(props) {
4695
5754
  };
4696
5755
  const title = config.title || (mode === "onramp" ? "Buy stablecoins" : mode === "offramp" ? "Cash out" : "Exchange");
4697
5756
  const soonLabel = mode === "onramp" ? "On-ramp coming soon" : "Off-ramp coming soon";
4698
- const quotePaused = connected ? flow.quotePaused : idle2 && preview.status === "ready";
4699
- const ctaLabel = rampMode ? soonLabel : submitting ? "Exchanging\u2026" : connected && flow.quoteStale ? flow.quotePaused ? "Refresh quote" : "Refreshing quote\u2026" : flow.insufficient ? "Insufficient balance" : flow.nativeShortfall || "Exchange";
4700
- const selected = connected ? flow.selected : null;
5757
+ const quotePaused = solActive ? false : addressed ? flow.quotePaused : idle2 && preview.status === "ready";
5758
+ const ctaLabel = rampMode ? soonLabel : submitting ? "Exchanging\u2026" : connected2 && flow.quoteStale ? flow.quotePaused ? "Refresh quote" : "Refreshing quote\u2026" : flow.insufficient ? "Insufficient balance" : flow.nativeShortfall || "Exchange";
5759
+ const selected = addressed ? flow.selected : null;
4701
5760
  const hasQuote = Boolean(quotable && !quoting && !quoteError && receive);
4702
5761
  const nativeWei = (() => {
4703
5762
  try {
@@ -4707,7 +5766,7 @@ function ExchangeCard(props) {
4707
5766
  return 0n;
4708
5767
  }
4709
5768
  })();
4710
- const networkFee = nativeWei > 0n ? `~${formatNative(nativeWei)} ${nativeSymbol(from?.chainId ?? 1, chains)}` : "Gas only";
5769
+ const networkFee = solActive ? solFlow.cost ? `~${(solFlow.cost.lamports / 1e9).toFixed(6)} SOL` : "Paid in SOL" : nativeWei > 0n ? `~${formatNative(nativeWei)} ${nativeSymbol(from?.chainId ?? 1, chains)}` : "Gas only";
4711
5770
  const eta = durationLabel(meta?.duration);
4712
5771
  const rate = hasQuote && receive && Number(normalizedAmount) > 0 ? (Number(receive) / Number(normalizedAmount)).toFixed(6) : null;
4713
5772
  const rateRows = hasQuote ? [{ label: "Network fee", value: networkFee }, ...eta ? [{ label: "Estimated time", value: eta }] : []] : [];
@@ -4715,8 +5774,8 @@ function ExchangeCard(props) {
4715
5774
  const routeShape = via === null ? "Direct" : via ? `Via ${via}` : "Two steps";
4716
5775
  const compliance = selected?.quote.compliance;
4717
5776
  const complianceHasQuote = Boolean(selected && flow.status !== "loading");
4718
- const fromUsd = usdOf(normalizedAmount, prices[from?.symbol ?? ""]);
4719
- const toUsd = usdOf(receive, prices[to?.symbol ?? ""]);
5777
+ const fromUsd = usdOf2(normalizedAmount, prices[from?.symbol ?? ""]);
5778
+ const toUsd = usdOf2(receive, prices[to?.symbol ?? ""]);
4720
5779
  const flippable = !rampMode && !submitting && Boolean(to && sourceTokens.some((t) => Number(t.chainId) === to.chainId && symbolKey(t.symbol) === to.symbol));
4721
5780
  const flip = () => {
4722
5781
  if (!flippable) return;
@@ -4724,8 +5783,8 @@ function ExchangeCard(props) {
4724
5783
  setTo(from);
4725
5784
  };
4726
5785
  const walletSlot = /* @__PURE__ */ jsxs("div", { className: "sg-head-tools", children: [
4727
- connected ? /* @__PURE__ */ jsx(HistoryButton, { btnRef: histBtnRef, disabled: submitting, onClick: () => setHist({}) }) : null,
4728
- /* @__PURE__ */ jsx("button", { type: "button", className: "sg-wallet", "data-connected": connected || void 0, onClick: connected ? void 0 : wallet.connect, disabled: wallet.connecting, children: connected ? /* @__PURE__ */ jsxs(Fragment, { children: [
5786
+ connected2 ? /* @__PURE__ */ jsx(HistoryButton, { btnRef: histBtnRef, disabled: submitting, onClick: () => setHist({}) }) : null,
5787
+ /* @__PURE__ */ jsx("button", { type: "button", className: "sg-wallet", "data-connected": connected2 || void 0, onClick: connected2 ? void 0 : wallet.connect, disabled: wallet.connecting, children: connected2 ? /* @__PURE__ */ jsxs(Fragment, { children: [
4729
5788
  /* @__PURE__ */ jsx("span", { className: "sg-wallet-dot", "aria-hidden": "true" }),
4730
5789
  " ",
4731
5790
  shortAddress(wallet.account)
@@ -4773,7 +5832,7 @@ function ExchangeCard(props) {
4773
5832
  }
4774
5833
  );
4775
5834
  const rateBox = (open) => /* @__PURE__ */ jsx(RateBox, { rate, fromSymbol: from?.symbol ?? "", fromLogoUrl: fromToken?.logoUrl, toTicker, rows: rateRows, defaultOpen: open, paused: quotePaused });
4776
- const sheetBody = sheet === "compliance" ? /* @__PURE__ */ jsx(ComplianceSheet, { compliance, direct: selected?.state === "DIRECT", hasQuote: complianceHasQuote, onClose: closeSheet }) : sheet === "quote" && hasQuote ? /* @__PURE__ */ jsx(
5835
+ const sheetBody = recipientState.open ? /* @__PURE__ */ jsx(RecipientSheet, { state: recipientState, symbol: toTicker }) : sheet === "compliance" ? /* @__PURE__ */ jsx(ComplianceSheet, { compliance, direct: selected?.state === "DIRECT", hasQuote: complianceHasQuote, onClose: closeSheet }) : sheet === "quote" && hasQuote ? /* @__PURE__ */ jsx(
4777
5836
  QuoteSheet,
4778
5837
  {
4779
5838
  onClose: closeSheet,
@@ -4790,8 +5849,33 @@ function ExchangeCard(props) {
4790
5849
  legs: selected && selected.legs.length > 1 ? selected.legs : void 0
4791
5850
  }
4792
5851
  ) : null;
5852
+ const connectPayer = async () => {
5853
+ const result = await solanaWallet.connect();
5854
+ setPayerChooser(Array.isArray(result) && result.length > 1);
5855
+ };
5856
+ const solanaCta = !solanaWallet.address ? /* @__PURE__ */ jsxs(Fragment, { children: [
5857
+ /* @__PURE__ */ jsx(Button, { onClick: () => void connectPayer(), busy: solanaWallet.status === "connecting", children: "Connect Solana wallet" }),
5858
+ payerChooser ? solanaWallet.wallets.map((w) => /* @__PURE__ */ jsx(Button, { variant: "ghost", onClick: () => void solanaWallet.connect(w.name).then(() => setPayerChooser(false)), disabled: solanaWallet.status === "connecting", children: w.name }, w.name)) : null,
5859
+ !solanaWallet.wallets.length ? /* @__PURE__ */ jsx("p", { className: "sg-cp-summary-sub", children: "No Solana wallet found. Install Phantom, Solflare or Backpack to pay from Solana." }) : null
5860
+ ] }) : !connected2 ? /* @__PURE__ */ jsxs(Fragment, { children: [
5861
+ /* @__PURE__ */ jsx(Button, { onClick: wallet.connect, busy: wallet.connecting, children: "Connect EVM wallet" }),
5862
+ /* @__PURE__ */ jsx("p", { className: "sg-cp-summary-sub", style: { textAlign: "center", margin: "8px 0 0" }, children: "Your EVM wallet owns the order and can cancel it." })
5863
+ ] }) : recipientState.missing ? /* @__PURE__ */ jsxs(Button, { onClick: () => void recipientState.connect(), busy: recipientState.familyWallet.connecting, children: [
5864
+ "Connect ",
5865
+ recipientState.recipientFamily === "solana" ? "Solana" : "EVM",
5866
+ " wallet"
5867
+ ] }) : /* @__PURE__ */ jsx(
5868
+ Button,
5869
+ {
5870
+ onClick: solFlow.run,
5871
+ busy: submitting,
5872
+ disabled: !quotable || !cryptoReady || !!recipientState.error || !solFlow.plan || solFlow.insufficient || solFlow.solShort || solFlow.status === "quoting",
5873
+ children: solFlow.status === "preparing" ? "Preparing order\u2026" : solFlow.status === "submitting" ? "Submitting\u2026" : solFlow.insufficient ? "Insufficient balance" : solFlow.solShort ? "Not enough SOL for network fees" : solFlow.status === "failed" ? "Try again" : !solFlow.plan ? "Exchange" : solFlow.needsPreparation ? "Continue in wallet" : "Submit"
5874
+ }
5875
+ );
5876
+ const solanaSteps = solActive && solFlow.plan && connected2 && solanaWallet.address ? /* @__PURE__ */ jsx("p", { className: "sg-cp-summary-sub", style: { textAlign: "center", margin: "0 0 8px" }, "data-testid": "solana-steps", children: solFlow.needsPreparation || solFlow.status === "preparing" ? "Prepare order \xB7 Submit \xB7 Track" : solFlow.status === "prepared" ? "Prepare order \u2713 \xB7 Submit \xB7 Track" : "Submit \xB7 Track" }) : null;
4793
5877
  let body;
4794
- if (hist && connected) {
5878
+ if (hist && connected2) {
4795
5879
  body = /* @__PURE__ */ jsx(TxHistoryPanel, { account: wallet.account, tokens, vaultIcons: catalogue?.vaultIcons, initialEntry: hist.entry ?? null, onBack: closeHistory });
4796
5880
  } else if (view === "from" || view === "to") {
4797
5881
  const isFrom = view === "from";
@@ -4799,6 +5883,9 @@ function ExchangeCard(props) {
4799
5883
  TokenSelect,
4800
5884
  {
4801
5885
  title: isFrom ? "Exchange from" : "Exchange to",
5886
+ side: isFrom ? "from" : "to",
5887
+ selected: isFrom ? from : to,
5888
+ fetchPrices: engine.fetchPrices,
4802
5889
  chains,
4803
5890
  tokens: isFrom ? fromPickerTokens : toPickerVisible,
4804
5891
  balances,
@@ -4813,6 +5900,26 @@ function ExchangeCard(props) {
4813
5900
  );
4814
5901
  } else if (sheetBody && !wide) {
4815
5902
  body = sheetBody;
5903
+ } else if (solActive && solFlow.status === "sent") {
5904
+ body = /* @__PURE__ */ jsxs(Fragment, { children: [
5905
+ /* @__PURE__ */ jsxs("div", { className: "sg-success", children: [
5906
+ /* @__PURE__ */ jsx("div", { className: "sg-success-check", "data-pending": "true", children: /* @__PURE__ */ jsx(CheckGlyph5, {}) }),
5907
+ /* @__PURE__ */ jsxs("div", { className: "sg-success-amt sg-mono", children: [
5908
+ solFlow.sent?.receive ?? receive,
5909
+ " ",
5910
+ solFlow.sent?.toTicker ?? toTicker
5911
+ ] }),
5912
+ /* @__PURE__ */ jsxs("div", { className: "sg-success-sub", children: [
5913
+ "Submitted on Solana \u2014 ZeroDelta delivers it",
5914
+ solFlow.sent?.recipient ? ` \xB7 ${shortAddress(solFlow.sent.recipient)}` : ""
5915
+ ] })
5916
+ ] }),
5917
+ /* @__PURE__ */ jsxs("div", { className: "sg-cta-wrap", children: [
5918
+ solFlow.signature ? /* @__PURE__ */ jsx("a", { className: "sg-btn sg-btn-ghost", href: `https://solscan.io/tx/${solFlow.signature}`, target: "_blank", rel: "noopener noreferrer", children: "View on Solscan" }) : null,
5919
+ solFlow.lastTxEntry && connected2 ? /* @__PURE__ */ jsx(Button, { variant: "ghost", onClick: () => setHist({ entry: solFlow.lastTxEntry }), children: "View transaction" }) : null,
5920
+ /* @__PURE__ */ jsx(Button, { variant: "ghost", onClick: solFlow.reset, children: "Start a new exchange" })
5921
+ ] })
5922
+ ] });
4816
5923
  } else if (flow.status === "success" || flow.status === "pending") {
4817
5924
  body = /* @__PURE__ */ jsxs(Fragment, { children: [
4818
5925
  /* @__PURE__ */ jsxs("div", { className: "sg-success", children: [
@@ -4824,7 +5931,7 @@ function ExchangeCard(props) {
4824
5931
  ] }),
4825
5932
  /* @__PURE__ */ jsxs("div", { className: "sg-success-sub", children: [
4826
5933
  flow.verdict?.status === "confirmed" ? "Confirmed on-chain" : "Submitted \u2014 awaiting confirmation",
4827
- props.recipient ? ` \xB7 ${shortAddress(props.recipient)}` : ""
5934
+ recipientState.recipientFamily === "solana" ? ` \xB7 ${shortAddress(flow.lastTxEntry?.recipient || recipient)}` : props.recipient ? ` \xB7 ${shortAddress(props.recipient)}` : ""
4828
5935
  ] })
4829
5936
  ] }),
4830
5937
  /* @__PURE__ */ jsxs("div", { className: "sg-cta-wrap", children: [
@@ -4835,8 +5942,19 @@ function ExchangeCard(props) {
4835
5942
  } else {
4836
5943
  const payToken = mode === "onramp" ? /* @__PURE__ */ jsx(FiatButton, { fiat, onCurrency: setFiatCurrency, disabled: submitting }) : /* @__PURE__ */ jsx(TokenButton, { label: "You pay", symbol: from?.symbol ?? null, chainId: from?.chainId ?? null, token: fromToken, disabled: submitting, btnRef: fromTileRef, onClick: () => setView("from") });
4837
5944
  const receiveToken = mode === "offramp" ? /* @__PURE__ */ jsx(FiatButton, { fiat, onCurrency: setFiatCurrency, disabled: submitting }) : /* @__PURE__ */ jsx(TokenButton, { label: "You receive", symbol: to?.symbol ?? null, chainId: to?.chainId ?? null, token: toToken, disabled: submitting, btnRef: toTileRef, onClick: () => setView("to") });
4838
- const cta = /* @__PURE__ */ jsxs("div", { className: "sg-cta-wrap", children: [
4839
- !connected && !rampMode ? /* @__PURE__ */ jsx(Button, { onClick: wallet.connect, busy: wallet.connecting, children: "Connect wallet" }) : /* @__PURE__ */ jsx(Button, { onClick: rampMode ? void 0 : flow.submit, busy: submitting, disabled: rampMode || !quotable || !cryptoReady || connected && (!flow.selected || flow.insufficient || !!flow.nativeShortfall || flow.status === "loading"), children: ctaLabel }),
5945
+ const cta = solActive ? /* @__PURE__ */ jsxs("div", { className: "sg-cta-wrap", children: [
5946
+ solanaSteps,
5947
+ solanaCta,
5948
+ /* @__PURE__ */ jsx(RecipientNote, { state: recipientState, disabled: submitting }),
5949
+ solanaWallet.error ? /* @__PURE__ */ jsx(StatusPanel, { tone: "error", children: solanaWallet.error }) : null,
5950
+ wallet.error ? /* @__PURE__ */ jsx(StatusPanel, { tone: "error", children: wallet.error }) : null
5951
+ ] }) : /* @__PURE__ */ jsxs("div", { className: "sg-cta-wrap", children: [
5952
+ !connected2 && !rampMode ? /* @__PURE__ */ jsx(Button, { onClick: wallet.connect, busy: wallet.connecting, children: "Connect wallet" }) : recipientState.missing && !rampMode && !submitting ? /* @__PURE__ */ jsxs(Button, { onClick: () => void recipientState.connect(), busy: recipientState.wallet.status === "connecting", children: [
5953
+ "Connect ",
5954
+ recipientState.recipientFamily === "solana" ? "Solana" : "EVM",
5955
+ " wallet"
5956
+ ] }) : /* @__PURE__ */ jsx(Button, { onClick: rampMode ? void 0 : flow.submit, busy: submitting, disabled: needsRecipient || rampMode || !quotable || !cryptoReady || connected2 && (!flow.selected || flow.insufficient || !!flow.nativeShortfall || flow.status === "loading"), children: ctaLabel }),
5957
+ !rampMode ? /* @__PURE__ */ jsx(RecipientNote, { state: recipientState, disabled: submitting }) : null,
4840
5958
  wallet.error ? /* @__PURE__ */ jsx(StatusPanel, { tone: "error", children: wallet.error }) : null
4841
5959
  ] });
4842
5960
  const notices = /* @__PURE__ */ jsxs(Fragment, { children: [
@@ -4985,4 +6103,4 @@ function mount(el, config) {
4985
6103
  return () => root.unmount();
4986
6104
  }
4987
6105
 
4988
- export { CompliancePanel, PaymentIsland, StableGenieExchange, StableGeniePay, StableGenieProvider, StableGenieRwaExchange, StableGenieSwap, darkTheme, lightTheme, mount, resolveTheme };
6106
+ export { CompliancePanel, PaymentIsland, StableGenieExchange, StableGeniePay, StableGenieProvider, StableGenieRwaExchange, StableGenieSwap, connectSolanaWallet, darkTheme, disconnectSolanaWallet, discoverSolanaWallets, lightTheme, mount, onSolanaAccountChange, resolveTheme, solanaWalletSigner, useSolanaWallet, watchSolanaWallets };