@fluent.xyz/connect 0.5.2 → 0.6.0-rc.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.
package/INTEGRATION.md CHANGED
@@ -1,1429 +1,43 @@
1
- # Integrating `@fluent.xyz/connect`
2
-
3
- A step-by-step guide to adding the Fluent Connect widget to a React app.
4
-
5
- > **Breaking in 0.3.0 — Partner is now App.**
6
- >
7
- > - `FluentWidgetConfig.partnerId` is renamed to `appId`. Passing `partnerId` throws
8
- > with this hint; there is no alias.
9
- > - The id value is `app_<32 hex>`, re-issued for every App and shown in the Fluent
10
- > Dashboard. Old `partner_<32 hex>` ids are refused at startup (the widget asserts
11
- > `^app_[0-9a-f]{32}$`) and are unknown to the service.
12
- > - `FluentAuthError.code` values `unknown_partner`, `partner_not_auth_enabled` and
13
- > `partner_mismatch` are now `unknown_app`, `app_not_auth_enabled` and `app_mismatch`.
14
- > - The PostHog event property `partner_id` is now `app_id`.
15
-
16
- The widget provides everything between "user clicks Connect" and "transaction is
17
- confirmed on Fluent": login (Privy), a ZeroDev smart account, the account/wallet
18
- UI, gas payment in ERC-20, and a single execution API (`createBatchOp`) that
19
- works for both smart accounts and external EOAs.
20
-
21
- > **Scope.** This widget targets apps running **on the Fluent network**. Auth,
22
- > the smart account, and the paymaster all use Fluent's shared infrastructure —
23
- > you bring an `appId`, not your own Privy/ZeroDev project.
24
-
25
- ---
26
-
27
- ## 1. Prerequisites
28
-
29
- Before writing code you need:
30
-
31
- 1. **A Fluent `appId`** — the `app_<32 hex>` id of your App, shown in the
32
- Fluent Dashboard. Identity: sponsorship, auth and analytics speak it.
33
- Required; the widget throws without it, and throws on any other shape.
34
- 2. **A Privy app client (`privyClientId`)** — the `client-…` value Fluent
35
- issued alongside. Login configuration: your allowed origins live on it.
36
- Required; the widget throws without it. The client is issued from the Privy
37
- app of your network: the dev Privy app for `testnet`, the production Privy
38
- app for `mainnet`, which Fluent hands out together with your production
39
- `appId`. A client of one Privy app does not sign in on the other.
40
- 3. **A target network** — `testnet` (default) or `mainnet`.
41
- 4. **Your app's origin registered on that Privy app client** — Fluent's sign-in
42
- dialog runs in your page, and Privy refuses an origin it does not know.
43
-
44
- > **Upgrading from 0.4?** The login config changed in 0.5.0 — see
45
- > [Upgrading from 0.4](#upgrading-from-04).
46
-
47
- > **Migrating from `clientId`?** The option is gone. The value it held is now
48
- > `privyClientId`, and `appId` is new — passing `clientId` throws with the
49
- > same hint.
50
-
51
- Peer requirement: **React 18 or 19**.
52
-
53
- ---
54
-
55
- ## 2. Install
56
-
57
- ```bash
58
- pnpm add @fluent.xyz/connect react react-dom viem wagmi @tanstack/react-query
59
- ```
60
-
61
- `react`, `react-dom`, `viem`, `wagmi`, and `@tanstack/react-query` are
62
- **peer dependencies** — you install them in your app so there is exactly **one**
63
- copy of each in the tree (see §9 for why this matters). Privy, ZeroDev, and
64
- Reown AppKit are bundled by the widget; you don't install those.
65
-
66
- Peer version ranges: `react >=18`, `viem ^2`, `wagmi ^2`, `@tanstack/react-query ^5`.
67
-
68
- ### `Buffer` is provided for you
69
-
70
- You do not need a `Buffer` polyfill. Importing `@fluent.xyz/connect` defines
71
- `globalThis.Buffer` when the page has none: Privy's embedded wallet calls `Buffer.from(...)`
72
- while signing a UserOperation, and a browser has no `Buffer`, so without it the first
73
- signature fails. The SDK ships the polyfill as a side-effecting module of its own, which
74
- survives a production build's tree-shaking, and it never replaces an existing
75
- `globalThis.Buffer` — a polyfill your app already ships keeps working.
76
-
77
- ---
78
-
79
- ## 3. Minimal setup
80
-
81
- Import the stylesheet once at your app entry, then mount `<FluentWidget>` near
82
- the root and render your app inside its render prop:
83
-
84
- ```tsx
85
- import { FluentWidget, resolveFluentWidgetNetworkFromEnv } from "@fluent.xyz/connect";
86
- import "@fluent.xyz/connect/styles.css";
87
-
88
- export function App() {
89
- return (
90
- <FluentWidget
91
- config={{
92
- appId: "app_<32 hex, from the Fluent Dashboard>",
93
- privyClientId: "client-<issued by Fluent>",
94
- network: resolveFluentWidgetNetworkFromEnv() ?? "testnet",
95
- appName: "My App",
96
- }}
97
- mode="page"
98
- renderPage={() => <YourApp />}
99
- />
100
- );
101
- }
102
- ```
103
-
104
- `@fluent.xyz/connect/styles.css` is the package's **only** stylesheet and
105
- carries everything the widget renders, including RainbowKit's styles for the
106
- bridge wallet picker. The JavaScript entry imports no CSS of its own, so
107
- `import "@fluent.xyz/connect"` also works where no bundler handles stylesheets
108
- — server-side rendering, plain Node scripts, Jest.
109
-
110
- `<FluentWidget>` is a **provider + UI host**. Everything rendered through
111
- `renderPage` (or `renderHome`) — and any component below it — can read the widget
112
- via `useFluentWidget()` / `useWidget()`. No prop-drilling required.
113
-
114
- Set the network from an env var if you prefer:
115
-
116
- ```bash
117
- # testnet (default) — aliases: development, dev
118
- VITE_FLUENT_WIDGET_NETWORK=testnet
119
- # mainnet — aliases: production, prod
120
- VITE_FLUENT_WIDGET_NETWORK=mainnet
121
- ```
122
-
123
- ### Networks and chain ids
124
-
125
- The chain id is **different per network** and is not derivable from the network
126
- name, so anything in your app that is pinned to a chain — a wagmi/viem config, a
127
- deployment address map, a subgraph — has to match the network the widget runs on.
128
-
129
- | `network` | Chain id | Chain name | Settles on | Explorer |
130
- |-------------|----------|----------------|----------------------|----------|
131
- | `"mainnet"` | `25363` | Fluent Mainnet | Ethereum (`1`) | https://fluentscan.xyz |
132
- | `"testnet"` | `20994` | Fluent Testnet | Sepolia (`11155111`) | https://testnet.fluentscan.xyz |
133
-
134
- RPC endpoints: `https://rpc.fluent.xyz/` and `https://rpc.testnet.fluent.xyz/`.
135
-
136
- Prefer reading these from the SDK over hardcoding them — the values travel with
137
- the package, so a chain id change is a version bump rather than a hunt through
138
- your codebase:
139
-
140
- ```ts
141
- import { getFluentChainForNetwork, getFluentChainByChainId } from "@fluent.xyz/connect";
142
-
143
- const chain = getFluentChainForNetwork("mainnet"); // viem Chain — chain.id === 25363
144
- const definition = getFluentChainByChainId(20994); // reverse lookup — { id: "fluent-testnet", name, rpcUrls, … }
145
- ```
146
-
147
- `fluentMainnet` and `fluentTestnet` are also exported directly as viem chains,
148
- ready to drop into `createConfig({ chains: [...] })`.
149
-
150
- > **Mismatch symptom.** A host pinned to one network while the widget runs on
151
- > another fails with an *unsupported chain id* error at the first write, not at
152
- > mount — the read path works fine until then, so the mismatch looks like a
153
- > broken transaction rather than a broken config. If you see that error, compare
154
- > your chain list against `network` before debugging the call itself.
155
-
156
- **Treat the network as a deploy-time choice.** There is no `switchNetwork()` API,
157
- and switching at runtime is not a supported flow today: changing `config.network`
158
- does rebuild the widget's network context and remount its auth provider, but what
159
- happens to an active session across that remount is undefined. If your app needs
160
- to offer more than one network, mount the widget per network behind your own
161
- routing rather than mutating `config.network` under a live session.
162
-
163
- ---
164
-
165
- ## 4. Config reference (`FluentWidgetConfig`)
166
-
167
- | Field | Required | Default | Notes |
168
- |---------------|----------|--------------------|-------|
169
- | `appId` | ✅ | — | The App's `app_<32 hex>` id — identity for sponsorship, auth and analytics; the token `aud`. Asserted at startup. |
170
- | `privyClientId` | ✅ | — | Privy app client issued by Fluent — login configuration; allowed origins live on it. Issued from the Privy app of the App's network: the dev Privy app for `testnet`, the production Privy app for `mainnet`; a client of one does not sign in on the other. |
171
- | `clientId` | ⛔ | — | Removed in 0.2.0, and still typed (as `never`) only so the error can name the fix: pass the App's id as `appId` and the Privy app client as `privyClientId`. Passing it throws at resolve time. |
172
- | `partnerId` | ⛔ | — | Renamed to `appId` in 0.3.0, and still typed (as `never`) only so the error can name the fix. Passing it throws at resolve time. |
173
- | `network` | ➖ | env → `"testnet"` | `"testnet"` or `"mainnet"` — see [Networks and chain ids](#networks-and-chain-ids). |
174
- | `appName` | ➖ | `"Fluent Connect Demo"` | Shown in login UI. |
175
- | `customOAuthRedirectUrl` | ➖ | current page | Exact HTTPS callback for the widget's Privy OAuth flows; no credentials, query, or fragment. See [Capacitor OAuth](#capacitor-oauth). |
176
- | `enabledAuthMethods` | ➖ | `["google", "email", "passkey"]` | Methods the sign-in dialog offers beside X, in the order given. X is always offered — see [Sign-in methods](#sign-in-methods). |
177
- | `source` | ➖ | `"fluent_connect_widget"` | Attribution tag. |
178
- | `campaign` | ➖ | — | Attribution tag. |
179
- | `reconnectOnMount` | ➖ | unset | Unset restores only injected wallets (including EIP-6963) and WalletConnect silently on page load. `true` restores every connector, including Base Account and Coinbase Wallet SDK, which may prompt. Explicit `false` restores none. Explicit connection and the Fluent session are unaffected. |
180
- | `disableAnalytics` | ➖ | `false` | `true` turns off all analytics — PostHog is never initialised, nothing sent or stored. |
181
- | `gasPayment` | ➖ | `{ defaultToken: "ETH", sponsorship: "auto" }` | Initial token, native-gas sponsorship policy, and optional `ethValueByToken` hints. A Fluent ID's saved token choice takes precedence; an external wallet applies no saved choice and always pays native gas — see [What the widget stores for a signed-in user](#what-the-widget-stores-for-a-signed-in-user). |
182
- | `quickSign` | ➖ | unset | `{ whitelistAddresses }` — call targets Quick sign may execute without the review. Set, an operation is silent only when every call's `to` is on the list (compared case-insensitively); any other target shows the review and the signer prompt even with Quick sign on, including for an explicit `confirmation: "session"`. An empty list stops Quick sign from silencing anything; unset covers every address. Message / typed-data signatures have no call target and are not scoped by it. |
183
- | `execution` | ➖ | `{ feeSource: "chain", receiptSource: "chain", chainCheckBeforeSign: false }` | Where a smart-account send reads its fees and its receipt, and whether the Signer's chain is read before every signature — see [Where a send reads fees and receipts](#where-a-send-reads-fees-and-receipts). A value outside the ones documented there throws a `FluentWidgetConfigError` at startup. |
184
- | `swapper` | ➖ | Fluent defaults | On-ramp/bridge config. |
185
- | `reputationEnabled` | ➖ | `true` | `false` hides the Reputation tab — and with it the tab strip, leaving Home. The families request is never made. |
186
- | `assets` | ➖ | Fluent brand | Override logo etc. |
187
- | `avatar` | ➖ | Fluent mark | `{ defaultLogoUrl, forceDefault }` — see [Account avatar](#account-avatar). |
188
- | `scopes` | ➖ | network defaults | Permission scopes requested at login. |
189
- | `sponsorshipUrl` | ➖ | network default | Point the widget at another sponsorship service. Local development only. |
190
- | `authTokenRenewalOffsetSeconds` | ➖ | `30` | How many seconds before `exp` `getAuthToken()` stops reusing a token and fetches a fresh one. `0` drops the margin: a token is reused until `exp` itself, not fetched afresh on every call. |
191
-
192
- ✅ required, ➖ optional, ⛔ forbidden. The table is the whole of `FluentWidgetConfig`: a ⛔
193
- field is still part of the type so that a config carrying it fails the typecheck and, past the
194
- type, throws a message naming its replacement. A key removed from the type outright is not in
195
- the table at all — for those, see the upgrade sections at the end of this document.
196
-
197
- ### Capacitor OAuth
198
-
199
- Capacitor apps run at a local origin such as `capacitor://localhost` on iOS.
200
- For X and other social sign-in, set
201
- `customOAuthRedirectUrl` to an HTTPS Universal Link that returns to the app:
202
-
203
- ```tsx
204
- <FluentWidget
205
- config={{
206
- appId,
207
- privyClientId,
208
- enabledAuthMethods: [], // X remains available.
209
- customOAuthRedirectUrl: "https://app.example.com/auth/ios/callback",
210
- }}
211
- />
212
- ```
213
-
214
- The widget passes this URL to its internal `PrivyProvider`. Omitting it, or
215
- passing a blank string, keeps Privy's current-page callback. Values are trimmed
216
- and otherwise preserved to match the dashboard's exact redirect allowlist.
217
- Custom schemes such as `capacitor://localhost` are not supported as callbacks.
218
-
219
- The host still needs to:
220
-
221
- 1. Register `capacitor://localhost` and the callback's HTTPS domain in the
222
- Fluent-issued Privy client's allowed origins; enable X in the shared Privy app.
223
- Register the exact callback URL in Privy's allowed OAuth redirects.
224
- 2. Configure iOS Associated Domains and serve an `apple-app-site-association`
225
- file for the callback domain and the app's team/bundle identifier.
226
- 3. Install Capacitor's App/Browser plugins and handle `appUrlOpen` (and the
227
- launch URL when appropriate). Validate the callback origin and path, then
228
- copy its `privy_oauth_code`, `privy_oauth_state`, and `privy_oauth_provider`
229
- query parameters to the local webview URL so Privy can finish its OAuth flow.
230
- Keep the local OAuth session/state intact and close the browser after return.
231
- 4. Test sign-in, cancellation, and return on an iOS device. Dashboard allowlists
232
- and Universal Links are deployment prerequisites; setting this option alone
233
- does not complete native authentication.
234
-
235
- See [Privy's Capacitor OAuth guide](https://docs.privy.io/recipes/capacitor-oauth)
236
- and [allowed OAuth redirects](https://docs.privy.io/recipes/react/allowed-oauth-redirects).
237
- This uses X OAuth through the browser; it does not guarantee a handoff to the
238
- installed X app.
239
-
240
- ### Sign-in methods
241
-
242
- Sign-in methods default to this order: **X, Google,
243
- email, passkey**. They and the external wallet list share a single Fluent dialog.
244
- Email verification stays in place; X and Google redirect to their OAuth provider
245
- and resume the matching dialog on return. Passkey login uses the browser's
246
- credential prompt for an existing passkey. Enable these methods in the shared
247
- Privy app's dashboard; displaying a button does not enable its provider.
248
- Privy still owns any required MFA, recovery, or signing prompt, and the Fluent
249
- dialog yields while those are open.
250
- The wallet list scrolls within the dialog on smaller screens. WalletConnect hands
251
- off to its QR flow after closing the Fluent dialog.
252
-
253
- All four methods are on by default. `enabledAuthMethods` names the ones an app
254
- wants beside X — **Google, email, passkey** — and the order it wants them in.
255
- **Sign-in with X is always offered and cannot be switched off**, so it is not a
256
- value here; it stays first whatever the list says.
257
-
258
- ```tsx
259
- <FluentWidget
260
- config={{
261
- appId,
262
- privyClientId,
263
- // Leaves X and email.
264
- enabledAuthMethods: ["email"],
265
- }}
266
- />
267
- ```
268
-
269
- Omit it to keep all three; pass `[]` to leave X as the only Fluent method. The
270
- external wallet list is unaffected either way.
271
-
272
- Hosts supplying their own `wallet` prop can optionally provide `choices` (an array
273
- of `{ id, name, icon?, handoff? }`) and `connectChoice(id)` to use the inline list.
274
- Set `handoff: true` for a choice that owns its own dialog. Without these optional
275
- fields, **Connect with other wallets** retains the existing `wallet.open()` behavior.
276
-
277
- ### Account avatar
278
-
279
- The tile on the connect button and in the account drawer shows the user's X
280
- profile picture when Privy has one, and the Fluent mark otherwise. `avatar`
281
- replaces that fallback with your own logo:
282
-
283
- ```tsx
284
- <FluentWidget
285
- config={{
286
- appId,
287
- privyClientId,
288
- avatar: {
289
- // URL or data URI — rendered in a 32px rounded tile.
290
- defaultLogoUrl: "/brand/logo.svg",
291
- // Ignore the X avatar and always show `defaultLogoUrl`.
292
- forceDefault: true,
293
- },
294
- }}
295
- />
296
- ```
297
-
298
- | Field | Default | Notes |
299
- |------------------|---------|-------|
300
- | `defaultLogoUrl` | Fluent mark | Shown when there is no X avatar. A logo that fails to load falls back to the Fluent mark. |
301
- | `forceDefault` | `false` | `true` drops the X avatar entirely, so every user sees `defaultLogoUrl`. |
302
-
303
- For a custom button, `renderConnectButton` receives `userAvatarUrl`. Components
304
- inside `renderPage` or `renderHome` can read the same URL with `useFluentWidget()`:
305
-
306
- ```tsx
307
- import { AccountAvatar, useFluentWidget } from "@fluent.xyz/connect";
308
-
309
- function AccountPicture() {
310
- const { userAvatarUrl } = useFluentWidget();
311
- return <AccountAvatar userLogoUrl={userAvatarUrl} defaultLogoUrl="/brand/logo.svg" />;
312
- }
313
- ```
314
-
315
- `userAvatarUrl` is undefined when Privy has no X picture, when an External wallet
316
- is displayed, or when `avatar.forceDefault` is true. It does not include the
317
- configured default logo; pass that separately to `AccountAvatar` if needed.
318
-
319
- ---
320
-
321
- ## 5. Placing the connect button
322
-
323
- By default a floating **Connect / Account** button renders top-right
324
- (`connectButton="fixed"`). You have three options:
325
-
326
- ```tsx
327
- // (a) default floating button — do nothing.
328
-
329
- // (b) inline the default button where you want it
330
- <FluentWidget connectButton={false} renderConnectButton={({ DefaultButton }) => (
331
- <header><DefaultButton /></header>
332
- )} mode="page" renderPage={() => <YourApp />} />
333
-
334
- // (c) fully custom CTA
335
- <FluentWidget connectButton={false} mode="page" renderPage={({
336
- openConnect, openAccount, hasConnectedAccount,
337
- }) => (
338
- <button onClick={hasConnectedAccount ? openAccount : openConnect}>
339
- {hasConnectedAccount ? "Account" : "Connect"}
340
- </button>
341
- )} />
342
- ```
343
-
344
- ---
345
-
346
- ## 6. Reading account state
347
-
348
- From any component under the widget:
349
-
350
- ```tsx
351
- import { useFluentWidget } from "@fluent.xyz/connect";
352
-
353
- function Balance() {
354
- const { widget, session, openConnect, refreshBalances } = useFluentWidget();
355
-
356
- const address = widget.account.address ?? session?.wallet.smartAccountAddress;
357
- const ready = widget.account.connected && widget.account.executionReady;
358
-
359
- if (!ready) return <button onClick={openConnect}>Connect</button>;
360
- return <span>{address}</span>;
361
- }
362
- ```
363
-
364
- Key fields on `widget.account`:
365
-
366
- - `connected` — a user is signed in.
367
- - `executionReady` — the account can send transactions **now**.
368
- - `executionStatus` / `executionError` — `"disconnected" | "ready" | "unavailable" | "error"` and a message.
369
- - `type` — `"smart"` or `"eoa"`.
370
- - `capabilities` — `{ atomicBatch, erc20Gas }` (both smart-account only), so you can adapt UI without branching on `type`. `erc20Gas` means gas can be paid in an ERC-20 via the paymaster — not free/sponsored gas.
371
-
372
- Use `useWidget()` if you only need the `widget` API and nothing else from the context.
373
-
374
- ### What the widget stores for a signed-in user
375
-
376
- Three things belong to the person, not to your page, and the widget keeps them on
377
- the Fluent service so they follow the user between your app, every other app that
378
- embeds the widget, and every browser they sign in from:
379
-
380
- - **Quick sign** — the "sign without a confirmation popup" preference.
381
- - **The gas token** — which token the paymaster is asked to charge.
382
- - **Their own token list** — the tokens they added by contract address
383
- ([§6](#6-reading-account-state)'s token list, not your `tokens` prop).
384
-
385
- Your `tokens` prop and Fluent's own defaults are untouched by this: they are part
386
- of the app, not of the user.
387
-
388
- The first two describe a Fluent smart account and nothing else: Quick sign
389
- governs the Fluent ID's signer, and the gas token decides what the paymaster is
390
- charged. **For an external wallet (`widget.account.type === "eoa"`) the widget
391
- neither applies nor writes either one.** It still performs the settings read —
392
- the user's token list rides on it — and that list is still loaded, added to,
393
- removed from and one-time-imported exactly as below, but no `PATCH /me/settings`
394
- is ever sent for a preference, on any path. An external wallet confirms every
395
- call in the wallet itself and pays native gas, so a stored value for either
396
- preference would describe nothing it does; and writing one would overwrite what
397
- the same person's Fluent ID keeps, because the service resolves both of their
398
- sessions to one person and cannot tell them apart.
399
-
400
- The widget reads once per sign-in and writes every change back — for an external
401
- wallet, every change to the token list — using the same Fluent token
402
- `getAuthToken()` returns ([§8](#8-auth-and-the-fluent-token)). Nothing is sent but that token —
403
- no user id is ever put in a request by the widget.
404
-
405
- It falls back to this browser's `localStorage` where no Fluent token can exist,
406
- and behaves there exactly as it did before 0.4.0:
407
-
408
- | State | The user's token list | Quick sign and the gas token |
409
- | --- | --- | --- |
410
- | Fluent ID | the service, or `localStorage` if the read fails | the service, or the in-memory defaults if the read fails |
411
- | external wallet | the service, or `localStorage` if the read fails | not kept: neither applies to an external wallet |
412
- | nobody connected | `localStorage` | the in-memory defaults |
413
-
414
- The first time a user signs in with tokens already in this browser's
415
- `localStorage` and none on the service, the widget carries that list over once and
416
- then clears the local key. This is the token list, so it happens for an external
417
- wallet too.
418
-
419
- ### What an external-wallet user sees in Settings
420
-
421
- The wallet menu's Settings screen says the same thing the table does, so nothing
422
- on it is a control over something that cannot happen. For an external wallet:
423
-
424
- - **Quick sign** is shown off and disabled, described as "Available with a Fluent
425
- smart account". Every call is confirmed in the wallet, whatever the row holds.
426
- - **Gas payment** is shown disabled, with the same description and the network's
427
- native token (ETH) as its value — what an external wallet always pays fees in,
428
- whatever `gasPayment.defaultToken` names.
429
- - **Faucet** is hidden. It funds a Fluent smart account, and there is none here.
430
- - **Explorer** reads "View account on explorer" and opens the EOA's own address
431
- rather than a smart account's.
432
-
433
- The user's token list is on the same screen's Home panel and behaves as it does
434
- for a Fluent ID: it loads from the service, and additions and removals are
435
- written there. A Fluent ID's Settings screen is unchanged — both preferences are
436
- live, the faucet is offered on a faucet network, and Explorer opens the smart
437
- account.
438
-
439
- One more thing is kept in `localStorage`, and it is not a preference: the **refresh
440
- token** that renews the Fluent token without asking the user to sign again. It is
441
- keyed by service, `appId` and account like everything else here, it is cleared when
442
- the user disconnects, and it is never exposed through a widget API. What it is, how
443
- long it lasts and what keeping it there costs you:
444
- [§8](#where-the-session-is-kept-and-what-that-costs).
445
-
446
- Nothing here is ever thrown at your app, and a read and a write fail differently:
447
-
448
- - **A failed read** falls back to what the table above calls the read-failure
449
- case: this browser's `localStorage` token list, and for the two preferences
450
- whatever is on screen already — the in-memory defaults (Quick sign on, the
451
- network's default gas token), or the user's own choice if they have changed one
452
- since signing in. A failed read never applies the defaults over a value the
453
- person chose. Whether they are told depends on what failed:
454
- - **Nothing is shown** when the read only says "not yet" — no wallet connected
455
- yet, no Privy token yet. It is read again as soon as the missing wallet
456
- signer arrives for the same account. A service with no settings routes at all
457
- (a bare `404`) is also silent: that describes a deployment, not anything the
458
- person did or can clear.
459
- - **The message is shown** for every other failure — the user rejects the
460
- wallet signature, the network is down, the service answers 401 or 500. The
461
- wallet menu's Settings screen puts the service's message on its status line,
462
- the same line a failed write uses. There is no retry behind the user's back;
463
- it is read again the next time they sign in.
464
-
465
- Nothing is logged either way. For an external wallet only the token list is
466
- affected: it applied neither preference from a read that succeeded either, and
467
- the defaults it is left with are inert — but a read failure that has a message
468
- still shows it, because the same read carries the token list.
469
- - **A failed write** — a preference the user just changed, or a token they added
470
- or removed — is visible: the wallet menu's Settings screen shows the service's
471
- message on its status line, and `AddTokenForm` shows it under the address
472
- field. The value the user chose stays in place for the rest of the session, and
473
- a failed removal is logged through `debugLogging`
474
- ([§9b](#9b-debugging-an-integration)). An external wallet writes no preference
475
- at all, so only its token writes can fail this way.
476
-
477
- Failed writes are not queued or replayed. The next sign-in reads whatever the
478
- service holds, which for a write that never landed is the old value.
479
-
480
- > **Breaking in 0.4.0.** `UserTokenStore` is now asynchronous — `list`, `add` and
481
- > `remove` return promises, and `add` has a new `{ status: "failed", message }`
482
- > result. If you inject your own `userTokenStore`, wrap each method's return value in
483
- > `Promise.resolve()` to port a 0.3.x implementation.
484
- >
485
- > `useFluentUserTokens()` changed shape with it, and that one needs no injected store to
486
- > reach you: `add` and `remove` return promises — `add` resolving that same result — and
487
- > `tokens` starts as an empty array on every mount, filling when the first load settles,
488
- > so an empty `tokens` on the first render means "not loaded yet", not "no tokens".
489
- > Called without `{ store }`, the hook reads and writes **this browser's `localStorage`
490
- > only**, never the service's list the widget syncs for a signed-in user, and after the
491
- > widget's one-time import moves the local list to the service, that local list is empty.
492
- > The widget does not expose its service-backed store, so a host that needs the user's
493
- > synced list must pass its own `store`. A failed load leaves the
494
- > last list that settled on screen and tells your component nothing; the failure goes to
495
- > `debugLogging`'s output ([§9b](#9b-debugging-an-integration)).
496
-
497
- ---
498
-
499
- ## 7. Sending a transaction
500
-
501
- All execution goes through **one** API: `widget.createBatchOp({...}).execute()`.
502
- The widget internally routes a smart account (one sponsored UserOp, signed under
503
- the user's Quick sign setting) vs an external EOA (sequential native-gas txs,
504
- each confirmed in the wallet, where Quick sign does not apply), waits for
505
- inclusion, and refreshes balances — **no host-side branching by account type.**
506
-
507
- The result includes `receipt` for `hash`, plus `userOpHash` for a smart-account
508
- operation. Hosts can validate the receipt's logs and read application state at
509
- `receipt.blockNumber` immediately, without waiting for another confirmation.
510
- For a sequential EOA batch, `receipt` belongs to the final call; execution stops
511
- if any call reverts. These fields are optional for compatibility with custom
512
- executors and older SDKs. An included receipt is not a finality guarantee.
513
-
514
- Each call is either raw calldata (`data`) or `abi + method + args`. The `to`
515
- address can be **any** contract — there is no token allow-list on operations.
516
-
517
- ### Example: approve + deposit (one atomic batch on a smart account)
518
-
519
- ```tsx
520
- import { useWidget } from "@fluent.xyz/connect";
521
- import { erc20Abi } from "./abi";
522
-
523
- function DepositButton({ asset, vault, amount, account }) {
524
- const widget = useWidget();
525
-
526
- async function onDeposit() {
527
- if (!widget.account.executionReady) return; // guard first
528
-
529
- const op = widget.createBatchOp({
530
- id: "approve-deposit",
531
- reviewTitle: "Approve + deposit",
532
- calls: [
533
- { to: asset, abi: erc20Abi, method: "approve", args: [vault, amount] },
534
- { to: vault, abi: vaultAbi, method: "deposit", args: [amount, account] },
535
- ],
536
- });
537
-
538
- const { hash, atomic } = await op.execute();
539
- // atomic === true → both landed in a single UserOp (smart account)
540
- }
541
-
542
- return <button onClick={onDeposit}>Deposit</button>;
543
- }
544
- ```
545
-
546
- ### Gas payment
547
-
548
- The widget starts with native **ETH** selected. On a Fluent ID a valid saved user
549
- preference takes precedence, and the user can choose another supported gas token
550
- in the menu. An external wallet pays native gas on every call: its menu shows the
551
- choice disabled over ETH, no saved preference is applied to it, and nothing is
552
- saved from it ([§6](#what-an-external-wallet-user-sees-in-settings)).
553
- Set the initial/fallback token and native-gas sponsorship policy in config:
554
-
555
- ```tsx
556
- <FluentWidget
557
- config={{
558
- appId,
559
- privyClientId,
560
- gasPayment: { defaultToken: "ETH", sponsorship: "never" },
561
- }}
562
- />
563
- ```
564
-
565
- `sponsorship: "never"` pays native gas from the smart account's ETH balance and
566
- skips sponsorship authentication and paymaster requests. The default `"auto"`
567
- retains app-sponsored execution with native-gas fallback. This policy does not
568
- disable an ERC-20 token's paymaster when the user selects BLEND or USDnr.
569
- The configured token must be a supported gas token on the selected network.
570
-
571
- Gas defaults to the token selected in the widget's own gas selector. To force a
572
- token explicitly, pass just its **symbol** — the widget resolves the ERC-20
573
- address for the active network internally, so you never pass (or mistype) an
574
- address:
575
-
576
- ```ts
577
- await op.execute({
578
- gasPayment: { symbol: "BLEND" },
579
- });
580
- ```
581
-
582
- To also fund the paymaster's ERC-20 allowance in the same batch, add
583
- `includeApproval: true` and `approveAmount`:
584
-
585
- ```ts
586
- await op.execute({
587
- gasPayment: { symbol: "BLEND", includeApproval: true, approveAmount: 100n * 10n ** 18n },
588
- });
589
- ```
590
-
591
- Gas can be paid in `USDnr`, `BLEND`, or native `ETH` (symbol `"ETH"` = native
592
- gas, no ERC-20 paymaster; app sponsorship still follows the policy above).
593
- This list is the *gas* token allow-list — it does **not**
594
- restrict which tokens your calls operate on.
595
-
596
- Per-operation `gasPayment.sponsorship` overrides the configured policy, so
597
- `op.execute({ gasPayment: { symbol: "ETH", sponsorship: "auto" } })` can request
598
- sponsorship even when the widget defaults to `"never"`.
599
-
600
- ### Skipping UserOperation gas estimation
601
-
602
- For a Fluent ID batch with known gas budgets, pass `userOperationGas.skipEstimation: true`:
603
-
604
- ```ts
605
- await widget.createBatchOp({ calls }).execute({
606
- userOperationGas: {
607
- skipEstimation: true,
608
- callGasLimit: 600_000n,
609
- verificationGasLimit: 500_000n,
610
- preVerificationGas: 100_000n,
611
- },
612
- });
613
- ```
614
-
615
- The flag defaults to `false`. Without it, a fixed `callGasLimit` still leaves other
616
- gas fields eligible for estimation. With it, the SDK skips the account's gas hook
617
- and `eth_estimateUserOperationGas` for sponsored, native-gas and ERC-20-gas
618
- UserOperations, including native-gas fallback after sponsorship fails. External
619
- wallet transactions keep their wallet's estimation.
620
-
621
- Supply all three account limits. With a paymaster, omit both paymaster limits to
622
- use the provider's validation and post-operation limits. Its returned
623
- `preVerificationGas` is accepted up to your configured value; a larger value
624
- fails before signing. Execution and account-validation limits stay fixed. The
625
- provider must return complete paymaster limits in its first response; later
626
- authorization may keep or replace them. The SDK preserves the authorized values
627
- through signing without invoking the account gas hook or bundler gas estimator.
628
-
629
- Alternatively, supply both `paymasterVerificationGasLimit` and
630
- `paymasterPostOpGasLimit` to fix every gas field, as in 0.5.0. When a paymaster is
631
- used, supplying only one fails before authorization. Limits are bigints:
632
- `preVerificationGas` must fit a positive
633
- uint256, `paymasterPostOpGasLimit` a nonnegative uint128, and the others a positive
634
- uint128. `callGasBuffer` cannot be combined with `skipEstimation: true`.
635
- Gas-policy validation reports `FluentUserOperationGasError` with code
636
- `invalid_policy` and names the option to correct.
637
-
638
- The example values are illustrative. Choose limits that cover the complete batch,
639
- including a prepended Gas token approval and account validation or deployment.
640
- Fixed paymaster limits must cover paymaster execution. The SDK does not verify
641
- that these budgets are sufficient; an underestimated operation can be rejected
642
- or fail during execution.
643
-
644
- The SDK supplies account gas before paymaster authorization. A data-only adapter's
645
- authorization or a stub marked final is reused; a nonfinal stub still requires
646
- final authorization. A changed execution or account-validation limit fails that
647
- attempt before signing with `FluentUserOperationGasError` code
648
- `paymaster_gas_mismatch`. With both paymaster limits fixed, any changed gas field
649
- fails the same way. Malformed provider gas and calldata overhead above the
650
- configured ceiling also fail before signing. Normal sponsorship fallback still
651
- applies, with the configured account limits and no gas estimation.
652
-
653
- This flag does not disable fee quotes, nonce or factory reads, paymaster
654
- authorization, signing, bundler submission checks or receipt waiting. A paymaster
655
- service may still perform its own estimation internally; the SDK cannot control
656
- that service's implementation.
657
-
658
- ### Execution timing
659
-
660
- Set `<FluentWidget debugLogging />` to emit `[fluent execution stage]` progress
661
- before waits and timing entries for setup, preparation, signing, broadcast and
662
- inclusion. Timing entries contain durations and public hashes, not signatures,
663
- calldata or authentication tokens. Each sponsored/fallback submission attempt
664
- has its own timing entry. Logging is off by default and does not repeat gas
665
- estimation, signing or submission.
666
-
667
- `[fluent submission timing]` carries the `feeSource` that quoted that attempt and
668
- `[fluent inclusion timing]` the `receiptSource` that produced the receipt — the one that
669
- answered, so a send that asked the chain and was answered by ZeroDev reads `"bundler"`. See
670
- [Where a send reads fees and receipts](#where-a-send-reads-fees-and-receipts).
671
-
672
- ETH avoids the ERC-20 paymaster request but still needs UserOperation gas
673
- estimation. Shorter receipt polling and receipt reuse do not remove bundler or
674
- paymaster preparation latency; compare these stages before attributing a delay
675
- to Fluent execution. Receipt inclusion is not additional block confirmation or
676
- L1 finality.
677
-
678
- Migration: the initial/fallback gas token changes from BLEND to ETH, without
679
- overwriting saved preferences. External-wallet auto-reconnect now restores only injected wallets (including
680
- EIP-6963) and WalletConnect when `reconnectOnMount` is unset. Base Account,
681
- Coinbase Wallet SDK and unknown connectors do not reconnect or prompt by default;
682
- explicit connection remains available. Set `reconnectOnMount: true` to restore
683
- every connector, or explicitly set `false` to restore none. Wallet users returning
684
- from Link X can therefore resume with the same EOA under the default policy.
685
-
686
- ### Where a send reads fees and receipts
687
-
688
- A smart-account send needs two answers that both the widget chain's RPC and the ZeroDev bundler
689
- can give: what the operation's fees should be, and whether it has been included.
690
- `FluentWidgetConfig.execution` decides which one is asked, and the defaults are the chain,
691
- because the chain answers both in about 70 ms against about 590 ms for a ZeroDev gas-price
692
- quote and about 345 ms for a ZeroDev receipt poll. Those per-request numbers are a probe's, not
693
- a measurement of this widget: what a whole send gains on Fluent testnet is being measured on
694
- `apps/sponsorship-demo` (FLU-1591), and the report is not in yet.
695
-
696
- > **Experimental.** `execution` and its three fields may change or be removed in a minor
697
- > release while the defaults are measured. The defaults are the recommended setting: leave
698
- > them unset unless you need today's ZeroDev behaviour back.
699
-
700
- ```tsx
701
- <FluentWidget
702
- config={{
703
- appId: "app_…",
704
- privyClientId: "client-…",
705
- execution: {
706
- feeSource: "chain", // or "bundler"
707
- receiptSource: "chain", // or "bundler"
708
- chainCheckBeforeSign: false, // or true
709
- },
710
- }}
711
- />
712
- ```
713
-
714
- | Field | Default | `"chain"` / `false` | `"bundler"` / `true` |
715
- |---|---|---|---|
716
- | `feeSource` | `"chain"` | `maxPriorityFeePerGas` is the chain's `eth_gasPrice`, and `maxFeePerGas` is that answer plus 10 %, rounded down | ZeroDev's `zd_getUserOperationGasPrice` quote, unchanged |
717
- | `receiptSource` | `"chain"` | inclusion is the EntryPoint's `UserOperationEvent`, polled with `eth_getLogs` every 200 ms on the chain's RPC | `eth_getUserOperationReceipt`, polled every 200 ms on the bundler |
718
- | `chainCheckBeforeSign` | `false` | the Signer signs without being asked its chain id first | the Signer's chain is read, and switched if it has to be, before every signature |
719
-
720
- The same defaults apply on testnet and on mainnet, because each `chain` source falls back to
721
- ZeroDev on its own and inside the send that needed it:
722
-
723
- - a chain `eth_gasPrice` that fails after the RPC transport's own retries is answered by
724
- ZeroDev's quote for that send, and the next send asks the chain again;
725
- - a chain `eth_blockNumber`, `eth_getLogs` or `eth_getTransactionReceipt` that fails the same way
726
- hands the wait back to `eth_getUserOperationReceipt` on the bundler, for what is left of the
727
- 120 s a send waits for its receipt. A send that reaches those 120 s with no receipt rejects
728
- with viem's `WaitForUserOperationReceiptTimeoutError`, as it did before.
729
-
730
- A bundler may refuse an operation whose `maxFeePerGas` or `maxPriorityFeePerGas` is below what
731
- it will accept. That one rejection is retried once, inside the same send, whichever source
732
- quoted the attempt it refused: the operation is prepared again with a fresh
733
- `zd_getUserOperationGasPrice` quote, signed again without a second review, and submitted a
734
- second time. A second refusal is the bundler's answer to the bundler's own quote and reaches your
735
- `catch` unchanged, after exactly two submissions. Nothing is remembered: the next send asks the
736
- chain first again.
737
-
738
- `chainCheckBeforeSign` is about the repeat, not about the check: the widget gives Privy its own
739
- chain as the only chain it supports, and the chain is checked once when the smart account is
740
- created, whatever this field says.
741
-
742
- `execution` changes apply to the next send and the next signature — the widget does not have to
743
- be remounted for them. A send already in flight keeps the three settings it started with, its
744
- fee retry and its second signature included, and it keeps them to itself: a `widget.signMessage`
745
- or a second send you start while it waits reads the settings as they are then, not as that send
746
- read them.
747
-
748
- ### Always guard on `executionReady`
749
-
750
- `createBatchOp` throws only on malformed input (an empty `calls` array, or a call
751
- with neither `data` nor `abi` + `method`), but `execute()` rejects if the session
752
- can't execute. Gate the button on `widget.account.executionReady` and surface
753
- `widget.account.executionError` to the user.
754
-
755
- ---
756
-
757
- ## 7b. Requesting a signature
758
-
759
- `widget.signMessage` and `widget.signTypedData` ask the connected account for an
760
- off-chain signature — marketplace orders, listings, signed approvals. Like
761
- `createBatchOp`, they route by account type so the host never branches:
762
-
763
- - **Smart account** (Fluent ID login): the signature comes from the ZeroDev Kernel
764
- account and is an **ERC-1271** signature. While the account is not deployed yet
765
- it is **ERC-6492**-wrapped; the wrapper is dropped automatically once it is.
766
- - **External wallet**: the wallet itself signs; the result is a plain ECDSA
767
- signature.
768
-
769
- ```tsx
770
- import { useWidget } from "@fluent.xyz/connect";
771
-
772
- function ListButton({ order }) {
773
- const widget = useWidget();
774
-
775
- async function onList() {
776
- const signature = await widget.signTypedData({
777
- domain: { name: "Marketplace", version: "1", chainId: 20994, verifyingContract: exchange },
778
- types: { Order: [{ name: "maker", type: "address" }, { name: "price", type: "uint256" }] },
779
- primaryType: "Order",
780
- message: order,
781
- });
782
- await submitOrder({ order, signature });
783
- }
784
-
785
- return <button onClick={onList}>List</button>;
786
- }
787
-
788
- // EIP-191 personal message
789
- const signature = await widget.signMessage({ message: "Sign in to Marketplace" });
790
- ```
791
-
792
- The user reviews every request in the widget before anything is signed: the
793
- origin of the page asking, the signing account, and — for typed data — the
794
- domain, primary type and message. **Quick sign never applies to signatures**;
795
- turning it on skips the review for transactions only. A dismissed review
796
- rejects the promise with `User rejected Fluent signature review`.
797
-
798
- ### Verify with ERC-1271 / ERC-6492, never `ecrecover`
799
-
800
- A smart-account signature does not recover to the account address, or to any
801
- address you can compare against. Verify it by asking the account:
802
-
803
- - **Off-chain**: viem `publicClient.verifyTypedData` / `verifyMessage` (they handle
804
- EOA, ERC-1271 and ERC-6492 in one call). Pass `address: widget.account.address`.
805
- - **On-chain**: OpenZeppelin `SignatureChecker.isValidSignatureNow(account, hash, signature)`.
806
- For a not-yet-deployed account use an ERC-6492-aware validator, or deploy the
807
- account first (any transaction through `createBatchOp` deploys it).
808
-
809
- A backend that does `ecrecover` and compares addresses will reject every
810
- smart-account user. Check `widget.account.type` if you need to know which kind of
811
- signature to expect.
812
-
813
- ### EIP-2612 `permit` does not work for smart accounts
814
-
815
- `permit(owner, spender, value, deadline, v, r, s)` recovers an EOA signature on
816
- chain; a Kernel account cannot produce one. Do not build a permit flow for
817
- smart-account users — batch the `approve` and the call instead, which lands in
818
- **one** atomic UserOp and needs no signature step:
819
-
820
- ```ts
821
- await widget.createBatchOp({
822
- reviewTitle: "Approve + buy",
823
- calls: [
824
- { to: token, abi: erc20Abi, method: "approve", args: [exchange, price] },
825
- { to: exchange, abi: exchangeAbi, method: "buy", args: [orderId] },
826
- ],
827
- }).execute();
828
- ```
829
-
830
- For an external wallet `permit` works as usual, so a host that supports both can
831
- branch on `widget.account.capabilities.atomicBatch`.
832
-
833
- ### What answers the signature
834
-
835
- For a Fluent ID the **in-page Signer** answers: the Privy embedded wallet that
836
- signed the user in, reached through the ZeroDev kernel in your page. For an
837
- external wallet the wallet answers. Either way the signature is produced where
838
- the user is, with no second window and no service round trip.
839
-
840
- ## 7c. Embedding a marketplace iframe
841
-
842
- A page embedded in your app on another origin cannot see the account signed in
843
- here: the browser partitions its storage by top-level site, so a widget inside the
844
- iframe would ask the user to sign in again. `useFluentIframeBridge` answers the
845
- embedded page's wallet calls with this page's account instead, over the JSON-RPC
846
- 2.0 `postMessage` protocol `@ledgerhq/iframe-provider` speaks, which white-label
847
- marketplace frontends use to borrow the host page's wallet, so such a page works
848
- without a second sign-in.
849
-
850
- ```tsx
851
- import { useRef } from "react";
852
- import { useFluentIframeBridge } from "@fluent.xyz/connect";
853
-
854
- function Marketplace() {
855
- const iframeRef = useRef<HTMLIFrameElement>(null);
856
- useFluentIframeBridge(iframeRef, { allowedOrigin: "https://market.example" });
857
- return <iframe ref={iframeRef} src="https://market.example/collection/cards" />;
858
- }
859
- ```
860
-
861
- `allowedOrigin` is the origin the marketplace is served from, scheme and host,
862
- normalised the way `event.origin` is; `"*"` and a bare host are refused at
863
- construction. Messages from any other
864
- origin, or from any other window, are dropped without a reply; this is the only
865
- origin check in the exchange, because the iframe side posts to `"*"` and checks
866
- nothing itself.
867
-
868
- What the bridge answers:
869
-
870
- | Method | Answer |
871
- | --- | --- |
872
- | `eth_accounts`, `eth_requestAccounts`, `enable` | the signed-in address, or `[]` |
873
- | `eth_chainId` | the widget's chain |
874
- | `eth_signTypedData_v4` / `_v3` / `eth_signTypedData`, `personal_sign` | `signTypedData` / `signMessage`, with the usual review |
875
- | `eth_sendTransaction` | `createBatchOp([...]).execute()`; the hash returned is the one `execute()` returns, which the embedded page can poll with `eth_getTransactionReceipt` |
876
- | `eth_call`, `eth_estimateGas`, `eth_getTransactionReceipt`, and the other read-only `eth_*` methods | forwarded to the chain RPC |
877
- | anything else (`wallet_*`, `eth_sign`, `eth_sendRawTransaction`) | error `4200 Unsupported method` |
878
-
879
- A request that names another address as `from` or signer is refused with `4100`.
880
- A dismissed review reaches the iframe as `4001` (`FluentReviewRejectedError` on
881
- this side); any other failure as `-32603` with the widget's message. The bridge states
882
- `chainChanged` and `accountsChanged` ahead of its first reply, so a page that
883
- loaded after the bridge still learns them; sign-in and sign-out reach the iframe
884
- as `accountsChanged` after that. `eth_sendTransaction` resolves once the
885
- transaction is included, so the hash it returns already has a receipt.
886
-
887
- As in §7b, a smart-account signature is ERC-1271, so the marketplace's order validation has to
888
- accept that; a validator without an ERC-6492 path also needs the account deployed,
889
- which means a not-yet-deployed account must send one transaction before its first
890
- listing validates.
891
-
892
- Outside React, `createFluentIframeBridge(iframe, { allowedOrigin, executor })` is
893
- the same bridge with the widget calls injected; `createFluentIframeRpcHandler(executor)`
894
- is the method mapping alone, for a transport of your own.
895
-
896
- ---
897
-
898
- ## 8. Auth and the Fluent token
899
-
900
- **Direct login** is the one way in. Clicking Connect opens **Fluent's own sign-in dialog**
901
- inside your page, carrying the sign-in methods and the external wallet list on one screen
902
- ([§4](#sign-in-methods)); Privy runs headless behind it and renders no modal of its own.
903
- Your origin **must** be registered on the Privy app client behind your `privyClientId`
904
- first, otherwise Privy rejects it with `invalid_origin` and the login button does nothing.
905
- Because the user's Privy session then lives in your page, so does everything that needs it:
906
- `signMessage` and `signTypedData` ([§7b](#7b-requesting-a-signature)), the iframe bridge
907
- ([§7c](#7c-embedding-a-marketplace-iframe)), `linkX()` ([§8c](#8c-linking-x)) and
908
- `getAuthToken()`.
909
-
910
- What each account type gets:
911
-
912
- | Account | Fluent token (`getAuthToken()`) minted by | Prompt | Signing | Sponsorship |
913
- | --- | --- | --- | --- | --- |
914
- | Fluent ID, on Direct login | widget, with the in-page Privy tokens | none | in page, with review | yes, with the Fluent token |
915
- | External wallet, on Direct login | widget, challenge + wallet signature | one per session | the wallet | none: an EOA pays its own gas |
916
-
917
- A Fluent ID exchanges the Privy tokens your page holds; an external wallet signs the
918
- challenge in the page. With nobody connected, `getAuthToken()` rejects with
919
- `not_connected`. How your backend checks the token:
920
- [§8b](#8b-verify-the-token-on-your-backend).
921
-
922
- ### The token renews itself, silently
923
-
924
- A Fluent token lives five minutes. The session behind it lives thirty days, and the
925
- widget renews the token from that session without involving the user at all — no
926
- Privy round trip for a Fluent ID, **and no wallet prompt for an external wallet**.
927
- The "one per session" in the Prompt column above is the whole change: the wallet
928
- signs when the session opens, and the renewals that follow ask it for nothing.
929
-
930
- What makes this work is a second, long-lived credential the service issues
931
- alongside every Fluent token — a **refresh token**, an opaque string with no
932
- structure that only the service can interpret. The widget keeps it, spends it for a
933
- new pair when the Fluent token is close to `exp`, and gets a fresh refresh token
934
- back each time. Each one is single-use: presenting the same one twice ends the
935
- session, which is how a stolen copy is caught. All of the above rests on the service
936
- issuing that credential: a deployment old enough to answer the exchange without a refresh
937
- half leaves the widget nothing to renew from, and the last case below is what happens
938
- instead.
939
-
940
- Your app never sees it, and never should. `getAuthToken()` returns the short-lived
941
- Fluent token and nothing else; no widget API exposes the refresh token.
942
-
943
- A **new signature** — a new full exchange — is needed only when:
944
-
945
- - the session's thirty days are up (the service's `REFRESH_TOKEN_TTL` default; a
946
- renewal hands out a new credential but never moves that deadline);
947
- - the service rejects the stored credential, because the session was revoked
948
- elsewhere or the same credential was presented twice;
949
- - there is no stored credential in this browser: the user disconnected, cleared
950
- site data, or opened your app in another browser or another profile;
951
- - the service answered the exchange without a refresh credential at all — a service
952
- deployment that predates refresh credentials. Nothing is stored, so nothing renews:
953
- every expired token is another full exchange, which for an external wallet is another
954
- signature every five minutes. The service this release targets issues one.
955
-
956
- Two limits worth knowing. The first: renewal is coordinated **within one page**, not
957
- across tabs. The stored credential is *shared* — the key carries the service, your
958
- `appId` and the account, and nothing that distinguishes one tab from another — so two
959
- tabs of your app hold one session between them, and only the page that renews knows the
960
- credential rotated. If the other tab renews with the copy it read, the service sees the
961
- same refresh token twice, ends that session as a suspected replay, and both tabs fall
962
- back to a full exchange: one new signature for an external wallet, then business as
963
- usual. Nothing is lost and nobody is signed out, but a multi-tab app should expect the
964
- occasional extra prompt. Coordinating tabs is not in this release.
965
-
966
- ### Where the session is kept, and what that costs
967
-
968
- The refresh token is kept in this browser's `localStorage`, under a key carrying the
969
- service URL, your `appId` and the connected account. One App never reads another's,
970
- and two accounts sharing a browser never read each other's.
971
-
972
- > **This is an XSS exposure, and we are not going to tell you otherwise.**
973
- > `localStorage` is readable by any script running on your page. A script that gets
974
- > onto your origin — through a compromised dependency, an injected tag, a `dangerouslySetInnerHTML`
975
- > you did not audit — can read the refresh token and use it, from that same origin, for
976
- > up to thirty days.
977
- >
978
- > Single-use rotation and the service's origin checks do **not** remove that. Rotation
979
- > means a stolen credential is *detected* once the real client renews next and the
980
- > session is then killed — it does not prevent the theft or the window before it.
981
- > The origin check means the stolen credential is not usable from *another* site in a
982
- > browser — it does nothing about the site it was taken from, which is yours. Both
983
- > narrow the blast radius; neither closes it.
984
- >
985
- > The tradeoff bought here is a user who signs once instead of every five minutes. What
986
- > narrows the exposure is a Content-Security-Policy and a dependency review you treat as
987
- > load-bearing — they were already — plus disconnecting a session you are done with, which
988
- > revokes the family and clears the stored credential. What does *not* remove it is
989
- > exchanging the Fluent token for your own session: the widget has already obtained and
990
- > stored the credential by the time it hands you a token to exchange, and holding a session
991
- > of your own neither clears it nor revokes it. This release offers no way to turn the
992
- > persistence off, so an app that cannot accept the exposure at all has no configuration to
993
- > reach for — tell us and it becomes a requirement rather than a workaround.
994
-
995
- Disconnecting ends the session properly: the widget asks the service to revoke it and
996
- clears the stored credential, so the thirty days stop there rather than running out on
997
- their own. A Fluent token already issued keeps verifying until its `exp` — at most five
998
- minutes — because its signature is checked offline and nothing can recall it. That is
999
- the same property the short lifetime was chosen for.
1000
-
1001
- The widget's own teardown is immediate, and the `Promise` that `disconnect()` returns is
1002
- the one that waits: it resolves after every refresh family the disconnect ended has been
1003
- revoked, best effort, including one opened by a `getAuthToken()` that was still out when
1004
- the user disconnected. A wallet dialog answered a minute after the disconnect still opens
1005
- a session, and that promise is what tells you there is none left. It can therefore take as
1006
- long as such a request does, and it never rejects — a service you cannot reach does not
1007
- leave the user signed in here, but do not read a resolved promise as proof the service
1008
- agreed. If you await `disconnect()` before signing the user out of your own backend, that
1009
- is the ordering you get.
1010
-
1011
- ### Sponsorship authenticates with the Fluent token
1012
-
1013
- Gas sponsorship is the same token, used by the widget rather than by you. When a
1014
- Fluent ID sends a transaction in direct mode, the widget mints a Fluent token for
1015
- the signed-in user and sends it as the `Authorization` bearer to the sponsorship
1016
- paymaster, which checks that the token's `aud` is your App and that the operation's
1017
- sender is an address the user proved. **Release 0.4.0 of `@fluent.xyz/connect` is the
1018
- first that sends the Fluent token**; earlier releases sent the Privy access token,
1019
- which the service accepted through a transition path that applies neither check.
1020
- That transition path will be withdrawn, and the SDK release notes will say in which
1021
- release: this guide sets no date for it. Once it is gone, a page still running an earlier
1022
- release will get unsponsored transactions rather than a hard error — the account pays its
1023
- own gas, as the table's other rows already do.
1024
-
1025
- The Sponsorship column above says what each account type gets, and only the first row
1026
- is sponsored. An external wallet sends through the wallet and never through the smart
1027
- account, so there is no user operation to sponsor. Nothing throws: the wallet pays its
1028
- own gas and the transaction goes through.
1029
-
1030
- If the paymaster rejects a token with a `401`, the widget mints one fresh token and
1031
- retries the operation once before the account falls back to paying its own gas. A
1032
- `403` means your App is not set up for sponsorship, and the widget stops asking — for as
1033
- long as the widget's provider subtree lives, which is not the same as the page. The latch
1034
- sits in that subtree, and toggling Quick sign rebuilds it, so after a toggle the next
1035
- operation asks once more and latches again on the same `403`. Turn on `debugLogging`
1036
- ([§9b](#9b-debugging-an-integration)) to see which of these happened.
1037
-
1038
- The SDK's chain, bundler and paymaster HTTP requests have a 30-second deadline per
1039
- request. A slow gas estimate can use that time with sponsored, account-paid or
1040
- ERC-20 gas, including account-paid fallback after sponsorship fails. Chain and
1041
- bundler requests retain up to three retries with exponential backoff; paymaster
1042
- authorization does not retry a timeout. These are request deadlines, so preparing
1043
- and submitting a transaction can take longer than 30 seconds across requests and
1044
- retries. A timeout reports an unanswered request and does not establish that the
1045
- Fluent ID lacks ETH.
1046
-
1047
- A Fluent token needs one more piece of setup, in either mode and for either
1048
- account type: your page origin must be registered on your App in the Fluent App
1049
- settings. That is the Fluent auth service's own list, separate from the Privy
1050
- origin registration direct mode needs. From an unregistered origin
1051
- `getAuthToken()` rejects with `FluentAuthError` code `origin_not_allowed`.
1052
-
1053
- > **Breaking in 0.4.0, for a host that builds its own ZeroDev account.** Two exported
1054
- > helpers changed with the switch to the Fluent token.
1055
- > `createFluentZeroDevSponsoredPaymaster({ chain, rpcUrl, bearerToken })` takes
1056
- > `bearerToken` where 0.3.x took `accessToken`, and the value is now the Fluent token
1057
- > `getAuthToken()` mints rather than a Privy access token. `useFluentZeroDevAccount` no
1058
- > longer reads a token itself: it sponsors nothing unless it is given
1059
- > `sponsorshipTokenSource` — a function returning the token source for the signed-in
1060
- > user — beside `appId` and `sponsorshipUrl`. `<FluentWidget>` wires both for you; this
1061
- > matters only if you call them yourself.
1062
-
1063
- ---
1064
-
1065
- ## 8b. Verify the token on your backend
1066
-
1067
- `widget.getAuthToken()` returns a short-lived ES256 JWT issued by the Fluent
1068
- auth service. Your backend needs no Fluent SDK to check it:
1069
-
1070
- 1. Fetch `<iss>/.well-known/jwks.json` and cache it; the response carries
1071
- `Cache-Control: public, max-age=3600`.
1072
- 2. Pick the key by the token's `kid`. Require `alg == ES256`. Verify the signature.
1073
- 3. Check `iss` equals the issuer you pinned, `aud` equals your `app_…` id, and `exp` is in the
1074
- future.
1075
- 4. Use `sub` as the user id. Read `addresses.account` only if your App has the `addresses`
1076
- scope, and only for on-chain joins.
1077
-
1078
- The issuer is **per network**, and no single rule derives it from the API host the widget calls.
1079
- Pin the one your widget's `network` says, and read its key set from that issuer:
1080
-
1081
- | `network` | `iss` | Key set |
1082
- |-------------|-------|---------|
1083
- | `"mainnet"` | `https://api.fluent.xyz/connect` | `https://api.fluent.xyz/connect/.well-known/jwks.json` |
1084
- | `"testnet"` | `https://api.fluent-connect.dev.gblend.xyz` | `https://api.fluent-connect.dev.gblend.xyz/.well-known/jwks.json` |
1085
-
1086
- Each issuer publishes its own key set, so a backend serving both networks pins both issuers and
1087
- picks the one it expects for that App — not the `iss` the token carries, which is the value
1088
- being checked.
1089
-
1090
- Go, with the same two libraries the Fluent auth service uses:
1091
-
1092
- ```go
1093
- jwks, _ := keyfunc.NewDefaultCtx(ctx, []string{issuer + "/.well-known/jwks.json"})
1094
- tok, err := jwt.Parse(raw, jwks.Keyfunc,
1095
- jwt.WithIssuer(issuer),
1096
- jwt.WithAudience(appID),
1097
- jwt.WithValidMethods([]string{"ES256"}),
1098
- jwt.WithExpirationRequired(),
1099
- )
1100
- if err != nil || !tok.Valid { /* 401 */ }
1101
- sub, _ := tok.Claims.GetSubject()
1102
- ```
1103
-
1104
- Node, with `jose`:
1105
-
1106
- ```ts
1107
- const JWKS = createRemoteJWKSet(new URL(`${issuer}/.well-known/jwks.json`));
1108
- const { payload } = await jwtVerify(raw, JWKS, { issuer, audience: appId, algorithms: ["ES256"] });
1109
- const userId = payload.sub;
1110
- ```
1111
-
1112
- Verify on every request, or exchange the token once for your own session. Both are fine; the
1113
- first needs no application-session state on your side.
1114
-
1115
- Do not persist our token — call `getAuthToken()` each time you need one. It lives five minutes,
1116
- and the SDK renews it silently for both account types, a Fluent ID and an external wallet.
1117
- **Calling it often no longer prompts the wallet.** The wallet signs once, when the session
1118
- opens, and every renewal for the next thirty days is a background request, for as long as the
1119
- service issues the refresh credential a renewal spends
1120
- ([§8](#the-token-renews-itself-silently)).
1121
-
1122
- So verifying on every request is a real option now, for external wallets too. Exchanging our
1123
- token once for your own session is still the lighter thing to do per request, and it is what to
1124
- reach for if you would rather your app's session outlive ours, or have its own expiry and its own
1125
- revocation. It does not change what the widget keeps in the browser: the refresh credential is
1126
- already stored by the time you have a token to exchange, and your own session neither clears nor
1127
- revokes it — see [§8](#where-the-session-is-kept-and-what-that-costs).
1128
-
1129
- ---
1130
-
1131
- ## 8c. Linking X
1132
-
1133
- Some apps need to know a user's X account — a gated drop, a leaderboard, an entitlement that
1134
- belongs to a handle rather than to an address. `linkX()` is how a connected user gets one
1135
- linked, headless: no widget screen, no settings page, one call from your own UI.
1136
-
1137
- It serves both account types. A **Fluent ID** — whether the user signed in *with* X, or with
1138
- Google, email or a passkey and has no X account yet — already has the Privy session the link
1139
- needs. An **external wallet** (MetaMask, say) gets one first: before the X redirect the SDK signs
1140
- the wallet in to Privy with Sign-In with Ethereum, which the user sees as a **signature
1141
- prompt** — and mints the wallet's Fluent token, a second prompt unless this page holds the token
1142
- already; see below. After that the two account types take exactly the same path, resolve the
1143
- same results and reject with the same codes.
1144
-
1145
- ### The call leaves the page, so it is idempotent instead
1146
-
1147
- Linking X means an OAuth round trip through X, and that round trip **navigates away from your
1148
- page**. There is no popup variant to reach for. So `linkX()` is not one long promise that waits
1149
- for the user to come back — it could not be, because the page it was called on is gone by then.
1150
- It is idempotent and re-enterable, and it resolves one of two things:
1151
-
1152
- ```ts
1153
- type FluentLinkXResult =
1154
- | { status: "linked"; x: FluentXAccount } // done; the account is right here
1155
- | { status: "redirecting" }; // the page is leaving for X
1156
- ```
1157
-
1158
- - **A user who already has X** resolves `{ status: "linked", x }`. No Privy dialog, no
1159
- navigation, one request.
1160
- - **A user who has none** resolves `{ status: "redirecting" }` once the navigation to X has
1161
- been started. The code after that `await` does run — briefly. Use it to show a "taking you to
1162
- X" state; do not use it to wait for the link, because the page is unloading and the link
1163
- completes on the page that comes back.
1164
-
1165
- When the browser comes back, **call `linkX()` again** — and this time it resolves `linked`.
1166
- Calling it again after the last call has settled costs one request and changes nothing for a
1167
- user who already has X. Keep **one `linkX()` in flight per page**: do not mount `useLinkX()` and
1168
- also call `linkX()` on mount, and do not mount two `useLinkX()` hooks. A second call made while
1169
- the first still waits for the return replaces it, and the first never settles.
1170
-
1171
- ```ts
1172
- type FluentXAccount = { id: string; handle: string; avatarUrl: string };
1173
-
1174
- /** The wire body of `GET /api/v1/me/profile` and of the link request. `x` is nullable. */
1175
- type FluentProfile = { subject: string; appId: string; x: FluentXAccount | null };
1176
- ```
1177
-
1178
- ### `useLinkX()` does the return trip for you
1179
-
1180
- ```tsx
1181
- import { useLinkX } from "@fluent.xyz/connect";
1182
-
1183
- function LinkXButton() {
1184
- const { linkX, status, x, error } = useLinkX();
1185
-
1186
- if (x) return <span>Linked as @{x.handle}</span>;
1187
- return (
1188
- <>
1189
- <button onClick={() => linkX()} disabled={status === "pending" || status === "redirecting"}>
1190
- {status === "redirecting" ? "Taking you to X…" : "Link X"}
1191
- </button>
1192
- {error ? <p>{error.code}</p> : null}
1193
- </>
1194
- );
1195
- }
1196
- ```
1197
-
1198
- Mount it and the return trip needs nothing from you: the hook sees that this tab started a link,
1199
- waits for the widget to finish it, and reports `status: "linked"` with `x`. Mount it on a page
1200
- that started no link and it does nothing at all.
1201
-
1202
- The same call is on the render context — `const { linkX } = useFluentWidget()` — and behaves
1203
- identically, including the return trip, for an integrator who would rather hold the state
1204
- themselves.
1205
-
1206
- A link that somebody else started in this tab — two people sharing a browser — or a stale
1207
- record of one is discarded, never resumed: the hook's mount-time re-entry stays idle and reports
1208
- no error, whether the other person is known from the stored session or only once Privy has
1209
- restored them, and a `linkX()` call you make yourself — on the hook or on the render context —
1210
- does no work and rejects with `link_failed`. Call again to start a link for the user who is
1211
- signed in now. For an external wallet the same applies to a link another wallet started: the
1212
- user switched wallets across the redirect, and the link the tab remembers is the other wallet's.
1213
-
1214
- What the widget waits for on the way back is the **user Privy restores**, not a callback: after a
1215
- redirected link, Privy's `onSuccess` never fires, because the intent that would have fired it did
1216
- not survive the reload. It waits without polling, and the request that completes the link carries
1217
- a freshly minted identity token — the service reads the X account out of that token, so a stale
1218
- one would link nothing. For an external wallet it also waits for the wallet's client, which the
1219
- connector hands over a moment after it has named the address: the client is what makes the
1220
- connected address the wallet's own — the widget takes the address as connected only once the
1221
- client that signs for it is there — and the link completes as that wallet. The ordinary return
1222
- asks the client for nothing: the request that completes the link is authenticated with the
1223
- wallet's Fluent token, renewed from the refresh credential the pre-redirect mint stored (see
1224
- below). Only a page whose credential has expired in the meantime mints the token again, and that
1225
- needs the client to sign.
1226
-
1227
- ### An external wallet signs in to Privy first
1228
-
1229
- Privy links X to a Privy user, and an external wallet has none until it signs in. So the first
1230
- `linkX()` for a wallet user — and only the first, while that Privy session lasts — starts with
1231
- **Sign-In with Ethereum**: the SDK asks Privy for a SIWE message for the connected address, asks
1232
- the wallet to sign it, and hands Privy the signature. The user sees one **signature prompt** in
1233
- their wallet, for a plain message naming your page and a nonce. **It is a signature, not a
1234
- transaction**: nothing is sent to the chain and nothing costs gas. Then, still before the
1235
- redirect, the SDK mints the wallet's Fluent token — the typed-data challenge of
1236
- [§8](#8-auth-and-the-fluent-token), the same one `getAuthToken()` signs — so that **every signature happens
1237
- before the page leaves**. On a page that has not minted the token yet that is a second prompt;
1238
- on one that already holds it (you called `getAuthToken()` first, or an earlier call minted it)
1239
- the wallet is asked nothing more. Only then does the X redirect happen. The page that comes back
1240
- renews the token from the refresh credential the mint stored and opens the wallet for nothing;
1241
- and on every later call with that Privy session live, nothing is signed again. Tell your users
1242
- to expect the prompts — a wallet user who has never seen Privy will not expect their wallet to
1243
- open before a trip to X.
1244
-
1245
- Each of Privy's two sign-in steps is bounded to ten seconds, and the wallet's own signature
1246
- prompt to five minutes; a step that never answers rejects `link_failed` with a message naming
1247
- the likely cause, and a late answer resumes nothing. **Captcha on the Privy app is not supported
1248
- for `linkX()` today**: with it enabled, Privy's headless sign-in waits for a captcha this SDK
1249
- does not render during `linkX()`, and the call fails after the bound. Wallet login disabled on
1250
- the Privy app ends the same way. Check both in the Privy Dashboard before shipping the wallet
1251
- path.
1252
-
1253
- Nothing about the Fluent user changes over it. The connected account is still the wallet, its
1254
- kind is still the external wallet's, and `getAuthToken()` still mints the wallet's own token —
1255
- keyed on the address, renewed by the wallet's own refresh family ([§8](#8-auth-and-the-fluent-token)) — before,
1256
- during and after the link. The Privy session SIWE makes is the link's machinery, not an account:
1257
- it never becomes a Fluent ID — not when Privy attaches an embedded wallet to it, not when the
1258
- wallet is disconnected or swapped for another while it lives — and the widget never signs with it.
1259
- The SDK tells that session from a Fluent ID's by the external wallet on the Privy user, which
1260
- rests on one assumption: this SDK is the only way an external wallet lands on a Privy user of
1261
- your Privy app — its sign-in offers no wallet method and links no wallets — so do not add one on
1262
- the same Privy app. Should the user choose a Fluent ID later, from the connect modal or the
1263
- account menu, while that session lives, the widget signs it out first: the sign-in method they
1264
- chose — X, Google, email or passkey — runs only once Privy has confirmed the sign-out, and a
1265
- sign-out that fails or runs past its bound runs no method and shows its error in the sign-in
1266
- dialog, where the next click tries again. The wallet stays connected throughout.
1267
-
1268
- Three things can go wrong that are the wallet's own:
1269
-
1270
- - **The user declines the signature.** `linkX()` rejects with `user_rejected` — the same code as
1271
- saying no at X — and nothing was linked or started; call again when they are ready.
1272
- - **Privy signs in a user who does not hold the connected wallet.** The SDK checks the user Privy
1273
- returns before it links anything: one without the connected address among their accounts is
1274
- not a session the link can use, so the SDK asks Privy to sign it out again and `linkX()`
1275
- rejects with `link_failed`, with nothing started. The sign-out is attempted and awaited within
1276
- a bound of ten seconds, and the call rejects with `link_failed` either way: when Privy confirms
1277
- it within the bound the session is gone, and when it does not — Privy's logout failed, or did
1278
- not finish in time — the rejection says so in its message and the session may still be live on
1279
- the page, though never as a Fluent ID: for as long as that page lives, the widget keeps reading
1280
- it as the wallet's failed sign-in. Kept otherwise, it would be the one Privy session that could
1281
- be taken for a Fluent ID on this page. The wallet stays connected and its token is untouched.
1282
- - **The service refuses the link with `403 privy_wallet_mismatch`.** The Privy session that linked
1283
- X belongs to a different wallet than the Fluent token's. `linkX()` rejects with `link_failed`.
1284
- The SDK makes this hard to reach: a Privy session left in the browser by another wallet — the
1285
- user switched accounts in MetaMask, and Privy kept the old session across the reload — is
1286
- **replaced before the link**, logged out and the connected wallet signed in afresh, rather than
1287
- reused; until then it stays that other wallet's session, never the start of a Fluent ID for
1288
- the wallet connected now. The one Privy session the SDK will not replace is a Fluent ID's: with
1289
- a Fluent ID signed in on the page — whether Privy has restored them yet or not — and an
1290
- external wallet connected beside it, `linkX()` for the wallet rejects with `link_failed`, since
1291
- signing the Fluent ID out from under the person is not the link's to do.
1292
-
1293
- ### What it rejects with
1294
-
1295
- Every rejection is a `FluentAuthError` with one of:
1296
-
1297
- | `code` | What happened |
1298
- | --- | --- |
1299
- | `user_rejected` | The user said no at X, closed the flow, or declined the SIWE signature or the Fluent token's challenge. |
1300
- | `linked_to_another_user` | That X account is already linked to another Fluent user. |
1301
- | `not_authenticated` | No Fluent ID or external wallet is connected, or the wallet's client is not here yet. Connect first, or wait and call again. |
1302
- | `bad_request` | The service refused the request body. Report it; it is ours, not yours. |
1303
- | `link_failed` | Everything else: a discarded link, `privy_wallet_mismatch`, a Fluent ID signed in beside the wallet, a sign-in step that timed out, a failure under the call. |
1304
-
1305
- No other code reaches you from `linkX()`. A refusal raised under it — by the request that mints
1306
- the Fluent token, say — keeps its message and arrives as `link_failed`, so one `switch` over the
1307
- five codes above is complete.
1308
-
1309
- ### The sequence your backend sees
1310
-
1311
- 1. Call `linkX()` until it reports `linked`. (`redirecting` means the browser is leaving; after
1312
- it returns, `useLinkX()` or your own call finishes the job.)
1313
- 2. Call `getAuthToken()` for a fresh Fluent token.
1314
- 3. Your backend verifies that token ([§8b](#8b-verify-the-token-on-your-backend)) and makes its
1315
- own check — `GET /api/v1/me/profile` with the token, server to server, reading `x`. The same
1316
- account `linkX()` returned is the one that endpoint reports.
1317
-
1318
- Step 3 is the one that counts. `linkX()` resolving `linked` is the widget telling you the link
1319
- went through; your backend verifying it is the part an entitlement should hang on.
1320
-
1321
- ---
1322
-
1323
- ## 9. One copy of the web3 stack (peer dependencies)
1324
-
1325
- `viem`, `wagmi`, and `@tanstack/react-query` are peer dependencies precisely
1326
- because they rely on **single-instance React context and singletons**:
1327
-
1328
- - **wagmi / react-query** — hooks resolve their provider by React-context object
1329
- identity. A second copy of the package is a *different* context object, so
1330
- hooks silently fail to see the provider across the boundary.
1331
- - **viem** — you build the `abi` / `Address` / `Hex` values you pass into
1332
- `createBatchOp` with *your* viem. A second, mismatched copy makes those types
1333
- incompatible at the boundary.
1334
-
1335
- Installing them as peers (§2) guarantees your package manager resolves a single
1336
- shared copy. **Do not** add them back as direct nested dependencies with a
1337
- divergent version.
1338
-
1339
- ### Provider model (phase 1: single-chain)
1340
-
1341
- `<FluentWidget>` mounts its own `WagmiProvider` + `QueryClientProvider` (Fluent
1342
- chain) and renders your app **inside** them via `renderPage`. For a single-chain
1343
- app that has no other wagmi, this is exactly what you want — the widget is the
1344
- one source of wallet/account state, and you read it through `useFluentWidget()`.
1345
-
1346
- > If you later need **multiple chains** (your own wagmi config alongside the
1347
- > widget's), that's a separate architecture — shared providers / a single
1348
- > `WagmiProvider`. Not supported in phase 1; talk to the Fluent team.
1349
-
1350
- ### Your own TanStack Query client
1351
-
1352
- Mount a `QueryClientProvider` **around** `<FluentWidget>` and everything you
1353
- render through `renderPage` / `renderHome` keeps resolving against *your* client:
1354
-
1355
- ```tsx
1356
- <QueryClientProvider client={queryClient}> {/* yours */}
1357
- <FluentWidget
1358
- config={{ /* … */ }}
1359
- mode="page"
1360
- renderPage={() => <YourApp />} {/* useQueryClient() === queryClient */}
1361
- />
1362
- </QueryClientProvider>
1363
- ```
1364
-
1365
- So a query you prefetched, or hydrated from your own server render, is served
1366
- from your cache instead of running a second time. There is no prop for it: the
1367
- widget reads the client from the context above it.
1368
-
1369
- The two caches stay separate. The widget's own queries stay on the widget's
1370
- client, so a `defaultOptions` you set, an `invalidateQueries` or a `clear()` of
1371
- yours does not reach them — and the widget's bridge queries do not appear in
1372
- your devtools. Mount no client of your own and nothing changes: your pages
1373
- resolve against the widget's, as before.
1374
-
1375
- ---
1376
-
1377
- ## 9b. Debugging an integration
1378
-
1379
- The widget's internal connect / smart-account / signing diagnostics are silent by
1380
- default. Turn them on with the `debugLogging` prop while wiring things up:
1381
-
1382
- ```tsx
1383
- <FluentWidget config={{ /* … */ }} debugLogging mode="page" renderPage={() => <YourApp />} />
1384
- ```
1385
-
1386
- `debugLogging={false}` (the default) suppresses **all** widget console output.
1387
- Leave it off in production.
1388
-
1389
- ## 10. Checklist
1390
-
1391
- - [ ] Got a Fluent `appId` and `privyClientId`.
1392
- - [ ] Picked network (`testnet` / `mainnet`) — and every chain id pinned elsewhere in the app matches it (§3).
1393
- - [ ] Origin allow-listed on the Privy app client behind your `privyClientId`.
1394
- - [ ] (`getAuthToken()`) page origin registered on your App in the Fluent App settings (§8).
1395
- - [ ] (linking X) called `linkX()` until it reports `linked` — it is re-entered after the redirect, not awaited across it — and verified the account on your backend (§8c).
1396
- - [ ] Imported `@fluent.xyz/connect/styles.css` once.
1397
- - [ ] Mounted `<FluentWidget>` at the root; app rendered via `renderPage`.
1398
- - [ ] Read account via `useFluentWidget()` / `useWidget()`.
1399
- - [ ] All txs go through `createBatchOp(...).execute()`, guarded on `executionReady`.
1400
- - [ ] Signatures go through `widget.signMessage` / `widget.signTypedData` and are verified with ERC-1271/6492, not `ecrecover` (§7b).
1401
- - [ ] Checked provider coexistence if the app already uses wagmi / viem / react-query (§9).
1402
-
1403
- ---
1404
-
1405
- ## Upgrading from 0.4
1406
-
1407
- 0.5.0 removes hosted mode. Direct login — Fluent's sign-in dialog inside your page
1408
- ([§8](#8-auth-and-the-fluent-token)) — is the one way to log in to a Fluent ID.
1409
-
1410
- - **`authMode` is removed from `FluentWidgetConfig`.** Delete the key. A config that passed
1411
- `authMode: "direct"` keeps exactly the behaviour it had; the widget accepts the key one
1412
- last time, ignores it and warns once. `authMode: "hosted"` throws at startup with these
1413
- instructions.
1414
- - **A config that omitted `authMode` was on hosted mode** — it was the 0.4.x default — and is
1415
- now on Direct login. Direct login mounts Privy on your page, so your App's origin has to be
1416
- registered on the Privy app client behind your `privyClientId`
1417
- ([§1](#1-prerequisites)). Ask Fluent to add it before you upgrade, or your
1418
- users meet a login button that silently does nothing.
1419
- - **`fluent.initialize().connect()` and `.buildAuthorizeUrl()` are removed**, together with
1420
- the `authorizeUrl` and `redirectUri` options of `fluent.initialize()`. There is no authorize
1421
- popup to open. `initialize`, `status()`, `setSession()` and `disconnect()` are unchanged.
1422
- - **The `hosted_not_supported` error code is gone** from `FluentAuthError` and from the
1423
- `linkX()` codes ([§8c](#8c-linking-x)): nothing refuses a signature, a token or a link for
1424
- want of an in-page Privy session any more.
1425
- - **A user signed in through hosted mode on 0.4.x signs in again** after your App upgrades.
1426
- Their stored session still shows them as connected and the first signature finds no signer;
1427
- Disconnect, then sign in again, clears it.
1428
- - `FluentWidgetAuthMode` is no longer exported, and `FluentWidgetRenderContext` and
1429
- `FluentIframeRpcExecutor` no longer carry `authMode`.
1
+ # Fluent Connect integration guide
2
+
3
+ The guide moved to [`docs/`](docs/getting-started.md), shipped with the package. This page maps
4
+ each section of the old single-file guide to its new place; a link to one of its sections lands
5
+ here. Sections the table does not list (what the widget stores, where a send reads fees and
6
+ receipts, where the session is kept, the 0.4 upgrade notes) described internals and were dropped.
7
+
8
+ | Old section | Now |
9
+ |---|---|
10
+ | 1. Prerequisites | [Getting started: What you need from Fluent](docs/getting-started.md#what-you-need-from-fluent) |
11
+ | 2. Install; `Buffer` is provided for you | [Getting started: Install](docs/getting-started.md#install) |
12
+ | 3. Minimal setup; Networks and chain ids | [Getting started: Network](docs/getting-started.md#network), [Mount the widget](docs/getting-started.md#mount-the-widget) |
13
+ | 4. Config reference (`FluentWidgetConfig`) | [Configuration](docs/configuration.md#fluentwidgetconfig) |
14
+ | 4. Config errors | [Errors: `FluentWidgetConfigError`](docs/errors.md#fluentwidgetconfigerror) |
15
+ | 4. Capacitor OAuth | [Configuration: Capacitor and other web views](docs/configuration.md#capacitor-and-other-web-views) |
16
+ | 4. The section on Auth methods | [Configuration: Auth methods](docs/configuration.md#auth-methods) |
17
+ | 4. Account avatar | [Configuration: Account avatar and images](docs/configuration.md#account-avatar-and-images) |
18
+ | 5. Placing the connect button | [Getting started: The connect button](docs/getting-started.md#the-connect-button) |
19
+ | 6. Reading account state | [Getting started: Reading the account](docs/getting-started.md#reading-the-account) |
20
+ | 6. The props, the render context and the session | [API reference: `FluentWidgetProps`](docs/api.md#fluentwidgetprops), [`FluentWidgetRenderContext`](docs/api.md#fluentwidgetrendercontext), [`FluentWidgetSession`](docs/api.md#fluentwidgetsession) |
21
+ | 6. What an External wallet user sees in Settings | [Concepts: What differs by account kind](docs/concepts.md#what-differs-by-account-kind) |
22
+ | 7. Sending a transaction; Example: approve + deposit | [Transactions](docs/guides/transactions.md#building-and-executing), [the example](docs/guides/transactions.md#example-approve-and-deposit-in-one-batch-operation) |
23
+ | 7. Gas payment | [Transactions: Gas payment](docs/guides/transactions.md#gas-payment); Sponsorship and its fallback in [Sponsorship](docs/guides/sponsorship.md) |
24
+ | 7. What `execute()` rejects with | [Transactions: Rejections](docs/guides/transactions.md#rejections), [Errors](docs/errors.md#how-to-branch) |
25
+ | 7. Skipping UserOperation gas estimation | [Experimental: `userOperationGas`](docs/experimental.md#useroperationgas) |
26
+ | 7. Execution timing | [Experimental: `paymaster` and `timing`](docs/experimental.md#paymaster-and-timing) |
27
+ | 7. Always guard on `executionReady` | [Transactions: Building and executing](docs/guides/transactions.md#building-and-executing) |
28
+ | 7b. Requesting a signature | [Signing](docs/guides/signing.md#the-two-calls) |
29
+ | 7b. Verify with ERC-1271 / ERC-6492; EIP-2612 `permit` | [Signing: Verifying a signature](docs/guides/signing.md#verifying-a-signature) |
30
+ | 7c. Embedding a marketplace iframe | [Iframe](docs/guides/iframe.md#set-it-up) |
31
+ | 8. Auth, and how the Auth token renews itself | [Backend auth: Get an Auth token](docs/guides/backend-auth.md#get-an-auth-token), [Renewal](docs/guides/backend-auth.md#renewal) |
32
+ | 8. How Sponsorship authenticates with the Auth token | [Sponsorship: Before you start](docs/guides/sponsorship.md#before-you-start), [Backend auth: Sponsorship uses the same token](docs/guides/backend-auth.md#sponsorship-uses-the-same-token) |
33
+ | 8. What `getAuthToken()` rejects with | [Errors: `FluentAuthError`](docs/errors.md#fluentautherror) |
34
+ | 8b. Verify the token on your backend | [Backend auth: Verify the token on a backend](docs/guides/backend-auth.md#verify-the-token-on-a-backend) |
35
+ | 8c. Linking X | [Link X](docs/guides/link-x.md#the-call) |
36
+ | 8c. What it rejects with | [Link X: Rejections](docs/guides/link-x.md#rejections) |
37
+ | 8c. The sequence your backend sees | [Link X: The sequence](docs/guides/link-x.md#the-sequence) |
38
+ | 9. Peer dependencies; Provider model; Your own TanStack Query client | [Getting started: Install](docs/getting-started.md#install) |
39
+ | 9b. Debugging an integration | [Getting started: Debugging](docs/getting-started.md#debugging) |
40
+ | 10. Checklist | [Getting started: Checklist](docs/getting-started.md#checklist) |
41
+ | 11. Export reference | [API reference](docs/api.md) |
42
+ | Upgrading from 0.5 | [Upgrading from 0.5](docs/upgrading-0.5.md) |
43
+ | What the Bridge page can do on mainnet | [Concepts: What the Swap page can do on mainnet](docs/concepts.md#what-the-swap-page-can-do-on-mainnet) |