@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/README.md CHANGED
@@ -1,310 +1,114 @@
1
1
  # `@fluent.xyz/connect`
2
2
 
3
- React widget for Fluent Connect — login, smart account, balances, batch txs, signatures, and gas payment UI.
3
+ A React widget and hooks that give an App a Fluent ID smart account on Fluent: Direct login to a
4
+ Fluent ID or a connected External wallet, the account's balances, and Batch operations with
5
+ gas-sponsored execution. It is for React Apps (React 18 or later) only.
4
6
 
5
7
  ## Install
6
8
 
7
9
  ```bash
8
- pnpm add @fluent.xyz/connect react react-dom
10
+ pnpm add @fluent.xyz/connect @tanstack/react-query react react-dom viem wagmi
9
11
  ```
10
12
 
11
- Also ensure peer/runtime packages your app needs are installed (versions compatible with this package):
13
+ The five peers are peers so that your App and the widget share one copy of each. You also need
14
+ an `appId` and a `privyClientId` from Fluent, your page origins allow-listed for Direct login,
15
+ and, for sponsored operations, the App enabled for Sponsorship and Auth tokens: see
16
+ [docs/getting-started.md](docs/getting-started.md).
12
17
 
13
- ```bash
14
- pnpm add @privy-io/react-auth viem wagmi @tanstack/react-query
15
- ```
16
-
17
- ### `Buffer` is provided for you
18
-
19
- Importing `@fluent.xyz/connect` defines `globalThis.Buffer` when the page has none, so your
20
- app needs no `Buffer` polyfill of its own. Privy's embedded wallet calls `Buffer.from(...)`
21
- while signing, and a browser has no `Buffer`; the SDK fills that gap at import time. An
22
- existing `globalThis.Buffer` is never replaced, so a polyfill your app already ships keeps
23
- working.
24
-
25
- ## Usage
26
-
27
- Set the Fluent network via `config.network` or an environment variable:
28
-
29
- ```bash
30
- # testnet (default)
31
- VITE_FLUENT_WIDGET_NETWORK=testnet
32
-
33
- # mainnet
34
- VITE_FLUENT_WIDGET_NETWORK=mainnet
35
- ```
36
-
37
- Aliases: `development` / `dev` → testnet, `production` / `prod` → mainnet.
18
+ ## Quickstart
38
19
 
