@fluent.xyz/connect 0.3.0 → 0.3.2

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
- import { toEventSelector, parseAbiItem, defineChain, http, createPublicClient, formatUnits, isAddress, getAddress, encodeFunctionData, parseUnits, zeroAddress, numberToHex, BaseError, HttpRequestError, fallback, isHex, stringToHex, bytesToHex } from 'viem';
1
+ import { toEventSelector, parseAbiItem, defineChain, http, createPublicClient, formatUnits, isAddress, getAddress, encodeFunctionData, parseUnits, zeroAddress, numberToHex, hexToBigInt, isHex, toHex, BaseError, HttpRequestError, fallback, 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';
@@ -6135,1430 +6135,1701 @@ function createFluentBundlerTransport(url) {
6135
6135
  });
6136
6136
  }
6137
6137
 
6138
- // src/widget/zerodevSession.ts
6139
- function useFluentZeroDevAccount(hookOptions = {}) {
6140
- const { chain, network } = useFluentWidgetNetwork();
6141
- const { authenticated, getAccessToken, login: privyLogin, ready } = usePrivy();
6142
- const login = hookOptions.login ?? privyLogin;
6143
- const { signMessage: promptSignMessage } = useSignMessage();
6144
- const { signTypedData: promptSignTypedData } = useSignTypedData();
6145
- const { wallets } = useWallets();
6146
- const [kernels, setKernels] = useState({});
6147
- const [error, setError] = useState(null);
6148
- const [smartAccountReady, setSmartAccountReady] = useState(false);
6149
- const initPromise = useRef({});
6150
- const sponsorshipUnavailable = useRef(false);
6151
- const embeddedWallet = wallets.find((wallet) => wallet.walletClientType === "privy");
6152
- const hostedSigner = useMemo(
6153
- () => hookOptions.allowHostedSigner !== false && hookOptions.authorizeUrl && hookOptions.sessionSignerAddress ? createFluentHostedSigner({
6154
- address: hookOptions.sessionSignerAddress,
6155
- authorizeUrl: hookOptions.authorizeUrl
6156
- }) : null,
6157
- [
6158
- hookOptions.allowHostedSigner,
6159
- hookOptions.authorizeUrl,
6160
- hookOptions.sessionSignerAddress
6161
- ]
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"
6211
+ }
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
6225
+ }
6162
6226
  );
6163
- const activeKernel = kernels.prompt ?? kernels.silent ?? null;
6164
- useEffect(() => {
6165
- setKernels({});
6166
- setSmartAccountReady(false);
6167
- setError(null);
6168
- initPromise.current = {};
6169
- }, [chain.id]);
6170
- useEffect(() => () => hostedSigner?.close(), [hostedSigner]);
6171
- const initialize2 = useCallback(async (options = {}) => {
6172
- const signerMode = options.signerMode ?? "prompt";
6173
- const cachedKernel = kernels[signerMode];
6174
- debugLog("[fluent zerodev] initialize requested", {
6175
- signerMode,
6176
- ready,
6177
- authenticated,
6178
- walletCount: wallets.length,
6179
- embeddedWalletCount: wallets.filter((wallet) => wallet.walletClientType === "privy").length,
6180
- embeddedWallet: embeddedWallet?.address,
6181
- hasKernel: Boolean(cachedKernel),
6182
- cachedSignerModes: Object.keys(kernels),
6183
- initInFlight: Boolean(initPromise.current[signerMode]),
6184
- throwOnError: Boolean(options.throwOnError),
6185
- hasProjectId: Boolean(FLUENT_CONNECT_ZERODEV_PROJECT_ID)
6186
- });
6187
- if (cachedKernel) {
6188
- debugLog("[fluent zerodev] using cached kernel", {
6189
- signerMode,
6190
- smartAccountAddress: cachedKernel.smartAccountAddress
6191
- });
6192
- return cachedKernel;
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
6193
6239
  }
6194
- const canUseLocalSigner = ready && authenticated && Boolean(embeddedWallet);
6195
- const canUseHostedSigner = Boolean(hostedSigner);
6196
- const canUseAuthorizationSession = signerMode === "silent" && Boolean(hookOptions.authorizationSession?.serializedPermissionAccount) && (hookOptions.authorizationSession?.expiresAt ?? 0) > Math.floor(Date.now() / 1e3);
6197
- if (!canUseLocalSigner && !canUseHostedSigner && !canUseAuthorizationSession) {
6198
- const nextError = new Error(getZeroDevReadinessMessage({
6199
- ready,
6200
- authenticated,
6201
- embeddedWalletCount: wallets.filter((wallet) => wallet.walletClientType === "privy").length,
6202
- walletCount: wallets.length,
6203
- hostedSignerAvailable: canUseHostedSigner
6204
- }));
6205
- debugWarn("[fluent zerodev] initialize blocked", {
6206
- message: nextError.message,
6207
- ready,
6208
- authenticated,
6209
- embeddedWalletCount: wallets.filter((wallet) => wallet.walletClientType === "privy").length,
6210
- walletCount: wallets.length
6211
- });
6212
- setError(nextError);
6213
- if (options.throwOnError) throw nextError;
6214
- return null;
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
6215
6252
  }
6216
- if (initPromise.current[signerMode]) {
6217
- debugLog("[fluent zerodev] joining in-flight initialization");
6218
- return initPromise.current[signerMode];
6253
+ );
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
6219
6280
  }
6220
- setSmartAccountReady(Boolean(activeKernel));
6221
- setError(null);
6222
- initPromise.current[signerMode] = (async () => {
6223
- debugLog("[fluent zerodev] initializing", {
6224
- signerMode,
6225
- embeddedWallet: embeddedWallet?.address,
6226
- walletClientType: embeddedWallet?.walletClientType,
6227
- hostedSigner: hostedSigner?.address
6228
- });
6229
- const nextKernel = canUseAuthorizationSession ? await createFluentZeroDevAuthorizedSessionKernel(
6230
- hookOptions.authorizationSession,
6231
- chain
6232
- ) : await createFluentZeroDevKernel({
6233
- wallet: canUseLocalSigner ? embeddedWallet : void 0,
6234
- hostedSigner: canUseLocalSigner ? void 0 : hostedSigner ?? void 0,
6235
- signerMode,
6236
- promptedSigners: {
6237
- signMessage: promptSignMessage,
6238
- signTypedData: promptSignTypedData
6239
- },
6240
- chain
6241
- });
6242
- if (hookOptions.sessionSmartAccountAddress && nextKernel.smartAccountAddress.toLowerCase() !== hookOptions.sessionSmartAccountAddress.toLowerCase()) {
6243
- throw new Error("Fluent Connect signer does not control the connected smart account");
6244
- }
6245
- debugLog("[fluent zerodev] ready", {
6246
- signerMode,
6247
- signerAddress: embeddedWallet?.address ?? hostedSigner?.address,
6248
- smartAccountAddress: nextKernel.smartAccountAddress
6249
- });
6250
- setKernels((current) => ({ ...current, [signerMode]: nextKernel }));
6251
- setSmartAccountReady(true);
6252
- return nextKernel;
6253
- })();
6254
- try {
6255
- return await initPromise.current[signerMode];
6256
- } catch (err) {
6257
- const nextError = err instanceof Error ? err : new Error("Failed to create ZeroDev account");
6258
- debugError("[fluent zerodev] initialization failed", nextError);
6259
- setKernels((current) => {
6260
- const { [signerMode]: _failed, ...rest } = current;
6261
- setSmartAccountReady(Object.keys(rest).length > 0);
6262
- return rest;
6263
- });
6264
- setError(nextError);
6265
- if (options.throwOnError) throw nextError;
6266
- return null;
6267
- } finally {
6268
- delete initPromise.current[signerMode];
6281
+ );
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
6269
6293
  }
6270
- }, [
6271
- activeKernel,
6272
- authenticated,
6273
- embeddedWallet,
6274
- hostedSigner,
6275
- kernels,
6276
- hookOptions.sessionSmartAccountAddress,
6277
- hookOptions.authorizationSession,
6278
- promptSignMessage,
6279
- promptSignTypedData,
6280
- ready
6281
- ]);
6282
- useEffect(() => {
6283
- if (!ready) return;
6284
- if (!authenticated) {
6285
- setKernels({});
6286
- setSmartAccountReady(false);
6287
- setError(null);
6288
- initPromise.current = {};
6294
+ );
6295
+ }
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
6289
6303
  }
6290
- }, [authenticated, ready]);
6291
- const sendTransaction = useCallback(
6292
- async (request) => {
6293
- const cachedKernel = kernels.prompt;
6294
- if (cachedKernel?.signerSource === "hosted" || !cachedKernel && hostedSigner && !(ready && authenticated && embeddedWallet)) {
6295
- hostedSigner?.prepare("always");
6296
- }
6297
- const executionKernel = cachedKernel ?? await initialize2({ signerMode: "prompt" });
6298
- if (!executionKernel) throw new Error(error?.message ?? "ZeroDev smart account is not ready");
6299
- debugLog("[fluent zerodev] sendTransaction", {
6300
- signerMode: executionKernel.signerMode,
6301
- smartAccountAddress: executionKernel.smartAccountAddress,
6302
- to: request.to,
6303
- hasData: Boolean(request.data && request.data !== "0x"),
6304
- value: (request.value ?? 0n).toString()
6305
- });
6306
- try {
6307
- const hash = await executionKernel.client.sendTransaction({
6308
- account: executionKernel.account,
6309
- chain: executionKernel.chain,
6310
- to: request.to,
6311
- data: request.data ?? "0x",
6312
- value: request.value ?? 0n
6313
- });
6314
- debugLog("[fluent zerodev] sendTransaction submitted", { hash });
6315
- return hash;
6316
- } catch (err) {
6317
- debugError("[fluent zerodev] sendTransaction failed", err);
6318
- throw err;
6319
- }
6320
- },
6321
- [authenticated, embeddedWallet, error, hostedSigner, initialize2, kernels.prompt, ready]
6322
6304
  );
6323
- const createSponsoredClient = useCallback(async (kernel) => {
6324
- if (!hookOptions.sponsorshipUrl || !hookOptions.appId) return null;
6325
- if (sponsorshipUnavailable.current) return null;
6326
- const accessToken = await getAccessToken();
6327
- if (!accessToken) return null;
6328
- return createKernelAccountClient({
6329
- account: kernel.account,
6330
- chain: kernel.chain,
6331
- bundlerTransport: createFluentBundlerTransport(kernel.zeroDevRpcUrl),
6332
- client: kernel.publicClient,
6333
- paymaster: createFluentZeroDevSponsoredPaymaster({
6334
- chain: kernel.chain,
6335
- accessToken,
6336
- rpcUrl: createFluentSponsorshipRpcUrl({
6337
- sponsorshipUrl: hookOptions.sponsorshipUrl,
6338
- appId: hookOptions.appId
6339
- })
6340
- })
6341
- });
6342
- }, [getAccessToken, hookOptions.appId, hookOptions.sponsorshipUrl]);
6343
- const sendCalls = useCallback(
6344
- async (calls, options) => {
6345
- const signerMode = confirmationToSignerMode(options?.confirmation ?? "always");
6346
- const cachedKernel = kernels[signerMode];
6347
- const hasAuthorizationSession = signerMode === "silent" && Boolean(hookOptions.authorizationSession?.serializedPermissionAccount) && (hookOptions.authorizationSession?.expiresAt ?? 0) > Math.floor(Date.now() / 1e3);
6348
- if (cachedKernel?.signerSource === "hosted" || !cachedKernel && !hasAuthorizationSession && hostedSigner && !(ready && authenticated && embeddedWallet)) {
6349
- hostedSigner?.prepare(options?.confirmation ?? "always");
6350
- }
6351
- const executionKernel = cachedKernel ?? await initialize2({ signerMode, throwOnError: true });
6352
- if (!executionKernel) throw new Error(error?.message ?? "ZeroDev smart account is not ready");
6353
- const gasToken = options?.gasPayment?.symbol ? getFluentGasTokenAddress(options.gasPayment.symbol, network) : void 0;
6354
- const preparedCalls = [...calls];
6355
- if (gasToken && options?.gasPayment?.includeApproval) {
6356
- preparedCalls.unshift(await createFluentZeroDevErc20PaymasterApprovalCall({
6357
- chain: executionKernel.chain,
6358
- gasToken,
6359
- approveAmount: options.gasPayment.approveAmount
6360
- }));
6361
- }
6362
- debugLog("[fluent zerodev] sendCalls", {
6363
- signerMode,
6364
- smartAccountAddress: executionKernel.smartAccountAddress,
6365
- gasToken,
6366
- gasTokenSymbol: options?.gasPayment?.symbol,
6367
- sponsorship: options?.gasPayment?.sponsorship ?? "auto",
6368
- approvalIncluded: Boolean(gasToken && options?.gasPayment?.includeApproval),
6369
- calls: preparedCalls.map((call) => ({
6370
- to: call.to,
6371
- hasData: Boolean(call.data && call.data !== "0x"),
6372
- value: (call.value ?? 0n).toString()
6373
- }))
6374
- });
6375
- setPromptSigningContext({
6376
- gasTokenSymbol: options?.gasPayment?.symbol
6377
- });
6378
- try {
6379
- const callArgs = {
6380
- account: executionKernel.account,
6381
- calls: preparedCalls.map((call) => ({
6382
- to: call.to,
6383
- data: call.data ?? "0x",
6384
- value: call.value ?? 0n
6385
- }))
6386
- };
6387
- const sponsorshipRefused = !gasToken && options?.gasPayment?.sponsorship === "never";
6388
- const sponsoredClient = gasToken || sponsorshipRefused ? null : await createSponsoredClient(executionKernel);
6389
- const executionClient = gasToken ? createFluentZeroDevErc20ExecutionClient(executionKernel, gasToken) : sponsoredClient ?? executionKernel.client;
6390
- let sponsorshipReason;
6391
- if (sponsorshipRefused) {
6392
- sponsorshipReason = "not_requested";
6393
- } else if (!gasToken && !sponsoredClient && hookOptions.sponsorshipUrl && hookOptions.appId) {
6394
- sponsorshipReason = sponsorshipUnavailable.current ? "unauthorized" : "no_token";
6395
- }
6396
- let settlementClient = executionClient;
6397
- let userOpHash;
6398
- try {
6399
- userOpHash = await executionClient.sendUserOperation(callArgs);
6400
- } catch (err) {
6401
- if (!sponsoredClient) throw err;
6402
- const failure = getSponsorshipFailure(err);
6403
- sponsorshipReason = failure.reason;
6404
- if (failure.disableSponsorship) sponsorshipUnavailable.current = true;
6405
- debugWarn("[fluent zerodev] sponsorship unavailable, paying own gas", {
6406
- reason: sponsorshipReason
6407
- });
6408
- settlementClient = executionKernel.client;
6409
- userOpHash = await executionKernel.client.sendUserOperation(callArgs);
6410
- }
6411
- debugLog("[fluent zerodev] sendCalls userOp submitted", { userOpHash });
6412
- const receipt = await settlementClient.waitForUserOperationReceipt({
6413
- hash: userOpHash
6414
- });
6415
- const paymaster = readUserOperationPaymaster(receipt);
6416
- const sponsored = gasToken ? false : paymaster ? paymaster !== zeroAddress : Boolean(sponsoredClient);
6417
- if (!gasToken && sponsoredClient && !sponsored) sponsorshipReason ??= "denied";
6418
- debugLog("[fluent zerodev] sendCalls receipt", {
6419
- userOpHash,
6420
- success: receipt.success,
6421
- reason: receipt.reason,
6422
- transactionHash: receipt.receipt.transactionHash,
6423
- sponsored,
6424
- paymaster,
6425
- sponsorshipReason
6426
- });
6427
- if (!receipt.success) {
6428
- throw new Error(receipt.reason ?? `UserOperation ${userOpHash} execution failed`);
6429
- }
6430
- return {
6431
- hash: receipt.receipt.transactionHash,
6432
- sponsored,
6433
- sponsorshipReason,
6434
- paymaster
6435
- };
6436
- } catch (err) {
6437
- debugError("[fluent zerodev] sendCalls failed", err);
6438
- throw err;
6439
- } finally {
6440
- clearPromptSigningContext();
6441
- }
6442
- },
6443
- [
6444
- authenticated,
6445
- createSponsoredClient,
6446
- embeddedWallet,
6447
- error,
6448
- hostedSigner,
6449
- hookOptions.authorizationSession,
6450
- hookOptions.appId,
6451
- hookOptions.sponsorshipUrl,
6452
- initialize2,
6453
- kernels,
6454
- network,
6455
- ready
6456
- ]
6305
+ }
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
+ }
6457
6317
  );
