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

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,36 @@
1
+ import type { EdelNetwork } from "@edel-finance/sdk";
2
+ import type { SwapWidgetTheme } from "./theme.js";
3
+ export interface SwapWidgetEmbedOptions {
4
+ /** Target Edel network (MainNet or TestNet). Defaults to "mainnet". */
5
+ network?: EdelNetwork;
6
+ /** Partner or integrator identifier for fee attribution. */
7
+ integratorId?: string;
8
+ /** Backwards-compatible alias for integratorId. */
9
+ partnerId?: string;
10
+ /** Default input asset symbol (for example "CC"). */
11
+ defaultFrom?: string;
12
+ /** Default output asset symbol (for example "USDCx"). */
13
+ defaultTo?: string;
14
+ /** Color theme for the embedded widget. Defaults to "dark". */
15
+ theme?: SwapWidgetTheme;
16
+ /** Optional custom widget host origin (defaults to Edel hosted swap embed). */
17
+ embedOrigin?: string;
18
+ }
19
+ export declare const SWAP_WIDGET_ORIGINS: Record<EdelNetwork, string>;
20
+ /**
21
+ * Builds the canonical iframe URL for embedding the Edel Swap Widget in
22
+ * partner dApps (SuperNova, Loop, institutional portals) or standalone pages.
23
+ */
24
+ export declare function buildSwapWidgetUrl(options?: SwapWidgetEmbedOptions): string;
25
+ /**
26
+ * Returns a ready-to-paste 3-line HTML iframe embed snippet for partner portals.
27
+ */
28
+ export declare function buildSwapWidgetEmbedSnippet(options?: SwapWidgetEmbedOptions & {
29
+ height?: number | string;
30
+ }): string;
31
+ /**
32
+ * Registers the `<edel-swap-widget>` Custom Element (Web Component) with Shadow DOM
33
+ * CSS isolation so non-React partners (SuperNova, Loop, plain HTML) can embed the
34
+ * widget without style collisions.
35
+ */
36
+ export declare function registerEdelSwapWidgetElement(tagName?: string): void;
package/dist/embed.js ADDED
@@ -0,0 +1,84 @@
1
+ export const SWAP_WIDGET_ORIGINS = {
2
+ mainnet: "https://app.edel.finance/embed/swap",
3
+ testnet: "https://testnet.edel.finance/embed/swap",
4
+ };
5
+ /**
6
+ * Builds the canonical iframe URL for embedding the Edel Swap Widget in
7
+ * partner dApps (SuperNova, Loop, institutional portals) or standalone pages.
8
+ */
9
+ export function buildSwapWidgetUrl(options = {}) {
10
+ const network = options.network ?? "mainnet";
11
+ const base = options.embedOrigin ?? SWAP_WIDGET_ORIGINS[network];
12
+ const url = new URL(base);
13
+ url.searchParams.set("network", network);
14
+ const integrator = options.integratorId ?? options.partnerId;
15
+ if (integrator)
16
+ url.searchParams.set("integratorId", integrator);
17
+ if (options.defaultFrom)
18
+ url.searchParams.set("from", options.defaultFrom);
19
+ if (options.defaultTo)
20
+ url.searchParams.set("to", options.defaultTo);
21
+ if (options.theme)
22
+ url.searchParams.set("theme", options.theme);
23
+ return url.toString();
24
+ }
25
+ /**
26
+ * Returns a ready-to-paste 3-line HTML iframe embed snippet for partner portals.
27
+ */
28
+ export function buildSwapWidgetEmbedSnippet(options = {}) {
29
+ const src = buildSwapWidgetUrl(options);
30
+ const height = options.height ?? 560;
31
+ return [
32
+ `<iframe src="${src}" title="Edel Swap Widget"`,
33
+ ` width="100%" height="${height}" allow="clipboard-write"`,
34
+ ` style="border:0;border-radius:18px;overflow:hidden;max-width:440px;"></iframe>`,
35
+ ].join("\n");
36
+ }
37
+ /**
38
+ * Registers the `<edel-swap-widget>` Custom Element (Web Component) with Shadow DOM
39
+ * CSS isolation so non-React partners (SuperNova, Loop, plain HTML) can embed the
40
+ * widget without style collisions.
41
+ */
42
+ export function registerEdelSwapWidgetElement(tagName = "edel-swap-widget") {
43
+ if (typeof window === "undefined" || typeof customElements === "undefined") {
44
+ return;
45
+ }
46
+ if (customElements.get(tagName)) {
47
+ return;
48
+ }
49
+ class EdelSwapWidgetElement extends HTMLElement {
50
+ shadow;
51
+ constructor() {
52
+ super();
53
+ this.shadow = this.attachShadow({ mode: "open" });
54
+ }
55
+ static get observedAttributes() {
56
+ return ["network", "integrator-id", "partner-id", "from", "to", "theme", "height"];
57
+ }
58
+ connectedCallback() {
59
+ this.render();
60
+ }
61
+ attributeChangedCallback() {
62
+ this.render();
63
+ }
64
+ render() {
65
+ const networkAttr = this.getAttribute("network");
66
+ const network = networkAttr === "testnet" ? "testnet" : "mainnet";
67
+ const themeAttr = this.getAttribute("theme");
68
+ const theme = themeAttr === "light" ? "light" : "dark";
69
+ const src = buildSwapWidgetUrl({
70
+ network,
71
+ integratorId: this.getAttribute("integrator-id") ?? this.getAttribute("partner-id") ?? undefined,
72
+ defaultFrom: this.getAttribute("from") ?? "CC",
73
+ defaultTo: this.getAttribute("to") ?? "USDCx",
74
+ theme,
75
+ });
76
+ const height = this.getAttribute("height") ?? "560";
77
+ this.shadow.innerHTML = `
78
+ <style>:host{display:block;max-width:440px;width:100%;}iframe{display:block;border:0;border-radius:18px;overflow:hidden;width:100%;}</style>
79
+ <iframe src="${src}" title="Edel Swap Widget" height="${height}" allow="clipboard-write" sandbox="allow-scripts allow-same-origin allow-popups allow-forms"></iframe>
80
+ `.trim();
81
+ }
82
+ }
83
+ customElements.define(tagName, EdelSwapWidgetElement);
84
+ }
@@ -0,0 +1,3 @@
1
+ export { buildSwapWidgetEmbedSnippet, buildSwapWidgetUrl, registerEdelSwapWidgetElement, SWAP_WIDGET_ORIGINS, type SwapWidgetEmbedOptions, } from "./embed.js";
2
+ export { ALPINE_FOREST_THEMES, type AlpineThemeTokens, getIsolatedWidgetCss, type SwapWidgetTheme, } from "./theme.js";
3
+ export { DEFAULT_SWAP_ASSETS, DEFAULT_WIDGET_QUOTE_TTL_SECONDS, DEFAULT_WIDGET_SLIPPAGE_BPS, EdelSwapWidget, type EdelSwapWidgetProps, formatBps, formatPresetPercent, getStepState, parseCustomSlippagePercent, resolveInitialSlippageBps, SLIPPAGE_PRESETS_BPS, SWAP_STATUS_STEPS, } from "./widget.js";
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { buildSwapWidgetEmbedSnippet, buildSwapWidgetUrl, registerEdelSwapWidgetElement, SWAP_WIDGET_ORIGINS, } from "./embed.js";
2
+ export { ALPINE_FOREST_THEMES, getIsolatedWidgetCss, } from "./theme.js";
3
+ export { DEFAULT_SWAP_ASSETS, DEFAULT_WIDGET_QUOTE_TTL_SECONDS, DEFAULT_WIDGET_SLIPPAGE_BPS, EdelSwapWidget, formatBps, formatPresetPercent, getStepState, parseCustomSlippagePercent, resolveInitialSlippageBps, SLIPPAGE_PRESETS_BPS, SWAP_STATUS_STEPS, } from "./widget.js";
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Alpine Forest II theme tokens and CSS-isolated style sheet for @edel-finance/swap-widget.
3
+ *
4
+ * All rules are scoped to `.edel-sw-root` with an explicit reset so the widget
5
+ * never inherits or leaks styles when embedded in SuperNova, Loop, or partner dApps.
6
+ */
7
+ export type SwapWidgetTheme = "dark" | "light";
8
+ export interface AlpineThemeTokens {
9
+ bg: string;
10
+ cardBg: string;
11
+ surfaceBg: string;
12
+ surfaceHover: string;
13
+ border: string;
14
+ borderStrong: string;
15
+ text: string;
16
+ textMuted: string;
17
+ accent: string;
18
+ accentHover: string;
19
+ accentText: string;
20
+ success: string;
21
+ warning: string;
22
+ danger: string;
23
+ shadow: string;
24
+ }
25
+ export declare const ALPINE_FOREST_THEMES: Record<SwapWidgetTheme, AlpineThemeTokens>;
26
+ export declare function getIsolatedWidgetCss(theme: SwapWidgetTheme): string;
package/dist/theme.js ADDED
@@ -0,0 +1,323 @@
1
+ /**
2
+ * Alpine Forest II theme tokens and CSS-isolated style sheet for @edel-finance/swap-widget.
3
+ *
4
+ * All rules are scoped to `.edel-sw-root` with an explicit reset so the widget
5
+ * never inherits or leaks styles when embedded in SuperNova, Loop, or partner dApps.
6
+ */
7
+ export const ALPINE_FOREST_THEMES = {
8
+ dark: {
9
+ bg: "#07110d",
10
+ cardBg: "#0c1b15",
11
+ surfaceBg: "#12261e",
12
+ surfaceHover: "#183328",
13
+ border: "#1d3a2e",
14
+ borderStrong: "#2a5241",
15
+ text: "#eef5f1",
16
+ textMuted: "#8aa89b",
17
+ accent: "#22c58b",
18
+ accentHover: "#34d399",
19
+ accentText: "#04120c",
20
+ success: "#34d399",
21
+ warning: "#fbbf24",
22
+ danger: "#f87171",
23
+ shadow: "0 20px 48px rgba(0, 0, 0, 0.45)",
24
+ },
25
+ light: {
26
+ bg: "#f4f8f6",
27
+ cardBg: "#ffffff",
28
+ surfaceBg: "#ebf2ee",
29
+ surfaceHover: "#dfeae4",
30
+ border: "#d3e2db",
31
+ borderStrong: "#a9c5b8",
32
+ text: "#0b1f17",
33
+ textMuted: "#4c6b5e",
34
+ accent: "#0f8a5f",
35
+ accentHover: "#0c734f",
36
+ accentText: "#ffffff",
37
+ success: "#0f8a5f",
38
+ warning: "#b45309",
39
+ danger: "#dc2626",
40
+ shadow: "0 16px 36px rgba(11, 31, 23, 0.08)",
41
+ },
42
+ };
43
+ export function getIsolatedWidgetCss(theme) {
44
+ const t = ALPINE_FOREST_THEMES[theme];
45
+ return `
46
+ .edel-sw-root {
47
+ all: initial;
48
+ display: block;
49
+ box-sizing: border-box;
50
+ font-family: -apple-system, BlinkMacSystemFont, "Inter", "Segoe UI", Roboto, sans-serif;
51
+ color: ${t.text};
52
+ background: ${t.cardBg};
53
+ border: 1px solid ${t.border};
54
+ border-radius: 18px;
55
+ padding: 20px;
56
+ width: 100%;
57
+ max-width: 440px;
58
+ box-shadow: ${t.shadow};
59
+ line-height: 1.4;
60
+ -webkit-font-smoothing: antialiased;
61
+ }
62
+ .edel-sw-root *, .edel-sw-root *::before, .edel-sw-root *::after {
63
+ box-sizing: border-box;
64
+ font-family: inherit;
65
+ }
66
+ .edel-sw-header {
67
+ display: flex;
68
+ align-items: center;
69
+ justify-content: space-between;
70
+ margin-bottom: 16px;
71
+ }
72
+ .edel-sw-title {
73
+ font-size: 16px;
74
+ font-weight: 700;
75
+ letter-spacing: -0.01em;
76
+ color: ${t.text};
77
+ }
78
+ .edel-sw-badge {
79
+ font-size: 11px;
80
+ font-weight: 600;
81
+ padding: 3px 8px;
82
+ border-radius: 999px;
83
+ background: ${t.surfaceBg};
84
+ border: 1px solid ${t.border};
85
+ color: ${t.accent};
86
+ text-transform: uppercase;
87
+ letter-spacing: 0.04em;
88
+ }
89
+ .edel-sw-box {
90
+ background: ${t.surfaceBg};
91
+ border: 1px solid ${t.border};
92
+ border-radius: 14px;
93
+ padding: 14px;
94
+ }
95
+ .edel-sw-row {
96
+ display: flex;
97
+ align-items: center;
98
+ justify-content: space-between;
99
+ gap: 10px;
100
+ }
101
+ .edel-sw-label {
102
+ font-size: 12px;
103
+ color: ${t.textMuted};
104
+ margin-bottom: 8px;
105
+ }
106
+ .edel-sw-input {
107
+ width: 100%;
108
+ background: transparent;
109
+ border: none;
110
+ outline: none;
111
+ font-size: 24px;
112
+ font-weight: 600;
113
+ color: ${t.text};
114
+ min-width: 0;
115
+ }
116
+ .edel-sw-select {
117
+ background: ${t.cardBg};
118
+ color: ${t.text};
119
+ border: 1px solid ${t.borderStrong};
120
+ border-radius: 10px;
121
+ padding: 7px 10px;
122
+ font-size: 14px;
123
+ font-weight: 600;
124
+ cursor: pointer;
125
+ }
126
+ .edel-sw-flip-wrap {
127
+ display: flex;
128
+ justify-content: center;
129
+ margin: -8px 0;
130
+ position: relative;
131
+ z-index: 2;
132
+ }
133
+ .edel-sw-flip {
134
+ width: 34px;
135
+ height: 34px;
136
+ border-radius: 10px;
137
+ border: 1px solid ${t.borderStrong};
138
+ background: ${t.cardBg};
139
+ color: ${t.accent};
140
+ font-size: 16px;
141
+ font-weight: 700;
142
+ cursor: pointer;
143
+ display: inline-flex;
144
+ align-items: center;
145
+ justify-content: center;
146
+ }
147
+ .edel-sw-fees {
148
+ margin-top: 14px;
149
+ padding: 12px 14px;
150
+ border-radius: 12px;
151
+ background: ${t.bg};
152
+ border: 1px solid ${t.border};
153
+ font-size: 12px;
154
+ display: flex;
155
+ flex-direction: column;
156
+ gap: 6px;
157
+ }
158
+ .edel-sw-fee-line {
159
+ display: flex;
160
+ justify-content: space-between;
161
+ color: ${t.textMuted};
162
+ }
163
+ .edel-sw-fee-line strong {
164
+ color: ${t.text};
165
+ font-weight: 600;
166
+ }
167
+ .edel-sw-ttl-bar {
168
+ height: 4px;
169
+ width: 100%;
170
+ border-radius: 999px;
171
+ background: ${t.surfaceBg};
172
+ overflow: hidden;
173
+ margin-top: 4px;
174
+ }
175
+ .edel-sw-ttl-fill {
176
+ height: 100%;
177
+ background: ${t.accent};
178
+ transition: width 0.25s linear;
179
+ }
180
+ .edel-sw-cta {
181
+ margin-top: 14px;
182
+ width: 100%;
183
+ padding: 13px 16px;
184
+ border-radius: 12px;
185
+ border: none;
186
+ background: ${t.accent};
187
+ color: ${t.accentText};
188
+ font-size: 15px;
189
+ font-weight: 700;
190
+ cursor: pointer;
191
+ }
192
+ .edel-sw-cta:disabled {
193
+ opacity: 0.5;
194
+ cursor: not-allowed;
195
+ }
196
+ .edel-sw-tracker {
197
+ margin-top: 14px;
198
+ padding: 12px 14px;
199
+ border-radius: 12px;
200
+ background: ${t.surfaceBg};
201
+ border: 1px solid ${t.border};
202
+ }
203
+ .edel-sw-steps {
204
+ display: flex;
205
+ justify-content: space-between;
206
+ gap: 4px;
207
+ margin-top: 8px;
208
+ }
209
+ .edel-sw-step {
210
+ flex: 1;
211
+ text-align: center;
212
+ font-size: 10px;
213
+ font-weight: 600;
214
+ padding: 5px 4px;
215
+ border-radius: 8px;
216
+ border: 1px solid ${t.border};
217
+ color: ${t.textMuted};
218
+ background: ${t.cardBg};
219
+ }
220
+ .edel-sw-step[data-state="active"] {
221
+ border-color: ${t.accent};
222
+ color: ${t.accent};
223
+ }
224
+ .edel-sw-step[data-state="done"] {
225
+ border-color: ${t.success};
226
+ background: ${t.accent};
227
+ color: ${t.accentText};
228
+ }
229
+ .edel-sw-slippage {
230
+ margin-top: 12px;
231
+ padding: 10px 12px;
232
+ border-radius: 12px;
233
+ background: ${t.surfaceBg};
234
+ border: 1px solid ${t.border};
235
+ }
236
+ .edel-sw-slippage-header {
237
+ display: flex;
238
+ align-items: center;
239
+ justify-content: space-between;
240
+ font-size: 12px;
241
+ color: ${t.textMuted};
242
+ margin-bottom: 8px;
243
+ }
244
+ .edel-sw-slippage-header strong {
245
+ color: ${t.text};
246
+ font-weight: 600;
247
+ }
248
+ .edel-sw-slippage-pills {
249
+ display: flex;
250
+ align-items: center;
251
+ gap: 6px;
252
+ border: 0;
253
+ margin: 0;
254
+ padding: 0;
255
+ }
256
+ .edel-sw-pill {
257
+ flex: 1;
258
+ padding: 6px 8px;
259
+ border-radius: 8px;
260
+ border: 1px solid ${t.border};
261
+ background: ${t.cardBg};
262
+ color: ${t.textMuted};
263
+ font-size: 12px;
264
+ font-weight: 600;
265
+ cursor: pointer;
266
+ text-align: center;
267
+ }
268
+ .edel-sw-pill[data-active="true"] {
269
+ border-color: ${t.accent};
270
+ background: ${t.accent};
271
+ color: ${t.accentText};
272
+ }
273
+ .edel-sw-custom-wrap {
274
+ display: flex;
275
+ align-items: center;
276
+ flex: 1.2;
277
+ background: ${t.cardBg};
278
+ border: 1px solid ${t.border};
279
+ border-radius: 8px;
280
+ padding: 0 8px;
281
+ }
282
+ .edel-sw-custom-wrap[data-active="true"] {
283
+ border-color: ${t.accent};
284
+ }
285
+ .edel-sw-custom-input {
286
+ width: 100%;
287
+ background: transparent;
288
+ border: none;
289
+ outline: none;
290
+ color: ${t.text};
291
+ font-size: 12px;
292
+ font-weight: 600;
293
+ padding: 6px 0;
294
+ min-width: 0;
295
+ }
296
+ .edel-sw-custom-suffix {
297
+ font-size: 11px;
298
+ color: ${t.textMuted};
299
+ margin-left: 2px;
300
+ }
301
+ .edel-sw-submit-btn {
302
+ margin-top: 10px;
303
+ width: 100%;
304
+ padding: 10px 14px;
305
+ border-radius: 10px;
306
+ border: 1px solid ${t.accent};
307
+ background: transparent;
308
+ color: ${t.accent};
309
+ font-size: 13px;
310
+ font-weight: 700;
311
+ cursor: pointer;
312
+ }
313
+ .edel-sw-submit-btn:disabled {
314
+ opacity: 0.5;
315
+ cursor: not-allowed;
316
+ }
317
+ .edel-sw-error {
318
+ margin-top: 10px;
319
+ font-size: 12px;
320
+ color: ${t.danger};
321
+ }
322
+ `.trim();
323
+ }
@@ -0,0 +1,65 @@
1
+ import { EdelClient, type EdelNetwork, 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 DEFAULT_SWAP_ASSETS: readonly ["CC", "USDCx", "ETH", "BTC"];
9
+ /** Alpine Forest II slippage presets: 1.0% (default), 2.0%, 3.0%. */
10
+ export declare const SLIPPAGE_PRESETS_BPS: readonly [100, 200, 300];
11
+ export declare const DEFAULT_WIDGET_SLIPPAGE_BPS = 100;
12
+ export declare const DEFAULT_WIDGET_QUOTE_TTL_SECONDS = 20;
13
+ /**
14
+ * Resolve initial slippage in basis points.
15
+ * Never defaults below 100 bps (1.0%) when omitted or invalid; explicit valid
16
+ * values within 1..5000 bps are respected.
17
+ */
18
+ export declare function resolveInitialSlippageBps(bps?: number): number;
19
+ /**
20
+ * Parse a user-entered custom slippage percentage string (e.g. "1.5" -> 150 bps).
21
+ * Returns null if the input is outside 0.01%..50.00% (1..5000 bps).
22
+ */
23
+ export declare function parseCustomSlippagePercent(raw: string): number | null;
24
+ export interface EdelSwapWidgetProps {
25
+ /** Integrator / partner identifier for fee attribution (SuperNova, Loop, etc.). */
26
+ integratorId?: string;
27
+ /** Backwards-compatible alias for integratorId. */
28
+ partnerId?: string;
29
+ /** Color theme: Alpine Forest II dark or light. Defaults to "dark". */
30
+ theme?: SwapWidgetTheme;
31
+ /** Target Edel network (MainNet or TestNet). Defaults to "mainnet". */
32
+ network?: EdelNetwork;
33
+ /** Default input asset symbol. Defaults to "CC". */
34
+ defaultFrom?: string;
35
+ /** Default output asset symbol. Defaults to "USDCx". */
36
+ defaultTo?: string;
37
+ /** Backwards-compatible alias for defaultFrom. */
38
+ defaultFromAsset?: string;
39
+ /** Backwards-compatible alias for defaultTo. */
40
+ defaultToAsset?: string;
41
+ /** Initial max slippage in basis points (1..5000). Defaults to 100 (1.0%). */
42
+ defaultMaxSlippageBps?: number;
43
+ /** Optional recipient Canton party / address for settlement. */
44
+ recipientAddress?: string;
45
+ /** Optional integrator fee markup in basis points. */
46
+ integratorFeeBps?: number;
47
+ /** Optional pre-configured EdelClient instance (useful for custom auth or testing). */
48
+ client?: EdelClient;
49
+ /** Optional initial quote (useful for SSR preview or testing). */
50
+ initialQuote?: SwapQuote | null;
51
+ /** Optional initial active order (useful for SSR preview or testing). */
52
+ initialOrder?: SwapOrder | null;
53
+ /** Callback fired when an active swap reaches the "settled" state. */
54
+ onSwapComplete?: (order: SwapOrder) => void;
55
+ /** Callback fired when an order is submitted via POST /v2/swaps/orders/:swapId/submit. */
56
+ onOrderSubmitted?: (order: SwapOrder) => void;
57
+ /** Callback fired on quote or execution errors. */
58
+ onError?: (error: Error) => void;
59
+ /** Additional inline styles applied to the root container. */
60
+ style?: CSSProperties;
61
+ }
62
+ export declare function getStepState(stepStatus: SwapOrderStatus, currentStatus: SwapOrderStatus): "done" | "active" | "pending";
63
+ export declare function formatBps(bps: number): string;
64
+ export declare function formatPresetPercent(bps: number): string;
65
+ export declare function EdelSwapWidget(props: EdelSwapWidgetProps): import("react").JSX.Element;
package/dist/widget.js ADDED
@@ -0,0 +1,300 @@
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 { getIsolatedWidgetCss } from "./theme.js";
5
+ export const SWAP_STATUS_STEPS = [
6
+ { status: "quoted", label: "Quoted" },
7
+ { status: "awaiting_lock", label: "Awaiting Lock" },
8
+ { status: "locked", label: "Locked" },
9
+ { status: "filled", label: "Filled" },
10
+ { status: "settled", label: "Settled" },
11
+ ];
12
+ export const DEFAULT_SWAP_ASSETS = ["CC", "USDCx", "ETH", "BTC"];
13
+ /** Alpine Forest II slippage presets: 1.0% (default), 2.0%, 3.0%. */
14
+ export const SLIPPAGE_PRESETS_BPS = [100, 200, 300];
15
+ export const DEFAULT_WIDGET_SLIPPAGE_BPS = DEFAULT_MAX_SLIPPAGE_BPS;
16
+ export const DEFAULT_WIDGET_QUOTE_TTL_SECONDS = DEFAULT_QUOTE_TTL_SECONDS;
17
+ /**
18
+ * Resolve initial slippage in basis points.
19
+ * Never defaults below 100 bps (1.0%) when omitted or invalid; explicit valid
20
+ * values within 1..5000 bps are respected.
21
+ */
22
+ export function resolveInitialSlippageBps(bps) {
23
+ if (bps === undefined || !Number.isFinite(bps)) {
24
+ return DEFAULT_WIDGET_SLIPPAGE_BPS;
25
+ }
26
+ const rounded = Math.round(bps);
27
+ if (rounded < MIN_SLIPPAGE_BPS || rounded > MAX_SLIPPAGE_BPS) {
28
+ return DEFAULT_WIDGET_SLIPPAGE_BPS;
29
+ }
30
+ return rounded;
31
+ }
32
+ /**
33
+ * Parse a user-entered custom slippage percentage string (e.g. "1.5" -> 150 bps).
34
+ * Returns null if the input is outside 0.01%..50.00% (1..5000 bps).
35
+ */
36
+ export function parseCustomSlippagePercent(raw) {
37
+ const trimmed = raw.trim();
38
+ if (!trimmed)
39
+ return null;
40
+ const pct = Number(trimmed);
41
+ if (!Number.isFinite(pct) || pct <= 0)
42
+ return null;
43
+ const bps = Math.round(pct * 100);
44
+ if (bps < MIN_SLIPPAGE_BPS || bps > MAX_SLIPPAGE_BPS)
45
+ return null;
46
+ return bps;
47
+ }
48
+ export function getStepState(stepStatus, currentStatus) {
49
+ const order = SWAP_STATUS_STEPS.map((s) => s.status);
50
+ const stepIdx = order.indexOf(stepStatus);
51
+ const curIdx = order.indexOf(currentStatus);
52
+ if (curIdx === -1)
53
+ return "pending";
54
+ if (stepIdx < curIdx || currentStatus === "settled")
55
+ return "done";
56
+ if (stepIdx === curIdx)
57
+ return "active";
58
+ return "pending";
59
+ }
60
+ export function formatBps(bps) {
61
+ return `${(bps / 100).toFixed(2)}%`;
62
+ }
63
+ export function formatPresetPercent(bps) {
64
+ return `${(bps / 100).toFixed(1)}%`;
65
+ }
66
+ export function EdelSwapWidget(props) {
67
+ const { integratorId, partnerId, theme = "dark", network = "mainnet", defaultFrom, defaultTo, defaultFromAsset, defaultToAsset, defaultMaxSlippageBps, recipientAddress = "", integratorFeeBps, client: providedClient, initialQuote = null, initialOrder = null, onSwapComplete, onOrderSubmitted, onError, style, } = props;
68
+ const effectiveIntegratorId = integratorId ?? partnerId;
69
+ const client = useMemo(() => providedClient ?? new EdelClient({ network }), [providedClient, network]);
70
+ const initialSlippage = resolveInitialSlippageBps(defaultMaxSlippageBps);
71
+ const isInitialPreset = SLIPPAGE_PRESETS_BPS.includes(initialSlippage);
72
+ const [pairs, setPairs] = useState([]);
73
+ const [fromAsset, setFromAsset] = useState(defaultFrom ?? defaultFromAsset ?? "CC");
74
+ const [toAsset, setToAsset] = useState(defaultTo ?? defaultToAsset ?? "USDCx");
75
+ const [fromAmount, setFromAmount] = useState("100");
76
+ const [recipient] = useState(recipientAddress);
77
+ const [maxSlippageBps, setMaxSlippageBps] = useState(initialSlippage);
78
+ const [customMode, setCustomMode] = useState(!isInitialPreset);
79
+ const [customSlippageInput, setCustomSlippageInput] = useState(isInitialPreset ? "" : (initialSlippage / 100).toFixed(2));
80
+ const [quote, setQuote] = useState(initialQuote);
81
+ const [order, setOrder] = useState(initialOrder);
82
+ const [loadingQuote, setLoadingQuote] = useState(false);
83
+ const [submitting, setSubmitting] = useState(false);
84
+ const [submittingSigned, setSubmittingSigned] = useState(false);
85
+ const [errorMessage, setErrorMessage] = useState(null);
86
+ const [remainingSec, setRemainingSec] = useState(initialQuote?.ttlSeconds ?? DEFAULT_WIDGET_QUOTE_TTL_SECONDS);
87
+ const completedRef = useRef(null);
88
+ const assetSymbols = useMemo(() => {
89
+ if (pairs.length === 0)
90
+ return [...DEFAULT_SWAP_ASSETS];
91
+ const set = new Set();
92
+ for (const pair of pairs) {
93
+ if (pair.active) {
94
+ set.add(pair.fromAsset.symbol);
95
+ set.add(pair.toAsset.symbol);
96
+ }
97
+ }
98
+ return set.size > 0 ? Array.from(set) : [...DEFAULT_SWAP_ASSETS];
99
+ }, [pairs]);
100
+ // Hydrate tradable swap pairs from @edel-finance/sdk
101
+ useEffect(() => {
102
+ let active = true;
103
+ client
104
+ .getSwapPairs()
105
+ .then((res) => {
106
+ if (active && Array.isArray(res)) {
107
+ setPairs(res);
108
+ }
109
+ })
110
+ .catch(() => {
111
+ // Fallback to DEFAULT_SWAP_ASSETS if endpoint is unreachable during offline preview
112
+ });
113
+ return () => {
114
+ active = false;
115
+ };
116
+ }, [client]);
117
+ // Fetch live RFQ quote when pair, amount, or maxSlippageBps changes
118
+ useEffect(() => {
119
+ const parsedAmount = Number(fromAmount);
120
+ if (!Number.isFinite(parsedAmount) || parsedAmount <= 0 || fromAsset === toAsset) {
121
+ setQuote(null);
122
+ return;
123
+ }
124
+ let cancelled = false;
125
+ setLoadingQuote(true);
126
+ setErrorMessage(null);
127
+ client
128
+ .getSwapQuote({
129
+ fromAsset,
130
+ toAsset,
131
+ fromAmount,
132
+ maxSlippageBps,
133
+ integratorId: effectiveIntegratorId,
134
+ integratorFeeBps,
135
+ recipientAddress: recipient || undefined,
136
+ })
137
+ .then((q) => {
138
+ if (cancelled)
139
+ return;
140
+ setQuote(q);
141
+ const fallbackTtl = q.ttlSeconds || DEFAULT_WIDGET_QUOTE_TTL_SECONDS;
142
+ const secs = Math.max(0, Math.ceil((q.expiresAtEpochMs - Date.now()) / 1000));
143
+ setRemainingSec(secs || fallbackTtl);
144
+ })
145
+ .catch((err) => {
146
+ if (cancelled)
147
+ return;
148
+ const e = err instanceof Error ? err : new Error(String(err));
149
+ setErrorMessage(e.message);
150
+ onError?.(e);
151
+ })
152
+ .finally(() => {
153
+ if (!cancelled)
154
+ setLoadingQuote(false);
155
+ });
156
+ return () => {
157
+ cancelled = true;
158
+ };
159
+ }, [
160
+ client,
161
+ fromAsset,
162
+ toAsset,
163
+ fromAmount,
164
+ maxSlippageBps,
165
+ effectiveIntegratorId,
166
+ integratorFeeBps,
167
+ recipient,
168
+ onError,
169
+ ]);
170
+ // Countdown quote TTL (20s default window)
171
+ useEffect(() => {
172
+ if (!quote)
173
+ return;
174
+ const tick = () => {
175
+ const secs = Math.max(0, Math.ceil((quote.expiresAtEpochMs - Date.now()) / 1000));
176
+ setRemainingSec(secs);
177
+ };
178
+ tick();
179
+ const timer = setInterval(tick, 1000);
180
+ return () => clearInterval(timer);
181
+ }, [quote]);
182
+ const activeOrderId = order?.swapId ?? order?.orderId;
183
+ const activeOrderStatus = order?.status;
184
+ // Subscribe to WebSocket live swap status transitions
185
+ useEffect(() => {
186
+ if (!activeOrderId ||
187
+ activeOrderStatus === "settled" ||
188
+ activeOrderStatus === "failed" ||
189
+ activeOrderStatus === "expired") {
190
+ return;
191
+ }
192
+ const rt = client.realtime();
193
+ const unsubscribe = rt.subscribeSwapOrder(activeOrderId, (event) => {
194
+ setOrder((prev) => {
195
+ if (!prev || (prev.swapId ?? prev.orderId) !== event.orderId)
196
+ return prev;
197
+ const next = {
198
+ ...prev,
199
+ status: event.status,
200
+ txHash: event.txHash ?? prev.txHash,
201
+ settlementTxHash: event.settlementTxHash ?? prev.settlementTxHash,
202
+ updatedAtEpochMs: event.updatedAtEpochMs,
203
+ };
204
+ if (next.status === "settled" && completedRef.current !== next.orderId) {
205
+ completedRef.current = next.orderId;
206
+ onSwapComplete?.(next);
207
+ }
208
+ return next;
209
+ });
210
+ });
211
+ rt.connect();
212
+ return () => {
213
+ unsubscribe();
214
+ rt.close();
215
+ };
216
+ }, [client, activeOrderId, activeOrderStatus, onSwapComplete]);
217
+ const handleFlip = () => {
218
+ setFromAsset(toAsset);
219
+ setToAsset(fromAsset);
220
+ };
221
+ const handleSelectPreset = (bps) => {
222
+ setCustomMode(false);
223
+ setCustomSlippageInput("");
224
+ setMaxSlippageBps(bps);
225
+ };
226
+ const handleCustomSlippageChange = (raw) => {
227
+ setCustomMode(true);
228
+ setCustomSlippageInput(raw);
229
+ const parsed = parseCustomSlippagePercent(raw);
230
+ if (parsed !== null) {
231
+ setMaxSlippageBps(parsed);
232
+ }
233
+ };
234
+ const handleSwap = async () => {
235
+ if (!quote || submitting)
236
+ return;
237
+ setSubmitting(true);
238
+ setErrorMessage(null);
239
+ try {
240
+ const created = await client.createSwapOrder({
241
+ quoteId: quote.quoteId,
242
+ recipientAddress: recipient || "self",
243
+ maxSlippageBps,
244
+ integratorId: effectiveIntegratorId,
245
+ });
246
+ setOrder(created);
247
+ if (created.status === "settled" && completedRef.current !== created.orderId) {
248
+ completedRef.current = created.orderId;
249
+ onSwapComplete?.(created);
250
+ }
251
+ }
252
+ catch (err) {
253
+ const e = err instanceof Error ? err : new Error(String(err));
254
+ setErrorMessage(e.message);
255
+ onError?.(e);
256
+ }
257
+ finally {
258
+ setSubmitting(false);
259
+ }
260
+ };
261
+ const handleSubmitOrder = async () => {
262
+ if (!order || submittingSigned)
263
+ return;
264
+ setSubmittingSigned(true);
265
+ setErrorMessage(null);
266
+ try {
267
+ const targetSwapId = order.swapId ?? order.orderId;
268
+ const submitted = await client.submitSwapOrder(targetSwapId, {
269
+ senderAddress: recipient || undefined,
270
+ });
271
+ setOrder(submitted);
272
+ onOrderSubmitted?.(submitted);
273
+ if (submitted.status === "settled" && completedRef.current !== submitted.orderId) {
274
+ completedRef.current = submitted.orderId;
275
+ onSwapComplete?.(submitted);
276
+ }
277
+ }
278
+ catch (err) {
279
+ const e = err instanceof Error ? err : new Error(String(err));
280
+ setErrorMessage(e.message);
281
+ onError?.(e);
282
+ }
283
+ finally {
284
+ setSubmittingSigned(false);
285
+ }
286
+ };
287
+ const effectiveTtlSeconds = quote?.ttlSeconds || DEFAULT_WIDGET_QUOTE_TTL_SECONDS;
288
+ const ttlPercent = quote && effectiveTtlSeconds > 0
289
+ ? Math.max(0, Math.min(100, (remainingSec / effectiveTtlSeconds) * 100))
290
+ : 0;
291
+ const canSubmitOrder = order !== null && (order.status === "quoted" || order.status === "awaiting_lock");
292
+ 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: [_jsx("span", { className: "edel-sw-title", children: "Edel Swap" }), _jsx("span", { className: "edel-sw-badge", children: network === "mainnet" ? "MainNet" : "TestNet" })] }), _jsxs("div", { className: "edel-sw-box", children: [_jsx("div", { className: "edel-sw-label", children: "You pay" }), _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.00" }), _jsx("select", { "aria-label": "From asset", className: "edel-sw-select", value: fromAsset, onChange: (e) => setFromAsset(e.target.value), children: assetSymbols.map((sym) => (_jsx("option", { value: sym, children: sym }, sym))) })] })] }), _jsx("div", { className: "edel-sw-flip-wrap", children: _jsx("button", { type: "button", className: "edel-sw-flip", "aria-label": "Flip swap pair", onClick: handleFlip, children: "\u2195" }) }), _jsxs("div", { className: "edel-sw-box", children: [_jsx("div", { className: "edel-sw-label", children: "You receive" }), _jsxs("div", { className: "edel-sw-row", children: [_jsx("input", { "aria-label": "To amount", className: "edel-sw-input", readOnly: true, value: loadingQuote ? "..." : (quote?.toAmount ?? "0.00") }), _jsx("select", { "aria-label": "To asset", className: "edel-sw-select", value: toAsset, onChange: (e) => setToAsset(e.target.value), children: assetSymbols.map((sym) => (_jsx("option", { value: sym, children: sym }, sym))) })] })] }), _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) => {
293
+ const isActive = !customMode && maxSlippageBps === bps;
294
+ 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));
295
+ }), _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: !quote || submitting || remainingSec === 0, onClick: handleSwap, children: submitting
296
+ ? "Executing swap..."
297
+ : loadingQuote
298
+ ? "Fetching live quote..."
299
+ : `Swap ${fromAsset} to ${toAsset}` })] }));
300
+ }
package/package.json CHANGED
@@ -1,6 +1,37 @@
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.1",
4
+ "description": "Embeddable React component, 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
+ },
14
+ "files": [
15
+ "dist",
16
+ "README.md"
17
+ ],
18
+ "dependencies": {
19
+ "@edel-finance/sdk": "0.0.1"
20
+ },
21
+ "peerDependencies": {
22
+ "react": ">=18.2.0"
23
+ },
24
+ "devDependencies": {
25
+ "@types/react": "^19.0.0",
26
+ "@types/react-dom": "^19.0.0",
27
+ "@typescript/native-preview": "^7.0.0-dev",
28
+ "react": "^19.0.0",
29
+ "react-dom": "^19.0.0"
30
+ },
31
+ "license": "MIT",
32
+ "scripts": {
33
+ "build": "tsgo -p tsconfig.json",
34
+ "test": "bun test",
35
+ "typecheck": "tsgo --noEmit -p tsconfig.json"
36
+ }
6
37
  }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.