39
20
  ```tsx
21
+ import "@fluent.xyz/connect/styles.css";
40
22
  import {
23
+ FluentReviewRejectedError,
41
24
  FluentWidget,
42
- resolveFluentWidgetNetworkFromEnv,
25
+ useFluentWidget,
26
+ type FluentWidgetConfig,
43
27
  } from "@fluent.xyz/connect";
44
- import "@fluent.xyz/connect/styles.css";
45
-
46
- export function App() {
47
- return (
48
- <FluentWidget
49
- config={{
50
- appId: "app_<32 hex, from the Fluent Dashboard>",
51
- privyClientId: "client-<issued by Fluent>",
52
- network: resolveFluentWidgetNetworkFromEnv() ?? "testnet",
53
- appName: "My App",
54
- }}
55
- mode="page"
56
- renderPage={({ session, openConnect, widget }) => (
57
- <button type="button" onClick={openConnect}>
58
- {session ? "Connected" : "Connect"}
59
- </button>
60
- )}
61
- />
62
- );
63
- }
64
- ```
65
-
66
- `appId` and `privyClientId` are both required and come from Fluent. `appId` is the
67
- App's identity — sponsorship, auth and analytics speak it — and must be the `app_<32 hex>`
68
- value the Fluent Dashboard shows; the widget throws on any other shape. `privyClientId` is
69
- login configuration: the Privy app client carrying your allowed origins, issued from the
70
- dev Privy app for `testnet` and from the production Privy app for `mainnet`.
71
-
72
- For Capacitor social login, pass
73
- `customOAuthRedirectUrl: "https://app.example.com/auth/ios/callback"` in `config`.
74
- This forwards an HTTPS Universal Link callback to Privy; the host must configure
75
- the dashboard allowlists, iOS Associated Domains, and callback handling.
76
- See [Capacitor OAuth setup](https://github.com/fluentlabs-xyz/fluent-connect-sdk/blob/devel/packages/connect/INTEGRATION.md#capacitor-oauth).
77
-
78
- > Upgrading from 0.2.x? `partnerId` was renamed to `appId` in 0.3.0 and the id value changed
79
- > from `partner_…` to `app_…`; passing `partnerId` throws with the same hint. Migrating from
80
- > `clientId`? That option is gone: the value it held is now `privyClientId`.
81
-
82
- ### Logging in
83
-
84
- Clicking Connect opens Fluent's own sign-in dialog inside your page — Direct login, the one
85
- way to log in to a Fluent ID. It mounts Privy on your origin, so that origin has to be
86
- registered on the Privy app client behind your `privyClientId`; Privy answers an unregistered
87
- origin with a silent no-op on the login button. Fluent registers the origins you give it when
88
- it issues the client. The user's Privy session then lives in your page, which is what lets
89
- `signMessage`, `signTypedData`, `getAuthToken()` and `linkX()` answer for a Fluent ID without
90
- leaving it. External wallets connect through Reown AppKit beside it.
91
-
92
- ### Authenticating your backend
93
-
94
- `getAuthToken()` (render context / `useFluentWidget()`) returns a 5-minute ES256 JWT signed by
95
- Fluent Connect. Send it to your backend once and issue your own session; verify it with the keys
96
- at `<iss>/.well-known/jwks.json` and check `iss`, `aud` (your `appId`) and `exp`. The issuer is
97
- per network, and no single rule derives it from the API host: on `testnet` it is
98
- `https://api.fluent-connect.dev.gblend.xyz`, on `mainnet` `https://api.fluent.xyz/connect`, whose
99
- key set is `https://api.fluent.xyz/connect/.well-known/jwks.json`. Pin the issuer of the network
100
- your widget runs on — [`INTEGRATION.md` §8b](INTEGRATION.md#8b-verify-the-token-on-your-backend).
101
- `sub` is stable per user per app. `addresses` is present only when your app has the `addresses`
102
- scope. A Fluent ID and an external wallet both get a token —
103
- for a wallet, an EOA or a deployed contract wallet signs in; a counterfactual smart account
104
- cannot (no ERC-6492).
105
- The token renews itself silently for both account types — against a service that issues the
106
- refresh credential this release expects, an external wallet signs once, when the session opens,
107
- not once per token; against a deployment that answers without one there is nothing to renew from,
108
- and every expired token costs another signature. The session and what holding it costs are in
109
- [`INTEGRATION.md` §8](INTEGRATION.md#8-auth-and-the-fluent-token). See
110
- [`apps/auth-demo`](https://github.com/fluentlabs-xyz/fluent-connect-sdk/tree/main/apps/auth-demo)
111
- for a browser-side verifier.
112
-
113
- Brand images (logo, wallet icons) ship inside the package as bundled data URLs — you do not need a `/fluent-assets` folder.
114
-
115
- ### Connect button placement
116
-
117
- By default the connect control floats top-right (`connectButton="fixed"`). To place it yourself:
118
-
119
- ```tsx
120
- // Hide the default control and use your own CTA
121
- <FluentWidget
122
- connectButton={false}
123
- config={{
124
- appId: "app_…",
125
- privyClientId: "client-…",
126
- network: "testnet",
127
- appName: "My App",
128
- }}
129
- mode="page"
130
- renderPage={({ openConnect, openAccount, hasConnectedAccount }) => (
131
- <button type="button" onClick={hasConnectedAccount ? openAccount : openConnect}>
132
- {hasConnectedAccount ? "Account" : "Connect"}
133
- </button>
134
- )}
135
- />
136
-
137
- // Or reuse the Fluent button in your layout
138
- <FluentWidget
139
- connectButton={false}
140
- renderConnectButton={({ DefaultButton }) => (
141
- <header className="flex justify-end p-4">
142
- <DefaultButton />
143
- </header>
144
- )}
145
- mode="page"
146
- renderPage={() => null}
147
- />
148
- ```
149
-
150
- ### Sending a transaction
151
-
152
- Everything your app sends goes through one call: `widget.createBatchOp({...}).execute()`.
153
- `widget` comes from the render context (`renderPage` / `renderHome`) or from
154
- `useFluentWidget()` anywhere below `<FluentWidget>`; `useWidget()` returns it on its own. The
155
- widget routes a Fluent ID (one UserOperation, all calls atomic) and an external wallet (one
156
- transaction per call, each confirmed in the wallet) itself, so your app never branches on the
157
- account type.
158
-
159
- ```tsx
160
- import { useFluentWidget } from "@fluent.xyz/connect";
161
- import { erc20Abi, exchangeAbi } from "./abi";
162
-
163
- function BuyButton({ token, exchange, price, orderId }) {
164
- const { widget } = useFluentWidget();
165
-
166
- async function onBuy() {
167
- // Guard first: `execute()` rejects when the session cannot execute, and
168
- // `widget.account.executionError` is the message to show when it is not ready.
169
- if (!widget.account.executionReady) return;
170
-
171
- const { hash, atomic } = await widget
172
- .createBatchOp({
173
- id: "buy-order",
174
- reviewTitle: "Approve + buy",
175
- calls: [
176
- { to: token, abi: erc20Abi, method: "approve", args: [exchange, price] },
177
- { to: exchange, abi: exchangeAbi, method: "buy", args: [orderId] },
178
- ],
179
- })
180
- .execute();
181
- // atomic === true → both calls landed in a single UserOperation (Fluent ID)
28
+ import { useState } from "react";
29
+ import { erc20Abi, parseUnits } from "viem";
30
+
31
+ const config: FluentWidgetConfig = {
32
+ appId: "app_0123456789abcdef0123456789abcdef",
33
+ privyClientId: "client-0123456789abcdef",
34
+ network: "testnet",
35
+ };
36
+
37
+ // Placeholders: your token's address and the recipient's.
38
+ const TOKEN = "0x1111111111111111111111111111111111111111";
39
+ const RECIPIENT = "0x2222222222222222222222222222222222222222";
40
+
41
+ function App() {
42
+ const { status, widget } = useFluentWidget();
43
+ const [message, setMessage] = useState("");
44
+ if (status !== "connected") return <p>Connect to continue.</p>;
45
+
46
+ async function send() {
47
+ const amount = parseUnits("1", 18);
48
+ try {
49
+ const result = await widget
50
+ .createBatchOp({
51
+ calls: [{ to: TOKEN, abi: erc20Abi, method: "transfer", args: [RECIPIENT, amount] }],
52
+ })
53
+ .execute();
54
+ setMessage("Sent: " + result.hash);
55
+ } catch (error) {
56
+ const dismissed =
57
+ error instanceof FluentReviewRejectedError &&
58
+ error.code === "transaction_review_rejected";
59
+ setMessage(dismissed ? "You dismissed the Review." : "The operation failed.");
60
+ }
182
61
  }
183
62
 
184
63
  return (
185
- <button type="button" onClick={onBuy} disabled={!widget.account.executionReady}>
186
- Buy
187
- </button>
64
+ <main>
65
+ <p>Your account: {widget.account.address}</p>
66
+ <button type="button" onClick={send}>
67
+ Send 1 token
68
+ </button>
69
+ <p>{message}</p>
70
+ </main>
188
71
  );
189
72
  }
190
- ```
191
-
192
- `calls` is the only required field: `reviewTitle` is the heading of the Fluent review modal
193
- and `id` is a label for your own bookkeeping. Each call carries either `abi` + `method` +
194
- `args` or raw `data`, and `to` can be any contract. `createBatchOp` itself throws straight
195
- away on an empty `calls` array, or on a call that has neither `data` nor `abi` + `method`.
196
-
197
- `execute()` resolves once the transaction is included, with `hash`, every hash in order as
198
- `hashes`, `atomic`, `sponsored`, the `receipt` for `hash`, and `userOpHash` for a
199
- smart-account operation. It rejects when the session cannot execute (the message is
200
- `widget.account.executionError`), when the user dismisses the Fluent review
201
- (`FluentReviewRejectedError`, message `User rejected Fluent transaction review`), when the
202
- wallet rejects a call, and when a call reverts — a sequential external-wallet batch stops at
203
- the call that reverted. Who pays the gas, how to force a gas token, and what each stage costs
204
- in time: [`INTEGRATION.md` §7](INTEGRATION.md#7-sending-a-transaction).
205
-
206
- ### Execution gas headroom
207
-
208
- For smart-account batches whose execution cost can change between estimation and
209
- inclusion, set `userOperationGas` on `execute()`:
210
-
211
- ```ts
212
- await widget.createBatchOp({ calls }).execute({
213
- userOperationGas: {
214
- callGasBuffer: { percentage: 50, fixed: 50_000n },
215
- },
216
- });
217
- ```
218
-
219
- This example sets `callGasLimit` to `ceil(estimate × 1.5) + 50,000`. The estimate
220
- covers the complete UserOperation, including account deployment and any gas-token
221
- approval prepended by the widget. The buffer is applied during normal gas
222
- preparation, before final paymaster authorization and signing, without adding an
223
- estimation request. Paymaster adapters that previously supplied data only once
224
- are called again to authorize the final gas limit. The same policy
225
- applies to sponsored, account-paid, and ERC-20 gas, including sponsorship fallback.
226
73
 
227
- Alternatively, supply a known execution limit with
228
- `userOperationGas: { callGasLimit: 600_000n }`. Use either `callGasLimit` or
229
- `callGasBuffer`. Percentages must be nonnegative safe integers; fixed gas must be
230
- a nonnegative bigint, and the final limit must fit a positive uint128. Defaults
231
- keep the existing estimation behavior. These options apply only to smart-account
232
- UserOperations; external EOA transactions keep their wallet's gas estimation.
233
-
234
- Choose headroom for your application's execution paths and paymaster limits.
235
- Headroom increases the maximum gas budget and does not guarantee execution if
236
- state changes. An included outer transaction can still contain a failed
237
- UserOperation; the widget continues to reject that failed execution.
238
-
239
- For a batch with known gas budgets, opt out of SDK gas estimation explicitly:
240
-
241
- ```ts
242
- await widget.createBatchOp({ calls }).execute({
243
- userOperationGas: {
244
- skipEstimation: true,
245
- callGasLimit: 600_000n,
246
- verificationGasLimit: 500_000n,
247
- preVerificationGas: 100_000n,
248
- },
249
- });
250
- ```
251
-
252
- This skips the account gas hook and `eth_estimateUserOperationGas`. Supply budgets
253
- for the complete batch and account deployment; the example values are
254
- illustrative. Omit both paymaster limits to use the provider's authorized limits
255
- and calldata overhead up to `preVerificationGas`, without SDK gas estimation.
256
- Supply both limits to require an exact match for every gas field, as in 0.5.0.
257
- The default is `skipEstimation: false`; a fixed `callGasLimit` alone
258
- still allows other gas fields to be estimated. See
259
- [`INTEGRATION.md` §7](INTEGRATION.md#skipping-useroperation-gas-estimation) for validation,
260
- authorization and remaining network requests.
261
-
262
- ## Styles
263
-
264
- Import the package CSS once in your app entry:
265
-
266
- ```ts
267
- import "@fluent.xyz/connect/styles.css";
74
+ export function Root() {
75
+ return <FluentWidget config={config} mode="page" renderPage={() => <App />} />;
76
+ }
268
77
  ```
269
78
 
270
- ## Upgrading from 0.4
271
-
272
- 0.5.0 removes hosted mode. Direct login — Fluent's sign-in dialog inside your page — is the one
273
- way to log in to a Fluent ID.
274
-
275
- - **`authMode` is removed from `FluentWidgetConfig`.** Delete the key. A config that passed
276
- `authMode: "direct"` keeps exactly the behaviour it had; the widget accepts the key one last
277
- time, ignores it and warns once. `authMode: "hosted"` throws at startup with this note's
278
- instructions.
279
- - **A config that omitted `authMode` was on hosted mode** — it was the 0.4.x default — and is
280
- now on Direct login. Direct login mounts Privy on your page, so your App's origin has to be
281
- registered on the Privy app client behind your `privyClientId`. Ask Fluent to add it before
282
- you upgrade, or your users meet a login button that silently does nothing.
283
- - **`fluent.initialize().connect()` and `.buildAuthorizeUrl()` are removed**, together with
284
- `authorizeUrl` and `redirectUri` on `fluent.initialize()`. There is no authorize popup to
285
- open. `initialize`, `status()`, `setSession()` and `disconnect()` are unchanged.
286
- - **The `hosted_not_supported` error code is gone** from `FluentAuthError` and from `linkX()`:
287
- nothing refuses a signature, a token or a link for want of an in-page Privy session any more.
288
- - **A user signed in through hosted mode on 0.4.x signs in again** after your App upgrades.
289
- Their stored session still shows them as connected and the first signature finds no signer;
290
- Disconnect, then sign in again, clears it.
291
- - `FluentWidgetAuthMode` is no longer exported, and `FluentWidgetRenderContext` and
292
- `FluentIframeRpcExecutor` no longer carry `authMode`.
293
-
294
- ## Native Privy SDK adapter
295
-
296
- Hosts that use a native Privy SDK can supply `privyAdapter` to `FluentWidget`.
297
- The adapter implements `FluentPrivyAdapter`: a provider and
298
- Privy-compatible hooks for authentication, user/identity tokens, embedded wallet
299
- RPC and the enabled login methods. Fluent Connect continues to derive the same
300
- ZeroDev account, exchange verified Privy tokens, review operations and apply
301
- sponsorship policy. Web hosts omit this prop and retain the React SDK.
302
-
303
- Keep one stable adapter and Provider per SDK runtime. The native provider must
304
- restore its own session before reporting ready, publish logout and token changes,
305
- and bind every signature to the connected native wallet. It must keep wallet keys
306
- in the SDK and implement or disable the login methods exposed by the UI. Passing
307
- mobile client IDs to the web provider alone does not provide native authentication.
79
+ `network` is required and has no default: pass `"testnet"` or `"mainnet"` as a literal for each
80
+ deployment. `execute()` resolves once the Batch operation is included. Whether a Fluent ID's
81
+ operation shows the widget's Review depends on Quick sign, `confirmation` and
82
+ `quickSign.whitelistAddresses` ([docs/concepts.md](docs/concepts.md#prompt-mode-and-silent-mode)).
83
+ When the person dismisses the widget's Review (shown for a Fluent ID in Prompt mode), it rejects
84
+ with `FluentReviewRejectedError`, whose `code` is `"transaction_review_rejected"`; an External
85
+ wallet's own prompt rejects with the wallet's error. Branch on the class and the `code`, not on
86
+ the message. Keep a `default` branch in any `switch` over a code or status union: a later
87
+ release may add a value. Every code is listed in [docs/errors.md](docs/errors.md).
88
+
89
+ ## Documentation
90
+
91
+ - [docs/getting-started.md](docs/getting-started.md): what to ask Fluent for, install, Network,
92
+ mounting the widget, the connect button, reading the account.
93
+ - [docs/concepts.md](docs/concepts.md): Fluent ID, External wallet, Widget account, Widget
94
+ session, Review, Quick sign, Sponsorship and the other terms.
95
+ - [docs/configuration.md](docs/configuration.md): the options of `config` and the props of
96
+ `<FluentWidget>`.
97
+ - [docs/guides/transactions.md](docs/guides/transactions.md): Batch operations, Gas payment and
98
+ Sponsorship.
99
+ - [docs/guides/sponsorship.md](docs/guides/sponsorship.md): Sponsorship flow by flow, reading
100
+ `sponsored`, and why an operation was not sponsored.
101
+ - [docs/guides/signing.md](docs/guides/signing.md): message and typed-data signatures.
102
+ - [docs/guides/backend-auth.md](docs/guides/backend-auth.md): Auth tokens and verifying them on
103
+ your backend.
104
+ - [docs/guides/link-x.md](docs/guides/link-x.md): linking an X account.
105
+ - [docs/guides/iframe.md](docs/guides/iframe.md): the Iframe bridge for a page your App embeds.
106
+ - [docs/errors.md](docs/errors.md): every error class and `code`, and how to branch on them.
107
+ - [docs/experimental.md](docs/experimental.md): what may change or be removed in a minor
108
+ release.
109
+ - [docs/api.md](docs/api.md): the reference of every export.
110
+
111
+ Upgrading from 0.5: [docs/upgrading-0.5.md](docs/upgrading-0.5.md)
308
112
 
309
113
  ## License
310
114