6458
- const ensureExecutionReady = useCallback(async (options = {}) => {
6459
- const signerMode = confirmationToSignerMode(options.confirmation ?? "always");
6460
- if (kernels[signerMode]) return kernels[signerMode];
6461
- if (!ready) throw new Error("Privy wallet context is still loading");
6462
- if (!authenticated && !hostedSigner) {
6463
- login();
6464
- throw new Error("Complete wallet login, then submit the transaction again");
6318
+ }
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
6465
6331
  }
6466
- const executionKernel = await initialize2({ signerMode, throwOnError: true });
6467
- if (!executionKernel) throw new Error(error?.message ?? "ZeroDev smart account is not ready");
6468
- return executionKernel;
6469
- }, [authenticated, error, hostedSigner, initialize2, kernels, login, ready]);
6470
- return {
6471
- smartAccountEnabled: Boolean(FLUENT_CONNECT_ZERODEV_PROJECT_ID),
6472
- smartAccountReady,
6473
- smartAccountAddress: activeKernel?.smartAccountAddress,
6474
- signerAddress: embeddedWallet?.address ?? hookOptions.sessionSignerAddress,
6475
- privyReady: ready,
6476
- privyAuthenticated: authenticated,
6477
- embeddedWalletCount: wallets.filter((wallet) => wallet.walletClientType === "privy").length,
6478
- authenticate: login,
6479
- kernel: activeKernel,
6480
- signerModesReady: Object.keys(kernels),
6481
- error,
6482
- ensureExecutionReady,
6483
- sendTransaction,
6484
- sendCalls,
6485
- refresh: () => initialize2({ throwOnError: true, signerMode: "prompt" })
6486
- };
6332
+ );
6487
6333
  }
6488
- var USER_OPERATION_EVENT_TOPIC = toEventSelector(
6489
- parseAbiItem(
6490
- "event UserOperationEvent(bytes32 indexed userOpHash, address indexed sender, address indexed paymaster, uint256 nonce, bool success, uint256 actualGasCost, uint256 actualGasUsed)"
6491
- )
6492
- ).toLowerCase();
6493
- function readUserOperationPaymaster(receipt) {
6494
- if (receipt.paymaster) return getAddress(receipt.paymaster);
6495
- const event = receipt.logs.find(
6496
- (log) => log.topics[0]?.toLowerCase() === USER_OPERATION_EVENT_TOPIC && log.topics[1]?.toLowerCase() === receipt.userOpHash.toLowerCase()
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
+ }
6497
6353
  );
6498
- const topic = event?.topics[3];
6499
- if (!topic || topic.length !== 66) return void 0;
6500
- return getAddress(`0x${topic.slice(26)}`);
6501
6354
  }
6502
- function getZeroDevReadinessMessage(params) {
6503
- if (!params.ready) return "Privy wallet context is still loading";
6504
- if (params.hostedSignerAvailable) return "Fluent hosted signer is preparing";
6505
- if (!params.authenticated) return "Fluent session is connected, but Privy embedded wallet is not authenticated on this page";
6506
- if (params.embeddedWalletCount === 0) {
6507
- return `Privy is authenticated, but no embedded wallet is available (${params.walletCount} linked wallets found)`;
6355
+ function ToastIcon({ type }) {
6356
+ let icon = null;
6357
+ if (type === "success") {
6358
+ icon = /* @__PURE__ */ jsx(CircleCheckIcon, { "aria-hidden": "true" });
6508
6359
  }
6509
- return "Fluent ZeroDev account is still preparing. Try again in a moment.";
6510
- }
6511
- async function createFluentZeroDevPermissionSession(params) {
6512
- const sessionAccount = privateKeyToAccount(params.sessionPrivateKey);
6513
- const signer = await toECDSASigner({ signer: sessionAccount });
6514
- const policies = [
6515
- toCallPolicy({
6516
- policyVersion: CallPolicyVersion.V0_0_5,
6517
- permissions: params.calls.map(
6518
- (call) => call.abi && call.functionName ? {
6519
- target: call.target,
6520
- abi: call.abi,
6521
- functionName: call.functionName,
6522
- args: call.args,
6523
- callType: call.callType,
6524
- valueLimit: call.valueLimit ?? 0n
6525
- } : {
6526
- target: call.target,
6527
- selector: call.selector,
6528
- callType: call.callType,
6529
- valueLimit: call.valueLimit ?? 0n
6530
- }
6531
- )
6532
- })
6533
- ];
6534
- if (params.expiresAt) {
6535
- policies.push(toTimestampPolicy({ validUntil: params.expiresAt }));
6360
+ if (type === "info") {
6361
+ icon = /* @__PURE__ */ jsx(InfoIcon, { "aria-hidden": "true" });
6536
6362
  }
6537
- const permissionPlugin = await toPermissionValidator(params.kernel.publicClient, {
6538
- signer,
6539
- policies,
6540
- entryPoint: getEntryPoint("0.7"),
6541
- kernelVersion: KERNEL_V3_3
6542
- });
6543
- const serializedPermissionAccount = await serializePermissionAccount(
6544
- params.kernel.account,
6545
- params.sessionPrivateKey,
6546
- void 0,
6547
- void 0,
6548
- permissionPlugin,
6549
- true
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
6381
+ }
6550
6382
  );
6551
- return {
6552
- serializedPermissionAccount,
6553
- sessionSignerAddress: sessionAccount.address,
6554
- smartAccountAddress: params.kernel.smartAccountAddress
6555
- };
6556
6383
  }
6557
- function confirmationToSignerMode(confirmation) {
6558
- return confirmation === "session" ? "silent" : "prompt";
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));
6559
6397
  }
6560
- async function createFluentZeroDevAuthorizedSessionKernel(authorizationSession, chain) {
6561
- const zeroDevRpcUrl = `https://rpc.zerodev.app/api/v3/${FLUENT_CONNECT_ZERODEV_PROJECT_ID}/chain/${chain.id}`;
6562
- const publicClient = createPublicClient({
6563
- chain,
6564
- transport: createFluentRpcTransport(chain)
6565
- });
6566
- const entryPoint = getEntryPoint("0.7");
6567
- const sessionSigner = await toECDSASigner({
6568
- signer: privateKeyToAccount(authorizationSession.sessionPrivateKey)
6569
- });
6570
- const account = await deserializePermissionAccount(
6571
- publicClient,
6572
- entryPoint,
6573
- KERNEL_V3_3,
6574
- authorizationSession.serializedPermissionAccount,
6575
- sessionSigner
6576
- );
6577
- const client2 = createKernelAccountClient({
6578
- account,
6579
- chain,
6580
- bundlerTransport: createFluentBundlerTransport(zeroDevRpcUrl),
6581
- client: publicClient
6582
- });
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
+ ] });
6407
+ }
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)}`;
6414
+ }
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
+ };
6583
6446
  return {
6584
- account,
6585
- client: client2,
6586
- publicClient,
6587
- smartAccountAddress: account.address,
6588
- zeroDevRpcUrl,
6589
- chain,
6590
- signerMode: "silent",
6591
- signerSource: "session"
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
6453
+ },
6454
+ wallet: {
6455
+ signerAddress: params.signerAddress,
6456
+ smartAccountAddress: params.smartAccountAddress
6457
+ },
6458
+ scopes: params.scopes,
6459
+ issuedAt,
6460
+ metadata: {
6461
+ authMode: "direct",
6462
+ origin: params.app.origin
6463
+ }
6592
6464
  };
6593
6465
  }
6594
- async function createFluentZeroDevKernel(params) {
6595
- if (!params.wallet && !params.hostedSigner) throw new Error("Fluent signer is unavailable");
6596
- if (params.wallet) {
6597
- debugLog("[fluent zerodev] ensuring Fluent chain", params.chain.id);
6598
- await ensureWalletOnFluentChain(params.wallet, params.chain);
6599
- debugLog("[fluent zerodev] Fluent chain ready", params.chain.id);
6466
+
6467
+ // src/utils/explorerAddress.ts
6468
+ function explorerAddress(address, network) {
6469
+ const baseUrl = getFluentExplorerBaseUrl(network ?? "testnet");
6470
+ return `${baseUrl}/address/${address}`;
6471
+ }
6472
+
6473
+ // src/utils/faucetToast.ts
6474
+ function normalize(value) {
6475
+ return (value ?? "").trim().toLowerCase();
6476
+ }
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;
6600
6490
  }
6601
- const zeroDevRpcUrl = `https://rpc.zerodev.app/api/v3/${FLUENT_CONNECT_ZERODEV_PROJECT_ID}/chain/${params.chain.id}`;
6602
- const publicClient = createPublicClient({
6603
- chain: params.chain,
6604
- transport: createFluentRpcTransport(params.chain)
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.")
6605
6495
  });
6606
- const entryPoint = getEntryPoint("0.7");
6607
- let signer;
6608
- if (params.hostedSigner) {
6609
- signer = toHostedSignerLocalAccount(params.hostedSigner, params.signerMode);
6610
- } else if (params.wallet && params.signerMode === "prompt") {
6611
- signer = toPromptedPrivyLocalAccount(params.wallet, params.promptedSigners, params.chain);
6612
- } else if (params.wallet) {
6613
- signer = toSilentPrivyLocalAccount(params.wallet, params.chain);
6614
- } else {
6615
- throw new Error("Fluent signer is unavailable");
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."
6504
+ });
6505
+ return;
6506
+ }
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;
6514
+ }
6515
+ toast.add({
6516
+ type: "error",
6517
+ title: "Faucet request failed",
6518
+ description: error.message || `Request failed with ${error.status}`
6519
+ });
6520
+ return;
6616
6521
  }
