@fluent.xyz/connect 0.4.2 → 0.5.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/dist/index.js CHANGED
@@ -1,24 +1,26 @@
1
1
  import './polyfills/buffer.js';
2
- import { parseAbi, toEventSelector, parseAbiItem, parseEther, defineChain, http, createPublicClient, formatUnits, isAddress, getAddress, parseUnits, BaseError, encodeFunctionData, zeroAddress, numberToHex, hexToBigInt, isHex, toHex, fallback, stringToHex, bytesToHex, HttpRequestError, erc20Abi, padHex, decodeEventLog } from 'viem';
2
+ import { parseAbi, toEventSelector, parseAbiItem, parseEther, defineChain, http, createPublicClient, formatUnits, isAddress, getAddress, parseUnits, BaseError, encodeFunctionData, zeroAddress, numberToHex, hexToBigInt, isHex, toHex, fallback, stringToHex, bytesToHex, HttpRequestError, decodeEventLog, erc20Abi, padHex } from 'viem';
3
3
  import * as React from 'react';
4
4
  import { createContext, forwardRef, useContext, useMemo, useState, useEffect, useCallback, useRef, useLayoutEffect, Fragment as Fragment$1 } from 'react';
5
5
  import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
6
- import { estimateUserOperationGas } from 'viem/account-abstraction';
6
+ import { estimateUserOperationGas, WaitForUserOperationReceiptTimeoutError, getPaymasterData, getPaymasterStubData } from 'viem/account-abstraction';
7
7
  import { toCallPolicy, CallPolicyVersion, toTimestampPolicy, CallType, ParamCondition } from '@zerodev/permissions/policies';
8
8
  export { CallType, ParamCondition } from '@zerodev/permissions/policies';
9
9
  import { privateKeyToAccount, toAccount, generatePrivateKey } from 'viem/accounts';
10
- import { usePrivy, useSignMessage, useSignTypedData, useWallets, PrivyProvider, useIdentityToken, useUser, useLinkAccount, useLoginWithSiwe, useModalStatus, useCreateWallet, useLoginWithEmail, useLoginWithOAuth, useLoginWithPasskey, Captcha } from '@privy-io/react-auth';
10
+ import * as web from '@privy-io/react-auth';
11
11
  import { signerToEcdsaValidator } from '@zerodev/ecdsa-validator';
12
12
  import { toPermissionValidator, serializePermissionAccount, deserializePermissionAccount } from '@zerodev/permissions';
13
13
  import { toECDSASigner } from '@zerodev/permissions/signers';
14
14
  import { createZeroDevPaymasterClient, getERC20PaymasterApproveCall, createKernelAccountClient, createKernelAccount } from '@zerodev/sdk';
15
15
  import { getEntryPoint, KERNEL_V3_3 } from '@zerodev/sdk/constants';
16
+ import { getUserOperationGasPrice } from '@zerodev/sdk/actions';
17
+ import { getBlockNumber, getLogs, getTransactionReceipt } from 'viem/actions';
16
18
  import { Toast as Toast$1 } from '@base-ui/react/toast';
17
19
  import { clsx } from 'clsx';
18
20
  import { twMerge } from 'tailwind-merge';
19
21
  import { Button as Button$1 } from '@base-ui/react/button';
20
22
  import { cva } from 'class-variance-authority';
21
- import { XIcon, RefreshCw, X, ChevronLeft, ExternalLink, Copy, Settings, LogOut, Loader2, ChevronDownIcon, CheckIcon, AlertTriangle, Layers, Trash2, Plus, Loader2Icon, ChevronUpIcon, CircleHelp, Wallet, ChevronRight, Check, LogIn, Send, RotateCw, KeyRound, Mail, CircleCheckIcon, InfoIcon, TriangleAlertIcon, OctagonXIcon } from 'lucide-react';
23
+ import { XIcon, Trash2, RefreshCw, X, ChevronLeft, ExternalLink, Copy, Settings, LogOut, Loader2, ChevronDownIcon, CheckIcon, AlertTriangle, Layers, Plus, Loader2Icon, ChevronUpIcon, CircleHelp, LogIn, Send, RotateCw, KeyRound, Mail, Wallet, Check, CircleCheckIcon, InfoIcon, TriangleAlertIcon, OctagonXIcon } from 'lucide-react';
22
24
  import { WagmiAdapter } from '@reown/appkit-adapter-wagmi';
23
25
  import { createAppKit, useAppKit } from '@reown/appkit/react';
24
26
  import { QueryClient, QueryClientContext, QueryClientProvider, useInfiniteQuery, useQuery } from '@tanstack/react-query';
@@ -5000,7 +5002,6 @@ function createFluentFamiliesClient(config) {
5000
5002
  }
5001
5003
 
5002
5004
  // ../connect-sdk/src/index.ts
5003
- var DEFAULT_AUTHORIZE_URL = "https://connect-preview.vercel.app/authorize";
5004
5005
  var DEFAULT_SCOPES = ["openid", "profile", "wallet", "faucet"];
5005
5006
  var INSTALLATION_ID_KEY = "fluent:connect:installation-id:v1";
5006
5007
  var SESSION_KEY = "fluent:connect:session:v1";
@@ -5011,13 +5012,6 @@ function getBrowserOrigin() {
5011
5012
  }
5012
5013
  return browserWindow.location.origin;
5013
5014
  }
5014
- function getBrowserRedirectUri() {
5015
- const browserWindow = globalThis.window;
5016
- if (!browserWindow?.location?.origin) {
5017
- throw new Error("redirectUri is required outside a browser");
5018
- }
5019
- return `${browserWindow.location.origin}${browserWindow.location.pathname ?? "/"}`;
5020
- }
5021
5015
  function getBrowserStorage() {
5022
5016
  return globalThis.window?.localStorage;
5023
5017
  }
@@ -5037,9 +5031,6 @@ function getOrCreateInstallationId(storage) {
5037
5031
  storage?.setItem(INSTALLATION_ID_KEY, next);
5038
5032
  return next;
5039
5033
  }
