@xochi/widget-lib
v0.6.0
Published
Embed the Xochi swap widget: iframe, EIP-1193 wallet bridge, auto-resize, trade events.
Maintainers
Readme
@xochi/widget-lib
Embeds the Xochi swap widget in an iframe with an EIP-1193 wallet bridge, auto-resize and lifecycle events, and implements the frame's end of that bridge. No runtime deps; ESM + CommonJS with types.
Embedding is origin-allowlisted. Production currently allows
https://xochi.fi; other host origins must be approved before their frames will load.
Install
npm install @xochi/widget-libUsage
import { createXochiWidget } from "@xochi/widget-lib";
const widget = createXochiWidget(document.getElementById("xochi")!, {
params: { fromChainId: 1, toChainId: 8453, sellSymbol: "USDT", buySymbol: "USDC", amount: "250" },
provider: window.ethereum, // any EIP-1193 provider; omit for none
autoConnect: false, // default: connect only on the user's click
walletUi: "host",
onConnectRequest: () => openWalletModal(),
onStatusChange: (status) => {
if (status.state === "error") showWidgetError(status.message);
},
// origin: "https://widget.xochi.fi" (default)
listeners: {
"trade:submitted": ({ tradeRef }) => console.log("submitted", tradeRef),
"trade:completed": ({ tradeRef }) => console.log("settled", tradeRef),
"trade:failed": ({ tradeRef, error }) => console.warn("failed", tradeRef, error),
},
});
widget.updateTheme("contrast"); // no reload; wallet and trade state stay intact
widget.updateParams({ sellSymbol: "USDC" }); // reloads the frame
widget.updateProvider(otherProvider); // or null
widget.destroy();walletUi defaults to "widget", which preserves the standalone widget's wallet and account controls. Set it to "host" only when the surrounding page owns that UI; hosted mode requires onConnectRequest and throws synchronously without it. A host-owned iframe stays hidden until the frame acknowledges protocol v1 and the requested ownership. Every iframe load or fresh xochi:ready starts a new bounded handshake and hides hosted UI again. onStatusChange reports loading, ready, or a bounded error after WIDGET_READY_TIMEOUT_MS (10 seconds), so a host can offer retry instead of leaving a blank frame. The iframe calls onConnectRequest when a disconnected trade needs the host to connect a wallet. updateProvider attaches or replaces the provider without recreating the iframe; replacement emits a detach/attach transition and invalidates requests still pending on the prior wallet.
Frame parameters
params sets what the frame opens on; {} opens it on its own defaults. encodeEmbedParams writes them as embedUrl and createXochiWidget do, and parseEmbedParams reads them back.
| Field | Query key | Value | Unset |
| ------------------------- | ------------ | ----------------------------------------------------------------------------------------------- | ------------------------- |
| fromChainId | fromChain | chain id, a positive integer of at most 12 digits | the frame's default route |
| toChainId | toChain | chain id | the frame's default route |
| sellSymbol | sell | token symbol, 1-16 letters or digits, any case | the frame's default route |
| buySymbol | buy | token symbol | the frame's default route |
| amount | amount | plain decimal string, in sell | none |
| settlement | settlement | "public" or "stealth" | "public" |
| theme | theme | EMBED_THEMES: "auto" (follows the OS), "light", "dim", "contrast" | "auto" |
| layout | layout | EMBED_LAYOUTS: "full", or "swap" for the swap card without its tab row | "full" |
| howItWorks | howItWorks | boolean, written 1 or 0; false hides the How it works disclosure | shown |
| height | height | whole pixels within EMBED_HEIGHT (480 to 1600); the frame scrolls inside it | grows to its content |
| locks | lock | EMBED_LOCKS the user cannot change: "fromChain", "sell", "amount", "toChain", "buy" | none |
| fromChains, toChains | same | chain ids each leg may use | any the frame offers |
| sellTokens, buyTokens | same | token symbols each leg may use | any the frame offers |
| ref, promo | same | referral and promo codes, uppercase, EMBED_CODE_PATTERN | none |
- The route, amount and settlement are defaults the user can change, unless
locksnames them, and only within the allow-lists. The frame checks each against what it can serve and ignores, silently, any value it cannot. LockingamountlocksfromChainandselltoo, since the amount is in them. locksand the four allow-lists are lists of 1 toMAX_EMBED_LIST(32) entries, none repeated (symbols compare in any case). The frame ignores a list it cannot read whole.locksis written inEMBED_LOCKSorder, and lists are written with plain commas. Locks and allow-lists are conveniences, not policy: a user who edits the URL is not bound by them.- With
height,createXochiWidgetmounts the iframe at that height, and the frame lays out at it. refandpromogo with every quote and the server decides. A code the server cannot use still prices, as if absent.normalizeEmbedCodeturns a typed code into its stored form, ornull.EMBED_CODE_PATTERNis the pattern of@xochi/client'sREFERRAL_CODE_REGEXandPROMO_CODE_REGEX; this package's tests hold them equal.encodeEmbedParams,embedUrlandcreateXochiWidgetthrow aTypeErrornaming the field for a value the frame would ignore, and for an unknown key;createXochiWidgetalso throws one for a non-https origin (except localhost).parseEmbedParamsnever throws: it drops what is malformed. Keys are written route first, in table order.
Runtime themes
Use params.theme for the initial paint and widget.updateTheme(theme) for subsequent changes. Both accept EmbedTheme: "auto", "light", "dim" or "contrast". Invalid runtime values throw a TypeError. For a host with dim / dark / light themes, map them to dim / contrast / light.
updateTheme sends xochi:theme only after the frame's ownership acknowledgement. Before readiness, calls coalesce to the latest value; that value is replayed after each accepted load/ready handshake. Theme updates never change the iframe URL, reload its document, replace the wallet, restart the provider handshake, or invalidate a pending wallet request.
updateParams is still route navigation: changed encoded params reload the frame and reset the runtime override to the new params.theme, or the URL default ("auto") when omitted. Identically encoded params are a true no-op and preserve the runtime override. A theme-only host preference change should therefore call updateTheme, not updateParams.
The frame app must apply host.theme() / host.onTheme() to its existing theme state, with the runtime value taking precedence over URL params. theme() is null until a valid theme message arrives; use the parsed URL theme in the meantime. onTheme reports changed values only and returns an unsubscribe; destroy removes its observers.
Compatibility and rollout: deploy the frame app using this SDK and its runtime theme subscription before updating hosts to rely on updateTheme. This is an additive message on protocol v1, not a version bump: older hosts still work with newer frames; older frames ignore runtime themes and retain URL behavior, so readiness alone does not prove runtime theme support. Custom TypeScript implementations must add XochiWidget.updateTheme, HostConnection.theme and HostConnection.onTheme; exhaustive HostMessage switches must handle xochi:theme.
Frame side
connectToHost is the other end of the bridge, run inside the frame. The Xochi widget uses it; this package's tests run it against createXochiWidget.
import { connectToHost, mintTradeRef } from "@xochi/widget-lib";
const host = connectToHost(); // null when the window is not framed
// connectToHost({ hostOrigin: "https://host.example" }) accepts that host only
if (host) {
host.provider; // EIP-1193 provider proxied to the host's wallet; 4900 while none is attached
host.onAvailability((available) => {}); // the host attached or detached its wallet
host.onAutoConnect(() => connectHostWallet()); // only when the host passed autoConnect: true
host.walletUi(); // "widget" until the handshake, then the host's ownership choice
host.onWalletUi((walletUi) => {}); // ownership changed, even if no wallet is attached
host.requestConnect(); // asks a host-owned wallet surface to connect
host.theme(); // null until a runtime theme arrives; use the URL theme before that
const stopTheme = host.onTheme((theme) => applyEmbedTheme(theme));
host.resize(document.body.getBoundingClientRect().height);
const tradeRef = mintTradeRef(); // once per trade, on every event of it
host.emit({ name: "trade:submitted", tradeRef });
}onAutoConnectcalls back once per attachment of the host wallet, never on a repeatedxochi:provider, so a user who disconnects in the frame stays disconnected until the host re-attaches.onWalletUireports ownership changes from valid provider handshakes independently of wallet availability, including a disconnected host-owned surface.- A v1 frame applies
walletUibefore sendingxochi:provider:ack; a v1 host does not expose host-owned UI or accept its operational messages before that acknowledgement. requestConnectqueues at most one call before the handshake pins the host origin. It sends only when the handshake sayswalletUi: "host"; widget-owned mode ignores it.emitthrows aTypeErrorfor an event the host would drop, and cuts atrade:failederror toMAX_ERROR_MESSAGE_LENGTH.- Wallet errors reject as
HostRpcError(name"ProviderRpcError",code, optionaldata).
Security model
- Messages are handled only if
event.sourceis this iframe's window andevent.originis the configured origin; every post after origin pinning names that origin astargetOrigin. - Hosted connect callbacks run only after a compatible frame acknowledges host wallet ownership, and only for an exact
xochi:connect:requestmessage from this iframe's window and the configured widget origin. Malformed, oversized, cross-source and cross-origin messages are ignored. - Runtime themes are exact
{ type: "xochi:theme", theme: EmbedTheme }messages. The frame validates againstEMBED_THEMESafter its existing JSON/size, parent-window and pinned-origin checks; malformed, oversized, wrong-source, wrong-origin and pre-handshake updates are ignored. - Protocol v1 adds
protocolVersionand a host-generatedhandshakeIdtoxochi:provider; the frame must echo both with the appliedwalletUiinxochi:provider:ack. An old, stale, or incompatible host-owned frame stays hidden and reaches a bounded error instead of restoring its own wallet UI. - Only
ALLOWED_RPC_METHODSreach the wallet; others get4200without reaching it. Every connection, signature, chain switch and transaction still prompts. - Inbound JSON is capped at
MAX_MESSAGE_LENGTH(128 KiB); at mostMAX_PENDING_RPC(16) wallet requests may be pending until the wallet settles them, across frame reloads. There is no per-request deadline (a prompt waits on a person), so an unanswered prompt holds its slot. - Wallet events (
accountsChanged,chainChanged,disconnect) reach the frame only after it has connected in the current load:autoConnect: true, or its owneth_requestAccounts/eth_accountsreturned accounts. - Lifecycle events carry
tradeRef, an opaque reference the frame mints per trade (TRADE_REF_PATTERN:tr_+ 32 lowercase hex, random), the same on every event of one trade. It is not the intent id and the API knows nothing of it, so the events let the host correlate a trade but not read it from the Worker. Events whosetradeRefdoes not match the pattern are dropped. - The events carry no intent id, but a host that supplies
providersees the full signedXochiIntent,intentIdincluded, when the frame asks that wallet to sign it (eth_signTypedData_v4). Only a wallet the frame owns keeps the intent id from the host. - The frame side,
connectToHost, posts onlyxochi:readybefore the handshake (to"*", or tohostOriginwhen given). It pins the origin of the first well-formedxochi:providerfromwindow.parent(onlyhostOrigin, when given; never the opaque"null"), then handles only messages from that window and origin and posts only to it. It applies the host's limits before asking: off-allowlist methods (4200), bad params (-32602), requests overMAX_MESSAGE_LENGTH(-32600) and more thanMAX_PENDING_RPCin flight (-32005) are refused with the host's own code and message, without posting anything. Host messages overMAX_MESSAGE_LENGTHare dropped (an answer that size rejects its request with-32603), and host error messages are cut toMAX_ERROR_MESSAGE_LENGTH.
Tabs and ramp integration
WidgetTab is trade | send | activity | claims. Trade has Buy (onramp),
Swap (swap), and Cash out (offramp). Send supports Wallet address (address)
and Stealth (stealth).
import { createXochiRampWidget } from "@xochi/widget-lib";
const widget = createXochiRampWidget(container, {
direction: "onramp", // default; opens Trade / Buy
listeners: {
"ramp:status": ({ rampRef, peer, xochi }) => {
// Correlate only; rampRef cannot authorize or retrieve an operation.
},
},
});
widget.updateParams({
initialTab: "trade",
tabs: ["trade", "send", "activity", "claims"],
initialMode: "offramp",
modes: ["onramp", "swap", "offramp"],
sendDestinations: ["address", "stealth"],
fiatCurrency: "USD",
rampProviders: ["peer"],
});The offramp facade opens Trade / Cash out for payouts to the user's own
payment account. updateParams retains the iframe element and
navigates its document when the encoded parameters change, as it does for existing
parameters; it restarts frame readiness and wallet handshaking. For wallet changes
use updateProvider.
The new defaults are initialTab, initialMode, and fiatCurrency (three uppercase
currency letters, validated against live offers before execution). The narrowing
lists are tabs, modes, sendDestinations (address | stealth), and
rampProviders (Phase 1: peer). These lists only hide surfaces; they never grant
capability, eligibility or executable rail availability. Omission uses frame defaults;
an explicit empty list hides every entry. URL parsing drops unknown defaults and
unknown list entries, including legacy payment_app, and deduplicates lists. An
all-unknown or oversized restriction remains empty. Encoding rejects unknown values, duplicates and
oversized lists. Existing trade amount has no meaning for ramp amounts.
Ramp events extend XochiWidgetEvent on the existing xochi:event channel:
ramp:started:rampRef,direction(onramp | offramp).ramp:statusandramp:terminal:rampRef,peer, optionalxochi.ramp:recovery-required:rampRef,leg(peer | xochi),code.
Leg states are the normalized ramp/1 states in RAMP_LEG_STATES; recovery codes
are limited to RAMP_RECOVERY_CODES, matching ramp/1 error codes. Unknown codes
must be normalized to internal by the trusted adapter before emitting. The frame
mints rampRef with mintRampRef: ramp_ and 128 random bits in lowercase hex.
It is opaque and non-authorizing. Both bridge ends rebuild validated public fields;
invalid events are rejected by the emitter and ignored by the host. Events exclude
amounts, assets, provider IDs and handles, URLs, payment/identity/proof data,
signatures and raw provider errors. Address and stealth sends never emit ramp events.
Bridge version decision: retain protocol v1. These are additive event names and
URL fields; the handshake and wallet RPC contract are unchanged. The frozen original
v1 host decoder in legacyEvent.v1.test.ts ignores all four ramp names and still
accepts trade events. bridge.test.ts exercises the new events over the same v1
origin-pinned bridge. Older frames ignore unsupported URL keys and modes. A frame from the prior
release candidate falls back to Swap when given initialMode=offramp without
mode narrowing. Protocol v1 readiness only confirms bridge compatibility. Deploy
the compatible frame before using the new Cash out entry point.
Custom TypeScript exhaustive event switches must add the new union members.
Migrate a hosted embed
@xochi/[email protected] needs a hosted frame built from widget source that
understands these parameters. The production frame at widget.xochi.fi does not
yet: it ignores initialTab, initialMode, modes and the other new keys, so
against it createXochiRampWidget silently opens Swap and no ramp events fire.
Deploy the compatible frame first. A standalone or legacy Swap embed can continue
using layout=swap. With the full layout, the widget opens on Trade > Swap by default.
Set initialTab: "trade" and
initialMode: "offramp" to land on Cash out, or use
createXochiRampWidget(container, { direction: "offramp" }). The original
Trade/Swap events remain on the same bridge.
An iframe waits for the origin-pinned current handshake before offering new Peer execution. Legacy handshakes leave ramp entry points unavailable. Activity can recover submitted operations even after ramp entry points are hidden.
Secret boundary
Integrators own the ramp/1 secret boundary. Public identifier fields carry only
locally minted, non-authorizing references; never copy provider session/order
handles into them. Widget events, logs and telemetry must exclude Peer
cookies/OAuth codes, payment credentials/handles, identity documents or
attributes, proof material/session IDs, bearer URLs/recovery tokens, raw provider
responses/errors, wallet private keys/signatures, and Xochi read tokens. A string
matching RAMP_REF_PATTERN does not make a provider secret public. Never log
input or diagnostics from an untrusted provider.
Changes: CHANGELOG.md.
License
MIT
Tabs and ramp integration
WidgetTab is trade | send | activity | claims. Trade has Buy (onramp),
Swap (swap), and Cash out (offramp). Send supports Wallet address (address)
and Stealth (stealth).
import { createXochiRampWidget } from "@xochi/widget-lib";
const widget = createXochiRampWidget(container, {
direction: "onramp", // default; opens Trade / Buy
listeners: {
"ramp:status": ({ rampRef, peer, xochi }) => {
// Correlate only; rampRef cannot authorize or retrieve an operation.
},
},
});
widget.updateParams({
initialTab: "trade",
tabs: ["trade", "send", "activity", "claims"],
initialMode: "offramp",
modes: ["onramp", "swap", "offramp"],
sendDestinations: ["address", "stealth"],
fiatCurrency: "USD",
rampProviders: ["peer"],
});The offramp facade opens Trade / Cash out for payouts to the user's own
payment account. updateParams retains the iframe element and
navigates its document when the encoded parameters change, as it does for existing
parameters; it restarts frame readiness and wallet handshaking. For wallet changes
use updateProvider.
The new defaults are initialTab, initialMode, and fiatCurrency (three uppercase
currency letters, validated against live offers before execution). The narrowing
lists are tabs, modes, sendDestinations (address | stealth), and
rampProviders (Phase 1: peer). These lists only hide surfaces; they never grant
capability, eligibility or executable rail availability. Omission uses frame defaults;
an explicit empty list hides every entry. URL parsing drops unknown defaults and
unknown list entries, including legacy payment_app, and deduplicates lists. An
all-unknown or oversized restriction remains empty. Encoding rejects unknown values, duplicates and
oversized lists. Existing trade amount has no meaning for ramp amounts.
Ramp events extend XochiWidgetEvent on the existing xochi:event channel:
ramp:started:rampRef,direction(onramp | offramp).ramp:statusandramp:terminal:rampRef,peer, optionalxochi.ramp:recovery-required:rampRef,leg(peer | xochi),code.
Leg states are the normalized ramp/1 states in RAMP_LEG_STATES; recovery codes
are limited to RAMP_RECOVERY_CODES, matching ramp/1 error codes. Unknown codes
must be normalized to internal by the trusted adapter before emitting. The frame
mints rampRef with mintRampRef: ramp_ and 128 random bits in lowercase hex.
It is opaque and non-authorizing. Both bridge ends rebuild validated public fields;
invalid events are rejected by the emitter and ignored by the host. Events exclude
amounts, assets, provider IDs and handles, URLs, payment/identity/proof data,
signatures and raw provider errors. Address and stealth sends never emit ramp events.
Bridge version decision: retain protocol v1. These are additive event names and
URL fields; the handshake and wallet RPC contract are unchanged. The frozen original
v1 host decoder in legacyEvent.v1.test.ts ignores all four ramp names and still
accepts trade events. bridge.test.ts exercises the new events over the same v1
origin-pinned bridge. Older frames ignore unsupported URL keys and modes. A frame from the prior
release candidate falls back to Swap when given initialMode=offramp without
mode narrowing. Protocol v1 readiness only confirms bridge compatibility. Deploy
the compatible frame before using the new Cash out entry point.
Custom TypeScript exhaustive event switches must add the new union members.
Migrate a hosted embed
Use @xochi/[email protected] with a hosted shell serving
@xochi/[email protected] or later compatible widget at /embed. Deploy that shell
first. A standalone or legacy Swap embed can continue using layout=swap.
With the full layout, the widget opens on Trade > Swap by default.
Set initialTab: "trade" and
initialMode: "offramp" to land on Cash out, or use
createXochiRampWidget(container, { direction: "offramp" }). The original
Trade/Swap events remain on the same bridge.
An iframe waits for the origin-pinned current handshake before offering new Peer execution. Legacy handshakes leave ramp entry points unavailable. Activity can recover submitted operations even after ramp entry points are hidden. For additional data-handling requirements, see the ramp/1 secret boundary.