6617
- const ecdsaValidator = await signerToEcdsaValidator(publicClient, {
6618
- signer,
6619
- entryPoint,
6620
- kernelVersion: KERNEL_V3_3
6621
- });
6622
- const account = await createKernelAccount(publicClient, {
6623
- entryPoint,
6624
- plugins: { sudo: ecdsaValidator },
6625
- kernelVersion: KERNEL_V3_3
6626
- });
6627
- const client2 = createKernelAccountClient({
6628
- account,
6629
- chain: params.chain,
6630
- bundlerTransport: createFluentBundlerTransport(zeroDevRpcUrl),
6631
- client: publicClient
6522
+ toast.add({
6523
+ type: "error",
6524
+ title: "Faucet request failed",
6525
+ description: error instanceof Error ? error.message : "Something went wrong."
6632
6526
  });
6633
- return {
6634
- account,
6635
- client: client2,
6636
- publicClient,
6637
- smartAccountAddress: account.address,
6638
- zeroDevRpcUrl,
6639
- chain: params.chain,
6640
- signerMode: params.signerMode,
6641
- signerSource: params.hostedSigner ? "hosted" : "privy"
6642
- };
6643
6527
  }
6644
- function toHostedSignerLocalAccount(signer, signerMode) {
6645
- const confirmation = signerMode === "silent" ? "session" : "always";
6646
- const source = {
6647
- address: signer.address,
6648
- async signMessage({ message }) {
6649
- return signer.signMessage(formatSignableMessageForPrivy(message), confirmation);
6650
- },
6651
- async signTransaction() {
6652
- throw new Error("Fluent ZeroDev signer does not sign raw transactions");
6528
+
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)
6653
6542
  },
6654
- async signTypedData(typedData) {
6655
- return signer.signTypedData(
6656
- {
6657
- domain: typedData.domain,
6658
- types: typedData.types,
6659
- primaryType: typedData.primaryType,
6660
- message: typedData.message
6661
- },
6662
- confirmation
6663
- );
6664
- }
6665
- };
6666
- return toAccount(source);
6543
+ null,
6544
+ 2
6545
+ );
6667
6546
  }
6668
- function createFluentZeroDevErc20ExecutionClient(kernel, gasToken) {
6669
- return createKernelAccountClient({
6670
- account: kernel.account,
6671
- chain: kernel.chain,
6672
- bundlerTransport: createFluentBundlerTransport(kernel.zeroDevRpcUrl),
6673
- client: kernel.publicClient,
6674
- paymaster: createFluentZeroDevErc20Paymaster({
6675
- chain: kernel.chain,
6676
- gasToken
6677
- })
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
6678
6557
  });
6679
6558
  }
6680
- var promptSigningContext = {};
6681
- function setPromptSigningContext(context) {
6682
- promptSigningContext = context;
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;
6683
6565
  }
6684
- function clearPromptSigningContext() {
6685
- promptSigningContext = {};
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");
6570
+ }
6571
+ if (balance.decimals <= maximumFractionDigits) {
6572
+ return formatFluentLocaleAmount(balance.formatted, maximumFractionDigits);
6573
+ }
6574
+ const maxDigits = Math.max(
6575
+ maximumFractionDigits,
6576
+ Math.min(balance.decimals, GAS_BALANCE_MAX_FRACTION_DIGITS)
6577
+ );
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
+ }
6583
+ }
6584
+ return formatFluentLocaleAmount(0, maximumFractionDigits);
6686
6585
  }
6687
- function buildPromptSigningUiOptions() {
6688
- const gasTokenSymbol = promptSigningContext.gasTokenSymbol;
6689
- return {
6690
- title: "Confirm Fluent transaction",
6691
- description: gasTokenSymbol ? `Gas will be paid in ${gasTokenSymbol}. Confirm this Fluent transaction.` : "Confirm this Fluent transaction.",
6692
- buttonText: "Sign"
6693
- };
6586
+
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
+ }
6611
+
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;
6620
+ }
6621
+
6622
+ // src/utils/getHighResTwitterAvatar.ts
6623
+ function getHighResTwitterAvatar(url) {
6624
+ if (!url) return "";
6625
+ return url.replace("_normal", "");
6626
+ }
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;
6635
+ }
6694
6636
  }
6695
- function toPromptedPrivyLocalAccount(wallet, promptedSigners, chain) {
6696
- const source = {
6697
- address: wallet.address,
6698
- async signMessage({ message }) {
6699
- await ensureWalletOnFluentChain(wallet, chain);
6700
- const { signature } = await promptedSigners.signMessage(
6701
- { message: formatSignableMessageForPrivy(message) },
6702
- {
6703
- address: wallet.address,
6704
- uiOptions: buildPromptSigningUiOptions()
6705
- }
6706
- );
6707
- return signature;
6708
- },
6709
- async signTransaction() {
6710
- throw new Error("Fluent ZeroDev signer does not sign raw transactions");
6711
- },
6712
- async signTypedData(typedData) {
6713
- await ensureWalletOnFluentChain(wallet, chain);
6714
- const { signature } = await promptedSigners.signTypedData(
6715
- {
6716
- domain: typedData.domain,
6717
- types: typedData.types,
6718
- primaryType: typedData.primaryType,
6719
- message: typedData.message
6637
+
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
+ );
6645
+ }
6646
+
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;
6702
+ }
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;
6724
+ }
6725
+ if (initPromise.current[signerMode]) {
6726
+ debugLog("[fluent zerodev] joining in-flight initialization");
6727
+ return initPromise.current[signerMode];
6728
+ }
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
6720
6748
  },
6721
- {
6722
- address: wallet.address,
6723
- uiOptions: buildPromptSigningUiOptions()
6724
- }
6725
- );
6726
- return signature;
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];
6727
6778
  }
6728
- };
6729
- return toAccount(source);
6730
- }
6731
- function toSilentPrivyLocalAccount(wallet, chain) {
6732
- const source = {
6733
- address: wallet.address,
6734
- async signMessage({ message }) {
6735
- debugLog("[fluent zerodev] requesting embedded provider signature", {
6736
- signerAddress: wallet.address,
6737
- messageKind: typeof message === "string" ? "string" : "raw" in message ? "raw" : typeof message
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()
6738
6814
  });
6739
- await ensureWalletOnFluentChain(wallet, chain);
6740
- const provider = await wallet.getEthereumProvider();
6741
- if (!provider?.request) throw new Error("Fluent embedded wallet provider is unavailable");
6742
- const formattedMessage = formatSignableMessageForPrivy(message);
6743
6815
  try {
6744
- const signature = await provider.request({
6745
- method: "personal_sign",
6746
- params: [isHex(formattedMessage) ? formattedMessage : stringToHex(formattedMessage), wallet.address]
6747
- });
6748
- if (typeof signature !== "string") throw new Error("Privy embedded wallet returned an invalid signature");
6749
- debugLog("[fluent zerodev] embedded provider signature ready", {
6750
- signerAddress: wallet.address,
6751
- signatureLength: signature.length
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
6752
6822
  });
6753
- return signature;
6823
+ debugLog("[fluent zerodev] sendTransaction submitted", { hash });
6824
+ return hash;
6754
6825
  } catch (err) {
6755
- debugError("[fluent zerodev] embedded provider signature failed", err);
6826
+ debugError("[fluent zerodev] sendTransaction failed", err);
6756
6827
  throw err;
6757
6828
  }
6758
- },
6759
- async signTransaction() {
6760
- throw new Error("Fluent ZeroDev signer does not sign raw transactions");
6761
- },
6762
- async signTypedData(typedData) {
6763
- debugLog("[fluent zerodev] requesting embedded provider typed-data signature", {
6764
- signerAddress: wallet.address,
6765
- primaryType: typedData.primaryType
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
6766
6887
  });
6767
- await ensureWalletOnFluentChain(wallet, chain);
6768
- const provider = await wallet.getEthereumProvider();
6769
- if (!provider?.request) throw new Error("Fluent embedded wallet provider is unavailable");
6770
6888
  try {
6771
- const signature = await provider.request({
6772
- method: "eth_signTypedData_v4",
6773
- params: [
6774
- wallet.address,
6775
- stringifyTypedDataForProvider({
6776
- domain: typedData.domain,
6777
- types: typedData.types,
6778
- primaryType: typedData.primaryType,
6779
- message: typedData.message
6780
- })
6781
- ]
6782
- });
6783
- if (typeof signature !== "string") {
6784
- throw new Error("Privy embedded wallet returned an invalid typed-data signature");
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";
6785
6905
  }
6786
- debugLog("[fluent zerodev] embedded provider typed-data signature ready", {
6787
- signerAddress: wallet.address,
6788
- signatureLength: signature.length
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
6789
6924
  });
6790
- return signature;
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
+ };
6791
6946
  } catch (err) {
6792
- debugError("[fluent zerodev] embedded provider typed-data signature failed", err);
6947
+ debugError("[fluent zerodev] sendCalls failed", err);
6793
6948
  throw err;
6949
+ } finally {
6950
+ clearPromptSigningContext();
6794
6951
  }
6795
- }
6796
- };
6797
- return toAccount(source);
6798
- }
6799
- function stringifyTypedDataForProvider(value) {
6800
- return JSON.stringify(
6801
- value,
6802
- (_key, next) => typeof next === "bigint" ? next.toString() : next
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
+ ]
6803
6967
  );
6804
- }
6805
- function formatSignableMessageForPrivy(message) {
6806
- if (typeof message === "string") return message;
6807
- if ("raw" in message) return typeof message.raw === "string" ? message.raw : bytesToHex(message.raw);
6808
- return String(message);
6809
- }
6810
- async function ensureWalletOnFluentChain(wallet, chain) {
6811
- const targetChainId = numberToHex(chain.id);
6812
- const provider = await wallet.getEthereumProvider();
6813
- if (wallet.switchChain) {
6814
- debugLog("[fluent zerodev] wallet.switchChain", chain.id);
6815
- await wallet.switchChain(chain.id);
6816
- }
6817
- if (provider?.request) {
6818
- const currentChainId = await getProviderChainId(provider);
6819
- debugLog("[fluent zerodev] provider chain", currentChainId);
6820
- if (currentChainId === targetChainId) return;
6821
- try {
6822
- await provider.request({
6823
- method: "wallet_switchEthereumChain",
6824
- params: [{ chainId: targetChainId }]
6825
- });
6826
- } catch (err) {
6827
- if (!isUnknownChainError(err)) throw err;
6828
- await provider.request({
6829
- method: "wallet_addEthereumChain",
6830
- params: [
6831
- {
6832
- chainId: targetChainId,
6833
- chainName: chain.name,
6834
- nativeCurrency: chain.nativeCurrency,
6835
- rpcUrls: chain.rpcUrls.default.http,
6836
- blockExplorerUrls: chain.blockExplorers?.default.url ? [chain.blockExplorers.default.url] : void 0
6837
- }
6838
- ]
6839
- });
6840
- await provider.request({
6841
- method: "wallet_switchEthereumChain",
6842
- params: [{ chainId: targetChainId }]
6843
- });
6844
- }
6845
- const nextChainId = await getProviderChainId(provider);
6846
- debugLog("[fluent zerodev] provider chain after switch", nextChainId);
6847
- if (nextChainId !== targetChainId) {
6848
- throw new Error(`Unsupported chainId ${Number(BigInt(nextChainId))}; switch to ${chain.name}`);
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");
6849
6975
  }
6850
- return;
6851
- }
6852
- throw new Error("Fluent embedded wallet provider is unavailable");
6853
- }
6854
- async function getProviderChainId(provider) {
6855
- const chainId = await provider.request({ method: "eth_chainId" });
6856
- if (typeof chainId !== "string") throw new Error("Unable to read embedded wallet chainId");
6857
- return chainId.toLowerCase();
6858
- }
6859
- function isUnknownChainError(err) {
6860
- const code = err?.code;
6861
- const nestedCode = err?.data?.originalError?.code;
6862
- return code === 4902 || nestedCode === 4902;
6863
- }
6864
-
6865
- // src/widget/permissionSession.ts
6866
- function createFluentPermissionApi(executor) {
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]);
6867
6980
  return {
6868
- createPermissionSession: (input) => createFluentPermissionSession(input, executor),
6869
- policies: createFluentPermissionPolicyBuilders()
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" })
6870
6996
  };
6871
6997
  }
6872
- function createFluentPermissionPolicyBuilders() {
6873
- return {
6874
- call: (input) => ({
6875
- kind: "call",
6876
- id: input.id,
6877
- call: input
6878
- }),
6879
- batch: (input) => ({
6880
- kind: "batch",
6881
- id: input.id,
6882
- calls: input.calls
6883
- })
6884
- };
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()
7007
+ );
7008
+ const topic = event?.topics[3];
7009
+ if (!topic || topic.length !== 66) return void 0;
7010
+ return getAddress(`0x${topic.slice(26)}`);
6885
7011
  }