5040
- function withoutTrailingSlash3(value) {
5041
- return value.replace(/\/+$/, "");
5042
- }
5043
5034
  var FluentConnectSDK = class {
5044
5035
  config;
5045
5036
  app;
@@ -5050,12 +5041,10 @@ var FluentConnectSDK = class {
5050
5041
  const installationId = getOrCreateInstallationId(storage);
5051
5042
  this.config = {
5052
5043
  ...config,
5053
- authorizeUrl: config.authorizeUrl ?? DEFAULT_AUTHORIZE_URL,
5054
5044
  scopes: config.scopes ?? DEFAULT_SCOPES,
5055
5045
  source: config.source ?? "fluent_connect_sdk",
5056
5046
  storage,
5057
- origin,
5058
- redirectUri: config.redirectUri ?? getBrowserRedirectUri()
5047
+ origin
5059
5048
  };
5060
5049
  this.app = {
5061
5050
  mode: config.clientId ? "registered" : "origin",
@@ -5074,27 +5063,6 @@ var FluentConnectSDK = class {
5074
5063
  session: this.session
5075
5064
  };
5076
5065
  }
5077
- buildAuthorizeUrl(state = randomId()) {
5078
- const url = new URL(withoutTrailingSlash3(this.config.authorizeUrl), this.app.origin);
5079
- url.searchParams.set("origin", this.app.origin);
5080
- url.searchParams.set("installation_id", this.app.installationId);
5081
- url.searchParams.set("redirect_uri", this.config.redirectUri ?? this.app.origin);
5082
- url.searchParams.set("scope", this.config.scopes.join(" "));
5083
- url.searchParams.set("state", state);
5084
- url.searchParams.set("network", this.config.network);
5085
- url.searchParams.set("source", this.config.source);
5086
- if (this.app.clientId) url.searchParams.set("client_id", this.app.clientId);
5087
- if (this.app.appName) url.searchParams.set("app_name", this.app.appName);
5088
- if (this.config.campaign) url.searchParams.set("campaign", this.config.campaign);
5089
- return url;
5090
- }
5091
- connect(options = {}) {
5092
- const url = this.buildAuthorizeUrl(options.state);
5093
- const browserWindow = globalThis.window;
5094
- const opener = options.popup ?? (browserWindow?.open ? browserWindow.open.bind(browserWindow) : void 0);
5095
- opener?.(url, "fluent-connect", "popup,width=460,height=680");
5096
- return url;
5097
- }
5098
5066
  setSession(session) {
5099
5067
  const nextSession = {
5100
5068
  ...session,
@@ -5310,6 +5278,9 @@ function getFluentChainForNetwork(network) {
5310
5278
  return fluentTestnet;
5311
5279
  }
5312
5280
  }
5281
+ function getFluentWidgetNetworkForChainId(chainId) {
5282
+ return chainId === fluentMainnet.id ? "mainnet" : "testnet";
5283
+ }
5313
5284
  function getFluentTokenDefaults(network) {
5314
5285
  return getFluentTokenDefaultsForNetwork(network);
5315
5286
  }
@@ -5326,20 +5297,24 @@ var FLUENT_WIDGET_REFRESH_CREDENTIAL_STORAGE_PREFIX = "fluent:widget:refresh:v1"
5326
5297
  // src/core/config.ts
5327
5298
  var FLUENT_CONNECT_PRIVY_APP_ID = "cmi7li7v901yojv0dmtfuf0v4";
5328
5299
  var FLUENT_CONNECT_REOWN_PROJECT_ID = "fbf7578f67b4a34e5101051131829ac0";
5329
- var FLUENT_CONNECT_ZERODEV_PROJECT_ID = "893acc63-da39-4b57-8789-5784ed7f1969";
5300
+ var FLUENT_CONNECT_TESTNET_ZERODEV_PROJECT_ID = "893acc63-da39-4b57-8789-5784ed7f1969";
5301
+ var FLUENT_CONNECT_MAINNET_ZERODEV_PROJECT_ID = "216ca7d9-2b97-4894-ac23-7aa6a287dd97";
5330
5302
  var FLUENT_CONNECT_POSTHOG_TOKEN = "phc_xr3QqFLEnKbDvmD5qsKvXuyaAdSkSKvcFGUH5VeDTLGD";
5331
5303
  var FLUENT_CONNECT_TESTNET_PUBLIC_API_URL = "https://api.fluent-connect.dev.gblend.xyz/api/v1";
5332
- var FLUENT_CONNECT_MAINNET_PUBLIC_API_URL = "https://fluent-connect.api.fluent.xyz/api/v1";
5304
+ var FLUENT_CONNECT_MAINNET_PUBLIC_API_URL = "https://api.fluent.xyz/connect/v1";
5333
5305
  var FLUENT_CONNECT_TESTNET_ANALYTICS_HOST = "https://api.fluent-connect.dev.gblend.xyz/ingest";
5334
- var FLUENT_CONNECT_MAINNET_ANALYTICS_HOST = "";
5306
+ var FLUENT_CONNECT_MAINNET_ANALYTICS_HOST = "https://api.fluent.xyz/connect/v1/ingest";
5335
5307
  var FLUENT_CONNECT_TESTNET_SPONSORSHIP_URL = "https://sponsorship.fluent-connect.dev.gblend.xyz";
5336
- var FLUENT_CONNECT_MAINNET_SPONSORSHIP_URL = "";
5308
+ var FLUENT_CONNECT_MAINNET_SPONSORSHIP_URL = "https://api.fluent.xyz/connect/v1";
5337
5309
  var FLUENT_CONNECT_TESTNET_REPUTATION_SIGNUP_URL = "https://connect-preview.vercel.app/signin";
5338
5310
  var FLUENT_CONNECT_MAINNET_REPUTATION_SIGNUP_URL = "https://connect.fluent.xyz/signin";
5339
- var FLUENT_CONNECT_TESTNET_AUTHORIZE_URL = "https://connect-preview.vercel.app/authorize";
5340
- var FLUENT_CONNECT_MAINNET_AUTHORIZE_URL = "https://connect.fluent.xyz/authorize";
5341
5311
  var FLUENT_CONNECT_TESTNET_FAUCET_ENDPOINT = "https://eco-faucet-api.fluent.xyz/fluent-connect/pre-fund";
5342
5312
  var FLUENT_CONNECT_DEFAULT_SILENT_SIGNING = true;
5313
+ var FLUENT_CONNECT_DEFAULT_EXECUTION = {
5314
+ feeSource: "chain",
5315
+ receiptSource: "chain",
5316
+ chainCheckBeforeSign: false
5317
+ };
5343
5318
  var FLUENT_CONNECT_DEFAULT_PORTAL_BRIDGE_URL = "https://portal.fluent.xyz/user/bridge";
5344
5319
  var FLUENT_CONNECT_DEFAULT_SWAPPER_CONFIG = {
5345
5320
  enabled: true,
@@ -5349,7 +5324,6 @@ var FLUENT_CONNECT_DEFAULT_SWAPPER_CONFIG = {
5349
5324
  };
5350
5325
  var FLUENT_CONNECT_NETWORK_ENDPOINTS = {
5351
5326
  testnet: {
5352
- authorizeUrl: FLUENT_CONNECT_TESTNET_AUTHORIZE_URL,
5353
5327
  publicApiUrl: FLUENT_CONNECT_TESTNET_PUBLIC_API_URL,
5354
5328
  reputationSignupUrl: FLUENT_CONNECT_TESTNET_REPUTATION_SIGNUP_URL,
5355
5329
  faucetEndpoint: FLUENT_CONNECT_TESTNET_FAUCET_ENDPOINT,
@@ -5358,7 +5332,6 @@ var FLUENT_CONNECT_NETWORK_ENDPOINTS = {
5358
5332
  sponsorshipUrl: FLUENT_CONNECT_TESTNET_SPONSORSHIP_URL
5359
5333
  },
5360
5334
  mainnet: {
5361
- authorizeUrl: FLUENT_CONNECT_MAINNET_AUTHORIZE_URL,
5362
5335
  publicApiUrl: FLUENT_CONNECT_MAINNET_PUBLIC_API_URL,
5363
5336
  reputationSignupUrl: FLUENT_CONNECT_MAINNET_REPUTATION_SIGNUP_URL,
5364
5337
  // Mainnet has no faucet.
@@ -5371,6 +5344,13 @@ var FLUENT_CONNECT_NETWORK_ENDPOINTS = {
5371
5344
  function getFluentWidgetNetworkEndpoints(network) {
5372
5345
  return FLUENT_CONNECT_NETWORK_ENDPOINTS[network];
5373
5346
  }
5347
+ var FLUENT_CONNECT_ZERODEV_PROJECT_IDS = {
5348
+ testnet: FLUENT_CONNECT_TESTNET_ZERODEV_PROJECT_ID,
5349
+ mainnet: FLUENT_CONNECT_MAINNET_ZERODEV_PROJECT_ID
5350
+ };
5351
+ function getFluentZeroDevProjectId(network) {
5352
+ return FLUENT_CONNECT_ZERODEV_PROJECT_IDS[network];
5353
+ }
5374
5354
  var FLUENT_CONNECT_DEFAULT_ASSETS = {
5375
5355
  fluentLogo: FLUENT_CONNECT_BUNDLED_ASSETS.fluentLogo,
5376
5356
  walletConnectIcon: FLUENT_CONNECT_BUNDLED_ASSETS.walletConnectIcon,
@@ -5409,10 +5389,10 @@ var FLUENT_CONNECT_PRIVY_CONFIG = {
5409
5389
  *
5410
5390
  * Privy resolves this once when `PrivyProvider` mounts and does not pick up a
5411
5391
  * later change to the `config` prop — which is why Quick sign used to key that
5412
- * provider and rebuild everything below it. A signer that wants Privy's
5413
- * confirmation screen asks for it per call instead (`uiOptions.showWalletUIs`,
5414
- * which wins over this), so the provider never has to be rebuilt to change
5415
- * its mind.
5392
+ * provider and rebuild everything below it. Neither signer mode shows Privy's
5393
+ * confirmation screen: Prompt mode is confirmed in the widget's own review,
5394
+ * and its signer still names `uiOptions.showWalletUIs: false` per call, which
5395
+ * wins over this.
5416
5396
  */
5417
5397
  embeddedWallets: {
5418
5398
  createOnLogin: "users-without-wallets",
@@ -5507,6 +5487,14 @@ function resolveFluentWidgetAuthMethods(enabledAuthMethods) {
5507
5487
  }
5508
5488
  return [...enabled];
5509
5489
  }
5490
+ var FluentWidgetConfigError = class extends Error {
5491
+ code;
5492
+ constructor(code, message2) {
5493
+ super(message2);
5494
+ this.name = "FluentWidgetConfigError";
5495
+ this.code = code;
5496
+ }
5497
+ };
5510
5498
  var APP_ID_PATTERN = /^app_[0-9a-f]{32}$/;
5511
5499
  var APP_ID_HINT = "Pass the app_<32 hex> id from the Fluent Dashboard as appId.";
5512
5500
  function resolveCustomOAuthRedirectUrl(value) {
@@ -5526,7 +5514,82 @@ function resolveCustomOAuthRedirectUrl(value) {
5526
5514
  }
5527
5515
  return redirectUrl;
5528
5516
  }
5517
+ function resolveQuickSignWhitelist(addresses) {
5518
+ if (addresses === void 0) return void 0;
5519
+ const resolved = /* @__PURE__ */ new Set();
5520
+ for (const value of addresses) {
5521
+ const address = typeof value === "string" ? value.trim() : "";
5522
+ if (!isAddress(address, { strict: false })) {
5523
+ throw new Error(
5524
+ `FluentWidgetConfig.quickSign.whitelistAddresses contains "${String(value)}", which is not an address. Pass 0x-prefixed 20-byte addresses.`
5525
+ );
5526
+ }
5527
+ resolved.add(address.toLowerCase());
5528
+ }
5529
+ return [...resolved];
5530
+ }
5531
+ var EXECUTION_SOURCES = ["chain", "bundler"];
5532
+ function resolveFluentWidgetExecution(execution) {
5533
+ return {
5534
+ feeSource: resolveExecutionSource(
5535
+ execution?.feeSource,
5536
+ "feeSource",
5537
+ "invalid_fee_source",
5538
+ FLUENT_CONNECT_DEFAULT_EXECUTION.feeSource
5539
+ ),
5540
+ receiptSource: resolveExecutionSource(
5541
+ execution?.receiptSource,
5542
+ "receiptSource",
5543
+ "invalid_receipt_source",
5544
+ FLUENT_CONNECT_DEFAULT_EXECUTION.receiptSource
5545
+ ),
5546
+ chainCheckBeforeSign: resolveChainCheckBeforeSign(execution?.chainCheckBeforeSign)
5547
+ };
5548
+ }
5549
+ function resolveExecutionSource(value, field, code, fallback2) {
5550
+ if (value === void 0) return fallback2;
5551
+ if (value === "chain" || value === "bundler") return value;
5552
+ throw new FluentWidgetConfigError(
5553
+ code,
5554
+ `FluentWidgetConfig.execution.${field} ${describeRejectedValue(value)} is not supported. Pass one of ${EXECUTION_SOURCES.map((source) => JSON.stringify(source)).join(" or ")}.`
5555
+ );
5556
+ }
5557
+ function resolveChainCheckBeforeSign(value) {
5558
+ if (value === void 0) return FLUENT_CONNECT_DEFAULT_EXECUTION.chainCheckBeforeSign;
5559
+ if (typeof value === "boolean") return value;
5560
+ throw new FluentWidgetConfigError(
5561
+ "invalid_chain_check_before_sign",
5562
+ `FluentWidgetConfig.execution.chainCheckBeforeSign ${describeRejectedValue(value)} is not a boolean. Pass true to read the Signer's chain before every signature, or false.`
5563
+ );
5564
+ }
5565
+ function describeRejectedValue(value) {
5566
+ if (typeof value === "string") return JSON.stringify(value);
5567
+ if (value === null) return "null";
5568
+ try {
5569
+ return `${typeof value} ${String(value)}`;
5570
+ } catch {
5571
+ return typeof value;
5572
+ }
5573
+ }
5574
+ var legacyAuthModeWarned = false;
5575
+ function checkRemovedAuthMode(config) {
5576
+ const authMode = config.authMode;
5577
+ if (authMode === void 0) return;
5578
+ if (authMode === "direct") {
5579
+ if (!legacyAuthModeWarned) {
5580
+ legacyAuthModeWarned = true;
5581
+ console.warn(
5582
+ 'FluentWidgetConfig.authMode was removed in 0.5.0 and is ignored. Delete the key: Direct login \u2014 what authMode: "direct" asked for \u2014 is now the only login.'
5583
+ );
5584
+ }
5585
+ return;
5586
+ }
5587
+ throw new Error(
5588
+ `FluentWidgetConfig.authMode: ${JSON.stringify(authMode)} is not supported \u2014 hosted mode was removed in 0.5.0. Delete the authMode key: every user now signs in with Direct login, which needs this App's origin registered on the Privy app client behind privyClientId.`
5589
+ );
5590
+ }
5529
5591
  function resolveFluentWidgetConfig(config) {
5592
+ checkRemovedAuthMode(config);
5530
5593
  if (config.clientId !== void 0) {
5531
5594
  throw new Error(
5532
5595
  `FluentWidgetConfig.clientId was removed in 0.2.0. ${APP_ID_HINT} Pass the Privy app client as privyClientId \u2014 both are required.`
@@ -5572,10 +5635,8 @@ function resolveFluentWidgetConfig(config) {
5572
5635
  appName: config.appName ?? "Fluent Connect Demo",
5573
5636
  appId,
5574
5637
  privyClientId,
5575
- authMode: config.authMode ?? "hosted",
5576
5638
  customOAuthRedirectUrl: resolveCustomOAuthRedirectUrl(config.customOAuthRedirectUrl),
5577
5639
  authMethods: resolveFluentWidgetAuthMethods(config.enabledAuthMethods),
5578
- authorizeUrl: endpoints.authorizeUrl,
5579
5640
  faucetEndpoint: endpoints.faucetEndpoint,
5580
5641
  eventsEndpoint: "",
5581
5642
  analyticsHost: endpoints.analyticsHost,
@@ -5597,6 +5658,10 @@ function resolveFluentWidgetConfig(config) {
5597
5658
  sponsorship: config.gasPayment?.sponsorship ?? "auto",
5598
5659
  ethValueByToken: config.gasPayment?.ethValueByToken
5599
5660
  },
5661
+ execution: resolveFluentWidgetExecution(config.execution),
5662
+ quickSign: {
5663
+ whitelistAddresses: resolveQuickSignWhitelist(config.quickSign?.whitelistAddresses)
5664
+ },
5600
5665
  reputationEnabled: config.reputationEnabled ?? true,
5601
5666
  scopes: config.scopes ?? getFluentWidgetDefaultScopes(network),
5602
5667
  source: config.source ?? "fluent_connect_widget",
@@ -5617,7 +5682,6 @@ function createFluentConnectForWidget(config) {
5617
5682
  network: resolved.network,
5618
5683
  appName: resolved.appName,
5619
5684
  clientId: resolved.privyClientId,
5620
- authorizeUrl: resolved.authorizeUrl,
5621
5685
  scopes: resolved.scopes,
5622
5686
  source: resolved.source,
5623
5687
  campaign: resolved.campaign
@@ -5666,9 +5730,6 @@ var debugLoggingEnabled = false;
5666
5730
  function setDebugLogging(enabled) {
5667
5731
  debugLoggingEnabled = enabled;
5668
5732
  }
5669
- function isDebugLoggingEnabled() {
5670
- return debugLoggingEnabled;
5671
- }
5672
5733
  function debugLog(...args) {
5673
5734
  if (debugLoggingEnabled) console.log(...args);
5674
5735
  }
@@ -6355,7 +6416,6 @@ var LINK_X_ERROR_CODES = /* @__PURE__ */ new Set([
6355
6416
  "user_rejected",
6356
6417
  "linked_to_another_user",
6357
6418
  "not_authenticated",
6358
- "hosted_not_supported",
6359
6419
  "bad_request",
6360
6420
  "link_failed"
6361
6421
  ]);
@@ -6393,12 +6453,6 @@ function toLinkXError(err) {
6393
6453
  return new FluentAuthError("link_failed", err instanceof Error ? err.message : String(err));
6394
6454
  }
6395
6455
  async function requestLinkX(params) {
6396
- if (params.authMode === "hosted") {
6397
- throw new FluentAuthError(
6398
- "hosted_not_supported",
6399
- `linkX() needs authMode: "direct" \u2014 in hosted mode the user's Privy session lives on the authorize page, not in this page.`
6400
- );
6401
- }
6402
6456
  if (params.accountKind === "eoa") {
6403
6457
  if (!params.wallet) {
6404
6458
  throw new FluentAuthError(
@@ -6614,9 +6668,44 @@ function getSponsorshipFailure(err) {
6614
6668
  if (httpError.status === 401) return { reason: "unauthorized", disableSponsorship: false };
6615
6669
  return { reason: "unreachable", disableSponsorship: false };
6616
6670
  }
6671
+ var FluentUserOperationGasError = class extends Error {
6672
+ constructor(code, message2) {
6673
+ super(message2);
6674
+ this.code = code;
6675
+ this.name = "FluentUserOperationGasError";
6676
+ }
6677
+ code;
6678
+ };
6617
6679
  var maxCallGasLimit = (1n << 128n) - 1n;
6680
+ var maxPreVerificationGas = (1n << 256n) - 1n;
6618
6681
  function validateUserOperationGas(gas) {
6619
6682
  if (!gas) return;
6683
+ if (gas.skipEstimation !== void 0 && typeof gas.skipEstimation !== "boolean") {
6684
+ throw new FluentUserOperationGasError("invalid_policy", "skipEstimation must be a boolean");
6685
+ }
6686
+ if (gas.skipEstimation) {
6687
+ if (gas.callGasBuffer !== void 0) {
6688
+ throw new FluentUserOperationGasError(
6689
+ "invalid_policy",
6690
+ "skipEstimation cannot be combined with callGasBuffer"
6691
+ );
6692
+ }
6693
+ validateFixedLimit("callGasLimit", gas.callGasLimit);
6694
+ validateFixedLimit("verificationGasLimit", gas.verificationGasLimit);
6695
+ validateFixedLimit("preVerificationGas", gas.preVerificationGas, maxPreVerificationGas);
6696
+ if (gas.paymasterVerificationGasLimit !== void 0) {
6697
+ validateFixedLimit("paymasterVerificationGasLimit", gas.paymasterVerificationGasLimit);
6698
+ }
6699
+ if (gas.paymasterPostOpGasLimit !== void 0) {
6700
+ validateFixedLimit(
6701
+ "paymasterPostOpGasLimit",
6702
+ gas.paymasterPostOpGasLimit,
6703
+ maxCallGasLimit,
6704
+ 0n
6705
+ );
6706
+ }
6707
+ return;
6708
+ }
6620
6709
  if (gas.callGasLimit !== void 0) {
6621
6710
  if (gas.callGasBuffer !== void 0) {
6622
6711
  throw new Error("Choose callGasLimit or callGasBuffer, not both");
@@ -6638,6 +6727,7 @@ function validateUserOperationGas(gas) {
6638
6727
  function withUserOperationGas(client2, args, gas) {
6639
6728
  validateUserOperationGas(gas);
6640
6729
  if (!gas) return args;
6730
+ if (gas.skipEstimation) return withoutGasEstimation(client2, args, gas);
6641
6731
  if (gas.callGasBuffer && (gas.callGasBuffer.percentage ?? 0) === 0 && (gas.callGasBuffer.fixed ?? 0n) === 0n) {
6642
6732
  return args;
6643
6733
  }
@@ -6712,8 +6802,125 @@ function withUserOperationGas(client2, args, gas) {
6712
6802
  }
6713
6803
  };
6714
6804
  }
6715
-
6716
- // src/widget/batchOperation.ts
6805
+ function validateFixedLimit(field, value, maximum = maxCallGasLimit, minimum = 1n) {
6806
+ if (typeof value !== "bigint" || value < minimum || value > maximum) {
6807
+ throw new FluentUserOperationGasError(
6808
+ "invalid_policy",
6809
+ `skipEstimation requires ${field} as a bigint between ${minimum} and ${maximum}`
6810
+ );
6811
+ }
6812
+ }
6813
+ function withoutGasEstimation(client2, args, gas) {
6814
+ const paymaster = args.paymaster ?? client2.paymaster;
6815
+ const fixedPaymasterGas = gas.paymasterVerificationGasLimit !== void 0;
6816
+ if (paymaster && fixedPaymasterGas !== (gas.paymasterPostOpGasLimit !== void 0)) {
6817
+ throw new FluentUserOperationGasError(
6818
+ "invalid_policy",
6819
+ "skipEstimation requires both paymasterVerificationGasLimit and paymasterPostOpGasLimit or neither when a paymaster is used"
6820
+ );
6821
+ }
6822
+ const providerGas = Boolean(paymaster && !fixedPaymasterGas);
6823
+ let limits = {
6824
+ callGasLimit: gas.callGasLimit,
6825
+ verificationGasLimit: gas.verificationGasLimit,
6826
+ preVerificationGas: gas.preVerificationGas,
6827
+ ...paymaster && fixedPaymasterGas ? {
6828
+ paymasterVerificationGasLimit: gas.paymasterVerificationGasLimit,
6829
+ paymasterPostOpGasLimit: gas.paymasterPostOpGasLimit
6830
+ } : {}
6831
+ };
6832
+ const adapter = paymaster === true ? {
6833
+ getPaymasterStubData: (operation) => getPaymasterStubData(client2, operation),
6834
+ getPaymasterData: (operation) => getPaymasterData(client2, operation)
6835
+ } : typeof paymaster === "object" ? paymaster : void 0;
6836
+ if (providerGas && !adapter) {
6837
+ throw new FluentUserOperationGasError(
6838
+ "invalid_policy",
6839
+ "skipEstimation needs a paymaster adapter to obtain provider gas limits"
6840
+ );
6841
+ }
6842
+ const acceptGas = (data, isFinal) => {
6843
+ if (providerGas) {
6844
+ if (isFinal) assertAuthorizedGas(data, {
6845
+ callGasLimit: gas.callGasLimit,
6846
+ verificationGasLimit: gas.verificationGasLimit
6847
+ });
6848
+ limits = readProviderGas(data, limits, gas.preVerificationGas);
6849
+ } else if (isFinal) assertAuthorizedGas(data, limits);
6850
+ };
6851
+ return {
6852
+ ...args,
6853
+ ...limits,
6854
+ ...adapter ? {
6855
+ paymaster: {
6856
+ async getPaymasterStubData(operation) {
6857
+ const getStub = adapter.getPaymasterStubData ?? adapter.getPaymasterData;
6858
+ const fixedOperation = { ...operation, ...limits };
6859
+ const data = await getStub.call(adapter, fixedOperation);
6860
+ const isFinal = !adapter.getPaymasterStubData || "isFinal" in data && data.isFinal === true;
6861
+ acceptGas(data, isFinal);
6862
+ return { ...data, ...limits, isFinal };
6863
+ },
6864
+ async getPaymasterData(operation) {
6865
+ const fixedOperation = { ...operation, ...limits };
6866
+ const data = await adapter.getPaymasterData(fixedOperation);
6867
+ acceptGas(data, true);
6868
+ return { ...data, ...limits };
6869
+ }
6870
+ }
6871
+ } : {},
6872
+ account: {
6873
+ ...args.account,
6874
+ userOperation: {
6875
+ ...args.account.userOperation,
6876
+ // Returning every required field keeps viem from invoking the bundler estimator.
6877
+ // The original account hook is deliberately bypassed for this submission alone.
6878
+ estimateGas: async () => limits
6879
+ }
6880
+ }
6881
+ };
6882
+ }
6883
+ function readProviderGas(data, current, preVerificationGasCeiling) {
6884
+ if (!data || typeof data !== "object") {
6885
+ throw new FluentUserOperationGasError(
6886
+ "paymaster_gas_mismatch",
6887
+ "skipEstimation requires a paymaster authorization object"
6888
+ );
6889
+ }
6890
+ const next = { ...current };
6891
+ for (const [field, minimum, maximum] of [
6892
+ ["preVerificationGas", 1n, preVerificationGasCeiling],
6893
+ ["paymasterVerificationGasLimit", 1n, maxCallGasLimit],
6894
+ ["paymasterPostOpGasLimit", 0n, maxCallGasLimit]
6895
+ ]) {
6896
+ const value = Object.hasOwn(data, field) ? Reflect.get(data, field) : current[field];
6897
+ if (typeof value !== "bigint" || value < minimum || value > maximum) {
6898
+ throw new FluentUserOperationGasError(
6899
+ "paymaster_gas_mismatch",
6900
+ `Paymaster ${field} must be a bigint between ${minimum} and ${maximum}`
6901
+ );
6902
+ }
6903
+ next[field] = value;
6904
+ }
6905
+ return next;
6906
+ }
6907
+ function assertAuthorizedGas(data, limits) {
6908
+ if (!data || typeof data !== "object") {
6909
+ throw new FluentUserOperationGasError(
6910
+ "paymaster_gas_mismatch",
6911
+ "skipEstimation requires a paymaster authorization object"
6912
+ );
6913
+ }
6914
+ for (const [field, value] of Object.entries(limits)) {
6915
+ const authorized = Reflect.get(data, field);
6916
+ if (authorized !== void 0 && authorized !== value) {
6917
+ throw new FluentUserOperationGasError(
6918
+ "paymaster_gas_mismatch",
6919
+ `Paymaster changed ${field} with skipEstimation enabled`
6920
+ );
6921
+ }
6922
+ }
6923
+ }
6717
6924
  function createFluentBatchOp(input, executor) {
6718
6925
  if (input.calls.length === 0) {
6719
6926
  throw new Error("A Fluent batch operation requires at least one call");
@@ -6742,6 +6949,9 @@ function createFluentBatchOp(input, executor) {
6742
6949
  confirmation: options?.confirmation ?? activeExecutor.defaultConfirmation ?? "always",
6743
6950
  gasPayment: gasPayment ? { ...gasPayment, sponsorship: gasPayment.sponsorship ?? activeExecutor.defaultSponsorship } : void 0
6744
6951
  };
6952
+ if (executionOptions.confirmation === "session" && activeExecutor.quickSignWhitelist && !isQuickSignWhitelisted(encodedCalls, activeExecutor.quickSignWhitelist)) {
6953
+ executionOptions.confirmation = "always";
6954
+ }
6745
6955
  if (executionOptions.confirmation === "always" && activeExecutor.account?.type !== "eoa") {
6746
6956
  await activeExecutor.confirm?.({
6747
6957
  id: input.id,
@@ -6765,6 +6975,10 @@ function createFluentBatchOp(input, executor) {
6765
6975
  }
6766
6976
  };
6767
6977
  }
6978
+ function isQuickSignWhitelisted(calls, whitelist) {
6979
+ const allowed = new Set(whitelist.map((address) => address.toLowerCase()));
6980
+ return calls.every((call) => allowed.has(call.to.toLowerCase()));
6981
+ }
6768
6982
  function encodeBatchCall(call) {
6769
6983
  if (call.data) {
6770
6984
  return {
@@ -6916,146 +7130,99 @@ function buildFluentTransferCall(params) {
6916
7130
  args: [to, amount]
6917
7131
  };
6918
7132
  }
6919
-
6920
- // src/core/hostedSigner.ts
6921
- var READY_TIMEOUT_MS = 3e4;
6922
- var SIGNATURE_TIMEOUT_MS = 12e4;
6923
- function createFluentHostedSigner(params) {
6924
- const authorizeOrigin = new URL(params.authorizeUrl, location.href).origin;
6925
- let signerWindow = null;
6926
- let activeConfirmation = null;
6927
- let state = "";
6928
- let readyPromise = null;
6929
- let resolveReady = null;
6930
- let rejectReady = null;
6931
- let pending2 = null;
6932
- const close = () => {
6933
- signerWindow?.close();
6934
- signerWindow = null;
6935
- activeConfirmation = null;
6936
- readyPromise = null;
6937
- resolveReady = null;
6938
- rejectReady = null;
6939
- pending2 = null;
6940
- };
6941
- const onMessage = (event) => {
6942
- if (event.origin !== authorizeOrigin || event.source !== signerWindow) return;
6943
- const response = event.data;
6944
- if (!response || response.state !== state) return;
6945
- if (response.type === "fluent:signer:ready") {
6946
- resolveReady?.();
6947
- resolveReady = null;
6948
- rejectReady = null;
6949
- return;
6950
- }
6951
- if (response.type === "fluent:signer:result") {
6952
- pending2?.resolve(response.signature);
6953
- pending2 = null;
6954
- return;
6955
- }
6956
- if (response.type === "fluent:signer:error") {
6957
- const error = new Error(response.error);
6958
- if (pending2) {
6959
- pending2.reject(error);
6960
- } else {
6961
- rejectReady?.(error);
6962
- }
6963
- pending2 = null;
6964
- resolveReady = null;
6965
- rejectReady = null;
6966
- }
6967
- };
6968
- addEventListener("message", onMessage);
6969
- const prepare = (confirmation = "always") => {
6970
- if (signerWindow && readyPromise && activeConfirmation === confirmation) return;
6971
- if (signerWindow || readyPromise) close();
6972
- state = crypto.randomUUID?.() ?? `${Date.now()}_${Math.random().toString(16).slice(2)}`;
6973
- const url = new URL(params.authorizeUrl, location.href);
6974
- url.searchParams.set("action", "fluent_sign");
6975
- url.searchParams.set("origin", location.origin);
6976
- url.searchParams.set("state", state);
6977
- url.searchParams.set("confirmation", confirmation);
6978
- activeConfirmation = confirmation;
6979
- signerWindow = window.open(
6980
- url.toString(),
6981
- "fluent-connect-signer",
6982
- "popup=yes,width=520,height=720,resizable=yes,scrollbars=yes"
6983
- );
6984
- if (!signerWindow) {
6985
- close();
6986
- throw new Error("Allow popups for this app to sign with Fluent Connect");
6987
- }
6988
- readyPromise = new Promise((resolve, reject) => {
6989
- resolveReady = resolve;
6990
- rejectReady = reject;
6991
- });
6992
- readyPromise.catch(() => {
6993
- });
6994
- };
6995
- const requestSignature = async (request) => {
6996
- prepare(request.confirmation);
6997
- if (!signerWindow || !readyPromise) {
6998
- throw new Error("Fluent Connect signer window is unavailable");
6999
- }
7000
- try {
7001
- await withTimeout(
7002
- readyPromise,
7003
- READY_TIMEOUT_MS,
7004
- "Fluent Connect signer did not become ready"
7005
- );
7006
- if (signerWindow.closed) throw new Error("Fluent Connect signer window was closed");
7007
- if (pending2) throw new Error("Another Fluent signature request is already pending");
7008
- const signature = new Promise((resolve, reject) => {
7009
- pending2 = { resolve, reject };
7010
- signerWindow?.postMessage({ ...request, state }, authorizeOrigin);
7011
- });
7012
- return await withTimeout(
7013
- signature,
7014
- SIGNATURE_TIMEOUT_MS,
7015
- "Fluent Connect signature request timed out"
7016
- );
7017
- } finally {
7018
- close();
7019
- }
7020
- };
7021
- return {
7022
- address: params.address,
7023
- prepare,
7024
- signMessage: (message2, confirmation = "always") => requestSignature({
7025
- type: "fluent:signer:request",
7026
- method: "personal_sign",
7027
- confirmation,
7028
- address: params.address,
7029
- message: message2
7030
- }),
7031
- signTypedData: (typedData, confirmation = "always") => requestSignature({
7032
- type: "fluent:signer:request",
7033
- method: "eth_signTypedData_v4",
7034
- confirmation,
7035
- address: params.address,
7036
- typedData
7037
- }),
7038
- close: () => {
7039
- removeEventListener("message", onMessage);
7040
- rejectReady?.(new Error("Fluent Connect signer was closed"));
7041
- pending2?.reject(new Error("Fluent Connect signer was closed"));
7042
- close();
7043
- }
7044
- };
7133
+ var AdapterContext = createContext(null);
7134
+ function FluentPrivyProvider({ adapter, ...props }) {
7135
+ const Provider = adapter?.PrivyProvider ?? web.PrivyProvider;
7136
+ return /* @__PURE__ */ jsx(AdapterContext.Provider, { value: adapter ?? null, children: /* @__PURE__ */ jsx(Provider, { ...props }) });
7045
7137
  }
7046
- async function withTimeout(promise, timeoutMs, message2) {
7047
- let timer;
7048
- try {
7049
- return await Promise.race([
7050
- promise,
7051
- new Promise((_resolve, reject) => {
7052
- timer = setTimeout(() => reject(new Error(message2)), timeoutMs);
7138
+ var usePrivy2 = (...args) => {
7139
+ const adapter = useContext(AdapterContext);
7140
+ return (adapter?.usePrivy ?? web.usePrivy)(...args);
7141
+ };
7142
+ var useSignMessage2 = (...args) => {
7143
+ const adapter = useContext(AdapterContext);
7144
+ return (adapter?.useSignMessage ?? web.useSignMessage)(...args);
7145
+ };
7146
+ var useSignTypedData2 = (...args) => {
7147
+ const adapter = useContext(AdapterContext);
7148
+ return (adapter?.useSignTypedData ?? web.useSignTypedData)(...args);
7149
+ };
7150
+ var useWallets2 = (...args) => {
7151
+ const adapter = useContext(AdapterContext);
7152
+ return (adapter?.useWallets ?? web.useWallets)(...args);
7153
+ };
7154
+ var useIdentityToken2 = (...args) => {
7155
+ const adapter = useContext(AdapterContext);
7156
+ return (adapter?.useIdentityToken ?? web.useIdentityToken)(...args);
7157
+ };
7158
+ var useUser2 = (...args) => {
7159
+ const adapter = useContext(AdapterContext);
7160
+ return (adapter?.useUser ?? web.useUser)(...args);
7161
+ };
7162
+ var useLinkAccount2 = (...args) => {
7163
+ const adapter = useContext(AdapterContext);
7164
+ return (adapter?.useLinkAccount ?? web.useLinkAccount)(...args);
7165
+ };
7166
+ var useLoginWithSiwe2 = (...args) => {
7167
+ const adapter = useContext(AdapterContext);
7168
+ return (adapter?.useLoginWithSiwe ?? web.useLoginWithSiwe)(...args);
7169
+ };
7170
+ var useModalStatus2 = (...args) => {
7171
+ const adapter = useContext(AdapterContext);
7172
+ return (adapter?.useModalStatus ?? web.useModalStatus)(...args);
7173
+ };
7174
+ var useCreateWallet2 = (...args) => {
7175
+ const adapter = useContext(AdapterContext);
7176
+ return (adapter?.useCreateWallet ?? web.useCreateWallet)(...args);
7177
+ };
7178
+ var useLoginWithEmail2 = (...args) => {
7179
+ const adapter = useContext(AdapterContext);
7180
+ return (adapter?.useLoginWithEmail ?? web.useLoginWithEmail)(...args);
7181
+ };
7182
+ var useLoginWithOAuth2 = (...args) => {
7183
+ const adapter = useContext(AdapterContext);
7184
+ return (adapter?.useLoginWithOAuth ?? web.useLoginWithOAuth)(...args);
7185
+ };
7186
+ var useLoginWithPasskey2 = (...args) => {
7187
+ const adapter = useContext(AdapterContext);
7188
+ return (adapter?.useLoginWithPasskey ?? web.useLoginWithPasskey)(...args);
7189
+ };
7190
+ var useLinkWithPasskey2 = (...args) => {
7191
+ const adapter = useContext(AdapterContext);
7192
+ return (adapter?.useLinkWithPasskey ?? web.useLinkWithPasskey)(...args);
7193
+ };
7194
+ function Captcha2(props) {
7195
+ const adapter = useContext(AdapterContext);
7196
+ const Component = adapter?.Captcha ?? web.Captcha;
7197
+ return /* @__PURE__ */ jsx(Component, { ...props });
7198
+ }
7199
+ var FLUENT_RPC_TIMEOUT_MS = 3e4;
7200
+ var FLUENT_RPC_RETRY_COUNT = 3;
7201
+ var FLUENT_RPC_RETRY_DELAY_MS = 300;
7202
+ function createFluentRpcTransport(chain) {
7203
+ const urls = chain.rpcUrls.default.http;
7204
+ const endpoints = urls.length > 0 ? urls : [void 0];
7205
+ return fallback(
7206
+ endpoints.map(
7207
+ (url) => http(url, {
7208
+ timeout: FLUENT_RPC_TIMEOUT_MS,
7209
+ retryCount: FLUENT_RPC_RETRY_COUNT,
7210
+ retryDelay: FLUENT_RPC_RETRY_DELAY_MS
7053
7211
  })
7054
- ]);
7055
- } finally {
7056
- if (timer) clearTimeout(timer);
7057
- }
7212
+ ),
7213
+ // Each http() already retries; let fallback only rank/fail over between URLs.
7214
+ { retryCount: 0 }
7215
+ );
7216
+ }
7217
+ function createFluentBundlerTransport(url) {
7218
+ return http(url, {
7219
+ timeout: FLUENT_RPC_TIMEOUT_MS,
7220
+ retryCount: FLUENT_RPC_RETRY_COUNT,
7221
+ retryDelay: FLUENT_RPC_RETRY_DELAY_MS
7222
+ });
7058
7223
  }
7224
+
7225
+ // src/core/zerodevPaymaster.ts
7059
7226
  var FLUENT_ZERODEV_ERC20_PAYMASTER_QUERY = "selfFunded=true";
7060
7227
  var FLUENT_ZERODEV_PAYMASTER_DEMO_RECIPIENT = "0x000000000000000000000000000000000000dEaD";
7061
7228
  function getFluentZeroDevErc20PaymasterTokens(network = "testnet") {
@@ -7072,7 +7239,9 @@ function getFluentZeroDevErc20PaymasterTokens(network = "testnet") {
7072
7239
  }
7073
7240
  function createFluentZeroDevRpcUrl(params = {}) {
7074
7241
  const chainId = params.chainId ?? fluentTestnet.id;
7075
- const projectId = params.projectId ?? FLUENT_CONNECT_ZERODEV_PROJECT_ID;
7242
+ const projectId = params.projectId ?? getFluentZeroDevProjectId(
7243
+ getFluentWidgetNetworkForChainId(chainId)
7244
+ );
7076
7245
  const baseUrl = `https://rpc.zerodev.app/api/v3/${projectId}/chain/${chainId}`;
7077
7246
  return params.selfFunded ? `${baseUrl}?${FLUENT_ZERODEV_ERC20_PAYMASTER_QUERY}` : baseUrl;
7078
7247
  }
@@ -7087,6 +7256,7 @@ function createFluentZeroDevSponsoredPaymaster(params) {
7087
7256
  const paymasterClient = createZeroDevPaymasterClient({
7088
7257
  chain: params.chain,
7089
7258
  transport: http(params.rpcUrl, {
7259
+ timeout: FLUENT_RPC_TIMEOUT_MS,
7090
7260
  fetchOptions: { headers: { Authorization: `Bearer ${params.bearerToken}` } }
7091
7261
  })
7092
7262
  });
@@ -7113,7 +7283,8 @@ function createFluentZeroDevErc20PaymasterClient(params = {}) {
7113
7283
  return createZeroDevPaymasterClient({
7114
7284
  chain,
7115
7285
  transport: http(
7116
- params.paymasterRpcUrl ?? createFluentZeroDevErc20PaymasterRpcUrl({ chainId: chain.id })
7286
+ params.paymasterRpcUrl ?? createFluentZeroDevErc20PaymasterRpcUrl({ chainId: chain.id }),
7287
+ { timeout: FLUENT_RPC_TIMEOUT_MS }
7117
7288
  )
7118
7289
  });
7119
7290
  }
@@ -7180,7 +7351,7 @@ async function sendFluentZeroDevErc20PaymasterDemo(params) {
7180
7351
  const client2 = createKernelAccountClient({
7181
7352
  account: params.kernel.account,
7182
7353
  chain,
7183
- bundlerTransport: http(params.kernel.zeroDevRpcUrl),
7354
+ bundlerTransport: http(params.kernel.zeroDevRpcUrl, { timeout: FLUENT_RPC_TIMEOUT_MS }),
7184
7355
  client: params.kernel.publicClient,
7185
7356
  paymaster: createFluentZeroDevErc20Paymaster({
7186
7357
  chain,
@@ -7256,6 +7427,7 @@ async function sendWithSponsorship(params) {
7256
7427
  ownGasClient,
7257
7428
  waitFor,
7258
7429
  disableSponsorship,
7430
+ isOperationFailure,
7259
7431
  log
7260
7432
  } = params;
7261
7433
  const settle = async (settlementClient, userOpHash, sponsored, sponsorshipReason) => {
@@ -7286,6 +7458,7 @@ async function sendWithSponsorship(params) {
7286
7458
  try {
7287
7459
  return { ok: true, userOpHash: await sendSponsored(client2) };
7288
7460
  } catch (err) {
7461
+ if (isOperationFailure?.(err)) throw err;
7289
7462
  const failure = getSponsorshipFailure(err);
7290
7463
  if (failure.disableSponsorship) disableSponsorship();
7291
7464
  return { ok: false, failure, error: err };
@@ -7315,89 +7488,440 @@ function isRejectedBearer(failure) {
7315
7488
  function sponsorshipTokenErrorCode(err) {
7316
7489
  return err instanceof FluentAuthError ? err.code : "unknown";
7317
7490
  }
7491
+ var FLUENT_CHAIN_FEE_MARGIN_PERCENT = 110n;
7492
+ function quoteFluentChainFees(gasPrice) {
7493
+ return {
7494
+ maxPriorityFeePerGas: gasPrice,
7495
+ maxFeePerGas: gasPrice * FLUENT_CHAIN_FEE_MARGIN_PERCENT / 100n
7496
+ };
7497
+ }
7498
+ var FLUENT_FEE_ATTEMPT = /* @__PURE__ */ Symbol.for("fluent.userOperation.feeAttempt");
7499
+ function withFluentFeeAttempt(account, attempt) {
7500
+ return { ...account, [FLUENT_FEE_ATTEMPT]: attempt };
7501
+ }
7502
+ function readFluentFeeAttempt(account) {
7503
+ if (typeof account !== "object" || account === null) return void 0;
7504
+ const attempt = account[FLUENT_FEE_ATTEMPT];
7505
+ return typeof attempt === "object" && attempt !== null ? attempt : void 0;
7506
+ }
7507
+ async function readFluentBundlerFees(bundlerClient) {
7508
+ return getUserOperationGasPrice(
7509
+ bundlerClient
7510
+ );
7511
+ }
7512
+ function createFluentUserOperationFeeHook(params) {
7513
+ return async ({ account, bundlerClient }) => {
7514
+ const attempt = readFluentFeeAttempt(account);
7515
+ const requested = attempt?.feeSource ?? params.readFeeSource();
7516
+ if (requested === "chain") {
7517
+ try {
7518
+ const fees2 = quoteFluentChainFees(await params.readGasPrice());
7519
+ if (attempt) attempt.settledFeeSource = "chain";
7520
+ debugLog("[fluent user operation fees] chain quote", {
7521
+ maxFeePerGas: fees2.maxFeePerGas.toString(),
7522
+ maxPriorityFeePerGas: fees2.maxPriorityFeePerGas.toString()
7523
+ });
7524
+ return fees2;
7525
+ } catch (err) {
7526
+ debugWarn("[fluent user operation fees] chain gas price unavailable, asking the bundler", {
7527
+ message: err instanceof Error ? err.message : String(err)
7528
+ });
7529
+ }
7530
+ }
7531
+ const fees = await readFluentBundlerFees(bundlerClient);
7532
+ if (attempt) attempt.settledFeeSource = "bundler";
7533
+ return fees;
7534
+ };
7535
+ }
7536
+ var FLUENT_FEE_REJECTION_MESSAGES = [
7537
+ "maxFeePerGas must be at least",
7538
+ "maxPriorityFeePerGas must be at least"
7539
+ ];
7540
+ function isFluentFeeRejection(err) {
7541
+ const needles = FLUENT_FEE_REJECTION_MESSAGES.map((message2) => message2.toLowerCase());
7542
+ for (const text of errorTexts(err)) {
7543
+ const lowered = text.toLowerCase();
7544
+ if (needles.some((needle) => lowered.includes(needle))) return true;
7545
+ }
7546
+ return false;
7547
+ }
7548
+ function errorTexts(err) {
7549
+ const texts = [];
7550
+ let current = err;
7551
+ for (let depth = 0; depth < 10 && current !== void 0 && current !== null; depth += 1) {
7552
+ if (current instanceof BaseError) {
7553
+ texts.push(current.shortMessage, current.details, ...current.metaMessages ?? []);
7554
+ }
7555
+ if (current instanceof Error) {
7556
+ texts.push(current.message);
7557
+ current = current.cause;
7558
+ continue;
7559
+ }
7560
+ if (typeof current === "string") texts.push(current);
7561
+ break;
7562
+ }
7563
+ return texts.filter((text) => typeof text === "string" && text.length > 0);
7564
+ }
7318
7565
 
7319
7566
  // src/core/userOperationTiming.ts
7320
- async function sendUserOperationWithTiming(client2, args, gas) {
7567
+ function monotonicNow() {
7568
+ return readClock(() => performance.now());
7569
+ }
7570
+ function epochNow() {
7571
+ return readClock(() => Date.now());
7572
+ }
7573
+ function readClock(read) {
7574
+ try {
7575
+ const value = read();
7576
+ return Number.isFinite(value) ? value : void 0;
7577
+ } catch {
7578
+ return void 0;
7579
+ }
7580
+ }
7581
+ function span(from, to) {
7582
+ return from === void 0 || to === void 0 ? void 0 : to - from;
7583
+ }
7584
+ function guarded(write) {
7585
+ return (...args) => {
7586
+ try {
7587
+ write(...args);
7588
+ } catch {
7589
+ }
7590
+ };
7591
+ }
7592
+ var timingLog = guarded(debugLog);
7593
+ var timingWarn = guarded(debugWarn);
7594
+ async function sendUserOperationWithTiming(client2, args, gas, record, feeAttempt) {
7321
7595
  const preparedArgs = withUserOperationGas(client2, args, gas);
7322
- if (!isDebugLoggingEnabled()) return client2.sendUserOperation(preparedArgs);
7323
- const startedAt = performance.now();
7596
+ const startedAt = monotonicNow();
7597
+ const startedAtEpochMs = epochNow();
7324
7598
  let signingAt;
7325
7599
  let signedAt;
7600
+ let askedToSign = false;
7601
+ let signatureReturned = false;
7326
7602
  let success = false;
7327
7603
  const account = preparedArgs.account;
7328
7604
  const observedAccount = {
7329
7605
  ...account,
7330
7606
  async signUserOperation(operation) {
7331
- signingAt = performance.now();
7332
- debugLog("[fluent execution stage]", {
7607
+ askedToSign = true;
7608
+ signingAt = monotonicNow();
7609
+ timingLog("[fluent execution stage]", {
7333
7610
  stage: "signing",
7334
- preparationMs: signingAt - startedAt
7611
+ preparationMs: span(startedAt, signingAt)
7335
7612
  });
7336
7613
  const signature = await account.signUserOperation(operation);
7337
- signedAt = performance.now();
7338
- debugLog("[fluent execution stage]", {
7614
+ signatureReturned = true;
7615
+ signedAt = monotonicNow();
7616
+ timingLog("[fluent execution stage]", {
7339
7617
  stage: "broadcasting",
7340
- signingMs: signedAt - signingAt
7618
+ signingMs: span(signingAt, signedAt)
7341
7619
  });
7342
7620
  return signature;
7343
7621
  }
7344
7622
  };
7345
- debugLog("[fluent execution stage]", { stage: "preparing" });
7623
+ const submittedAccount = feeAttempt ? withFluentFeeAttempt(observedAccount, feeAttempt) : observedAccount;
7624
+ let closed;
7625
+ const close = () => {
7626
+ if (closed) return closed.measurement;
7627
+ const finishedAt = monotonicNow();
7628
+ const finishedAtEpochMs = epochNow();
7629
+ closed = startedAt === void 0 || startedAtEpochMs === void 0 || finishedAt === void 0 || finishedAtEpochMs === void 0 ? {} : {
7630
+ measurement: {
7631
+ startedAt,
7632
+ startedAtEpochMs,
7633
+ // The attempt's whole span counts as preparation only when preparation is where
7634
+ // it ended; once a signature was asked for, preparation is measured to that
7635
+ // request or not at all.
7636
+ prepareMs: askedToSign ? span(startedAt, signingAt) : finishedAt - startedAt,
7637
+ // Signing that never returned was still running when the attempt ended, so the
7638
+ // attempt's end is its real boundary. Signing that did return, at an unreadable
7639
+ // instant, has no measurable end — and must not borrow the broadcast's.
7640
+ signMs: span(signingAt, signatureReturned ? signedAt : finishedAt),
7641
+ broadcastMs: span(signedAt, finishedAt),
7642
+ finishedAt,
7643
+ finishedAtEpochMs
7644
+ }
7645
+ };
7646
+ return closed.measurement;
7647
+ };
7648
+ let settledUserOpHash;
7649
+ timingLog("[fluent execution stage]", { stage: "preparing" });
7346
7650
  try {
7347
- const hash = await client2.sendUserOperation({ ...preparedArgs, account: observedAccount });
7651
+ settledUserOpHash = await client2.sendUserOperation({
7652
+ ...preparedArgs,
7653
+ account: submittedAccount
7654
+ });
7348
7655
  success = true;
7349
- return hash;
7656
+ return { userOpHash: settledUserOpHash, measurement: close() };
7350
7657
  } finally {
7351
- const finishedAt = performance.now();
7352
- debugLog("[fluent submission timing]", {
7658
+ const measurement = close();
7659
+ try {
7660
+ record?.(
7661
+ settledUserOpHash === void 0 ? { measurement } : { userOpHash: settledUserOpHash, measurement }
7662
+ );
7663
+ } catch {
7664
+ }
7665
+ timingLog("[fluent submission timing]", {
7353
7666
  success,
7354
- preparationMs: (signingAt ?? finishedAt) - startedAt,
7355
- signingMs: signingAt === void 0 ? void 0 : (signedAt ?? finishedAt) - signingAt,
7356
- broadcastMs: signedAt === void 0 ? void 0 : finishedAt - signedAt,
7357
- totalMs: finishedAt - startedAt
7667
+ // Which source actually quoted this attempt's fees, not which one it asked: a chain
7668
+ // quote that failed is reported as the bundler's, because that is what was paid for.
7669
+ feeSource: feeAttempt?.settledFeeSource,
7670
+ preparationMs: measurement?.prepareMs,
7671
+ signingMs: measurement?.signMs,
7672
+ broadcastMs: measurement?.broadcastMs,
7673
+ // Not `totalMs`: this is one submission, and the send's total runs on to the receipt.
7674
+ // Two different numbers under one name is the confusion this Issue exists to end.
7675
+ submissionMs: span(measurement?.startedAt, measurement?.finishedAt)
7358
7676
  });
7359
7677
  }
7360
7678
  }
7361
- var FLUENT_RPC_RETRY_COUNT = 3;
7362
- var FLUENT_RPC_RETRY_DELAY_MS = 300;
7363
- function createFluentRpcTransport(chain) {
7364
- const urls = chain.rpcUrls.default.http;
7365
- const endpoints = urls.length > 0 ? urls : [void 0];
7366
- return fallback(
7367
- endpoints.map(
7368
- (url) => http(url, {
7369
- retryCount: FLUENT_RPC_RETRY_COUNT,
7370
- retryDelay: FLUENT_RPC_RETRY_DELAY_MS
7371
- })
7372
- ),
7373
- // Each http() already retries; let fallback only rank/fail over between URLs.
7374
- { retryCount: 0 }
7679
+ async function closeSendTiming(params) {
7680
+ const { attempts, settledUserOpHash, receivedAt, receivedAtEpochMs } = params;
7681
+ const first = attempts[0];
7682
+ const settled = attempts.find(
7683
+ (attempt) => attempt.userOpHash !== void 0 && attempt.userOpHash === settledUserOpHash
7375
7684
  );
7685
+ if (!first?.measurement || !settled?.measurement) return void 0;
7686
+ const measurement = settled.measurement;
7687
+ const firstMeasurement = first.measurement;
7688
+ const blockTimestampEpochMs = await readBlockTimestamp(params.getBlock, params.blockNumber);
7689
+ return {
7690
+ prepareMs: measurement.prepareMs,
7691
+ signMs: measurement.signMs,
7692
+ broadcastMs: measurement.broadcastMs,
7693
+ // Signed, unclamped, and across two clocks on purpose — see `FluentExecuteTiming`.
7694
+ inclusionMs: blockTimestampEpochMs === void 0 ? void 0 : blockTimestampEpochMs - measurement.finishedAtEpochMs,
7695
+ detectMs: blockTimestampEpochMs === void 0 ? void 0 : receivedAtEpochMs - blockTimestampEpochMs,
7696
+ // Everything before the settled attempt started: the rejected submissions and the fresh
7697
+ // token exchange between them. One monotonic subtraction, so it cannot go negative.
7698
+ retryMs: measurement.startedAt - firstMeasurement.startedAt,
7699
+ totalMs: receivedAt - firstMeasurement.startedAt,
7700
+ instants: {
7701
+ submittedAtEpochMs: firstMeasurement.startedAtEpochMs,
7702
+ broadcastedAtEpochMs: measurement.finishedAtEpochMs,
7703
+ receivedAtEpochMs,
7704
+ blockTimestampEpochMs,
7705
+ attempts: attempts.length
7706
+ }
7707
+ };
7376
7708
  }
7377
- function createFluentBundlerTransport(url) {
7378
- return http(url, {
7379
- retryCount: FLUENT_RPC_RETRY_COUNT,
7380
- retryDelay: FLUENT_RPC_RETRY_DELAY_MS
7381
- });
7382
- }
7383
-
7384
- // src/utils/buildFluentBridgeUrl.ts
7385
- function buildFluentBridgeUrl(bridgeUrl, recipient) {
7386
- if (!recipient) return bridgeUrl;
7709
+ async function readBlockTimestamp(getBlock, blockNumber) {
7710
+ if (!getBlock || blockNumber === void 0) return void 0;
7387
7711
  try {
7388
- const url = new URL(bridgeUrl);
7389
- url.searchParams.set("recipient", recipient);
7390
- return url.toString();
7712
+ const block = await getBlock({ blockNumber });
7713
+ if (typeof block?.timestamp !== "bigint") return void 0;
7714
+ return Number(block.timestamp) * 1e3;
7391
7715
  } catch {
7392
- const join = bridgeUrl.includes("?") ? "&" : "?";
7393
- return `${bridgeUrl}${join}recipient=${encodeURIComponent(recipient)}`;
7716
+ timingWarn("[fluent inclusion timing] including block unavailable", {
7717
+ blockNumber: blockNumber.toString()
7718
+ });
7719
+ return void 0;
7394
7720
  }
7395
7721
  }
7396
-
7397
- // src/utils/clearPrivyRecentLoginMethod.ts
7398
- function clearPrivyRecentLoginMethod(appId) {
7399
- if (typeof window === "undefined" || !appId) return;
7400
- try {
7722
+ var FLUENT_INCLUSION_TIMEOUT_MS = 12e4;
7723
+ var FLUENT_INCLUSION_POLL_INTERVAL_MS = 200;
7724
+ var FLUENT_USER_OPERATION_EVENT = {
7725
+ type: "event",
7726
+ name: "UserOperationEvent",
7727
+ inputs: [
7728
+ { name: "userOpHash", type: "bytes32", indexed: true },
7729
+ { name: "sender", type: "address", indexed: true },
7730
+ { name: "paymaster", type: "address", indexed: true },
7731
+ { name: "nonce", type: "uint256", indexed: false },
7732
+ { name: "success", type: "bool", indexed: false },
7733
+ { name: "actualGasCost", type: "uint256", indexed: false },
7734
+ { name: "actualGasUsed", type: "uint256", indexed: false }
7735
+ ]
7736
+ };
7737
+ var FLUENT_USER_OPERATION_REVERT_REASON_EVENT = {
7738
+ type: "event",
7739
+ name: "UserOperationRevertReason",
7740
+ inputs: [
7741
+ { name: "userOpHash", type: "bytes32", indexed: true },
7742
+ { name: "sender", type: "address", indexed: true },
7743
+ { name: "nonce", type: "uint256", indexed: false },
7744
+ { name: "revertReason", type: "bytes", indexed: false }
7745
+ ]
7746
+ };
7747
+ var FLUENT_BEFORE_EXECUTION_EVENT = {
7748
+ type: "event",
7749
+ name: "BeforeExecution",
7750
+ inputs: []
7751
+ };
7752
+ var USER_OPERATION_EVENT_TOPIC = toEventSelector(FLUENT_USER_OPERATION_EVENT).toLowerCase();
7753
+ var USER_OPERATION_REVERT_REASON_TOPIC = toEventSelector(
7754
+ FLUENT_USER_OPERATION_REVERT_REASON_EVENT
7755
+ ).toLowerCase();
7756
+ var BEFORE_EXECUTION_TOPIC = toEventSelector(FLUENT_BEFORE_EXECUTION_EVENT).toLowerCase();
7757
+ async function readFluentInclusionAnchor(chainClient) {
7758
+ try {
7759
+ return await getBlockNumber(chainClient, { cacheTime: 0 });
7760
+ } catch (err) {
7761
+ debugWarn("[fluent inclusion] anchor block unavailable, waiting on the bundler", {
7762
+ message: err instanceof Error ? err.message : String(err)
7763
+ });
7764
+ return void 0;
7765
+ }
7766
+ }
7767
+ async function waitForFluentUserOperationReceipt(params) {
7768
+ const { bundlerClient, chainClient, hash, entryPoint, anchorBlockNumber, receiptSource } = params;
7769
+ const now = params.now ?? (() => Date.now());
7770
+ const deadlineAt = now() + FLUENT_INCLUSION_TIMEOUT_MS;
7771
+ const reportSource = (source) => {
7772
+ try {
7773
+ params.onReceiptSource?.(source);
7774
+ } catch {
7775
+ }
7776
+ };
7777
+ const waitOnBundler = (timeout = FLUENT_INCLUSION_TIMEOUT_MS) => {
7778
+ reportSource("bundler");
7779
+ return bundlerClient.waitForUserOperationReceipt({
7780
+ hash,
7781
+ pollingInterval: FLUENT_INCLUSION_POLL_INTERVAL_MS,
7782
+ timeout
7783
+ });
7784
+ };
7785
+ const remainingMs = () => Math.max(1, deadlineAt - now());
7786
+ if (receiptSource === "bundler") return waitOnBundler();
7787
+ if (anchorBlockNumber === void 0) return waitOnBundler();
7788
+ const fromBlock = anchorBlockNumber > 0n ? anchorBlockNumber - 1n : 0n;
7789
+ const pollChain = async () => {
7790
+ for (; ; ) {
7791
+ if (now() >= deadlineAt) throw new WaitForUserOperationReceiptTimeoutError({ hash });
7792
+ let events;
7793
+ try {
7794
+ events = await readUserOperationEvents({ chainClient, entryPoint, hash, fromBlock });
7795
+ } catch (err) {
7796
+ debugWarn("[fluent inclusion] chain logs unavailable, waiting on the bundler", {
7797
+ userOpHash: hash,
7798
+ message: err instanceof Error ? err.message : String(err)
7799
+ });
7800
+ return waitOnBundler(remainingMs());
7801
+ }
7802
+ const event = events[0];
7803
+ if (event) {
7804
+ try {
7805
+ const receipt = await buildChainReceipt({
7806
+ chainClient,
7807
+ entryPoint,
7808
+ hash,
7809
+ event
7810
+ });
7811
+ reportSource("chain");
7812
+ debugLog("[fluent inclusion] receipt built from the chain", {
7813
+ userOpHash: hash,
7814
+ transactionHash: receipt.receipt.transactionHash
7815
+ });
7816
+ return receipt;
7817
+ } catch (err) {
7818
+ debugWarn("[fluent inclusion] transaction receipt unavailable, waiting on the bundler", {
7819
+ userOpHash: hash,
7820
+ message: err instanceof Error ? err.message : String(err)
7821
+ });
7822
+ return waitOnBundler(remainingMs());
7823
+ }
7824
+ }
7825
+ await delay(FLUENT_INCLUSION_POLL_INTERVAL_MS);
7826
+ }
7827
+ };
7828
+ return untilDeadline(pollChain(), remainingMs(), hash);
7829
+ }
7830
+ function untilDeadline(work, msLeft, hash) {
7831
+ let timer;
7832
+ const expiry = new Promise((_resolve, reject) => {
7833
+ timer = setTimeout(() => {
7834
+ reject(new WaitForUserOperationReceiptTimeoutError({ hash }));
7835
+ }, msLeft);
7836
+ });
7837
+ return Promise.race([work, expiry]).finally(() => {
7838
+ clearTimeout(timer);
7839
+ });
7840
+ }
7841
+ async function readUserOperationEvents(params) {
7842
+ return getLogs(params.chainClient, {
7843
+ address: params.entryPoint,
7844
+ event: FLUENT_USER_OPERATION_EVENT,
7845
+ args: { userOpHash: params.hash },
7846
+ fromBlock: params.fromBlock,
7847
+ // A log whose data does not decode against this event is not this event: better dropped
7848
+ // than turned into a receipt with absent fields.
7849
+ strict: true
7850
+ });
7851
+ }
7852
+ async function buildChainReceipt(params) {
7853
+ const { chainClient, entryPoint, hash, event } = params;
7854
+ const transactionReceipt = await getTransactionReceipt(chainClient, {
7855
+ hash: event.transactionHash
7856
+ });
7857
+ const built = {
7858
+ userOpHash: hash,
7859
+ entryPoint,
7860
+ sender: event.args.sender,
7861
+ nonce: event.args.nonce,
7862
+ success: event.args.success,
7863
+ // The zero address is the EntryPoint's spelling of "no paymaster", and a bundler's receipt
7864
+ // leaves the field out for it (alto `parseUserOpReceipt`); so does this one, so a reader
7865
+ // of either source sees the same absence when the account paid for itself.
7866
+ paymaster: event.args.paymaster === zeroAddress ? void 0 : event.args.paymaster,
7867
+ actualGasCost: event.args.actualGasCost,
7868
+ actualGasUsed: event.args.actualGasUsed,
7869
+ logs: sliceOperationLogs(transactionReceipt.logs, event.logIndex),
7870
+ reason: readRevertReason(transactionReceipt.logs, hash),
7871
+ receipt: transactionReceipt
7872
+ };
7873
+ return built;
7874
+ }
7875
+ function sliceOperationLogs(logs, logIndex) {
7876
+ const at = logs.findIndex((log) => log.logIndex === logIndex);
7877
+ if (at < 0) return [...logs];
7878
+ let from = 0;
7879
+ for (let index = at - 1; index >= 0; index -= 1) {
7880
+ const topic = logs[index]?.topics[0]?.toLowerCase();
7881
+ if (topic === USER_OPERATION_EVENT_TOPIC || topic === BEFORE_EXECUTION_TOPIC) {
7882
+ from = index + 1;
7883
+ break;
7884
+ }
7885
+ }
7886
+ return logs.slice(from, at);
7887
+ }
7888
+ function readRevertReason(logs, hash) {
7889
+ const target = hash.toLowerCase();
7890
+ for (const log of logs) {
7891
+ if (log.topics[0]?.toLowerCase() !== USER_OPERATION_REVERT_REASON_TOPIC) continue;
7892
+ if (log.topics[1]?.toLowerCase() !== target) continue;
7893
+ const decoded = decodeEventLog({
7894
+ abi: [FLUENT_USER_OPERATION_REVERT_REASON_EVENT],
7895
+ data: log.data,
7896
+ topics: log.topics
7897
+ });
7898
+ return decoded.args.revertReason;
7899
+ }
7900
+ return void 0;
7901
+ }
7902
+ function delay(ms) {
7903
+ return new Promise((resolve) => {
7904
+ setTimeout(resolve, ms);
7905
+ });
7906
+ }
7907
+
7908
+ // src/utils/buildFluentBridgeUrl.ts
7909
+ function buildFluentBridgeUrl(bridgeUrl, recipient) {
7910
+ if (!recipient) return bridgeUrl;
7911
+ try {
7912
+ const url = new URL(bridgeUrl);
7913
+ url.searchParams.set("recipient", recipient);
7914
+ return url.toString();
7915
+ } catch {
7916
+ const join = bridgeUrl.includes("?") ? "&" : "?";
7917
+ return `${bridgeUrl}${join}recipient=${encodeURIComponent(recipient)}`;
7918
+ }
7919
+ }
7920
+
7921
+ // src/utils/clearPrivyRecentLoginMethod.ts
7922
+ function clearPrivyRecentLoginMethod(appId) {
7923
+ if (typeof window === "undefined" || !appId) return;
7924
+ try {
7401
7925
  window.localStorage.removeItem(`privy:${appId}:recent-login-method`);
7402
7926
  window.localStorage.removeItem(`privy:${appId}:recent-login-wallet-client`);
7403
7927
  window.localStorage.removeItem(`privy:${appId}:recent-login-chain-type`);
@@ -7795,7 +8319,6 @@ function createLocalFluentSession(params) {
7795
8319
  scopes: params.scopes,
7796
8320
  issuedAt,
7797
8321
  metadata: {
7798
- authMode: "direct",
7799
8322
  origin: params.app.origin
7800
8323
  }
7801
8324
  };
@@ -7992,38 +8515,65 @@ function stringifyWithBigInt(value, space) {
7992
8515
  }
7993
8516
 
7994
8517
  // src/widget/zerodevSession.ts
8518
+ var FLUENT_SIGNER_CHAIN_CHECK = /* @__PURE__ */ Symbol.for("fluent.signer.chainCheck");
8519
+ function carryFluentSignerChainCheck(account, check) {
8520
+ return { ...account, [FLUENT_SIGNER_CHAIN_CHECK]: check };
8521
+ }
8522
+ function readFluentSignerChainCheck(account) {
8523
+ if (typeof account !== "object" || account === null) return void 0;
8524
+ const check = account[FLUENT_SIGNER_CHAIN_CHECK];
8525
+ return typeof check === "function" ? check : void 0;
8526
+ }
8527
+ function withFluentSignerChainCheck(account, signatures, before) {
8528
+ const checked = { ...account };
8529
+ for (const name of signatures) {
8530
+ const sign = account[name];
8531
+ if (typeof sign !== "function") continue;
8532
+ checked[name] = async (...args) => {
8533
+ await before();
8534
+ return sign.apply(account, args);
8535
+ };
8536
+ }
8537
+ return checked;
8538
+ }
8539
+ function toFluentSigningAccount(params) {
8540
+ const check = () => ensureWalletOnFluentChain(params.wallet, params.chain);
8541
+ return withFluentSignerChainCheck(
8542
+ carryFluentSignerChainCheck(params.account, check),
8543
+ ["signMessage", "signTypedData"],
8544
+ async () => {
8545
+ if (!params.readExecution().chainCheckBeforeSign) return;
8546
+ await check();
8547
+ }
8548
+ );
8549
+ }
7995
8550
  function useFluentZeroDevAccount(hookOptions = {}) {
7996
8551
  const { chain, network } = useFluentWidgetNetwork();
7997
- const { authenticated, login: privyLogin, ready } = usePrivy();
8552
+ const zeroDevProjectId = getFluentZeroDevProjectId(network);
8553
+ const { authenticated, login: privyLogin, ready } = usePrivy2();
7998
8554
  const login = hookOptions.login ?? privyLogin;
7999
- const { signMessage: promptSignMessage } = useSignMessage();
8000
- const { signTypedData: promptSignTypedData } = useSignTypedData();
8001
- const { wallets } = useWallets();
8555
+ const { signMessage: promptSignMessage } = useSignMessage2();
8556
+ const { signTypedData: promptSignTypedData } = useSignTypedData2();
8557
+ const { wallets } = useWallets2();
8002
8558
  const [kernels, setKernels] = useState({});
8003
8559
  const [error, setError] = useState(null);
8004
8560
  const [smartAccountReady, setSmartAccountReady] = useState(false);
8005
8561
  const initPromise = useRef({});
8006
8562
  const sponsorshipUnavailable = useRef(false);
8007
8563
  const embeddedWallet = wallets.find((wallet) => wallet.walletClientType === "privy");
8008
- const hostedSigner = useMemo(
8009
- () => hookOptions.allowHostedSigner !== false && hookOptions.authorizeUrl && hookOptions.sessionSignerAddress ? createFluentHostedSigner({
8010
- address: hookOptions.sessionSignerAddress,
8011
- authorizeUrl: hookOptions.authorizeUrl
8012
- }) : null,
8013
- [
8014
- hookOptions.allowHostedSigner,
8015
- hookOptions.authorizeUrl,
8016
- hookOptions.sessionSignerAddress
8017
- ]
8018
- );
8019
8564
  const activeKernel = kernels.prompt ?? kernels.silent ?? null;
8565
+ const executionRef = useRef(FLUENT_CONNECT_DEFAULT_EXECUTION);
8566
+ executionRef.current = hookOptions.execution ?? FLUENT_CONNECT_DEFAULT_EXECUTION;
8567
+ const readExecution = useCallback(
8568
+ () => executionRef.current,
8569
+ []
8570
+ );
8020
8571
  useEffect(() => {
8021
8572
  setKernels({});
8022
8573
  setSmartAccountReady(false);
8023
8574
  setError(null);
8024
8575
  initPromise.current = {};
8025
8576
  }, [chain.id]);
8026
- useEffect(() => () => hostedSigner?.close(), [hostedSigner]);
8027
8577
  const initialize2 = useCallback(async (options = {}) => {
8028
8578
  const signerMode = options.signerMode ?? "prompt";
8029
8579
  const cachedKernel = kernels[signerMode];
@@ -8038,7 +8588,7 @@ function useFluentZeroDevAccount(hookOptions = {}) {
8038
8588
  cachedSignerModes: Object.keys(kernels),
8039
8589
  initInFlight: Boolean(initPromise.current[signerMode]),
8040
8590
  throwOnError: Boolean(options.throwOnError),
8041
- hasProjectId: Boolean(FLUENT_CONNECT_ZERODEV_PROJECT_ID)
8591
+ hasProjectId: Boolean(zeroDevProjectId)
8042
8592
  });
8043
8593
  if (cachedKernel) {
8044
8594
  debugLog("[fluent zerodev] using cached kernel", {
@@ -8048,15 +8598,13 @@ function useFluentZeroDevAccount(hookOptions = {}) {
8048
8598
  return cachedKernel;
8049
8599
  }
8050
8600
  const canUseLocalSigner = ready && authenticated && Boolean(embeddedWallet);
8051
- const canUseHostedSigner = Boolean(hostedSigner);
8052
8601
  const canUseAuthorizationSession = signerMode === "silent" && Boolean(hookOptions.authorizationSession?.serializedPermissionAccount) && (hookOptions.authorizationSession?.expiresAt ?? 0) > Math.floor(Date.now() / 1e3);
8053
- if (!canUseLocalSigner && !canUseHostedSigner && !canUseAuthorizationSession) {
8602
+ if (!canUseLocalSigner && !canUseAuthorizationSession) {
8054
8603
  const nextError = new Error(getZeroDevReadinessMessage({
8055
8604
  ready,
8056
8605
  authenticated,
8057
8606
  embeddedWalletCount: wallets.filter((wallet) => wallet.walletClientType === "privy").length,
8058
- walletCount: wallets.length,
8059
- hostedSignerAvailable: canUseHostedSigner
8607
+ walletCount: wallets.length
8060
8608
  }));
8061
8609
  debugWarn("[fluent zerodev] initialize blocked", {
8062
8610
  message: nextError.message,
@@ -8073,34 +8621,41 @@ function useFluentZeroDevAccount(hookOptions = {}) {
8073
8621
  debugLog("[fluent zerodev] joining in-flight initialization");
8074
8622
  return initPromise.current[signerMode];
8075
8623
  }
8624
+ if (!zeroDevProjectId) {
8625
+ setKernels({});
8626
+ setSmartAccountReady(false);
8627
+ setError(null);
8628
+ debugWarn("[fluent zerodev] initialize blocked: project id missing");
8629
+ return null;
8630
+ }
8076
8631
  setSmartAccountReady(Boolean(activeKernel));
8077
8632
  setError(null);
8078
8633
  initPromise.current[signerMode] = (async () => {
8079
8634
  debugLog("[fluent zerodev] initializing", {
8080
8635
  signerMode,
8081
8636
  embeddedWallet: embeddedWallet?.address,
8082
- walletClientType: embeddedWallet?.walletClientType,
8083
- hostedSigner: hostedSigner?.address
8637
+ walletClientType: embeddedWallet?.walletClientType
8084
8638
  });
8085
8639
  const nextKernel = canUseAuthorizationSession ? await createFluentZeroDevAuthorizedSessionKernel(
8086
8640
  hookOptions.authorizationSession,
8087
- chain
8641
+ chain,
8642
+ readExecution
8088
8643
  ) : await createFluentZeroDevKernel({
8089
- wallet: canUseLocalSigner ? embeddedWallet : void 0,
8090
- hostedSigner: canUseLocalSigner ? void 0 : hostedSigner ?? void 0,
8644
+ wallet: embeddedWallet,
8091
8645
  signerMode,
8092
8646
  promptedSigners: {
8093
8647
  signMessage: promptSignMessage,
8094
8648
  signTypedData: promptSignTypedData
8095
8649
  },
8096
- chain
8650
+ chain,
8651
+ readExecution
8097
8652
  });
8098
8653
  if (hookOptions.sessionSmartAccountAddress && nextKernel.smartAccountAddress.toLowerCase() !== hookOptions.sessionSmartAccountAddress.toLowerCase()) {
8099
8654
  throw new Error("Fluent Connect signer does not control the connected smart account");
8100
8655
  }
8101
8656
  debugLog("[fluent zerodev] ready", {
8102
8657
  signerMode,
8103
- signerAddress: embeddedWallet?.address ?? hostedSigner?.address,
8658
+ signerAddress: embeddedWallet?.address,
8104
8659
  smartAccountAddress: nextKernel.smartAccountAddress
8105
8660
  });
8106
8661
  setKernels((current) => ({ ...current, [signerMode]: nextKernel }));
@@ -8127,13 +8682,14 @@ function useFluentZeroDevAccount(hookOptions = {}) {
8127
8682
  activeKernel,
8128
8683
  authenticated,
8129
8684
  embeddedWallet,
8130
- hostedSigner,
8131
8685
  kernels,
8132
8686
  hookOptions.sessionSmartAccountAddress,
8133
8687
  hookOptions.authorizationSession,
8134
8688
  promptSignMessage,
8135
8689
  promptSignTypedData,
8136
- ready
8690
+ readExecution,
8691
+ ready,
8692
+ zeroDevProjectId
8137
8693
  ]);
8138
8694
  useEffect(() => {
8139
8695
  if (!ready) return;
@@ -8147,9 +8703,6 @@ function useFluentZeroDevAccount(hookOptions = {}) {
8147
8703
  const sendTransaction = useCallback(
8148
8704
  async (request) => {
8149
8705
  const cachedKernel = kernels.prompt;
8150
- if (cachedKernel?.signerSource === "hosted" || !cachedKernel && hostedSigner && !(ready && authenticated && embeddedWallet)) {
8151
- hostedSigner?.prepare("always");
8152
- }
8153
8706
  const executionKernel = cachedKernel ?? await initialize2({ signerMode: "prompt" });
8154
8707
  if (!executionKernel) throw new Error(error?.message ?? "ZeroDev smart account is not ready");
8155
8708
  debugLog("[fluent zerodev] sendTransaction", {
@@ -8174,7 +8727,7 @@ function useFluentZeroDevAccount(hookOptions = {}) {
8174
8727
  throw err;
8175
8728
  }
8176
8729
  },
8177
- [authenticated, embeddedWallet, error, hostedSigner, initialize2, kernels.prompt, ready]
8730
+ [error, initialize2, kernels.prompt]
8178
8731
  );
8179
8732
  const createSponsoredClient = useCallback(
8180
8733
  (kernel, sponsorship) => (bearerToken) => buildSponsoredClient({
@@ -8183,28 +8736,26 @@ function useFluentZeroDevAccount(hookOptions = {}) {
8183
8736
  sponsorshipUrl: sponsorship.sponsorshipUrl,
8184
8737
  appId: sponsorship.appId,
8185
8738
  createPaymaster: createFluentZeroDevSponsoredPaymaster,
8186
- createClient: ({ kernel: target, paymaster }) => createKernelAccountClient({
8187
- account: target.account,
8188
- chain: target.chain,
8189
- bundlerTransport: createFluentBundlerTransport(target.zeroDevRpcUrl),
8190
- client: target.publicClient,
8191
- paymaster
8192
- })
8739
+ createClient: ({ kernel: target, paymaster }) => createFluentZeroDevKernelClient({ kernel: target, readExecution, paymaster })
8193
8740
  }),
8194
- []
8741
+ [readExecution]
8195
8742
  );
8196
8743
  const sendCalls = useCallback(
8197
8744
  async (calls, options, readyAccount) => {
8198
- const startedAt = performance.now();
8199
- debugLog("[fluent execution stage]", { stage: "setup" });
8745
+ const timingLog2 = (label, line) => {
8746
+ try {
8747
+ debugLog(label, line);
8748
+ } catch {
8749
+ }
8750
+ };
8751
+ const startedAt = monotonicNow();
8752
+ timingLog2("[fluent execution stage]", { stage: "setup" });
8200
8753
  validateUserOperationGas(options?.userOperationGas);
8754
+ const execution = readExecution();
8201
8755
  const signerMode = confirmationToSignerMode(options?.confirmation ?? "always");
8202
8756
  const readyKernel = readyAccount && typeof readyAccount === "object" && readyAccount.signerMode === signerMode ? readyAccount : void 0;
8203
8757
  const knownKernel = readyKernel ?? kernels[signerMode];
8204
- const hasAuthorizationSession = signerMode === "silent" && Boolean(hookOptions.authorizationSession?.serializedPermissionAccount) && (hookOptions.authorizationSession?.expiresAt ?? 0) > Math.floor(Date.now() / 1e3);
8205
- if (knownKernel?.signerSource === "hosted" || !knownKernel && !hasAuthorizationSession && hostedSigner && !(ready && authenticated && embeddedWallet)) {
8206
- hostedSigner?.prepare(options?.confirmation ?? "always");
8207
- }
8758
+ signerMode === "silent" && Boolean(hookOptions.authorizationSession?.serializedPermissionAccount) && (hookOptions.authorizationSession?.expiresAt ?? 0) > Math.floor(Date.now() / 1e3);
8208
8759
  const executionKernel = knownKernel ?? await initialize2({ signerMode, throwOnError: true });
8209
8760
  if (!executionKernel) throw new Error(error?.message ?? "ZeroDev smart account is not ready");
8210
8761
  const gasToken = options?.gasPayment?.symbol ? getFluentGasTokenAddress(options.gasPayment.symbol, network) : void 0;
@@ -8229,30 +8780,74 @@ function useFluentZeroDevAccount(hookOptions = {}) {
8229
8780
  value: (call.value ?? 0n).toString()
8230
8781
  }))
8231
8782
  });
8232
- setPromptSigningContext({
8233
- intent: "transaction",
8234
- gasTokenSymbol: options?.gasPayment?.symbol
8235
- });
8783
+ const signerChainCheck = execution.chainCheckBeforeSign ? readFluentSignerChainCheck(executionKernel.account) : void 0;
8784
+ const signingAccount = signerChainCheck ? withFluentSignerChainCheck(
8785
+ executionKernel.account,
8786
+ ["signUserOperation"],
8787
+ signerChainCheck
8788
+ ) : executionKernel.account;
8236
8789
  try {
8237
- const submissionStartedAt = performance.now();
8790
+ const submissionStartedAt = monotonicNow();
8791
+ const submissions = [];
8792
+ const submitOnce = async (client2, feeAttempt) => {
8793
+ const submission = await sendUserOperationWithTiming(
8794
+ client2,
8795
+ callArgs,
8796
+ options?.userOperationGas,
8797
+ (attempt) => {
8798
+ submissions.push(attempt);
8799
+ },
8800
+ feeAttempt
8801
+ );
8802
+ return submission.userOpHash;
8803
+ };
8804
+ let feeRetrySpent = false;
8805
+ const submit = async (client2) => {
8806
+ const feeAttempt = { feeSource: execution.feeSource };
8807
+ try {
8808
+ return await submitOnce(client2, feeAttempt);
8809
+ } catch (err) {
8810
+ if (feeRetrySpent) throw err;
8811
+ if (!isFluentFeeRejection(err)) throw err;
8812
+ feeRetrySpent = true;
8813
+ debugWarn("[fluent zerodev] fee rejected, retrying with the bundler's quote", {
8814
+ feeSource: feeAttempt.settledFeeSource
8815
+ });
8816
+ return await submitOnce(client2, { feeSource: "bundler" });
8817
+ }
8818
+ };
8819
+ let receivedAt;
8820
+ let receivedAtEpochMs;
8821
+ let inclusionAnchor;
8238
8822
  const waitForInclusion = async (client2, hash) => {
8239
- const inclusionStartedAt = performance.now();
8240
- debugLog("[fluent execution stage]", { stage: "submitted", userOpHash: hash });
8823
+ const waitStartedAt = monotonicNow();
8824
+ timingLog2("[fluent execution stage]", { stage: "submitted", userOpHash: hash });
8825
+ let settledReceiptSource;
8241
8826
  try {
8242
- return await client2.waitForUserOperationReceipt({
8827
+ const operation = await waitForFluentUserOperationReceipt({
8828
+ bundlerClient: client2,
8829
+ chainClient: executionKernel.publicClient,
8243
8830
  hash,
8244
- pollingInterval: 200,
8245
- timeout: 12e4
8831
+ entryPoint: executionKernel.account.entryPoint.address,
8832
+ anchorBlockNumber: inclusionAnchor,
8833
+ receiptSource: execution.receiptSource,
8834
+ onReceiptSource: (source) => {
8835
+ settledReceiptSource = source;
8836
+ }
8246
8837
  });
8838
+ receivedAt = monotonicNow();
8839
+ receivedAtEpochMs = epochNow();
8840
+ return operation;
8247
8841
  } finally {
8248
- debugLog("[fluent inclusion timing]", {
8842
+ timingLog2("[fluent inclusion timing]", {
8249
8843
  userOpHash: hash,
8250
- inclusionMs: performance.now() - inclusionStartedAt
8844
+ waitMs: span(waitStartedAt, monotonicNow()),
8845
+ receiptSource: settledReceiptSource
8251
8846
  });
8252
8847
  }
8253
8848
  };
8254
8849
  const callArgs = {
8255
- account: executionKernel.account,
8850
+ account: signingAccount,
8256
8851
  calls: preparedCalls.map((call) => ({
8257
8852
  to: call.to,
8258
8853
  data: call.data ?? "0x",
@@ -8261,8 +8856,11 @@ function useFluentZeroDevAccount(hookOptions = {}) {
8261
8856
  };
8262
8857
  const sponsorshipRefused = !gasToken && options?.gasPayment?.sponsorship === "never";
8263
8858
  const sponsorship = hookOptions.sponsorshipUrl && hookOptions.appId ? { sponsorshipUrl: hookOptions.sponsorshipUrl, appId: hookOptions.appId } : null;
8264
- const executionClient = gasToken ? createFluentZeroDevErc20ExecutionClient(executionKernel, gasToken) : executionKernel.client;
8859
+ const executionClient = gasToken ? createFluentZeroDevErc20ExecutionClient(executionKernel, gasToken, readExecution) : executionKernel.client;
8265
8860
  const callSponsored = !gasToken && !sponsorshipRefused && sponsorship && !sponsorshipUnavailable.current;
8861
+ if (execution.receiptSource === "chain") {
8862
+ inclusionAnchor = await readFluentInclusionAnchor(executionKernel.publicClient);
8863
+ }
8266
8864
  let sponsorshipReason;
8267
8865
  let settlementClient = executionClient;
8268
8866
  let userOpHash;
@@ -8278,10 +8876,14 @@ function useFluentZeroDevAccount(hookOptions = {}) {
8278
8876
  log: sponsorshipLog
8279
8877
  }),
8280
8878
  buildClient: createSponsoredClient(executionKernel, sponsorship),
8281
- sendSponsored: (client2) => sendUserOperationWithTiming(client2, callArgs, options?.userOperationGas),
8282
- sendOwnGas: () => sendUserOperationWithTiming(executionKernel.client, callArgs, options?.userOperationGas),
8879
+ sendSponsored: (client2) => submit(client2),
8880
+ sendOwnGas: () => submit(executionKernel.client),
8283
8881
  ownGasClient: executionKernel.client,
8284
8882
  waitFor: ({ client: client2, userOpHash: hash }) => waitForInclusion(client2, hash),
8883
+ // A fee the bundler refused is the operation's, not the paymaster's: `submit` has
8884
+ // already answered it with ZeroDev's own quote, so an own-gas submission here
8885
+ // would be a third operation over a fee the account cannot change.
8886
+ isOperationFailure: isFluentFeeRejection,
8285
8887
  disableSponsorship: () => {
8286
8888
  sponsorshipUnavailable.current = true;
8287
8889
  },
@@ -8294,7 +8896,7 @@ function useFluentZeroDevAccount(hookOptions = {}) {
8294
8896
  else if (!gasToken && sponsorship && sponsorshipUnavailable.current) {
8295
8897
  sponsorshipReason = "unauthorized";
8296
8898
  }
8297
- userOpHash = await sendUserOperationWithTiming(executionClient, callArgs, options?.userOperationGas);
8899
+ userOpHash = await submit(executionClient);
8298
8900
  debugLog("[fluent zerodev] sendCalls userOp submitted", { userOpHash });
8299
8901
  receipt = await waitForInclusion(settlementClient, userOpHash);
8300
8902
  }
@@ -8310,28 +8912,44 @@ function useFluentZeroDevAccount(hookOptions = {}) {
8310
8912
  paymaster,
8311
8913
  sponsorshipReason
8312
8914
  });
8313
- if (!receipt.success) {
8314
- throw new Error(receipt.reason ?? `UserOperation ${userOpHash} execution failed`);
8315
- }
8316
- debugLog("[fluent execution timing]", {
8317
- setupMs: submissionStartedAt - startedAt,
8318
- totalMs: performance.now() - startedAt,
8915
+ const timing = receivedAt === void 0 || receivedAtEpochMs === void 0 ? (
8916
+ // Only an unreadable clock gets here. Standing in a fresh instant would be worse
8917
+ // than an absent timeline: the stages would still look measured.
8918
+ void 0
8919
+ ) : await closeSendTiming({
8920
+ attempts: submissions,
8921
+ settledUserOpHash: userOpHash,
8922
+ receivedAt,
8923
+ receivedAtEpochMs,
8924
+ blockNumber: receipt.receipt.blockNumber,
8925
+ // The widget chain's own public client, the same transport `publicClient` was
8926
+ // built with. Reached only after `receivedAt` was taken, so it inflates no stage.
8927
+ getBlock: ({ blockNumber }) => executionKernel.publicClient.getBlock({ blockNumber })
8928
+ });
8929
+ timingLog2("[fluent execution timing]", {
8930
+ setupMs: span(startedAt, submissionStartedAt),
8931
+ // The whole call including kernel and authentication setup, which `timing.totalMs`
8932
+ // deliberately excludes — the two are different spans and say so.
8933
+ elapsedMs: span(startedAt, monotonicNow()),
8934
+ timing,
8319
8935
  userOpHash,
8320
8936
  hash: receipt.receipt.transactionHash
8321
8937
  });
8938
+ if (!receipt.success) {
8939
+ throw new Error(receipt.reason ?? `UserOperation ${userOpHash} execution failed`);
8940
+ }
8322
8941
  return {
8323
8942
  hash: receipt.receipt.transactionHash,
8324
8943
  receipt: receipt.receipt,
8325
8944
  userOpHash,
8326
8945
  sponsored,
8327
8946
  sponsorshipReason,
8328
- paymaster
8947
+ paymaster,
8948
+ timing
8329
8949
  };
8330
8950
  } catch (err) {
8331
8951
  debugError("[fluent zerodev] sendCalls failed", err);
8332
8952
  throw err;
8333
- } finally {
8334
- clearPromptSigningContext();
8335
8953
  }
8336
8954
  },
8337
8955
  [
@@ -8339,7 +8957,6 @@ function useFluentZeroDevAccount(hookOptions = {}) {
8339
8957
  createSponsoredClient,
8340
8958
  embeddedWallet,
8341
8959
  error,
8342
- hostedSigner,
8343
8960
  hookOptions.authorizationSession,
8344
8961
  hookOptions.appId,
8345
8962
  hookOptions.sponsorshipTokenSource,
@@ -8347,6 +8964,7 @@ function useFluentZeroDevAccount(hookOptions = {}) {
8347
8964
  initialize2,
8348
8965
  kernels,
8349
8966
  network,
8967
+ readExecution,
8350
8968
  ready
8351
8969
  ]
8352
8970
  );
@@ -8354,16 +8972,16 @@ function useFluentZeroDevAccount(hookOptions = {}) {
8354
8972
  const signerMode = confirmationToSignerMode(options.confirmation ?? "always");
8355
8973
  if (kernels[signerMode]) return kernels[signerMode];
8356
8974
  if (!ready) throw new Error("Privy wallet context is still loading");
8357
- if (!authenticated && !hostedSigner) {
8975
+ if (!authenticated) {
8358
8976
  login();
8359
8977
  throw new Error("Complete wallet login, then submit the transaction again");
8360
8978
  }
8361
8979
  const executionKernel = await initialize2({ signerMode, throwOnError: true });
8362
8980
  if (!executionKernel) throw new Error(error?.message ?? "ZeroDev smart account is not ready");
8363
8981
  return executionKernel;
8364
- }, [authenticated, error, hostedSigner, initialize2, kernels, login, ready]);
8982
+ }, [authenticated, error, initialize2, kernels, login, ready]);
8365
8983
  return {
8366
- smartAccountEnabled: Boolean(FLUENT_CONNECT_ZERODEV_PROJECT_ID),
8984
+ smartAccountEnabled: Boolean(zeroDevProjectId),
8367
8985
  smartAccountReady,
8368
8986
  smartAccountAddress: activeKernel?.smartAccountAddress,
8369
8987
  signerAddress: embeddedWallet?.address ?? hookOptions.sessionSignerAddress,
@@ -8384,7 +9002,7 @@ var sponsorshipLog = {
8384
9002
  debug: (message2, detail) => debugLog(message2, detail),
8385
9003
  warn: (message2, detail) => debugWarn(message2, detail)
8386
9004
  };
8387
- var USER_OPERATION_EVENT_TOPIC = toEventSelector(
9005
+ var USER_OPERATION_EVENT_TOPIC2 = toEventSelector(
8388
9006
  parseAbiItem(
8389
9007
  "event UserOperationEvent(bytes32 indexed userOpHash, address indexed sender, address indexed paymaster, uint256 nonce, bool success, uint256 actualGasCost, uint256 actualGasUsed)"
8390
9008
  )
@@ -8392,7 +9010,7 @@ var USER_OPERATION_EVENT_TOPIC = toEventSelector(
8392
9010
  function readUserOperationPaymaster(receipt) {
8393
9011
  if (receipt.paymaster) return getAddress(receipt.paymaster);
8394
9012
  const event = receipt.logs.find(
8395
- (log) => log.topics[0]?.toLowerCase() === USER_OPERATION_EVENT_TOPIC && log.topics[1]?.toLowerCase() === receipt.userOpHash.toLowerCase()
9013
+ (log) => log.topics[0]?.toLowerCase() === USER_OPERATION_EVENT_TOPIC2 && log.topics[1]?.toLowerCase() === receipt.userOpHash.toLowerCase()
8396
9014
  );
8397
9015
  const topic = event?.topics[3];
8398
9016
  if (!topic || topic.length !== 66) return void 0;
@@ -8400,7 +9018,6 @@ function readUserOperationPaymaster(receipt) {
8400
9018
  }
8401
9019
  function getZeroDevReadinessMessage(params) {
8402
9020
  if (!params.ready) return "Privy wallet context is still loading";
8403
- if (params.hostedSignerAvailable) return "Fluent hosted signer is preparing";
8404
9021
  if (!params.authenticated) return "Fluent session is connected, but Privy embedded wallet is not authenticated on this page";
8405
9022
  if (params.embeddedWalletCount === 0) {
8406
9023
  return `Privy is authenticated, but no embedded wallet is available (${params.walletCount} linked wallets found)`;
@@ -8456,8 +9073,30 @@ async function createFluentZeroDevPermissionSession(params) {
8456
9073
  function confirmationToSignerMode(confirmation) {
8457
9074
  return confirmation === "session" ? "silent" : "prompt";
8458
9075
  }
8459
- async function createFluentZeroDevAuthorizedSessionKernel(authorizationSession, chain) {
8460
- const zeroDevRpcUrl = `https://rpc.zerodev.app/api/v3/${FLUENT_CONNECT_ZERODEV_PROJECT_ID}/chain/${chain.id}`;
9076
+ function createFluentZeroDevKernelClient(params) {
9077
+ const { kernel, readExecution, paymaster } = params;
9078
+ return createKernelAccountClient({
9079
+ account: kernel.account,
9080
+ chain: kernel.chain,
9081
+ bundlerTransport: createFluentBundlerTransport(kernel.zeroDevRpcUrl),
9082
+ client: kernel.publicClient,
9083
+ ...paymaster ? { paymaster } : {},
9084
+ userOperation: {
9085
+ estimateFeesPerGas: createFluentUserOperationFeeHook({
9086
+ // The widget chain's own public client, so the quote and the account's reads travel
9087
+ // the same transport and its retry policy.
9088
+ readGasPrice: () => kernel.publicClient.getGasPrice(),
9089
+ readFeeSource: () => readExecution().feeSource
9090
+ })
9091
+ }
9092
+ });
9093
+ }
9094
+ async function createFluentZeroDevAuthorizedSessionKernel(authorizationSession, chain, readExecution) {
9095
+ const projectId = getFluentZeroDevProjectId(getFluentWidgetNetworkForChainId(chain.id));
9096
+ if (!projectId) {
9097
+ throw new Error("Fluent ZeroDev project is not configured");
9098
+ }
9099
+ const zeroDevRpcUrl = `https://rpc.zerodev.app/api/v3/${projectId}/chain/${chain.id}`;
8461
9100
  const publicClient = createPublicClient({
8462
9101
  chain,
8463
9102
  transport: createFluentRpcTransport(chain)
@@ -8473,11 +9112,9 @@ async function createFluentZeroDevAuthorizedSessionKernel(authorizationSession,
8473
9112
  authorizationSession.serializedPermissionAccount,
8474
9113
  sessionSigner
8475
9114
  );
8476
- const client2 = createKernelAccountClient({
8477
- account,
8478
- chain,
8479
- bundlerTransport: createFluentBundlerTransport(zeroDevRpcUrl),
8480
- client: publicClient
9115
+ const client2 = createFluentZeroDevKernelClient({
9116
+ kernel: { account, chain, publicClient, zeroDevRpcUrl },
9117
+ readExecution
8481
9118
  });
8482
9119
  return {
8483
9120
  account,
@@ -8491,43 +9128,38 @@ async function createFluentZeroDevAuthorizedSessionKernel(authorizationSession,
8491
9128
  };
8492
9129
  }
8493
9130
  async function createFluentZeroDevKernel(params) {
8494
- if (!params.wallet && !params.hostedSigner) throw new Error("Fluent signer is unavailable");
8495
- if (params.wallet) {
8496
- debugLog("[fluent zerodev] ensuring Fluent chain", params.chain.id);
8497
- await ensureWalletOnFluentChain(params.wallet, params.chain);
8498
- debugLog("[fluent zerodev] Fluent chain ready", params.chain.id);
8499
- }
8500
- const zeroDevRpcUrl = `https://rpc.zerodev.app/api/v3/${FLUENT_CONNECT_ZERODEV_PROJECT_ID}/chain/${params.chain.id}`;
9131
+ const projectId = getFluentZeroDevProjectId(getFluentWidgetNetworkForChainId(params.chain.id));
9132
+ if (!projectId) throw new Error("Fluent ZeroDev project is not configured");
9133
+ if (!params.wallet) throw new Error("Fluent signer is unavailable");
9134
+ debugLog("[fluent zerodev] ensuring Fluent chain", params.chain.id);
9135
+ await ensureWalletOnFluentChain(params.wallet, params.chain);
9136
+ debugLog("[fluent zerodev] Fluent chain ready", params.chain.id);
9137
+ const zeroDevRpcUrl = `https://rpc.zerodev.app/api/v3/${projectId}/chain/${params.chain.id}`;
8501
9138
  const publicClient = createPublicClient({
8502
9139
  chain: params.chain,
8503
9140
  transport: createFluentRpcTransport(params.chain)
8504
9141
  });
8505
9142
  const entryPoint = getEntryPoint("0.7");
8506
- let signer;
8507
- if (params.hostedSigner) {
8508
- signer = toHostedSignerLocalAccount(params.hostedSigner, params.signerMode);
8509
- } else if (params.wallet && params.signerMode === "prompt") {
8510
- signer = toPromptedPrivyLocalAccount(params.wallet, params.promptedSigners, params.chain);
8511
- } else if (params.wallet) {
8512
- signer = toSilentPrivyLocalAccount(params.wallet, params.chain);
8513
- } else {
8514
- throw new Error("Fluent signer is unavailable");
8515
- }
9143
+ const signer = params.signerMode === "prompt" ? toPromptedPrivyLocalAccount(params.wallet, params.promptedSigners) : toSilentPrivyLocalAccount(params.wallet);
8516
9144
  const ecdsaValidator = await signerToEcdsaValidator(publicClient, {
8517
9145
  signer,
8518
9146
  entryPoint,
8519
9147
  kernelVersion: KERNEL_V3_3
8520
9148
  });
8521
- const account = await createKernelAccount(publicClient, {
9149
+ const derivedAccount = await createKernelAccount(publicClient, {
8522
9150
  entryPoint,
8523
9151
  plugins: { sudo: ecdsaValidator },
8524
9152
  kernelVersion: KERNEL_V3_3
8525
9153
  });
8526
- const client2 = createKernelAccountClient({
8527
- account,
9154
+ const account = toFluentSigningAccount({
9155
+ account: derivedAccount,
9156
+ wallet: params.wallet,
8528
9157
  chain: params.chain,
8529
- bundlerTransport: createFluentBundlerTransport(zeroDevRpcUrl),
8530
- client: publicClient
9158
+ readExecution: params.readExecution
9159
+ });
9160
+ const client2 = createFluentZeroDevKernelClient({
9161
+ kernel: { account, chain: params.chain, publicClient, zeroDevRpcUrl },
9162
+ readExecution: params.readExecution
8531
9163
  });
8532
9164
  return {
8533
9165
  account,
@@ -8537,87 +9169,29 @@ async function createFluentZeroDevKernel(params) {
8537
9169
  zeroDevRpcUrl,
8538
9170
  chain: params.chain,
8539
9171
  signerMode: params.signerMode,
8540
- signerSource: params.hostedSigner ? "hosted" : "privy"
8541
- };
8542
- }
8543
- function toHostedSignerLocalAccount(signer, signerMode) {
8544
- const confirmation = signerMode === "silent" ? "session" : "always";
8545
- const source = {
8546
- address: signer.address,
8547
- async signMessage({ message: message2 }) {
8548
- return signer.signMessage(formatSignableMessageForPrivy(message2), confirmation);
8549
- },
8550
- async signTransaction() {
8551
- throw new Error("Fluent ZeroDev signer does not sign raw transactions");
8552
- },
8553
- async signTypedData(typedData) {
8554
- return signer.signTypedData(
8555
- {
8556
- domain: typedData.domain,
8557
- types: typedData.types,
8558
- primaryType: typedData.primaryType,
8559
- message: typedData.message
8560
- },
8561
- confirmation
8562
- );
8563
- }
9172
+ signerSource: "privy"
8564
9173
  };
8565
- return toAccount(source);
8566
9174
  }
8567
- function createFluentZeroDevErc20ExecutionClient(kernel, gasToken) {
8568
- return createKernelAccountClient({
8569
- account: kernel.account,
8570
- chain: kernel.chain,
8571
- bundlerTransport: createFluentBundlerTransport(kernel.zeroDevRpcUrl),
8572
- client: kernel.publicClient,
9175
+ function createFluentZeroDevErc20ExecutionClient(kernel, gasToken, readExecution) {
9176
+ return createFluentZeroDevKernelClient({
9177
+ kernel,
9178
+ readExecution,
8573
9179
  paymaster: createFluentZeroDevErc20Paymaster({
8574
9180
  chain: kernel.chain,
8575
9181
  gasToken
8576
9182
  })
8577
9183
  });
8578
9184
  }
8579
- var promptSigningContext = {};
8580
- function setPromptSigningContext(context) {
8581
- promptSigningContext = context;
8582
- }
8583
- function clearPromptSigningContext() {
8584
- promptSigningContext = {};
8585
- }
8586
- async function withFluentSignaturePrompt(sign) {
8587
- setPromptSigningContext({ intent: "signature" });
8588
- try {
8589
- return await sign();
8590
- } finally {
8591
- clearPromptSigningContext();
8592
- }
8593
- }
8594
- function buildPromptSigningUiOptions() {
8595
- if (promptSigningContext.intent === "signature") {
8596
- return {
8597
- showWalletUIs: true,
8598
- title: "Sign with Fluent",
8599
- description: "Sign this request with your Fluent account. Nothing is sent on chain.",
8600
- buttonText: "Sign"
8601
- };
8602
- }
8603
- const gasTokenSymbol = promptSigningContext.gasTokenSymbol;
8604
- return {
8605
- showWalletUIs: true,
8606
- title: "Confirm Fluent transaction",
8607
- description: gasTokenSymbol ? `Gas will be paid in ${gasTokenSymbol}. Confirm this Fluent transaction.` : "Confirm this Fluent transaction.",
8608
- buttonText: "Sign"
8609
- };
8610
- }
8611
- function toPromptedPrivyLocalAccount(wallet, promptedSigners, chain) {
9185
+ var PROMPT_MODE_PRIVY_UI_OPTIONS = { showWalletUIs: false };
9186
+ function toPromptedPrivyLocalAccount(wallet, promptedSigners) {
8612
9187
  const source = {
8613
9188
  address: wallet.address,
8614
9189
  async signMessage({ message: message2 }) {
8615
- await ensureWalletOnFluentChain(wallet, chain);
8616
9190
  const { signature } = await promptedSigners.signMessage(
8617
9191
  { message: formatSignableMessageForPrivy(message2) },
8618
9192
  {
8619
9193
  address: wallet.address,
8620
- uiOptions: buildPromptSigningUiOptions()
9194
+ uiOptions: PROMPT_MODE_PRIVY_UI_OPTIONS
8621
9195
  }
8622
9196
  );
8623
9197
  return signature;
@@ -8626,7 +9200,6 @@ function toPromptedPrivyLocalAccount(wallet, promptedSigners, chain) {
8626
9200
  throw new Error("Fluent ZeroDev signer does not sign raw transactions");
8627
9201
  },
8628
9202
  async signTypedData(typedData) {
8629
- await ensureWalletOnFluentChain(wallet, chain);
8630
9203
  const { signature } = await promptedSigners.signTypedData(
8631
9204
  {
8632
9205
  domain: typedData.domain,
@@ -8636,7 +9209,7 @@ function toPromptedPrivyLocalAccount(wallet, promptedSigners, chain) {
8636
9209
  },
8637
9210
  {
8638
9211
  address: wallet.address,
8639
- uiOptions: buildPromptSigningUiOptions()
9212
+ uiOptions: PROMPT_MODE_PRIVY_UI_OPTIONS
8640
9213
  }
8641
9214
  );
8642
9215
  return signature;
@@ -8644,7 +9217,7 @@ function toPromptedPrivyLocalAccount(wallet, promptedSigners, chain) {
8644
9217
  };
8645
9218
  return toAccount(source);
8646
9219
  }
8647
- function toSilentPrivyLocalAccount(wallet, chain) {
9220
+ function toSilentPrivyLocalAccount(wallet) {
8648
9221
  const source = {
8649
9222
  address: wallet.address,
8650
9223
  async signMessage({ message: message2 }) {
@@ -8652,7 +9225,6 @@ function toSilentPrivyLocalAccount(wallet, chain) {
8652
9225
  signerAddress: wallet.address,
8653
9226
  messageKind: typeof message2 === "string" ? "string" : "raw" in message2 ? "raw" : typeof message2
8654
9227
  });
8655
- await ensureWalletOnFluentChain(wallet, chain);
8656
9228
  const provider = await wallet.getEthereumProvider();
8657
9229
  if (!provider?.request) throw new Error("Fluent embedded wallet provider is unavailable");
8658
9230
  const formattedMessage = formatSignableMessageForPrivy(message2);
@@ -8680,7 +9252,6 @@ function toSilentPrivyLocalAccount(wallet, chain) {
8680
9252
  signerAddress: wallet.address,
8681
9253
  primaryType: typedData.primaryType
8682
9254
  });
8683
- await ensureWalletOnFluentChain(wallet, chain);
8684
9255
  const provider = await wallet.getEthereumProvider();
8685
9256
  if (!provider?.request) throw new Error("Fluent embedded wallet provider is unavailable");
8686
9257
  try {
@@ -8922,14 +9493,6 @@ function createFluentIframeRpcHandler(executor) {
8922
9493
  throw new FluentIframeRpcError(4100, `${method}: ${candidate} is not the signed-in account`);
8923
9494
  }
8924
9495
  };
8925
- const assertDirectMode = () => {
8926
- if (executor.authMode === "hosted") {
8927
- throw new FluentAuthError(
8928
- "hosted_not_supported",
8929
- 'The iframe bridge needs authMode: "direct" \u2014 there is no hosted signer to ask.'
8930
- );
8931
- }
8932
- };
8933
9496
  const parseTypedData = (payload, method) => {
8934
9497
  const value = typeof payload === "string" ? safeJsonParse(payload) : payload;
8935
9498
  if (!value || typeof value !== "object") {
@@ -8958,26 +9521,22 @@ function createFluentIframeRpcHandler(executor) {
8958
9521
  return toHex(executor.chainId);
8959
9522
  case "eth_signTypedData_v4":
8960
9523
  case "eth_signTypedData_v3": {
8961
- assertDirectMode();
8962
9524
  assertOwnAddress(params[0], method);
8963
9525
  return executor.sign.signTypedData(parseTypedData(params[1], method));
8964
9526
  }
8965
9527
  case "eth_signTypedData": {
8966
- assertDirectMode();
8967
9528
  const [first, second] = params;
8968
9529
  const addressFirst = typeof first === "string" && isAddress(first);
8969
9530
  assertOwnAddress(addressFirst ? first : second, method);
8970
9531
  return executor.sign.signTypedData(parseTypedData(addressFirst ? second : first, method));
8971
9532
  }
8972
9533
  case "personal_sign": {
8973
- assertDirectMode();
8974
9534
  assertOwnAddress(params[1], method);
8975
9535
  const message2 = params[0];
8976
9536
  if (typeof message2 !== "string") throw invalid(method, "a message");
8977
9537
  return executor.sign.signMessage({ message: isHex(message2) ? { raw: message2 } : message2 });
8978
9538
  }
8979
9539
  case "eth_sendTransaction": {
8980
- assertDirectMode();
8981
9540
  const tx = params[0];
8982
9541
  if (!tx || typeof tx !== "object") throw invalid(method, "a transaction object");
8983
9542
  const { from, to, data, value } = tx;
@@ -9058,8 +9617,7 @@ function toRpcError(error) {
9058
9617
  if (error instanceof FluentIframeRpcError) return { code: error.code, message: error.message };
9059
9618
  if (error instanceof FluentReviewRejectedError) return { code: 4001, message: error.message };
9060
9619
  if (error instanceof FluentAuthError) {
9061
- const code = error.code === "hosted_not_supported" ? 4200 : -32603;
9062
- return { code, message: `${error.code}: ${error.message}` };
9620
+ return { code: -32603, message: `${error.code}: ${error.message}` };
9063
9621
  }
9064
9622
  const message2 = error instanceof Error ? error.message : String(error);
9065
9623
  return { code: -32603, message: message2 };
@@ -9078,7 +9636,7 @@ function exactOrigin(candidate) {
9078
9636
  return origin;
9079
9637
  }
9080
9638
  function useFluentIframeBridge(iframeRef, { allowedOrigin }) {
9081
- const { widget, authMode } = useFluentWidget();
9639
+ const { widget } = useFluentWidget();
9082
9640
  const { chain } = useFluentWidgetNetwork();
9083
9641
  const widgetRef = useRef(widget);
9084
9642
  widgetRef.current = widget;
@@ -9096,7 +9654,6 @@ function useFluentIframeBridge(iframeRef, { allowedOrigin }) {
9096
9654
  const bridge = createFluentIframeBridge(iframe, {
9097
9655
  allowedOrigin,
9098
9656
  executor: {
9099
- authMode,
9100
9657
  account: () => widgetRef.current.account,
9101
9658
  chainId: chain.id,
9102
9659
  sign: {
@@ -9113,7 +9670,7 @@ function useFluentIframeBridge(iframeRef, { allowedOrigin }) {
9113
9670
  bridge.dispose();
9114
9671
  bridgeRef.current = null;
9115
9672
  };
9116
- }, [iframeRef, allowedOrigin, authMode, chain.id, rpc]);
9673
+ }, [iframeRef, allowedOrigin, chain.id, rpc]);
9117
9674
  const address = widget.account.address;
9118
9675
  useEffect(() => {
9119
9676
  bridgeRef.current?.notifyAccountsChanged(address ? [address] : []);
@@ -9121,7 +9678,7 @@ function useFluentIframeBridge(iframeRef, { allowedOrigin }) {
9121
9678
  }
9122
9679
 
9123
9680
  // package.json
9124
- var version = "0.4.2";
9681
+ var version = "0.5.1";
9125
9682
 
9126
9683
  // src/core/analytics.ts
9127
9684
  var INSTANCE_NAME = "fluent";
@@ -9205,7 +9762,6 @@ function createTracker(config, getContext) {
9205
9762
  const base = {
9206
9763
  app_id: config.appId,
9207
9764
  network: config.network,
9208
- auth_mode: config.authMode,
9209
9765
  source: config.source,
9210
9766
  campaign: config.campaign,
9211
9767
  sdk_version: version
@@ -9250,9 +9806,9 @@ async function getBridgeTransactions({
9250
9806
  }
9251
9807
  return await response.json();
9252
9808
  }
9253
- function findBridgeTxBySentHash(history2, sentTxHash) {
9809
+ function findBridgeTxBySentHash(history, sentTxHash) {
9254
9810
  const target = sentTxHash.toLowerCase();
9255
- return history2.items.find((item) => item.sent_tx_hash?.toLowerCase() === target);
9811
+ return history.items.find((item) => item.sent_tx_hash?.toLowerCase() === target);
9256
9812
  }
9257
9813
  var BRIDGE_TX_HISTORY_PAGE_SIZE = 10;
9258
9814
  function useBridgeTxHistoryPages({
@@ -9521,51 +10077,160 @@ function clearInlineOAuth() {
9521
10077
  } catch {
9522
10078
  }
9523
10079
  }
9524
- function connectDescription(appName) {
9525
- return `Use Fluent Connect to access ${appName?.trim() || "this app"}.`;
10080
+ function Dialog({ ...props }) {
10081
+ return /* @__PURE__ */ jsx(Dialog$1.Root, { "data-slot": "dialog", ...props });
9526
10082
  }
9527
- var privacyPolicyUrl = "https://cdn.prod.website-files.com/67ae0a445cb83ac7024dc85a/69bd38dc078b1bd9bb296af3_Fluent%20Foundation%20-%20Privacy%20Policy%20%5BDRAFT%5D.docx.pdf";
9528
- function FluentBranch({
9529
- children,
9530
- className
10083
+ function DialogTrigger({ ...props }) {
10084
+ return /* @__PURE__ */ jsx(Dialog$1.Trigger, { "data-slot": "dialog-trigger", ...props });
10085
+ }
10086
+ function DialogPortal({ container, children, ...props }) {
10087
+ return /* @__PURE__ */ jsx(
10088
+ Dialog$1.Portal,
10089
+ {
10090
+ "data-slot": "dialog-portal",
10091
+ container: useFluentModalPortalContainer(container),
10092
+ ...props,
10093
+ children: /* @__PURE__ */ jsx(FluentTopLayerSlot, { children })
10094
+ }
10095
+ );
10096
+ }
10097
+ function DialogClose({ ...props }) {
10098
+ return /* @__PURE__ */ jsx(Dialog$1.Close, { "data-slot": "dialog-close", ...props });
10099
+ }
10100
+ function DialogOverlay({
10101
+ className,
10102
+ ...props
9531
10103
  }) {
9532
- return /* @__PURE__ */ jsxs("div", { className: cn("flex flex-col gap-2", className), children: [
9533
- children,
9534
- /* @__PURE__ */ jsxs("p", { className: "px-2.5 text-center text-[10px] leading-snug text-white/50", children: [
9535
- "Gasless transactions and quick sign.",
9536
- /* @__PURE__ */ jsx("br", {}),
9537
- "By continuing, you accept our",
9538
- " ",
9539
- /* @__PURE__ */ jsx(
9540
- "a",
9541
- {
9542
- href: privacyPolicyUrl,
9543
- target: "_blank",
9544
- rel: "noopener noreferrer",
9545
- className: "whitespace-nowrap text-white/70 underline underline-offset-2 hover:text-white",
9546
- children: "Privacy Policy"
9547
- }
10104
+ return /* @__PURE__ */ jsx(
10105
+ Dialog$1.Backdrop,
10106
+ {
10107
+ "data-slot": "dialog-overlay",
10108
+ className: cn(
10109
+ "fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",
10110
+ className
9548
10111
  ),
9549
- "."
9550
- ] })
10112
+ ...props
10113
+ }
10114
+ );
10115
+ }
10116
+ function DialogContent({
10117
+ className,
10118
+ children,
10119
+ showCloseButton = true,
10120
+ ...props
10121
+ }) {
10122
+ return /* @__PURE__ */ jsxs(DialogPortal, { children: [
10123
+ /* @__PURE__ */ jsx(DialogOverlay, {}),
10124
+ /* @__PURE__ */ jsxs(
10125
+ Dialog$1.Popup,
10126
+ {
10127
+ "data-slot": "dialog-content",
10128
+ className: cn(
10129
+ "fixed top-1/2 left-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-4 rounded-3xl bg-popover p-4 text-sm text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
10130
+ className
10131
+ ),
10132
+ ...props,
10133
+ children: [
10134
+ children,
10135
+ showCloseButton && /* @__PURE__ */ jsxs(
10136
+ Dialog$1.Close,
10137
+ {
10138
+ "data-slot": "dialog-close",
10139
+ render: /* @__PURE__ */ jsx(
10140
+ Button,
10141
+ {
10142
+ variant: "ghost",
10143
+ className: "absolute top-3.5 right-3.5 z-50 rounded-full",
10144
+ size: "icon-sm"
10145
+ }
10146
+ ),
10147
+ children: [
10148
+ /* @__PURE__ */ jsx(XIcon, {}),
10149
+ /* @__PURE__ */ jsx("span", { className: "sr-only", children: "Close" })
10150
+ ]
10151
+ }
10152
+ )
10153
+ ]
10154
+ }
10155
+ )
9551
10156
  ] });
9552
10157
  }
9553
- function OrDivider() {
10158
+ function DialogHeader({ className, ...props }) {
10159
+ return /* @__PURE__ */ jsx(
10160
+ "div",
10161
+ {
10162
+ "data-slot": "dialog-header",
10163
+ className: cn("flex flex-col gap-2", className),
10164
+ ...props
10165
+ }
10166
+ );
10167
+ }
10168
+ function DialogFooter({
10169
+ className,
10170
+ showCloseButton = false,
10171
+ children,
10172
+ ...props
10173
+ }) {
9554
10174
  return /* @__PURE__ */ jsxs(
9555
10175
  "div",
9556
10176
  {
9557
- className: "flex items-center gap-3 px-1 py-2 text-[11px] font-medium uppercase tracking-wide text-white/40",
9558
- "aria-hidden": true,
10177
+ "data-slot": "dialog-footer",
10178
+ className: cn(
10179
+ "-mx-4 -mb-4 flex flex-col-reverse gap-2 rounded-b-xl border-t bg-muted/50 p-4 sm:flex-row sm:justify-end",
10180
+ className
10181
+ ),
10182
+ ...props,
9559
10183
  children: [
9560
- /* @__PURE__ */ jsx("span", { className: "h-px flex-1 bg-white/10" }),
9561
- "or",
9562
- /* @__PURE__ */ jsx("span", { className: "h-px flex-1 bg-white/10" })
10184
+ children,
10185
+ showCloseButton && /* @__PURE__ */ jsxs(Dialog$1.Close, { render: /* @__PURE__ */ jsx(Button, { variant: "outline" }), children: [
10186
+ /* @__PURE__ */ jsx(XIcon, { className: "size-4 shrink-0", "aria-hidden": true }),
10187
+ "Close"
10188
+ ] })
9563
10189
  ]
9564
10190
  }
9565
10191
  );
9566
10192
  }
9567
- function WalletBranchNote() {
9568
- return /* @__PURE__ */ jsx("p", { className: "px-2.5 text-center text-[10px] leading-snug text-white/50", children: "Existing wallet. Manual signing, gas fees may apply." });
10193
+ function DialogTitle({ className, ...props }) {
10194
+ return /* @__PURE__ */ jsx(
10195
+ Dialog$1.Title,
10196
+ {
10197
+ "data-slot": "dialog-title",
10198
+ className: cn(
10199
+ "text-base leading-none font-medium",
10200
+ className
10201
+ ),
10202
+ ...props
10203
+ }
10204
+ );
10205
+ }
10206
+ function DialogDescription({
10207
+ className,
10208
+ ...props
10209
+ }) {
10210
+ return /* @__PURE__ */ jsx(
10211
+ Dialog$1.Description,
10212
+ {
10213
+ "data-slot": "dialog-description",
10214
+ className: cn(
10215
+ "text-sm text-muted-foreground *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground",
10216
+ className
10217
+ ),
10218
+ ...props
10219
+ }
10220
+ );
10221
+ }
10222
+ function Label({ className, ...props }) {
10223
+ return /* @__PURE__ */ jsx(
10224
+ "label",
10225
+ {
10226
+ "data-slot": "label",
10227
+ className: cn(
10228
+ "flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
10229
+ className
10230
+ ),
10231
+ ...props
10232
+ }
10233
+ );
9569
10234
  }
9570
10235
  var icons = {
9571
10236
  google: (props) => /* @__PURE__ */ jsxs("svg", { viewBox: "0 0 24 24", fill: "none", xmlns: "http://www.w3.org/2000/svg", ...props, children: [
@@ -9638,177 +10303,89 @@ var icons = {
9638
10303
  ] }),
9639
10304
  /* @__PURE__ */ jsxs("linearGradient", { id: "rabby__c", x1: "14.023", x2: "5.231", y1: "16.707", y2: "11.849", gradientUnits: "userSpaceOnUse", children: [
9640
10305
  /* @__PURE__ */ jsx("stop", { stopColor: "#8697FF" }),
9641
- /* @__PURE__ */ jsx("stop", { offset: "1", stopColor: "#8697FF", stopOpacity: "0" })
9642
- ] }),
9643
- /* @__PURE__ */ jsxs("linearGradient", { id: "rabby__d", x1: "9.054", x2: "15.173", y1: "11.617", y2: "19.089", gradientUnits: "userSpaceOnUse", children: [
9644
- /* @__PURE__ */ jsx("stop", { stopColor: "#fff" }),
9645
- /* @__PURE__ */ jsx("stop", { offset: ".984", stopColor: "#D1D8FF" })
9646
- ] })
9647
- ] })
9648
- ] })
9649
- };
9650
- function Icon({
9651
- name,
9652
- className,
9653
- ...props
9654
- }) {
9655
- const Render = icons[name];
9656
- return /* @__PURE__ */ jsx(Render, { className: cn(className), "aria-hidden": "true", ...props });
9657
- }
9658
- function Dialog({ ...props }) {
9659
- return /* @__PURE__ */ jsx(Dialog$1.Root, { "data-slot": "dialog", ...props });
9660
- }
9661
- function DialogTrigger({ ...props }) {
9662
- return /* @__PURE__ */ jsx(Dialog$1.Trigger, { "data-slot": "dialog-trigger", ...props });
9663
- }
9664
- function DialogPortal({ container, children, ...props }) {
9665
- return /* @__PURE__ */ jsx(
9666
- Dialog$1.Portal,
9667
- {
9668
- "data-slot": "dialog-portal",
9669
- container: useFluentModalPortalContainer(container),
9670
- ...props,
9671
- children: /* @__PURE__ */ jsx(FluentTopLayerSlot, { children })
9672
- }
9673
- );
9674
- }
9675
- function DialogClose({ ...props }) {
9676
- return /* @__PURE__ */ jsx(Dialog$1.Close, { "data-slot": "dialog-close", ...props });
9677
- }
9678
- function DialogOverlay({
9679
- className,
9680
- ...props
9681
- }) {
9682
- return /* @__PURE__ */ jsx(
9683
- Dialog$1.Backdrop,
9684
- {
9685
- "data-slot": "dialog-overlay",
9686
- className: cn(
9687
- "fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",
9688
- className
9689
- ),
9690
- ...props
9691
- }
9692
- );
9693
- }
9694
- function DialogContent({
9695
- className,
9696
- children,
9697
- showCloseButton = true,
9698
- ...props
9699
- }) {
9700
- return /* @__PURE__ */ jsxs(DialogPortal, { children: [
9701
- /* @__PURE__ */ jsx(DialogOverlay, {}),
9702
- /* @__PURE__ */ jsxs(
9703
- Dialog$1.Popup,
9704
- {
9705
- "data-slot": "dialog-content",
9706
- className: cn(
9707
- "fixed top-1/2 left-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-4 rounded-3xl bg-popover p-4 text-sm text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
9708
- className
9709
- ),
9710
- ...props,
9711
- children: [
9712
- children,
9713
- showCloseButton && /* @__PURE__ */ jsxs(
9714
- Dialog$1.Close,
9715
- {
9716
- "data-slot": "dialog-close",
9717
- render: /* @__PURE__ */ jsx(
9718
- Button,
9719
- {
9720
- variant: "ghost",
9721
- className: "absolute top-3.5 right-3.5 z-50 rounded-full",
9722
- size: "icon-sm"
9723
- }
9724
- ),
9725
- children: [
9726
- /* @__PURE__ */ jsx(XIcon, {}),
9727
- /* @__PURE__ */ jsx("span", { className: "sr-only", children: "Close" })
9728
- ]
9729
- }
9730
- )
9731
- ]
9732
- }
9733
- )
9734
- ] });
10306
+ /* @__PURE__ */ jsx("stop", { offset: "1", stopColor: "#8697FF", stopOpacity: "0" })
10307
+ ] }),
10308
+ /* @__PURE__ */ jsxs("linearGradient", { id: "rabby__d", x1: "9.054", x2: "15.173", y1: "11.617", y2: "19.089", gradientUnits: "userSpaceOnUse", children: [
10309
+ /* @__PURE__ */ jsx("stop", { stopColor: "#fff" }),
10310
+ /* @__PURE__ */ jsx("stop", { offset: ".984", stopColor: "#D1D8FF" })
10311
+ ] })
10312
+ ] })
10313
+ ] })
10314
+ };
10315
+ function Icon({
10316
+ name,
10317
+ className,
10318
+ ...props
10319
+ }) {
10320
+ const Render = icons[name];
10321
+ return /* @__PURE__ */ jsx(Render, { className: cn(className), "aria-hidden": "true", ...props });
9735
10322
  }
9736
- function DialogHeader({ className, ...props }) {
10323
+ function connectDescription(appName) {
10324
+ return `Sign in or create a Fluent Connect account to use ${appName?.trim() || "this app"}.`;
10325
+ }
10326
+ var termsOfUseUrl = "https://cdn.fluent.xyz/docs/fluent-connect-sdk-terms-of-use.pdf";
10327
+ var privacyPolicyUrl = "https://cdn.fluent.xyz/docs/fluent-connect-sdk-privacy-policy.pdf";
10328
+ function ConsentLink({ href, children }) {
9737
10329
  return /* @__PURE__ */ jsx(
9738
- "div",
10330
+ "a",
9739
10331
  {
9740
- "data-slot": "dialog-header",
9741
- className: cn("flex flex-col gap-2", className),
9742
- ...props
10332
+ href,
10333
+ target: "_blank",
10334
+ rel: "noopener noreferrer",
10335
+ className: "whitespace-nowrap text-white/55 underline underline-offset-2 hover:text-white/80",
10336
+ children
9743
10337
  }
9744
10338
  );
9745
10339
  }
9746
- function DialogFooter({
9747
- className,
9748
- showCloseButton = false,
10340
+ function FluentBranch({
9749
10341
  children,
9750
- ...props
10342
+ className
9751
10343
  }) {
9752
10344
  return /* @__PURE__ */ jsxs(
9753
10345
  "div",
9754
10346
  {
9755
- "data-slot": "dialog-footer",
9756
10347
  className: cn(
9757
- "-mx-4 -mb-4 flex flex-col-reverse gap-2 rounded-b-xl border-t bg-muted/50 p-4 sm:flex-row sm:justify-end",
10348
+ // The edge is a 1px gradient ring drawn by ::before and cut out of its own padding box,
10349
+ // with a gap cut from its top run where the badge sits: the badge's width plus 8px a side.
10350
+ // The same cut crosses the bottom run, where the edge has already faded to nothing.
10351
+ // Rounded at the top only; surface and edge both fade to nothing by 70% of the height, so the
10352
+ // panel has no bottom to speak of and its last 30% dissolves into the dialog.
10353
+ "relative mt-3 flex flex-col gap-2 rounded-t-2xl bg-[linear-gradient(to_bottom,rgba(255,255,255,0.08),transparent_70%)] px-5 pt-5 pb-2",
10354
+ "before:pointer-events-none before:absolute before:inset-0 before:rounded-t-2xl before:p-px before:bg-[linear-gradient(to_bottom,rgba(255,255,255,0.2),transparent_70%)]",
10355
+ "before:[mask:linear-gradient(to_right,#000_calc(50%-60px),transparent_calc(50%-60px)_calc(50%+60px),#000_calc(50%+60px))_intersect,linear-gradient(#000_0_0)_content-box_exclude,linear-gradient(#000_0_0)]",
9758
10356
  className
9759
10357
  ),
9760
- ...props,
9761
10358
  children: [
10359
+ /* @__PURE__ */ jsx("span", { className: "absolute top-0 left-1/2 w-26 -translate-x-1/2 -translate-y-1/2 rounded-full bg-white/10 py-0.5 text-center text-[10px] font-medium uppercase leading-4 tracking-wider text-white ring-1 ring-inset ring-white/20 shadow-[inset_0_1px_0_rgba(255,255,255,0.25)] backdrop-blur-md", children: "Recommended" }),
9762
10360
  children,
9763
- showCloseButton && /* @__PURE__ */ jsxs(Dialog$1.Close, { render: /* @__PURE__ */ jsx(Button, { variant: "outline" }), children: [
9764
- /* @__PURE__ */ jsx(XIcon, { className: "size-4 shrink-0", "aria-hidden": true }),
9765
- "Close"
10361
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-0.5 pt-0.5 text-center text-[11px] leading-4", children: [
10362
+ /* @__PURE__ */ jsx("p", { className: "text-white/60", children: "Gasless transactions and faster signing." }),
10363
+ /* @__PURE__ */ jsxs("p", { className: "-mx-5 text-balance text-[10px] text-white/40", children: [
10364
+ "By continuing, you agree to our",
10365
+ " ",
10366
+ /* @__PURE__ */ jsx(ConsentLink, { href: termsOfUseUrl, children: "Terms of Use" }),
10367
+ " and",
10368
+ " ",
10369
+ /* @__PURE__ */ jsx(ConsentLink, { href: privacyPolicyUrl, children: "Privacy Policy" }),
10370
+ "."
10371
+ ] })
9766
10372
  ] })
9767
10373
  ]
9768
10374
  }
9769
10375
  );
9770
10376
  }
9771
- function DialogTitle({ className, ...props }) {
9772
- return /* @__PURE__ */ jsx(
9773
- Dialog$1.Title,
9774
- {
9775
- "data-slot": "dialog-title",
9776
- className: cn(
9777
- "text-base leading-none font-medium",
9778
- className
9779
- ),
9780
- ...props
9781
- }
9782
- );
9783
- }
9784
- function DialogDescription({
9785
- className,
9786
- ...props
9787
- }) {
10377
+ function BranchDivider() {
9788
10378
  return /* @__PURE__ */ jsx(
9789
- Dialog$1.Description,
10379
+ "div",
9790
10380
  {
9791
- "data-slot": "dialog-description",
9792
- className: cn(
9793
- "text-sm text-muted-foreground *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground",
9794
- className
9795
- ),
9796
- ...props
10381
+ className: "my-1 h-px bg-gradient-to-r from-transparent via-white/15 to-transparent",
10382
+ "aria-hidden": true
9797
10383
  }
9798
10384
  );
9799
10385
  }
9800
- function Label({ className, ...props }) {
9801
- return /* @__PURE__ */ jsx(
9802
- "label",
9803
- {
9804
- "data-slot": "label",
9805
- className: cn(
9806
- "flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
9807
- className
9808
- ),
9809
- ...props
9810
- }
9811
- );
10386
+ var walletRowClassName = "bg-transparent text-white/85 ring-1 ring-inset ring-white/10 hover:bg-white/5 hover:text-white";
10387
+ function WalletBranchNote() {
10388
+ return /* @__PURE__ */ jsx("p", { className: "text-center text-[11px] leading-4 text-white/45", children: "Manual signing required. Gas fees may apply." });
9812
10389
  }
9813
10390
  var buttonIcons = {
9814
10391
  x: (props) => /* @__PURE__ */ jsx(Icon, { ...props, name: "x" }),
@@ -9833,7 +10410,7 @@ function InlineConnectModal(props) {
9833
10410
  onClose,
9834
10411
  onFluentLogin,
9835
10412
  onRetry,
9836
- hostedError,
10413
+ loginError,
9837
10414
  wallet,
9838
10415
  track,
9839
10416
  onExternalWalletSelected,
@@ -9845,13 +10422,13 @@ function InlineConnectModal(props) {
9845
10422
  () => resolveFluentWidgetAuthMethods(config?.enabledAuthMethods),
9846
10423
  [config?.enabledAuthMethods]
9847
10424
  );
9848
- const { ready, authenticated, user } = usePrivy();
9849
- const { isOpen: securityPromptOpen } = useModalStatus();
9850
- const { wallets, ready: walletsReady } = useWallets();
9851
- const { createWallet } = useCreateWallet();
9852
- const { sendCode, loginWithCode } = useLoginWithEmail();
9853
- const { initOAuth, state: oauthState } = useLoginWithOAuth();
9854
- const { loginWithPasskey } = useLoginWithPasskey();
10425
+ const { ready, authenticated, user } = usePrivy2();
10426
+ const { isOpen: securityPromptOpen } = useModalStatus2();
10427
+ const { wallets, ready: walletsReady } = useWallets2();
10428
+ const { createWallet } = useCreateWallet2();
10429
+ const { sendCode, loginWithCode } = useLoginWithEmail2();
10430
+ const { initOAuth, state: oauthState } = useLoginWithOAuth2();
10431
+ const { loginWithPasskey } = useLoginWithPasskey2();
9855
10432
  const [step, setStep] = React.useState(
9856
10433
  () => hasPendingInlineOAuth() ? "oauth" : "choice"
9857
10434
  );
@@ -9883,7 +10460,7 @@ function InlineConnectModal(props) {
9883
10460
  active.current = open;
9884
10461
  const connecting = step !== "choice" && authenticated;
9885
10462
  const screen = connecting ? "connecting" : step;
9886
- const shownError = error || captchaError || (connecting ? signInRefusal || hostedError : "");
10463
+ const shownError = error || captchaError || (connecting ? signInRefusal || loginError : "");
9887
10464
  React.useEffect(() => {
9888
10465
  if (!open) {
9889
10466
  generation.current++;
@@ -10166,14 +10743,14 @@ function InlineConnectModal(props) {
10166
10743
  }),
10167
10744
  authMethods.map((method) => /* @__PURE__ */ jsx(React.Fragment, { children: authMethodButton(method) }, method))
10168
10745
  ] }),
10169
- /* @__PURE__ */ jsx(OrDivider, {}),
10170
- showWallets ? /* @__PURE__ */ jsxs(
10746
+ /* @__PURE__ */ jsx(BranchDivider, {}),
10747
+ /* @__PURE__ */ jsx("div", { className: "flex flex-col gap-2 px-5", children: showWallets ? /* @__PURE__ */ jsxs(
10171
10748
  "div",
10172
10749
  {
10173
10750
  className: "flex flex-col gap-2 animate-in fade-in-0 slide-in-from-bottom-1 duration-200 motion-reduce:animate-none",
10174
10751
  ref: walletList,
10175
10752
  role: "group",
10176
- "aria-label": "Other wallets",
10753
+ "aria-label": "Connect with other wallets",
10177
10754
  children: [
10178
10755
  wallet?.choices?.length ? wallet.choices.map((choice) => /* @__PURE__ */ jsxs(
10179
10756
  "button",
@@ -10204,7 +10781,7 @@ function InlineConnectModal(props) {
10204
10781
  }
10205
10782
  ) : /* @__PURE__ */ jsxs(React.Fragment, { children: [
10206
10783
  button(
10207
- "Other wallets",
10784
+ "Connect with other wallets",
10208
10785
  () => {
10209
10786
  if (!wallet?.connectChoice || !wallet.choices) {
10210
10787
  track("connect_method_selected", {
@@ -10220,18 +10797,11 @@ function InlineConnectModal(props) {
10220
10797
  {
10221
10798
  icon: "wallet",
10222
10799
  disabled: busy || !wallet?.configured,
10223
- className: "justify-start",
10224
- trailing: /* @__PURE__ */ jsx(
10225
- ChevronRight,
10226
- {
10227
- className: "ml-auto size-4 text-white/50",
10228
- "aria-hidden": true
10229
- }
10230
- )
10800
+ className: walletRowClassName
10231
10801
  }
10232
10802
  ),
10233
10803
  /* @__PURE__ */ jsx(WalletBranchNote, {})
10234
- ] })
10804
+ ] }) })
10235
10805
  ] });
10236
10806
  } else if (screen === "wallet") {
10237
10807
  title = `Connecting to ${walletChoice?.name ?? "wallet"}`;
@@ -10400,7 +10970,17 @@ function InlineConnectModal(props) {
10400
10970
  /* @__PURE__ */ jsxs(DialogHeader, { className: "items-center px-4 pt-5 pb-3 text-center", children: [
10401
10971
  headerIcon,
10402
10972
  /* @__PURE__ */ jsx("div", { ref: heading, tabIndex: -1, className: "outline-none", children: /* @__PURE__ */ jsx(DialogTitle, { children: title }) }),
10403
- /* @__PURE__ */ jsx(DialogDescription, { className: "break-words text-balance", children: description })
10973
+ /* @__PURE__ */ jsx(
10974
+ DialogDescription,
10975
+ {
10976
+ className: cn(
10977
+ "break-words text-balance",
10978
+ // Quieter under the lockup, where it sits on the brightest part of the gradient.
10979
+ screen === "choice" && "text-white/60"
10980
+ ),
10981
+ children: description
10982
+ }
10983
+ )
10404
10984
  ] }),
10405
10985
  /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-2 p-2.5", children: [
10406
10986
  content,
@@ -10424,7 +11004,7 @@ function InlineConnectModal(props) {
10424
11004
  ),
10425
11005
  // One captcha instance per login attempt, outside the animated screens.
10426
11006
  open && !authenticated && /* @__PURE__ */ jsx(
10427
- Captcha,
11007
+ Captcha2,
10428
11008
  {
10429
11009
  onError: () => setCaptchaError("Verification could not load. Please retry."),
10430
11010
  onUnsupported: () => setCaptchaError(
@@ -10453,115 +11033,6 @@ function InlineConnectModal(props) {
10453
11033
  }
10454
11034
  );
10455
11035
  }
10456
- function ConnectChoiceModal(props) {
10457
- return props.authMode === "direct" ? /* @__PURE__ */ jsx(InlineConnectModal, { ...props }) : /* @__PURE__ */ jsx(HostedConnectChoiceModal, { ...props });
10458
- }
10459
- function HostedConnectChoiceModal({
10460
- track,
10461
- onExternalWalletSelected,
10462
- open,
10463
- wallet,
10464
- onClose,
10465
- onFluentLogin,
10466
- fluentAuthorizeUrl,
10467
- fluentReady,
10468
- authMode = "hosted",
10469
- config,
10470
- hostedError
10471
- }) {
10472
- const directAuth = authMode === "direct";
10473
- const fluentActionReady = fluentReady && (directAuth || Boolean(fluentAuthorizeUrl));
10474
- const openWallet = () => {
10475
- track("connect_method_selected", { method: "external" });
10476
- onExternalWalletSelected();
10477
- wallet?.open();
10478
- onClose();
10479
- };
10480
- return /* @__PURE__ */ jsx(
10481
- Dialog,
10482
- {
10483
- open,
10484
- onOpenChange: (next) => {
10485
- if (!next) onClose();
10486
- },
10487
- children: /* @__PURE__ */ jsxs(
10488
- DialogContent,
10489
- {
10490
- "aria-describedby": void 0,
10491
- className: "dark text-white antialiased overflow-hidden",
10492
- children: [
10493
- /* @__PURE__ */ jsxs("div", { className: "z-20", children: [
10494
- /* @__PURE__ */ jsxs(DialogHeader, { className: "items-center text-center pt-5 pb-3 px-4", children: [
10495
- /* @__PURE__ */ jsx(DialogTitle, { children: "Connect Wallet" }),
10496
- /* @__PURE__ */ jsx(DialogDescription, { children: connectDescription(config?.appName) })
10497
- ] }),
10498
- /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-2 p-2.5", children: [
10499
- /* @__PURE__ */ jsx(FluentBranch, { children: /* @__PURE__ */ jsxs(
10500
- Button,
10501
- {
10502
- href: directAuth ? void 0 : fluentAuthorizeUrl,
10503
- target: directAuth ? void 0 : "fluent_connect_popup",
10504
- rel: directAuth ? void 0 : "opener",
10505
- "aria-disabled": !fluentActionReady,
10506
- onClick: (event) => {
10507
- if (!fluentActionReady) {
10508
- event.preventDefault();
10509
- return;
10510
- }
10511
- track("connect_method_selected", { method: "fluent" });
10512
- onFluentLogin();
10513
- onClose();
10514
- },
10515
- children: [
10516
- /* @__PURE__ */ jsx(Icon, { name: "fluent", className: "size-5 shrink-0", "aria-hidden": true }),
10517
- "Continue with Fluent Connect"
10518
- ]
10519
- }
10520
- ) }),
10521
- /* @__PURE__ */ jsx(OrDivider, {}),
10522
- /* @__PURE__ */ jsxs(
10523
- Button,
10524
- {
10525
- variant: "secondary",
10526
- disabled: !wallet?.configured,
10527
- onClick: openWallet,
10528
- className: "w-full justify-start",
10529
- children: [
10530
- /* @__PURE__ */ jsx(Wallet, { className: "size-4 shrink-0", "aria-hidden": true }),
10531
- "Other wallets",
10532
- /* @__PURE__ */ jsx(
10533
- ChevronRight,
10534
- {
10535
- className: "ml-auto size-4 text-white/50",
10536
- "aria-hidden": true
10537
- }
10538
- )
10539
- ]
10540
- }
10541
- ),
10542
- /* @__PURE__ */ jsx(WalletBranchNote, {}),
10543
- !wallet?.configured ? /* @__PURE__ */ jsx("p", { className: "px-2.5 text-xs text-[#ff8fda]", children: "WalletConnect bridge is unavailable." }) : null,
10544
- hostedError ? /* @__PURE__ */ jsx("p", { className: "px-2.5 text-xs text-[#ff8fda]", children: hostedError }) : null
10545
- ] })
10546
- ] }),
10547
- /* @__PURE__ */ jsx(
10548
- "div",
10549
- {
10550
- className: "absolute z-[1] inset-1.5 rounded-[18px]",
10551
- style: {
10552
- background: "radial-gradient(152.48% 152.48% at 50% 84.8%, #000 25.21%, #5011FF 53.1%)",
10553
- backgroundSize: "150% auto",
10554
- backgroundPosition: "center center",
10555
- backgroundRepeat: "no-repeat"
10556
- }
10557
- }
10558
- )
10559
- ]
10560
- }
10561
- )
10562
- }
10563
- );
10564
- }
10565
11036
  var Select = Select$1.Root;
10566
11037
  function SelectValue({ className, ...props }) {
10567
11038
  return /* @__PURE__ */ jsx(
@@ -13066,23 +13537,23 @@ function useBridgeHistoryRows({
13066
13537
  }) {
13067
13538
  const { address, isConnected } = useAccount();
13068
13539
  const wallet = isConnected ? address : void 0;
13069
- const history2 = useBridgeTxHistoryPages({ baseUrl: route.indexerUrl, address: wallet });
13540
+ const history = useBridgeTxHistoryPages({ baseUrl: route.indexerUrl, address: wallet });
13070
13541
  const hyperlaneToken = getBridgeTokens(network).find((t) => t.route === "fast-path");
13071
13542
  const hyperlane = useHyperlaneTransfers({ address: wallet, route, token: hyperlaneToken });
13072
13543
  const rows = useMemo(() => {
13073
- const fromIndexer = (history2.data?.pages ?? []).flatMap((page) => page.items.map(rowFromIndexer));
13544
+ const fromIndexer = (history.data?.pages ?? []).flatMap((page) => page.items.map(rowFromIndexer));
13074
13545
  const fromHyperlane = (hyperlane.data ?? []).map((t) => rowFromHyperlane(t, route, hyperlaneToken));
13075
13546
  return sortRows([...fromIndexer, ...fromHyperlane]);
13076
- }, [history2.data, hyperlane.data, hyperlaneToken, route]);
13547
+ }, [history.data, hyperlane.data, hyperlaneToken, route]);
13077
13548
  return {
13078
13549
  address: wallet,
13079
13550
  rows,
13080
- pending: Boolean(wallet) && (history2.isPending || hyperlane.isPending),
13081
- error: history2.isError ? history2.error.message : null,
13551
+ pending: Boolean(wallet) && (history.isPending || hyperlane.isPending),
13552
+ error: history.isError ? history.error.message : null,
13082
13553
  hyperlaneError: hyperlane.isError,
13083
- hasNextPage: Boolean(history2.hasNextPage),
13084
- isFetchingNextPage: history2.isFetchingNextPage,
13085
- fetchNextPage: () => void history2.fetchNextPage()
13554
+ hasNextPage: Boolean(history.hasNextPage),
13555
+ isFetchingNextPage: history.isFetchingNextPage,
13556
+ fetchNextPage: () => void history.fetchNextPage()
13086
13557
  };
13087
13558
  }
13088
13559
  var dayFormat = new Intl.DateTimeFormat(void 0, { dateStyle: "medium" });
@@ -13494,7 +13965,10 @@ function WalletMenuActionCard({
13494
13965
  onMintUsdnr,
13495
13966
  mintUsdnrBusy = false,
13496
13967
  onRevealAccount,
13497
- gasContext
13968
+ gasContext,
13969
+ onAddPasskey,
13970
+ passkeys = [],
13971
+ onRemovePasskey
13498
13972
  }) {
13499
13973
  const resolvedConfig = resolveFluentWidgetConfig(config);
13500
13974
  const [ownPanel, setOwnPanel] = useState("tokens");
@@ -13520,6 +13994,8 @@ function WalletMenuActionCard({
13520
13994
  const [activity, setActivity] = useState(null);
13521
13995
  const [reputation, setReputation] = useState({ phase: "disconnected" });
13522
13996
  const [actionStatus, setActionStatus] = useState(null);
13997
+ const [addingPasskey, setAddingPasskey] = useState(false);
13998
+ const [removingPasskey, setRemovingPasskey] = useState(null);
13523
13999
  const reputationEnabled = resolvedConfig.reputationEnabled;
13524
14000
  const client2 = useMemo(() => {
13525
14001
  if (!reputationEnabled) return null;
@@ -13618,6 +14094,34 @@ function WalletMenuActionCard({
13618
14094
  }
13619
14095
  await mint(accountAddress);
13620
14096
  };
14097
+ const handleAddPasskey = async (addPasskey) => {
14098
+ if (addingPasskey) return;
14099
+ setActionStatus(null);
14100
+ setAddingPasskey(true);
14101
+ track("wallet_passkey_link_started");
14102
+ try {
14103
+ await addPasskey();
14104
+ track("wallet_passkey_linked");
14105
+ } catch (error) {
14106
+ setActionStatus(error instanceof Error ? error.message : "Could not add a passkey");
14107
+ } finally {
14108
+ setAddingPasskey(false);
14109
+ }
14110
+ };
14111
+ const handleRemovePasskey = async (removePasskey, credentialId) => {
14112
+ if (removingPasskey !== null || addingPasskey) return;
14113
+ setActionStatus(null);
14114
+ setRemovingPasskey(credentialId);
14115
+ track("wallet_passkey_unlink_started");
14116
+ try {
14117
+ await removePasskey(credentialId);
14118
+ track("wallet_passkey_unlinked");
14119
+ } catch (error) {
14120
+ setActionStatus(error instanceof Error ? error.message : "Could not remove the passkey");
14121
+ } finally {
14122
+ setRemovingPasskey(null);
14123
+ }
14124
+ };
13621
14125
  const {
13622
14126
  balances,
13623
14127
  busy: balancesBusy,
@@ -13741,6 +14245,38 @@ function WalletMenuActionCard({
13741
14245
  ] }),
13742
14246
  statusLine ? /* @__PURE__ */ jsx("p", { className: "text-xs text-destructive", role: "status", children: statusLine }) : null
13743
14247
  ] }),
14248
+ onAddPasskey ? /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-2", children: [
14249
+ /* @__PURE__ */ jsx("span", { className: "text-xs font-medium opacity-50 uppercase", children: "Security" }),
14250
+ /* @__PURE__ */ jsxs(FieldGroup, { className: "w-full gap-2", children: [
14251
+ passkeys.map((passkey) => /* @__PURE__ */ jsx("div", { className: "rounded-xl bg-white/10", children: /* @__PURE__ */ jsxs(Field, { orientation: "horizontal", className: "px-3.5 py-3", children: [
14252
+ /* @__PURE__ */ jsxs(FieldContent, { children: [
14253
+ /* @__PURE__ */ jsx(FieldTitle, { children: passkey.label }),
14254
+ /* @__PURE__ */ jsx(FieldDescription, { children: removingPasskey === passkey.credentialId ? "Removing\u2026" : passkey.addedOn ? `Added ${passkey.addedOn}` : "Signs you in on this account" })
14255
+ ] }),
14256
+ onRemovePasskey ? /* @__PURE__ */ jsx(
14257
+ Button,
14258
+ {
14259
+ variant: "ghost",
14260
+ size: "icon-sm",
14261
+ className: "shrink-0 rounded-full",
14262
+ "aria-label": `Remove passkey: ${passkey.label}`,
14263
+ disabled: removingPasskey !== null || addingPasskey,
14264
+ onClick: () => void handleRemovePasskey(onRemovePasskey, passkey.credentialId),
14265
+ children: /* @__PURE__ */ jsx(Trash2, { className: "size-4", "aria-hidden": true })
14266
+ }
14267
+ ) : null
14268
+ ] }) }, passkey.credentialId)),
14269
+ /* @__PURE__ */ jsx(
14270
+ SettingsActionField,
14271
+ {
14272
+ title: addingPasskey ? "Waiting for your passkey" : "Add passkey",
14273
+ description: passkeys.length > 0 ? "Add another for a different device" : "Sign in without X next time",
14274
+ disabled: addingPasskey || removingPasskey !== null,
14275
+ onClick: () => void handleAddPasskey(onAddPasskey)
14276
+ }
14277
+ )
14278
+ ] })
14279
+ ] }) : null,
13744
14280
  /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-2", children: [
13745
14281
  /* @__PURE__ */ jsx("span", { className: "text-xs font-medium opacity-50 uppercase", children: "Developer" }),
13746
14282
  /* @__PURE__ */ jsxs(FieldGroup, { className: "w-full gap-2", children: [
@@ -14759,17 +15295,17 @@ function useBridgeDeposit({
14759
15295
  const pollIndexer = async () => {
14760
15296
  if (!state.hash) return false;
14761
15297
  try {
14762
- const history2 = await getBridgeTransactions({
15298
+ const history = await getBridgeTransactions({
14763
15299
  baseUrl: route.indexerUrl,
14764
15300
  address,
14765
15301
  signal: controller.signal
14766
15302
  });
14767
- const item = findBridgeTxBySentHash(history2, state.hash);
15303
+ const item = findBridgeTxBySentHash(history, state.hash);
14768
15304
  debugLog("[FluentBridge] indexer transactions", {
14769
15305
  sentTxHash: state.hash,
14770
15306
  matched: item,
14771
- items: history2.items.length,
14772
- l1RequiredConfirmations: history2.l1_required_confirmations
15307
+ items: history.items.length,
15308
+ l1RequiredConfirmations: history.l1_required_confirmations
14773
15309
  });
14774
15310
  if (!item || !active) return false;
14775
15311
  if (item.received_tx_hash) {
@@ -15741,9 +16277,7 @@ function deriveWidgetAccount(input) {
15741
16277
  const {
15742
16278
  smartAccount,
15743
16279
  wallet,
15744
- sessionUserId,
15745
16280
  sessionSmartAccountAddress,
15746
- directAuth,
15747
16281
  walletUserPrivySession = false
15748
16282
  } = input;
15749
16283
  const fluentAccountAddress = smartAccount.smartAccountAddress ?? sessionSmartAccountAddress;
@@ -15756,16 +16290,14 @@ function deriveWidgetAccount(input) {
15756
16290
  smartAccount.privyReady && smartAccount.privyAuthenticated && smartAccount.embeddedWalletCount > 0
15757
16291
  );
15758
16292
  const fluentAccountReady = Boolean(
15759
- smartAccount.smartAccountReady && smartAccount.smartAccountAddress && (!directAuth || localPrivySignerReady)
15760
- );
15761
- const hasConnectedAccount = Boolean(
15762
- externalConnected || (directAuth ? fluentAccountReady : sessionUserId || sessionSmartAccountAddress)
16293
+ smartAccount.smartAccountReady && smartAccount.smartAccountAddress && localPrivySignerReady
15763
16294
  );
16295
+ const hasConnectedAccount = Boolean(externalConnected || fluentAccountReady);
15764
16296
  const connecting = Boolean(
15765
- !hasConnectedAccount && directAuth && smartAccount.privyAuthenticated && !walletUserPrivySession && !smartAccount.error
16297
+ !hasConnectedAccount && smartAccount.privyAuthenticated && !walletUserPrivySession && !smartAccount.error
15766
16298
  );
15767
16299
  const restoring = Boolean(
15768
- !hasConnectedAccount && !connecting && !smartAccount.error && (directAuth && !smartAccount.privyReady || wallet?.reconnecting)
16300
+ !hasConnectedAccount && !connecting && !smartAccount.error && (!smartAccount.privyReady || wallet?.reconnecting)
15769
16301
  );
15770
16302
  const status = hasConnectedAccount ? "connected" : connecting ? "connecting" : restoring ? "restoring" : "disconnected";
15771
16303
  const externalReady = Boolean(externalConnected && wallet?.hasWalletClient);
@@ -15840,18 +16372,14 @@ function useWidgetAccount(input) {
15840
16372
  const {
15841
16373
  smartAccount,
15842
16374
  wallet,
15843
- sessionUserId,
15844
16375
  sessionSmartAccountAddress,
15845
- directAuth,
15846
16376
  walletUserPrivySession = false
15847
16377
  } = input;
15848
16378
  return useMemo(
15849
16379
  () => deriveWidgetAccount({
15850
16380
  smartAccount,
15851
16381
  wallet,
15852
- sessionUserId,
15853
16382
  sessionSmartAccountAddress,
15854
- directAuth,
15855
16383
  walletUserPrivySession
15856
16384
  }),
15857
16385
  [
@@ -15866,9 +16394,7 @@ function useWidgetAccount(input) {
15866
16394
  wallet?.address,
15867
16395
  wallet?.hasWalletClient,
15868
16396
  wallet?.reconnecting,
15869
- sessionUserId,
15870
16397
  sessionSmartAccountAddress,
15871
- directAuth,
15872
16398
  walletUserPrivySession
15873
16399
  ]
15874
16400
  );
@@ -16105,14 +16631,6 @@ function externalWalletSigner(wallet) {
16105
16631
  };
16106
16632
  }
16107
16633
  function createFluentSignApi(executor) {
16108
- const assertDirectMode = () => {
16109
- if (executor.authMode === "hosted") {
16110
- throw new FluentAuthError(
16111
- "hosted_not_supported",
16112
- 'Signing needs authMode: "direct" \u2014 there is no hosted signer to ask.'
16113
- );
16114
- }
16115
- };
16116
16634
  const smartAccountSigner = () => ({
16117
16635
  address: executor.account.address,
16118
16636
  review: !executor.silentSigning,
@@ -16131,7 +16649,6 @@ function createFluentSignApi(executor) {
16131
16649
  }
16132
16650
  });
16133
16651
  const pickSigner = () => {
16134
- assertDirectMode();
16135
16652
  if (executor.account.type === "smart" && executor.account.address) return smartAccountSigner();
16136
16653
  if (executor.account.type === "eoa") {
16137
16654
  const signer = executor.wallet ? externalWalletSigner(executor.wallet) : null;
@@ -16215,8 +16732,8 @@ function useWidgetExecution(params) {
16215
16732
  defaultConfirmationMode,
16216
16733
  selectedGasPaymentToken,
16217
16734
  defaultSponsorship,
16735
+ quickSignWhitelist,
16218
16736
  confirmBatchOperation,
16219
- authMode,
16220
16737
  confirmSignature,
16221
16738
  refreshBalances,
16222
16739
  track
@@ -16228,10 +16745,19 @@ function useWidgetExecution(params) {
16228
16745
  const sendCalls = useCallback(
16229
16746
  async (calls, options, readyAccount) => {
16230
16747
  if (fluentAccountReady || readyAccount) {
16231
- const { hash, receipt, userOpHash, sponsored, sponsorshipReason, paymaster } = await smartAccount.sendCalls(calls, options, readyAccount);
16748
+ const { hash, receipt, userOpHash, sponsored, sponsorshipReason, paymaster, timing } = await smartAccount.sendCalls(calls, options, readyAccount);
16232
16749
  track("wallet_gas_sponsored", { sponsored, reason: sponsorshipReason });
16233
16750
  refreshBalances();
16234
- return { hash, receipt, userOpHash, hashes: [hash], atomic: true, sponsored, paymaster };
16751
+ return {
16752
+ hash,
16753
+ receipt,
16754
+ userOpHash,
16755
+ hashes: [hash],
16756
+ atomic: true,
16757
+ sponsored,
16758
+ paymaster,
16759
+ timing
16760
+ };
16235
16761
  }
16236
16762
  if (wallet?.connected && wallet.walletClient) {
16237
16763
  const result = await sendCallsViaExternalWallet(calls, wallet, chain, eoaPublicClient);
@@ -16258,6 +16784,7 @@ function useWidgetExecution(params) {
16258
16784
  defaultConfirmation: defaultConfirmationMode,
16259
16785
  defaultGasPayment: selectedGasPaymentToken,
16260
16786
  defaultSponsorship,
16787
+ quickSignWhitelist,
16261
16788
  confirm: confirmBatchOperation,
16262
16789
  sendCalls
16263
16790
  }),
@@ -16269,7 +16796,8 @@ function useWidgetExecution(params) {
16269
16796
  defaultConfirmationMode,
16270
16797
  selectedGasPaymentToken,
16271
16798
  confirmBatchOperation,
16272
- defaultSponsorship
16799
+ defaultSponsorship,
16800
+ quickSignWhitelist
16273
16801
  ]
16274
16802
  );
16275
16803
  const permissionApi = useMemo(
@@ -16281,7 +16809,6 @@ function useWidgetExecution(params) {
16281
16809
  );
16282
16810
  const signApi = useMemo(
16283
16811
  () => createFluentSignApi({
16284
- authMode,
16285
16812
  account: widgetAccount,
16286
16813
  origin: window.location.origin,
16287
16814
  silentSigning: defaultConfirmationMode === "session",
@@ -16291,15 +16818,14 @@ function useWidgetExecution(params) {
16291
16818
  return {
16292
16819
  signerSource: kernel.signerSource,
16293
16820
  account: {
16294
- signMessage: (params2) => withFluentSignaturePrompt(() => kernel.account.signMessage(params2)),
16295
- signTypedData: (typedData) => withFluentSignaturePrompt(() => kernel.account.signTypedData(typedData))
16821
+ signMessage: (params2) => kernel.account.signMessage(params2),
16822
+ signTypedData: (typedData) => kernel.account.signTypedData(typedData)
16296
16823
  }
16297
16824
  };
16298
16825
  },
16299
16826
  wallet: wallet?.connected ? wallet : void 0
16300
16827
  }),
16301
16828
  [
16302
- authMode,
16303
16829
  widgetAccount,
16304
16830
  defaultConfirmationMode,
16305
16831
  confirmSignature,
@@ -16454,7 +16980,7 @@ function useUsdnrMint(params) {
16454
16980
  return { mintUsdnr, mintingUsdnr: minting };
16455
16981
  }
16456
16982
  function useZeroDevInitializer(params) {
16457
- const { smartAccount, directAuth, session, widgetAccount } = params;
16983
+ const { smartAccount, session, widgetAccount } = params;
16458
16984
  const initRequested = useRef(false);
16459
16985
  const resetInitialization = useCallback(() => {
16460
16986
  initRequested.current = false;
@@ -16492,7 +17018,6 @@ function useZeroDevInitializer(params) {
16492
17018
  ]);
16493
17019
  useEffect(() => {
16494
17020
  if (smartAccount.smartAccountReady) return;
16495
- if (!directAuth && !session) return;
16496
17021
  if (!smartAccount.privyAuthenticated || smartAccount.embeddedWalletCount === 0) {
16497
17022
  debugWarn("[fluent widget] ZeroDev init skipped: signer unavailable", {
16498
17023
  privyReady: smartAccount.privyReady,
@@ -16512,8 +17037,6 @@ function useZeroDevInitializer(params) {
16512
17037
  debugWarn("[fluent widget] ZeroDev account initialization failed", error);
16513
17038
  });
16514
17039
  }, [
16515
- directAuth,
16516
- session,
16517
17040
  smartAccount.embeddedWalletCount,
16518
17041
  smartAccount.privyAuthenticated,
16519
17042
  smartAccount.refresh,
@@ -16540,140 +17063,6 @@ function useConnectStatus() {
16540
17063
  const [error, setError] = useState(null);
16541
17064
  return { status, setStatus, error, setError };
16542
17065
  }
16543
- var FLUENT_WIDGET_AUTH_STATE_STORAGE_KEY = "fluent:widget:auth-state:v1";
16544
- function useHostedConnect(params) {
16545
- const {
16546
- fluentConnect,
16547
- authorizeUrl,
16548
- appId,
16549
- appName,
16550
- authMode,
16551
- setSession,
16552
- resetInitialization,
16553
- setConnectOpen,
16554
- setStatus,
16555
- setError,
16556
- smartAccountRefresh,
16557
- track
16558
- } = params;
16559
- const [hostedAuthorizeUrl, setHostedAuthorizeUrl] = useState();
16560
- const hostedConnectWindow = useRef(null);
16561
- const hostedConnectState = useRef(null);
16562
- const beginHostedConnect = useCallback(() => {
16563
- const state = crypto.randomUUID?.() ?? `${Date.now()}_${Math.random().toString(16).slice(2)}`;
16564
- hostedConnectState.current = state;
16565
- try {
16566
- window.sessionStorage.setItem(FLUENT_WIDGET_AUTH_STATE_STORAGE_KEY, state);
16567
- } catch {
16568
- }
16569
- const url = fluentConnect.buildAuthorizeUrl(state).toString();
16570
- debugLog("[fluent widget] open connect", { state, authorizeUrl: url, appId, appName, authMode });
16571
- setHostedAuthorizeUrl(url);
16572
- setConnectOpen(true);
16573
- }, [appName, authMode, appId, fluentConnect, setConnectOpen]);
16574
- const acceptHostedResult = useCallback(
16575
- (data) => {
16576
- if (!data || typeof data !== "object") return;
16577
- const payload = data;
16578
- if (payload.type === "fluent:connect:error") {
16579
- track("connect_login_failed", { reason: "hosted_error" });
16580
- setError(typeof payload.error === "string" ? payload.error : "Fluent Connect login failed");
16581
- hostedConnectWindow.current?.close();
16582
- hostedConnectWindow.current = null;
16583
- return;
16584
- }
16585
- if (payload.type !== "fluent:connect:session" || !payload.session) return;
16586
- let expectedState = hostedConnectState.current;
16587
- try {
16588
- expectedState ??= window.sessionStorage.getItem(FLUENT_WIDGET_AUTH_STATE_STORAGE_KEY);
16589
- } catch {
16590
- }
16591
- if (!payload.state || !expectedState || payload.state !== expectedState) {
16592
- track("connect_login_failed", { reason: "state_mismatch" });
16593
- setError("Fluent Connect login failed state validation");
16594
- hostedConnectWindow.current?.close();
16595
- hostedConnectWindow.current = null;
16596
- return;
16597
- }
16598
- if (payload.session.app?.origin && payload.session.app.origin !== fluentConnect.status().app.origin) {
16599
- track("connect_login_failed", { reason: "origin_mismatch" });
16600
- setError("Fluent Connect session origin does not match this app");
16601
- hostedConnectWindow.current?.close();
16602
- hostedConnectWindow.current = null;
16603
- return;
16604
- }
16605
- if (!payload.session.wallet?.smartAccountAddress) {
16606
- track("connect_login_failed", { reason: "smart_account_missing" });
16607
- setError("Fluent smart account is not ready. Reconnect with Fluent ID.");
16608
- hostedConnectWindow.current?.close();
16609
- hostedConnectWindow.current = null;
16610
- return;
16611
- }
16612
- const nextIdentityToken = typeof payload.privyIdentityToken === "string" ? payload.privyIdentityToken : null;
16613
- debugLog("[fluent widget] hosted result accepted", {
16614
- userId: payload.session.user?.id,
16615
- signerAddress: payload.session.wallet?.signerAddress,
16616
- smartAccountAddress: payload.session.wallet?.smartAccountAddress,
16617
- scopes: payload.session.scopes,
16618
- hasIdentityToken: Boolean(nextIdentityToken)
16619
- });
16620
- setSession(payload.session);
16621
- track("connect_login_completed");
16622
- resetInitialization();
16623
- fluentConnect.setSession(payload.session);
16624
- const storage = resolveLocalStorage();
16625
- if (nextIdentityToken) {
16626
- writeStoredValue(storage, FLUENT_WIDGET_IDENTITY_TOKEN_STORAGE_KEY, nextIdentityToken);
16627
- } else {
16628
- removeStoredValue(storage, FLUENT_WIDGET_IDENTITY_TOKEN_STORAGE_KEY);
16629
- }
16630
- setStatus("Wallet connected!");
16631
- setError(null);
16632
- setConnectOpen(false);
16633
- hostedConnectState.current = null;
16634
- try {
16635
- window.sessionStorage.removeItem(FLUENT_WIDGET_AUTH_STATE_STORAGE_KEY);
16636
- } catch {
16637
- }
16638
- hostedConnectWindow.current?.close();
16639
- hostedConnectWindow.current = null;
16640
- window.setTimeout(() => {
16641
- smartAccountRefresh().catch((error) => {
16642
- debugWarn("[fluent widget] ZeroDev account not ready after hosted login", error);
16643
- });
16644
- }, 250);
16645
- },
16646
- [fluentConnect, resetInitialization, setConnectOpen, setError, setSession, setStatus, smartAccountRefresh, track]
16647
- );
16648
- useEffect(() => {
16649
- const hash = new URLSearchParams(location.hash.replace(/^#/, ""));
16650
- const rawResult = hash.get("fluent_connect_result");
16651
- if (!rawResult) return;
16652
- try {
16653
- acceptHostedResult(JSON.parse(rawResult));
16654
- } catch {
16655
- setError("Could not parse Fluent Connect result");
16656
- } finally {
16657
- history.replaceState(null, "", `${location.pathname}${location.search}`);
16658
- }
16659
- }, [acceptHostedResult, setError]);
16660
- useEffect(() => {
16661
- function onMessage(event) {
16662
- if (event.origin !== new URL(authorizeUrl, location.href).origin) return;
16663
- if (!event.data) return;
16664
- acceptHostedResult(event.data);
16665
- }
16666
- addEventListener("message", onMessage);
16667
- return () => removeEventListener("message", onMessage);
16668
- }, [acceptHostedResult, authorizeUrl]);
16669
- useEffect(() => {
16670
- return () => {
16671
- hostedConnectWindow.current?.close();
16672
- hostedConnectWindow.current = null;
16673
- };
16674
- }, []);
16675
- return { hostedAuthorizeUrl, beginHostedConnect };
16676
- }
16677
17066
  function useAccountMenu(params) {
16678
17067
  const {
16679
17068
  accountMenuAddress,
@@ -16832,16 +17221,15 @@ function settingsAudienceKey(params) {
16832
17221
  return `${params.publicApiUrl}|${params.appId}`;
16833
17222
  }
16834
17223
  function resolveSettingsSubject(params) {
16835
- const { authMode, accountType, privyUserId, walletAddress } = params;
16836
- if (authMode === "hosted" && accountType === "smart") return null;
17224
+ const { accountType, privyUserId, walletAddress } = params;
16837
17225
  if (accountType === "smart" && privyUserId) return `privy:${privyUserId}`;
16838
17226
  if (accountType === "eoa" && walletAddress) return `wallet:${walletAddress.toLowerCase()}`;
16839
17227
  return null;
16840
17228
  }
16841
17229
  function resolveSettingsIdentities(params) {
16842
- const { authMode, privyUserId, walletAddress } = params;
17230
+ const { privyUserId, walletAddress } = params;
16843
17231
  const identities = [];
16844
- if (authMode !== "hosted" && privyUserId) identities.push(`privy:${privyUserId}`);
17232
+ if (privyUserId) identities.push(`privy:${privyUserId}`);
16845
17233
  if (walletAddress) identities.push(`wallet:${walletAddress.toLowerCase()}`);
16846
17234
  return identities;
16847
17235
  }
@@ -17104,7 +17492,6 @@ async function requestAuthToken(params, state, options = {}) {
17104
17492
  const {
17105
17493
  publicApiUrl,
17106
17494
  appId,
17107
- authMode,
17108
17495
  renewalOffsetSeconds,
17109
17496
  accountType,
17110
17497
  privyUserId,
@@ -17114,12 +17501,6 @@ async function requestAuthToken(params, state, options = {}) {
17114
17501
  walletClient,
17115
17502
  origin
17116
17503
  } = params;
17117
- if (authMode === "hosted" && accountType === "smart") {
17118
- throw new FluentAuthError(
17119
- "hosted_not_supported",
17120
- 'getAuthToken() for a Fluent ID needs authMode: "direct" \u2014 in hosted mode its Privy session lives on the authorize page, not in this page.'
17121
- );
17122
- }
17123
17504
  const subject = accountType === "smart" && privyUserId ? `privy:${privyUserId}` : accountType === "eoa" && walletAddress ? `wallet:${walletAddress.toLowerCase()}` : null;
17124
17505
  if (!subject) {
17125
17506
  throw new FluentAuthError("not_connected", "Connect a Fluent ID or an external wallet first.");
@@ -17278,7 +17659,6 @@ function useAuthToken(params, state) {
17278
17659
  const {
17279
17660
  publicApiUrl,
17280
17661
  appId,
17281
- authMode,
17282
17662
  renewalOffsetSeconds,
17283
17663
  accountType,
17284
17664
  privyUserId,
@@ -17295,7 +17675,6 @@ function useAuthToken(params, state) {
17295
17675
  {
17296
17676
  publicApiUrl,
17297
17677
  appId,
17298
- authMode,
17299
17678
  renewalOffsetSeconds,
17300
17679
  accountType,
17301
17680
  privyUserId,
@@ -17311,7 +17690,6 @@ function useAuthToken(params, state) {
17311
17690
  ),
17312
17691
  [
17313
17692
  accountType,
17314
- authMode,
17315
17693
  renewalOffsetSeconds,
17316
17694
  appId,
17317
17695
  getAccessToken,
@@ -17334,7 +17712,6 @@ function useAuthToken(params, state) {
17334
17712
  await endAuthSession({
17335
17713
  publicApiUrl,
17336
17714
  appId,
17337
- authMode,
17338
17715
  accountType,
17339
17716
  privyUserId,
17340
17717
  walletAddress,
@@ -17343,7 +17720,6 @@ function useAuthToken(params, state) {
17343
17720
  }, [
17344
17721
  accountType,
17345
17722
  appId,
17346
- authMode,
17347
17723
  privyUserId,
17348
17724
  publicApiUrl,
17349
17725
  storage,
@@ -17360,7 +17736,6 @@ function useUserSettings(params) {
17360
17736
  state,
17361
17737
  publicApiUrl,
17362
17738
  appId,
17363
- authMode,
17364
17739
  network,
17365
17740
  defaultGasToken = FLUENT_WIDGET_DEFAULT_GAS_TOKEN,
17366
17741
  accountType,
@@ -17388,8 +17763,8 @@ function useUserSettings(params) {
17388
17763
  [network]
17389
17764
  );
17390
17765
  const subject = useMemo(
17391
- () => resolveSettingsSubject({ authMode, accountType, privyUserId, walletAddress }),
17392
- [authMode, accountType, privyUserId, walletAddress]
17766
+ () => resolveSettingsSubject({ accountType, privyUserId, walletAddress }),
17767
+ [accountType, privyUserId, walletAddress]
17393
17768
  );
17394
17769
  const ready = useMemo(
17395
17770
  () => isSettingsSubjectReady({ accountType, identityToken, walletAddress, hasWalletClient }),
@@ -17425,8 +17800,8 @@ function useUserSettings(params) {
17425
17800
  [appId, publicApiUrl]
17426
17801
  );
17427
17802
  const identities = useMemo(
17428
- () => resolveSettingsIdentities({ authMode, privyUserId, walletAddress }),
17429
- [authMode, privyUserId, walletAddress]
17803
+ () => resolveSettingsIdentities({ privyUserId, walletAddress }),
17804
+ [privyUserId, walletAddress]
17430
17805
  );
17431
17806
  const knownSubjects = useMemo(
17432
17807
  () => identities.map(
@@ -17841,6 +18216,7 @@ function FluentConnectButtonSlot({
17841
18216
  connected: hasConnectedAccount,
17842
18217
  pending: connecting,
17843
18218
  addressLabel: connectAddressLabel,
18219
+ userAvatarUrl: userLogoUrl || void 0,
17844
18220
  onClick: onTopConnectClick,
17845
18221
  openConnect,
17846
18222
  openAccount,
@@ -17849,7 +18225,7 @@ function FluentConnectButtonSlot({
17849
18225
  return renderConnectButton?.(connectButtonContext) ?? (connectButton === false ? null : connectButton === "inline" ? defaultConnectButton : /* @__PURE__ */ jsx("div", { className: "fixed top-5 right-5 z-50", children: defaultConnectButton }));
17850
18226
  }
17851
18227
  function DebugPanel(props) {
17852
- const { session, wallet, walletStatus, hostedError } = props;
18228
+ const { session, wallet, walletStatus, loginError } = props;
17853
18229
  return /* @__PURE__ */ jsxs("section", { className: "overflow-hidden rounded-2xl border border-white/10 bg-black/70 text-white shadow-2xl backdrop-blur-md", children: [
17854
18230
  /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-3 border-b border-white/10 px-4 py-3.5", children: [
17855
18231
  /* @__PURE__ */ jsx("h2", { className: "m-0 text-base font-medium", children: "Host app callback" }),
@@ -17861,7 +18237,7 @@ function DebugPanel(props) {
17861
18237
  /* @__PURE__ */ jsx("span", { className: "rounded-full bg-[#49eded]/15 px-2 py-1 text-xs font-medium text-[#49eded]", children: wallet?.connected ? "Reown" : "wallet" })
17862
18238
  ] }),
17863
18239
  /* @__PURE__ */ jsx("pre", { className: "overflow-auto p-4 text-xs", children: formatExternalWallet(wallet, walletStatus) }),
17864
- hostedError ? /* @__PURE__ */ jsx("p", { className: "m-0 px-4 pb-4 text-[13px] leading-5 text-[#ff8fda]", children: hostedError }) : null
18240
+ loginError ? /* @__PURE__ */ jsx("p", { className: "m-0 px-4 pb-4 text-[13px] leading-5 text-[#ff8fda]", children: loginError }) : null
17865
18241
  ] });
17866
18242
  }
17867
18243
  var FLUENT_WIDGET_DIRECT_LOGIN_INTENT_KEY = "fluent:widget:direct-login-intent:v1";
@@ -17937,7 +18313,6 @@ function FluentWidgetContent({
17937
18313
  requestPrivyLogin,
17938
18314
  inlineLoginRequest,
17939
18315
  handledInlineLoginRequest,
17940
- pendingPrivyLoginRef,
17941
18316
  authTokenState,
17942
18317
  userSettingsRef,
17943
18318
  connectedPresentation
@@ -17952,15 +18327,26 @@ function FluentWidgetContent({
17952
18327
  login: requestPrivyLogin,
17953
18328
  appId: resolvedConfig.appId,
17954
18329
  sponsorshipUrl: resolvedConfig.sponsorshipUrl,
17955
- sponsorshipTokenSource: readSponsorshipTokenSource
18330
+ sponsorshipTokenSource: readSponsorshipTokenSource,
18331
+ // Passed on every render, not captured once: the hook reads these settings at the moment a
18332
+ // send or a signature needs them, so a host that changes them is obeyed by the next one
18333
+ // without the kernel being rebuilt.
18334
+ execution: resolvedConfig.execution
17956
18335
  });
17957
- const { authenticated, getAccessToken, login, logout, ready: privyReady, user } = usePrivy();
17958
- const { identityToken } = useIdentityToken();
17959
- const { refreshUser } = useUser();
18336
+ const {
18337
+ authenticated,
18338
+ getAccessToken,
18339
+ login,
18340
+ logout,
18341
+ ready: privyReady,
18342
+ unlinkPasskey,
18343
+ user
18344
+ } = usePrivy2();
18345
+ const { identityToken } = useIdentityToken2();
18346
+ const { refreshUser } = useUser2();
17960
18347
  const activeWallet = wallet ?? internalWallet;
17961
18348
  const { chain } = useFluentWidgetNetwork();
17962
18349
  const fluentConnect = useMemo(() => createFluentConnectForWidget(config), [config]);
17963
- const directAuth = resolvedConfig.authMode === "direct";
17964
18350
  const directAuthRequested = useRef(
17965
18351
  (() => {
17966
18352
  try {
@@ -17971,6 +18357,7 @@ function FluentWidgetContent({
17971
18357
  })()
17972
18358
  );
17973
18359
  const directAuthInFlight = useRef(false);
18360
+ const dialogAskedOnThisPage = useRef(false);
17974
18361
  const disconnectingRef = useRef(false);
17975
18362
  const { session, setSession } = useFluentSession({
17976
18363
  reportAnalyticsSession,
@@ -17979,13 +18366,13 @@ function FluentWidgetContent({
17979
18366
  const {
17980
18367
  status: walletStatus,
17981
18368
  setStatus: setWalletStatus,
17982
- error: hostedError,
17983
- setError: setHostedError
18369
+ error: loginError,
18370
+ setError: setLoginError
17984
18371
  } = useConnectStatus();
17985
18372
  const [balanceRevisionCounter, setBalanceRevisionCounter] = useState(0);
17986
18373
  const [walletMenuPanel, setWalletMenuPanel] = useState("tokens");
17987
18374
  const refreshBalances = useCallback(() => setBalanceRevisionCounter((value) => value + 1), []);
17988
- const [connectOpen, setConnectOpen] = useState(() => directAuth && hasPendingInlineOAuth());
18375
+ const [connectOpen, setConnectOpen] = useState(() => hasPendingInlineOAuth());
17989
18376
  const connectedWalletAddress = activeWallet?.connected ? activeWallet.address : void 0;
17990
18377
  const walletClientReady = Boolean(
17991
18378
  activeWallet?.address && activeWallet.walletClient?.account?.address?.toLowerCase() === activeWallet.address.toLowerCase()
@@ -17995,7 +18382,7 @@ function FluentWidgetContent({
17995
18382
  const linkXSiweLogins = useRef({ pending: false, userIds: /* @__PURE__ */ new Set() });
17996
18383
  const siweSignedInOnThisPage = linkXSiweLogins.current.pending || user?.id !== void 0 && linkXSiweLogins.current.userIds.has(user.id);
17997
18384
  const dialogSignInUserIds = useRef(/* @__PURE__ */ new Set());
17998
- if (directAuth && user?.id !== void 0 && !dialogSignInUserIds.current.has(user.id) && privyUserHasExternalWallet(user) && directLoginDialogMarksPresent())
18385
+ if (user?.id !== void 0 && !dialogSignInUserIds.current.has(user.id) && privyUserHasExternalWallet(user) && (dialogAskedOnThisPage.current || directLoginDialogMarksPresent()))
17999
18386
  dialogSignInUserIds.current.add(user.id);
18000
18387
  const dialogSignedInOnThisPage = user?.id !== void 0 && dialogSignInUserIds.current.has(user.id);
18001
18388
  const walletUserPrivySession = (privyUserHasExternalWallet(user) || siweSignedInOnThisPage) && !fluentSessionNamesPrivyUser && !(dialogSignedInOnThisPage && !siweSignedInOnThisPage);
@@ -18020,9 +18407,7 @@ function FluentWidgetContent({
18020
18407
  hasWalletClient: walletClientReady,
18021
18408
  reconnecting: activeWallet.reconnecting
18022
18409
  } : null,
18023
- sessionUserId: session?.user?.id,
18024
18410
  sessionSmartAccountAddress: session?.wallet?.smartAccountAddress,
18025
- directAuth,
18026
18411
  walletUserPrivySession
18027
18412
  });
18028
18413
  const walletConnected = Boolean(activeWallet?.connected);
@@ -18065,7 +18450,6 @@ function FluentWidgetContent({
18065
18450
  const { resetInitialization } = useZeroDevInitializer({
18066
18451
  // The same count the account model reads: a wallet's own Privy session initializes nothing.
18067
18452
  smartAccount: { ...smartAccount, embeddedWalletCount },
18068
- directAuth,
18069
18453
  session,
18070
18454
  widgetAccount
18071
18455
  });
@@ -18075,22 +18459,9 @@ function FluentWidgetContent({
18075
18459
  chainId: activeWallet?.chainId,
18076
18460
  track
18077
18461
  });
18078
- const { hostedAuthorizeUrl, beginHostedConnect } = useHostedConnect({
18079
- fluentConnect,
18080
- authorizeUrl: resolvedConfig.authorizeUrl,
18081
- appId: resolvedConfig.appId,
18082
- appName: resolvedConfig.appName,
18083
- authMode: resolvedConfig.authMode,
18084
- setSession,
18085
- resetInitialization,
18086
- setConnectOpen,
18087
- setStatus: setWalletStatus,
18088
- setError: setHostedError,
18089
- smartAccountRefresh: smartAccount.refresh,
18090
- track
18091
- });
18092
18462
  const setDirectAuthRequested = useCallback((pending2) => {
18093
18463
  directAuthRequested.current = pending2;
18464
+ dialogAskedOnThisPage.current = pending2;
18094
18465
  try {
18095
18466
  if (pending2) window.sessionStorage.setItem(FLUENT_WIDGET_DIRECT_LOGIN_INTENT_KEY, "1");
18096
18467
  else window.sessionStorage.removeItem(FLUENT_WIDGET_DIRECT_LOGIN_INTENT_KEY);
@@ -18101,14 +18472,10 @@ function FluentWidgetContent({
18101
18472
  (trigger = "connect_button") => {
18102
18473
  track("connect_opened", { trigger });
18103
18474
  setAccountOpen(false);
18104
- setHostedError(null);
18105
- if (directAuth) {
18106
- setConnectOpen(true);
18107
- return;
18108
- }
18109
- beginHostedConnect();
18475
+ setLoginError(null);
18476
+ setConnectOpen(true);
18110
18477
  },
18111
- [beginHostedConnect, directAuth, setAccountOpen, setHostedError, track]
18478
+ [setAccountOpen, setLoginError, track]
18112
18479
  );
18113
18480
  const handleTopConnectClick = useCallback(() => {
18114
18481
  if (hasConnectedAccount) {
@@ -18131,7 +18498,7 @@ function FluentWidgetContent({
18131
18498
  fluentConnect.disconnect();
18132
18499
  removeStoredValue(resolveLocalStorage(), FLUENT_WIDGET_IDENTITY_TOKEN_STORAGE_KEY);
18133
18500
  setWalletStatus("Disconnected");
18134
- if (directAuth && authenticated) {
18501
+ if (authenticated) {
18135
18502
  try {
18136
18503
  await logout();
18137
18504
  } catch (error) {
@@ -18147,7 +18514,7 @@ function FluentWidgetContent({
18147
18514
  disconnectingRef.current = false;
18148
18515
  }
18149
18516
  if (awaitAuthSession) await authSessionEnded;
18150
- }, [activeWallet, authenticated, commitSilentSigningEnabled, connectedPresentation, directAuth, fluentConnect, logout, setDirectAuthRequested, setSession]);
18517
+ }, [activeWallet, authenticated, commitSilentSigningEnabled, connectedPresentation, fluentConnect, logout, setDirectAuthRequested, setSession]);
18151
18518
  const requestDisconnect = useCallback(() => {
18152
18519
  track("wallet_disconnected");
18153
18520
  return handleDisconnect({ awaitAuthSession: true });
@@ -18197,7 +18564,7 @@ function FluentWidgetContent({
18197
18564
  setStatus: setWalletStatus
18198
18565
  });
18199
18566
  const completeDirectAuthorization = useCallback(async () => {
18200
- if (!directAuth || !authenticated || !user?.id || directAuthInFlight.current) return;
18567
+ if (!authenticated || !user?.id || directAuthInFlight.current) return;
18201
18568
  if (disconnectingRef.current) return;
18202
18569
  if (walletUserPrivySession) return;
18203
18570
  if (session && !directAuthRequested.current && session.user?.id === user.id) return;
@@ -18207,7 +18574,7 @@ function FluentWidgetContent({
18207
18574
  }
18208
18575
  directAuthInFlight.current = true;
18209
18576
  setWalletStatus("Preparing Fluent account");
18210
- setHostedError(null);
18577
+ setLoginError(null);
18211
18578
  try {
18212
18579
  const kernel = smartAccount.kernel ?? await smartAccount.refresh();
18213
18580
  if (!kernel?.smartAccountAddress) {
@@ -18244,14 +18611,13 @@ function FluentWidgetContent({
18244
18611
  clearInlineOAuth();
18245
18612
  track("connect_login_failed", { reason: "direct_auth_failed" });
18246
18613
  debugError("[fluent widget] direct auth failed", error);
18247
- setHostedError(message2);
18614
+ setLoginError(message2);
18248
18615
  setWalletStatus(message2);
18249
18616
  } finally {
18250
18617
  directAuthInFlight.current = false;
18251
18618
  }
18252
18619
  }, [
18253
18620
  authenticated,
18254
- directAuth,
18255
18621
  fluentConnect,
18256
18622
  identityToken,
18257
18623
  resolvedConfig.scopes,
@@ -18266,7 +18632,6 @@ function FluentWidgetContent({
18266
18632
  walletUserPrivySession
18267
18633
  ]);
18268
18634
  useEffect(() => {
18269
- if (!directAuth) return;
18270
18635
  if (disconnectingRef.current) return;
18271
18636
  if (!privyReady || !authenticated) return;
18272
18637
  if (embeddedWalletCount === 0) return;
@@ -18274,7 +18639,6 @@ function FluentWidgetContent({
18274
18639
  }, [
18275
18640
  authenticated,
18276
18641
  completeDirectAuthorization,
18277
- directAuth,
18278
18642
  embeddedWalletCount,
18279
18643
  identityToken,
18280
18644
  privyReady,
@@ -18282,13 +18646,8 @@ function FluentWidgetContent({
18282
18646
  smartAccount.smartAccountAddress,
18283
18647
  smartAccount.smartAccountReady
18284
18648
  ]);
18285
- useEffect(() => {
18286
- if (!pendingPrivyLoginRef.current || !privyReady || authenticated) return;
18287
- pendingPrivyLoginRef.current = false;
18288
- login();
18289
- }, [authenticated, login, pendingPrivyLoginRef, privyReady]);
18290
18649
  const startDirectFluentLogin = useCallback(async () => {
18291
- setHostedError(null);
18650
+ setLoginError(null);
18292
18651
  const live = privySessionNow.current;
18293
18652
  if (live.authenticated && !live.walletUserPrivySession) {
18294
18653
  setWalletStatus("Opening Fluent Connect ID");
@@ -18304,7 +18663,7 @@ function FluentWidgetContent({
18304
18663
  const message2 = error instanceof Error ? error.message : "Privy did not sign the previous session out.";
18305
18664
  debugWarn("[fluent widget] could not sign the wallet's Privy session out", error);
18306
18665
  setDirectAuthRequested(false);
18307
- setHostedError(message2);
18666
+ setLoginError(message2);
18308
18667
  setWalletStatus(message2);
18309
18668
  throw error instanceof Error ? error : new Error(message2);
18310
18669
  }
@@ -18314,27 +18673,19 @@ function FluentWidgetContent({
18314
18673
  setConnectOpen(true);
18315
18674
  }, [completeDirectAuthorization, setDirectAuthRequested]);
18316
18675
  useEffect(() => {
18317
- if (!directAuth || inlineLoginRequest <= handledInlineLoginRequest.current) return;
18676
+ if (inlineLoginRequest <= handledInlineLoginRequest.current) return;
18318
18677
  handledInlineLoginRequest.current = inlineLoginRequest;
18319
- setHostedError(null);
18678
+ setLoginError(null);
18320
18679
  setDirectAuthRequested(true);
18321
18680
  setConnectOpen(true);
18322
- }, [directAuth, inlineLoginRequest, handledInlineLoginRequest, setDirectAuthRequested]);
18681
+ }, [inlineLoginRequest, handledInlineLoginRequest, setDirectAuthRequested]);
18323
18682
  const handleConnectWithX = useCallback(async () => {
18324
18683
  await handleDisconnect({ awaitAuthSession: false });
18325
- if (directAuth) {
18326
- void startDirectFluentLogin().catch(() => void 0);
18327
- return;
18328
- }
18329
- openConnectFlow();
18330
- }, [directAuth, handleDisconnect, openConnectFlow, startDirectFluentLogin]);
18684
+ void startDirectFluentLogin().catch(() => void 0);
18685
+ }, [handleDisconnect, startDirectFluentLogin]);
18331
18686
  const signInWithFluent = useCallback(() => {
18332
- if (directAuth) {
18333
- void startDirectFluentLogin().catch(() => void 0);
18334
- return;
18335
- }
18336
- openConnectFlow();
18337
- }, [directAuth, openConnectFlow, startDirectFluentLogin]);
18687
+ void startDirectFluentLogin().catch(() => void 0);
18688
+ }, [startDirectFluentLogin]);
18338
18689
  const closeAccountMenu = useCallback(() => setAccountOpen(false), [setAccountOpen]);
18339
18690
  const reviewOriginRef = useRef(null);
18340
18691
  const openReviewPage = useCallback(() => {
@@ -18383,7 +18734,7 @@ function FluentWidgetContent({
18383
18734
  selectedGasPaymentToken,
18384
18735
  confirmBatchOperation,
18385
18736
  defaultSponsorship: resolvedConfig.gasPayment.sponsorship,
18386
- authMode: resolvedConfig.authMode,
18737
+ quickSignWhitelist: resolvedConfig.quickSign.whitelistAddresses,
18387
18738
  confirmSignature,
18388
18739
  refreshBalances,
18389
18740
  track
@@ -18442,7 +18793,6 @@ function FluentWidgetContent({
18442
18793
  {
18443
18794
  publicApiUrl: resolvedConfig.publicApiUrl,
18444
18795
  appId: resolvedConfig.appId,
18445
- authMode: resolvedConfig.authMode,
18446
18796
  renewalOffsetSeconds: resolvedConfig.authTokenRenewalOffsetSeconds,
18447
18797
  accountType: widgetAccount.type,
18448
18798
  privyUserId: user?.id,
@@ -18502,7 +18852,7 @@ function FluentWidgetContent({
18502
18852
  waiting.reject(error);
18503
18853
  return true;
18504
18854
  }, []);
18505
- const { linkTwitter } = useLinkAccount({
18855
+ const { linkTwitter } = useLinkAccount2({
18506
18856
  onError: (code) => {
18507
18857
  const error = toLinkXPrivyError(code);
18508
18858
  debugWarn("[fluent widget] linking X failed", { code, fluentCode: error.code });
@@ -18742,12 +19092,6 @@ function FluentWidgetContent({
18742
19092
  []
18743
19093
  );
18744
19094
  const linkX = useCallback(async () => {
18745
- if (resolvedConfig.authMode !== "direct") {
18746
- throw new FluentAuthError(
18747
- "hosted_not_supported",
18748
- `linkX() needs authMode: "direct" \u2014 in hosted mode the user's Privy session lives on the authorize page, not in this page.`
18749
- );
18750
- }
18751
19095
  const storage = resolveSessionStorage();
18752
19096
  const stored = readLinkXMarker(storage);
18753
19097
  if (stored.kind === "invalid") {
@@ -18765,7 +19109,6 @@ function FluentWidgetContent({
18765
19109
  }
18766
19110
  const live = linkXInputs.current;
18767
19111
  return requestLinkX({
18768
- authMode: resolvedConfig.authMode,
18769
19112
  accountKind: live.accountKind,
18770
19113
  subject: live.privyUserId,
18771
19114
  wallet: live.wallet,
@@ -18822,10 +19165,9 @@ function FluentWidgetContent({
18822
19165
  awaitLinkXReturn,
18823
19166
  linkTwitterForLinkX,
18824
19167
  logoutPrivyForLinkX,
18825
- resolvedConfig.authMode,
18826
19168
  resolvedConfig.publicApiUrl
18827
19169
  ]);
18828
- const sessionPrivyUserId = directAuth ? session?.user?.id : void 0;
19170
+ const sessionPrivyUserId = session?.user?.id;
18829
19171
  const fluentIdRebuilding = Boolean(sessionPrivyUserId) && smartAccount.smartAccountEnabled && !derivedAccount.fluentAccountReady && !smartAccount.error;
18830
19172
  const settingsAccountKind = fluentIdRebuilding ? void 0 : widgetAccount.type;
18831
19173
  const {
@@ -18839,7 +19181,6 @@ function FluentWidgetContent({
18839
19181
  state: userSettingsRef,
18840
19182
  publicApiUrl: resolvedConfig.publicApiUrl,
18841
19183
  appId: resolvedConfig.appId,
18842
- authMode: resolvedConfig.authMode,
18843
19184
  network: resolvedConfig.network,
18844
19185
  accountType: settingsAccountKind,
18845
19186
  defaultGasToken: resolvedConfig.gasPayment.defaultToken,
@@ -18883,10 +19224,34 @@ function FluentWidgetContent({
18883
19224
  },
18884
19225
  [onGasTokenChange, setGasPaymentToken]
18885
19226
  );
19227
+ const { linkWithPasskey } = useLinkWithPasskey2();
19228
+ const addPasskey = useCallback(() => linkWithPasskey(), [linkWithPasskey]);
19229
+ const removePasskey = useCallback(
19230
+ async (credentialId) => {
19231
+ await unlinkPasskey(credentialId);
19232
+ },
19233
+ [unlinkPasskey]
19234
+ );
19235
+ const passkeyOffered = settingsAccountKind === "smart" && authenticated && user !== null;
19236
+ const passkeys = useMemo(() => {
19237
+ const accounts = user?.linkedAccounts ?? [];
19238
+ return accounts.filter((account2) => account2.type === "passkey").map((account2) => ({
19239
+ credentialId: account2.credentialId,
19240
+ label: account2.authenticatorName || [account2.createdWithBrowser, account2.createdWithOs].filter(Boolean).join(" on ") || "Passkey",
19241
+ addedOn: account2.firstVerifiedAt ? new Date(account2.firstVerifiedAt).toLocaleDateString(void 0, {
19242
+ year: "numeric",
19243
+ month: "short",
19244
+ day: "numeric"
19245
+ }) : void 0
19246
+ }));
19247
+ }, [user?.linkedAccounts]);
19248
+ const userAvatarUrl = resolvedConfig.avatar.forceDefault || accountMenuIsExternalWallet ? void 0 : getHighResTwitterAvatar(user?.twitter?.profilePictureUrl) || void 0;
19249
+ const defaultLogoUrl = resolvedConfig.avatar.defaultLogoUrl;
18886
19250
  const context = useMemo(
18887
19251
  () => ({
18888
19252
  session,
18889
19253
  connectedAddress,
19254
+ userAvatarUrl,
18890
19255
  wallet: activeWallet,
18891
19256
  widget: widgetApi,
18892
19257
  openConnect,
@@ -18897,12 +19262,12 @@ function FluentWidgetContent({
18897
19262
  connecting,
18898
19263
  refreshBalances,
18899
19264
  getAuthToken,
18900
- linkX,
18901
- authMode: resolvedConfig.authMode
19265
+ linkX
18902
19266
  }),
18903
19267
  [
18904
19268
  session,
18905
19269
  connectedAddress,
19270
+ userAvatarUrl,
18906
19271
  activeWallet,
18907
19272
  widgetApi,
18908
19273
  openConnect,
@@ -18913,12 +19278,9 @@ function FluentWidgetContent({
18913
19278
  connecting,
18914
19279
  refreshBalances,
18915
19280
  getAuthToken,
18916
- linkX,
18917
- resolvedConfig.authMode
19281
+ linkX
18918
19282
  ]
18919
19283
  );
18920
- const accountAvatarUrl = resolvedConfig.avatar.forceDefault || accountMenuIsExternalWallet ? void 0 : getHighResTwitterAvatar(user?.twitter?.profilePictureUrl);
18921
- const defaultLogoUrl = resolvedConfig.avatar.defaultLogoUrl;
18922
19284
  const widget = /* @__PURE__ */ jsxs(FluentPortalContainerProvider, { children: [
18923
19285
  /* @__PURE__ */ jsx(FluentTopLayerBridge, {}),
18924
19286
  !session && connectedWalletAddress !== void 0 ? /* @__PURE__ */ jsx(LinkXSiweSource, { source: linkXSiwe }) : null,
@@ -18935,7 +19297,7 @@ function FluentWidgetContent({
18935
19297
  subPageTitle: subPage?.title ?? null,
18936
19298
  subPageDismiss: subPage?.dismiss,
18937
19299
  onCloseSubPage: closeSubPage,
18938
- userLogoUrl: accountAvatarUrl,
19300
+ userLogoUrl: userAvatarUrl,
18939
19301
  defaultLogoUrl,
18940
19302
  connectButton: /* @__PURE__ */ jsx(
18941
19303
  FluentConnectButtonSlot,
@@ -18950,7 +19312,7 @@ function FluentWidgetContent({
18950
19312
  openAccount: openAccountMenu,
18951
19313
  renderConnectButton,
18952
19314
  connectButton,
18953
- userLogoUrl: accountAvatarUrl,
19315
+ userLogoUrl: userAvatarUrl,
18954
19316
  defaultLogoUrl
18955
19317
  }
18956
19318
  ),
@@ -18997,7 +19359,10 @@ function FluentWidgetContent({
18997
19359
  onMintUsdnr: mintUsdnr,
18998
19360
  mintUsdnrBusy: mintingUsdnr,
18999
19361
  onRevealAccount: () => setAccountOpen(true),
19000
- gasContext
19362
+ gasContext,
19363
+ onAddPasskey: passkeyOffered ? addPasskey : void 0,
19364
+ onRemovePasskey: passkeyOffered ? removePasskey : void 0,
19365
+ passkeys
19001
19366
  }
19002
19367
  ) : /* @__PURE__ */ jsx(
19003
19368
  BridgeScreen,
@@ -19018,38 +19383,33 @@ function FluentWidgetContent({
19018
19383
  session,
19019
19384
  wallet: activeWallet,
19020
19385
  walletStatus,
19021
- hostedError
19386
+ loginError
19022
19387
  }
19023
19388
  ) : null,
19024
19389
  /* @__PURE__ */ jsx(
19025
- ConnectChoiceModal,
19390
+ InlineConnectModal,
19026
19391
  {
19027
19392
  open: connectOpen,
19028
19393
  onClose: () => {
19029
19394
  setConnectOpen(false);
19030
- if (directAuth) setDirectAuthRequested(false);
19395
+ setDirectAuthRequested(false);
19031
19396
  },
19032
19397
  onRetry: () => {
19033
- setHostedError(null);
19398
+ setLoginError(null);
19034
19399
  void completeDirectAuthorization();
19035
19400
  },
19036
19401
  wallet: activeWallet,
19037
- fluentReady: directAuth ? privyReady : true,
19038
- authMode: resolvedConfig.authMode,
19039
19402
  walletUserPrivySession,
19040
19403
  signInRefusal: directLoginSignInRefusal,
19041
19404
  config,
19042
- fluentAuthorizeUrl: directAuth ? void 0 : hostedAuthorizeUrl,
19043
- hostedError: hostedError ?? smartAccount.error?.message,
19405
+ loginError: loginError ?? smartAccount.error?.message,
19044
19406
  track,
19045
19407
  onExternalWalletSelected: () => {
19046
19408
  externalWalletAnalytics.current.intent = true;
19047
19409
  },
19048
19410
  onFluentLogin: () => {
19049
19411
  track("connect_login_started");
19050
- if (directAuth) return startDirectFluentLogin();
19051
- setWalletStatus("Opening hosted Fluent Connect ID");
19052
- return void 0;
19412
+ return startDirectFluentLogin();
19053
19413
  }
19054
19414
  }
19055
19415
  ),
@@ -19069,7 +19429,7 @@ function FluentWidgetContent({
19069
19429
  function LinkXSiweSource({
19070
19430
  source
19071
19431
  }) {
19072
- const { generateSiweMessage, loginWithSiwe } = useLoginWithSiwe();
19432
+ const { generateSiweMessage, loginWithSiwe } = useLoginWithSiwe2();
19073
19433
  source.current = { generateSiweMessage, loginWithSiwe };
19074
19434
  useEffect(
19075
19435
  () => () => {
@@ -19093,10 +19453,8 @@ function FluentWidget(props) {
19093
19453
  FLUENT_CONNECT_DEFAULT_SILENT_SIGNING
19094
19454
  );
19095
19455
  const silentSigningRemountTimer = useRef(null);
19096
- const [privyEpoch, setPrivyEpoch] = useState(0);
19097
19456
  const [inlineLoginRequest, setInlineLoginRequest] = useState(0);
19098
19457
  const handledInlineLoginRequest = useRef(0);
19099
- const pendingPrivyLoginRef = useRef(false);
19100
19458
  const [accountOpen, setAccountOpen] = useState(false);
19101
19459
  const [walletMenuTab, setWalletMenuTab] = useState("home");
19102
19460
  const [gasPaymentToken, setGasPaymentToken] = useState(
@@ -19199,8 +19557,9 @@ function FluentWidget(props) {
19199
19557
  }, [flushTabViewOnUnload, pauseTabView, resumeTabView]);
19200
19558
  const privyConfig = useMemo(
19201
19559
  () => ({
19202
- // Inline direct login owns its captcha. Privy still owns MFA, recovery and signing UI.
19203
- headless: resolvedConfig.authMode === "direct",
19560
+ // The in-page sign-in dialog owns its captcha. Privy still owns MFA, recovery
19561
+ // and signing UI.
19562
+ headless: true,
19204
19563
  ...createFluentConnectPrivyConfig({
19205
19564
  network: resolvedNetwork,
19206
19565
  logo: props.config?.assets?.fluentLogo ?? FLUENT_CONNECT_DEFAULT_ASSETS.fluentLogo,
@@ -19209,14 +19568,13 @@ function FluentWidget(props) {
19209
19568
  }),
19210
19569
  [
19211
19570
  props.config?.assets?.fluentLogo,
19212
- resolvedConfig.authMode,
19213
19571
  resolvedConfig.customOAuthRedirectUrl,
19214
19572
  resolvedNetwork
19215
19573
  ]
19216
19574
  );
19217
19575
  useLayoutEffect(() => {
19218
19576
  clearPrivyRecentLoginMethod(FLUENT_CONNECT_PRIVY_APP_ID);
19219
- }, [privyEpoch]);
19577
+ }, []);
19220
19578
  const applySilentSigningEnabled = useCallback((enabled) => {
19221
19579
  setSilentSigningEnabled(enabled);
19222
19580
  }, []);
@@ -19246,13 +19604,8 @@ function FluentWidget(props) {
19246
19604
  );
19247
19605
  const requestPrivyLogin = useCallback(() => {
19248
19606
  clearPrivyRecentLoginMethod(FLUENT_CONNECT_PRIVY_APP_ID);
19249
- if (resolvedConfig.authMode === "direct") {
19250
- setInlineLoginRequest((value) => value + 1);
19251
- return;
19252
- }
19253
- pendingPrivyLoginRef.current = true;
19254
- setPrivyEpoch((value) => value + 1);
19255
- }, [resolvedConfig.authMode]);
19607
+ setInlineLoginRequest((value) => value + 1);
19608
+ }, []);
19256
19609
  useEffect(() => {
19257
19610
  return () => {
19258
19611
  if (silentSigningRemountTimer.current) {
@@ -19268,8 +19621,9 @@ function FluentWidget(props) {
19268
19621
  disableAnalytics: resolvedConfig.disableAnalytics,
19269
19622
  reconnectOnMount: resolvedConfig.reconnectOnMount,
19270
19623
  children: /* @__PURE__ */ jsx(
19271
- PrivyProvider,
19624
+ FluentPrivyProvider,
19272
19625
  {
19626
+ adapter: props.privyAdapter,
19273
19627
  appId: FLUENT_CONNECT_PRIVY_APP_ID,
19274
19628
  clientId: privyClientId,
19275
19629
  config: privyConfig,
@@ -19293,19 +19647,18 @@ function FluentWidget(props) {
19293
19647
  requestPrivyLogin,
19294
19648
  inlineLoginRequest,
19295
19649
  handledInlineLoginRequest,
19296
- pendingPrivyLoginRef,
19297
19650
  authTokenState,
19298
19651
  userSettingsRef: userSettings,
19299
19652
  connectedPresentation
19300
19653
  }
19301
19654
  )
19302
19655
  },
19303
- `${resolvedNetwork}-${privyEpoch}`
19656
+ resolvedNetwork
19304
19657
  )
19305
19658
  }
19306
19659
  ) });
19307
19660
  }
19308
19661
 
19309
- export { AccountAvatar, Button, Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogOverlay, DialogPortal, DialogTitle, DialogTrigger, FLUENT_CONNECT_DEFAULT_ASSETS, FLUENT_GAS_PAYMENT_DEFAULT_ETH_RATES, FLUENT_USER_TOKEN_LIMIT, FLUENT_WIDGET_DEFAULT_GAS_TOKEN, FLUENT_WIDGET_SESSION_STORAGE_KEY, FLUENT_WIDGET_USER_TOKENS_IMPORT_MARKER_KEY, FLUENT_WIDGET_USER_TOKENS_STORAGE_KEY, FLUENT_ZERODEV_ERC20_PAYMASTER_QUERY, FLUENT_ZERODEV_PAYMASTER_DEMO_RECIPIENT, FluentAccountDrawer, FluentAuthError, FluentIframeRpcError, FluentPortalContainerProvider, FluentReviewRejectedError, FluentSettingsError, FluentSponsorshipFallbackError, FluentWidget, FluentWidgetConnectButton, FluentWidgetNetworkProvider, Icon, Label, Separator, Switch, WIDGET_STYLE_SCOPE, WalletMenuActionCard, buildFluentTransferCall, buttonVariants, checkFluentTransferFee, clearPrivyRecentLoginMethod, createFluentBackendUserTokenStore, createFluentBatchOp, createFluentClient, createFluentFamiliesClient, createFluentIframeBridge, createFluentIframeRpcHandler, createFluentPermissionApi, createFluentPermissionClient, createFluentPermissionPolicyBuilders, createFluentPermissionSession, createFluentSettingsClient, createFluentSponsorshipRpcUrl, createFluentUserTokenStore, createFluentZeroDevErc20Paymaster, createFluentZeroDevErc20PaymasterApprovalCall, createFluentZeroDevErc20PaymasterClient, createFluentZeroDevErc20PaymasterRpcUrl, createFluentZeroDevPermissionSession, createFluentZeroDevRpcUrl, createFluentZeroDevSponsoredPaymaster, deriveFluentGasEthRates, findFluentSymbolCollisions, fluent2 as fluent, apps as fluentApps, fluentBridgeAbi, fluent as fluentChain, fluentChains, fluentDefinitionToViemChain, integrations as fluentIntegrations, l1Chains as fluentL1Chains, fluentMainnet, fluentMainnetTokenDefaults, fluentTestnet, fluentTestnetTokenDefaults, fluentTokenIdentity, fluentTransferAbi, fluentZeroDevChainIds, getApp, getContractAddressFromChain, getFluentChain, getFluentChainByChainId, getFluentChainForNetwork, getFluentDefaultWidgetDisplayTokens, getFluentDefaultWidgetGasTokens, getFluentExplorerBaseUrl, getFluentGasPaymentEthValue, getFluentGasPaymentTokens, getFluentGasPaymentValueTier, getFluentGasTokenAddress, getFluentTokenDefaults, getFluentTokenDefaultsForNetwork, getFluentZeroDevErc20PaymasterTokens, getL1Chain, getL1ForFluentChain, getZeroDevRpcUrl, getZerodevIntegration, isFaucetNetwork, isFluentDefaultToken, isFluentNativeToken, isFluentZeroDevChain, l1DefinitionToViemChain, mergeFluentDisplayTokens, normalizeFluentWidgetNetwork, parseFluentTransferAmount, parseFluentTransferRecipient, readFluentTokenBalances, readFluentTokenMetadata, registryVersion, resolveBridgeAddresses, resolveDefaultGasToken, resolveFluentWidgetNetworkFromEnv, resolveFluentZeroDevErc20PaymasterToken, resolveL1Definition, selectFluentGasPaymentToken, sendFluentZeroDevErc20PaymasterDemo, sortFluentGasTokens, useFluentIframeBridge, useFluentUserTokens, useFluentWidget, useFluentWidgetNetwork, useFluentZeroDevAccount, useLinkX, useWidget, withFluentSignaturePrompt };
19662
+ export { AccountAvatar, Button, Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogOverlay, DialogPortal, DialogTitle, DialogTrigger, FLUENT_CONNECT_DEFAULT_ASSETS, FLUENT_GAS_PAYMENT_DEFAULT_ETH_RATES, FLUENT_USER_TOKEN_LIMIT, FLUENT_WIDGET_DEFAULT_GAS_TOKEN, FLUENT_WIDGET_SESSION_STORAGE_KEY, FLUENT_WIDGET_USER_TOKENS_IMPORT_MARKER_KEY, FLUENT_WIDGET_USER_TOKENS_STORAGE_KEY, FLUENT_ZERODEV_ERC20_PAYMASTER_QUERY, FLUENT_ZERODEV_PAYMASTER_DEMO_RECIPIENT, FluentAccountDrawer, FluentAuthError, FluentIframeRpcError, FluentPortalContainerProvider, FluentReviewRejectedError, FluentSettingsError, FluentSponsorshipFallbackError, FluentUserOperationGasError, FluentWidget, FluentWidgetConfigError, FluentWidgetConnectButton, FluentWidgetNetworkProvider, Icon, Label, Separator, Switch, WIDGET_STYLE_SCOPE, WalletMenuActionCard, buildFluentTransferCall, buttonVariants, checkFluentTransferFee, clearPrivyRecentLoginMethod, createFluentBackendUserTokenStore, createFluentBatchOp, createFluentClient, createFluentFamiliesClient, createFluentIframeBridge, createFluentIframeRpcHandler, createFluentPermissionApi, createFluentPermissionClient, createFluentPermissionPolicyBuilders, createFluentPermissionSession, createFluentSettingsClient, createFluentSponsorshipRpcUrl, createFluentUserTokenStore, createFluentZeroDevErc20Paymaster, createFluentZeroDevErc20PaymasterApprovalCall, createFluentZeroDevErc20PaymasterClient, createFluentZeroDevErc20PaymasterRpcUrl, createFluentZeroDevPermissionSession, createFluentZeroDevRpcUrl, createFluentZeroDevSponsoredPaymaster, deriveFluentGasEthRates, findFluentSymbolCollisions, fluent2 as fluent, apps as fluentApps, fluentBridgeAbi, fluent as fluentChain, fluentChains, fluentDefinitionToViemChain, integrations as fluentIntegrations, l1Chains as fluentL1Chains, fluentMainnet, fluentMainnetTokenDefaults, fluentTestnet, fluentTestnetTokenDefaults, fluentTokenIdentity, fluentTransferAbi, fluentZeroDevChainIds, getApp, getContractAddressFromChain, getFluentChain, getFluentChainByChainId, getFluentChainForNetwork, getFluentDefaultWidgetDisplayTokens, getFluentDefaultWidgetGasTokens, getFluentExplorerBaseUrl, getFluentGasPaymentEthValue, getFluentGasPaymentTokens, getFluentGasPaymentValueTier, getFluentGasTokenAddress, getFluentTokenDefaults, getFluentTokenDefaultsForNetwork, getFluentZeroDevErc20PaymasterTokens, getL1Chain, getL1ForFluentChain, getZeroDevRpcUrl, getZerodevIntegration, isFaucetNetwork, isFluentDefaultToken, isFluentNativeToken, isFluentZeroDevChain, l1DefinitionToViemChain, mergeFluentDisplayTokens, normalizeFluentWidgetNetwork, parseFluentTransferAmount, parseFluentTransferRecipient, readFluentTokenBalances, readFluentTokenMetadata, registryVersion, resolveBridgeAddresses, resolveDefaultGasToken, resolveFluentWidgetNetworkFromEnv, resolveFluentZeroDevErc20PaymasterToken, resolveL1Definition, selectFluentGasPaymentToken, sendFluentZeroDevErc20PaymasterDemo, sortFluentGasTokens, useFluentIframeBridge, useFluentUserTokens, useFluentWidget, useFluentWidgetNetwork, useFluentZeroDevAccount, useLinkX, useWidget };
19310
19663
  //# sourceMappingURL=index.js.map
19311
19664
  //# sourceMappingURL=index.js.map