Widget
Embed the 7.Exchange swap interface with @7exchange/widget. Customize it in the playground , then copy the React or JavaScript integration code into your application.
The current release is 1.1.0, using widget protocol v1.
The widget package and typed SDK are separate integrations:
| Package | Use |
|---|---|
@7exchange/widget/react | Render the complete hosted swap UI with a React component |
@7exchange/widget | Mount the same iframe from plain JavaScript or another framework |
@7exchange/sdk | Build your own UI and supply your own wallet integration |
Widget consumers do not need to install the SDK or wallet libraries. Connection and execution run inside the hosted frame. The widget does not automatically reuse the embedding application’s connected wallet.
Install
npm install @7exchange/widgetThe React entry requires React ^18.2.0 or ^19.0.0 already installed in the host. React is a peer dependency and is not bundled. The JavaScript entry works without React. Both entries provide TypeScript declarations. Package development tooling requires Node.js 22+; browser hosts need modern crypto.getRandomValues, fetch, and postMessage support.
React and Next.js
'use client'
import { SwapWidget } from '@7exchange/widget/react'
export function SwapPanel() {
return (
<SwapWidget
initialConfig={{ version: 1, referralCode: 'PARTNER_CODE' }}
title="Swap with 7.exchange"
onEvent={(event) => {
if (event.type === 'statusChanged') {
console.log(event.payload.status)
}
}}
/>
)
}The React entry preserves its client boundary for Next.js and can be imported during server rendering. Server rendering reserves the initial minimum height without creating an iframe; the hosted page displays a swap-card skeleton while it loads. Ordinary rerenders, callback changes, and live theme updates preserve the active iframe.
Initial options are captured once. Changing initialConfig, sameOrigin, title, or sizing requires an intentional new mount, such as changing the React key after the current session is complete. Do not remount an active swap just to change appearance or an event callback. Track sessionState to keep the iframe mounted while its session is active. Unmounting cannot cancel a provider action, restore a consumed lock, or recover lost execution credentials.
Use the playground guide to customize and test the package with a fully functional preview.
JavaScript and other frameworks
Add a container to your page:
<div id="swap"></div>Mount after that element exists:
import { mountWidget } from '@7exchange/widget'
const container = document.getElementById('swap')
if (!container) throw new Error('Swap container is missing')
const widget = mountWidget(container, {
initialConfig: { version: 1 },
onEvent(event) { /* typed notification */ },
})
// When your application removes the panel:
widget.destroy()The package root has no runtime dependencies. Importing it does not access browser globals; call mountWidget only in a browser, for example in your framework’s mount effect. Mount only once per container, and call the idempotent destroy() during teardown to remove the iframe, listeners, and timers. There is no execute, wallet-RPC, or live financial-configuration method on the handle.
Initial configuration
| Field | Type / meaning |
|---|---|
version | Required literal 1 inside initialConfig; omitting the whole option uses { version: 1 } |
srcChain, srcAddress | Optional source asset pair; provide both, using API discovery values |
dstChain, dstAddress | Optional destination asset pair; provide both, using API discovery values |
amount | Human-readable decimal string, such as "10.25"; up to 128 characters, without exponent notation. Zero is a valid initial UI value, but swap requests require a positive amount. |
recipient | Visible, editable recipient preset; validated for the destination chain |
referralCode | Referral attribution retained through lock and execute |
locale | en, es, ko, pt, tr, zh |
accent | Reviewed default, blue, green choices; dark UI |
theme | Optional appearance settings described below |
Configuration is public and travels in the iframe fragment. Text presets must be non-empty, at most 256 characters, and free of control characters. The encoded fragment, including channel metadata, is capped at 8192 characters. Invalid configuration throws rather than silently changing a value. Unknown fields are rejected. There are no auto-execute, private key, arbitrary API/RPC URL, redirect, token/chain restriction, or parent wallet-signing configuration fields. Asset presets remain editable; they do not enforce an allowlist. Asset availability and transaction validation remain authoritative on the backend.
Wrapper options and sizing
| Option | Default | Behavior |
|---|---|---|
initialConfig | { version: 1 } | Initial public presets; captured at mount |
theme | initialConfig.theme or defaults | Live appearance override |
sameOrigin | false | First-party hosting only: load /widget on the current page’s origin; leave unset for integrations |
title | Swap with 7.exchange | Accessible iframe title |
minHeight | 360 | Integer pixels, at least 320; also reserves initial React container space |
maxHeight | 640, or minHeight when larger | Integer pixels, at most 2000, and at least minHeight |
readyTimeoutMs | 20000 | Handshake deadline; integer 100–120000 milliseconds |
onEvent | Omitted | Callback receiving typed notifications; updates without replacing the iframe |
The frame grows and shrinks with its contents up to maxHeight, then scrolls internally. Opening the token selector expands the card to fit its chain shortcuts; closing it restores the content-based height. Use at least 320px width. React also accepts className and style for its container; set style={{ width: '100%', maxWidth: 560 }} to constrain its width. Host CSS styles the outer container; use theme tokens for the iframe contents.
The hosted URL for integrations is https://7.exchange/widget. First-party playgrounds can use sameOrigin to load /widget on their own host. Embedding requires approval of your application’s origin as described below.
Live appearance
Pass theme on SwapWidget, or call widget.setTheme(theme) on the JavaScript handle. Appearance changes preserve the iframe and financial state. initialConfig.theme sets the initial appearance; a live theme replaces the prior override.
Supported keys are background, surface, surfaceHover, primary, onPrimary, text, mutedText, border (six-digit hex strings), and borderRadius (integer 0–32 px). Missing values use the default dark palette, with the legacy accent choice if supplied. primary overrides that accent. Custom CSS, resource URLs and financial parameters are rejected by the appearance channel. Asset and settings dialogs inherit these tokens; error/warning colors remain semantic. Theme coverage targets the dark interface; light palettes and third-party wallet modals do not have complete theme coverage.
| Token | Default | Applies to |
|---|---|---|
background | #0f1a1d | Card and full-card overlay backgrounds |
surface | #152224 | Asset and content surfaces |
surfaceHover | #1d3033 | Hover surfaces and skeleton placeholders |
primary | #00d0ff | Primary action color |
onPrimary | #0f1a1d | Primary action text |
text | #ffffff | Main text |
mutedText | #8fa1a4 | Secondary text |
border | #2c6865 | Existing converter borders |
borderRadius | 32 | Card corner radius in pixels |
'use client'
import { useState } from 'react'
import { SwapWidget } from '@7exchange/widget/react'
import type { WidgetTheme } from '@7exchange/widget'
export function ThemedSwap() {
const [theme, setTheme] = useState<WidgetTheme>({ primary: '#00d0ff' })
return <>
<label>
Button color
<input type="color" value={theme.primary} onChange={event =>
setTheme({ primary: event.target.value })} />
</label>
<SwapWidget initialConfig={{ version: 1 }} theme={theme} />
</>
}For JavaScript, call widget.setTheme({ primary: '#72e5bd' }). Each update replaces the prior override rather than merging it; setTheme({}) restores defaults. Updates made before the handshake are queued. They do not change amounts, recipients, selected routes, or active execution state.
The webapp playground uses the same package validation for its controls, iframe configuration and copied React/JavaScript examples. Colors apply live. Language and financial presets require Apply presets, which starts a fresh embedded session. Finish an active swap before applying new presets. Wallet connection, quote review and execution run directly in the widget.
Events
Events have a discriminated type and typed payload:
| Type | Payload / meaning |
|---|---|
ready | protocolVersion: 1, uiVersion, executionModes; the current hosted widget advertises wallet and deposit execution |
resize | height before the host clamps it to its bounds |
sessionState | active; keep the iframe mounted while its lock/execution/tracking session is active |
quoteSelected | provider, optional routeId |
handoffRequested | Empty payload; retained for protocol compatibility. The current UI executes in-frame. |
transactionSubmitted | transactionId, sourceHash; never an approval or off-chain signature alone |
orderSubmitted | transactionId, orderId of an accepted gasless UniswapX order; the fill is reported through statusChanged |
statusChanged | transactionId, status, final; tolerate future status strings |
error | code, phase, outcomeUnknown, optional requestId |
Import WidgetConfig, WidgetTheme, WidgetOptions, WidgetHandle, WidgetEvent, WidgetLocale, and WidgetPhase from the package root. React also exports SwapWidgetProps. Narrow events by type to access their payload. Error phases are config, connection, quote, lock, execute, signature, tracking, or protocol.
Both sides validate actual origin, source window, instance ID, protocol version, sequence and payload fields. Tracking capabilities, auth tokens, signatures and raw provider objects do not cross to the parent.
Events are UI notifications, not proof of payment. Before crediting funds, verify expected assets, amount, recipient and final status using your own trusted API integration.
UniswapX gasless orders are approved and signed inside the hosted converter; a filler pays the swap gas. The npm controller does not sign or call provider APIs. Keep the same iframe mounted while sessionState.active is true. Order signatures, tracking tokens and execution payloads remain inside the hosted UI and are never sent to the parent.
Hosting and wallet support
Embedding requires approval of your application’s exact HTTPS origin. Installing from npm does not grant framing permission. Allow https://7.exchange in your page’s CSP frame-src. The wrapper runs in your own bundle; no remotely hosted loader script is required.
Request approval in #dev-general with each exact origin you need, including any non-default port. Wildcards and URL paths are not accepted, and configuration in your own application cannot grant framing permission. Framing approval and API browser access are separate approvals; request both if your own front end also calls the API directly.
The widget uses the same converter, wallet button, multi-network wallet selection, balances, and Keystore Wallet as the 7.Exchange app. Quote lock, execution, deposit instructions and tracking run in the iframe. Its solid, borderless modals and wallet panels are positioned inside the widget card and cover its entire surface. Injected wallet availability still depends on the wallet extension’s iframe support; WalletConnect uses the existing webapp connection flow.
The hosted widget uses the same execution flow as the 7.Exchange app. A missing recorded transaction or an unknown lock/execute outcome stops further actions and provides reconciliation guidance. Sensitive requests are not automatically retried.
Your lockfile pins the npm wrapper, while the remotely hosted UI can update independently. Protocol v1 compatibility is maintained for released wrappers. A future incompatible protocol requires a separately supported route.
Raw iframe and configuration helpers
The root exports validateConfig, validateTheme, encodeConfig, decodeConfig, and DEFAULT_WIDGET_THEME. encodeConfig(config) returns a public #config=… fragment; decodeConfig(fragment) validates it and defaults to { version: 1 } when no configuration is present. Never hand-concatenate unescaped configuration or put secrets in it.
A raw iframe can use that encoded fragment with the hosted URL and an explicit size, subject to the same origin approval. It does not have the package’s handshake, typed host events, live theme channel, or automatic resizing. Prefer the package wrapper for these features. Changing a fragment after bootstrap does not reconfigure a running swap.
Troubleshooting
| Symptom | Check |
|---|---|
| Package cannot be installed from the registry | Package name is @7exchange/widget; check registry access and your package manager’s configuration |
WIDGET_READY_TIMEOUT | Hosted deployment exists, exact embedding origin approved, parent frame-src allows the host, and the network request succeeded |
| Configuration throws before mounting | Required version, paired asset presets, decimal strings, supported locale, strict theme values, and encoded size limit |
| Wallet extension is absent | That wallet’s iframe injection support; try the existing WalletConnect flow where supported |
| New presets do not replace the current values | Initial options are captured at mount; remount intentionally after the active session finishes |
| Content is taller than the panel | Internal scrolling at maxHeight is expected; adjust initial sizing options if your integration needs more space |
Event has outcomeUnknown: true | Preserve the session and reconcile; do not automatically remount, re-lock, execute, sign, or send a deposit again |
Use the playground to reproduce appearance and preset issues. Include the sanitized event code and request ID when contacting support; omit capabilities, provider payloads, wallet secrets, and signatures.