6886
- async function createFluentPermissionSession(input, executor) {
6887
- if (!executor?.kernel || executor.smartAccountReady === false) {
6888
- throw new Error("ZeroDev smart account is not ready");
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)`;
6889
7018
  }
6890
- if (input.policies.length === 0) {
6891
- throw new Error("A permission session requires at least one policy");
7019
+ return "Fluent ZeroDev account is still preparing. Try again in a moment.";
7020
+ }
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 }));
6892
7046
  }
6893
- const calls = input.policies.flatMap(
6894
- (policy) => policy.kind === "batch" ? policy.calls.map((call) => toZeroDevPermissionCall(call, CallType.BATCH_CALL)) : [toZeroDevPermissionCall(policy.call, CallType.CALL)]
6895
- );
6896
- const expiresAt = toUnixSeconds(input.expiresAt);
6897
- const permission = await createFluentZeroDevPermissionSession({
6898
- kernel: executor.kernel,
6899
- sessionPrivateKey: input.sessionPrivateKey ?? generatePrivateKey(),
6900
- calls,
6901
- expiresAt
7047
+ const permissionPlugin = await toPermissionValidator(params.kernel.publicClient, {
7048
+ signer,
7049
+ policies,
7050
+ entryPoint: getEntryPoint("0.7"),
7051
+ kernelVersion: KERNEL_V3_3
6902
7052
  });
7053
+ const serializedPermissionAccount = await serializePermissionAccount(
7054
+ params.kernel.account,
7055
+ params.sessionPrivateKey,
7056
+ void 0,
7057
+ void 0,
7058
+ permissionPlugin,
7059
+ true
7060
+ );
6903
7061
  return {
6904
- ...permission,
6905
- label: input.label,
6906
- delegate: input.delegate,
6907
- expiresAt,
6908
- policies: input.policies
7062
+ serializedPermissionAccount,
7063
+ sessionSignerAddress: sessionAccount.address,
7064
+ smartAccountAddress: params.kernel.smartAccountAddress
6909
7065
  };
6910
7066
  }
6911
- function toZeroDevPermissionCall(call, callType) {
6912
- const functionName = call.functionName ?? call.method;
6913
- if (!functionName) throw new Error("Permission policy requires method or functionName");
6914
- return {
6915
- target: call.to,
6916
- abi: call.abi,
6917
- functionName,
6918
- args: normalizePermissionArgs(call.abi, functionName, call.args),
6919
- callType,
6920
- valueLimit: call.valueLimit
6921
- };
7067
+ function confirmationToSignerMode(confirmation) {
7068
+ return confirmation === "session" ? "silent" : "prompt";
6922
7069
  }
6923
- function normalizePermissionArgs(abi, functionName, args) {
6924
- if (!args) return void 0;
6925
- if (Array.isArray(args)) return args.map(toZeroDevCondition);
6926
- const fn = findAbiFunction(abi, functionName);
6927
- const namedArgs = args;
6928
- return fn.inputs.map((input) => {
6929
- if (!input.name) return null;
6930
- return toZeroDevCondition(namedArgs[input.name]);
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)
6931
7075
  });
6932
- }
6933
- function toZeroDevCondition(rule) {
6934
- if (!rule) return null;
6935
- if ("equals" in rule) {
6936
- return { condition: ParamCondition.EQUAL, value: rule.equals };
6937
- }
6938
- if ("max" in rule) {
6939
- return { condition: ParamCondition.LESS_THAN_OR_EQUAL, value: rule.max };
6940
- }
6941
- return { condition: ParamCondition.GREATER_THAN_OR_EQUAL, value: rule.min };
6942
- }
6943
- function findAbiFunction(abi, functionName) {
6944
- const matches = abi.filter(
6945
- (item) => item.type === "function" && item.name === functionName
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
6946
7086
  );
6947
- if (matches.length !== 1) {
6948
- throw new Error(
6949
- matches.length === 0 ? `Function "${functionName}" not found in ABI` : `Function "${functionName}" is overloaded; pass positional args or a filtered ABI`
6950
- );
6951
- }
6952
- return matches[0];
6953
- }
6954
- function toUnixSeconds(value) {
6955
- if (value === void 0) return void 0;
6956
- if (value instanceof Date) return Math.floor(value.getTime() / 1e3);
6957
- return value > 1e12 ? Math.floor(value / 1e3) : Math.floor(value);
6958
- }
6959
-
6960
- // package.json
6961
- var version = "0.3.0";
6962
-
6963
- // src/core/analytics.ts
6964
- var INSTANCE_NAME = "fluent";
6965
- var POSTHOG_UI_HOST = "https://us.posthog.com";
6966
- var BLOCK_SELECTOR = 'body > *:not([data-slot="dialog-portal"]):not([data-slot="drawer-portal"])';
6967
- var UNLOAD_CAPTURE_OPTIONS = {
6968
- transport: "sendBeacon",
6969
- send_instantly: true
6970
- };
6971
- var client = null;
6972
- var loading = null;
6973
- var loadFailed = false;
6974
- var pending = [];
6975
- var widgetLoadedTracked = false;
6976
- function analyticsEnabled(config) {
6977
- return !config.disableAnalytics && Boolean(config.analyticsHost);
6978
- }
6979
- function initFluentAnalytics(config) {
6980
- if (!analyticsEnabled(config) || loading) return;
6981
- loading = import('posthog-js').then(({ default: posthog }) => {
6982
- client = posthog.init(
6983
- FLUENT_CONNECT_POSTHOG_TOKEN,
6984
- {
6985
- api_host: config.analyticsHost,
6986
- ui_host: POSTHOG_UI_HOST,
6987
- persistence: "localStorage",
6988
- // The widget is a guest in someone else's page — no automatic collection.
6989
- // Every one of these must be set explicitly: the project's remote config
6990
- // turns performance capture, heatmaps and console recording ON, so leaving
6991
- // an option out is not the same as switching it off.
6992
- autocapture: false,
6993
- capture_pageview: false,
6994
- capture_pageleave: false,
6995
- rageclick: false,
6996
- capture_performance: false,
6997
- capture_heatmaps: false,
6998
- capture_dead_clicks: false,
6999
- // Widget console logs carry session ids and wallet addresses.
7000
- enable_recording_console_log: false,
7001
- session_recording: { blockSelector: BLOCK_SELECTOR }
7002
- },
7003
- INSTANCE_NAME
7004
- );
7005
- for (const queued of pending.splice(0)) {
7006
- capture(queued.eventName, queued.payload, queued.unload);
7007
- }
7008
- }).catch(() => {
7009
- loadFailed = true;
7010
- pending = [];
7087
+ const client2 = createKernelAccountClient({
7088
+ account,
7089
+ chain,
7090
+ bundlerTransport: createFluentBundlerTransport(zeroDevRpcUrl),
7091
+ client: publicClient
7011
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
+ };
7012
7103
  }
7013
- function sanitise(properties) {
7014
- if (!properties) return properties;
7015
- const safe = {};
7016
- for (const [key, value] of Object.entries(properties)) {
7017
- const type = typeof value;
7018
- if (value === null || type === "string" || type === "number" || type === "boolean") {
7019
- safe[key] = value;
7020
- }
7021
- }
7022
- return safe;
7023
- }
7024
- function capture(eventName, payload, unload) {
7025
- if (unload) {
7026
- client?.capture(eventName, payload, UNLOAD_CAPTURE_OPTIONS);
7027
- return;
7028
- }
7029
- client?.capture(eventName, payload);
7030
- }
7031
- function send(eventName, payload, unload) {
7032
- if (client) {
7033
- capture(eventName, payload, unload);
7034
- return;
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);
7035
7110
  }
7036
- if (loadFailed) return;
7037
- pending.push({ eventName, payload, unload });
7038
- }
7039
- function createTracker(config, getContext) {
7040
- const enabled = analyticsEnabled(config);
7041
- if (enabled) initFluentAnalytics(config);
7042
- const base = {
7043
- app_id: config.appId,
7044
- network: config.network,
7045
- auth_mode: config.authMode,
7046
- source: config.source,
7047
- campaign: config.campaign,
7048
- sdk_version: version
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");
7126
+ }
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"
7049
7152
  };
7050
- const track = (eventName, properties, options) => {
7051
- if (!enabled) return;
7052
- const payload = { ...sanitise(properties), ...base, ...getContext?.() };
7053
- send(eventName, payload, Boolean(options?.unload));
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
+ );
7174
+ }
7054
7175
  };
7055
- track.live = enabled;
7056
- return track;
7176
+ return toAccount(source);
7057
7177
  }
7058
- function trackWidgetLoadedOnce(track, properties) {
7059
- if (widgetLoadedTracked) return;
7060
- track("widget_loaded", properties);
7061
- if (track.live) widgetLoadedTracked = true;
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
+ });
7062
7189
  }
7063
-
7064
- // src/utils/buildFluentBridgeUrl.ts
7065
- function buildFluentBridgeUrl(bridgeUrl, recipient) {
7066
- if (!recipient) return bridgeUrl;
7067
- try {
7068
- const url = new URL(bridgeUrl);
7069
- url.searchParams.set("recipient", recipient);
7070
- return url.toString();
7071
- } catch {
7072
- const join = bridgeUrl.includes("?") ? "&" : "?";
7073
- return `${bridgeUrl}${join}recipient=${encodeURIComponent(recipient)}`;
7074
- }
7190
+ var promptSigningContext = {};
7191
+ function setPromptSigningContext(context) {
7192
+ promptSigningContext = context;
7075
7193
  }
7076
-
7077
- // src/utils/clearPrivyRecentLoginMethod.ts
7078
- function clearPrivyRecentLoginMethod(appId) {
7079
- if (typeof window === "undefined" || !appId) return;
7194
+ function clearPromptSigningContext() {
7195
+ promptSigningContext = {};
7196
+ }
7197
+ async function withFluentSignaturePrompt(sign) {
7198
+ setPromptSigningContext({ intent: "signature" });
7080
7199
  try {
7081
- window.localStorage.removeItem(`privy:${appId}:recent-login-method`);
7082
- window.localStorage.removeItem(`privy:${appId}:recent-login-wallet-client`);
7083
- window.localStorage.removeItem(`privy:${appId}:recent-login-chain-type`);
7084
- } catch {
7200
+ return await sign();
7201
+ } finally {
7202
+ clearPromptSigningContext();
7085
7203
  }
7086
7204
  }
7087
- function cn(...inputs) {
7088
- return twMerge(clsx(inputs));
7089
- }
7090
- var WIDGET_STYLE_SCOPE = "fluent-root dark contents text-foreground";
7091
- var FluentPortalContainerContext = createContext(null);
7092
- function FluentPortalContainerProvider({ children }) {
7093
- const [container, setContainer] = useState(null);
7094
- useLayoutEffect(() => {
7095
- const element = document.createElement("div");
7096
- element.setAttribute("data-fluent-portal-root", "");
7097
- element.className = WIDGET_STYLE_SCOPE;
7098
- document.body.appendChild(element);
7099
- setContainer(element);
7100
- return () => {
7101
- element.remove();
7102
- setContainer(null);
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"
7103
7211
  };
7104
- }, []);
7105
- return /* @__PURE__ */ jsx(FluentPortalContainerContext.Provider, { value: container, children });
7212
+ }
7213
+ const gasTokenSymbol = promptSigningContext.gasTokenSymbol;
7214
+ return {
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
+ };
7106
7219
  }
7107
- function useFluentPortalContainer(override) {
7108
- const container = useContext(FluentPortalContainerContext);
7109
- return override ?? container ?? void 0;
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;
7233
+ },
7234
+ async signTransaction() {
7235
+ throw new Error("Fluent ZeroDev signer does not sign raw transactions");
7236
+ },
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);
7110
7255
  }
7111
- var buttonVariants = cva(
7112
- "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",
7113
- {
7114
- variants: {
7115
- variant: {
7116
- default: "bg-primary text-primary-foreground hover:bg-primary/80",
7117
- 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",
7118
- secondary: "bg-button text-button-foreground hover:bg-button-hover aria-expanded:bg-button aria-expanded:text-button-foreground",
7119
- ghost: "hover:bg-primary/10 hover:text-foreground dark:hover:bg-primary/10",
7120
- 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",
7121
- link: "text-primary underline-offset-4 hover:underline"
7122
- },
7123
- size: {
7124
- 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",
7125
- 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",
7126
- 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",
7127
- lg: "h-9 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
7128
- icon: "size-8",
7129
- "icon-xs": "size-6 rounded-[min(var(--radius-md),10px)] in-data-[slot=button-group]:rounded-lg [&_svg:not([class*='size-'])]:size-3",
7130
- "icon-sm": "size-7 rounded-[min(var(--radius-md),12px)] in-data-[slot=button-group]:rounded-lg",
7131
- "icon-lg": "size-9"
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;
7132
7282
  }
7133
7283
  },
7134
- defaultVariants: {
7135
- variant: "default",
7136
- size: "default"
7137
- }
7138
- }
7139
- );
7140
- var Button = forwardRef(function Button2({ className, variant = "default", size = "default", href, target, rel, render, ...props }, ref) {
7141
- const isLink = href !== void 0;
7142
- return /* @__PURE__ */ jsx(
7143
- Button$1,
7144
- {
7145
- ref,
7146
- "data-slot": "button",
7147
- nativeButton: isLink ? false : void 0,
7148
- className: cn(buttonVariants({ variant, size, className })),
7149
- render: isLink ? /* @__PURE__ */ jsx("a", { href, target, rel }) : render,
7150
- ...props
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
+ }
7151
7320
  }
7152
- );
7153
- });
7154
- var toast = Toast$1.createToastManager();
7155
- function ToastProvider({ ...props }) {
7156
- return /* @__PURE__ */ jsx(Toast$1.Provider, { ...props });
7321
+ };
7322
+ return toAccount(source);
7157
7323
  }
7158
- function ToastPortal({ container, ...props }) {
7159
- return /* @__PURE__ */ jsx(
7160
- Toast$1.Portal,
7161
- {
7162
- "data-slot": "toast-portal",
7163
- container: useFluentPortalContainer(container),
7164
- ...props
7165
- }
7166
- );
7324
+ function stringifyTypedDataForProvider(value) {
7325
+ return stringifyWithBigInt(value);
7167
7326
  }
7168
- function ToastViewport({ className, ...props }) {
7169
- return /* @__PURE__ */ jsx(
7170
- Toast$1.Viewport,
7171
- {
7172
- "data-slot": "toast-viewport",
7173
- className: cn(
7174
- "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",
7175
- className
7176
- ),
7177
- ...props
7178
- }
7179
- );
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);
7180
7331
  }
7181
- function Toast({ className, style, ...props }) {
7182
- return /* @__PURE__ */ jsx(
7183
- Toast$1.Root,
7184
- {
7185
- "data-slot": "toast",
7186
- style: { maxWidth: 368, ...style },
7187
- className: cn(
7188
- "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",
7189
- "[--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))]",
7190
- "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]",
7191
- "after:absolute after:top-full after:left-0 after:h-[calc(var(--gap)+1px)] after:w-full after:content-['']",
7192
- "data-expanded:h-(--toast-height) data-expanded:[transform:translateX(var(--toast-swipe-movement-x))_translateY(var(--offset-y))]",
7193
- "data-limited:opacity-0 data-starting-style:[transform:translateY(150%)]",
7194
- "[&[data-ending-style]:not([data-limited]):not([data-swipe-direction])]:[transform:translateY(150%)]",
7195
- "data-ending-style:data-[swipe-direction=down]:[transform:translateY(calc(var(--toast-swipe-movement-y)+150%))]",
7196
- "data-ending-style:data-[swipe-direction=left]:[transform:translateX(calc(var(--toast-swipe-movement-x)-150%))_translateY(var(--offset-y))]",
7197
- "data-ending-style:data-[swipe-direction=right]:[transform:translateX(calc(var(--toast-swipe-movement-x)+150%))_translateY(var(--offset-y))]",
7198
- "data-ending-style:data-[swipe-direction=up]:[transform:translateY(calc(var(--toast-swipe-movement-y)-150%))]",
7199
- "data-expanded:data-ending-style:data-[swipe-direction=down]:[transform:translateY(calc(var(--toast-swipe-movement-y)+150%))]",
7200
- "data-expanded:data-ending-style:data-[swipe-direction=left]:[transform:translateX(calc(var(--toast-swipe-movement-x)-150%))_translateY(var(--offset-y))]",
7201
- "data-expanded:data-ending-style:data-[swipe-direction=right]:[transform:translateX(calc(var(--toast-swipe-movement-x)+150%))_translateY(var(--offset-y))]",
7202
- "data-expanded:data-ending-style:data-[swipe-direction=up]:[transform:translateY(calc(var(--toast-swipe-movement-y)-150%))]",
7203
- className
7204
- ),
7205
- ...props
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);
7338
+ }
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 }]
7347
+ });
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 }]
7365
+ });
7206
7366
  }
7207
- );
7208
- }
7209
- function ToastContent({ className, ...props }) {
7210
- return /* @__PURE__ */ jsx(
7211
- Toast$1.Content,
7212
- {
7213
- "data-slot": "toast-content",
7214
- className: cn(
7215
- "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",
7216
- className
7217
- ),
7218
- ...props
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}`);
7219
7371
  }
