@fluent.xyz/connect 0.6.1 → 0.6.2-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/docs/api.md CHANGED
@@ -128,7 +128,7 @@ export type FluentWidgetRenderContext = {
128
128
  | `disconnect` | `() => Promise<void>` | no | no | Tear down the current session without going through the widget's account menu — the same teardown that menu's "Disconnect" runs. The session and the stored identity token are cleared before this resolves, so a host can await it before resetting its own state. It also asks the service to revoke the Service session, and any Service session that a `getAuthToken()` still out at the disconnect opens later, and resolves once those requests have been answered or have failed, so it can take as long as that `getAuthToken()` does. A failed revocation is not retried: the promise resolving does not prove the service ended the Service session. |
129
129
  | `hasConnectedAccount` | `boolean` | no | no | Whether a Widget account, a Fluent ID or an External wallet, is connected now. `false` while a stored session is still being restored: branch on `status` to tell that apart. |
130
130
  | `status` | `FluentWidgetStatus` | no | no | Connection state as a single value that is meaningful on every render — including the first, before a stored session has been reconciled. Branch on this rather than on `hasConnectedAccount` alone: `"restoring"` and `"disconnected"` both have `hasConnectedAccount === false`, and treating them alike shows a Connect button to users who are already signed in. The account's address is `widget.account.address`. |
131
- | `refreshBalances` | `() => void` | no | no | Refetch the widget's on-chain balances. Transactions run through `widget.createBatchOp` refresh automatically; call this after a tx sent via an External wallet client (outside the widget's execution path). |
131
+ | `refreshBalances` | `() => void` | no | no | Refetch the widget's on-chain balances. Transactions run through `widget.createBatchOp` refresh automatically, and the wallet menu reads them itself when it opens and every 10 seconds while it stays open; call this to show a tx sent via an External wallet client (outside the widget's execution path) before the next scheduled read. |
132
132
  | `getAuthToken` | `() => Promise<string>` | no | no | A short-lived (5 min) Auth token, a Fluent-signed JWT for the connected person. Verify it on your backend against `<iss>/.well-known/jwks.json` (ES256), checking `iss`, `aud` (= your appId) and `exp`; `sub` is stable per person per App. Reused until `authTokenRenewalOffsetSeconds` before `exp`, then renewed; a renewal the service accepts asks the wallet for nothing. When the wallet is asked to sign: [guides/backend-auth.md](guides/backend-auth.md#renewal). External wallets: EOAs and deployed smart-contract wallets sign in; a not-yet-deployed smart account cannot (no ERC-6492). **Throws** `FluentAuthError`, its `code` one of: - `not_connected`: no Widget account is connected, or an External wallet has no client when the call has to sign the Sign-in challenge; - `login_credential_missing`: a Fluent ID's login left no credential in the page; - `origin_mismatch`: the Sign-in challenge names an origin other than the page's; - `request_failed`: the request did not reach the service, its answer carried no code or no token, or the External wallet refused to sign the Sign-in challenge; - `service_refused`: the service refused with a code this SDK does not name; - a code the service answered with: `unknown_app`, `app_not_auth_enabled`, `origin_not_allowed`, `origin_missing`, `bad_request`, `challenge_unknown`, `challenge_used`, `challenge_expired`, `app_mismatch`, `invalid_signature`, `signature_prefix_rejected`, `address_already_linked`, `invalid_login_credential`, `no_signer`, `rate_limited` or `internal`. A refused refresh credential is not among them: the call forgets it and signs in again within the same call, which can prompt the External wallet. Keep a `default` branch. |
133
133
  | `linkX` | `() => Promise<FluentLinkXResult>` | no | no | Link an X account to the connected person, headless: no widget screen, no settings page, one call. Idempotent and re-enterable, because linking X needs an OAuth round trip that leaves the page. A person who already has X resolves `{ status: "linked", x }` without leaving the page. A person who has none resolves `{ status: "redirecting" }` once the navigation to X has started: the page is unloading, so nothing on it may wait for the link to finish. When the browser comes back, `useLinkX()` calls `linkX()` again on mount, and it resolves `linked`; nothing public tells a page that calls `linkX()` itself that it is a return from X. A link somebody else started in this tab, or a stale record of one, is discarded rather than resumed: the call does no work and rejects with `link_failed`; call again to start one for the signed-in person. An External wallet can be asked to sign before either result: [guides/link-x.md](guides/link-x.md) says when. **Throws** `FluentAuthError`, whose codes today are `user_rejected`, `linked_to_another_user`, `not_authenticated`, `bad_request` and `link_failed`; keep a `default` branch for any code a later release adds. |
134
134
 
@@ -104,6 +104,13 @@ paymaster's two are a `FluentFixedPaymasterGas` (`paymasterVerificationGasLimit`
104
104
  `paymasterPostOpGasLimit`): pass both, or neither to use the limits the paymaster authorizes
