@edel-finance/swap-widget 0.0.0-stage → 0.0.2

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.
@@ -0,0 +1,89 @@
1
+ import { EdelClient, type EdelNetwork, type MarketSummary, type SwapOrder, type SwapOrderStatus, type SwapQuote } from "@edel-finance/sdk";
2
+ import type { CSSProperties } from "react";
3
+ import { type SwapWidgetTheme } from "./theme.js";
4
+ export declare const SWAP_STATUS_STEPS: ReadonlyArray<{
5
+ status: SwapOrderStatus;
6
+ label: string;
7
+ }>;
8
+ export declare const SWAP_RAIL_STEPS: readonly ["Quote", "Review", "Sign", "Settled"];
9
+ export declare const DEFAULT_SWAP_ASSETS: readonly ["CC", "USDCx", "EDELx", "NVDAe", "SPYe", "QQQe", "SPCXe", "ANTe", "TTWOe"];
10
+ /** Alpine Forest II slippage presets: 1.0% (default), 2.0%, 3.0%. */
11
+ export declare const SLIPPAGE_PRESETS_BPS: readonly [100, 200, 300];
12
+ export declare const DEFAULT_WIDGET_SLIPPAGE_BPS = 100;
13
+ export declare const DEFAULT_WIDGET_QUOTE_TTL_SECONDS = 20;
14
+ /**
15
+ * Resolve initial slippage in basis points.
16
+ * Never defaults below 100 bps (1.0%) when omitted or invalid; explicit valid
17
+ * values within 1..5000 bps are respected.
18
+ */
19
+ export declare function resolveInitialSlippageBps(bps?: number): number;
20
+ /**
21
+ * Parse a user-entered custom slippage percentage string (e.g. "1.5" -> 150 bps).
22
+ * Returns null if the input is outside 0.01%..50.00% (1..5000 bps).
23
+ */
24
+ export declare function parseCustomSlippagePercent(raw: string): number | null;
25
+ export interface SwapRailProgress {
26
+ index: 0 | 1 | 2 | 3;
27
+ complete: boolean;
28
+ }
29
+ /**
30
+ * Map current swap quote / order state to the 4-step top progress rail.
31
+ */
32
+ export declare function getSwapRailProgress(quote: SwapQuote | null, order: SwapOrder | null): SwapRailProgress;
33
+ export interface EdelSwapWidgetProps {
34
+ /** Integrator / partner identifier for fee attribution (SuperNova, Loop, etc.). */
35
+ integratorId?: string;
36
+ /** Backwards-compatible alias for integratorId. */
37
+ partnerId?: string;
38
+ /** Color theme: Alpine Forest II dark or light. Defaults to "dark". */
39
+ theme?: SwapWidgetTheme;
40
+ /** Target Edel network (MainNet or TestNet). Defaults to "mainnet". */
41
+ network?: EdelNetwork;
42
+ /** Default input asset symbol. Defaults to "CC". */
43
+ defaultFrom?: string;
44
+ /** Default output asset symbol. Defaults to "USDCx". */
45
+ defaultTo?: string;
46
+ /** Backwards-compatible alias for defaultFrom. */
47
+ defaultFromAsset?: string;
48
+ /** Backwards-compatible alias for defaultTo. */
49
+ defaultToAsset?: string;
50
+ /** Initial max slippage in basis points (1..5000). Defaults to 100 (1.0%). */
51
+ defaultMaxSlippageBps?: number;
52
+ /** Optional recipient Canton party / address for settlement. */
53
+ recipientAddress?: string;
54
+ /** Optional integrator fee markup in basis points. */
55
+ integratorFeeBps?: number;
56
+ /** Optional pre-configured EdelClient instance (useful for custom auth or testing). */
57
+ client?: EdelClient;
58
+ /** Optional initial quote (useful for SSR preview or testing). */
59
+ initialQuote?: SwapQuote | null;
60
+ /** Optional initial active order (useful for SSR preview or testing). */
61
+ initialOrder?: SwapOrder | null;
62
+ /** Optional initial baseAsset -> HTTPS logoUrl map (useful for SSR preview or testing). */
63
+ initialLogoUrls?: Readonly<Record<string, string>>;
64
+ /** Callback fired whenever a live quote is fetched. */
65
+ onQuote?: (quote: SwapQuote) => void;
66
+ /** Callback fired when the user updates max slippage (in basis points). */
67
+ onSlippageChange?: (maxSlippageBps: number) => void;
68
+ /** Callback fired when an active swap reaches the "settled" state. */
69
+ onSwapComplete?: (order: SwapOrder) => void;
70
+ /** Callback fired when an order is submitted via POST /v2/swaps/orders/:swapId/submit. */
71
+ onOrderSubmitted?: (order: SwapOrder) => void;
72
+ /** Callback fired on quote or execution errors. */
73
+ onError?: (error: Error) => void;
74
+ /** Additional inline styles applied to the root container. */
75
+ style?: CSSProperties;
76
+ }
77
+ export declare function getStepState(stepStatus: SwapOrderStatus, currentStatus: SwapOrderStatus): "done" | "active" | "pending";
78
+ export declare function formatBps(bps: number): string;
79
+ export declare function formatPresetPercent(bps: number): string;
80
+ /**
81
+ * Extract a baseAsset -> HTTPS logoUrl map from Edel Markets API summaries.
82
+ * Ignores markets with logoUnavailable === true or non-HTTPS URLs.
83
+ */
84
+ export declare function extractMarketLogoUrls(markets: readonly MarketSummary[]): Record<string, string>;
85
+ /**
86
+ * Filter token options by symbol or display name (case-insensitive).
87
+ */
88
+ export declare function filterTokenOptions(options: readonly string[], query: string, assetNames?: Readonly<Record<string, string>>): string[];
89
+ export declare function EdelSwapWidget(props: EdelSwapWidgetProps): import("react").JSX.Element;
package/dist/widget.js ADDED
@@ -0,0 +1,473 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { DEFAULT_MAX_SLIPPAGE_BPS, DEFAULT_QUOTE_TTL_SECONDS, EdelClient, MAX_SLIPPAGE_BPS, MIN_SLIPPAGE_BPS, } from "@edel-finance/sdk";
3
+ import { useEffect, useMemo, useRef, useState } from "react";
4
+ import { EdelBrandMark, getTokenDisplayName, isValidHttpsLogoUrl, TokenOnChainLogo, } from "./logos.js";
5
+ import { getIsolatedWidgetCss } from "./theme.js";
6
+ export const SWAP_STATUS_STEPS = [
7
+ { status: "quoted", label: "Quoted" },
8
+ { status: "awaiting_lock", label: "Awaiting Lock" },
9
+ { status: "locked", label: "Locked" },
10
+ { status: "filled", label: "Filled" },
11
+ { status: "settled", label: "Settled" },
12
+ ];
13
+ export const SWAP_RAIL_STEPS = ["Quote", "Review", "Sign", "Settled"];
14
+ export const DEFAULT_SWAP_ASSETS = [
15
+ "CC",
16
+ "USDCx",
17
+ "EDELx",
18
+ "NVDAe",
19
+ "SPYe",
20
+ "QQQe",
21
+ "SPCXe",
22
+ "ANTe",
23
+ "TTWOe",
24
+ ];
25
+ /** Alpine Forest II slippage presets: 1.0% (default), 2.0%, 3.0%. */
26
+ export const SLIPPAGE_PRESETS_BPS = [100, 200, 300];
27
+ export const DEFAULT_WIDGET_SLIPPAGE_BPS = DEFAULT_MAX_SLIPPAGE_BPS;
28
+ export const DEFAULT_WIDGET_QUOTE_TTL_SECONDS = DEFAULT_QUOTE_TTL_SECONDS;
29
+ /**
30
+ * Resolve initial slippage in basis points.
31
+ * Never defaults below 100 bps (1.0%) when omitted or invalid; explicit valid
32
+ * values within 1..5000 bps are respected.
33
+ */
34
+ export function resolveInitialSlippageBps(bps) {
35
+ if (bps === undefined || !Number.isFinite(bps)) {
36
+ return DEFAULT_WIDGET_SLIPPAGE_BPS;
37
+ }
38
+ const rounded = Math.round(bps);
39
+ if (rounded < MIN_SLIPPAGE_BPS || rounded > MAX_SLIPPAGE_BPS) {
40
+ return DEFAULT_WIDGET_SLIPPAGE_BPS;
41
+ }
42
+ return rounded;
43
+ }
44
+ /**
45
+ * Parse a user-entered custom slippage percentage string (e.g. "1.5" -> 150 bps).
46
+ * Returns null if the input is outside 0.01%..50.00% (1..5000 bps).
47
+ */
48
+ export function parseCustomSlippagePercent(raw) {
49
+ const trimmed = raw.trim();
50
+ if (!trimmed)
51
+ return null;
52
+ const pct = Number(trimmed);
53
+ if (!Number.isFinite(pct) || pct <= 0)
54
+ return null;
55
+ const bps = Math.round(pct * 100);
56
+ if (bps < MIN_SLIPPAGE_BPS || bps > MAX_SLIPPAGE_BPS)
57
+ return null;
58
+ return bps;
59
+ }
60
+ /**
61
+ * Map current swap quote / order state to the 4-step top progress rail.
62
+ */
63
+ export function getSwapRailProgress(quote, order) {
64
+ if (order) {
65
+ if (order.status === "settled")
66
+ return { index: 3, complete: true };
67
+ if (order.status === "filled")
68
+ return { index: 3, complete: false };
69
+ return { index: 2, complete: false };
70
+ }
71
+ if (quote)
72
+ return { index: 1, complete: false };
73
+ return { index: 0, complete: false };
74
+ }
75
+ export function getStepState(stepStatus, currentStatus) {
76
+ const order = SWAP_STATUS_STEPS.map((s) => s.status);
77
+ const stepIdx = order.indexOf(stepStatus);
78
+ const curIdx = order.indexOf(currentStatus);
79
+ if (curIdx === -1)
80
+ return "pending";
81
+ if (stepIdx < curIdx || currentStatus === "settled")
82
+ return "done";
83
+ if (stepIdx === curIdx)
84
+ return "active";
85
+ return "pending";
86
+ }
87
+ export function formatBps(bps) {
88
+ return `${(bps / 100).toFixed(2)}%`;
89
+ }
90
+ export function formatPresetPercent(bps) {
91
+ return `${(bps / 100).toFixed(1)}%`;
92
+ }
93
+ /**
94
+ * Extract a baseAsset -> HTTPS logoUrl map from Edel Markets API summaries.
95
+ * Ignores markets with logoUnavailable === true or non-HTTPS URLs.
96
+ */
97
+ export function extractMarketLogoUrls(markets) {
98
+ const map = {};
99
+ for (const market of markets) {
100
+ const info = market && typeof market.info === "object" && market.info !== null
101
+ ? market.info
102
+ : null;
103
+ if (!info || info.logoUnavailable === true)
104
+ continue;
105
+ if (!isValidHttpsLogoUrl(info.logoUrl))
106
+ continue;
107
+ const logoUrl = info.logoUrl.trim();
108
+ const baseAsset = typeof info.baseAsset === "string" ? info.baseAsset.trim() : "";
109
+ const marketBase = typeof market.base === "string" ? market.base.trim() : "";
110
+ if (baseAsset && !(baseAsset in map)) {
111
+ map[baseAsset] = logoUrl;
112
+ }
113
+ if (marketBase && !(marketBase in map)) {
114
+ map[marketBase] = logoUrl;
115
+ }
116
+ }
117
+ return map;
118
+ }
119
+ /**
120
+ * Filter token options by symbol or display name (case-insensitive).
121
+ */
122
+ export function filterTokenOptions(options, query, assetNames) {
123
+ const q = query.trim().toLowerCase();
124
+ if (!q)
125
+ return [...options];
126
+ return options.filter((sym) => {
127
+ const name = getTokenDisplayName(sym, assetNames?.[sym]).toLowerCase();
128
+ return sym.toLowerCase().includes(q) || name.includes(q);
129
+ });
130
+ }
131
+ function TokenPickerButton({ ariaLabel, value, open, logoUrls, onToggle, testId, }) {
132
+ return (_jsx("div", { className: "edel-sw-token-picker", "data-testid": testId, children: _jsxs("button", { type: "button", className: "edel-sw-token-trigger", "aria-label": ariaLabel, "aria-haspopup": "listbox", "aria-expanded": open, "data-selected-asset": value, onClick: onToggle, children: [_jsx(TokenOnChainLogo, { symbol: value, size: 24, className: "edel-sw-token-icon", logoUrl: logoUrls?.[value] }), _jsx("span", { className: "edel-sw-token-symbol", children: value }), _jsx("svg", { width: "14", height: "14", viewBox: "0 0 16 16", fill: "none", xmlns: "http://www.w3.org/2000/svg", className: "edel-sw-token-chevron", "aria-hidden": "true", focusable: "false", children: _jsx("path", { d: "M4 6L8 10L12 6", stroke: "currentColor", strokeWidth: "1.6", strokeLinecap: "round", strokeLinejoin: "round" }) })] }) }));
133
+ }
134
+ function TokenDropdown({ ariaLabel, value, options, assetNames, logoUrls, onSelect, onClose, testId, }) {
135
+ const [query, setQuery] = useState("");
136
+ const inputRef = useRef(null);
137
+ useEffect(() => {
138
+ inputRef.current?.focus();
139
+ }, []);
140
+ const filtered = useMemo(() => filterTokenOptions(options, query, assetNames), [options, query, assetNames]);
141
+ return (_jsxs("div", { className: "edel-sw-token-menu", role: "listbox", "aria-label": ariaLabel, "data-testid": testId, children: [_jsxs("div", { className: "edel-sw-token-search", children: [_jsxs("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", xmlns: "http://www.w3.org/2000/svg", "aria-hidden": "true", focusable: "false", children: [_jsx("circle", { cx: "11", cy: "11", r: "7", stroke: "currentColor", strokeWidth: "2" }), _jsx("path", { d: "M20 20L16.65 16.65", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round" })] }), _jsx("input", { ref: inputRef, type: "search", placeholder: "Search token...", "aria-label": "Search token", value: query, onChange: (e) => setQuery(e.target.value), onKeyDown: (e) => {
142
+ if (e.key === "Escape") {
143
+ e.stopPropagation();
144
+ onClose();
145
+ }
146
+ } })] }), _jsx("div", { className: "edel-sw-token-list", children: filtered.length === 0 ? (_jsxs("div", { className: "edel-sw-token-empty", children: ["No tokens matching \u201C", query.trim(), "\u201D"] })) : (filtered.map((sym) => {
147
+ const selected = sym === value;
148
+ const displayName = getTokenDisplayName(sym, assetNames?.[sym]);
149
+ return (_jsxs("button", { type: "button", role: "option", "aria-selected": selected, className: "edel-sw-token-option", "data-token-option": sym, onClick: () => {
150
+ onSelect(sym);
151
+ onClose();
152
+ }, children: [_jsx(TokenOnChainLogo, { symbol: sym, size: 28, className: "edel-sw-token-icon", logoUrl: logoUrls?.[sym] }), _jsxs("span", { className: "edel-sw-token-option-text", children: [_jsx("strong", { children: sym }), _jsx("span", { children: displayName })] }), _jsx("span", { className: "edel-sw-token-option-aside", children: "Canton" }), _jsx("span", { className: "edel-sw-token-check", "aria-hidden": "true", children: selected ? (_jsx("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", xmlns: "http://www.w3.org/2000/svg", "aria-hidden": "true", focusable: "false", children: _jsx("path", { d: "M5 13L9.5 17.5L19 7.5", stroke: "currentColor", strokeWidth: "2.4", strokeLinecap: "round", strokeLinejoin: "round" }) })) : null })] }, sym));
153
+ })) })] }));
154
+ }
155
+ export function EdelSwapWidget(props) {
156
+ const { integratorId, partnerId, theme = "dark", network = "mainnet", defaultFrom, defaultTo, defaultFromAsset, defaultToAsset, defaultMaxSlippageBps, recipientAddress = "", integratorFeeBps, client: providedClient, initialQuote = null, initialOrder = null, initialLogoUrls, onQuote, onSlippageChange, onSwapComplete, onOrderSubmitted, onError, style, } = props;
157
+ const effectiveIntegratorId = integratorId ?? partnerId;
158
+ const client = useMemo(() => providedClient ?? new EdelClient({ network }), [providedClient, network]);
159
+ const initialSlippage = resolveInitialSlippageBps(defaultMaxSlippageBps);
160
+ const isInitialPreset = SLIPPAGE_PRESETS_BPS.includes(initialSlippage);
161
+ const [pairs, setPairs] = useState([]);
162
+ const [logoUrls, setLogoUrls] = useState(() => ({
163
+ ...initialLogoUrls,
164
+ }));
165
+ const [fromAsset, setFromAsset] = useState(defaultFrom ?? defaultFromAsset ?? "CC");
166
+ const [toAsset, setToAsset] = useState(defaultTo ?? defaultToAsset ?? "USDCx");
167
+ const [fromAmount, setFromAmount] = useState("100");
168
+ const [recipient] = useState(recipientAddress);
169
+ const [maxSlippageBps, setMaxSlippageBps] = useState(initialSlippage);
170
+ const [customMode, setCustomMode] = useState(!isInitialPreset);
171
+ const [customSlippageInput, setCustomSlippageInput] = useState(isInitialPreset ? "" : (initialSlippage / 100).toFixed(2));
172
+ const [quote, setQuote] = useState(initialQuote);
173
+ const [order, setOrder] = useState(initialOrder);
174
+ const [loadingQuote, setLoadingQuote] = useState(false);
175
+ const [submitting, setSubmitting] = useState(false);
176
+ const [submittingSigned, setSubmittingSigned] = useState(false);
177
+ const [errorMessage, setErrorMessage] = useState(null);
178
+ const [remainingSec, setRemainingSec] = useState(initialQuote?.ttlSeconds ?? DEFAULT_WIDGET_QUOTE_TTL_SECONDS);
179
+ const [openPicker, setOpenPicker] = useState(null);
180
+ const [flipCount, setFlipCount] = useState(0);
181
+ const completedRef = useRef(null);
182
+ const pairRef = useRef(null);
183
+ // Close open token dropdown on outside click or Escape
184
+ useEffect(() => {
185
+ if (!openPicker)
186
+ return;
187
+ const handlePointerDown = (event) => {
188
+ const container = pairRef.current;
189
+ if (!container)
190
+ return;
191
+ const path = typeof event.composedPath === "function" ? event.composedPath() : [];
192
+ if (path.length > 0 ? !path.includes(container) : !container.contains(event.target)) {
193
+ setOpenPicker(null);
194
+ }
195
+ };
196
+ const handleKeyDown = (event) => {
197
+ if (event.key === "Escape") {
198
+ setOpenPicker(null);
199
+ }
200
+ };
201
+ document.addEventListener("pointerdown", handlePointerDown);
202
+ document.addEventListener("keydown", handleKeyDown);
203
+ return () => {
204
+ document.removeEventListener("pointerdown", handlePointerDown);
205
+ document.removeEventListener("keydown", handleKeyDown);
206
+ };
207
+ }, [openPicker]);
208
+ const { assetSymbols, assetNames } = useMemo(() => {
209
+ if (pairs.length === 0) {
210
+ return {
211
+ assetSymbols: [...DEFAULT_SWAP_ASSETS],
212
+ assetNames: {},
213
+ };
214
+ }
215
+ const set = new Set();
216
+ const names = {};
217
+ for (const pair of pairs) {
218
+ if (pair.active) {
219
+ set.add(pair.fromAsset.symbol);
220
+ set.add(pair.toAsset.symbol);
221
+ if (pair.fromAsset.name)
222
+ names[pair.fromAsset.symbol] = pair.fromAsset.name;
223
+ if (pair.toAsset.name)
224
+ names[pair.toAsset.symbol] = pair.toAsset.name;
225
+ }
226
+ }
227
+ return {
228
+ assetSymbols: set.size > 0 ? Array.from(set) : [...DEFAULT_SWAP_ASSETS],
229
+ assetNames: names,
230
+ };
231
+ }, [pairs]);
232
+ // Hydrate tradable swap pairs and official token logos from @edel-finance/sdk
233
+ useEffect(() => {
234
+ let active = true;
235
+ client
236
+ .getSwapPairs()
237
+ .then((res) => {
238
+ if (active && Array.isArray(res)) {
239
+ setPairs(res);
240
+ }
241
+ })
242
+ .catch(() => {
243
+ // Fallback to DEFAULT_SWAP_ASSETS if endpoint is unreachable during offline preview
244
+ });
245
+ if (typeof client.getMarkets === "function") {
246
+ client
247
+ .getMarkets()
248
+ .catch(() => [])
249
+ .then((markets) => {
250
+ if (!active || !Array.isArray(markets))
251
+ return;
252
+ const next = extractMarketLogoUrls(markets);
253
+ if (Object.keys(next).length > 0) {
254
+ setLogoUrls((prev) => ({ ...prev, ...next }));
255
+ }
256
+ });
257
+ }
258
+ return () => {
259
+ active = false;
260
+ };
261
+ }, [client]);
262
+ // Fetch live RFQ quote when pair, amount, or maxSlippageBps changes
263
+ useEffect(() => {
264
+ const parsedAmount = Number(fromAmount);
265
+ if (!Number.isFinite(parsedAmount) || parsedAmount <= 0 || fromAsset === toAsset) {
266
+ setQuote(null);
267
+ return;
268
+ }
269
+ let cancelled = false;
270
+ setLoadingQuote(true);
271
+ setErrorMessage(null);
272
+ client
273
+ .getSwapQuote({
274
+ fromAsset,
275
+ toAsset,
276
+ fromAmount,
277
+ maxSlippageBps,
278
+ integratorId: effectiveIntegratorId,
279
+ integratorFeeBps,
280
+ recipientAddress: recipient || undefined,
281
+ })
282
+ .then((q) => {
283
+ if (cancelled)
284
+ return;
285
+ setQuote(q);
286
+ const fallbackTtl = q.ttlSeconds || DEFAULT_WIDGET_QUOTE_TTL_SECONDS;
287
+ const secs = Math.max(0, Math.ceil((q.expiresAtEpochMs - Date.now()) / 1000));
288
+ setRemainingSec(secs || fallbackTtl);
289
+ onQuote?.(q);
290
+ })
291
+ .catch((err) => {
292
+ if (cancelled)
293
+ return;
294
+ const e = err instanceof Error ? err : new Error(String(err));
295
+ setErrorMessage(e.message);
296
+ onError?.(e);
297
+ })
298
+ .finally(() => {
299
+ if (!cancelled)
300
+ setLoadingQuote(false);
301
+ });
302
+ return () => {
303
+ cancelled = true;
304
+ };
305
+ }, [
306
+ client,
307
+ fromAsset,
308
+ toAsset,
309
+ fromAmount,
310
+ maxSlippageBps,
311
+ effectiveIntegratorId,
312
+ integratorFeeBps,
313
+ recipient,
314
+ onQuote,
315
+ onError,
316
+ ]);
317
+ // Countdown quote TTL (20s default window)
318
+ useEffect(() => {
319
+ if (!quote)
320
+ return;
321
+ const tick = () => {
322
+ const secs = Math.max(0, Math.ceil((quote.expiresAtEpochMs - Date.now()) / 1000));
323
+ setRemainingSec(secs);
324
+ };
325
+ tick();
326
+ const timer = setInterval(tick, 1000);
327
+ return () => clearInterval(timer);
328
+ }, [quote]);
329
+ const activeOrderId = order?.swapId ?? order?.orderId;
330
+ const activeOrderStatus = order?.status;
331
+ // Subscribe to WebSocket live swap status transitions
332
+ useEffect(() => {
333
+ if (!activeOrderId ||
334
+ activeOrderStatus === "settled" ||
335
+ activeOrderStatus === "failed" ||
336
+ activeOrderStatus === "expired") {
337
+ return;
338
+ }
339
+ const rt = client.realtime();
340
+ const unsubscribe = rt.subscribeSwapOrder(activeOrderId, (event) => {
341
+ setOrder((prev) => {
342
+ if (!prev || (prev.swapId ?? prev.orderId) !== event.orderId)
343
+ return prev;
344
+ const next = {
345
+ ...prev,
346
+ status: event.status,
347
+ txHash: event.txHash ?? prev.txHash,
348
+ settlementTxHash: event.settlementTxHash ?? prev.settlementTxHash,
349
+ updatedAtEpochMs: event.updatedAtEpochMs,
350
+ };
351
+ if (next.status === "settled" && completedRef.current !== next.orderId) {
352
+ completedRef.current = next.orderId;
353
+ onSwapComplete?.(next);
354
+ }
355
+ return next;
356
+ });
357
+ });
358
+ rt.connect();
359
+ return () => {
360
+ unsubscribe();
361
+ rt.close();
362
+ };
363
+ }, [client, activeOrderId, activeOrderStatus, onSwapComplete]);
364
+ const handleFlip = () => {
365
+ const prevFrom = fromAsset;
366
+ const prevTo = toAsset;
367
+ setFromAsset(prevTo);
368
+ setToAsset(prevFrom);
369
+ setFlipCount((c) => c + 1);
370
+ setOpenPicker(null);
371
+ };
372
+ const handleSelectFromAsset = (next) => {
373
+ if (next === toAsset) {
374
+ setToAsset(fromAsset);
375
+ }
376
+ setFromAsset(next);
377
+ };
378
+ const handleSelectToAsset = (next) => {
379
+ if (next === fromAsset) {
380
+ setFromAsset(toAsset);
381
+ }
382
+ setToAsset(next);
383
+ };
384
+ const handleSelectPreset = (bps) => {
385
+ setCustomMode(false);
386
+ setCustomSlippageInput("");
387
+ setMaxSlippageBps(bps);
388
+ onSlippageChange?.(bps);
389
+ };
390
+ const handleCustomSlippageChange = (raw) => {
391
+ setCustomMode(true);
392
+ setCustomSlippageInput(raw);
393
+ const parsed = parseCustomSlippagePercent(raw);
394
+ if (parsed !== null) {
395
+ setMaxSlippageBps(parsed);
396
+ onSlippageChange?.(parsed);
397
+ }
398
+ };
399
+ const handleSwap = async () => {
400
+ if (!quote || submitting)
401
+ return;
402
+ setSubmitting(true);
403
+ setErrorMessage(null);
404
+ try {
405
+ const created = await client.createSwapOrder({
406
+ quoteId: quote.quoteId,
407
+ recipientAddress: recipient || "self",
408
+ maxSlippageBps,
409
+ integratorId: effectiveIntegratorId,
410
+ });
411
+ setOrder(created);
412
+ if (created.status === "settled" && completedRef.current !== created.orderId) {
413
+ completedRef.current = created.orderId;
414
+ onSwapComplete?.(created);
415
+ }
416
+ }
417
+ catch (err) {
418
+ const e = err instanceof Error ? err : new Error(String(err));
419
+ setErrorMessage(e.message);
420
+ onError?.(e);
421
+ }
422
+ finally {
423
+ setSubmitting(false);
424
+ }
425
+ };
426
+ const handleSubmitOrder = async () => {
427
+ if (!order || submittingSigned)
428
+ return;
429
+ setSubmittingSigned(true);
430
+ setErrorMessage(null);
431
+ try {
432
+ const targetSwapId = order.swapId ?? order.orderId;
433
+ const submitted = await client.submitSwapOrder(targetSwapId, {
434
+ senderAddress: recipient || undefined,
435
+ });
436
+ setOrder(submitted);
437
+ onOrderSubmitted?.(submitted);
438
+ if (submitted.status === "settled" && completedRef.current !== submitted.orderId) {
439
+ completedRef.current = submitted.orderId;
440
+ onSwapComplete?.(submitted);
441
+ }
442
+ }
443
+ catch (err) {
444
+ const e = err instanceof Error ? err : new Error(String(err));
445
+ setErrorMessage(e.message);
446
+ onError?.(e);
447
+ }
448
+ finally {
449
+ setSubmittingSigned(false);
450
+ }
451
+ };
452
+ const effectiveTtlSeconds = quote?.ttlSeconds || DEFAULT_WIDGET_QUOTE_TTL_SECONDS;
453
+ const ttlPercent = quote && effectiveTtlSeconds > 0
454
+ ? Math.max(0, Math.min(100, (remainingSec / effectiveTtlSeconds) * 100))
455
+ : 0;
456
+ const parsedFromAmount = Number(fromAmount);
457
+ const hasPositiveAmount = Number.isFinite(parsedFromAmount) && parsedFromAmount > 0;
458
+ const canSubmitOrder = order !== null && (order.status === "quoted" || order.status === "awaiting_lock");
459
+ const rail = getSwapRailProgress(quote, order);
460
+ return (_jsxs("div", { className: "edel-sw-root", "data-edel-theme": theme, "data-edel-network": network, "data-max-slippage-bps": maxSlippageBps, style: style, children: [_jsx("style", { children: getIsolatedWidgetCss(theme) }), _jsxs("div", { className: "edel-sw-header", children: [_jsxs("span", { className: "edel-sw-brand", children: [_jsx(EdelBrandMark, { size: 20, className: "edel-sw-brand-mark" }), _jsx("span", { className: "edel-sw-title", children: "Edel Swap" })] }), _jsx("span", { className: "edel-sw-badge", children: network === "mainnet" ? "MainNet" : "TestNet" })] }), _jsx("ol", { className: "edel-sw-rail", "aria-label": "Swap steps", "data-testid": "swap-step-rail", children: SWAP_RAIL_STEPS.map((label, idx) => {
461
+ const state = rail.complete || idx < rail.index ? "done" : idx === rail.index ? "current" : "next";
462
+ return (_jsx("li", { className: "edel-sw-rail-step", "data-state": state, "aria-current": state === "current" ? "step" : undefined, children: _jsxs("span", { className: "edel-sw-rail-inner", children: [_jsx("span", { className: "edel-sw-rail-marker", "aria-hidden": "true", children: state === "done" ? (_jsx("svg", { width: "12", height: "12", viewBox: "0 0 24 24", fill: "none", xmlns: "http://www.w3.org/2000/svg", "aria-hidden": "true", focusable: "false", children: _jsx("path", { d: "M5 13L9.5 17.5L19 7.5", stroke: "currentColor", strokeWidth: "3", strokeLinecap: "round", strokeLinejoin: "round" }) })) : (idx + 1) }), _jsx("span", { className: "edel-sw-rail-label", children: label })] }) }, label));
463
+ }) }), _jsxs("div", { className: "edel-sw-pair", ref: pairRef, children: [_jsxs("div", { className: "edel-sw-box-wrap", children: [_jsxs("div", { className: "edel-sw-box", "data-pay": "true", children: [_jsxs("div", { className: "edel-sw-label", children: [_jsx("span", { children: "You send" }), _jsx("span", { className: "edel-sw-label-meta", children: "Canton Network" })] }), _jsxs("div", { className: "edel-sw-row", children: [_jsx("input", { "aria-label": "From amount", className: "edel-sw-input", inputMode: "decimal", value: fromAmount, onChange: (e) => setFromAmount(e.target.value), placeholder: "0" }), _jsx(TokenPickerButton, { ariaLabel: "From asset", testId: "from-asset-selector", value: fromAsset, open: openPicker === "from", logoUrls: logoUrls, onToggle: () => setOpenPicker((prev) => (prev === "from" ? null : "from")) })] }), _jsx("div", { className: "edel-sw-box-sub", children: _jsx("span", { children: getTokenDisplayName(fromAsset, assetNames[fromAsset]) }) })] }), openPicker === "from" && (_jsx(TokenDropdown, { ariaLabel: "Select token to send", testId: "from-asset-dropdown", value: fromAsset, options: assetSymbols, assetNames: assetNames, logoUrls: logoUrls, onSelect: handleSelectFromAsset, onClose: () => setOpenPicker(null) }))] }), _jsx("button", { type: "button", className: "edel-sw-flip", "aria-label": "Flip swap pair", "data-testid": "flip-pair-btn", "data-flip-count": flipCount, onClick: handleFlip, children: _jsx("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", xmlns: "http://www.w3.org/2000/svg", className: "edel-sw-flip-icon", style: { transform: `rotate(${flipCount * 180}deg)` }, "aria-hidden": "true", focusable: "false", children: _jsx("path", { d: "M7 4V20M7 4L3.5 7.5M7 4L10.5 7.5M17 20V4M17 20L13.5 16.5M17 20L20.5 16.5", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }) }) }), _jsxs("div", { className: "edel-sw-box-wrap", children: [_jsxs("div", { className: "edel-sw-box", children: [_jsxs("div", { className: "edel-sw-label", children: [_jsx("span", { children: "You receive" }), quote?.estimatedSeconds !== undefined && (_jsxs("span", { className: "edel-sw-label-meta", children: ["~", quote.estimatedSeconds, "s"] }))] }), _jsxs("div", { className: "edel-sw-row", children: [_jsx("input", { "aria-label": "To amount", className: "edel-sw-input", "data-empty": !quote && !loadingQuote ? "true" : undefined, readOnly: true, value: loadingQuote ? "..." : (quote?.toAmount ?? "0") }), _jsx(TokenPickerButton, { ariaLabel: "To asset", testId: "to-asset-selector", value: toAsset, open: openPicker === "to", logoUrls: logoUrls, onToggle: () => setOpenPicker((prev) => (prev === "to" ? null : "to")) })] }), _jsx("div", { className: "edel-sw-box-sub", children: _jsx("span", { children: getTokenDisplayName(toAsset, assetNames[toAsset]) }) })] }), openPicker === "to" && (_jsx(TokenDropdown, { ariaLabel: "Select token to receive", testId: "to-asset-dropdown", value: toAsset, options: assetSymbols, assetNames: assetNames, logoUrls: logoUrls, onSelect: handleSelectToAsset, onClose: () => setOpenPicker(null) }))] })] }), _jsxs("div", { className: "edel-sw-slippage", "data-testid": "slippage-selector", children: [_jsxs("div", { className: "edel-sw-slippage-header", children: [_jsx("span", { children: "Max slippage" }), _jsx("strong", { children: formatBps(maxSlippageBps) })] }), _jsxs("fieldset", { className: "edel-sw-slippage-pills", "aria-label": "Max slippage presets", children: [SLIPPAGE_PRESETS_BPS.map((bps) => {
464
+ const isActive = !customMode && maxSlippageBps === bps;
465
+ return (_jsx("button", { type: "button", className: "edel-sw-pill", "data-slippage-bps": bps, "data-active": isActive ? "true" : "false", "aria-pressed": isActive, onClick: () => handleSelectPreset(bps), children: formatPresetPercent(bps) }, bps));
466
+ }), _jsxs("div", { className: "edel-sw-custom-wrap", "data-active": customMode ? "true" : "false", children: [_jsx("input", { "aria-label": "Custom slippage percent", className: "edel-sw-custom-input", inputMode: "decimal", placeholder: "Custom", value: customSlippageInput, onFocus: () => setCustomMode(true), onChange: (e) => handleCustomSlippageChange(e.target.value) }), _jsx("span", { className: "edel-sw-custom-suffix", children: "%" })] })] })] }), quote && (_jsxs("div", { className: "edel-sw-fees", "data-testid": "quote-fee-breakdown", "data-min-amount-out-atoms": quote.minAmountOutAtoms, children: [_jsxs("div", { className: "edel-sw-fee-line", children: [_jsx("span", { children: "Rate" }), _jsxs("strong", { children: ["1 ", quote.fromAsset, " = ", quote.rate, " ", quote.toAsset] })] }), _jsxs("div", { className: "edel-sw-fee-line", children: [_jsxs("span", { children: ["Edel RFQ fee (", formatBps(quote.fees.edelRfqFeeBps), ")"] }), _jsxs("strong", { children: [quote.fees.edelRfqFeeAmount, " ", quote.toAsset] })] }), _jsxs("div", { className: "edel-sw-fee-line", children: [_jsx("span", { children: "Network fee" }), _jsxs("strong", { children: [quote.fees.networkFeeAmount, " ", quote.fees.networkFeeAsset] })] }), _jsxs("div", { className: "edel-sw-fee-line", children: [_jsxs("span", { children: ["Integrator markup (", formatBps(quote.fees.integratorFeeBps), ")"] }), _jsxs("strong", { children: [quote.fees.integratorFeeAmount, " ", quote.toAsset] })] }), _jsxs("div", { className: "edel-sw-fee-line", children: [_jsx("span", { children: "Price impact" }), _jsx("strong", { children: formatBps(quote.priceImpactBps) })] }), _jsxs("div", { className: "edel-sw-fee-line", children: [_jsx("span", { children: "Min received" }), _jsxs("strong", { children: [quote.minReceived, " ", quote.toAsset] })] }), quote.minAmountOutAtoms !== undefined && (_jsxs("div", { className: "edel-sw-fee-line", children: [_jsx("span", { children: "Min output (atoms)" }), _jsx("strong", { children: quote.minAmountOutAtoms })] })), quote.estimatedSeconds !== undefined && (_jsxs("div", { className: "edel-sw-fee-line", children: [_jsx("span", { children: "Estimated settlement" }), _jsxs("strong", { children: ["~", quote.estimatedSeconds, "s"] })] })), _jsxs("div", { className: "edel-sw-fee-line", children: [_jsx("span", { children: "Quote expires in" }), _jsxs("strong", { children: [remainingSec, "s"] })] }), _jsx("div", { className: "edel-sw-ttl-bar", children: _jsx("div", { className: "edel-sw-ttl-fill", style: { width: `${ttlPercent}%` } }) })] })), order && (_jsxs("div", { className: "edel-sw-tracker", "data-testid": "swap-status-tracker", children: [_jsxs("div", { className: "edel-sw-fee-line", children: [_jsxs("span", { children: ["Order ", order.swapId ?? order.orderId] }), _jsx("strong", { children: order.status })] }), _jsx("div", { className: "edel-sw-steps", children: SWAP_STATUS_STEPS.map((step) => (_jsx("div", { className: "edel-sw-step", "data-status": step.status, "data-state": getStepState(step.status, order.status), children: step.label }, step.status))) }), canSubmitOrder && (_jsx("button", { type: "button", className: "edel-sw-submit-btn", "data-testid": "submit-swap-order-btn", disabled: submittingSigned, onClick: handleSubmitOrder, children: submittingSigned ? "Submitting swap..." : "Submit Swap Order" }))] })), errorMessage && (_jsx("div", { className: "edel-sw-error", role: "alert", children: errorMessage })), _jsx("button", { type: "button", className: "edel-sw-cta", disabled: !hasPositiveAmount || !quote || submitting || remainingSec === 0, onClick: handleSwap, children: !hasPositiveAmount
467
+ ? "Enter an amount"
468
+ : submitting
469
+ ? "Executing swap..."
470
+ : loadingQuote
471
+ ? "Fetching live quote..."
472
+ : `Swap ${fromAsset} to ${toAsset}` })] }));
473
+ }
package/package.json CHANGED
@@ -1,6 +1,60 @@
1
1
  {
2
2
  "name": "@edel-finance/swap-widget",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.0.2",
4
+ "description": "Embeddable React, Vue 3, Svelte 5, Angular, SolidJS, Shadow DOM Web Component, and iframe Swap Widget for Edel Markets.",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js"
12
+ },
13
+ "./vue": {
14
+ "types": "./dist/adapters/vue.d.ts",
15
+ "import": "./dist/adapters/vue.js"
16
+ },
17
+ "./svelte": {
18
+ "types": "./dist/adapters/svelte.d.ts",
19
+ "import": "./dist/adapters/svelte.js"
20
+ },
21
+ "./angular": {
22
+ "types": "./dist/adapters/angular.d.ts",
23
+ "import": "./dist/adapters/angular.js"
24
+ },
25
+ "./solid": {
26
+ "types": "./dist/adapters/solid.d.ts",
27
+ "import": "./dist/adapters/solid.js"
28
+ }
29
+ },
30
+ "files": [
31
+ "dist",
32
+ "README.md"
33
+ ],
34
+ "dependencies": {
35
+ "@edel-finance/sdk": "0.0.2"
36
+ },
37
+ "peerDependencies": {
38
+ "react": ">=18.2.0",
39
+ "react-dom": ">=18.2.0"
40
+ },
41
+ "devDependencies": {
42
+ "@storybook/react-vite": "^11.0.2",
43
+ "@types/react": "^19.0.0",
44
+ "@types/react-dom": "^19.0.0",
45
+ "@typescript/native-preview": "^7.0.0-dev",
46
+ "@vitejs/plugin-react": "^6.3.1",
47
+ "react": "^19.0.0",
48
+ "react-dom": "^19.0.0",
49
+ "storybook": "^11.0.2",
50
+ "vite": "^8.4.1"
51
+ },
52
+ "license": "MIT",
53
+ "scripts": {
54
+ "build": "tsgo -p tsconfig.json",
55
+ "build-storybook": "storybook build -o storybook-static",
56
+ "storybook": "storybook dev -p 6006",
57
+ "test": "bun test",
58
+ "typecheck": "tsgo --noEmit -p tsconfig.json"
59
+ }
6
60
  }