7220
- );
7372
+ return;
7373
+ }
7374
+ throw new Error("Fluent embedded wallet provider is unavailable");
7221
7375
  }
7222
- function ToastTitle({ className, ...props }) {
7223
- return /* @__PURE__ */ jsx(
7224
- Toast$1.Title,
7225
- {
7226
- "data-slot": "toast-title",
7227
- className: cn("text-sm font-medium", className),
7228
- ...props
7229
- }
7230
- );
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();
7231
7380
  }
7232
- function ToastDescription({
7233
- className,
7234
- ...props
7235
- }) {
7236
- return /* @__PURE__ */ jsx(
7237
- Toast$1.Description,
7238
- {
7239
- "data-slot": "toast-description",
7240
- className: cn("text-sm text-muted-foreground", className),
7241
- ...props
7242
- }
7243
- );
7381
+ function isUnknownChainError(err) {
7382
+ const code = err?.code;
7383
+ const nestedCode = err?.data?.originalError?.code;
7384
+ return code === 4902 || nestedCode === 4902;
7244
7385
  }
7245
- function ToastAction({
7246
- className,
7247
- render = /* @__PURE__ */ jsx(Button, { variant: "outline", size: "sm" }),
7248
- ...props
7249
- }) {
7250
- return /* @__PURE__ */ jsx(
7251
- Toast$1.Action,
7252
- {
7253
- "data-slot": "toast-action",
7254
- render,
7255
- className: cn("shrink-0", className),
7256
- ...props
7257
- }
7258
- );
7386
+
7387
+ // src/widget/permissionSession.ts
7388
+ function createFluentPermissionApi(executor) {
7389
+ return {
7390
+ createPermissionSession: (input) => createFluentPermissionSession(input, executor),
7391
+ policies: createFluentPermissionPolicyBuilders()
7392
+ };
7259
7393
  }
7260
- function ToastClose({
7261
- className,
7262
- children,
7263
- render = /* @__PURE__ */ jsx(Button, { variant: "ghost", size: "icon-sm" }),
7264
- ...props
7265
- }) {
7266
- return /* @__PURE__ */ jsx(
7267
- Toast$1.Close,
7268
- {
7269
- "data-slot": "toast-close",
7270
- "aria-label": "Close toast",
7271
- render,
7272
- className: cn(
7273
- "relative shrink-0 text-muted-foreground after:absolute after:-inset-2 after:content-[''] hover:text-foreground",
7274
- className
7275
- ),
7276
- ...props,
7277
- children: children ?? /* @__PURE__ */ jsx(XIcon, { "aria-hidden": "true" })
7278
- }
7279
- );
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
+ };
7280
7407
  }
7281
- function ToastIcon({ type }) {
7282
- let icon = null;
7283
- if (type === "success") {
7284
- icon = /* @__PURE__ */ jsx(CircleCheckIcon, { "aria-hidden": "true" });
7285
- }
7286
- if (type === "info") {
7287
- icon = /* @__PURE__ */ jsx(InfoIcon, { "aria-hidden": "true" });
7288
- }
7289
- if (type === "warning") {
7290
- icon = /* @__PURE__ */ jsx(TriangleAlertIcon, { "aria-hidden": "true" });
7408
+ async function createFluentPermissionSession(input, executor) {
7409
+ if (!executor?.kernel || executor.smartAccountReady === false) {
7410
+ throw new Error("ZeroDev smart account is not ready");
7291
7411
  }
7292
- if (type === "error") {
7293
- icon = /* @__PURE__ */ jsx(OctagonXIcon, { className: "text-destructive", "aria-hidden": "true" });
7412
+ if (input.policies.length === 0) {
7413
+ throw new Error("A permission session requires at least one policy");
7294
7414
  }
7295
- if (type === "loading") {
7296
- icon = /* @__PURE__ */ jsx(Loader2Icon, { className: "animate-spin", "aria-hidden": "true" });
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)]
7417
+ );
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 };
7297
7459
  }
7298
- if (!icon) {
7299
- return null;
7460
+ if ("max" in rule) {
7461
+ return { condition: ParamCondition.LESS_THAN_OR_EQUAL, value: rule.max };
7300
7462
  }
7301
- return /* @__PURE__ */ jsx(
7302
- "span",
7303
- {
7304
- "data-slot": "toast-icon",
7305
- className: "shrink-0 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4",
7306
- children: icon
7307
- }
7308
- );
7463
+ return { condition: ParamCondition.GREATER_THAN_OR_EQUAL, value: rule.min };
7309
7464
  }
7310
- function ToastList() {
7311
- const { toasts } = Toast$1.useToastManager();
7312
- return toasts.map((toastItem) => /* @__PURE__ */ jsx(Toast, { toast: toastItem, children: /* @__PURE__ */ jsxs(ToastContent, { children: [
7313
- /* @__PURE__ */ jsxs("div", { className: "flex min-w-0 flex-1 flex-col gap-1", children: [
7314
- /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1.5", children: [
7315
- /* @__PURE__ */ jsx(ToastIcon, { type: toastItem.type }),
7316
- /* @__PURE__ */ jsx(ToastTitle, {})
7317
- ] }),
7318
- /* @__PURE__ */ jsx(ToastDescription, {})
7319
- ] }),
7320
- /* @__PURE__ */ jsx(ToastAction, {}),
7321
- /* @__PURE__ */ jsx(ToastClose, {})
7322
- ] }) }, toastItem.id));
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
+ );
7473
+ }
7474
+ return matches[0];
7323
7475
  }
7324
- function Toaster({
7325
- children,
7326
- toastManager = toast,
7327
- ...props
7328
- }) {
7329
- return /* @__PURE__ */ jsxs(ToastProvider, { toastManager, ...props, children: [
7330
- children,
7331
- /* @__PURE__ */ jsx(ToastPortal, { children: /* @__PURE__ */ jsx(ToastViewport, { children: /* @__PURE__ */ jsx(ToastList, {}) }) })
7332
- ] });
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);
7333
7480
  }
7334
- Toast$1.createToastManager;
7335
- Toast$1.useToastManager;
7336
7481
 
7337
- // src/utils/formatAddress.ts
7338
- function formatAddress(address) {
7339
- return `${address.slice(0, 6)}...${address.slice(-4)}`;
7340
- }
7482
+ // src/widget/reviewRejected.ts
7483
+ var FluentReviewRejectedError = class extends Error {
7484
+ constructor(review) {
7485
+ super(`User rejected Fluent ${review} review`);
7486
+ this.review = review;
7487
+ this.name = "FluentReviewRejectedError";
7488
+ }
7489
+ review;
7490
+ };
7341
7491
 