105
105
  ([api.md](api.md#fluentfixedaccountgas), [api.md](api.md#fluentfixedpaymastergas)).
106
106
 
107
+ For a Gas token payment, whatever the policy, the widget asks the paymaster for a
108
+ `paymasterPostOpGasLimit` of at least 50 000 gas: the paymaster charges the Gas token after
109
+ the operation, and ZeroDev refuses to authorize a USDnr payment whose request leaves that limit
110
+ at 0 or out. A larger limit, fixed or estimated, is asked for as it is. A `skipEstimation` policy
111
+ that fixes `paymasterPostOpGasLimit` below 50 000 for a Gas token payment therefore rejects with
112
+ `paymaster_gas_mismatch` before anything is signed.
113
+
107
114
  - **Default**: omitted, the widget estimates every limit. Omitting it is the recommended
108
115
  setting.
109
116
  - **When to use it**: a buffer when an operation's estimate runs short; fixed limits when the
@@ -317,6 +317,28 @@ export function Root() {
317
317
  When the widget refuses its `config`, the error's message names the option and how to fix it,
318
318
  and its `code` is listed in [errors.md](errors.md#fluentwidgetconfigerror).
319
319
 
320
+ ## Network access
321
+
322
+ The widget reaches the hosts below from the page, each for the feature in the first column. A
323
+ `Content-Security-Policy` that restricts `connect-src` has to allow the ones for your Network;
324
+ a host it blocks costs that feature and nothing else, without a configuration error: USD prices
325
+ stay empty, history does not load, Sponsorship is refused.
326
+
327
+ | For | `testnet` | `mainnet` |
328
+ | --- | --- | --- |
329
+ | Fluent Connect service: Auth tokens, User settings, Link X, Sponsorship, analytics | `api.fluent-connect.dev.gblend.xyz`, `sponsorship.fluent-connect.dev.gblend.xyz` | `api.fluent.xyz` |
330
+ | Fluent RPC: balances, fees, receipts | `rpc.testnet.fluent.xyz` | `rpc.fluent.xyz` |
331
+ | Bundler and paymaster (ZeroDev) | `rpc.zerodev.app` | `rpc.zerodev.app` |
332
+ | USD prices: Coinbase and CoinGecko first, DefiLlama for what they leave unanswered | `api.coinbase.com`, `api.coingecko.com`, `coins.llama.fi` | the same three |
333
+ | Transaction history (the explorer's API) | `testnet.fluentscan.xyz` | `fluentscan.xyz` |
334
+ | Bridge: the Ethereum RPC, the deposit indexer, the Hyperlane explorer | `ethereum-sepolia-rpc.publicnode.com`, `api.gblend.xyz`, `api.hyperlane.xyz` | `ethereum-rpc.publicnode.com`, `eth.llamarpc.com`, `eth.drpc.org`, `api.fluent.xyz`, `api.hyperlane.xyz` |
335
+ | Pre-funding a new Fluent ID (faucet) | `eco-faucet-api.fluent.xyz` | not used |
336
+
337
+ The SDKs the widget embeds reach their own hosts, and their documentation is the list to
338
+ follow for those: Privy for Direct login (`auth.privy.io`), Reown AppKit for External wallets
339
+ (`relay.walletconnect.org` and `rpc.walletconnect.org` among others), and the Swapper deposit
340
+ page, which is an iframe from `deposit.swapper.finance` and so needs `frame-src` as well.
341
+
320
342
  ## Checklist
321
343
 
322
344
  - `appId` and `privyClientId` from Fluent, and every page origin allow-listed for Direct login.
@@ -330,6 +352,7 @@ and its `code` is listed in [errors.md](errors.md#fluentwidgetconfigerror).
330
352
  - `useFluentWidget()` called only inside the content `renderPage` or `renderHome` returns.
331
353
  - UI branched on `status`, with a `default` branch.
332
354
  - `debugLogging` off in production.
355
+ - Under a `Content-Security-Policy`, the hosts in [Network access](#network-access) allowed.
333
356
 
334
357
  Next: send a Batch operation ([guides/transactions.md](guides/transactions.md)), request a
335
358
  signature ([guides/signing.md](guides/signing.md)), or verify the person on your backend
@@ -55,20 +55,161 @@ export function App() {
55
55
  }
56
56
  ```
57
57
 
58
- ## What the embedded page sends
58
+ ## Set up the embedded page
59
59
 
60
- The embedded page speaks JSON-RPC 2.0 over `postMessage`, the protocol of
61
- `@ledgerhq/iframe-provider`: it posts a request to `window.parent`, and the bridge posts the
62
- reply back with the same `id`, holding `result` or `error`. Events carry no `id`. A message
63
- without an `id` gets no reply.
60
+ The embedded page needs no library: the bridge speaks JSON-RPC 2.0 over `postMessage`, and this
61
+ wire format is what the bridge guarantees. The page posts each request to `window.parent`, and
62
+ the bridge posts the reply to the page's window with the same `id`.
63
+
64
+ A request is an object with `jsonrpc: "2.0"`, a string `method`, an `id` and, when the method
65
+ takes any, positional `params` in a list:
64
66
 
65
67
  ```json
66
68
  { "jsonrpc": "2.0", "id": 1, "method": "eth_requestAccounts", "params": [] }
67
69
  ```
68
70
 
69
- Before its first reply the bridge posts `chainChanged` with the Network's chain id and
70
- `accountsChanged` with the connected Widget account. After that, connecting and disconnecting
71
- reach the iframe as `accountsChanged` (an empty list on disconnect).
71
+ - The `id` is a number or a string, and the reply carries it back as it was sent. A message with
72
+ no `id`, or with `id: null`, gets no reply and runs nothing.
73
+ - A message that is not an object with `jsonrpc: "2.0"` and a string `method` is ignored.
74
+ - `params` that is not a list is refused with `-32602`.
75
+ - The method `enable` is answered as `eth_accounts` is, for clients that send it.
76
+ - The bridge sets no time limit: a request waiting on a Review is answered when the person
77
+ decides, however long that takes.
78
+
79
+ A reply that succeeds holds `result`:
80
+
81
+ ```json
82
+ { "jsonrpc": "2.0", "id": 1, "result": ["0x52908400098527886E0F7030069857D2E4169EE7"] }
83
+ ```
84
+
85
+ A reply that fails holds `error`, its `code` one of
86
+ [the codes below](#errors-the-embedded-page-receives):
87
+
88
+ ```json
89
+ {
90
+ "jsonrpc": "2.0",
91
+ "id": 2,
92
+ "error": { "code": 4100, "message": "eth_sendTransaction: no account is signed in" }
93
+ }
94
+ ```
95
+
96
+ The bridge posts every reply and event with the target origin `allowedOrigin`, so the browser
97
+ delivers them only while the iframe shows a page of that origin. The page posts its requests
98
+ with the App's origin as the target origin, not `"*"`, so that they reach no other page in the
99
+ parent window, and its `message` listener checks `event.source` and `event.origin` the same way:
100
+
101
+ ```ts
102
+ /** The origin of the App that embeds this page. */
103
+ const APP_ORIGIN = "https://app.example";
104
+
105
+ /** The `error` of a failed reply. */
106
+ export class RpcError extends Error {
107
+ constructor(
108
+ readonly code: number,
109
+ message: string,
110
+ ) {
111
+ super(message);
112
+ }
113
+ }
114
+
115
+ type Message = {
116
+ jsonrpc?: string;
117
+ id?: number;
118
+ method?: string;
119
+ params?: unknown[];
120
+ result?: unknown;
121
+ error?: { code: number; message: string };
122
+ };
123
+
124
+ /** What the page knows of the App's side, kept up to date by the bridge's events. */
125
+ export const app: { account?: string; chainId?: number } = {};
126
+
127
+ type Waiting = { resolve: (result: unknown) => void; reject: (error: Error) => void };
128
+ const waiting = new Map<number, Waiting>();
129
+ let nextId = 1;
130
+
131
+ window.addEventListener("message", (event: MessageEvent) => {
132
+ if (event.source !== window.parent || event.origin !== APP_ORIGIN) return;
133
+ const message = event.data as Message;
134
+ if (message?.jsonrpc !== "2.0") return;
135
+ if (message.method === "accountsChanged") {
136
+ // An empty list when no Widget account is signed in.
137
+ app.account = (message.params?.[0] as string[])[0];
138
+ } else if (message.method === "chainChanged") {
139
+ // Hex, such as "0x5202" for 20994.
140
+ app.chainId = Number(message.params?.[0]);
141
+ } else if (message.id !== undefined) {
142
+ const request = waiting.get(message.id);
143
+ waiting.delete(message.id);
144
+ if (message.error) request?.reject(new RpcError(message.error.code, message.error.message));
145
+ else request?.resolve(message.result);
146
+ }
147
+ });
148
+
149
+ export function request(method: string, params: unknown[] = []): Promise<unknown> {
150
+ const id = nextId++;
151
+ return new Promise((resolve, reject) => {
152
+ waiting.set(id, { resolve, reject });
153
+ window.parent.postMessage({ jsonrpc: "2.0", id, method, params }, APP_ORIGIN);
154
+ });
155
+ }
156
+
157
+ /** Sends `value` wei, written as hex, to `to`; `undefined` when nobody is signed in. */
158
+ export async function pay(to: string, value: string): Promise<string | undefined> {
159
+ const [from] = (await request("eth_requestAccounts")) as string[];
160
+ if (!from) return undefined;
161
+ try {
162
+ return (await request("eth_sendTransaction", [{ from, to, value }])) as string;
163
+ } catch (error) {
164
+ // 4001: the person dismissed the Review.
165
+ if (error instanceof RpcError && error.code === 4001) return undefined;
166
+ throw error;
167
+ }
168
+ }
169
+ ```
170
+
171
+ ### Events
172
+
173
+ The bridge posts two events, which carry no `id`. `chainChanged` holds the chain id of the
174
+ Network as unpadded hex, `"0x5202"` on testnet (20994) and `"0x6313"` on mainnet (25363):
175
+
176
+ ```json
177
+ { "jsonrpc": "2.0", "method": "chainChanged", "params": ["0x5202"] }
178
+ ```
179
+
180
+ `accountsChanged` holds one parameter, the list of accounts, so its `params` is a list holding
181
+ that list: the address of the Widget account, or an empty list when `widget.account.address` is
182
+ empty.
183
+
184
+ ```json
185
+ {
186
+ "jsonrpc": "2.0",
187
+ "method": "accountsChanged",
188
+ "params": [["0x52908400098527886E0F7030069857D2E4169EE7"]]
189
+ }
190
+ ```
191
+
192
+ When the component that calls `useFluentIframeBridge` mounts, the bridge posts `chainChanged`
193
+ and then `accountsChanged`. After that, it posts `accountsChanged` each time
194
+ `widget.account.address` changes, as on sign-in and on sign-out (an empty list). When the
195
+ Network's chain or `allowedOrigin` changes, the hook replaces the bridge with a new one, which
196
+ posts `chainChanged` again but not `accountsChanged`. Once the component unmounts, the bridge
197
+ posts no more events.
198
+
199
+ Events the bridge posts before the embedded page has added its `message` listener are lost, and
200
+ the events of the mount can be among them. So the bridge posts `chainChanged` and
201
+ `accountsChanged` again ahead of its reply to the page's first request, whether that request
202
+ succeeds or fails. It does this once for each bridge.
203
+
204
+ ### A ready-made client
205
+
206
+ `@ledgerhq/iframe-provider` speaks this protocol, and its `IFrameEthereumProvider` can stand in
207
+ for the code above. The package is archived: its last release is 0.4.3, from January 2023, and
208
+ its repository takes no more changes. The wire format above is what the bridge keeps working;
209
+ the package is one client of it. Two of its defaults differ from the example: it posts with the
210
+ target origin `"*"` unless it is built with `new IFrameEthereumProvider({ targetOrigin })`, and
211
+ it rejects a request with no reply within 240 seconds, while the bridge may still answer it
212
+ later, for example once the person confirms a Review left open that long.
72
213
 
73
214
  ## What the bridge answers
74
215
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fluent.xyz/connect",
3
- "version": "0.6.1",
3
+ "version": "0.6.2-rc.1",
4
4
  "description": "Fluent Connect React widget \u2014 Privy login, ZeroDev smart account, batch operations, and wallet UI",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",