@fluent.xyz/connect 0.2.3 → 0.3.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,6 +1,6 @@
1
1
  import { toEventSelector, parseAbiItem, defineChain, http, createPublicClient, formatUnits, isAddress, getAddress, encodeFunctionData, parseUnits, zeroAddress, numberToHex, BaseError, HttpRequestError, fallback, isHex, stringToHex, bytesToHex } from 'viem';
2
2
  import * as React2 from 'react';
3
- import { createContext, forwardRef, useContext, useMemo, useState, useCallback, useRef, useEffect, useLayoutEffect } from 'react';
3
+ import { createContext, forwardRef, useContext, useMemo, useState, useCallback, useLayoutEffect, useRef, useEffect } from 'react';
4
4
  import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
5
5
  import { toCallPolicy, CallPolicyVersion, toTimestampPolicy, CallType, ParamCondition } from '@zerodev/permissions/policies';
6
6
  export { CallType, ParamCondition } from '@zerodev/permissions/policies';
@@ -5262,32 +5262,40 @@ var FLUENT_FAMILY_TIER_PROGRESS = {
5262
5262
  C: 33,
5263
5263
  D: 0
5264
5264
  };
5265
+ var APP_ID_PATTERN = /^app_[0-9a-f]{32}$/;
5266
+ var APP_ID_HINT = "Pass the app_<32 hex> id from the Fluent Dashboard as appId.";
5265
5267
  function resolveFluentWidgetConfig(config) {
5266
5268
  if (config.clientId !== void 0) {
5267
5269
  throw new Error(
5268
- "FluentWidgetConfig.clientId was replaced in the PartnerId cutover. Pass partnerId (the partner_<32 hex> id from the Fluent console) and the Privy app client as privyClientId \u2014 both are required."
5270
+ `FluentWidgetConfig.clientId was removed in 0.2.0. ${APP_ID_HINT} Pass the Privy app client as privyClientId \u2014 both are required.`
5269
5271
  );
5270
5272
  }
5271
- const partnerId = (config.partnerId ?? "").trim();
5272
- if (!partnerId) {
5273
+ if (config.partnerId !== void 0) {
5274
+ throw new Error(`FluentWidgetConfig.partnerId was renamed to appId in 0.3.0. ${APP_ID_HINT}`);
5275
+ }
5276
+ const appId = (config.appId ?? "").trim();
5277
+ if (!appId) {
5278
+ throw new Error(`FluentWidgetConfig.appId is required. ${APP_ID_HINT}`);
5279
+ }
5280
+ if (appId.startsWith("client-")) {
5273
5281
  throw new Error(
5274
- "FluentWidgetConfig.partnerId is required. Pass the partner_<32 hex> id from the Fluent console."
5282
+ `FluentWidgetConfig.appId "${appId}" is a Privy app client, not an app id. Pass the app_<32 hex> id as appId and the Privy client as privyClientId.`
5275
5283
  );
5276
5284
  }
5277
- if (partnerId.startsWith("client-")) {
5285
+ if (!APP_ID_PATTERN.test(appId)) {
5278
5286
  throw new Error(
5279
- `FluentWidgetConfig.partnerId "${partnerId}" is a Privy app client, not a partner id. Pass the partner_<32 hex> id as partnerId and the Privy client as privyClientId.`
5287
+ `FluentWidgetConfig.appId "${appId}" is not an app id. Expected app_<32 hex> (lowercase), the id the Fluent Dashboard shows for the App.`
5280
5288
  );
5281
5289
  }
5282
5290
  const privyClientId = (config.privyClientId ?? "").trim();
5283
5291
  if (!privyClientId) {
5284
5292
  throw new Error(
5285
- "FluentWidgetConfig.privyClientId is required. Pass the Privy app client issued by Fluent for this partner."
5293
+ "FluentWidgetConfig.privyClientId is required. Pass the Privy app client issued by Fluent for this App."
5286
5294
  );
5287
5295
  }
5288
- if (privyClientId.startsWith("partner_")) {
5296
+ if (privyClientId.startsWith("app_")) {
5289
5297
  throw new Error(
5290
- `FluentWidgetConfig.privyClientId "${privyClientId}" is a partner id, not a Privy app client. Swap the two: partnerId takes the partner_<32 hex> id, privyClientId the client-\u2026 value.`
5298
+ `FluentWidgetConfig.privyClientId "${privyClientId}" is an app id, not a Privy app client. Swap the two: appId takes the app_<32 hex> id, privyClientId the client-\u2026 value.`
5291
5299
  );
5292
5300
  }
5293
5301
  if (!privyClientId.startsWith("client-")) {
@@ -5300,7 +5308,7 @@ function resolveFluentWidgetConfig(config) {
5300
5308
  return {
5301
5309
  network,
5302
5310
  appName: config.appName ?? "Fluent Connect Demo",
5303
- partnerId,
5311
+ appId,
5304
5312
  privyClientId,
5305
5313
  authMode: config.authMode ?? "hosted",
5306
5314
  authorizeUrl: endpoints.authorizeUrl,
@@ -5572,7 +5580,7 @@ function toAuthError(err) {
5572
5580
  async function exchangePrivyAuthToken(params) {
5573
5581
  try {
5574
5582
  const { token } = await postJson(`${params.publicApiUrl}/auth/exchange/privy`, {
5575
- partnerId: params.partnerId,
5583
+ appId: params.appId,
5576
5584
  accessToken: params.accessToken,
5577
5585
  identityToken: params.identityToken
5578
5586
  });
@@ -5584,7 +5592,7 @@ async function exchangePrivyAuthToken(params) {
5584
5592
  async function exchangeWalletAuthToken(params) {
5585
5593
  const attempt = async () => {
5586
5594
  const challenge = await postJson(`${params.publicApiUrl}/auth/challenge`, {
5587
- partnerId: params.partnerId,
5595
+ appId: params.appId,
5588
5596
  address: params.address
5589
5597
  });
5590
5598
  if (challenge.typedData.message.origin !== params.origin) {
@@ -5598,7 +5606,7 @@ async function exchangeWalletAuthToken(params) {
5598
5606
  ...challenge.typedData
5599
5607
  });
5600
5608
  const { token } = await postJson(`${params.publicApiUrl}/auth/exchange/wallet`, {
5601
- partnerId: params.partnerId,
5609
+ appId: params.appId,
5602
5610
  nonce: challenge.nonce,
5603
5611
  signature
5604
5612
  });
@@ -5950,7 +5958,7 @@ function createFluentZeroDevErc20PaymasterRpcUrl(params = {}) {
5950
5958
  }
5951
5959
  function createFluentSponsorshipRpcUrl(params) {
5952
5960
  const base = params.sponsorshipUrl.replace(/\/+$/, "");
5953
- return `${base}/paymaster/${encodeURIComponent(params.partnerId)}`;
5961
+ return `${base}/paymaster/${encodeURIComponent(params.appId)}`;
5954
5962
  }
5955
5963
  function createFluentZeroDevSponsoredPaymaster(params) {
5956
5964
  const paymasterClient = createZeroDevPaymasterClient({
@@ -6127,1430 +6135,1452 @@ function createFluentBundlerTransport(url) {
6127
6135
  });
6128
6136
  }
6129
6137
 
6130
- // src/widget/zerodevSession.ts
6131
- function useFluentZeroDevAccount(hookOptions = {}) {
6132
- const { chain, network } = useFluentWidgetNetwork();
6133
- const { authenticated, getAccessToken, login: privyLogin, ready } = usePrivy();
6134
- const login = hookOptions.login ?? privyLogin;
6135
- const { signMessage: promptSignMessage } = useSignMessage();
6136
- const { signTypedData: promptSignTypedData } = useSignTypedData();
6137
- const { wallets } = useWallets();
6138
- const [kernels, setKernels] = useState({});
6139
- const [error, setError] = useState(null);
6140
- const [smartAccountReady, setSmartAccountReady] = useState(false);
6141
- const initPromise = useRef({});
6142
- const sponsorshipUnavailable = useRef(false);
6143
- const embeddedWallet = wallets.find((wallet) => wallet.walletClientType === "privy");
6144
- const hostedSigner = useMemo(
6145
- () => hookOptions.allowHostedSigner !== false && hookOptions.authorizeUrl && hookOptions.sessionSignerAddress ? createFluentHostedSigner({
6146
- address: hookOptions.sessionSignerAddress,
6147
- authorizeUrl: hookOptions.authorizeUrl
6148
- }) : null,
6149
- [
6150
- hookOptions.allowHostedSigner,
6151
- hookOptions.authorizeUrl,
6152
- hookOptions.sessionSignerAddress
6153
- ]
6154
- );
6155
- const activeKernel = kernels.prompt ?? kernels.silent ?? null;
6156
- useEffect(() => {
6157
- setKernels({});
6158
- setSmartAccountReady(false);
6159
- setError(null);
6160
- initPromise.current = {};
6161
- }, [chain.id]);
6162
- useEffect(() => () => hostedSigner?.close(), [hostedSigner]);
6163
- const initialize2 = useCallback(async (options = {}) => {
6164
- const signerMode = options.signerMode ?? "prompt";
6165
- const cachedKernel = kernels[signerMode];
6166
- debugLog("[fluent zerodev] initialize requested", {
6167
- signerMode,
6168
- ready,
6169
- authenticated,
6170
- walletCount: wallets.length,
6171
- embeddedWalletCount: wallets.filter((wallet) => wallet.walletClientType === "privy").length,
6172
- embeddedWallet: embeddedWallet?.address,
6173
- hasKernel: Boolean(cachedKernel),
6174
- cachedSignerModes: Object.keys(kernels),
6175
- initInFlight: Boolean(initPromise.current[signerMode]),
6176
- throwOnError: Boolean(options.throwOnError),
6177
- hasProjectId: Boolean(FLUENT_CONNECT_ZERODEV_PROJECT_ID)
6178
- });
6179
- if (cachedKernel) {
6180
- debugLog("[fluent zerodev] using cached kernel", {
6181
- signerMode,
6182
- smartAccountAddress: cachedKernel.smartAccountAddress
6183
- });
6184
- return cachedKernel;
6138
+ // src/utils/buildFluentBridgeUrl.ts
6139
+ function buildFluentBridgeUrl(bridgeUrl, recipient) {
6140
+ if (!recipient) return bridgeUrl;
6141
+ try {
6142
+ const url = new URL(bridgeUrl);
6143
+ url.searchParams.set("recipient", recipient);
6144
+ return url.toString();
6145
+ } catch {
6146
+ const join = bridgeUrl.includes("?") ? "&" : "?";
6147
+ return `${bridgeUrl}${join}recipient=${encodeURIComponent(recipient)}`;
6148
+ }
6149
+ }
6150
+
6151
+ // src/utils/clearPrivyRecentLoginMethod.ts
6152
+ function clearPrivyRecentLoginMethod(appId) {
6153
+ if (typeof window === "undefined" || !appId) return;
6154
+ try {
6155
+ window.localStorage.removeItem(`privy:${appId}:recent-login-method`);
6156
+ window.localStorage.removeItem(`privy:${appId}:recent-login-wallet-client`);
6157
+ window.localStorage.removeItem(`privy:${appId}:recent-login-chain-type`);
6158
+ } catch {
6159
+ }
6160
+ }
6161
+ function cn(...inputs) {
6162
+ return twMerge(clsx(inputs));
6163
+ }
6164
+ var WIDGET_STYLE_SCOPE = "fluent-root dark contents text-foreground";
6165
+ var FluentPortalContainerContext = createContext(null);
6166
+ function FluentPortalContainerProvider({ children }) {
6167
+ const [container, setContainer] = useState(null);
6168
+ useLayoutEffect(() => {
6169
+ const element = document.createElement("div");
6170
+ element.setAttribute("data-fluent-portal-root", "");
6171
+ element.className = WIDGET_STYLE_SCOPE;
6172
+ document.body.appendChild(element);
6173
+ setContainer(element);
6174
+ return () => {
6175
+ element.remove();
6176
+ setContainer(null);
6177
+ };
6178
+ }, []);
6179
+ return /* @__PURE__ */ jsx(FluentPortalContainerContext.Provider, { value: container, children });
6180
+ }
6181
+ function useFluentPortalContainer(override) {
6182
+ const container = useContext(FluentPortalContainerContext);
6183
+ return override ?? container ?? void 0;
6184
+ }
6185
+ var buttonVariants = cva(
6186
+ "group/button inline-flex shrink-0 items-center justify-center rounded-xl border border-transparent bg-clip-padding font-medium whitespace-nowrap transition-all duration-75 outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
6187
+ {
6188
+ variants: {
6189
+ variant: {
6190
+ default: "bg-primary text-primary-foreground hover:bg-primary/80",
6191
+ outline: "border-border bg-background hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",
6192
+ secondary: "bg-button text-button-foreground hover:bg-button-hover aria-expanded:bg-button aria-expanded:text-button-foreground",
6193
+ ghost: "hover:bg-primary/10 hover:text-foreground dark:hover:bg-primary/10",
6194
+ destructive: "bg-destructive/10 text-destructive hover:bg-destructive/20 focus-visible:border-destructive/40 focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:hover:bg-destructive/30 dark:focus-visible:ring-destructive/40",
6195
+ link: "text-primary underline-offset-4 hover:underline"
6196
+ },
6197
+ size: {
6198
+ default: "h-10 gap-1.5 px-3.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2 text-sm",
6199
+ xs: "h-6 gap-1 rounded-[min(var(--radius-md),10px)] px-2 text-xs in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3",
6200
+ sm: "h-7 gap-1 rounded-[min(var(--radius-md),12px)] px-2.5 text-[0.8rem] in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5",
6201
+ lg: "h-9 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
6202
+ icon: "size-8",
6203
+ "icon-xs": "size-6 rounded-[min(var(--radius-md),10px)] in-data-[slot=button-group]:rounded-lg [&_svg:not([class*='size-'])]:size-3",
6204
+ "icon-sm": "size-7 rounded-[min(var(--radius-md),12px)] in-data-[slot=button-group]:rounded-lg",
6205
+ "icon-lg": "size-9"
6206
+ }
6207
+ },
6208
+ defaultVariants: {
6209
+ variant: "default",
6210
+ size: "default"
6185
6211
  }
6186
- const canUseLocalSigner = ready && authenticated && Boolean(embeddedWallet);
6187
- const canUseHostedSigner = Boolean(hostedSigner);
6188
- const canUseAuthorizationSession = signerMode === "silent" && Boolean(hookOptions.authorizationSession?.serializedPermissionAccount) && (hookOptions.authorizationSession?.expiresAt ?? 0) > Math.floor(Date.now() / 1e3);
6189
- if (!canUseLocalSigner && !canUseHostedSigner && !canUseAuthorizationSession) {
6190
- const nextError = new Error(getZeroDevReadinessMessage({
6191
- ready,
6192
- authenticated,
6193
- embeddedWalletCount: wallets.filter((wallet) => wallet.walletClientType === "privy").length,
6194
- walletCount: wallets.length,
6195
- hostedSignerAvailable: canUseHostedSigner
6196
- }));
6197
- debugWarn("[fluent zerodev] initialize blocked", {
6198
- message: nextError.message,
6199
- ready,
6200
- authenticated,
6201
- embeddedWalletCount: wallets.filter((wallet) => wallet.walletClientType === "privy").length,
6202
- walletCount: wallets.length
6203
- });
6204
- setError(nextError);
6205
- if (options.throwOnError) throw nextError;
6206
- return null;
6212
+ }
6213
+ );
6214
+ var Button = forwardRef(function Button2({ className, variant = "default", size = "default", href, target, rel, render, ...props }, ref) {
6215
+ const isLink = href !== void 0;
6216
+ return /* @__PURE__ */ jsx(
6217
+ Button$1,
6218
+ {
6219
+ ref,
6220
+ "data-slot": "button",
6221
+ nativeButton: isLink ? false : void 0,
6222
+ className: cn(buttonVariants({ variant, size, className })),
6223
+ render: isLink ? /* @__PURE__ */ jsx("a", { href, target, rel }) : render,
6224
+ ...props
6207
6225
  }
6208
- if (initPromise.current[signerMode]) {
6209
- debugLog("[fluent zerodev] joining in-flight initialization");
6210
- return initPromise.current[signerMode];
6226
+ );
6227
+ });
6228
+ var toast = Toast$1.createToastManager();
6229
+ function ToastProvider({ ...props }) {
6230
+ return /* @__PURE__ */ jsx(Toast$1.Provider, { ...props });
6231
+ }
6232
+ function ToastPortal({ container, ...props }) {
6233
+ return /* @__PURE__ */ jsx(
6234
+ Toast$1.Portal,
6235
+ {
6236
+ "data-slot": "toast-portal",
6237
+ container: useFluentPortalContainer(container),
6238
+ ...props
6211
6239
  }
6212
- setSmartAccountReady(Boolean(activeKernel));
6213
- setError(null);
6214
- initPromise.current[signerMode] = (async () => {
6215
- debugLog("[fluent zerodev] initializing", {
6216
- signerMode,
6217
- embeddedWallet: embeddedWallet?.address,
6218
- walletClientType: embeddedWallet?.walletClientType,
6219
- hostedSigner: hostedSigner?.address
6220
- });
6221
- const nextKernel = canUseAuthorizationSession ? await createFluentZeroDevAuthorizedSessionKernel(
6222
- hookOptions.authorizationSession,
6223
- chain
6224
- ) : await createFluentZeroDevKernel({
6225
- wallet: canUseLocalSigner ? embeddedWallet : void 0,
6226
- hostedSigner: canUseLocalSigner ? void 0 : hostedSigner ?? void 0,
6227
- signerMode,
6228
- promptedSigners: {
6229
- signMessage: promptSignMessage,
6230
- signTypedData: promptSignTypedData
6231
- },
6232
- chain
6233
- });
6234
- if (hookOptions.sessionSmartAccountAddress && nextKernel.smartAccountAddress.toLowerCase() !== hookOptions.sessionSmartAccountAddress.toLowerCase()) {
6235
- throw new Error("Fluent Connect signer does not control the connected smart account");
6236
- }
6237
- debugLog("[fluent zerodev] ready", {
6238
- signerMode,
6239
- signerAddress: embeddedWallet?.address ?? hostedSigner?.address,
6240
- smartAccountAddress: nextKernel.smartAccountAddress
6241
- });
6242
- setKernels((current) => ({ ...current, [signerMode]: nextKernel }));
6243
- setSmartAccountReady(true);
6244
- return nextKernel;
6245
- })();
6246
- try {
6247
- return await initPromise.current[signerMode];
6248
- } catch (err) {
6249
- const nextError = err instanceof Error ? err : new Error("Failed to create ZeroDev account");
6250
- debugError("[fluent zerodev] initialization failed", nextError);
6251
- setKernels((current) => {
6252
- const { [signerMode]: _failed, ...rest } = current;
6253
- setSmartAccountReady(Object.keys(rest).length > 0);
6254
- return rest;
6255
- });
6256
- setError(nextError);
6257
- if (options.throwOnError) throw nextError;
6258
- return null;
6259
- } finally {
6260
- delete initPromise.current[signerMode];
6240
+ );
6241
+ }
6242
+ function ToastViewport({ className, ...props }) {
6243
+ return /* @__PURE__ */ jsx(
6244
+ Toast$1.Viewport,
6245
+ {
6246
+ "data-slot": "toast-viewport",
6247
+ className: cn(
6248
+ "dark pointer-events-none fixed inset-x-4 bottom-4 z-[100] mx-auto w-[min(100%,368px)] max-w-[368px] text-foreground outline-none sm:right-4 sm:left-auto sm:mx-0",
6249
+ className
6250
+ ),
6251
+ ...props
6261
6252
  }
6262
- }, [
6263
- activeKernel,
6264
- authenticated,
6265
- embeddedWallet,
6266
- hostedSigner,
6267
- kernels,
6268
- hookOptions.sessionSmartAccountAddress,
6269
- hookOptions.authorizationSession,
6270
- promptSignMessage,
6271
- promptSignTypedData,
6272
- ready
6273
- ]);
6274
- useEffect(() => {
6275
- if (!ready) return;
6276
- if (!authenticated) {
6277
- setKernels({});
6278
- setSmartAccountReady(false);
6279
- setError(null);
6280
- initPromise.current = {};
6281
- }
6282
- }, [authenticated, ready]);
6283
- const sendTransaction = useCallback(
6284
- async (request) => {
6285
- const cachedKernel = kernels.prompt;
6286
- if (cachedKernel?.signerSource === "hosted" || !cachedKernel && hostedSigner && !(ready && authenticated && embeddedWallet)) {
6287
- hostedSigner?.prepare("always");
6288
- }
6289
- const executionKernel = cachedKernel ?? await initialize2({ signerMode: "prompt" });
6290
- if (!executionKernel) throw new Error(error?.message ?? "ZeroDev smart account is not ready");
6291
- debugLog("[fluent zerodev] sendTransaction", {
6292
- signerMode: executionKernel.signerMode,
6293
- smartAccountAddress: executionKernel.smartAccountAddress,
6294
- to: request.to,
6295
- hasData: Boolean(request.data && request.data !== "0x"),
6296
- value: (request.value ?? 0n).toString()
6297
- });
6298
- try {
6299
- const hash = await executionKernel.client.sendTransaction({
6300
- account: executionKernel.account,
6301
- chain: executionKernel.chain,
6302
- to: request.to,
6303
- data: request.data ?? "0x",
6304
- value: request.value ?? 0n
6305
- });
6306
- debugLog("[fluent zerodev] sendTransaction submitted", { hash });
6307
- return hash;
6308
- } catch (err) {
6309
- debugError("[fluent zerodev] sendTransaction failed", err);
6310
- throw err;
6311
- }
6312
- },
6313
- [authenticated, embeddedWallet, error, hostedSigner, initialize2, kernels.prompt, ready]
6314
6253
  );
6315
- const createSponsoredClient = useCallback(async (kernel) => {
6316
- if (!hookOptions.sponsorshipUrl || !hookOptions.partnerId) return null;
6317
- if (sponsorshipUnavailable.current) return null;
6318
- const accessToken = await getAccessToken();
6319
- if (!accessToken) return null;
6320
- return createKernelAccountClient({
6321
- account: kernel.account,
6322
- chain: kernel.chain,
6323
- bundlerTransport: createFluentBundlerTransport(kernel.zeroDevRpcUrl),
6324
- client: kernel.publicClient,
6325
- paymaster: createFluentZeroDevSponsoredPaymaster({
6326
- chain: kernel.chain,
6327
- accessToken,
6328
- rpcUrl: createFluentSponsorshipRpcUrl({
6329
- sponsorshipUrl: hookOptions.sponsorshipUrl,
6330
- partnerId: hookOptions.partnerId
6331
- })
6332
- })
6333
- });
6334
- }, [getAccessToken, hookOptions.partnerId, hookOptions.sponsorshipUrl]);
6335
- const sendCalls = useCallback(
6336
- async (calls, options) => {
6337
- const signerMode = confirmationToSignerMode(options?.confirmation ?? "always");
6338
- const cachedKernel = kernels[signerMode];
6339
- const hasAuthorizationSession = signerMode === "silent" && Boolean(hookOptions.authorizationSession?.serializedPermissionAccount) && (hookOptions.authorizationSession?.expiresAt ?? 0) > Math.floor(Date.now() / 1e3);
6340
- if (cachedKernel?.signerSource === "hosted" || !cachedKernel && !hasAuthorizationSession && hostedSigner && !(ready && authenticated && embeddedWallet)) {
6341
- hostedSigner?.prepare(options?.confirmation ?? "always");
6342
- }
6343
- const executionKernel = cachedKernel ?? await initialize2({ signerMode, throwOnError: true });
6344
- if (!executionKernel) throw new Error(error?.message ?? "ZeroDev smart account is not ready");
6345
- const gasToken = options?.gasPayment?.symbol ? getFluentGasTokenAddress(options.gasPayment.symbol, network) : void 0;
6346
- const preparedCalls = [...calls];
6347
- if (gasToken && options?.gasPayment?.includeApproval) {
6348
- preparedCalls.unshift(await createFluentZeroDevErc20PaymasterApprovalCall({
6349
- chain: executionKernel.chain,
6350
- gasToken,
6351
- approveAmount: options.gasPayment.approveAmount
6352
- }));
6353
- }
6354
- debugLog("[fluent zerodev] sendCalls", {
6355
- signerMode,
6356
- smartAccountAddress: executionKernel.smartAccountAddress,
6357
- gasToken,
6358
- gasTokenSymbol: options?.gasPayment?.symbol,
6359
- sponsorship: options?.gasPayment?.sponsorship ?? "auto",
6360
- approvalIncluded: Boolean(gasToken && options?.gasPayment?.includeApproval),
6361
- calls: preparedCalls.map((call) => ({
6362
- to: call.to,
6363
- hasData: Boolean(call.data && call.data !== "0x"),
6364
- value: (call.value ?? 0n).toString()
6365
- }))
6366
- });
6367
- setPromptSigningContext({
6368
- gasTokenSymbol: options?.gasPayment?.symbol
6369
- });
6370
- try {
6371
- const callArgs = {
6372
- account: executionKernel.account,
6373
- calls: preparedCalls.map((call) => ({
6374
- to: call.to,
6375
- data: call.data ?? "0x",
6376
- value: call.value ?? 0n
6377
- }))
6378
- };
6379
- const sponsorshipRefused = !gasToken && options?.gasPayment?.sponsorship === "never";
6380
- const sponsoredClient = gasToken || sponsorshipRefused ? null : await createSponsoredClient(executionKernel);
6381
- const executionClient = gasToken ? createFluentZeroDevErc20ExecutionClient(executionKernel, gasToken) : sponsoredClient ?? executionKernel.client;
6382
- let sponsorshipReason;
6383
- if (sponsorshipRefused) {
6384
- sponsorshipReason = "not_requested";
6385
- } else if (!gasToken && !sponsoredClient && hookOptions.sponsorshipUrl && hookOptions.partnerId) {
6386
- sponsorshipReason = sponsorshipUnavailable.current ? "unauthorized" : "no_token";
6387
- }
6388
- let settlementClient = executionClient;
6389
- let userOpHash;
6390
- try {
6391
- userOpHash = await executionClient.sendUserOperation(callArgs);
6392
- } catch (err) {
6393
- if (!sponsoredClient) throw err;
6394
- const failure = getSponsorshipFailure(err);
6395
- sponsorshipReason = failure.reason;
6396
- if (failure.disableSponsorship) sponsorshipUnavailable.current = true;
6397
- debugWarn("[fluent zerodev] sponsorship unavailable, paying own gas", {
6398
- reason: sponsorshipReason
6399
- });
6400
- settlementClient = executionKernel.client;
6401
- userOpHash = await executionKernel.client.sendUserOperation(callArgs);
6402
- }
6403
- debugLog("[fluent zerodev] sendCalls userOp submitted", { userOpHash });
6404
- const receipt = await settlementClient.waitForUserOperationReceipt({
6405
- hash: userOpHash
6406
- });
6407
- const paymaster = readUserOperationPaymaster(receipt);
6408
- const sponsored = gasToken ? false : paymaster ? paymaster !== zeroAddress : Boolean(sponsoredClient);
6409
- if (!gasToken && sponsoredClient && !sponsored) sponsorshipReason ??= "denied";
6410
- debugLog("[fluent zerodev] sendCalls receipt", {
6411
- userOpHash,
6412
- success: receipt.success,
6413
- reason: receipt.reason,
6414
- transactionHash: receipt.receipt.transactionHash,
6415
- sponsored,
6416
- paymaster,
6417
- sponsorshipReason
6418
- });
6419
- if (!receipt.success) {
6420
- throw new Error(receipt.reason ?? `UserOperation ${userOpHash} execution failed`);
6421
- }
6422
- return {
6423
- hash: receipt.receipt.transactionHash,
6424
- sponsored,
6425
- sponsorshipReason,
6426
- paymaster
6427
- };
6428
- } catch (err) {
6429
- debugError("[fluent zerodev] sendCalls failed", err);
6430
- throw err;
6431
- } finally {
6432
- clearPromptSigningContext();
6433
- }
6434
- },
6435
- [
6436
- authenticated,
6437
- createSponsoredClient,
6438
- embeddedWallet,
6439
- error,
6440
- hostedSigner,
6441
- hookOptions.authorizationSession,
6442
- hookOptions.partnerId,
6443
- hookOptions.sponsorshipUrl,
6444
- initialize2,
6445
- kernels,
6446
- network,
6447
- ready
6448
- ]
6254
+ }
6255
+ function Toast({ className, style, ...props }) {
6256
+ return /* @__PURE__ */ jsx(
6257
+ Toast$1.Root,
6258
+ {
6259
+ "data-slot": "toast",
6260
+ style: { maxWidth: 368, ...style },
6261
+ className: cn(
6262
+ "group/toast pointer-events-auto absolute right-0 bottom-0 z-[calc(1000-var(--toast-index))] w-full max-w-[368px] origin-bottom rounded-2xl border border-white/20 bg-popover text-popover-foreground shadow-lg will-change-transform outline-none select-none focus-visible:border-border focus-visible:ring-[3px] focus-visible:ring-ring/50",
6263
+ "[--gap:0.75rem] [--height:var(--toast-frontmost-height,var(--toast-height))] [--offset-y:calc(var(--toast-offset-y)*-1+calc(var(--toast-index)*var(--gap)*-1)+var(--toast-swipe-movement-y))] [--peek:0.75rem] [--scale:calc(max(0,1-(var(--toast-index)*0.1)))] [--shrink:calc(1-var(--scale))]",
6264
+ "h-(--height) [transform:translateX(var(--toast-swipe-movement-x))_translateY(calc(var(--toast-swipe-movement-y)-(var(--toast-index)*var(--peek))-(var(--shrink)*var(--height))))_scale(var(--scale))] [transition:transform_500ms_cubic-bezier(0.22,1,0.36,1),opacity_500ms,height_150ms]",
6265
+ "after:absolute after:top-full after:left-0 after:h-[calc(var(--gap)+1px)] after:w-full after:content-['']",
6266
+ "data-expanded:h-(--toast-height) data-expanded:[transform:translateX(var(--toast-swipe-movement-x))_translateY(var(--offset-y))]",
6267
+ "data-limited:opacity-0 data-starting-style:[transform:translateY(150%)]",
6268
+ "[&[data-ending-style]:not([data-limited]):not([data-swipe-direction])]:[transform:translateY(150%)]",
6269
+ "data-ending-style:data-[swipe-direction=down]:[transform:translateY(calc(var(--toast-swipe-movement-y)+150%))]",
6270
+ "data-ending-style:data-[swipe-direction=left]:[transform:translateX(calc(var(--toast-swipe-movement-x)-150%))_translateY(var(--offset-y))]",
6271
+ "data-ending-style:data-[swipe-direction=right]:[transform:translateX(calc(var(--toast-swipe-movement-x)+150%))_translateY(var(--offset-y))]",
6272
+ "data-ending-style:data-[swipe-direction=up]:[transform:translateY(calc(var(--toast-swipe-movement-y)-150%))]",
6273
+ "data-expanded:data-ending-style:data-[swipe-direction=down]:[transform:translateY(calc(var(--toast-swipe-movement-y)+150%))]",
6274
+ "data-expanded:data-ending-style:data-[swipe-direction=left]:[transform:translateX(calc(var(--toast-swipe-movement-x)-150%))_translateY(var(--offset-y))]",
6275
+ "data-expanded:data-ending-style:data-[swipe-direction=right]:[transform:translateX(calc(var(--toast-swipe-movement-x)+150%))_translateY(var(--offset-y))]",
6276
+ "data-expanded:data-ending-style:data-[swipe-direction=up]:[transform:translateY(calc(var(--toast-swipe-movement-y)-150%))]",
6277
+ className
6278
+ ),
6279
+ ...props
6280
+ }
6449
6281
  );
6450
- const ensureExecutionReady = useCallback(async (options = {}) => {
6451
- const signerMode = confirmationToSignerMode(options.confirmation ?? "always");
6452
- if (kernels[signerMode]) return kernels[signerMode];
6453
- if (!ready) throw new Error("Privy wallet context is still loading");
6454
- if (!authenticated && !hostedSigner) {
6455
- login();
6456
- throw new Error("Complete wallet login, then submit the transaction again");
6282
+ }
6283
+ function ToastContent({ className, ...props }) {
6284
+ return /* @__PURE__ */ jsx(
6285
+ Toast$1.Content,
6286
+ {
6287
+ "data-slot": "toast-content",
6288
+ className: cn(
6289
+ "flex h-full items-start gap-3 overflow-hidden p-4 transition-opacity duration-250 ease-[cubic-bezier(0.22,1,0.36,1)] data-behind:opacity-0 data-expanded:opacity-100",
6290
+ className
6291
+ ),
6292
+ ...props
6457
6293
  }
6458
- const executionKernel = await initialize2({ signerMode, throwOnError: true });
6459
- if (!executionKernel) throw new Error(error?.message ?? "ZeroDev smart account is not ready");
6460
- return executionKernel;
6461
- }, [authenticated, error, hostedSigner, initialize2, kernels, login, ready]);
6462
- return {
6463
- smartAccountEnabled: Boolean(FLUENT_CONNECT_ZERODEV_PROJECT_ID),
6464
- smartAccountReady,
6465
- smartAccountAddress: activeKernel?.smartAccountAddress,
6466
- signerAddress: embeddedWallet?.address ?? hookOptions.sessionSignerAddress,
6467
- privyReady: ready,
6468
- privyAuthenticated: authenticated,
6469
- embeddedWalletCount: wallets.filter((wallet) => wallet.walletClientType === "privy").length,
6470
- authenticate: login,
6471
- kernel: activeKernel,
6472
- signerModesReady: Object.keys(kernels),
6473
- error,
6474
- ensureExecutionReady,
6475
- sendTransaction,
6476
- sendCalls,
6477
- refresh: () => initialize2({ throwOnError: true, signerMode: "prompt" })
6478
- };
6294
+ );
6479
6295
  }
6480
- var USER_OPERATION_EVENT_TOPIC = toEventSelector(
6481
- parseAbiItem(
6482
- "event UserOperationEvent(bytes32 indexed userOpHash, address indexed sender, address indexed paymaster, uint256 nonce, bool success, uint256 actualGasCost, uint256 actualGasUsed)"
6483
- )
6484
- ).toLowerCase();
6485
- function readUserOperationPaymaster(receipt) {
6486
- if (receipt.paymaster) return getAddress(receipt.paymaster);
6487
- const event = receipt.logs.find(
6488
- (log) => log.topics[0]?.toLowerCase() === USER_OPERATION_EVENT_TOPIC && log.topics[1]?.toLowerCase() === receipt.userOpHash.toLowerCase()
6296
+ function ToastTitle({ className, ...props }) {
6297
+ return /* @__PURE__ */ jsx(
6298
+ Toast$1.Title,
6299
+ {
6300
+ "data-slot": "toast-title",
6301
+ className: cn("text-sm font-medium", className),
6302
+ ...props
6303
+ }
6489
6304
  );
6490
- const topic = event?.topics[3];
6491
- if (!topic || topic.length !== 66) return void 0;
6492
- return getAddress(`0x${topic.slice(26)}`);
6493
6305
  }
6494
- function getZeroDevReadinessMessage(params) {
6495
- if (!params.ready) return "Privy wallet context is still loading";
6496
- if (params.hostedSignerAvailable) return "Fluent hosted signer is preparing";
6497
- if (!params.authenticated) return "Fluent session is connected, but Privy embedded wallet is not authenticated on this page";
6498
- if (params.embeddedWalletCount === 0) {
6499
- return `Privy is authenticated, but no embedded wallet is available (${params.walletCount} linked wallets found)`;
6500
- }
6501
- return "Fluent ZeroDev account is still preparing. Try again in a moment.";
6502
- }
6503
- async function createFluentZeroDevPermissionSession(params) {
6504
- const sessionAccount = privateKeyToAccount(params.sessionPrivateKey);
6505
- const signer = await toECDSASigner({ signer: sessionAccount });
6506
- const policies = [
6507
- toCallPolicy({
6508
- policyVersion: CallPolicyVersion.V0_0_5,
6509
- permissions: params.calls.map(
6510
- (call) => call.abi && call.functionName ? {
6511
- target: call.target,
6512
- abi: call.abi,
6513
- functionName: call.functionName,
6514
- args: call.args,
6515
- callType: call.callType,
6516
- valueLimit: call.valueLimit ?? 0n
6517
- } : {
6518
- target: call.target,
6519
- selector: call.selector,
6520
- callType: call.callType,
6521
- valueLimit: call.valueLimit ?? 0n
6522
- }
6523
- )
6524
- })
6525
- ];
6526
- if (params.expiresAt) {
6527
- policies.push(toTimestampPolicy({ validUntil: params.expiresAt }));
6528
- }
6529
- const permissionPlugin = await toPermissionValidator(params.kernel.publicClient, {
6530
- signer,
6531
- policies,
6532
- entryPoint: getEntryPoint("0.7"),
6533
- kernelVersion: KERNEL_V3_3
6534
- });
6535
- const serializedPermissionAccount = await serializePermissionAccount(
6536
- params.kernel.account,
6537
- params.sessionPrivateKey,
6538
- void 0,
6539
- void 0,
6540
- permissionPlugin,
6541
- true
6306
+ function ToastDescription({
6307
+ className,
6308
+ ...props
6309
+ }) {
6310
+ return /* @__PURE__ */ jsx(
6311
+ Toast$1.Description,
6312
+ {
6313
+ "data-slot": "toast-description",
6314
+ className: cn("text-sm text-muted-foreground", className),
6315
+ ...props
6316
+ }
6542
6317
  );
6543
- return {
6544
- serializedPermissionAccount,
6545
- sessionSignerAddress: sessionAccount.address,
6546
- smartAccountAddress: params.kernel.smartAccountAddress
6547
- };
6548
6318
  }
6549
- function confirmationToSignerMode(confirmation) {
6550
- return confirmation === "session" ? "silent" : "prompt";
6319
+ function ToastAction({
6320
+ className,
6321
+ render = /* @__PURE__ */ jsx(Button, { variant: "outline", size: "sm" }),
6322
+ ...props
6323
+ }) {
6324
+ return /* @__PURE__ */ jsx(
6325
+ Toast$1.Action,
6326
+ {
6327
+ "data-slot": "toast-action",
6328
+ render,
6329
+ className: cn("shrink-0", className),
6330
+ ...props
6331
+ }
6332
+ );
6551
6333
  }
6552
- async function createFluentZeroDevAuthorizedSessionKernel(authorizationSession, chain) {
6553
- const zeroDevRpcUrl = `https://rpc.zerodev.app/api/v3/${FLUENT_CONNECT_ZERODEV_PROJECT_ID}/chain/${chain.id}`;
6554
- const publicClient = createPublicClient({
6555
- chain,
6556
- transport: createFluentRpcTransport(chain)
6557
- });
6558
- const entryPoint = getEntryPoint("0.7");
6559
- const sessionSigner = await toECDSASigner({
6560
- signer: privateKeyToAccount(authorizationSession.sessionPrivateKey)
6561
- });
6562
- const account = await deserializePermissionAccount(
6563
- publicClient,
6564
- entryPoint,
6565
- KERNEL_V3_3,
6566
- authorizationSession.serializedPermissionAccount,
6567
- sessionSigner
6334
+ function ToastClose({
6335
+ className,
6336
+ children,
6337
+ render = /* @__PURE__ */ jsx(Button, { variant: "ghost", size: "icon-sm" }),
6338
+ ...props
6339
+ }) {
6340
+ return /* @__PURE__ */ jsx(
6341
+ Toast$1.Close,
6342
+ {
6343
+ "data-slot": "toast-close",
6344
+ "aria-label": "Close toast",
6345
+ render,
6346
+ className: cn(
6347
+ "relative shrink-0 text-muted-foreground after:absolute after:-inset-2 after:content-[''] hover:text-foreground",
6348
+ className
6349
+ ),
6350
+ ...props,
6351
+ children: children ?? /* @__PURE__ */ jsx(XIcon, { "aria-hidden": "true" })
6352
+ }
6568
6353
  );
6569
- const client2 = createKernelAccountClient({
6570
- account,
6571
- chain,
6572
- bundlerTransport: createFluentBundlerTransport(zeroDevRpcUrl),
6573
- client: publicClient
6574
- });
6575
- return {
6576
- account,
6577
- client: client2,
6578
- publicClient,
6579
- smartAccountAddress: account.address,
6580
- zeroDevRpcUrl,
6581
- chain,
6582
- signerMode: "silent",
6583
- signerSource: "session"
6584
- };
6585
6354
  }
6586
- async function createFluentZeroDevKernel(params) {
6587
- if (!params.wallet && !params.hostedSigner) throw new Error("Fluent signer is unavailable");
6588
- if (params.wallet) {
6589
- debugLog("[fluent zerodev] ensuring Fluent chain", params.chain.id);
6590
- await ensureWalletOnFluentChain(params.wallet, params.chain);
6591
- debugLog("[fluent zerodev] Fluent chain ready", params.chain.id);
6355
+ function ToastIcon({ type }) {
6356
+ let icon = null;
6357
+ if (type === "success") {
6358
+ icon = /* @__PURE__ */ jsx(CircleCheckIcon, { "aria-hidden": "true" });
6592
6359
  }
6593
- const zeroDevRpcUrl = `https://rpc.zerodev.app/api/v3/${FLUENT_CONNECT_ZERODEV_PROJECT_ID}/chain/${params.chain.id}`;
6594
- const publicClient = createPublicClient({
6595
- chain: params.chain,
6596
- transport: createFluentRpcTransport(params.chain)
6597
- });
6598
- const entryPoint = getEntryPoint("0.7");
6599
- let signer;
6600
- if (params.hostedSigner) {
6601
- signer = toHostedSignerLocalAccount(params.hostedSigner, params.signerMode);
6602
- } else if (params.wallet && params.signerMode === "prompt") {
6603
- signer = toPromptedPrivyLocalAccount(params.wallet, params.promptedSigners, params.chain);
6604
- } else if (params.wallet) {
6605
- signer = toSilentPrivyLocalAccount(params.wallet, params.chain);
6606
- } else {
6607
- throw new Error("Fluent signer is unavailable");
6360
+ if (type === "info") {
6361
+ icon = /* @__PURE__ */ jsx(InfoIcon, { "aria-hidden": "true" });
6608
6362
  }
6609
- const ecdsaValidator = await signerToEcdsaValidator(publicClient, {
6610
- signer,
6611
- entryPoint,
6612
- kernelVersion: KERNEL_V3_3
6613
- });
6614
- const account = await createKernelAccount(publicClient, {
6615
- entryPoint,
6616
- plugins: { sudo: ecdsaValidator },
6617
- kernelVersion: KERNEL_V3_3
6618
- });
6619
- const client2 = createKernelAccountClient({
6620
- account,
6621
- chain: params.chain,
6622
- bundlerTransport: createFluentBundlerTransport(zeroDevRpcUrl),
6623
- client: publicClient
6624
- });
6625
- return {
6626
- account,
6627
- client: client2,
6628
- publicClient,
6629
- smartAccountAddress: account.address,
6630
- zeroDevRpcUrl,
6631
- chain: params.chain,
6632
- signerMode: params.signerMode,
6633
- signerSource: params.hostedSigner ? "hosted" : "privy"
6634
- };
6635
- }
6636
- function toHostedSignerLocalAccount(signer, signerMode) {
6637
- const confirmation = signerMode === "silent" ? "session" : "always";
6638
- const source = {
6639
- address: signer.address,
6640
- async signMessage({ message }) {
6641
- return signer.signMessage(formatSignableMessageForPrivy(message), confirmation);
6642
- },
6643
- async signTransaction() {
6644
- throw new Error("Fluent ZeroDev signer does not sign raw transactions");
6645
- },
6646
- async signTypedData(typedData) {
6647
- return signer.signTypedData(
6648
- {
6649
- domain: typedData.domain,
6650
- types: typedData.types,
6651
- primaryType: typedData.primaryType,
6652
- message: typedData.message
6653
- },
6654
- confirmation
6655
- );
6363
+ if (type === "warning") {
6364
+ icon = /* @__PURE__ */ jsx(TriangleAlertIcon, { "aria-hidden": "true" });
6365
+ }
6366
+ if (type === "error") {
6367
+ icon = /* @__PURE__ */ jsx(OctagonXIcon, { className: "text-destructive", "aria-hidden": "true" });
6368
+ }
6369
+ if (type === "loading") {
6370
+ icon = /* @__PURE__ */ jsx(Loader2Icon, { className: "animate-spin", "aria-hidden": "true" });
6371
+ }
6372
+ if (!icon) {
6373
+ return null;
6374
+ }
6375
+ return /* @__PURE__ */ jsx(
6376
+ "span",
6377
+ {
6378
+ "data-slot": "toast-icon",
6379
+ className: "shrink-0 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4",
6380
+ children: icon
6656
6381
  }
6657
- };
6658
- return toAccount(source);
6659
- }
6660
- function createFluentZeroDevErc20ExecutionClient(kernel, gasToken) {
6661
- return createKernelAccountClient({
6662
- account: kernel.account,
6663
- chain: kernel.chain,
6664
- bundlerTransport: createFluentBundlerTransport(kernel.zeroDevRpcUrl),
6665
- client: kernel.publicClient,
6666
- paymaster: createFluentZeroDevErc20Paymaster({
6667
- chain: kernel.chain,
6668
- gasToken
6669
- })
6670
- });
6671
- }
6672
- var promptSigningContext = {};
6673
- function setPromptSigningContext(context) {
6674
- promptSigningContext = context;
6382
+ );
6675
6383
  }
6676
- function clearPromptSigningContext() {
6677
- promptSigningContext = {};
6384
+ function ToastList() {
6385
+ const { toasts } = Toast$1.useToastManager();
6386
+ return toasts.map((toastItem) => /* @__PURE__ */ jsx(Toast, { toast: toastItem, children: /* @__PURE__ */ jsxs(ToastContent, { children: [
6387
+ /* @__PURE__ */ jsxs("div", { className: "flex min-w-0 flex-1 flex-col gap-1", children: [
6388
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1.5", children: [
6389
+ /* @__PURE__ */ jsx(ToastIcon, { type: toastItem.type }),
6390
+ /* @__PURE__ */ jsx(ToastTitle, {})
6391
+ ] }),
6392
+ /* @__PURE__ */ jsx(ToastDescription, {})
6393
+ ] }),
6394
+ /* @__PURE__ */ jsx(ToastAction, {}),
6395
+ /* @__PURE__ */ jsx(ToastClose, {})
6396
+ ] }) }, toastItem.id));
6678
6397
  }
6679
- function buildPromptSigningUiOptions() {
6680
- const gasTokenSymbol = promptSigningContext.gasTokenSymbol;
6681
- return {
6682
- title: "Confirm Fluent transaction",
6683
- description: gasTokenSymbol ? `Gas will be paid in ${gasTokenSymbol}. Confirm this Fluent transaction.` : "Confirm this Fluent transaction.",
6684
- buttonText: "Sign"
6685
- };
6398
+ function Toaster({
6399
+ children,
6400
+ toastManager = toast,
6401
+ ...props
6402
+ }) {
6403
+ return /* @__PURE__ */ jsxs(ToastProvider, { toastManager, ...props, children: [
6404
+ children,
6405
+ /* @__PURE__ */ jsx(ToastPortal, { children: /* @__PURE__ */ jsx(ToastViewport, { children: /* @__PURE__ */ jsx(ToastList, {}) }) })
6406
+ ] });
6686
6407
  }
6687
- function toPromptedPrivyLocalAccount(wallet, promptedSigners, chain) {
6688
- const source = {
6689
- address: wallet.address,
6690
- async signMessage({ message }) {
6691
- await ensureWalletOnFluentChain(wallet, chain);
6692
- const { signature } = await promptedSigners.signMessage(
6693
- { message: formatSignableMessageForPrivy(message) },
6694
- {
6695
- address: wallet.address,
6696
- uiOptions: buildPromptSigningUiOptions()
6697
- }
6698
- );
6699
- return signature;
6700
- },
6701
- async signTransaction() {
6702
- throw new Error("Fluent ZeroDev signer does not sign raw transactions");
6703
- },
6704
- async signTypedData(typedData) {
6705
- await ensureWalletOnFluentChain(wallet, chain);
6706
- const { signature } = await promptedSigners.signTypedData(
6707
- {
6708
- domain: typedData.domain,
6709
- types: typedData.types,
6710
- primaryType: typedData.primaryType,
6711
- message: typedData.message
6712
- },
6713
- {
6714
- address: wallet.address,
6715
- uiOptions: buildPromptSigningUiOptions()
6716
- }
6717
- );
6718
- return signature;
6719
- }
6720
- };
6721
- return toAccount(source);
6408
+ Toast$1.createToastManager;
6409
+ Toast$1.useToastManager;
6410
+
6411
+ // src/utils/formatAddress.ts
6412
+ function formatAddress(address) {
6413
+ return `${address.slice(0, 6)}...${address.slice(-4)}`;
6722
6414
  }
6723
- function toSilentPrivyLocalAccount(wallet, chain) {
6724
- const source = {
6725
- address: wallet.address,
6726
- async signMessage({ message }) {
6727
- debugLog("[fluent zerodev] requesting embedded provider signature", {
6728
- signerAddress: wallet.address,
6729
- messageKind: typeof message === "string" ? "string" : "raw" in message ? "raw" : typeof message
6730
- });
6731
- await ensureWalletOnFluentChain(wallet, chain);
6732
- const provider = await wallet.getEthereumProvider();
6733
- if (!provider?.request) throw new Error("Fluent embedded wallet provider is unavailable");
6734
- const formattedMessage = formatSignableMessageForPrivy(message);
6735
- try {
6736
- const signature = await provider.request({
6737
- method: "personal_sign",
6738
- params: [isHex(formattedMessage) ? formattedMessage : stringToHex(formattedMessage), wallet.address]
6739
- });
6740
- if (typeof signature !== "string") throw new Error("Privy embedded wallet returned an invalid signature");
6741
- debugLog("[fluent zerodev] embedded provider signature ready", {
6742
- signerAddress: wallet.address,
6743
- signatureLength: signature.length
6744
- });
6745
- return signature;
6746
- } catch (err) {
6747
- debugError("[fluent zerodev] embedded provider signature failed", err);
6748
- throw err;
6749
- }
6415
+
6416
+ // src/utils/copyAddress.ts
6417
+ async function copyAddressToClipboard(address) {
6418
+ try {
6419
+ await navigator.clipboard.writeText(address);
6420
+ toast.add({
6421
+ type: "success",
6422
+ title: "Address copied",
6423
+ description: formatAddress(address)
6424
+ });
6425
+ } catch (error) {
6426
+ debugWarn("[fluent connect] Failed to copy address", error);
6427
+ toast.add({
6428
+ type: "error",
6429
+ title: "Copy failed",
6430
+ description: "Could not copy address to clipboard."
6431
+ });
6432
+ }
6433
+ }
6434
+
6435
+ // src/utils/createLocalFluentSession.ts
6436
+ function createLocalFluentSession(params) {
6437
+ const issuedAt = Math.floor(Date.now() / 1e3);
6438
+ const payload = {
6439
+ iss: typeof location !== "undefined" ? location.origin : "fluent-local",
6440
+ aud: params.appId,
6441
+ sub: params.userId,
6442
+ app: params.app,
6443
+ scopes: params.scopes,
6444
+ iat: issuedAt
6445
+ };
6446
+ return {
6447
+ app: params.app,
6448
+ appId: params.appId,
6449
+ idToken: `mock.${btoa(JSON.stringify(payload))}.signature`,
6450
+ user: {
6451
+ id: params.userId,
6452
+ email: params.email
6750
6453
  },
6751
- async signTransaction() {
6752
- throw new Error("Fluent ZeroDev signer does not sign raw transactions");
6454
+ wallet: {
6455
+ signerAddress: params.signerAddress,
6456
+ smartAccountAddress: params.smartAccountAddress
6753
6457
  },
6754
- async signTypedData(typedData) {
6755
- debugLog("[fluent zerodev] requesting embedded provider typed-data signature", {
6756
- signerAddress: wallet.address,
6757
- primaryType: typedData.primaryType
6758
- });
6759
- await ensureWalletOnFluentChain(wallet, chain);
6760
- const provider = await wallet.getEthereumProvider();
6761
- if (!provider?.request) throw new Error("Fluent embedded wallet provider is unavailable");
6762
- try {
6763
- const signature = await provider.request({
6764
- method: "eth_signTypedData_v4",
6765
- params: [
6766
- wallet.address,
6767
- stringifyTypedDataForProvider({
6768
- domain: typedData.domain,
6769
- types: typedData.types,
6770
- primaryType: typedData.primaryType,
6771
- message: typedData.message
6772
- })
6773
- ]
6774
- });
6775
- if (typeof signature !== "string") {
6776
- throw new Error("Privy embedded wallet returned an invalid typed-data signature");
6777
- }
6778
- debugLog("[fluent zerodev] embedded provider typed-data signature ready", {
6779
- signerAddress: wallet.address,
6780
- signatureLength: signature.length
6781
- });
6782
- return signature;
6783
- } catch (err) {
6784
- debugError("[fluent zerodev] embedded provider typed-data signature failed", err);
6785
- throw err;
6786
- }
6458
+ scopes: params.scopes,
6459
+ issuedAt,
6460
+ metadata: {
6461
+ authMode: "direct",
6462
+ origin: params.app.origin
6787
6463
  }
6788
6464
  };
6789
- return toAccount(source);
6790
6465
  }
6791
- function stringifyTypedDataForProvider(value) {
6792
- return JSON.stringify(
6793
- value,
6794
- (_key, next) => typeof next === "bigint" ? next.toString() : next
6795
- );
6466
+
6467
+ // src/utils/explorerAddress.ts
6468
+ function explorerAddress(address, network) {
6469
+ const baseUrl = getFluentExplorerBaseUrl(network ?? "testnet");
6470
+ return `${baseUrl}/address/${address}`;
6796
6471
  }
6797
- function formatSignableMessageForPrivy(message) {
6798
- if (typeof message === "string") return message;
6799
- if ("raw" in message) return typeof message.raw === "string" ? message.raw : bytesToHex(message.raw);
6800
- return String(message);
6472
+
6473
+ // src/utils/faucetToast.ts
6474
+ function normalize(value) {
6475
+ return (value ?? "").trim().toLowerCase();
6801
6476
  }
6802
- async function ensureWalletOnFluentChain(wallet, chain) {
6803
- const targetChainId = numberToHex(chain.id);
6804
- const provider = await wallet.getEthereumProvider();
6805
- if (wallet.switchChain) {
6806
- debugLog("[fluent zerodev] wallet.switchChain", chain.id);
6807
- await wallet.switchChain(chain.id);
6477
+ function isAlreadyClaimed(status, message) {
6478
+ const statusNorm = normalize(status);
6479
+ const messageNorm = normalize(message);
6480
+ return statusNorm.includes("already") || messageNorm.includes("already");
6481
+ }
6482
+ function toastFaucetSuccess(receipt) {
6483
+ if (isAlreadyClaimed(receipt.status, receipt.message)) {
6484
+ toast.add({
6485
+ type: "info",
6486
+ title: "Already claimed",
6487
+ description: receipt.message || "BLEND faucet was already claimed for this account."
6488
+ });
6489
+ return;
6808
6490
  }
6809
- if (provider?.request) {
6810
- const currentChainId = await getProviderChainId(provider);
6811
- debugLog("[fluent zerodev] provider chain", currentChainId);
6812
- if (currentChainId === targetChainId) return;
6813
- try {
6814
- await provider.request({
6815
- method: "wallet_switchEthereumChain",
6816
- params: [{ chainId: targetChainId }]
6817
- });
6818
- } catch (err) {
6819
- if (!isUnknownChainError(err)) throw err;
6820
- await provider.request({
6821
- method: "wallet_addEthereumChain",
6822
- params: [
6823
- {
6824
- chainId: targetChainId,
6825
- chainName: chain.name,
6826
- nativeCurrency: chain.nativeCurrency,
6827
- rpcUrls: chain.rpcUrls.default.http,
6828
- blockExplorerUrls: chain.blockExplorers?.default.url ? [chain.blockExplorers.default.url] : void 0
6829
- }
6830
- ]
6831
- });
6832
- await provider.request({
6833
- method: "wallet_switchEthereumChain",
6834
- params: [{ chainId: targetChainId }]
6491
+ toast.add({
6492
+ type: "success",
6493
+ title: "Faucet claimed",
6494
+ description: receipt.message || (receipt.txHash ? `Transaction ${receipt.txHash}` : "BLEND was sent to your wallet.")
6495
+ });
6496
+ }
6497
+ function toastFaucetError(error) {
6498
+ if (error instanceof HttpError) {
6499
+ if (isAlreadyClaimed(error.body?.status, error.message) || error.status === 409) {
6500
+ toast.add({
6501
+ type: "info",
6502
+ title: "Already claimed",
6503
+ description: error.message || "BLEND faucet was already claimed for this account."
6835
6504
  });
6505
+ return;
6836
6506
  }
6837
- const nextChainId = await getProviderChainId(provider);
6838
- debugLog("[fluent zerodev] provider chain after switch", nextChainId);
6839
- if (nextChainId !== targetChainId) {
6840
- throw new Error(`Unsupported chainId ${Number(BigInt(nextChainId))}; switch to ${chain.name}`);
6507
+ if (error.status === 429) {
6508
+ toast.add({
6509
+ type: "warning",
6510
+ title: "Too many requests",
6511
+ description: error.message || "Please wait a moment and try again."
6512
+ });
6513
+ return;
6841
6514
  }
6515
+ toast.add({
6516
+ type: "error",
6517
+ title: "Faucet request failed",
6518
+ description: error.message || `Request failed with ${error.status}`
6519
+ });
6842
6520
  return;
6843
6521
  }
6844
- throw new Error("Fluent embedded wallet provider is unavailable");
6845
- }
6846
- async function getProviderChainId(provider) {
6847
- const chainId = await provider.request({ method: "eth_chainId" });
6848
- if (typeof chainId !== "string") throw new Error("Unable to read embedded wallet chainId");
6849
- return chainId.toLowerCase();
6850
- }
6851
- function isUnknownChainError(err) {
6852
- const code = err?.code;
6853
- const nestedCode = err?.data?.originalError?.code;
6854
- return code === 4902 || nestedCode === 4902;
6522
+ toast.add({
6523
+ type: "error",
6524
+ title: "Faucet request failed",
6525
+ description: error instanceof Error ? error.message : "Something went wrong."
6526
+ });
6855
6527
  }
6856
6528
 
6857
- // src/widget/permissionSession.ts
6858
- function createFluentPermissionApi(executor) {
6859
- return {
6860
- createPermissionSession: (input) => createFluentPermissionSession(input, executor),
6861
- policies: createFluentPermissionPolicyBuilders()
6862
- };
6863
- }
6864
- function createFluentPermissionPolicyBuilders() {
6865
- return {
6866
- call: (input) => ({
6867
- kind: "call",
6868
- id: input.id,
6869
- call: input
6870
- }),
6871
- batch: (input) => ({
6872
- kind: "batch",
6873
- id: input.id,
6874
- calls: input.calls
6875
- })
6876
- };
6877
- }
6878
- async function createFluentPermissionSession(input, executor) {
6879
- if (!executor?.kernel || executor.smartAccountReady === false) {
6880
- throw new Error("ZeroDev smart account is not ready");
6881
- }
6882
- if (input.policies.length === 0) {
6883
- throw new Error("A permission session requires at least one policy");
6884
- }
6885
- const calls = input.policies.flatMap(
6886
- (policy) => policy.kind === "batch" ? policy.calls.map((call) => toZeroDevPermissionCall(call, CallType.BATCH_CALL)) : [toZeroDevPermissionCall(policy.call, CallType.CALL)]
6529
+ // src/utils/formatExternalWallet.ts
6530
+ function formatExternalWallet(wallet, status) {
6531
+ return JSON.stringify(
6532
+ {
6533
+ status: status ?? "Waiting for wallet connection",
6534
+ wallet: wallet ? {
6535
+ provider: "Reown AppKit",
6536
+ configured: wallet.configured,
6537
+ connected: wallet.connected,
6538
+ address: wallet.address,
6539
+ chainId: wallet.chainId
6540
+ } : null,
6541
+ walletConnectEnabled: Boolean(wallet?.configured)
6542
+ },
6543
+ null,
6544
+ 2
6887
6545
  );
6888
- const expiresAt = toUnixSeconds(input.expiresAt);
6889
- const permission = await createFluentZeroDevPermissionSession({
6890
- kernel: executor.kernel,
6891
- sessionPrivateKey: input.sessionPrivateKey ?? generatePrivateKey(),
6892
- calls,
6893
- expiresAt
6894
- });
6895
- return {
6896
- ...permission,
6897
- label: input.label,
6898
- delegate: input.delegate,
6899
- expiresAt,
6900
- policies: input.policies
6901
- };
6902
- }
6903
- function toZeroDevPermissionCall(call, callType) {
6904
- const functionName = call.functionName ?? call.method;
6905
- if (!functionName) throw new Error("Permission policy requires method or functionName");
6906
- return {
6907
- target: call.to,
6908
- abi: call.abi,
6909
- functionName,
6910
- args: normalizePermissionArgs(call.abi, functionName, call.args),
6911
- callType,
6912
- valueLimit: call.valueLimit
6913
- };
6914
6546
  }
6915
- function normalizePermissionArgs(abi, functionName, args) {
6916
- if (!args) return void 0;
6917
- if (Array.isArray(args)) return args.map(toZeroDevCondition);
6918
- const fn = findAbiFunction(abi, functionName);
6919
- const namedArgs = args;
6920
- return fn.inputs.map((input) => {
6921
- if (!input.name) return null;
6922
- return toZeroDevCondition(namedArgs[input.name]);
6547
+
6548
+ // src/utils/formatFluentLocaleAmount.ts
6549
+ var FLUENT_AMOUNT_LOCALE = "en-US";
6550
+ var FLUENT_DECIMAL_SEPARATOR = new Intl.NumberFormat(FLUENT_AMOUNT_LOCALE).formatToParts(1.1).find((part) => part.type === "decimal")?.value ?? ".";
6551
+ function formatFluentLocaleAmount(value, maximumFractionDigits = 2) {
6552
+ const amount = typeof value === "number" ? value : Number(value);
6553
+ if (!Number.isFinite(amount)) return typeof value === "string" ? value : String(value);
6554
+ return amount.toLocaleString(FLUENT_AMOUNT_LOCALE, {
6555
+ minimumFractionDigits: 0,
6556
+ maximumFractionDigits
6923
6557
  });
6924
6558
  }
6925
- function toZeroDevCondition(rule) {
6926
- if (!rule) return null;
6927
- if ("equals" in rule) {
6928
- return { condition: ParamCondition.EQUAL, value: rule.equals };
6559
+
6560
+ // src/utils/formatFluentGasTokenBalance.ts
6561
+ var GAS_BALANCE_MAX_FRACTION_DIGITS = 6;
6562
+ function roundToFractionDigits(raw, decimals, digits) {
6563
+ const discardedScale = 10n ** BigInt(decimals - digits);
6564
+ return (raw + discardedScale / 2n) / discardedScale;
6565
+ }
6566
+ function formatFluentGasTokenBalance(balance, maximumFractionDigits = 1) {
6567
+ if (balance.raw === null || balance.formatted === null) return null;
6568
+ if (maximumFractionDigits < 0 || !Number.isInteger(maximumFractionDigits)) {
6569
+ throw new Error("maximumFractionDigits must be a non-negative integer");
6929
6570
  }
6930
- if ("max" in rule) {
6931
- return { condition: ParamCondition.LESS_THAN_OR_EQUAL, value: rule.max };
6571
+ if (balance.decimals <= maximumFractionDigits) {
6572
+ return formatFluentLocaleAmount(balance.formatted, maximumFractionDigits);
6932
6573
  }
6933
- return { condition: ParamCondition.GREATER_THAN_OR_EQUAL, value: rule.min };
6934
- }
6935
- function findAbiFunction(abi, functionName) {
6936
- const matches = abi.filter(
6937
- (item) => item.type === "function" && item.name === functionName
6574
+ const maxDigits = Math.max(
6575
+ maximumFractionDigits,
6576
+ Math.min(balance.decimals, GAS_BALANCE_MAX_FRACTION_DIGITS)
6938
6577
  );
6939
- if (matches.length !== 1) {
6940
- throw new Error(
6941
- matches.length === 0 ? `Function "${functionName}" not found in ABI` : `Function "${functionName}" is overloaded; pass positional args or a filtered ABI`
6942
- );
6578
+ for (let digits = maximumFractionDigits; digits <= maxDigits; digits += 1) {
6579
+ const rounded = roundToFractionDigits(balance.raw, balance.decimals, digits);
6580
+ if (rounded > 0n || balance.raw === 0n) {
6581
+ return formatFluentLocaleAmount(formatUnits(rounded, digits), digits);
6582
+ }
6943
6583
  }
6944
- return matches[0];
6945
- }
6946
- function toUnixSeconds(value) {
6947
- if (value === void 0) return void 0;
6948
- if (value instanceof Date) return Math.floor(value.getTime() / 1e3);
6949
- return value > 1e12 ? Math.floor(value / 1e3) : Math.floor(value);
6584
+ return formatFluentLocaleAmount(0, maximumFractionDigits);
6950
6585
  }
6951
6586
 
6952
- // package.json
6953
- var version = "0.2.3";
6587
+ // src/utils/formatSession.ts
6588
+ function formatSession(session) {
6589
+ if (!session) return "Waiting for Fluent login";
6590
+ return JSON.stringify(
6591
+ {
6592
+ app: {
6593
+ mode: session.app.mode,
6594
+ origin: session.app.origin,
6595
+ installationId: session.app.installationId,
6596
+ clientId: session.app.clientId,
6597
+ appName: session.app.appName
6598
+ },
6599
+ user: session.user,
6600
+ wallet: {
6601
+ smartAccountAddress: session.wallet.smartAccountAddress
6602
+ },
6603
+ scopes: session.scopes,
6604
+ issuedAt: session.issuedAt,
6605
+ idToken: session.idToken
6606
+ },
6607
+ null,
6608
+ 2
6609
+ );
6610
+ }
6954
6611
 
6955
- // src/core/analytics.ts
6956
- var INSTANCE_NAME = "fluent";
6957
- var POSTHOG_UI_HOST = "https://us.posthog.com";
6958
- var BLOCK_SELECTOR = 'body > *:not([data-slot="dialog-portal"]):not([data-slot="drawer-portal"])';
6959
- var UNLOAD_CAPTURE_OPTIONS = {
6960
- transport: "sendBeacon",
6961
- send_instantly: true
6962
- };
6963
- var client = null;
6964
- var loading = null;
6965
- var loadFailed = false;
6966
- var pending = [];
6967
- var widgetLoadedTracked = false;
6968
- function analyticsEnabled(config) {
6969
- return !config.disableAnalytics && Boolean(config.analyticsHost);
6612
+ // src/utils/getAnonymousId.ts
6613
+ function getAnonymousId() {
6614
+ const storageKey = "fluent_demo_visitor_id";
6615
+ const existing = localStorage.getItem(storageKey);
6616
+ if (existing) return existing;
6617
+ const next = crypto.randomUUID?.() ?? `visitor_${Date.now()}_${Math.random().toString(16).slice(2)}`;
6618
+ localStorage.setItem(storageKey, next);
6619
+ return next;
6970
6620
  }
6971
- function initFluentAnalytics(config) {
6972
- if (!analyticsEnabled(config) || loading) return;
6973
- loading = import('posthog-js').then(({ default: posthog }) => {
6974
- client = posthog.init(
6975
- FLUENT_CONNECT_POSTHOG_TOKEN,
6976
- {
6977
- api_host: config.analyticsHost,
6978
- ui_host: POSTHOG_UI_HOST,
6979
- persistence: "localStorage",
6980
- // The widget is a guest in someone else's page — no automatic collection.
6981
- // Every one of these must be set explicitly: the project's remote config
6982
- // turns performance capture, heatmaps and console recording ON, so leaving
6983
- // an option out is not the same as switching it off.
6984
- autocapture: false,
6985
- capture_pageview: false,
6986
- capture_pageleave: false,
6987
- rageclick: false,
6988
- capture_performance: false,
6989
- capture_heatmaps: false,
6990
- capture_dead_clicks: false,
6991
- // Widget console logs carry session ids and wallet addresses.
6992
- enable_recording_console_log: false,
6993
- session_recording: { blockSelector: BLOCK_SELECTOR }
6994
- },
6995
- INSTANCE_NAME
6996
- );
6997
- for (const queued of pending.splice(0)) {
6998
- capture(queued.eventName, queued.payload, queued.unload);
6999
- }
7000
- }).catch(() => {
7001
- loadFailed = true;
7002
- pending = [];
7003
- });
6621
+
6622
+ // src/utils/getHighResTwitterAvatar.ts
6623
+ function getHighResTwitterAvatar(url) {
6624
+ if (!url) return "";
6625
+ return url.replace("_normal", "");
7004
6626
  }
7005
- function sanitise(properties) {
7006
- if (!properties) return properties;
7007
- const safe = {};
7008
- for (const [key, value] of Object.entries(properties)) {
7009
- const type = typeof value;
7010
- if (value === null || type === "string" || type === "number" || type === "boolean") {
7011
- safe[key] = value;
7012
- }
6627
+
6628
+ // src/utils/hasStoredWidgetSession.ts
6629
+ function hasStoredWidgetSession(storage = globalThis.window?.localStorage) {
6630
+ if (!storage) return false;
6631
+ try {
6632
+ return Boolean(storage.getItem(FLUENT_WIDGET_SESSION_STORAGE_KEY));
6633
+ } catch {
6634
+ return false;
7013
6635
  }
7014
- return safe;
7015
- }
7016
- function capture(eventName, payload, unload) {
7017
- if (unload) {
7018
- client?.capture(eventName, payload, UNLOAD_CAPTURE_OPTIONS);
7019
- return;
7020
- }
7021
- client?.capture(eventName, payload);
7022
- }
7023
- function send(eventName, payload, unload) {
7024
- if (client) {
7025
- capture(eventName, payload, unload);
7026
- return;
7027
- }
7028
- if (loadFailed) return;
7029
- pending.push({ eventName, payload, unload });
7030
- }
7031
- function createTracker(config, getContext) {
7032
- const enabled = analyticsEnabled(config);
7033
- if (enabled) initFluentAnalytics(config);
7034
- const base = {
7035
- partner_id: config.partnerId,
7036
- network: config.network,
7037
- auth_mode: config.authMode,
7038
- source: config.source,
7039
- campaign: config.campaign,
7040
- sdk_version: version
7041
- };
7042
- const track = (eventName, properties, options) => {
7043
- if (!enabled) return;
7044
- const payload = { ...sanitise(properties), ...base, ...getContext?.() };
7045
- send(eventName, payload, Boolean(options?.unload));
7046
- };
7047
- track.live = enabled;
7048
- return track;
7049
- }
7050
- function trackWidgetLoadedOnce(track, properties) {
7051
- if (widgetLoadedTracked) return;
7052
- track("widget_loaded", properties);
7053
- if (track.live) widgetLoadedTracked = true;
7054
6636
  }
7055
6637
 
7056
- // src/utils/buildFluentBridgeUrl.ts
7057
- function buildFluentBridgeUrl(bridgeUrl, recipient) {
7058
- if (!recipient) return bridgeUrl;
7059
- try {
7060
- const url = new URL(bridgeUrl);
7061
- url.searchParams.set("recipient", recipient);
7062
- return url.toString();
7063
- } catch {
7064
- const join = bridgeUrl.includes("?") ? "&" : "?";
7065
- return `${bridgeUrl}${join}recipient=${encodeURIComponent(recipient)}`;
7066
- }
6638
+ // src/utils/stringifyWithBigInt.ts
6639
+ function stringifyWithBigInt(value, space) {
6640
+ return JSON.stringify(
6641
+ value,
6642
+ (_key, next) => typeof next === "bigint" ? next.toString() : next,
6643
+ space
6644
+ );
7067
6645
  }
7068
6646
 
7069
- // src/utils/clearPrivyRecentLoginMethod.ts
7070
- function clearPrivyRecentLoginMethod(appId) {
7071
- if (typeof window === "undefined" || !appId) return;
7072
- try {
7073
- window.localStorage.removeItem(`privy:${appId}:recent-login-method`);
7074
- window.localStorage.removeItem(`privy:${appId}:recent-login-wallet-client`);
7075
- window.localStorage.removeItem(`privy:${appId}:recent-login-chain-type`);
7076
- } catch {
7077
- }
7078
- }
7079
- function cn(...inputs) {
7080
- return twMerge(clsx(inputs));
7081
- }
7082
- var WIDGET_STYLE_SCOPE = "fluent-root dark contents text-foreground";
7083
- var FluentPortalContainerContext = createContext(null);
7084
- function FluentPortalContainerProvider({ children }) {
7085
- const [container, setContainer] = useState(null);
7086
- useLayoutEffect(() => {
7087
- const element = document.createElement("div");
7088
- element.setAttribute("data-fluent-portal-root", "");
7089
- element.className = WIDGET_STYLE_SCOPE;
7090
- document.body.appendChild(element);
7091
- setContainer(element);
7092
- return () => {
7093
- element.remove();
7094
- setContainer(null);
7095
- };
7096
- }, []);
7097
- return /* @__PURE__ */ jsx(FluentPortalContainerContext.Provider, { value: container, children });
7098
- }
7099
- function useFluentPortalContainer(override) {
7100
- const container = useContext(FluentPortalContainerContext);
7101
- return override ?? container ?? void 0;
7102
- }
7103
- var buttonVariants = cva(
7104
- "group/button inline-flex shrink-0 items-center justify-center rounded-xl border border-transparent bg-clip-padding font-medium whitespace-nowrap transition-all duration-75 outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
7105
- {
7106
- variants: {
7107
- variant: {
7108
- default: "bg-primary text-primary-foreground hover:bg-primary/80",
7109
- outline: "border-border bg-background hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",
7110
- secondary: "bg-button text-button-foreground hover:bg-button-hover aria-expanded:bg-button aria-expanded:text-button-foreground",
7111
- ghost: "hover:bg-primary/10 hover:text-foreground dark:hover:bg-primary/10",
7112
- destructive: "bg-destructive/10 text-destructive hover:bg-destructive/20 focus-visible:border-destructive/40 focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:hover:bg-destructive/30 dark:focus-visible:ring-destructive/40",
7113
- link: "text-primary underline-offset-4 hover:underline"
7114
- },
7115
- size: {
7116
- default: "h-10 gap-1.5 px-3.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2 text-sm",
7117
- xs: "h-6 gap-1 rounded-[min(var(--radius-md),10px)] px-2 text-xs in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3",
7118
- sm: "h-7 gap-1 rounded-[min(var(--radius-md),12px)] px-2.5 text-[0.8rem] in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5",
7119
- lg: "h-9 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
7120
- icon: "size-8",
7121
- "icon-xs": "size-6 rounded-[min(var(--radius-md),10px)] in-data-[slot=button-group]:rounded-lg [&_svg:not([class*='size-'])]:size-3",
7122
- "icon-sm": "size-7 rounded-[min(var(--radius-md),12px)] in-data-[slot=button-group]:rounded-lg",
7123
- "icon-lg": "size-9"
7124
- }
7125
- },
7126
- defaultVariants: {
7127
- variant: "default",
7128
- size: "default"
6647
+ // src/widget/zerodevSession.ts
6648
+ function useFluentZeroDevAccount(hookOptions = {}) {
6649
+ const { chain, network } = useFluentWidgetNetwork();
6650
+ const { authenticated, getAccessToken, login: privyLogin, ready } = usePrivy();
6651
+ const login = hookOptions.login ?? privyLogin;
6652
+ const { signMessage: promptSignMessage } = useSignMessage();
6653
+ const { signTypedData: promptSignTypedData } = useSignTypedData();
6654
+ const { wallets } = useWallets();
6655
+ const [kernels, setKernels] = useState({});
6656
+ const [error, setError] = useState(null);
6657
+ const [smartAccountReady, setSmartAccountReady] = useState(false);
6658
+ const initPromise = useRef({});
6659
+ const sponsorshipUnavailable = useRef(false);
6660
+ const embeddedWallet = wallets.find((wallet) => wallet.walletClientType === "privy");
6661
+ const hostedSigner = useMemo(
6662
+ () => hookOptions.allowHostedSigner !== false && hookOptions.authorizeUrl && hookOptions.sessionSignerAddress ? createFluentHostedSigner({
6663
+ address: hookOptions.sessionSignerAddress,
6664
+ authorizeUrl: hookOptions.authorizeUrl
6665
+ }) : null,
6666
+ [
6667
+ hookOptions.allowHostedSigner,
6668
+ hookOptions.authorizeUrl,
6669
+ hookOptions.sessionSignerAddress
6670
+ ]
6671
+ );
6672
+ const activeKernel = kernels.prompt ?? kernels.silent ?? null;
6673
+ useEffect(() => {
6674
+ setKernels({});
6675
+ setSmartAccountReady(false);
6676
+ setError(null);
6677
+ initPromise.current = {};
6678
+ }, [chain.id]);
6679
+ useEffect(() => () => hostedSigner?.close(), [hostedSigner]);
6680
+ const initialize2 = useCallback(async (options = {}) => {
6681
+ const signerMode = options.signerMode ?? "prompt";
6682
+ const cachedKernel = kernels[signerMode];
6683
+ debugLog("[fluent zerodev] initialize requested", {
6684
+ signerMode,
6685
+ ready,
6686
+ authenticated,
6687
+ walletCount: wallets.length,
6688
+ embeddedWalletCount: wallets.filter((wallet) => wallet.walletClientType === "privy").length,
6689
+ embeddedWallet: embeddedWallet?.address,
6690
+ hasKernel: Boolean(cachedKernel),
6691
+ cachedSignerModes: Object.keys(kernels),
6692
+ initInFlight: Boolean(initPromise.current[signerMode]),
6693
+ throwOnError: Boolean(options.throwOnError),
6694
+ hasProjectId: Boolean(FLUENT_CONNECT_ZERODEV_PROJECT_ID)
6695
+ });
6696
+ if (cachedKernel) {
6697
+ debugLog("[fluent zerodev] using cached kernel", {
6698
+ signerMode,
6699
+ smartAccountAddress: cachedKernel.smartAccountAddress
6700
+ });
6701
+ return cachedKernel;
7129
6702
  }
7130
- }
7131
- );
7132
- var Button = forwardRef(function Button2({ className, variant = "default", size = "default", href, target, rel, render, ...props }, ref) {
7133
- const isLink = href !== void 0;
7134
- return /* @__PURE__ */ jsx(
7135
- Button$1,
7136
- {
7137
- ref,
7138
- "data-slot": "button",
7139
- nativeButton: isLink ? false : void 0,
7140
- className: cn(buttonVariants({ variant, size, className })),
7141
- render: isLink ? /* @__PURE__ */ jsx("a", { href, target, rel }) : render,
7142
- ...props
6703
+ const canUseLocalSigner = ready && authenticated && Boolean(embeddedWallet);
6704
+ const canUseHostedSigner = Boolean(hostedSigner);
6705
+ const canUseAuthorizationSession = signerMode === "silent" && Boolean(hookOptions.authorizationSession?.serializedPermissionAccount) && (hookOptions.authorizationSession?.expiresAt ?? 0) > Math.floor(Date.now() / 1e3);
6706
+ if (!canUseLocalSigner && !canUseHostedSigner && !canUseAuthorizationSession) {
6707
+ const nextError = new Error(getZeroDevReadinessMessage({
6708
+ ready,
6709
+ authenticated,
6710
+ embeddedWalletCount: wallets.filter((wallet) => wallet.walletClientType === "privy").length,
6711
+ walletCount: wallets.length,
6712
+ hostedSignerAvailable: canUseHostedSigner
6713
+ }));
6714
+ debugWarn("[fluent zerodev] initialize blocked", {
6715
+ message: nextError.message,
6716
+ ready,
6717
+ authenticated,
6718
+ embeddedWalletCount: wallets.filter((wallet) => wallet.walletClientType === "privy").length,
6719
+ walletCount: wallets.length
6720
+ });
6721
+ setError(nextError);
6722
+ if (options.throwOnError) throw nextError;
6723
+ return null;
7143
6724
  }
7144
- );
7145
- });
7146
- var toast = Toast$1.createToastManager();
7147
- function ToastProvider({ ...props }) {
7148
- return /* @__PURE__ */ jsx(Toast$1.Provider, { ...props });
7149
- }
7150
- function ToastPortal({ container, ...props }) {
7151
- return /* @__PURE__ */ jsx(
7152
- Toast$1.Portal,
7153
- {
7154
- "data-slot": "toast-portal",
7155
- container: useFluentPortalContainer(container),
7156
- ...props
6725
+ if (initPromise.current[signerMode]) {
6726
+ debugLog("[fluent zerodev] joining in-flight initialization");
6727
+ return initPromise.current[signerMode];
7157
6728
  }
7158
- );
7159
- }
7160
- function ToastViewport({ className, ...props }) {
7161
- return /* @__PURE__ */ jsx(
7162
- Toast$1.Viewport,
7163
- {
7164
- "data-slot": "toast-viewport",
7165
- className: cn(
7166
- "dark pointer-events-none fixed inset-x-4 bottom-4 z-[100] mx-auto w-[min(100%,368px)] max-w-[368px] text-foreground outline-none sm:right-4 sm:left-auto sm:mx-0",
7167
- className
7168
- ),
7169
- ...props
6729
+ setSmartAccountReady(Boolean(activeKernel));
6730
+ setError(null);
6731
+ initPromise.current[signerMode] = (async () => {
6732
+ debugLog("[fluent zerodev] initializing", {
6733
+ signerMode,
6734
+ embeddedWallet: embeddedWallet?.address,
6735
+ walletClientType: embeddedWallet?.walletClientType,
6736
+ hostedSigner: hostedSigner?.address
6737
+ });
6738
+ const nextKernel = canUseAuthorizationSession ? await createFluentZeroDevAuthorizedSessionKernel(
6739
+ hookOptions.authorizationSession,
6740
+ chain
6741
+ ) : await createFluentZeroDevKernel({
6742
+ wallet: canUseLocalSigner ? embeddedWallet : void 0,
6743
+ hostedSigner: canUseLocalSigner ? void 0 : hostedSigner ?? void 0,
6744
+ signerMode,
6745
+ promptedSigners: {
6746
+ signMessage: promptSignMessage,
6747
+ signTypedData: promptSignTypedData
6748
+ },
6749
+ chain
6750
+ });
6751
+ if (hookOptions.sessionSmartAccountAddress && nextKernel.smartAccountAddress.toLowerCase() !== hookOptions.sessionSmartAccountAddress.toLowerCase()) {
6752
+ throw new Error("Fluent Connect signer does not control the connected smart account");
6753
+ }
6754
+ debugLog("[fluent zerodev] ready", {
6755
+ signerMode,
6756
+ signerAddress: embeddedWallet?.address ?? hostedSigner?.address,
6757
+ smartAccountAddress: nextKernel.smartAccountAddress
6758
+ });
6759
+ setKernels((current) => ({ ...current, [signerMode]: nextKernel }));
6760
+ setSmartAccountReady(true);
6761
+ return nextKernel;
6762
+ })();
6763
+ try {
6764
+ return await initPromise.current[signerMode];
6765
+ } catch (err) {
6766
+ const nextError = err instanceof Error ? err : new Error("Failed to create ZeroDev account");
6767
+ debugError("[fluent zerodev] initialization failed", nextError);
6768
+ setKernels((current) => {
6769
+ const { [signerMode]: _failed, ...rest } = current;
6770
+ setSmartAccountReady(Object.keys(rest).length > 0);
6771
+ return rest;
6772
+ });
6773
+ setError(nextError);
6774
+ if (options.throwOnError) throw nextError;
6775
+ return null;
6776
+ } finally {
6777
+ delete initPromise.current[signerMode];
7170
6778
  }
6779
+ }, [
6780
+ activeKernel,
6781
+ authenticated,
6782
+ embeddedWallet,
6783
+ hostedSigner,
6784
+ kernels,
6785
+ hookOptions.sessionSmartAccountAddress,
6786
+ hookOptions.authorizationSession,
6787
+ promptSignMessage,
6788
+ promptSignTypedData,
6789
+ ready
6790
+ ]);
6791
+ useEffect(() => {
6792
+ if (!ready) return;
6793
+ if (!authenticated) {
6794
+ setKernels({});
6795
+ setSmartAccountReady(false);
6796
+ setError(null);
6797
+ initPromise.current = {};
6798
+ }
6799
+ }, [authenticated, ready]);
6800
+ const sendTransaction = useCallback(
6801
+ async (request) => {
6802
+ const cachedKernel = kernels.prompt;
6803
+ if (cachedKernel?.signerSource === "hosted" || !cachedKernel && hostedSigner && !(ready && authenticated && embeddedWallet)) {
6804
+ hostedSigner?.prepare("always");
6805
+ }
6806
+ const executionKernel = cachedKernel ?? await initialize2({ signerMode: "prompt" });
6807
+ if (!executionKernel) throw new Error(error?.message ?? "ZeroDev smart account is not ready");
6808
+ debugLog("[fluent zerodev] sendTransaction", {
6809
+ signerMode: executionKernel.signerMode,
6810
+ smartAccountAddress: executionKernel.smartAccountAddress,
6811
+ to: request.to,
6812
+ hasData: Boolean(request.data && request.data !== "0x"),
6813
+ value: (request.value ?? 0n).toString()
6814
+ });
6815
+ try {
6816
+ const hash = await executionKernel.client.sendTransaction({
6817
+ account: executionKernel.account,
6818
+ chain: executionKernel.chain,
6819
+ to: request.to,
6820
+ data: request.data ?? "0x",
6821
+ value: request.value ?? 0n
6822
+ });
6823
+ debugLog("[fluent zerodev] sendTransaction submitted", { hash });
6824
+ return hash;
6825
+ } catch (err) {
6826
+ debugError("[fluent zerodev] sendTransaction failed", err);
6827
+ throw err;
6828
+ }
6829
+ },
6830
+ [authenticated, embeddedWallet, error, hostedSigner, initialize2, kernels.prompt, ready]
6831
+ );
6832
+ const createSponsoredClient = useCallback(async (kernel) => {
6833
+ if (!hookOptions.sponsorshipUrl || !hookOptions.appId) return null;
6834
+ if (sponsorshipUnavailable.current) return null;
6835
+ const accessToken = await getAccessToken();
6836
+ if (!accessToken) return null;
6837
+ return createKernelAccountClient({
6838
+ account: kernel.account,
6839
+ chain: kernel.chain,
6840
+ bundlerTransport: createFluentBundlerTransport(kernel.zeroDevRpcUrl),
6841
+ client: kernel.publicClient,
6842
+ paymaster: createFluentZeroDevSponsoredPaymaster({
6843
+ chain: kernel.chain,
6844
+ accessToken,
6845
+ rpcUrl: createFluentSponsorshipRpcUrl({
6846
+ sponsorshipUrl: hookOptions.sponsorshipUrl,
6847
+ appId: hookOptions.appId
6848
+ })
6849
+ })
6850
+ });
6851
+ }, [getAccessToken, hookOptions.appId, hookOptions.sponsorshipUrl]);
6852
+ const sendCalls = useCallback(
6853
+ async (calls, options) => {
6854
+ const signerMode = confirmationToSignerMode(options?.confirmation ?? "always");
6855
+ const cachedKernel = kernels[signerMode];
6856
+ const hasAuthorizationSession = signerMode === "silent" && Boolean(hookOptions.authorizationSession?.serializedPermissionAccount) && (hookOptions.authorizationSession?.expiresAt ?? 0) > Math.floor(Date.now() / 1e3);
6857
+ if (cachedKernel?.signerSource === "hosted" || !cachedKernel && !hasAuthorizationSession && hostedSigner && !(ready && authenticated && embeddedWallet)) {
6858
+ hostedSigner?.prepare(options?.confirmation ?? "always");
6859
+ }
6860
+ const executionKernel = cachedKernel ?? await initialize2({ signerMode, throwOnError: true });
6861
+ if (!executionKernel) throw new Error(error?.message ?? "ZeroDev smart account is not ready");
6862
+ const gasToken = options?.gasPayment?.symbol ? getFluentGasTokenAddress(options.gasPayment.symbol, network) : void 0;
6863
+ const preparedCalls = [...calls];
6864
+ if (gasToken && options?.gasPayment?.includeApproval) {
6865
+ preparedCalls.unshift(await createFluentZeroDevErc20PaymasterApprovalCall({
6866
+ chain: executionKernel.chain,
6867
+ gasToken,
6868
+ approveAmount: options.gasPayment.approveAmount
6869
+ }));
6870
+ }
6871
+ debugLog("[fluent zerodev] sendCalls", {
6872
+ signerMode,
6873
+ smartAccountAddress: executionKernel.smartAccountAddress,
6874
+ gasToken,
6875
+ gasTokenSymbol: options?.gasPayment?.symbol,
6876
+ sponsorship: options?.gasPayment?.sponsorship ?? "auto",
6877
+ approvalIncluded: Boolean(gasToken && options?.gasPayment?.includeApproval),
6878
+ calls: preparedCalls.map((call) => ({
6879
+ to: call.to,
6880
+ hasData: Boolean(call.data && call.data !== "0x"),
6881
+ value: (call.value ?? 0n).toString()
6882
+ }))
6883
+ });
6884
+ setPromptSigningContext({
6885
+ intent: "transaction",
6886
+ gasTokenSymbol: options?.gasPayment?.symbol
6887
+ });
6888
+ try {
6889
+ const callArgs = {
6890
+ account: executionKernel.account,
6891
+ calls: preparedCalls.map((call) => ({
6892
+ to: call.to,
6893
+ data: call.data ?? "0x",
6894
+ value: call.value ?? 0n
6895
+ }))
6896
+ };
6897
+ const sponsorshipRefused = !gasToken && options?.gasPayment?.sponsorship === "never";
6898
+ const sponsoredClient = gasToken || sponsorshipRefused ? null : await createSponsoredClient(executionKernel);
6899
+ const executionClient = gasToken ? createFluentZeroDevErc20ExecutionClient(executionKernel, gasToken) : sponsoredClient ?? executionKernel.client;
6900
+ let sponsorshipReason;
6901
+ if (sponsorshipRefused) {
6902
+ sponsorshipReason = "not_requested";
6903
+ } else if (!gasToken && !sponsoredClient && hookOptions.sponsorshipUrl && hookOptions.appId) {
6904
+ sponsorshipReason = sponsorshipUnavailable.current ? "unauthorized" : "no_token";
6905
+ }
6906
+ let settlementClient = executionClient;
6907
+ let userOpHash;
6908
+ try {
6909
+ userOpHash = await executionClient.sendUserOperation(callArgs);
6910
+ } catch (err) {
6911
+ if (!sponsoredClient) throw err;
6912
+ const failure = getSponsorshipFailure(err);
6913
+ sponsorshipReason = failure.reason;
6914
+ if (failure.disableSponsorship) sponsorshipUnavailable.current = true;
6915
+ debugWarn("[fluent zerodev] sponsorship unavailable, paying own gas", {
6916
+ reason: sponsorshipReason
6917
+ });
6918
+ settlementClient = executionKernel.client;
6919
+ userOpHash = await executionKernel.client.sendUserOperation(callArgs);
6920
+ }
6921
+ debugLog("[fluent zerodev] sendCalls userOp submitted", { userOpHash });
6922
+ const receipt = await settlementClient.waitForUserOperationReceipt({
6923
+ hash: userOpHash
6924
+ });
6925
+ const paymaster = readUserOperationPaymaster(receipt);
6926
+ const sponsored = gasToken ? false : paymaster ? paymaster !== zeroAddress : Boolean(sponsoredClient);
6927
+ if (!gasToken && sponsoredClient && !sponsored) sponsorshipReason ??= "denied";
6928
+ debugLog("[fluent zerodev] sendCalls receipt", {
6929
+ userOpHash,
6930
+ success: receipt.success,
6931
+ reason: receipt.reason,
6932
+ transactionHash: receipt.receipt.transactionHash,
6933
+ sponsored,
6934
+ paymaster,
6935
+ sponsorshipReason
6936
+ });
6937
+ if (!receipt.success) {
6938
+ throw new Error(receipt.reason ?? `UserOperation ${userOpHash} execution failed`);
6939
+ }
6940
+ return {
6941
+ hash: receipt.receipt.transactionHash,
6942
+ sponsored,
6943
+ sponsorshipReason,
6944
+ paymaster
6945
+ };
6946
+ } catch (err) {
6947
+ debugError("[fluent zerodev] sendCalls failed", err);
6948
+ throw err;
6949
+ } finally {
6950
+ clearPromptSigningContext();
6951
+ }
6952
+ },
6953
+ [
6954
+ authenticated,
6955
+ createSponsoredClient,
6956
+ embeddedWallet,
6957
+ error,
6958
+ hostedSigner,
6959
+ hookOptions.authorizationSession,
6960
+ hookOptions.appId,
6961
+ hookOptions.sponsorshipUrl,
6962
+ initialize2,
6963
+ kernels,
6964
+ network,
6965
+ ready
6966
+ ]
7171
6967
  );
7172
- }
7173
- function Toast({ className, style, ...props }) {
7174
- return /* @__PURE__ */ jsx(
7175
- Toast$1.Root,
7176
- {
7177
- "data-slot": "toast",
7178
- style: { maxWidth: 368, ...style },
7179
- className: cn(
7180
- "group/toast pointer-events-auto absolute right-0 bottom-0 z-[calc(1000-var(--toast-index))] w-full max-w-[368px] origin-bottom rounded-2xl border border-white/20 bg-popover text-popover-foreground shadow-lg will-change-transform outline-none select-none focus-visible:border-border focus-visible:ring-[3px] focus-visible:ring-ring/50",
7181
- "[--gap:0.75rem] [--height:var(--toast-frontmost-height,var(--toast-height))] [--offset-y:calc(var(--toast-offset-y)*-1+calc(var(--toast-index)*var(--gap)*-1)+var(--toast-swipe-movement-y))] [--peek:0.75rem] [--scale:calc(max(0,1-(var(--toast-index)*0.1)))] [--shrink:calc(1-var(--scale))]",
7182
- "h-(--height) [transform:translateX(var(--toast-swipe-movement-x))_translateY(calc(var(--toast-swipe-movement-y)-(var(--toast-index)*var(--peek))-(var(--shrink)*var(--height))))_scale(var(--scale))] [transition:transform_500ms_cubic-bezier(0.22,1,0.36,1),opacity_500ms,height_150ms]",
7183
- "after:absolute after:top-full after:left-0 after:h-[calc(var(--gap)+1px)] after:w-full after:content-['']",
7184
- "data-expanded:h-(--toast-height) data-expanded:[transform:translateX(var(--toast-swipe-movement-x))_translateY(var(--offset-y))]",
7185
- "data-limited:opacity-0 data-starting-style:[transform:translateY(150%)]",
7186
- "[&[data-ending-style]:not([data-limited]):not([data-swipe-direction])]:[transform:translateY(150%)]",
7187
- "data-ending-style:data-[swipe-direction=down]:[transform:translateY(calc(var(--toast-swipe-movement-y)+150%))]",
7188
- "data-ending-style:data-[swipe-direction=left]:[transform:translateX(calc(var(--toast-swipe-movement-x)-150%))_translateY(var(--offset-y))]",
7189
- "data-ending-style:data-[swipe-direction=right]:[transform:translateX(calc(var(--toast-swipe-movement-x)+150%))_translateY(var(--offset-y))]",
7190
- "data-ending-style:data-[swipe-direction=up]:[transform:translateY(calc(var(--toast-swipe-movement-y)-150%))]",
7191
- "data-expanded:data-ending-style:data-[swipe-direction=down]:[transform:translateY(calc(var(--toast-swipe-movement-y)+150%))]",
7192
- "data-expanded:data-ending-style:data-[swipe-direction=left]:[transform:translateX(calc(var(--toast-swipe-movement-x)-150%))_translateY(var(--offset-y))]",
7193
- "data-expanded:data-ending-style:data-[swipe-direction=right]:[transform:translateX(calc(var(--toast-swipe-movement-x)+150%))_translateY(var(--offset-y))]",
7194
- "data-expanded:data-ending-style:data-[swipe-direction=up]:[transform:translateY(calc(var(--toast-swipe-movement-y)-150%))]",
7195
- className
7196
- ),
7197
- ...props
6968
+ const ensureExecutionReady = useCallback(async (options = {}) => {
6969
+ const signerMode = confirmationToSignerMode(options.confirmation ?? "always");
6970
+ if (kernels[signerMode]) return kernels[signerMode];
6971
+ if (!ready) throw new Error("Privy wallet context is still loading");
6972
+ if (!authenticated && !hostedSigner) {
6973
+ login();
6974
+ throw new Error("Complete wallet login, then submit the transaction again");
7198
6975
  }
7199
- );
6976
+ const executionKernel = await initialize2({ signerMode, throwOnError: true });
6977
+ if (!executionKernel) throw new Error(error?.message ?? "ZeroDev smart account is not ready");
6978
+ return executionKernel;
6979
+ }, [authenticated, error, hostedSigner, initialize2, kernels, login, ready]);
6980
+ return {
6981
+ smartAccountEnabled: Boolean(FLUENT_CONNECT_ZERODEV_PROJECT_ID),
6982
+ smartAccountReady,
6983
+ smartAccountAddress: activeKernel?.smartAccountAddress,
6984
+ signerAddress: embeddedWallet?.address ?? hookOptions.sessionSignerAddress,
6985
+ privyReady: ready,
6986
+ privyAuthenticated: authenticated,
6987
+ embeddedWalletCount: wallets.filter((wallet) => wallet.walletClientType === "privy").length,
6988
+ authenticate: login,
6989
+ kernel: activeKernel,
6990
+ signerModesReady: Object.keys(kernels),
6991
+ error,
6992
+ ensureExecutionReady,
6993
+ sendTransaction,
6994
+ sendCalls,
6995
+ refresh: () => initialize2({ throwOnError: true, signerMode: "prompt" })
6996
+ };
7200
6997
  }
7201
- function ToastContent({ className, ...props }) {
7202
- return /* @__PURE__ */ jsx(
7203
- Toast$1.Content,
7204
- {
7205
- "data-slot": "toast-content",
7206
- className: cn(
7207
- "flex h-full items-start gap-3 overflow-hidden p-4 transition-opacity duration-250 ease-[cubic-bezier(0.22,1,0.36,1)] data-behind:opacity-0 data-expanded:opacity-100",
7208
- className
7209
- ),
7210
- ...props
7211
- }
6998
+ var USER_OPERATION_EVENT_TOPIC = toEventSelector(
6999
+ parseAbiItem(
7000
+ "event UserOperationEvent(bytes32 indexed userOpHash, address indexed sender, address indexed paymaster, uint256 nonce, bool success, uint256 actualGasCost, uint256 actualGasUsed)"
7001
+ )
7002
+ ).toLowerCase();
7003
+ function readUserOperationPaymaster(receipt) {
7004
+ if (receipt.paymaster) return getAddress(receipt.paymaster);
7005
+ const event = receipt.logs.find(
7006
+ (log) => log.topics[0]?.toLowerCase() === USER_OPERATION_EVENT_TOPIC && log.topics[1]?.toLowerCase() === receipt.userOpHash.toLowerCase()
7212
7007
  );
7008
+ const topic = event?.topics[3];
7009
+ if (!topic || topic.length !== 66) return void 0;
7010
+ return getAddress(`0x${topic.slice(26)}`);
7213
7011
  }
7214
- function ToastTitle({ className, ...props }) {
7215
- return /* @__PURE__ */ jsx(
7216
- Toast$1.Title,
7217
- {
7218
- "data-slot": "toast-title",
7219
- className: cn("text-sm font-medium", className),
7220
- ...props
7221
- }
7222
- );
7012
+ function getZeroDevReadinessMessage(params) {
7013
+ if (!params.ready) return "Privy wallet context is still loading";
7014
+ if (params.hostedSignerAvailable) return "Fluent hosted signer is preparing";
7015
+ if (!params.authenticated) return "Fluent session is connected, but Privy embedded wallet is not authenticated on this page";
7016
+ if (params.embeddedWalletCount === 0) {
7017
+ return `Privy is authenticated, but no embedded wallet is available (${params.walletCount} linked wallets found)`;
7018
+ }
7019
+ return "Fluent ZeroDev account is still preparing. Try again in a moment.";
7223
7020
  }
7224
- function ToastDescription({
7225
- className,
7226
- ...props
7227
- }) {
7228
- return /* @__PURE__ */ jsx(
7229
- Toast$1.Description,
7230
- {
7231
- "data-slot": "toast-description",
7232
- className: cn("text-sm text-muted-foreground", className),
7233
- ...props
7234
- }
7021
+ async function createFluentZeroDevPermissionSession(params) {
7022
+ const sessionAccount = privateKeyToAccount(params.sessionPrivateKey);
7023
+ const signer = await toECDSASigner({ signer: sessionAccount });
7024
+ const policies = [
7025
+ toCallPolicy({
7026
+ policyVersion: CallPolicyVersion.V0_0_5,
7027
+ permissions: params.calls.map(
7028
+ (call) => call.abi && call.functionName ? {
7029
+ target: call.target,
7030
+ abi: call.abi,
7031
+ functionName: call.functionName,
7032
+ args: call.args,
7033
+ callType: call.callType,
7034
+ valueLimit: call.valueLimit ?? 0n
7035
+ } : {
7036
+ target: call.target,
7037
+ selector: call.selector,
7038
+ callType: call.callType,
7039
+ valueLimit: call.valueLimit ?? 0n
7040
+ }
7041
+ )
7042
+ })
7043
+ ];
7044
+ if (params.expiresAt) {
7045
+ policies.push(toTimestampPolicy({ validUntil: params.expiresAt }));
7046
+ }
7047
+ const permissionPlugin = await toPermissionValidator(params.kernel.publicClient, {
7048
+ signer,
7049
+ policies,
7050
+ entryPoint: getEntryPoint("0.7"),
7051
+ kernelVersion: KERNEL_V3_3
7052
+ });
7053
+ const serializedPermissionAccount = await serializePermissionAccount(
7054
+ params.kernel.account,
7055
+ params.sessionPrivateKey,
7056
+ void 0,
7057
+ void 0,
7058
+ permissionPlugin,
7059
+ true
7235
7060
  );
7061
+ return {
7062
+ serializedPermissionAccount,
7063
+ sessionSignerAddress: sessionAccount.address,
7064
+ smartAccountAddress: params.kernel.smartAccountAddress
7065
+ };
7236
7066
  }
7237
- function ToastAction({
7238
- className,
7239
- render = /* @__PURE__ */ jsx(Button, { variant: "outline", size: "sm" }),
7240
- ...props
7241
- }) {
7242
- return /* @__PURE__ */ jsx(
7243
- Toast$1.Action,
7244
- {
7245
- "data-slot": "toast-action",
7246
- render,
7247
- className: cn("shrink-0", className),
7248
- ...props
7249
- }
7250
- );
7067
+ function confirmationToSignerMode(confirmation) {
7068
+ return confirmation === "session" ? "silent" : "prompt";
7251
7069
  }
7252
- function ToastClose({
7253
- className,
7254
- children,
7255
- render = /* @__PURE__ */ jsx(Button, { variant: "ghost", size: "icon-sm" }),
7256
- ...props
7257
- }) {
7258
- return /* @__PURE__ */ jsx(
7259
- Toast$1.Close,
7260
- {
7261
- "data-slot": "toast-close",
7262
- "aria-label": "Close toast",
7263
- render,
7264
- className: cn(
7265
- "relative shrink-0 text-muted-foreground after:absolute after:-inset-2 after:content-[''] hover:text-foreground",
7266
- className
7267
- ),
7268
- ...props,
7269
- children: children ?? /* @__PURE__ */ jsx(XIcon, { "aria-hidden": "true" })
7270
- }
7070
+ async function createFluentZeroDevAuthorizedSessionKernel(authorizationSession, chain) {
7071
+ const zeroDevRpcUrl = `https://rpc.zerodev.app/api/v3/${FLUENT_CONNECT_ZERODEV_PROJECT_ID}/chain/${chain.id}`;
7072
+ const publicClient = createPublicClient({
7073
+ chain,
7074
+ transport: createFluentRpcTransport(chain)
7075
+ });
7076
+ const entryPoint = getEntryPoint("0.7");
7077
+ const sessionSigner = await toECDSASigner({
7078
+ signer: privateKeyToAccount(authorizationSession.sessionPrivateKey)
7079
+ });
7080
+ const account = await deserializePermissionAccount(
7081
+ publicClient,
7082
+ entryPoint,
7083
+ KERNEL_V3_3,
7084
+ authorizationSession.serializedPermissionAccount,
7085
+ sessionSigner
7271
7086
  );
7272
- }
7273
- function ToastIcon({ type }) {
7274
- let icon = null;
7275
- if (type === "success") {
7276
- icon = /* @__PURE__ */ jsx(CircleCheckIcon, { "aria-hidden": "true" });
7277
- }
7278
- if (type === "info") {
7279
- icon = /* @__PURE__ */ jsx(InfoIcon, { "aria-hidden": "true" });
7280
- }
7281
- if (type === "warning") {
7282
- icon = /* @__PURE__ */ jsx(TriangleAlertIcon, { "aria-hidden": "true" });
7283
- }
7284
- if (type === "error") {
7285
- icon = /* @__PURE__ */ jsx(OctagonXIcon, { className: "text-destructive", "aria-hidden": "true" });
7286
- }
7287
- if (type === "loading") {
7288
- icon = /* @__PURE__ */ jsx(Loader2Icon, { className: "animate-spin", "aria-hidden": "true" });
7087
+ const client2 = createKernelAccountClient({
7088
+ account,
7089
+ chain,
7090
+ bundlerTransport: createFluentBundlerTransport(zeroDevRpcUrl),
7091
+ client: publicClient
7092
+ });
7093
+ return {
7094
+ account,
7095
+ client: client2,
7096
+ publicClient,
7097
+ smartAccountAddress: account.address,
7098
+ zeroDevRpcUrl,
7099
+ chain,
7100
+ signerMode: "silent",
7101
+ signerSource: "session"
7102
+ };
7103
+ }
7104
+ async function createFluentZeroDevKernel(params) {
7105
+ if (!params.wallet && !params.hostedSigner) throw new Error("Fluent signer is unavailable");
7106
+ if (params.wallet) {
7107
+ debugLog("[fluent zerodev] ensuring Fluent chain", params.chain.id);
7108
+ await ensureWalletOnFluentChain(params.wallet, params.chain);
7109
+ debugLog("[fluent zerodev] Fluent chain ready", params.chain.id);
7289
7110
  }
7290
- if (!icon) {
7291
- return null;
7111
+ const zeroDevRpcUrl = `https://rpc.zerodev.app/api/v3/${FLUENT_CONNECT_ZERODEV_PROJECT_ID}/chain/${params.chain.id}`;
7112
+ const publicClient = createPublicClient({
7113
+ chain: params.chain,
7114
+ transport: createFluentRpcTransport(params.chain)
7115
+ });
7116
+ const entryPoint = getEntryPoint("0.7");
7117
+ let signer;
7118
+ if (params.hostedSigner) {
7119
+ signer = toHostedSignerLocalAccount(params.hostedSigner, params.signerMode);
7120
+ } else if (params.wallet && params.signerMode === "prompt") {
7121
+ signer = toPromptedPrivyLocalAccount(params.wallet, params.promptedSigners, params.chain);
7122
+ } else if (params.wallet) {
7123
+ signer = toSilentPrivyLocalAccount(params.wallet, params.chain);
7124
+ } else {
7125
+ throw new Error("Fluent signer is unavailable");
7292
7126
  }
7293
- return /* @__PURE__ */ jsx(
7294
- "span",
7295
- {
7296
- "data-slot": "toast-icon",
7297
- className: "shrink-0 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4",
7298
- children: icon
7127
+ const ecdsaValidator = await signerToEcdsaValidator(publicClient, {
7128
+ signer,
7129
+ entryPoint,
7130
+ kernelVersion: KERNEL_V3_3
7131
+ });
7132
+ const account = await createKernelAccount(publicClient, {
7133
+ entryPoint,
7134
+ plugins: { sudo: ecdsaValidator },
7135
+ kernelVersion: KERNEL_V3_3
7136
+ });
7137
+ const client2 = createKernelAccountClient({
7138
+ account,
7139
+ chain: params.chain,
7140
+ bundlerTransport: createFluentBundlerTransport(zeroDevRpcUrl),
7141
+ client: publicClient
7142
+ });
7143
+ return {
7144
+ account,
7145
+ client: client2,
7146
+ publicClient,
7147
+ smartAccountAddress: account.address,
7148
+ zeroDevRpcUrl,
7149
+ chain: params.chain,
7150
+ signerMode: params.signerMode,
7151
+ signerSource: params.hostedSigner ? "hosted" : "privy"
7152
+ };
7153
+ }
7154
+ function toHostedSignerLocalAccount(signer, signerMode) {
7155
+ const confirmation = signerMode === "silent" ? "session" : "always";
7156
+ const source = {
7157
+ address: signer.address,
7158
+ async signMessage({ message }) {
7159
+ return signer.signMessage(formatSignableMessageForPrivy(message), confirmation);
7160
+ },
7161
+ async signTransaction() {
7162
+ throw new Error("Fluent ZeroDev signer does not sign raw transactions");
7163
+ },
7164
+ async signTypedData(typedData) {
7165
+ return signer.signTypedData(
7166
+ {
7167
+ domain: typedData.domain,
7168
+ types: typedData.types,
7169
+ primaryType: typedData.primaryType,
7170
+ message: typedData.message
7171
+ },
7172
+ confirmation
7173
+ );
7299
7174
  }
7300
- );
7175
+ };
7176
+ return toAccount(source);
7301
7177
  }
7302
- function ToastList() {
7303
- const { toasts } = Toast$1.useToastManager();
7304
- return toasts.map((toastItem) => /* @__PURE__ */ jsx(Toast, { toast: toastItem, children: /* @__PURE__ */ jsxs(ToastContent, { children: [
7305
- /* @__PURE__ */ jsxs("div", { className: "flex min-w-0 flex-1 flex-col gap-1", children: [
7306
- /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1.5", children: [
7307
- /* @__PURE__ */ jsx(ToastIcon, { type: toastItem.type }),
7308
- /* @__PURE__ */ jsx(ToastTitle, {})
7309
- ] }),
7310
- /* @__PURE__ */ jsx(ToastDescription, {})
7311
- ] }),
7312
- /* @__PURE__ */ jsx(ToastAction, {}),
7313
- /* @__PURE__ */ jsx(ToastClose, {})
7314
- ] }) }, toastItem.id));
7178
+ function createFluentZeroDevErc20ExecutionClient(kernel, gasToken) {
7179
+ return createKernelAccountClient({
7180
+ account: kernel.account,
7181
+ chain: kernel.chain,
7182
+ bundlerTransport: createFluentBundlerTransport(kernel.zeroDevRpcUrl),
7183
+ client: kernel.publicClient,
7184
+ paymaster: createFluentZeroDevErc20Paymaster({
7185
+ chain: kernel.chain,
7186
+ gasToken
7187
+ })
7188
+ });
7315
7189
  }
7316
- function Toaster({
7317
- children,
7318
- toastManager = toast,
7319
- ...props
7320
- }) {
7321
- return /* @__PURE__ */ jsxs(ToastProvider, { toastManager, ...props, children: [
7322
- children,
7323
- /* @__PURE__ */ jsx(ToastPortal, { children: /* @__PURE__ */ jsx(ToastViewport, { children: /* @__PURE__ */ jsx(ToastList, {}) }) })
7324
- ] });
7190
+ var promptSigningContext = {};
7191
+ function setPromptSigningContext(context) {
7192
+ promptSigningContext = context;
7325
7193
  }
7326
- Toast$1.createToastManager;
7327
- Toast$1.useToastManager;
7328
-
7329
- // src/utils/formatAddress.ts
7330
- function formatAddress(address) {
7331
- return `${address.slice(0, 6)}...${address.slice(-4)}`;
7194
+ function clearPromptSigningContext() {
7195
+ promptSigningContext = {};
7332
7196
  }
7333
-
7334
- // src/utils/copyAddress.ts
7335
- async function copyAddressToClipboard(address) {
7197
+ async function withFluentSignaturePrompt(sign) {
7198
+ setPromptSigningContext({ intent: "signature" });
7336
7199
  try {
7337
- await navigator.clipboard.writeText(address);
7338
- toast.add({
7339
- type: "success",
7340
- title: "Address copied",
7341
- description: formatAddress(address)
7342
- });
7343
- } catch (error) {
7344
- debugWarn("[fluent connect] Failed to copy address", error);
7345
- toast.add({
7346
- type: "error",
7347
- title: "Copy failed",
7348
- description: "Could not copy address to clipboard."
7349
- });
7200
+ return await sign();
7201
+ } finally {
7202
+ clearPromptSigningContext();
7350
7203
  }
7351
7204
  }
7352
-
7353
- // src/utils/createLocalFluentSession.ts
7354
- function createLocalFluentSession(params) {
7355
- const issuedAt = Math.floor(Date.now() / 1e3);
7356
- const payload = {
7357
- iss: typeof location !== "undefined" ? location.origin : "fluent-local",
7358
- aud: params.partnerId,
7359
- sub: params.userId,
7360
- app: params.app,
7361
- scopes: params.scopes,
7362
- iat: issuedAt
7363
- };
7205
+ function buildPromptSigningUiOptions() {
7206
+ if (promptSigningContext.intent === "signature") {
7207
+ return {
7208
+ title: "Sign with Fluent",
7209
+ description: "Sign this request with your Fluent account. Nothing is sent on chain.",
7210
+ buttonText: "Sign"
7211
+ };
7212
+ }
7213
+ const gasTokenSymbol = promptSigningContext.gasTokenSymbol;
7364
7214
  return {
7365
- app: params.app,
7366
- partnerId: params.partnerId,
7367
- idToken: `mock.${btoa(JSON.stringify(payload))}.signature`,
7368
- user: {
7369
- id: params.userId,
7370
- email: params.email
7215
+ title: "Confirm Fluent transaction",
7216
+ description: gasTokenSymbol ? `Gas will be paid in ${gasTokenSymbol}. Confirm this Fluent transaction.` : "Confirm this Fluent transaction.",
7217
+ buttonText: "Sign"
7218
+ };
7219
+ }
7220
+ function toPromptedPrivyLocalAccount(wallet, promptedSigners, chain) {
7221
+ const source = {
7222
+ address: wallet.address,
7223
+ async signMessage({ message }) {
7224
+ await ensureWalletOnFluentChain(wallet, chain);
7225
+ const { signature } = await promptedSigners.signMessage(
7226
+ { message: formatSignableMessageForPrivy(message) },
7227
+ {
7228
+ address: wallet.address,
7229
+ uiOptions: buildPromptSigningUiOptions()
7230
+ }
7231
+ );
7232
+ return signature;
7371
7233
  },
7372
- wallet: {
7373
- signerAddress: params.signerAddress,
7374
- smartAccountAddress: params.smartAccountAddress
7234
+ async signTransaction() {
7235
+ throw new Error("Fluent ZeroDev signer does not sign raw transactions");
7375
7236
  },
7376
- scopes: params.scopes,
7377
- issuedAt,
7378
- metadata: {
7379
- authMode: "direct",
7380
- origin: params.app.origin
7237
+ async signTypedData(typedData) {
7238
+ await ensureWalletOnFluentChain(wallet, chain);
7239
+ const { signature } = await promptedSigners.signTypedData(
7240
+ {
7241
+ domain: typedData.domain,
7242
+ types: typedData.types,
7243
+ primaryType: typedData.primaryType,
7244
+ message: typedData.message
7245
+ },
7246
+ {
7247
+ address: wallet.address,
7248
+ uiOptions: buildPromptSigningUiOptions()
7249
+ }
7250
+ );
7251
+ return signature;
7252
+ }
7253
+ };
7254
+ return toAccount(source);
7255
+ }
7256
+ function toSilentPrivyLocalAccount(wallet, chain) {
7257
+ const source = {
7258
+ address: wallet.address,
7259
+ async signMessage({ message }) {
7260
+ debugLog("[fluent zerodev] requesting embedded provider signature", {
7261
+ signerAddress: wallet.address,
7262
+ messageKind: typeof message === "string" ? "string" : "raw" in message ? "raw" : typeof message
7263
+ });
7264
+ await ensureWalletOnFluentChain(wallet, chain);
7265
+ const provider = await wallet.getEthereumProvider();
7266
+ if (!provider?.request) throw new Error("Fluent embedded wallet provider is unavailable");
7267
+ const formattedMessage = formatSignableMessageForPrivy(message);
7268
+ try {
7269
+ const signature = await provider.request({
7270
+ method: "personal_sign",
7271
+ params: [isHex(formattedMessage) ? formattedMessage : stringToHex(formattedMessage), wallet.address]
7272
+ });
7273
+ if (typeof signature !== "string") throw new Error("Privy embedded wallet returned an invalid signature");
7274
+ debugLog("[fluent zerodev] embedded provider signature ready", {
7275
+ signerAddress: wallet.address,
7276
+ signatureLength: signature.length
7277
+ });
7278
+ return signature;
7279
+ } catch (err) {
7280
+ debugError("[fluent zerodev] embedded provider signature failed", err);
7281
+ throw err;
7282
+ }
7283
+ },
7284
+ async signTransaction() {
7285
+ throw new Error("Fluent ZeroDev signer does not sign raw transactions");
7286
+ },
7287
+ async signTypedData(typedData) {
7288
+ debugLog("[fluent zerodev] requesting embedded provider typed-data signature", {
7289
+ signerAddress: wallet.address,
7290
+ primaryType: typedData.primaryType
7291
+ });
7292
+ await ensureWalletOnFluentChain(wallet, chain);
7293
+ const provider = await wallet.getEthereumProvider();
7294
+ if (!provider?.request) throw new Error("Fluent embedded wallet provider is unavailable");
7295
+ try {
7296
+ const signature = await provider.request({
7297
+ method: "eth_signTypedData_v4",
7298
+ params: [
7299
+ wallet.address,
7300
+ stringifyTypedDataForProvider({
7301
+ domain: typedData.domain,
7302
+ types: typedData.types,
7303
+ primaryType: typedData.primaryType,
7304
+ message: typedData.message
7305
+ })
7306
+ ]
7307
+ });
7308
+ if (typeof signature !== "string") {
7309
+ throw new Error("Privy embedded wallet returned an invalid typed-data signature");
7310
+ }
7311
+ debugLog("[fluent zerodev] embedded provider typed-data signature ready", {
7312
+ signerAddress: wallet.address,
7313
+ signatureLength: signature.length
7314
+ });
7315
+ return signature;
7316
+ } catch (err) {
7317
+ debugError("[fluent zerodev] embedded provider typed-data signature failed", err);
7318
+ throw err;
7319
+ }
7381
7320
  }
7382
7321
  };
7322
+ return toAccount(source);
7383
7323
  }
7384
-
7385
- // src/utils/explorerAddress.ts
7386
- function explorerAddress(address, network) {
7387
- const baseUrl = getFluentExplorerBaseUrl(network ?? "testnet");
7388
- return `${baseUrl}/address/${address}`;
7389
- }
7390
-
7391
- // src/utils/faucetToast.ts
7392
- function normalize(value) {
7393
- return (value ?? "").trim().toLowerCase();
7324
+ function stringifyTypedDataForProvider(value) {
7325
+ return stringifyWithBigInt(value);
7394
7326
  }
7395
- function isAlreadyClaimed(status, message) {
7396
- const statusNorm = normalize(status);
7397
- const messageNorm = normalize(message);
7398
- return statusNorm.includes("already") || messageNorm.includes("already");
7327
+ function formatSignableMessageForPrivy(message) {
7328
+ if (typeof message === "string") return message;
7329
+ if ("raw" in message) return typeof message.raw === "string" ? message.raw : bytesToHex(message.raw);
7330
+ return String(message);
7399
7331
  }
7400
- function toastFaucetSuccess(receipt) {
7401
- if (isAlreadyClaimed(receipt.status, receipt.message)) {
7402
- toast.add({
7403
- type: "info",
7404
- title: "Already claimed",
7405
- description: receipt.message || "BLEND faucet was already claimed for this account."
7406
- });
7407
- return;
7332
+ async function ensureWalletOnFluentChain(wallet, chain) {
7333
+ const targetChainId = numberToHex(chain.id);
7334
+ const provider = await wallet.getEthereumProvider();
7335
+ if (wallet.switchChain) {
7336
+ debugLog("[fluent zerodev] wallet.switchChain", chain.id);
7337
+ await wallet.switchChain(chain.id);
7408
7338
  }
7409
- toast.add({
7410
- type: "success",
7411
- title: "Faucet claimed",
7412
- description: receipt.message || (receipt.txHash ? `Transaction ${receipt.txHash}` : "BLEND was sent to your wallet.")
7413
- });
7414
- }
7415
- function toastFaucetError(error) {
7416
- if (error instanceof HttpError) {
7417
- if (isAlreadyClaimed(error.body?.status, error.message) || error.status === 409) {
7418
- toast.add({
7419
- type: "info",
7420
- title: "Already claimed",
7421
- description: error.message || "BLEND faucet was already claimed for this account."
7339
+ if (provider?.request) {
7340
+ const currentChainId = await getProviderChainId(provider);
7341
+ debugLog("[fluent zerodev] provider chain", currentChainId);
7342
+ if (currentChainId === targetChainId) return;
7343
+ try {
7344
+ await provider.request({
7345
+ method: "wallet_switchEthereumChain",
7346
+ params: [{ chainId: targetChainId }]
7422
7347
  });
7423
- return;
7424
- }
7425
- if (error.status === 429) {
7426
- toast.add({
7427
- type: "warning",
7428
- title: "Too many requests",
7429
- description: error.message || "Please wait a moment and try again."
7348
+ } catch (err) {
7349
+ if (!isUnknownChainError(err)) throw err;
7350
+ await provider.request({
7351
+ method: "wallet_addEthereumChain",
7352
+ params: [
7353
+ {
7354
+ chainId: targetChainId,
7355
+ chainName: chain.name,
7356
+ nativeCurrency: chain.nativeCurrency,
7357
+ rpcUrls: chain.rpcUrls.default.http,
7358
+ blockExplorerUrls: chain.blockExplorers?.default.url ? [chain.blockExplorers.default.url] : void 0
7359
+ }
7360
+ ]
7361
+ });
7362
+ await provider.request({
7363
+ method: "wallet_switchEthereumChain",
7364
+ params: [{ chainId: targetChainId }]
7430
7365
  });
7431
- return;
7432
7366
  }
7433
- toast.add({
7434
- type: "error",
7435
- title: "Faucet request failed",
7436
- description: error.message || `Request failed with ${error.status}`
7437
- });
7367
+ const nextChainId = await getProviderChainId(provider);
7368
+ debugLog("[fluent zerodev] provider chain after switch", nextChainId);
7369
+ if (nextChainId !== targetChainId) {
7370
+ throw new Error(`Unsupported chainId ${Number(BigInt(nextChainId))}; switch to ${chain.name}`);
7371
+ }
7438
7372
  return;
7439
7373
  }
7440
- toast.add({
7441
- type: "error",
7442
- title: "Faucet request failed",
7443
- description: error instanceof Error ? error.message : "Something went wrong."
7444
- });
7374
+ throw new Error("Fluent embedded wallet provider is unavailable");
7445
7375
  }
7446
-
7447
- // src/utils/formatExternalWallet.ts
7448
- function formatExternalWallet(wallet, status) {
7449
- return JSON.stringify(
7450
- {
7451
- status: status ?? "Waiting for wallet connection",
7452
- wallet: wallet ? {
7453
- provider: "Reown AppKit",
7454
- configured: wallet.configured,
7455
- connected: wallet.connected,
7456
- address: wallet.address,
7457
- chainId: wallet.chainId
7458
- } : null,
7459
- walletConnectEnabled: Boolean(wallet?.configured)
7460
- },
7461
- null,
7462
- 2
7463
- );
7376
+ async function getProviderChainId(provider) {
7377
+ const chainId = await provider.request({ method: "eth_chainId" });
7378
+ if (typeof chainId !== "string") throw new Error("Unable to read embedded wallet chainId");
7379
+ return chainId.toLowerCase();
7464
7380
  }
7465
-
7466
- // src/utils/formatFluentLocaleAmount.ts
7467
- var FLUENT_AMOUNT_LOCALE = "en-US";
7468
- var FLUENT_DECIMAL_SEPARATOR = new Intl.NumberFormat(FLUENT_AMOUNT_LOCALE).formatToParts(1.1).find((part) => part.type === "decimal")?.value ?? ".";
7469
- function formatFluentLocaleAmount(value, maximumFractionDigits = 2) {
7470
- const amount = typeof value === "number" ? value : Number(value);
7471
- if (!Number.isFinite(amount)) return typeof value === "string" ? value : String(value);
7472
- return amount.toLocaleString(FLUENT_AMOUNT_LOCALE, {
7473
- minimumFractionDigits: 0,
7474
- maximumFractionDigits
7475
- });
7381
+ function isUnknownChainError(err) {
7382
+ const code = err?.code;
7383
+ const nestedCode = err?.data?.originalError?.code;
7384
+ return code === 4902 || nestedCode === 4902;
7476
7385
  }
7477
7386
 
7478
- // src/utils/formatFluentGasTokenBalance.ts
7479
- var GAS_BALANCE_MAX_FRACTION_DIGITS = 6;
7480
- function roundToFractionDigits(raw, decimals, digits) {
7481
- const discardedScale = 10n ** BigInt(decimals - digits);
7482
- return (raw + discardedScale / 2n) / discardedScale;
7387
+ // src/widget/permissionSession.ts
7388
+ function createFluentPermissionApi(executor) {
7389
+ return {
7390
+ createPermissionSession: (input) => createFluentPermissionSession(input, executor),
7391
+ policies: createFluentPermissionPolicyBuilders()
7392
+ };
7483
7393
  }
7484
- function formatFluentGasTokenBalance(balance, maximumFractionDigits = 1) {
7485
- if (balance.raw === null || balance.formatted === null) return null;
7486
- if (maximumFractionDigits < 0 || !Number.isInteger(maximumFractionDigits)) {
7487
- throw new Error("maximumFractionDigits must be a non-negative integer");
7394
+ function createFluentPermissionPolicyBuilders() {
7395
+ return {
7396
+ call: (input) => ({
7397
+ kind: "call",
7398
+ id: input.id,
7399
+ call: input
7400
+ }),
7401
+ batch: (input) => ({
7402
+ kind: "batch",
7403
+ id: input.id,
7404
+ calls: input.calls
7405
+ })
7406
+ };
7407
+ }
7408
+ async function createFluentPermissionSession(input, executor) {
7409
+ if (!executor?.kernel || executor.smartAccountReady === false) {
7410
+ throw new Error("ZeroDev smart account is not ready");
7488
7411
  }
7489
- if (balance.decimals <= maximumFractionDigits) {
7490
- return formatFluentLocaleAmount(balance.formatted, maximumFractionDigits);
7412
+ if (input.policies.length === 0) {
7413
+ throw new Error("A permission session requires at least one policy");
7491
7414
  }
7492
- const maxDigits = Math.max(
7493
- maximumFractionDigits,
7494
- Math.min(balance.decimals, GAS_BALANCE_MAX_FRACTION_DIGITS)
7415
+ const calls = input.policies.flatMap(
7416
+ (policy) => policy.kind === "batch" ? policy.calls.map((call) => toZeroDevPermissionCall(call, CallType.BATCH_CALL)) : [toZeroDevPermissionCall(policy.call, CallType.CALL)]
7495
7417
  );
7496
- for (let digits = maximumFractionDigits; digits <= maxDigits; digits += 1) {
7497
- const rounded = roundToFractionDigits(balance.raw, balance.decimals, digits);
7498
- if (rounded > 0n || balance.raw === 0n) {
7499
- return formatFluentLocaleAmount(formatUnits(rounded, digits), digits);
7500
- }
7418
+ const expiresAt = toUnixSeconds(input.expiresAt);
7419
+ const permission = await createFluentZeroDevPermissionSession({
7420
+ kernel: executor.kernel,
7421
+ sessionPrivateKey: input.sessionPrivateKey ?? generatePrivateKey(),
7422
+ calls,
7423
+ expiresAt
7424
+ });
7425
+ return {
7426
+ ...permission,
7427
+ label: input.label,
7428
+ delegate: input.delegate,
7429
+ expiresAt,
7430
+ policies: input.policies
7431
+ };
7432
+ }
7433
+ function toZeroDevPermissionCall(call, callType) {
7434
+ const functionName = call.functionName ?? call.method;
7435
+ if (!functionName) throw new Error("Permission policy requires method or functionName");
7436
+ return {
7437
+ target: call.to,
7438
+ abi: call.abi,
7439
+ functionName,
7440
+ args: normalizePermissionArgs(call.abi, functionName, call.args),
7441
+ callType,
7442
+ valueLimit: call.valueLimit
7443
+ };
7444
+ }
7445
+ function normalizePermissionArgs(abi, functionName, args) {
7446
+ if (!args) return void 0;
7447
+ if (Array.isArray(args)) return args.map(toZeroDevCondition);
7448
+ const fn = findAbiFunction(abi, functionName);
7449
+ const namedArgs = args;
7450
+ return fn.inputs.map((input) => {
7451
+ if (!input.name) return null;
7452
+ return toZeroDevCondition(namedArgs[input.name]);
7453
+ });
7454
+ }
7455
+ function toZeroDevCondition(rule) {
7456
+ if (!rule) return null;
7457
+ if ("equals" in rule) {
7458
+ return { condition: ParamCondition.EQUAL, value: rule.equals };
7459
+ }
7460
+ if ("max" in rule) {
7461
+ return { condition: ParamCondition.LESS_THAN_OR_EQUAL, value: rule.max };
7462
+ }
7463
+ return { condition: ParamCondition.GREATER_THAN_OR_EQUAL, value: rule.min };
7464
+ }
7465
+ function findAbiFunction(abi, functionName) {
7466
+ const matches = abi.filter(
7467
+ (item) => item.type === "function" && item.name === functionName
7468
+ );
7469
+ if (matches.length !== 1) {
7470
+ throw new Error(
7471
+ matches.length === 0 ? `Function "${functionName}" not found in ABI` : `Function "${functionName}" is overloaded; pass positional args or a filtered ABI`
7472
+ );
7501
7473
  }
7502
- return formatFluentLocaleAmount(0, maximumFractionDigits);
7474
+ return matches[0];
7475
+ }
7476
+ function toUnixSeconds(value) {
7477
+ if (value === void 0) return void 0;
7478
+ if (value instanceof Date) return Math.floor(value.getTime() / 1e3);
7479
+ return value > 1e12 ? Math.floor(value / 1e3) : Math.floor(value);
7503
7480
  }
7504
7481
 
7505
- // src/utils/formatSession.ts
7506
- function formatSession(session) {
7507
- if (!session) return "Waiting for Fluent login";
7508
- return JSON.stringify(
7509
- {
7510
- app: {
7511
- mode: session.app.mode,
7512
- origin: session.app.origin,
7513
- installationId: session.app.installationId,
7514
- clientId: session.app.clientId,
7515
- appName: session.app.appName
7516
- },
7517
- user: session.user,
7518
- wallet: {
7519
- smartAccountAddress: session.wallet.smartAccountAddress
7482
+ // package.json
7483
+ var version = "0.3.1";
7484
+
7485
+ // src/core/analytics.ts
7486
+ var INSTANCE_NAME = "fluent";
7487
+ var POSTHOG_UI_HOST = "https://us.posthog.com";
7488
+ var BLOCK_SELECTOR = 'body > *:not([data-slot="dialog-portal"]):not([data-slot="drawer-portal"])';
7489
+ var UNLOAD_CAPTURE_OPTIONS = {
7490
+ transport: "sendBeacon",
7491
+ send_instantly: true
7492
+ };
7493
+ var client = null;
7494
+ var loading = null;
7495
+ var loadFailed = false;
7496
+ var pending = [];
7497
+ var widgetLoadedTracked = false;
7498
+ function analyticsEnabled(config) {
7499
+ return !config.disableAnalytics && Boolean(config.analyticsHost);
7500
+ }
7501
+ function initFluentAnalytics(config) {
7502
+ if (!analyticsEnabled(config) || loading) return;
7503
+ loading = import('posthog-js').then(({ default: posthog }) => {
7504
+ client = posthog.init(
7505
+ FLUENT_CONNECT_POSTHOG_TOKEN,
7506
+ {
7507
+ api_host: config.analyticsHost,
7508
+ ui_host: POSTHOG_UI_HOST,
7509
+ persistence: "localStorage",
7510
+ // The widget is a guest in someone else's page — no automatic collection.
7511
+ // Every one of these must be set explicitly: the project's remote config
7512
+ // turns performance capture, heatmaps and console recording ON, so leaving
7513
+ // an option out is not the same as switching it off.
7514
+ autocapture: false,
7515
+ capture_pageview: false,
7516
+ capture_pageleave: false,
7517
+ rageclick: false,
7518
+ capture_performance: false,
7519
+ capture_heatmaps: false,
7520
+ capture_dead_clicks: false,
7521
+ // Widget console logs carry session ids and wallet addresses.
7522
+ enable_recording_console_log: false,
7523
+ session_recording: { blockSelector: BLOCK_SELECTOR }
7520
7524
  },
7521
- scopes: session.scopes,
7522
- issuedAt: session.issuedAt,
7523
- idToken: session.idToken
7524
- },
7525
- null,
7526
- 2
7527
- );
7525
+ INSTANCE_NAME
7526
+ );
7527
+ for (const queued of pending.splice(0)) {
7528
+ capture(queued.eventName, queued.payload, queued.unload);
7529
+ }
7530
+ }).catch(() => {
7531
+ loadFailed = true;
7532
+ pending = [];
7533
+ });
7528
7534
  }
7529
-
7530
- // src/utils/getAnonymousId.ts
7531
- function getAnonymousId() {
7532
- const storageKey = "fluent_demo_visitor_id";
7533
- const existing = localStorage.getItem(storageKey);
7534
- if (existing) return existing;
7535
- const next = crypto.randomUUID?.() ?? `visitor_${Date.now()}_${Math.random().toString(16).slice(2)}`;
7536
- localStorage.setItem(storageKey, next);
7537
- return next;
7535
+ function sanitise(properties) {
7536
+ if (!properties) return properties;
7537
+ const safe = {};
7538
+ for (const [key, value] of Object.entries(properties)) {
7539
+ const type = typeof value;
7540
+ if (value === null || type === "string" || type === "number" || type === "boolean") {
7541
+ safe[key] = value;
7542
+ }
7543
+ }
7544
+ return safe;
7538
7545
  }
7539
-
7540
- // src/utils/getHighResTwitterAvatar.ts
7541
- function getHighResTwitterAvatar(url) {
7542
- if (!url) return "";
7543
- return url.replace("_normal", "");
7546
+ function capture(eventName, payload, unload) {
7547
+ if (unload) {
7548
+ client?.capture(eventName, payload, UNLOAD_CAPTURE_OPTIONS);
7549
+ return;
7550
+ }
7551
+ client?.capture(eventName, payload);
7544
7552
  }
7545
-
7546
- // src/utils/hasStoredWidgetSession.ts
7547
- function hasStoredWidgetSession(storage = globalThis.window?.localStorage) {
7548
- if (!storage) return false;
7549
- try {
7550
- return Boolean(storage.getItem(FLUENT_WIDGET_SESSION_STORAGE_KEY));
7551
- } catch {
7552
- return false;
7553
+ function send(eventName, payload, unload) {
7554
+ if (client) {
7555
+ capture(eventName, payload, unload);
7556
+ return;
7553
7557
  }
7558
+ if (loadFailed) return;
7559
+ pending.push({ eventName, payload, unload });
7560
+ }
7561
+ function createTracker(config, getContext) {
7562
+ const enabled = analyticsEnabled(config);
7563
+ if (enabled) initFluentAnalytics(config);
7564
+ const base = {
7565
+ app_id: config.appId,
7566
+ network: config.network,
7567
+ auth_mode: config.authMode,
7568
+ source: config.source,
7569
+ campaign: config.campaign,
7570
+ sdk_version: version
7571
+ };
7572
+ const track = (eventName, properties, options) => {
7573
+ if (!enabled) return;
7574
+ const payload = { ...sanitise(properties), ...base, ...getContext?.() };
7575
+ send(eventName, payload, Boolean(options?.unload));
7576
+ };
7577
+ track.live = enabled;
7578
+ return track;
7579
+ }
7580
+ function trackWidgetLoadedOnce(track, properties) {
7581
+ if (widgetLoadedTracked) return;
7582
+ track("widget_loaded", properties);
7583
+ if (track.live) widgetLoadedTracked = true;
7554
7584
  }
7555
7585
  var REOWN_PROJECT_ID = FLUENT_CONNECT_REOWN_PROJECT_ID;
7556
7586
  var queryClient = new QueryClient();
@@ -9612,12 +9642,16 @@ function useIsMobile() {
9612
9642
  }, []);
9613
9643
  return !!isMobile;
9614
9644
  }
9615
- function BatchOperationReviewModal({
9616
- operation,
9645
+ function ReviewDialog({
9646
+ eyebrow,
9647
+ title,
9648
+ ariaLabel,
9649
+ address,
9650
+ footnote,
9617
9651
  onConfirm,
9618
- onCancel
9652
+ onCancel,
9653
+ children
9619
9654
  }) {
9620
- if (!operation) return null;
9621
9655
  return /* @__PURE__ */ jsx(
9622
9656
  "div",
9623
9657
  {
@@ -9632,48 +9666,21 @@ function BatchOperationReviewModal({
9632
9666
  className: "w-full max-w-[520px] rounded-[18px] border border-[#49eded]/30 bg-[#030213] p-[18px] text-white shadow-2xl",
9633
9667
  role: "dialog",
9634
9668
  "aria-modal": "true",
9635
- "aria-label": "Confirm Fluent transaction",
9669
+ "aria-label": ariaLabel,
9636
9670
  children: [
9637
9671
  /* @__PURE__ */ jsxs("div", { className: "mb-3.5 flex items-start justify-between gap-3", children: [
9638
9672
  /* @__PURE__ */ jsxs("div", { children: [
9639
- /* @__PURE__ */ jsx("span", { className: "text-xs font-black uppercase text-[#49eded]", children: "Fluent transaction review" }),
9640
- /* @__PURE__ */ jsx("h2", { className: "mt-1 text-2xl leading-[30px] font-medium", children: operation.reviewTitle ?? "Confirm transaction" })
9673
+ /* @__PURE__ */ jsx("span", { className: "text-xs font-black uppercase text-[#49eded]", children: eyebrow }),
9674
+ /* @__PURE__ */ jsx("h2", { className: "mt-1 text-2xl leading-[30px] font-medium", children: title })
9641
9675
  ] }),
9642
- /* @__PURE__ */ jsx(
9643
- Button,
9644
- {
9645
- type: "button",
9646
- variant: "secondary",
9647
- size: "icon",
9648
- "aria-label": "Close",
9649
- onClick: onCancel,
9650
- children: "x"
9651
- }
9652
- )
9676
+ /* @__PURE__ */ jsx(Button, { type: "button", variant: "secondary", size: "icon", "aria-label": "Close", onClick: onCancel, children: "x" })
9653
9677
  ] }),
9654
9678
  /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-3 rounded-xl border border-[#49eded]/20 bg-[#49eded]/10 p-3", children: [
9655
9679
  /* @__PURE__ */ jsx("span", { className: "text-xs text-white/65", children: "Signing account" }),
9656
- /* @__PURE__ */ jsx("strong", { className: "text-sm", children: operation.account?.address ? formatAddress(operation.account.address) : "Fluent account" })
9680
+ /* @__PURE__ */ jsx("strong", { className: "text-sm", children: address ? formatAddress(address) : "Fluent account" })
9657
9681
  ] }),
9658
- /* @__PURE__ */ jsx("ul", { className: "my-3 flex list-none flex-col gap-2 p-0", "aria-label": "Transaction calls", children: operation.encodedCalls.map((call, index) => /* @__PURE__ */ jsxs(
9659
- "li",
9660
- {
9661
- className: "flex flex-col gap-1 rounded-xl border border-[#49eded]/20 bg-[#49eded]/10 p-3",
9662
- children: [
9663
- /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-3", children: [
9664
- /* @__PURE__ */ jsx("strong", { className: "text-sm", children: call.label ?? operation.calls[index]?.method ?? operation.calls[index]?.functionName ?? "Contract call" }),
9665
- /* @__PURE__ */ jsx("span", { className: "text-xs text-white/65", children: formatAddress(call.to) })
9666
- ] }),
9667
- call.value > 0n ? /* @__PURE__ */ jsxs("small", { className: "text-xs text-white/65", children: [
9668
- "Value ",
9669
- call.value.toString(),
9670
- " wei"
9671
- ] }) : null
9672
- ]
9673
- },
9674
- call.id ?? `${call.to}-${index}`
9675
- )) }),
9676
- /* @__PURE__ */ jsx("p", { className: "text-xs leading-[18px] text-white/65", children: "Confirming allows the Fluent embedded signer to sign this ZeroDev UserOperation." }),
9682
+ children,
9683
+ /* @__PURE__ */ jsx("p", { className: "text-xs leading-[18px] text-white/65", children: footnote }),
9677
9684
  /* @__PURE__ */ jsxs("div", { className: "mt-3 grid grid-cols-[minmax(0,0.8fr)_minmax(0,1.2fr)] gap-2.5", children: [
9678
9685
  /* @__PURE__ */ jsx(Button, { type: "button", variant: "secondary", onClick: onCancel, children: "Cancel" }),
9679
9686
  /* @__PURE__ */ jsx(Button, { type: "button", onClick: onConfirm, children: "Confirm and sign" })
@@ -9684,6 +9691,85 @@ function BatchOperationReviewModal({
9684
9691
  }
9685
9692
  );
9686
9693
  }
9694
+ function BatchOperationReviewModal({
9695
+ operation,
9696
+ onConfirm,
9697
+ onCancel
9698
+ }) {
9699
+ if (!operation) return null;
9700
+ return /* @__PURE__ */ jsx(
9701
+ ReviewDialog,
9702
+ {
9703
+ eyebrow: "Fluent transaction review",
9704
+ title: operation.reviewTitle ?? "Confirm transaction",
9705
+ ariaLabel: "Confirm Fluent transaction",
9706
+ address: operation.account?.address,
9707
+ footnote: "Confirming allows the Fluent embedded signer to sign this ZeroDev UserOperation.",
9708
+ onConfirm,
9709
+ onCancel,
9710
+ children: /* @__PURE__ */ jsx("ul", { className: "my-3 flex list-none flex-col gap-2 p-0", "aria-label": "Transaction calls", children: operation.encodedCalls.map((call, index) => /* @__PURE__ */ jsxs(
9711
+ "li",
9712
+ {
9713
+ className: "flex flex-col gap-1 rounded-xl border border-[#49eded]/20 bg-[#49eded]/10 p-3",
9714
+ children: [
9715
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-3", children: [
9716
+ /* @__PURE__ */ jsx("strong", { className: "text-sm", children: call.label ?? operation.calls[index]?.method ?? operation.calls[index]?.functionName ?? "Contract call" }),
9717
+ /* @__PURE__ */ jsx("span", { className: "text-xs text-white/65", children: formatAddress(call.to) })
9718
+ ] }),
9719
+ call.value > 0n ? /* @__PURE__ */ jsxs("small", { className: "text-xs text-white/65", children: [
9720
+ "Value ",
9721
+ call.value.toString(),
9722
+ " wei"
9723
+ ] }) : null
9724
+ ]
9725
+ },
9726
+ call.id ?? `${call.to}-${index}`
9727
+ )) })
9728
+ }
9729
+ );
9730
+ }
9731
+ function formatMessage(message) {
9732
+ if (typeof message === "string") return message;
9733
+ return typeof message.raw === "string" ? message.raw : bytesToHex(message.raw);
9734
+ }
9735
+ var ROW = "rounded-xl border border-[#49eded]/20 bg-[#49eded]/10 p-3";
9736
+ var CODE = "max-h-60 overflow-auto whitespace-pre-wrap break-all text-xs";
9737
+ function SignatureReviewModal({
9738
+ review,
9739
+ onConfirm,
9740
+ onCancel
9741
+ }) {
9742
+ if (!review) return null;
9743
+ return /* @__PURE__ */ jsx(
9744
+ ReviewDialog,
9745
+ {
9746
+ eyebrow: "Fluent signature review",
9747
+ title: review.kind === "message" ? "Sign message" : "Sign typed data",
9748
+ ariaLabel: "Confirm Fluent signature",
9749
+ address: review.address,
9750
+ footnote: review.account.type === "smart" ? "Confirming signs this request with your Fluent ID. Nothing is sent on chain." : "Confirming opens your wallet's own signature prompt. Nothing is sent on chain.",
9751
+ onConfirm,
9752
+ onCancel,
9753
+ children: /* @__PURE__ */ jsxs("div", { className: "my-3 flex flex-col gap-2", children: [
9754
+ /* @__PURE__ */ jsxs("div", { className: `flex items-center justify-between gap-3 ${ROW}`, children: [
9755
+ /* @__PURE__ */ jsx("span", { className: "text-xs text-white/65", children: "Requested by" }),
9756
+ /* @__PURE__ */ jsx("strong", { className: "break-all text-sm", children: review.origin })
9757
+ ] }),
9758
+ review.kind === "message" ? /* @__PURE__ */ jsx("pre", { className: `${ROW} ${CODE}`, "aria-label": "Message", children: formatMessage(review.message) }) : /* @__PURE__ */ jsxs(Fragment, { children: [
9759
+ /* @__PURE__ */ jsxs("div", { className: `flex flex-col gap-1 ${ROW}`, children: [
9760
+ /* @__PURE__ */ jsx("span", { className: "text-xs text-white/65", children: "Domain" }),
9761
+ /* @__PURE__ */ jsx("pre", { className: CODE, children: stringifyWithBigInt(review.typedData.domain ?? {}, 2) })
9762
+ ] }),
9763
+ /* @__PURE__ */ jsxs("div", { className: `flex items-center justify-between gap-3 ${ROW}`, children: [
9764
+ /* @__PURE__ */ jsx("span", { className: "text-xs text-white/65", children: "Primary type" }),
9765
+ /* @__PURE__ */ jsx("strong", { className: "text-sm", children: review.typedData.primaryType })
9766
+ ] }),
9767
+ /* @__PURE__ */ jsx("pre", { className: `${ROW} ${CODE}`, "aria-label": "Message", children: stringifyWithBigInt(review.typedData.message, 2) })
9768
+ ] })
9769
+ ] })
9770
+ }
9771
+ );
9772
+ }
9687
9773
  function deriveWidgetAccount(input) {
9688
9774
  const { smartAccount, wallet, sessionUserId, sessionSmartAccountAddress, directAuth } = input;
9689
9775
  const fluentAccountAddress = smartAccount.smartAccountAddress ?? sessionSmartAccountAddress;
@@ -9784,41 +9870,67 @@ function useGasPaymentSelection(params) {
9784
9870
  const defaultConfirmationMode = silentSigningEnabled ? "session" : "always";
9785
9871
  return { selectedGasPaymentToken, defaultConfirmationMode };
9786
9872
  }
9787
- function useBatchReview(options) {
9788
- const [batchReview, setBatchReview] = useState(null);
9873
+ function useReviewPrompt(options) {
9874
+ const { label, onOpen } = options;
9875
+ const [review, setReview] = useState(null);
9789
9876
  const resolution = useRef(null);
9790
- const onOpen = options?.onOpen;
9791
- const confirmBatchOperation = useCallback(
9792
- (operation) => {
9877
+ const request = useCallback(
9878
+ (next) => {
9793
9879
  onOpen?.();
9794
- resolution.current?.reject(
9795
- new Error("A newer Fluent transaction review replaced this request")
9796
- );
9797
- setBatchReview(operation);
9798
- return new Promise((resolve, reject) => {
9799
- resolution.current = { resolve, reject };
9880
+ resolution.current?.reject(new Error(`A newer Fluent ${label} review replaced this request`));
9881
+ setReview(next);
9882
+ return new Promise((resolve, reject2) => {
9883
+ resolution.current = { resolve, reject: reject2 };
9800
9884
  });
9801
9885
  },
9802
- [onOpen]
9886
+ [label, onOpen]
9803
9887
  );
9804
- const acceptBatchReview = useCallback(() => {
9888
+ const accept = useCallback(() => {
9805
9889
  resolution.current?.resolve();
9806
9890
  resolution.current = null;
9807
- setBatchReview(null);
9891
+ setReview(null);
9808
9892
  }, []);
9809
- const rejectBatchReview = useCallback(() => {
9810
- resolution.current?.reject(new Error("User rejected Fluent transaction review"));
9893
+ const reject = useCallback(() => {
9894
+ resolution.current?.reject(new Error(`User rejected Fluent ${label} review`));
9811
9895
  resolution.current = null;
9812
- setBatchReview(null);
9896
+ setReview(null);
9813
9897
  }, []);
9814
9898
  useEffect(
9815
9899
  () => () => {
9816
- resolution.current?.reject(new Error("Fluent transaction review was closed"));
9900
+ resolution.current?.reject(new Error(`Fluent ${label} review was closed`));
9817
9901
  resolution.current = null;
9818
9902
  },
9819
- []
9903
+ [label]
9820
9904
  );
9821
- return { batchReview, confirmBatchOperation, acceptBatchReview, rejectBatchReview };
9905
+ return { review, request, accept, reject };
9906
+ }
9907
+
9908
+ // src/widget/hooks/useBatchReview.ts
9909
+ function useBatchReview(options) {
9910
+ const { review, request, accept, reject } = useReviewPrompt({
9911
+ label: "transaction",
9912
+ onOpen: options?.onOpen
9913
+ });
9914
+ return {
9915
+ batchReview: review,
9916
+ confirmBatchOperation: request,
9917
+ acceptBatchReview: accept,
9918
+ rejectBatchReview: reject
9919
+ };
9920
+ }
9921
+
9922
+ // src/widget/hooks/useSignatureReview.ts
9923
+ function useSignatureReview(options) {
9924
+ const { review, request, accept, reject } = useReviewPrompt({
9925
+ label: "signature",
9926
+ onOpen: options?.onOpen
9927
+ });
9928
+ return {
9929
+ signatureReview: review,
9930
+ confirmSignature: request,
9931
+ acceptSignatureReview: accept,
9932
+ rejectSignatureReview: reject
9933
+ };
9822
9934
  }
9823
9935
  function useFaucet(params) {
9824
9936
  const {
@@ -9947,6 +10059,81 @@ function useFluentSession(params) {
9947
10059
  return { session, setSession };
9948
10060
  }
9949
10061
 
10062
+ // src/widget/signRequest.ts
10063
+ function externalWalletSigner(wallet) {
10064
+ const walletClient = wallet.walletClient;
10065
+ const account = walletClient?.account ?? wallet.address;
10066
+ if (!walletClient || !account) return null;
10067
+ const address = typeof account === "string" ? account : account.address;
10068
+ return {
10069
+ address,
10070
+ async resolve() {
10071
+ return {
10072
+ signMessage: ({ message }) => walletClient.signMessage({ account, message }),
10073
+ signTypedData: (typedData) => walletClient.signTypedData({ account, ...typedData })
10074
+ };
10075
+ }
10076
+ };
10077
+ }
10078
+ function createFluentSignApi(executor) {
10079
+ const assertDirectMode = () => {
10080
+ if (executor.authMode === "hosted") {
10081
+ throw new FluentAuthError(
10082
+ "hosted_not_supported",
10083
+ 'Signing needs authMode: "direct" \u2014 there is no hosted signer to ask.'
10084
+ );
10085
+ }
10086
+ };
10087
+ const smartAccountSigner = () => ({
10088
+ address: executor.account.address,
10089
+ async resolve() {
10090
+ const kernel = await executor.ensureReady({ confirmation: "always" });
10091
+ if (kernel.signerSource !== "privy") {
10092
+ throw new FluentAuthError(
10093
+ "root_signer_required",
10094
+ "Only the Fluent ID root signer can sign for the smart account."
10095
+ );
10096
+ }
10097
+ return kernel.account;
10098
+ }
10099
+ });
10100
+ const pickSigner = () => {
10101
+ assertDirectMode();
10102
+ if (executor.account.type === "smart" && executor.account.address) return smartAccountSigner();
10103
+ if (executor.account.type === "eoa") {
10104
+ const signer = executor.wallet ? externalWalletSigner(executor.wallet) : null;
10105
+ if (!signer) throw new FluentAuthError("not_connected", "External wallet has no signer.");
10106
+ return signer;
10107
+ }
10108
+ throw new FluentAuthError("not_connected", "Connect a Fluent ID or an External wallet first.");
10109
+ };
10110
+ return {
10111
+ async signMessage({ message }) {
10112
+ const signer = pickSigner();
10113
+ await executor.confirm({
10114
+ kind: "message",
10115
+ origin: executor.origin,
10116
+ account: executor.account,
10117
+ address: signer.address,
10118
+ message
10119
+ });
10120
+ return (await signer.resolve()).signMessage({ message });
10121
+ },
10122
+ async signTypedData(typedData) {
10123
+ const signer = pickSigner();
10124
+ const request = typedData;
10125
+ await executor.confirm({
10126
+ kind: "typedData",
10127
+ origin: executor.origin,
10128
+ account: executor.account,
10129
+ address: signer.address,
10130
+ typedData: request
10131
+ });
10132
+ return (await signer.resolve()).signTypedData(request);
10133
+ }
10134
+ };
10135
+ }
10136
+
9950
10137
  // src/widget/sendCallsViaExternalWallet.ts
9951
10138
  async function sendCallsViaExternalWallet(calls, wallet, chain, publicClient) {
9952
10139
  const walletClient = wallet.walletClient;
@@ -9985,6 +10172,8 @@ function useWidgetExecution(params) {
9985
10172
  defaultConfirmationMode,
9986
10173
  selectedGasPaymentToken,
9987
10174
  confirmBatchOperation,
10175
+ authMode,
10176
+ confirmSignature,
9988
10177
  refreshBalances,
9989
10178
  track
9990
10179
  } = params;
@@ -10044,15 +10233,43 @@ function useWidgetExecution(params) {
10044
10233
  }),
10045
10234
  [smartAccount.kernel, smartAccount.smartAccountReady]
10046
10235
  );
10236
+ const signApi = useMemo(
10237
+ () => createFluentSignApi({
10238
+ authMode,
10239
+ account: widgetAccount,
10240
+ origin: window.location.origin,
10241
+ confirm: confirmSignature,
10242
+ ensureReady: async (options) => {
10243
+ const kernel = await smartAccount.ensureExecutionReady(options);
10244
+ return {
10245
+ signerSource: kernel.signerSource,
10246
+ account: {
10247
+ signMessage: (params2) => withFluentSignaturePrompt(() => kernel.account.signMessage(params2)),
10248
+ signTypedData: (typedData) => withFluentSignaturePrompt(() => kernel.account.signTypedData(typedData))
10249
+ }
10250
+ };
10251
+ },
10252
+ wallet: wallet?.connected ? wallet : void 0
10253
+ }),
10254
+ [authMode, widgetAccount, confirmSignature, smartAccount.ensureExecutionReady, wallet]
10255
+ );
10047
10256
  return useMemo(
10048
10257
  () => ({
10049
10258
  account: widgetAccount,
10050
10259
  confirmationMode: defaultConfirmationMode,
10051
10260
  gasPayment: selectedGasPaymentToken,
10052
10261
  createBatchOp,
10053
- ...permissionApi
10262
+ ...permissionApi,
10263
+ ...signApi
10054
10264
  }),
10055
- [widgetAccount, defaultConfirmationMode, selectedGasPaymentToken, createBatchOp, permissionApi]
10265
+ [
10266
+ widgetAccount,
10267
+ defaultConfirmationMode,
10268
+ selectedGasPaymentToken,
10269
+ createBatchOp,
10270
+ permissionApi,
10271
+ signApi
10272
+ ]
10056
10273
  );
10057
10274
  }
10058
10275
  function useZeroDevInitializer(params) {
@@ -10147,7 +10364,7 @@ function useHostedConnect(params) {
10147
10364
  const {
10148
10365
  fluentConnect,
10149
10366
  authorizeUrl,
10150
- partnerId,
10367
+ appId,
10151
10368
  appName,
10152
10369
  authMode,
10153
10370
  setSession,
@@ -10169,10 +10386,10 @@ function useHostedConnect(params) {
10169
10386
  } catch {
10170
10387
  }
10171
10388
  const url = fluentConnect.buildAuthorizeUrl(state).toString();
10172
- debugLog("[fluent widget] open connect", { state, authorizeUrl: url, partnerId, appName, authMode });
10389
+ debugLog("[fluent widget] open connect", { state, authorizeUrl: url, appId, appName, authMode });
10173
10390
  setHostedAuthorizeUrl(url);
10174
10391
  setConnectOpen(true);
10175
- }, [appName, authMode, partnerId, fluentConnect, setConnectOpen]);
10392
+ }, [appName, authMode, appId, fluentConnect, setConnectOpen]);
10176
10393
  const acceptHostedResult = useCallback(
10177
10394
  (data) => {
10178
10395
  if (!data || typeof data !== "object") return;
@@ -10323,12 +10540,12 @@ function useAccountMenu(params) {
10323
10540
  return { openAccountMenu, handleAccountMenuAction };
10324
10541
  }
10325
10542
  function authTokenCacheKey(params) {
10326
- return `${params.publicApiUrl}|${params.partnerId}|${params.subject}`;
10543
+ return `${params.publicApiUrl}|${params.appId}|${params.subject}`;
10327
10544
  }
10328
10545
  function useAuthToken(params) {
10329
10546
  const {
10330
10547
  publicApiUrl,
10331
- partnerId,
10548
+ appId,
10332
10549
  authMode,
10333
10550
  renewalOffsetSeconds,
10334
10551
  accountType,
@@ -10351,7 +10568,7 @@ function useAuthToken(params) {
10351
10568
  if (!subject) {
10352
10569
  throw new FluentAuthError("not_connected", "Connect a Fluent ID or an external wallet first.");
10353
10570
  }
10354
- const key = authTokenCacheKey({ publicApiUrl, partnerId, subject });
10571
+ const key = authTokenCacheKey({ publicApiUrl, appId, subject });
10355
10572
  const cached = cache.current;
10356
10573
  if (cached?.key === key && cached.expiresAt - renewalOffsetSeconds * 1e3 > Date.now()) {
10357
10574
  return cached.token;
@@ -10367,14 +10584,14 @@ function useAuthToken(params) {
10367
10584
  "Privy session is not ready; sign in again."
10368
10585
  );
10369
10586
  }
10370
- token = await exchangePrivyAuthToken({ publicApiUrl, partnerId, accessToken, identityToken });
10587
+ token = await exchangePrivyAuthToken({ publicApiUrl, appId, accessToken, identityToken });
10371
10588
  } else {
10372
10589
  if (!walletClient) {
10373
10590
  throw new FluentAuthError("not_connected", "External wallet has no signer.");
10374
10591
  }
10375
10592
  token = await exchangeWalletAuthToken({
10376
10593
  publicApiUrl,
10377
- partnerId,
10594
+ appId,
10378
10595
  walletClient,
10379
10596
  address: walletAddress,
10380
10597
  origin: window.location.origin
@@ -10394,7 +10611,7 @@ function useAuthToken(params) {
10394
10611
  accountType,
10395
10612
  authMode,
10396
10613
  renewalOffsetSeconds,
10397
- partnerId,
10614
+ appId,
10398
10615
  getAccessToken,
10399
10616
  identityToken,
10400
10617
  privyUserId,
@@ -10793,7 +11010,7 @@ function FluentWidgetContent({
10793
11010
  const resolvedConfig = useMemo(() => resolveFluentWidgetConfig(config), [config]);
10794
11011
  const smartAccount = useFluentZeroDevAccount({
10795
11012
  login: requestPrivyLogin,
10796
- partnerId: resolvedConfig.partnerId,
11013
+ appId: resolvedConfig.appId,
10797
11014
  sponsorshipUrl: resolvedConfig.sponsorshipUrl
10798
11015
  });
10799
11016
  const { authenticated, getAccessToken, login, logout, ready: privyReady, user } = usePrivy();
@@ -10876,7 +11093,7 @@ function FluentWidgetContent({
10876
11093
  const { hostedAuthorizeUrl, beginHostedConnect } = useHostedConnect({
10877
11094
  fluentConnect,
10878
11095
  authorizeUrl: resolvedConfig.authorizeUrl,
10879
- partnerId: resolvedConfig.partnerId,
11096
+ appId: resolvedConfig.appId,
10880
11097
  appName: resolvedConfig.appName,
10881
11098
  authMode: resolvedConfig.authMode,
10882
11099
  setSession,
@@ -10996,7 +11213,7 @@ function FluentWidgetContent({
10996
11213
  const app = fluentConnect.status().app;
10997
11214
  const nextSession = createLocalFluentSession({
10998
11215
  app,
10999
- partnerId: resolvedConfig.partnerId,
11216
+ appId: resolvedConfig.appId,
11000
11217
  scopes: resolvedConfig.scopes,
11001
11218
  userId: user.id,
11002
11219
  email: typeof user.email?.address === "string" ? user.email.address : void 0,
@@ -11083,6 +11300,7 @@ function FluentWidgetContent({
11083
11300
  }, [directAuth, handleDisconnect, openConnectFlow, startDirectFluentLogin]);
11084
11301
  const closeAccountMenu = useCallback(() => setAccountOpen(false), [setAccountOpen]);
11085
11302
  const { batchReview, confirmBatchOperation, acceptBatchReview, rejectBatchReview } = useBatchReview({ onOpen: closeAccountMenu });
11303
+ const { signatureReview, confirmSignature, acceptSignatureReview, rejectSignatureReview } = useSignatureReview({ onOpen: closeAccountMenu });
11086
11304
  const widgetApi = useWidgetExecution({
11087
11305
  chain,
11088
11306
  fluentAccountReady,
@@ -11092,12 +11310,14 @@ function FluentWidgetContent({
11092
11310
  defaultConfirmationMode,
11093
11311
  selectedGasPaymentToken,
11094
11312
  confirmBatchOperation,
11313
+ authMode: resolvedConfig.authMode,
11314
+ confirmSignature,
11095
11315
  refreshBalances,
11096
11316
  track
11097
11317
  });
11098
11318
  const getAuthToken = useAuthToken({
11099
11319
  publicApiUrl: resolvedConfig.publicApiUrl,
11100
- partnerId: resolvedConfig.partnerId,
11320
+ appId: resolvedConfig.appId,
11101
11321
  authMode: resolvedConfig.authMode,
11102
11322
  renewalOffsetSeconds: resolvedConfig.authTokenRenewalOffsetSeconds,
11103
11323
  accountType: widgetAccount.type,
@@ -11237,6 +11457,14 @@ function FluentWidgetContent({
11237
11457
  onConfirm: acceptBatchReview,
11238
11458
  onCancel: rejectBatchReview
11239
11459
  }
11460
+ ),
11461
+ /* @__PURE__ */ jsx(
11462
+ SignatureReviewModal,
11463
+ {
11464
+ review: signatureReview,
11465
+ onConfirm: acceptSignatureReview,
11466
+ onCancel: rejectSignatureReview
11467
+ }
11240
11468
  )
11241
11469
  ] })
11242
11470
  ] }) });
@@ -11431,6 +11659,6 @@ function FluentWidget(props) {
11431
11659
  ) });
11432
11660
  }
11433
11661
 
11434
- 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_SESSION_STORAGE_KEY, FLUENT_WIDGET_USER_TOKENS_STORAGE_KEY, FLUENT_ZERODEV_ERC20_PAYMASTER_QUERY, FLUENT_ZERODEV_PAYMASTER_DEMO_RECIPIENT, FluentAccountDrawer, FluentAuthError, FluentPortalContainerProvider, FluentWidget, FluentWidgetConnectButton, FluentWidgetNetworkProvider, Icon, Label, Separator, Switch, WIDGET_STYLE_SCOPE, WalletMenuActionCard, buttonVariants, clearPrivyRecentLoginMethod, createFluentBatchOp, createFluentClient, createFluentFamiliesClient, createFluentPermissionApi, createFluentPermissionClient, createFluentPermissionPolicyBuilders, createFluentPermissionSession, createFluentSponsorshipRpcUrl, createFluentUserTokenStore, createFluentZeroDevErc20Paymaster, createFluentZeroDevErc20PaymasterApprovalCall, createFluentZeroDevErc20PaymasterClient, createFluentZeroDevErc20PaymasterRpcUrl, createFluentZeroDevPermissionSession, createFluentZeroDevRpcUrl, createFluentZeroDevSponsoredPaymaster, findFluentSymbolCollisions, fluent2 as fluent, apps as fluentApps, fluentBridgeAbi, fluent as fluentChain, fluentChains, fluentDefinitionToViemChain, integrations as fluentIntegrations, l1Chains as fluentL1Chains, fluentMainnet, fluentMainnetTokenDefaults, fluentTestnet, fluentTestnetTokenDefaults, fluentTokenIdentity, 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, readFluentTokenBalances, readFluentTokenMetadata, registryVersion, resolveBridgeAddresses, resolveFluentWidgetNetworkFromEnv, resolveFluentZeroDevErc20PaymasterToken, resolveL1Definition, selectFluentGasPaymentToken, sendFluentZeroDevErc20PaymasterDemo, sortFluentGasTokens, useFluentUserTokens, useFluentWidget, useFluentWidgetNetwork, useFluentZeroDevAccount, useWidget };
11662
+ 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_SESSION_STORAGE_KEY, FLUENT_WIDGET_USER_TOKENS_STORAGE_KEY, FLUENT_ZERODEV_ERC20_PAYMASTER_QUERY, FLUENT_ZERODEV_PAYMASTER_DEMO_RECIPIENT, FluentAccountDrawer, FluentAuthError, FluentPortalContainerProvider, FluentWidget, FluentWidgetConnectButton, FluentWidgetNetworkProvider, Icon, Label, Separator, Switch, WIDGET_STYLE_SCOPE, WalletMenuActionCard, buttonVariants, clearPrivyRecentLoginMethod, createFluentBatchOp, createFluentClient, createFluentFamiliesClient, createFluentPermissionApi, createFluentPermissionClient, createFluentPermissionPolicyBuilders, createFluentPermissionSession, createFluentSponsorshipRpcUrl, createFluentUserTokenStore, createFluentZeroDevErc20Paymaster, createFluentZeroDevErc20PaymasterApprovalCall, createFluentZeroDevErc20PaymasterClient, createFluentZeroDevErc20PaymasterRpcUrl, createFluentZeroDevPermissionSession, createFluentZeroDevRpcUrl, createFluentZeroDevSponsoredPaymaster, findFluentSymbolCollisions, fluent2 as fluent, apps as fluentApps, fluentBridgeAbi, fluent as fluentChain, fluentChains, fluentDefinitionToViemChain, integrations as fluentIntegrations, l1Chains as fluentL1Chains, fluentMainnet, fluentMainnetTokenDefaults, fluentTestnet, fluentTestnetTokenDefaults, fluentTokenIdentity, 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, readFluentTokenBalances, readFluentTokenMetadata, registryVersion, resolveBridgeAddresses, resolveFluentWidgetNetworkFromEnv, resolveFluentZeroDevErc20PaymasterToken, resolveL1Definition, selectFluentGasPaymentToken, sendFluentZeroDevErc20PaymasterDemo, sortFluentGasTokens, useFluentUserTokens, useFluentWidget, useFluentWidgetNetwork, useFluentZeroDevAccount, useWidget, withFluentSignaturePrompt };
11435
11663
  //# sourceMappingURL=index.js.map
11436
11664
  //# sourceMappingURL=index.js.map