7342
- // src/utils/copyAddress.ts
7343
- async function copyAddressToClipboard(address) {
7492
+ // src/widget/iframeBridge.ts
7493
+ var READ_ONLY_METHODS = /* @__PURE__ */ new Set([
7494
+ "eth_blockNumber",
7495
+ "eth_call",
7496
+ "eth_estimateGas",
7497
+ "eth_feeHistory",
7498
+ "eth_gasPrice",
7499
+ "eth_getBalance",
7500
+ "eth_getBlockByHash",
7501
+ "eth_getBlockByNumber",
7502
+ "eth_getCode",
7503
+ "eth_getLogs",
7504
+ "eth_getStorageAt",
7505
+ "eth_getTransactionByHash",
7506
+ "eth_getTransactionCount",
7507
+ "eth_getTransactionReceipt",
7508
+ "eth_maxPriorityFeePerGas",
7509
+ "net_version"
7510
+ ]);
7511
+ var FluentIframeRpcError = class extends Error {
7512
+ constructor(code, message) {
7513
+ super(message);
7514
+ this.code = code;
7515
+ this.name = "FluentIframeRpcError";
7516
+ }
7517
+ code;
7518
+ };
7519
+ function createFluentIframeRpcHandler(executor) {
7520
+ const invalid = (method, what) => new FluentIframeRpcError(-32602, `${method}: expected ${what}`);
7521
+ const assertOwnAddress = (candidate, method) => {
7522
+ const address = executor.account().address;
7523
+ if (!address) {
7524
+ throw new FluentIframeRpcError(4100, `${method}: no account is signed in`);
7525
+ }
7526
+ if (typeof candidate !== "string" || !isAddress(candidate)) {
7527
+ throw invalid(method, "an address");
7528
+ }
7529
+ if (candidate.toLowerCase() !== address.toLowerCase()) {
7530
+ throw new FluentIframeRpcError(4100, `${method}: ${candidate} is not the signed-in account`);
7531
+ }
7532
+ };
7533
+ const assertDirectMode = () => {
7534
+ if (executor.authMode === "hosted") {
7535
+ throw new FluentAuthError(
7536
+ "hosted_not_supported",
7537
+ 'The iframe bridge needs authMode: "direct" \u2014 there is no hosted signer to ask.'
7538
+ );
7539
+ }
7540
+ };
7541
+ const parseTypedData = (payload, method) => {
7542
+ const value = typeof payload === "string" ? safeJsonParse(payload) : payload;
7543
+ if (!value || typeof value !== "object") {
7544
+ throw invalid(method, "EIP-712 typed data");
7545
+ }
7546
+ return value;
7547
+ };
7548
+ const parseHex = (value, method, what) => {
7549
+ if (value === void 0 || value === null) return void 0;
7550
+ if (typeof value !== "string" || !isHex(value)) throw invalid(method, `${what} as hex`);
7551
+ return value;
7552
+ };
7553
+ return async (request) => {
7554
+ const { method } = request;
7555
+ const params = request.params ?? [];
7556
+ if (!Array.isArray(params)) throw invalid(method, "positional params");
7557
+ switch (method) {
7558
+ // `enable` is what `@ledgerhq/iframe-provider`'s own `enable()` sends.
7559
+ case "enable":
7560
+ case "eth_accounts":
7561
+ case "eth_requestAccounts": {
7562
+ const address = executor.account().address;
7563
+ return address ? [address] : [];
7564
+ }
7565
+ case "eth_chainId":
7566
+ return toHex(executor.chainId);
7567
+ case "eth_signTypedData_v4":
7568
+ case "eth_signTypedData_v3": {
7569
+ assertDirectMode();
7570
+ assertOwnAddress(params[0], method);
7571
+ return executor.sign.signTypedData(parseTypedData(params[1], method));
7572
+ }
7573
+ case "eth_signTypedData": {
7574
+ assertDirectMode();
7575
+ const [first, second] = params;
7576
+ const addressFirst = typeof first === "string" && isAddress(first);
7577
+ assertOwnAddress(addressFirst ? first : second, method);
7578
+ return executor.sign.signTypedData(parseTypedData(addressFirst ? second : first, method));
7579
+ }
7580
+ case "personal_sign": {
7581
+ assertDirectMode();
7582
+ assertOwnAddress(params[1], method);
7583
+ const message = params[0];
7584
+ if (typeof message !== "string") throw invalid(method, "a message");
7585
+ return executor.sign.signMessage({ message: isHex(message) ? { raw: message } : message });
7586
+ }
7587
+ case "eth_sendTransaction": {
7588
+ assertDirectMode();
7589
+ const tx = params[0];
7590
+ if (!tx || typeof tx !== "object") throw invalid(method, "a transaction object");
7591
+ const { from, to, data, value } = tx;
7592
+ assertOwnAddress(from, method);
7593
+ if (typeof to !== "string" || !isAddress(to)) throw invalid(method, "a recipient");
7594
+ const valueHex = parseHex(value, method, "value");
7595
+ const result = await executor.sendCalls([
7596
+ {
7597
+ to,
7598
+ data: parseHex(data, method, "data") ?? "0x",
7599
+ value: valueHex === void 0 ? 0n : hexToBigInt(valueHex)
7600
+ }
7601
+ ]);
7602
+ return result.hash;
7603
+ }
7604
+ default:
7605
+ if (READ_ONLY_METHODS.has(method)) {
7606
+ return executor.rpc(method, request.params);
7607
+ }
7608
+ throw new FluentIframeRpcError(4200, `Unsupported method: ${method}`);
7609
+ }
7610
+ };
7611
+ }
7612
+ function safeJsonParse(text) {
7344
7613
  try {
7345
- await navigator.clipboard.writeText(address);
7346
- toast.add({
7347
- type: "success",
7348
- title: "Address copied",
7349
- description: formatAddress(address)
7350
- });
7351
- } catch (error) {
7352
- debugWarn("[fluent connect] Failed to copy address", error);
7353
- toast.add({
7354
- type: "error",
7355
- title: "Copy failed",
7356
- description: "Could not copy address to clipboard."
7357
- });
7614
+ return JSON.parse(text);
7615
+ } catch {
7616
+ return void 0;
7358
7617
  }
7359
7618
  }
7360
-
7361
- // src/utils/createLocalFluentSession.ts
7362
- function createLocalFluentSession(params) {
7363
- const issuedAt = Math.floor(Date.now() / 1e3);
7364
- const payload = {
7365
- iss: typeof location !== "undefined" ? location.origin : "fluent-local",
7366
- aud: params.appId,
7367
- sub: params.userId,
7368
- app: params.app,
7369
- scopes: params.scopes,
7370
- iat: issuedAt
7619
+ function isJsonRpcRequest(data) {
7620
+ if (!data || typeof data !== "object") return false;
7621
+ const { jsonrpc, method } = data;
7622
+ return jsonrpc === "2.0" && typeof method === "string";
7623
+ }
7624
+ function createFluentIframeBridge(iframe, options) {
7625
+ const { executor } = options;
7626
+ const allowedOrigin = exactOrigin(options.allowedOrigin);
7627
+ const listenOn = options.listenOn ?? globalThis.window;
7628
+ const handle = createFluentIframeRpcHandler(executor);
7629
+ let disposed = false;
7630
+ let announced = false;
7631
+ const post = (message) => {
7632
+ iframe.contentWindow?.postMessage(message, allowedOrigin);
7633
+ };
7634
+ const notify = (message) => {
7635
+ if (disposed) return;
7636
+ post(message);
7637
+ };
7638
+ const listener = (event) => {
7639
+ if (event.origin !== allowedOrigin) return;
7640
+ if (!iframe.contentWindow || event.source !== iframe.contentWindow) return;
7641
+ if (!isJsonRpcRequest(event.data)) return;
7642
+ const { id, method, params } = event.data;
7643
+ if (id === void 0 || id === null) return;
7644
+ if (!announced) {
7645
+ announced = true;
7646
+ post({ jsonrpc: "2.0", method: "chainChanged", params: [toHex(executor.chainId)] });
7647
+ const address = executor.account().address;
7648
+ post({ jsonrpc: "2.0", method: "accountsChanged", params: [address ? [address] : []] });
7649
+ }
7650
+ void handle({ method, params }).then(
7651
+ (result) => post({ jsonrpc: "2.0", id, result }),
7652
+ (error) => post({ jsonrpc: "2.0", id, error: toRpcError(error) })
7653
+ );
7371
7654
  };
7655
+ listenOn.addEventListener("message", listener);
7372
7656
  return {
7373
- app: params.app,
7374
- appId: params.appId,
7375
- idToken: `mock.${btoa(JSON.stringify(payload))}.signature`,
7376
- user: {
7377
- id: params.userId,
7378
- email: params.email
7379
- },
7380
- wallet: {
7381
- signerAddress: params.signerAddress,
7382
- smartAccountAddress: params.smartAccountAddress
7383
- },
7384
- scopes: params.scopes,
7385
- issuedAt,
7386
- metadata: {
7387
- authMode: "direct",
7388
- origin: params.app.origin
7657
+ notifyAccountsChanged: (accounts) => notify({ jsonrpc: "2.0", method: "accountsChanged", params: [accounts] }),
7658
+ notifyChainChanged: (chainId) => notify({ jsonrpc: "2.0", method: "chainChanged", params: [toHex(chainId)] }),
7659
+ dispose: () => {
7660
+ disposed = true;
7661
+ listenOn.removeEventListener("message", listener);
7389
7662
  }
7390
7663
  };
7391
7664
  }
7392
-
7393
- // src/utils/explorerAddress.ts
7394
- function explorerAddress(address, network) {
7395
- const baseUrl = getFluentExplorerBaseUrl(network ?? "testnet");
7396
- return `${baseUrl}/address/${address}`;
7397
- }
7398
-
7399
- // src/utils/faucetToast.ts
7400
- function normalize(value) {
7401
- return (value ?? "").trim().toLowerCase();
7402
- }
7403
- function isAlreadyClaimed(status, message) {
7404
- const statusNorm = normalize(status);
7405
- const messageNorm = normalize(message);
7406
- return statusNorm.includes("already") || messageNorm.includes("already");
7407
- }
7408
- function toastFaucetSuccess(receipt) {
7409
- if (isAlreadyClaimed(receipt.status, receipt.message)) {
7410
- toast.add({
7411
- type: "info",
7412
- title: "Already claimed",
7413
- description: receipt.message || "BLEND faucet was already claimed for this account."
7414
- });
7415
- return;
7665
+ function toRpcError(error) {
7666
+ if (error instanceof FluentIframeRpcError) return { code: error.code, message: error.message };
7667
+ if (error instanceof FluentReviewRejectedError) return { code: 4001, message: error.message };
7668
+ if (error instanceof FluentAuthError) {
7669
+ const code = error.code === "hosted_not_supported" ? 4200 : -32603;
7670
+ return { code, message: `${error.code}: ${error.message}` };
7416
7671
  }
7417
- toast.add({
7418
- type: "success",
7419
- title: "Faucet claimed",
7420
- description: receipt.message || (receipt.txHash ? `Transaction ${receipt.txHash}` : "BLEND was sent to your wallet.")
7421
- });
7672
+ const message = error instanceof Error ? error.message : String(error);
7673
+ return { code: -32603, message };
7422
7674
  }
7423
- function toastFaucetError(error) {
7424
- if (error instanceof HttpError) {
7425
- if (isAlreadyClaimed(error.body?.status, error.message) || error.status === 409) {
7426
- toast.add({
7427
- type: "info",
7428
- title: "Already claimed",
7429
- description: error.message || "BLEND faucet was already claimed for this account."
7430
- });
7431
- return;
7432
- }
7433
- if (error.status === 429) {
7434
- toast.add({
7435
- type: "warning",
7436
- title: "Too many requests",
7437
- description: error.message || "Please wait a moment and try again."
7438
- });
7439
- return;
7440
- }
7441
- toast.add({
7442
- type: "error",
7443
- title: "Faucet request failed",
7444
- description: error.message || `Request failed with ${error.status}`
7445
- });
7446
- return;
7675
+ function exactOrigin(candidate) {
7676
+ let origin;
7677
+ try {
7678
+ const url = new URL(candidate);
7679
+ if (url.protocol === "http:" || url.protocol === "https:") origin = url.origin;
7680
+ } catch {
7681
+ origin = void 0;
7447
7682
  }
7448
- toast.add({
7449
- type: "error",
7450
- title: "Faucet request failed",
7451
- description: error instanceof Error ? error.message : "Something went wrong."
7452
- });
7683
+ if (!origin || origin === "null") {
7684
+ throw new Error(`allowedOrigin must be an origin such as https://market.example, got "${candidate}"`);
7685
+ }
7686
+ return origin;
7453
7687
  }
7454
-
7455
- // src/utils/formatExternalWallet.ts
7456
- function formatExternalWallet(wallet, status) {
7457
- return JSON.stringify(
7458
- {
7459
- status: status ?? "Waiting for wallet connection",
7460
- wallet: wallet ? {
7461
- provider: "Reown AppKit",
7462
- configured: wallet.configured,
7463
- connected: wallet.connected,
7464
- address: wallet.address,
7465
- chainId: wallet.chainId
7466
- } : null,
7467
- walletConnectEnabled: Boolean(wallet?.configured)
7468
- },
7469
- null,
7470
- 2
7688
+ function useFluentIframeBridge(iframeRef, { allowedOrigin }) {
7689
+ const { widget, authMode } = useFluentWidget();
7690
+ const { chain } = useFluentWidgetNetwork();
7691
+ const widgetRef = useRef(widget);
7692
+ widgetRef.current = widget;
7693
+ const rpc = useMemo(
7694
+ () => createPublicClient({ chain, transport: createFluentRpcTransport(chain) }),
7695
+ [chain]
7471
7696
  );
7697
+ const bridgeRef = useRef(null);
7698
+ useEffect(() => {
7699
+ const iframe = {
7700
+ get contentWindow() {
7701
+ return iframeRef.current?.contentWindow ?? null;
7702
+ }
7703
+ };
7704
+ const bridge = createFluentIframeBridge(iframe, {
7705
+ allowedOrigin,
7706
+ executor: {
7707
+ authMode,
7708
+ account: () => widgetRef.current.account,
7709
+ chainId: chain.id,
7710
+ sign: {
7711
+ signMessage: (params) => widgetRef.current.signMessage(params),
7712
+ signTypedData: (typedData) => widgetRef.current.signTypedData(typedData)
7713
+ },
7714
+ sendCalls: (calls) => widgetRef.current.createBatchOp({ calls }).execute(),
7715
+ rpc: (method, params) => rpc.request({ method, params })
7716
+ }
7717
+ });
7718
+ bridge.notifyChainChanged(chain.id);
7719
+ bridgeRef.current = bridge;
7720
+ return () => {
7721
+ bridge.dispose();
7722
+ bridgeRef.current = null;
7723
+ };
7724
+ }, [iframeRef, allowedOrigin, authMode, chain.id, rpc]);
7725
+ const address = widget.account.address;
7726
+ useEffect(() => {
7727
+ bridgeRef.current?.notifyAccountsChanged(address ? [address] : []);
7728
+ }, [address]);
7472
7729
  }
7473
7730
 
7474
- // src/utils/formatFluentLocaleAmount.ts
7475
- var FLUENT_AMOUNT_LOCALE = "en-US";
7476
- var FLUENT_DECIMAL_SEPARATOR = new Intl.NumberFormat(FLUENT_AMOUNT_LOCALE).formatToParts(1.1).find((part) => part.type === "decimal")?.value ?? ".";
7477
- function formatFluentLocaleAmount(value, maximumFractionDigits = 2) {
7478
- const amount = typeof value === "number" ? value : Number(value);
7479
- if (!Number.isFinite(amount)) return typeof value === "string" ? value : String(value);
7480
- return amount.toLocaleString(FLUENT_AMOUNT_LOCALE, {
7481
- minimumFractionDigits: 0,
7482
- maximumFractionDigits
7483
- });
7731
+ // package.json
7732
+ var version = "0.3.2";
7733
+
7734
+ // src/core/analytics.ts
7735
+ var INSTANCE_NAME = "fluent";
7736
+ var POSTHOG_UI_HOST = "https://us.posthog.com";
7737
+ var BLOCK_SELECTOR = 'body > *:not([data-slot="dialog-portal"]):not([data-slot="drawer-portal"])';
7738
+ var UNLOAD_CAPTURE_OPTIONS = {
7739
+ transport: "sendBeacon",
7740
+ send_instantly: true
7741
+ };
7742
+ var client = null;
7743
+ var loading = null;
7744
+ var loadFailed = false;
7745
+ var pending = [];
7746
+ var widgetLoadedTracked = false;
7747
+ function analyticsEnabled(config) {
7748
+ return !config.disableAnalytics && Boolean(config.analyticsHost);
7484
7749
  }
7485
-
7486
- // src/utils/formatFluentGasTokenBalance.ts
7487
- var GAS_BALANCE_MAX_FRACTION_DIGITS = 6;
7488
- function roundToFractionDigits(raw, decimals, digits) {
7489
- const discardedScale = 10n ** BigInt(decimals - digits);
7490
- return (raw + discardedScale / 2n) / discardedScale;
7750
+ function initFluentAnalytics(config) {
7751
+ if (!analyticsEnabled(config) || loading) return;
7752
+ loading = import('posthog-js').then(({ default: posthog }) => {
7753
+ client = posthog.init(
7754
+ FLUENT_CONNECT_POSTHOG_TOKEN,
7755
+ {
7756
+ api_host: config.analyticsHost,
7757
+ ui_host: POSTHOG_UI_HOST,
7758
+ persistence: "localStorage",
7759
+ // The widget is a guest in someone else's page — no automatic collection.
7760
+ // Every one of these must be set explicitly: the project's remote config
7761
+ // turns performance capture, heatmaps and console recording ON, so leaving
7762
+ // an option out is not the same as switching it off.
7763
+ autocapture: false,
7764
+ capture_pageview: false,
7765
+ capture_pageleave: false,
7766
+ rageclick: false,
7767
+ capture_performance: false,
7768
+ capture_heatmaps: false,
7769
+ capture_dead_clicks: false,
7770
+ // Widget console logs carry session ids and wallet addresses.
7771
+ enable_recording_console_log: false,
7772
+ session_recording: { blockSelector: BLOCK_SELECTOR }
7773
+ },
7774
+ INSTANCE_NAME
7775
+ );
7776
+ for (const queued of pending.splice(0)) {
7777
+ capture(queued.eventName, queued.payload, queued.unload);
7778
+ }
7779
+ }).catch(() => {
7780
+ loadFailed = true;
7781
+ pending = [];
7782
+ });
7491
7783
  }
7492
- function formatFluentGasTokenBalance(balance, maximumFractionDigits = 1) {
7493
- if (balance.raw === null || balance.formatted === null) return null;
7494
- if (maximumFractionDigits < 0 || !Number.isInteger(maximumFractionDigits)) {
7495
- throw new Error("maximumFractionDigits must be a non-negative integer");
7496
- }
7497
- if (balance.decimals <= maximumFractionDigits) {
7498
- return formatFluentLocaleAmount(balance.formatted, maximumFractionDigits);
7499
- }
7500
- const maxDigits = Math.max(
7501
- maximumFractionDigits,
7502
- Math.min(balance.decimals, GAS_BALANCE_MAX_FRACTION_DIGITS)
7503
- );
7504
- for (let digits = maximumFractionDigits; digits <= maxDigits; digits += 1) {
7505
- const rounded = roundToFractionDigits(balance.raw, balance.decimals, digits);
7506
- if (rounded > 0n || balance.raw === 0n) {
7507
- return formatFluentLocaleAmount(formatUnits(rounded, digits), digits);
7784
+ function sanitise(properties) {
7785
+ if (!properties) return properties;
7786
+ const safe = {};
7787
+ for (const [key, value] of Object.entries(properties)) {
7788
+ const type = typeof value;
7789
+ if (value === null || type === "string" || type === "number" || type === "boolean") {
7790
+ safe[key] = value;
7508
7791
  }
7509
7792
  }
7510
- return formatFluentLocaleAmount(0, maximumFractionDigits);
7793
+ return safe;
7511
7794
  }
7512
-
7513
- // src/utils/formatSession.ts
7514
- function formatSession(session) {
7515
- if (!session) return "Waiting for Fluent login";
7516
- return JSON.stringify(
7517
- {
7518
- app: {
7519
- mode: session.app.mode,
7520
- origin: session.app.origin,
7521
- installationId: session.app.installationId,
7522
- clientId: session.app.clientId,
7523
- appName: session.app.appName
7524
- },
7525
- user: session.user,
7526
- wallet: {
7527
- smartAccountAddress: session.wallet.smartAccountAddress
7528
- },
7529
- scopes: session.scopes,
7530
- issuedAt: session.issuedAt,
7531
- idToken: session.idToken
7532
- },
7533
- null,
7534
- 2
7535
- );
7795
+ function capture(eventName, payload, unload) {
7796
+ if (unload) {
7797
+ client?.capture(eventName, payload, UNLOAD_CAPTURE_OPTIONS);
7798
+ return;
7799
+ }
7800
+ client?.capture(eventName, payload);
7536
7801
  }
7537
-
7538
- // src/utils/getAnonymousId.ts
7539
- function getAnonymousId() {
7540
- const storageKey = "fluent_demo_visitor_id";
7541
- const existing = localStorage.getItem(storageKey);
7542
- if (existing) return existing;
7543
- const next = crypto.randomUUID?.() ?? `visitor_${Date.now()}_${Math.random().toString(16).slice(2)}`;
7544
- localStorage.setItem(storageKey, next);
7545
- return next;
7802
+ function send(eventName, payload, unload) {
7803
+ if (client) {
7804
+ capture(eventName, payload, unload);
7805
+ return;
7806
+ }
7807
+ if (loadFailed) return;
7808
+ pending.push({ eventName, payload, unload });
7546
7809
  }
7547
-
7548
- // src/utils/getHighResTwitterAvatar.ts
7549
- function getHighResTwitterAvatar(url) {
7550
- if (!url) return "";
7551
- return url.replace("_normal", "");
7810
+ function createTracker(config, getContext) {
7811
+ const enabled = analyticsEnabled(config);
7812
+ if (enabled) initFluentAnalytics(config);
7813
+ const base = {
7814
+ app_id: config.appId,
7815
+ network: config.network,
7816
+ auth_mode: config.authMode,
7817
+ source: config.source,
7818
+ campaign: config.campaign,
7819
+ sdk_version: version
7820
+ };
7821
+ const track = (eventName, properties, options) => {
7822
+ if (!enabled) return;
7823
+ const payload = { ...sanitise(properties), ...base, ...getContext?.() };
7824
+ send(eventName, payload, Boolean(options?.unload));
7825
+ };
7826
+ track.live = enabled;
7827
+ return track;
7552
7828
  }
7553
-
7554
- // src/utils/hasStoredWidgetSession.ts
7555
- function hasStoredWidgetSession(storage = globalThis.window?.localStorage) {
7556
- if (!storage) return false;
7557
- try {
7558
- return Boolean(storage.getItem(FLUENT_WIDGET_SESSION_STORAGE_KEY));
7559
- } catch {
7560
- return false;
7561
- }
7829
+ function trackWidgetLoadedOnce(track, properties) {
7830
+ if (widgetLoadedTracked) return;
7831
+ track("widget_loaded", properties);
7832
+ if (track.live) widgetLoadedTracked = true;
7562
7833
  }
7563
7834
  var REOWN_PROJECT_ID = FLUENT_CONNECT_REOWN_PROJECT_ID;
7564
7835
  var queryClient = new QueryClient();
@@ -9620,12 +9891,16 @@ function useIsMobile() {
9620
9891
  }, []);
9621
9892
  return !!isMobile;
9622
9893
  }
9623
- function BatchOperationReviewModal({
9624
- operation,
9894
+ function ReviewDialog({
9895
+ eyebrow,
9896
+ title,
9897
+ ariaLabel,
9898
+ address,
9899
+ footnote,
9625
9900
  onConfirm,
9626
- onCancel
9901
+ onCancel,
9902
+ children
9627
9903
  }) {
9628
- if (!operation) return null;
9629
9904
  return /* @__PURE__ */ jsx(
9630
9905
  "div",
9631
9906
  {
@@ -9640,48 +9915,21 @@ function BatchOperationReviewModal({
9640
9915
  className: "w-full max-w-[520px] rounded-[18px] border border-[#49eded]/30 bg-[#030213] p-[18px] text-white shadow-2xl",
9641
9916
  role: "dialog",
9642
9917
  "aria-modal": "true",
9643
- "aria-label": "Confirm Fluent transaction",
9918
+ "aria-label": ariaLabel,
9644
9919
  children: [
9645
9920
  /* @__PURE__ */ jsxs("div", { className: "mb-3.5 flex items-start justify-between gap-3", children: [
9646
9921
  /* @__PURE__ */ jsxs("div", { children: [
9647
- /* @__PURE__ */ jsx("span", { className: "text-xs font-black uppercase text-[#49eded]", children: "Fluent transaction review" }),
9648
- /* @__PURE__ */ jsx("h2", { className: "mt-1 text-2xl leading-[30px] font-medium", children: operation.reviewTitle ?? "Confirm transaction" })
9922
+ /* @__PURE__ */ jsx("span", { className: "text-xs font-black uppercase text-[#49eded]", children: eyebrow }),
9923
+ /* @__PURE__ */ jsx("h2", { className: "mt-1 text-2xl leading-[30px] font-medium", children: title })
9649
9924
  ] }),
9650
- /* @__PURE__ */ jsx(
9651
- Button,
9652
- {
9653
- type: "button",
9654
- variant: "secondary",
9655
- size: "icon",
9656
- "aria-label": "Close",
9657
- onClick: onCancel,
9658
- children: "x"
9659
- }
9660
- )
9925
+ /* @__PURE__ */ jsx(Button, { type: "button", variant: "secondary", size: "icon", "aria-label": "Close", onClick: onCancel, children: "x" })
9661
9926
  ] }),
9662
9927
  /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-3 rounded-xl border border-[#49eded]/20 bg-[#49eded]/10 p-3", children: [
9663
9928
  /* @__PURE__ */ jsx("span", { className: "text-xs text-white/65", children: "Signing account" }),
9664
- /* @__PURE__ */ jsx("strong", { className: "text-sm", children: operation.account?.address ? formatAddress(operation.account.address) : "Fluent account" })
9929
+ /* @__PURE__ */ jsx("strong", { className: "text-sm", children: address ? formatAddress(address) : "Fluent account" })
9665
9930
  ] }),
9666
- /* @__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(
9667
- "li",
9668
- {
9669
- className: "flex flex-col gap-1 rounded-xl border border-[#49eded]/20 bg-[#49eded]/10 p-3",
9670
- children: [
9671
- /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-3", children: [
9672
- /* @__PURE__ */ jsx("strong", { className: "text-sm", children: call.label ?? operation.calls[index]?.method ?? operation.calls[index]?.functionName ?? "Contract call" }),
9673
- /* @__PURE__ */ jsx("span", { className: "text-xs text-white/65", children: formatAddress(call.to) })
9674
- ] }),
9675
- call.value > 0n ? /* @__PURE__ */ jsxs("small", { className: "text-xs text-white/65", children: [
9676
- "Value ",
9677
- call.value.toString(),
9678
- " wei"
9679
- ] }) : null
9680
- ]
9681
- },
9682
- call.id ?? `${call.to}-${index}`
9683
- )) }),
9684
- /* @__PURE__ */ jsx("p", { className: "text-xs leading-[18px] text-white/65", children: "Confirming allows the Fluent embedded signer to sign this ZeroDev UserOperation." }),
9931
+ children,
9932
+ /* @__PURE__ */ jsx("p", { className: "text-xs leading-[18px] text-white/65", children: footnote }),
9685
9933
  /* @__PURE__ */ jsxs("div", { className: "mt-3 grid grid-cols-[minmax(0,0.8fr)_minmax(0,1.2fr)] gap-2.5", children: [
9686
9934
  /* @__PURE__ */ jsx(Button, { type: "button", variant: "secondary", onClick: onCancel, children: "Cancel" }),
9687
9935
  /* @__PURE__ */ jsx(Button, { type: "button", onClick: onConfirm, children: "Confirm and sign" })
@@ -9692,6 +9940,85 @@ function BatchOperationReviewModal({
9692
9940
  }
9693
9941
  );
9694
9942
  }
9943
+ function BatchOperationReviewModal({
9944
+ operation,
9945
+ onConfirm,
9946
+ onCancel
9947
+ }) {
9948
+ if (!operation) return null;
9949
+ return /* @__PURE__ */ jsx(
9950
+ ReviewDialog,
9951
+ {
9952
+ eyebrow: "Fluent transaction review",
9953
+ title: operation.reviewTitle ?? "Confirm transaction",
9954
+ ariaLabel: "Confirm Fluent transaction",
9955
+ address: operation.account?.address,
9956
+ footnote: "Confirming allows the Fluent embedded signer to sign this ZeroDev UserOperation.",
9957
+ onConfirm,
9958
+ onCancel,
9959
+ 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(
9960
+ "li",
9961
+ {
9962
+ className: "flex flex-col gap-1 rounded-xl border border-[#49eded]/20 bg-[#49eded]/10 p-3",
9963
+ children: [
9964
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-3", children: [
9965
+ /* @__PURE__ */ jsx("strong", { className: "text-sm", children: call.label ?? operation.calls[index]?.method ?? operation.calls[index]?.functionName ?? "Contract call" }),
9966
+ /* @__PURE__ */ jsx("span", { className: "text-xs text-white/65", children: formatAddress(call.to) })
9967
+ ] }),
9968
+ call.value > 0n ? /* @__PURE__ */ jsxs("small", { className: "text-xs text-white/65", children: [
9969
+ "Value ",
9970
+ call.value.toString(),
9971
+ " wei"
9972
+ ] }) : null
9973
+ ]
9974
+ },
9975
+ call.id ?? `${call.to}-${index}`
9976
+ )) })
9977
+ }
9978
+ );
9979
+ }
9980
+ function formatMessage(message) {
9981
+ if (typeof message === "string") return message;
9982
+ return typeof message.raw === "string" ? message.raw : bytesToHex(message.raw);
9983
+ }
9984
+ var ROW = "rounded-xl border border-[#49eded]/20 bg-[#49eded]/10 p-3";
9985
+ var CODE = "max-h-60 overflow-auto whitespace-pre-wrap break-all text-xs";
9986
+ function SignatureReviewModal({
9987
+ review,
9988
+ onConfirm,
9989
+ onCancel
9990
+ }) {
9991
+ if (!review) return null;
9992
+ return /* @__PURE__ */ jsx(
9993
+ ReviewDialog,
9994
+ {
9995
+ eyebrow: "Fluent signature review",
9996
+ title: review.kind === "message" ? "Sign message" : "Sign typed data",
9997
+ ariaLabel: "Confirm Fluent signature",
9998
+ address: review.address,
9999
+ 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.",
10000
+ onConfirm,
10001
+ onCancel,
10002
+ children: /* @__PURE__ */ jsxs("div", { className: "my-3 flex flex-col gap-2", children: [
10003
+ /* @__PURE__ */ jsxs("div", { className: `flex items-center justify-between gap-3 ${ROW}`, children: [
10004
+ /* @__PURE__ */ jsx("span", { className: "text-xs text-white/65", children: "Requested by" }),
10005
+ /* @__PURE__ */ jsx("strong", { className: "break-all text-sm", children: review.origin })
10006
+ ] }),
10007
+ review.kind === "message" ? /* @__PURE__ */ jsx("pre", { className: `${ROW} ${CODE}`, "aria-label": "Message", children: formatMessage(review.message) }) : /* @__PURE__ */ jsxs(Fragment, { children: [
10008
+ /* @__PURE__ */ jsxs("div", { className: `flex flex-col gap-1 ${ROW}`, children: [
10009
+ /* @__PURE__ */ jsx("span", { className: "text-xs text-white/65", children: "Domain" }),
10010
+ /* @__PURE__ */ jsx("pre", { className: CODE, children: stringifyWithBigInt(review.typedData.domain ?? {}, 2) })
10011
+ ] }),
10012
+ /* @__PURE__ */ jsxs("div", { className: `flex items-center justify-between gap-3 ${ROW}`, children: [
10013
+ /* @__PURE__ */ jsx("span", { className: "text-xs text-white/65", children: "Primary type" }),
10014
+ /* @__PURE__ */ jsx("strong", { className: "text-sm", children: review.typedData.primaryType })
10015
+ ] }),
10016
+ /* @__PURE__ */ jsx("pre", { className: `${ROW} ${CODE}`, "aria-label": "Message", children: stringifyWithBigInt(review.typedData.message, 2) })
10017
+ ] })
10018
+ ] })
10019
+ }
10020
+ );
10021
+ }
9695
10022
  function deriveWidgetAccount(input) {
9696
10023
  const { smartAccount, wallet, sessionUserId, sessionSmartAccountAddress, directAuth } = input;
9697
10024
  const fluentAccountAddress = smartAccount.smartAccountAddress ?? sessionSmartAccountAddress;
@@ -9792,41 +10119,67 @@ function useGasPaymentSelection(params) {
9792
10119
  const defaultConfirmationMode = silentSigningEnabled ? "session" : "always";
9793
10120
  return { selectedGasPaymentToken, defaultConfirmationMode };
9794
10121
  }
9795
- function useBatchReview(options) {
9796
- const [batchReview, setBatchReview] = useState(null);
10122
+ function useReviewPrompt(options) {
10123
+ const { label, onOpen } = options;
10124
+ const [review, setReview] = useState(null);
9797
10125
  const resolution = useRef(null);
9798
- const onOpen = options?.onOpen;
9799
- const confirmBatchOperation = useCallback(
9800
- (operation) => {
10126
+ const request = useCallback(
10127
+ (next) => {
9801
10128
  onOpen?.();
9802
- resolution.current?.reject(
9803
- new Error("A newer Fluent transaction review replaced this request")
9804
- );
9805
- setBatchReview(operation);
9806
- return new Promise((resolve, reject) => {
9807
- resolution.current = { resolve, reject };
10129
+ resolution.current?.reject(new Error(`A newer Fluent ${label} review replaced this request`));
10130
+ setReview(next);
10131
+ return new Promise((resolve, reject2) => {
10132
+ resolution.current = { resolve, reject: reject2 };
9808
10133
  });
9809
10134
  },
9810
- [onOpen]
10135
+ [label, onOpen]
9811
10136
  );
9812
- const acceptBatchReview = useCallback(() => {
10137
+ const accept = useCallback(() => {
9813
10138
  resolution.current?.resolve();
9814
10139
  resolution.current = null;
9815
- setBatchReview(null);
10140
+ setReview(null);
9816
10141
  }, []);
9817
- const rejectBatchReview = useCallback(() => {
9818
- resolution.current?.reject(new Error("User rejected Fluent transaction review"));
10142
+ const reject = useCallback(() => {
10143
+ resolution.current?.reject(new FluentReviewRejectedError(label));
9819
10144
  resolution.current = null;
9820
- setBatchReview(null);
10145
+ setReview(null);
9821
10146
  }, []);
9822
10147
  useEffect(
9823
10148
  () => () => {
9824
- resolution.current?.reject(new Error("Fluent transaction review was closed"));
10149
+ resolution.current?.reject(new Error(`Fluent ${label} review was closed`));
9825
10150
  resolution.current = null;
9826
10151
  },
9827
- []
10152
+ [label]
9828
10153
  );
9829
- return { batchReview, confirmBatchOperation, acceptBatchReview, rejectBatchReview };
10154
+ return { review, request, accept, reject };
10155
+ }
10156
+
10157
+ // src/widget/hooks/useBatchReview.ts
10158
+ function useBatchReview(options) {
10159
+ const { review, request, accept, reject } = useReviewPrompt({
10160
+ label: "transaction",
10161
+ onOpen: options?.onOpen
10162
+ });
10163
+ return {
10164
+ batchReview: review,
10165
+ confirmBatchOperation: request,
10166
+ acceptBatchReview: accept,
10167
+ rejectBatchReview: reject
10168
+ };
10169
+ }
10170
+
10171
+ // src/widget/hooks/useSignatureReview.ts
10172
+ function useSignatureReview(options) {
10173
+ const { review, request, accept, reject } = useReviewPrompt({
10174
+ label: "signature",
10175
+ onOpen: options?.onOpen
10176
+ });
10177
+ return {
10178
+ signatureReview: review,
10179
+ confirmSignature: request,
10180
+ acceptSignatureReview: accept,
10181
+ rejectSignatureReview: reject
10182
+ };
9830
10183
  }
9831
10184
  function useFaucet(params) {
9832
10185
  const {
@@ -9955,6 +10308,81 @@ function useFluentSession(params) {
9955
10308
  return { session, setSession };
9956
10309
  }
9957
10310
 
10311
+ // src/widget/signRequest.ts
10312
+ function externalWalletSigner(wallet) {
10313
+ const walletClient = wallet.walletClient;
10314
+ const account = walletClient?.account ?? wallet.address;
10315
+ if (!walletClient || !account) return null;
10316
+ const address = typeof account === "string" ? account : account.address;
10317
+ return {
10318
+ address,
10319
+ async resolve() {
10320
+ return {
10321
+ signMessage: ({ message }) => walletClient.signMessage({ account, message }),
10322
+ signTypedData: (typedData) => walletClient.signTypedData({ account, ...typedData })
10323
+ };
10324
+ }
10325
+ };
10326
+ }
10327
+ function createFluentSignApi(executor) {
10328
+ const assertDirectMode = () => {
10329
+ if (executor.authMode === "hosted") {
10330
+ throw new FluentAuthError(
10331
+ "hosted_not_supported",
10332
+ 'Signing needs authMode: "direct" \u2014 there is no hosted signer to ask.'
10333
+ );
10334
+ }
10335
+ };
10336
+ const smartAccountSigner = () => ({
10337
+ address: executor.account.address,
10338
+ async resolve() {
10339
+ const kernel = await executor.ensureReady({ confirmation: "always" });
10340
+ if (kernel.signerSource !== "privy") {
10341
+ throw new FluentAuthError(
10342
+ "root_signer_required",
10343
+ "Only the Fluent ID root signer can sign for the smart account."
10344
+ );
10345
+ }
10346
+ return kernel.account;
10347
+ }
10348
+ });
10349
+ const pickSigner = () => {
10350
+ assertDirectMode();
10351
+ if (executor.account.type === "smart" && executor.account.address) return smartAccountSigner();
10352
+ if (executor.account.type === "eoa") {
10353
+ const signer = executor.wallet ? externalWalletSigner(executor.wallet) : null;
10354
+ if (!signer) throw new FluentAuthError("not_connected", "External wallet has no signer.");
10355
+ return signer;
10356
+ }
10357
+ throw new FluentAuthError("not_connected", "Connect a Fluent ID or an External wallet first.");
10358
+ };
10359
+ return {
10360
+ async signMessage({ message }) {
10361
+ const signer = pickSigner();
10362
+ await executor.confirm({
10363
+ kind: "message",
10364
+ origin: executor.origin,
10365
+ account: executor.account,
10366
+ address: signer.address,
10367
+ message
10368
+ });
10369
+ return (await signer.resolve()).signMessage({ message });
10370
+ },
10371
+ async signTypedData(typedData) {
10372
+ const signer = pickSigner();
10373
+ const request = typedData;
10374
+ await executor.confirm({
10375
+ kind: "typedData",
10376
+ origin: executor.origin,
10377
+ account: executor.account,
10378
+ address: signer.address,
10379
+ typedData: request
10380
+ });
10381
+ return (await signer.resolve()).signTypedData(request);
10382
+ }
10383
+ };
10384
+ }
10385
+
9958
10386
  // src/widget/sendCallsViaExternalWallet.ts
9959
10387
  async function sendCallsViaExternalWallet(calls, wallet, chain, publicClient) {
9960
10388
  const walletClient = wallet.walletClient;
@@ -9993,6 +10421,8 @@ function useWidgetExecution(params) {
9993
10421
  defaultConfirmationMode,
9994
10422
  selectedGasPaymentToken,
9995
10423
  confirmBatchOperation,
10424
+ authMode,
10425
+ confirmSignature,
9996
10426
  refreshBalances,
9997
10427
  track
9998
10428
  } = params;
@@ -10052,15 +10482,43 @@ function useWidgetExecution(params) {
10052
10482
  }),
10053
10483
  [smartAccount.kernel, smartAccount.smartAccountReady]
10054
10484
  );
10485
+ const signApi = useMemo(
10486
+ () => createFluentSignApi({
10487
+ authMode,
10488
+ account: widgetAccount,
10489
+ origin: window.location.origin,
10490
+ confirm: confirmSignature,
10491
+ ensureReady: async (options) => {
10492
+ const kernel = await smartAccount.ensureExecutionReady(options);
10493
+ return {
10494
+ signerSource: kernel.signerSource,
10495
+ account: {
10496
+ signMessage: (params2) => withFluentSignaturePrompt(() => kernel.account.signMessage(params2)),
10497
+ signTypedData: (typedData) => withFluentSignaturePrompt(() => kernel.account.signTypedData(typedData))
10498
+ }
10499
+ };
10500
+ },
10501
+ wallet: wallet?.connected ? wallet : void 0
10502
+ }),
10503
+ [authMode, widgetAccount, confirmSignature, smartAccount.ensureExecutionReady, wallet]
10504
+ );
10055
10505
  return useMemo(
10056
10506
  () => ({
10057
10507
  account: widgetAccount,
10058
10508
  confirmationMode: defaultConfirmationMode,
10059
10509
  gasPayment: selectedGasPaymentToken,
10060
10510
  createBatchOp,
10061
- ...permissionApi
10511
+ ...permissionApi,
10512
+ ...signApi
10062
10513
  }),
10063
- [widgetAccount, defaultConfirmationMode, selectedGasPaymentToken, createBatchOp, permissionApi]
10514
+ [
10515
+ widgetAccount,
10516
+ defaultConfirmationMode,
10517
+ selectedGasPaymentToken,
10518
+ createBatchOp,
10519
+ permissionApi,
10520
+ signApi
10521
+ ]
10064
10522
  );
10065
10523
  }
10066
10524
  function useZeroDevInitializer(params) {
@@ -11091,6 +11549,7 @@ function FluentWidgetContent({
11091
11549
  }, [directAuth, handleDisconnect, openConnectFlow, startDirectFluentLogin]);
11092
11550
  const closeAccountMenu = useCallback(() => setAccountOpen(false), [setAccountOpen]);
11093
11551
  const { batchReview, confirmBatchOperation, acceptBatchReview, rejectBatchReview } = useBatchReview({ onOpen: closeAccountMenu });
11552
+ const { signatureReview, confirmSignature, acceptSignatureReview, rejectSignatureReview } = useSignatureReview({ onOpen: closeAccountMenu });
11094
11553
  const widgetApi = useWidgetExecution({
11095
11554
  chain,
11096
11555
  fluentAccountReady,
@@ -11100,6 +11559,8 @@ function FluentWidgetContent({
11100
11559
  defaultConfirmationMode,
11101
11560
  selectedGasPaymentToken,
11102
11561
  confirmBatchOperation,
11562
+ authMode: resolvedConfig.authMode,
11563
+ confirmSignature,
11103
11564
  refreshBalances,
11104
11565
  track
11105
11566
  });
@@ -11128,7 +11589,8 @@ function FluentWidgetContent({
11128
11589
  status,
11129
11590
  connecting,
11130
11591
  refreshBalances,
11131
- getAuthToken
11592
+ getAuthToken,
11593
+ authMode: resolvedConfig.authMode
11132
11594
  }),
11133
11595
  [
11134
11596
  session,
@@ -11142,7 +11604,8 @@ function FluentWidgetContent({
11142
11604
  status,
11143
11605
  connecting,
11144
11606
  refreshBalances,
11145
- getAuthToken
11607
+ getAuthToken,
11608
+ resolvedConfig.authMode
11146
11609
  ]
11147
11610
  );
11148
11611
  const accountAvatarUrl = resolvedConfig.avatar.forceDefault ? void 0 : getHighResTwitterAvatar(user?.twitter?.profilePictureUrl);
@@ -11245,6 +11708,14 @@ function FluentWidgetContent({
11245
11708
  onConfirm: acceptBatchReview,
11246
11709
  onCancel: rejectBatchReview
11247
11710
  }
11711
+ ),
11712
+ /* @__PURE__ */ jsx(
11713
+ SignatureReviewModal,
11714
+ {
11715
+ review: signatureReview,
11716
+ onConfirm: acceptSignatureReview,
11717
+ onCancel: rejectSignatureReview
11718
+ }
11248
11719
  )
11249
11720
  ] })
11250
11721
  ] }) });
@@ -11439,6 +11910,6 @@ function FluentWidget(props) {
11439
11910
  ) });
11440
11911
  }
11441
11912
 
11442
- 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 };
11913
+ 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, FluentIframeRpcError, FluentPortalContainerProvider, FluentReviewRejectedError, FluentWidget, FluentWidgetConnectButton, FluentWidgetNetworkProvider, Icon, Label, Separator, Switch, WIDGET_STYLE_SCOPE, WalletMenuActionCard, buttonVariants, clearPrivyRecentLoginMethod, createFluentBatchOp, createFluentClient, createFluentFamiliesClient, createFluentIframeBridge, createFluentIframeRpcHandler, 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, useFluentIframeBridge, useFluentUserTokens, useFluentWidget, useFluentWidgetNetwork, useFluentZeroDevAccount, useWidget, withFluentSignaturePrompt };
11443
11914
  //# sourceMappingURL=index.js.map
11444
11915
  //# sourceMappingURL=index.js.map