@fluent.xyz/connect 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { toEventSelector, parseAbiItem, defineChain, http, createPublicClient, formatUnits, isAddress, getAddress, encodeFunctionData, parseUnits, zeroAddress, numberToHex, BaseError, HttpRequestError, fallback, isHex, stringToHex, bytesToHex } from 'viem';
2
2
  import * as React2 from 'react';
3
- import { createContext, forwardRef, useContext, useMemo, useState, useCallback, useRef, useEffect, useLayoutEffect } from 'react';
3
+ import { createContext, forwardRef, useContext, useMemo, useState, useCallback, useLayoutEffect, useRef, useEffect } from 'react';
4
4
  import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
5
5
  import { toCallPolicy, CallPolicyVersion, toTimestampPolicy, CallType, ParamCondition } from '@zerodev/permissions/policies';
6
6
  export { CallType, ParamCondition } from '@zerodev/permissions/policies';
@@ -6135,1430 +6135,1452 @@ 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
- ]
6162
- );
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;
6193
- }
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;
6215
- }
6216
- if (initPromise.current[signerMode]) {
6217
- debugLog("[fluent zerodev] joining in-flight initialization");
6218
- return initPromise.current[signerMode];
6219
- }
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];
6269
- }
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 = {};
6289
- }
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
- );
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
- ]
6457
- );
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");
6465
- }
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
- };
6487
- }
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()
6497
- );
6498
- const topic = event?.topics[3];
6499
- if (!topic || topic.length !== 66) return void 0;
6500
- return getAddress(`0x${topic.slice(26)}`);
6501
- }
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)`;
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)}`;
6508
6148
  }
6509
- return "Fluent ZeroDev account is still preparing. Try again in a moment.";
6510
6149
  }
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 }));
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 {
6536
6159
  }
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
6550
- );
6551
- return {
6552
- serializedPermissionAccount,
6553
- sessionSignerAddress: sessionAccount.address,
6554
- smartAccountAddress: params.kernel.smartAccountAddress
6555
- };
6556
6160
  }
6557
- function confirmationToSignerMode(confirmation) {
6558
- return confirmation === "session" ? "silent" : "prompt";
6161
+ function cn(...inputs) {
6162
+ return twMerge(clsx(inputs));
6559
6163
  }
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
- });
6583
- return {
6584
- account,
6585
- client: client2,
6586
- publicClient,
6587
- smartAccountAddress: account.address,
6588
- zeroDevRpcUrl,
6589
- chain,
6590
- signerMode: "silent",
6591
- signerSource: "session"
6592
- };
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 });
6593
6180
  }
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);
6600
- }
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)
6605
- });
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");
6616
- }
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
6632
- });
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
- };
6181
+ function useFluentPortalContainer(override) {
6182
+ const container = useContext(FluentPortalContainerContext);
6183
+ return override ?? container ?? void 0;
6643
6184
  }
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");
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
+ }
6653
6207
  },
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
- );
6208
+ defaultVariants: {
6209
+ variant: "default",
6210
+ size: "default"
6664
6211
  }
6665
- };
6666
- return toAccount(source);
6667
- }
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
- })
6678
- });
6679
- }
6680
- var promptSigningContext = {};
6681
- function setPromptSigningContext(context) {
6682
- promptSigningContext = context;
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
+ }
6226
+ );
6227
+ });
6228
+ var toast = Toast$1.createToastManager();
6229
+ function ToastProvider({ ...props }) {
6230
+ return /* @__PURE__ */ jsx(Toast$1.Provider, { ...props });
6683
6231
  }
6684
- function clearPromptSigningContext() {
6685
- promptSigningContext = {};
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
6239
+ }
6240
+ );
6686
6241
  }
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
- };
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
6252
+ }
6253
+ );
6694
6254
  }
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
6720
- },
6721
- {
6722
- address: wallet.address,
6723
- uiOptions: buildPromptSigningUiOptions()
6724
- }
6725
- );
6726
- return signature;
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
6727
6280
  }
6728
- };
6729
- return toAccount(source);
6281
+ );
6730
6282
  }
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
6738
- });
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
- 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
6752
- });
6753
- return signature;
6754
- } catch (err) {
6755
- debugError("[fluent zerodev] embedded provider signature failed", err);
6756
- throw err;
6757
- }
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
6766
- });
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
- 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");
6785
- }
6786
- debugLog("[fluent zerodev] embedded provider typed-data signature ready", {
6787
- signerAddress: wallet.address,
6788
- signatureLength: signature.length
6789
- });
6790
- return signature;
6791
- } catch (err) {
6792
- debugError("[fluent zerodev] embedded provider typed-data signature failed", err);
6793
- throw err;
6794
- }
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
6795
6293
  }
6796
- };
6797
- return toAccount(source);
6294
+ );
6798
6295
  }
6799
- function stringifyTypedDataForProvider(value) {
6800
- return JSON.stringify(
6801
- value,
6802
- (_key, next) => typeof next === "bigint" ? next.toString() : next
6296
+ function ToastTitle({ className, ...props }) {
6297
+ return /* @__PURE__ */ jsx(
6298
+ Toast$1.Title,
6299
+ {
6300
+ "data-slot": "toast-title",
6301
+ className: cn("text-sm font-medium", className),
6302
+ ...props
6303
+ }
6803
6304
  );
6804
6305
  }
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);
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
+ }
6317
+ );
6809
6318
  }
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
- });
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
6844
6331
  }
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}`);
6332
+ );
6333
+ }
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" })
6849
6352
  }
6850
- return;
6353
+ );
6354
+ }
6355
+ function ToastIcon({ type }) {
6356
+ let icon = null;
6357
+ if (type === "success") {
6358
+ icon = /* @__PURE__ */ jsx(CircleCheckIcon, { "aria-hidden": "true" });
6851
6359
  }
6852
- throw new Error("Fluent embedded wallet provider is unavailable");
6360
+ if (type === "info") {
6361
+ icon = /* @__PURE__ */ jsx(InfoIcon, { "aria-hidden": "true" });
6362
+ }
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
+ }
6382
+ );
6853
6383
  }
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();
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));
6397
+ }
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)}`;
6858
6414
  }
6859
- function isUnknownChainError(err) {
6860
- const code = err?.code;
6861
- const nestedCode = err?.data?.originalError?.code;
6862
- return code === 4902 || nestedCode === 4902;
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
+ }
6863
6433
  }
6864
6434
 
6865
- // src/widget/permissionSession.ts
6866
- function createFluentPermissionApi(executor) {
6867
- return {
6868
- createPermissionSession: (input) => createFluentPermissionSession(input, executor),
6869
- policies: createFluentPermissionPolicyBuilders()
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
6870
6445
  };
6871
- }
6872
- function createFluentPermissionPolicyBuilders() {
6873
6446
  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
- })
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
+ }
6884
6464
  };
6885
6465
  }
6886
- async function createFluentPermissionSession(input, executor) {
6887
- if (!executor?.kernel || executor.smartAccountReady === false) {
6888
- throw new Error("ZeroDev smart account is not ready");
6889
- }
6890
- if (input.policies.length === 0) {
6891
- throw new Error("A permission session requires at least one policy");
6892
- }
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
6902
- });
6903
- return {
6904
- ...permission,
6905
- label: input.label,
6906
- delegate: input.delegate,
6907
- expiresAt,
6908
- policies: input.policies
6909
- };
6466
+
6467
+ // src/utils/explorerAddress.ts
6468
+ function explorerAddress(address, network) {
6469
+ const baseUrl = getFluentExplorerBaseUrl(network ?? "testnet");
6470
+ return `${baseUrl}/address/${address}`;
6910
6471
  }
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
- };
6472
+
6473
+ // src/utils/faucetToast.ts
6474
+ function normalize(value) {
6475
+ return (value ?? "").trim().toLowerCase();
6922
6476
  }
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]);
6931
- });
6477
+ function isAlreadyClaimed(status, message) {
6478
+ const statusNorm = normalize(status);
6479
+ const messageNorm = normalize(message);
6480
+ return statusNorm.includes("already") || messageNorm.includes("already");
6932
6481
  }
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 };
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;
6940
6490
  }
6941
- return { condition: ParamCondition.GREATER_THAN_OR_EQUAL, value: rule.min };
6491
+ toast.add({
6492
+ type: "success",
6493
+ title: "Faucet claimed",
6494
+ description: receipt.message || (receipt.txHash ? `Transaction ${receipt.txHash}` : "BLEND was sent to your wallet.")
6495
+ });
6942
6496
  }
6943
- function findAbiFunction(abi, functionName) {
6944
- const matches = abi.filter(
6945
- (item) => item.type === "function" && item.name === functionName
6946
- );
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
- );
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;
6951
6521
  }
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);
6522
+ toast.add({
6523
+ type: "error",
6524
+ title: "Faucet request failed",
6525
+ description: error instanceof Error ? error.message : "Something went wrong."
6526
+ });
6958
6527
  }
6959
6528
 
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);
6529
+ // src/utils/formatExternalWallet.ts
6530
+ function formatExternalWallet(wallet, status) {
6531
+ return JSON.stringify(
6532
+ {
6533
+ status: status ?? "Waiting for wallet connection",
6534
+ wallet: wallet ? {
6535
+ provider: "Reown AppKit",
6536
+ configured: wallet.configured,
6537
+ connected: wallet.connected,
6538
+ address: wallet.address,
6539
+ chainId: wallet.chainId
6540
+ } : null,
6541
+ walletConnectEnabled: Boolean(wallet?.configured)
6542
+ },
6543
+ null,
6544
+ 2
6545
+ );
6978
6546
  }
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 = [];
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
7011
6557
  });
7012
6558
  }
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;
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;
7023
6565
  }
7024
- function capture(eventName, payload, unload) {
7025
- if (unload) {
7026
- client?.capture(eventName, payload, UNLOAD_CAPTURE_OPTIONS);
7027
- return;
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");
7028
6570
  }
7029
- client?.capture(eventName, payload);
7030
- }
7031
- function send(eventName, payload, unload) {
7032
- if (client) {
7033
- capture(eventName, payload, unload);
7034
- return;
6571
+ if (balance.decimals <= maximumFractionDigits) {
6572
+ return formatFluentLocaleAmount(balance.formatted, maximumFractionDigits);
7035
6573
  }
7036
- if (loadFailed) return;
7037
- pending.push({ eventName, payload, unload });
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);
7038
6585
  }
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
7049
- };
7050
- const track = (eventName, properties, options) => {
7051
- if (!enabled) return;
7052
- const payload = { ...sanitise(properties), ...base, ...getContext?.() };
7053
- send(eventName, payload, Boolean(options?.unload));
7054
- };
7055
- track.live = enabled;
7056
- return track;
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
+ );
7057
6610
  }
7058
- function trackWidgetLoadedOnce(track, properties) {
7059
- if (widgetLoadedTracked) return;
7060
- track("widget_loaded", properties);
7061
- if (track.live) widgetLoadedTracked = true;
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;
7062
6620
  }
7063
6621
 
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
- }
6622
+ // src/utils/getHighResTwitterAvatar.ts
6623
+ function getHighResTwitterAvatar(url) {
6624
+ if (!url) return "";
6625
+ return url.replace("_normal", "");
7075
6626
  }
7076
6627
 
7077
- // src/utils/clearPrivyRecentLoginMethod.ts
7078
- function clearPrivyRecentLoginMethod(appId) {
7079
- if (typeof window === "undefined" || !appId) return;
6628
+ // src/utils/hasStoredWidgetSession.ts
6629
+ function hasStoredWidgetSession(storage = globalThis.window?.localStorage) {
6630
+ if (!storage) return false;
7080
6631
  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`);
6632
+ return Boolean(storage.getItem(FLUENT_WIDGET_SESSION_STORAGE_KEY));
7084
6633
  } catch {
6634
+ return false;
7085
6635
  }
7086
6636
  }
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);
7103
- };
7104
- }, []);
7105
- return /* @__PURE__ */ jsx(FluentPortalContainerContext.Provider, { value: container, children });
7106
- }
7107
- function useFluentPortalContainer(override) {
7108
- const container = useContext(FluentPortalContainerContext);
7109
- return override ?? container ?? void 0;
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
+ );
7110
6645
  }
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"
7132
- }
7133
- },
7134
- defaultVariants: {
7135
- variant: "default",
7136
- size: "default"
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;
7137
6724
  }
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
6725
+ if (initPromise.current[signerMode]) {
6726
+ debugLog("[fluent zerodev] joining in-flight initialization");
6727
+ return initPromise.current[signerMode];
7151
6728
  }
7152
- );
7153
- });
7154
- var toast = Toast$1.createToastManager();
7155
- function ToastProvider({ ...props }) {
7156
- return /* @__PURE__ */ jsx(Toast$1.Provider, { ...props });
7157
- }
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
6729
+ setSmartAccountReady(Boolean(activeKernel));
6730
+ setError(null);
6731
+ initPromise.current[signerMode] = (async () => {
6732
+ debugLog("[fluent zerodev] initializing", {
6733
+ signerMode,
6734
+ embeddedWallet: embeddedWallet?.address,
6735
+ walletClientType: embeddedWallet?.walletClientType,
6736
+ hostedSigner: hostedSigner?.address
6737
+ });
6738
+ const nextKernel = canUseAuthorizationSession ? await createFluentZeroDevAuthorizedSessionKernel(
6739
+ hookOptions.authorizationSession,
6740
+ chain
6741
+ ) : await createFluentZeroDevKernel({
6742
+ wallet: canUseLocalSigner ? embeddedWallet : void 0,
6743
+ hostedSigner: canUseLocalSigner ? void 0 : hostedSigner ?? void 0,
6744
+ signerMode,
6745
+ promptedSigners: {
6746
+ signMessage: promptSignMessage,
6747
+ signTypedData: promptSignTypedData
6748
+ },
6749
+ chain
6750
+ });
6751
+ if (hookOptions.sessionSmartAccountAddress && nextKernel.smartAccountAddress.toLowerCase() !== hookOptions.sessionSmartAccountAddress.toLowerCase()) {
6752
+ throw new Error("Fluent Connect signer does not control the connected smart account");
6753
+ }
6754
+ debugLog("[fluent zerodev] ready", {
6755
+ signerMode,
6756
+ signerAddress: embeddedWallet?.address ?? hostedSigner?.address,
6757
+ smartAccountAddress: nextKernel.smartAccountAddress
6758
+ });
6759
+ setKernels((current) => ({ ...current, [signerMode]: nextKernel }));
6760
+ setSmartAccountReady(true);
6761
+ return nextKernel;
6762
+ })();
6763
+ try {
6764
+ return await initPromise.current[signerMode];
6765
+ } catch (err) {
6766
+ const nextError = err instanceof Error ? err : new Error("Failed to create ZeroDev account");
6767
+ debugError("[fluent zerodev] initialization failed", nextError);
6768
+ setKernels((current) => {
6769
+ const { [signerMode]: _failed, ...rest } = current;
6770
+ setSmartAccountReady(Object.keys(rest).length > 0);
6771
+ return rest;
6772
+ });
6773
+ setError(nextError);
6774
+ if (options.throwOnError) throw nextError;
6775
+ return null;
6776
+ } finally {
6777
+ delete initPromise.current[signerMode];
7165
6778
  }
7166
- );
7167
- }
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
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 = {};
7178
6798
  }
6799
+ }, [authenticated, ready]);
6800
+ const sendTransaction = useCallback(
6801
+ async (request) => {
6802
+ const cachedKernel = kernels.prompt;
6803
+ if (cachedKernel?.signerSource === "hosted" || !cachedKernel && hostedSigner && !(ready && authenticated && embeddedWallet)) {
6804
+ hostedSigner?.prepare("always");
6805
+ }
6806
+ const executionKernel = cachedKernel ?? await initialize2({ signerMode: "prompt" });
6807
+ if (!executionKernel) throw new Error(error?.message ?? "ZeroDev smart account is not ready");
6808
+ debugLog("[fluent zerodev] sendTransaction", {
6809
+ signerMode: executionKernel.signerMode,
6810
+ smartAccountAddress: executionKernel.smartAccountAddress,
6811
+ to: request.to,
6812
+ hasData: Boolean(request.data && request.data !== "0x"),
6813
+ value: (request.value ?? 0n).toString()
6814
+ });
6815
+ try {
6816
+ const hash = await executionKernel.client.sendTransaction({
6817
+ account: executionKernel.account,
6818
+ chain: executionKernel.chain,
6819
+ to: request.to,
6820
+ data: request.data ?? "0x",
6821
+ value: request.value ?? 0n
6822
+ });
6823
+ debugLog("[fluent zerodev] sendTransaction submitted", { hash });
6824
+ return hash;
6825
+ } catch (err) {
6826
+ debugError("[fluent zerodev] sendTransaction failed", err);
6827
+ throw err;
6828
+ }
6829
+ },
6830
+ [authenticated, embeddedWallet, error, hostedSigner, initialize2, kernels.prompt, ready]
6831
+ );
6832
+ const createSponsoredClient = useCallback(async (kernel) => {
6833
+ if (!hookOptions.sponsorshipUrl || !hookOptions.appId) return null;
6834
+ if (sponsorshipUnavailable.current) return null;
6835
+ const accessToken = await getAccessToken();
6836
+ if (!accessToken) return null;
6837
+ return createKernelAccountClient({
6838
+ account: kernel.account,
6839
+ chain: kernel.chain,
6840
+ bundlerTransport: createFluentBundlerTransport(kernel.zeroDevRpcUrl),
6841
+ client: kernel.publicClient,
6842
+ paymaster: createFluentZeroDevSponsoredPaymaster({
6843
+ chain: kernel.chain,
6844
+ accessToken,
6845
+ rpcUrl: createFluentSponsorshipRpcUrl({
6846
+ sponsorshipUrl: hookOptions.sponsorshipUrl,
6847
+ appId: hookOptions.appId
6848
+ })
6849
+ })
6850
+ });
6851
+ }, [getAccessToken, hookOptions.appId, hookOptions.sponsorshipUrl]);
6852
+ const sendCalls = useCallback(
6853
+ async (calls, options) => {
6854
+ const signerMode = confirmationToSignerMode(options?.confirmation ?? "always");
6855
+ const cachedKernel = kernels[signerMode];
6856
+ const hasAuthorizationSession = signerMode === "silent" && Boolean(hookOptions.authorizationSession?.serializedPermissionAccount) && (hookOptions.authorizationSession?.expiresAt ?? 0) > Math.floor(Date.now() / 1e3);
6857
+ if (cachedKernel?.signerSource === "hosted" || !cachedKernel && !hasAuthorizationSession && hostedSigner && !(ready && authenticated && embeddedWallet)) {
6858
+ hostedSigner?.prepare(options?.confirmation ?? "always");
6859
+ }
6860
+ const executionKernel = cachedKernel ?? await initialize2({ signerMode, throwOnError: true });
6861
+ if (!executionKernel) throw new Error(error?.message ?? "ZeroDev smart account is not ready");
6862
+ const gasToken = options?.gasPayment?.symbol ? getFluentGasTokenAddress(options.gasPayment.symbol, network) : void 0;
6863
+ const preparedCalls = [...calls];
6864
+ if (gasToken && options?.gasPayment?.includeApproval) {
6865
+ preparedCalls.unshift(await createFluentZeroDevErc20PaymasterApprovalCall({
6866
+ chain: executionKernel.chain,
6867
+ gasToken,
6868
+ approveAmount: options.gasPayment.approveAmount
6869
+ }));
6870
+ }
6871
+ debugLog("[fluent zerodev] sendCalls", {
6872
+ signerMode,
6873
+ smartAccountAddress: executionKernel.smartAccountAddress,
6874
+ gasToken,
6875
+ gasTokenSymbol: options?.gasPayment?.symbol,
6876
+ sponsorship: options?.gasPayment?.sponsorship ?? "auto",
6877
+ approvalIncluded: Boolean(gasToken && options?.gasPayment?.includeApproval),
6878
+ calls: preparedCalls.map((call) => ({
6879
+ to: call.to,
6880
+ hasData: Boolean(call.data && call.data !== "0x"),
6881
+ value: (call.value ?? 0n).toString()
6882
+ }))
6883
+ });
6884
+ setPromptSigningContext({
6885
+ intent: "transaction",
6886
+ gasTokenSymbol: options?.gasPayment?.symbol
6887
+ });
6888
+ try {
6889
+ const callArgs = {
6890
+ account: executionKernel.account,
6891
+ calls: preparedCalls.map((call) => ({
6892
+ to: call.to,
6893
+ data: call.data ?? "0x",
6894
+ value: call.value ?? 0n
6895
+ }))
6896
+ };
6897
+ const sponsorshipRefused = !gasToken && options?.gasPayment?.sponsorship === "never";
6898
+ const sponsoredClient = gasToken || sponsorshipRefused ? null : await createSponsoredClient(executionKernel);
6899
+ const executionClient = gasToken ? createFluentZeroDevErc20ExecutionClient(executionKernel, gasToken) : sponsoredClient ?? executionKernel.client;
6900
+ let sponsorshipReason;
6901
+ if (sponsorshipRefused) {
6902
+ sponsorshipReason = "not_requested";
6903
+ } else if (!gasToken && !sponsoredClient && hookOptions.sponsorshipUrl && hookOptions.appId) {
6904
+ sponsorshipReason = sponsorshipUnavailable.current ? "unauthorized" : "no_token";
6905
+ }
6906
+ let settlementClient = executionClient;
6907
+ let userOpHash;
6908
+ try {
6909
+ userOpHash = await executionClient.sendUserOperation(callArgs);
6910
+ } catch (err) {
6911
+ if (!sponsoredClient) throw err;
6912
+ const failure = getSponsorshipFailure(err);
6913
+ sponsorshipReason = failure.reason;
6914
+ if (failure.disableSponsorship) sponsorshipUnavailable.current = true;
6915
+ debugWarn("[fluent zerodev] sponsorship unavailable, paying own gas", {
6916
+ reason: sponsorshipReason
6917
+ });
6918
+ settlementClient = executionKernel.client;
6919
+ userOpHash = await executionKernel.client.sendUserOperation(callArgs);
6920
+ }
6921
+ debugLog("[fluent zerodev] sendCalls userOp submitted", { userOpHash });
6922
+ const receipt = await settlementClient.waitForUserOperationReceipt({
6923
+ hash: userOpHash
6924
+ });
6925
+ const paymaster = readUserOperationPaymaster(receipt);
6926
+ const sponsored = gasToken ? false : paymaster ? paymaster !== zeroAddress : Boolean(sponsoredClient);
6927
+ if (!gasToken && sponsoredClient && !sponsored) sponsorshipReason ??= "denied";
6928
+ debugLog("[fluent zerodev] sendCalls receipt", {
6929
+ userOpHash,
6930
+ success: receipt.success,
6931
+ reason: receipt.reason,
6932
+ transactionHash: receipt.receipt.transactionHash,
6933
+ sponsored,
6934
+ paymaster,
6935
+ sponsorshipReason
6936
+ });
6937
+ if (!receipt.success) {
6938
+ throw new Error(receipt.reason ?? `UserOperation ${userOpHash} execution failed`);
6939
+ }
6940
+ return {
6941
+ hash: receipt.receipt.transactionHash,
6942
+ sponsored,
6943
+ sponsorshipReason,
6944
+ paymaster
6945
+ };
6946
+ } catch (err) {
6947
+ debugError("[fluent zerodev] sendCalls failed", err);
6948
+ throw err;
6949
+ } finally {
6950
+ clearPromptSigningContext();
6951
+ }
6952
+ },
6953
+ [
6954
+ authenticated,
6955
+ createSponsoredClient,
6956
+ embeddedWallet,
6957
+ error,
6958
+ hostedSigner,
6959
+ hookOptions.authorizationSession,
6960
+ hookOptions.appId,
6961
+ hookOptions.sponsorshipUrl,
6962
+ initialize2,
6963
+ kernels,
6964
+ network,
6965
+ ready
6966
+ ]
7179
6967
  );
7180
- }
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
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");
7206
6975
  }
7207
- );
6976
+ const executionKernel = await initialize2({ signerMode, throwOnError: true });
6977
+ if (!executionKernel) throw new Error(error?.message ?? "ZeroDev smart account is not ready");
6978
+ return executionKernel;
6979
+ }, [authenticated, error, hostedSigner, initialize2, kernels, login, ready]);
6980
+ return {
6981
+ smartAccountEnabled: Boolean(FLUENT_CONNECT_ZERODEV_PROJECT_ID),
6982
+ smartAccountReady,
6983
+ smartAccountAddress: activeKernel?.smartAccountAddress,
6984
+ signerAddress: embeddedWallet?.address ?? hookOptions.sessionSignerAddress,
6985
+ privyReady: ready,
6986
+ privyAuthenticated: authenticated,
6987
+ embeddedWalletCount: wallets.filter((wallet) => wallet.walletClientType === "privy").length,
6988
+ authenticate: login,
6989
+ kernel: activeKernel,
6990
+ signerModesReady: Object.keys(kernels),
6991
+ error,
6992
+ ensureExecutionReady,
6993
+ sendTransaction,
6994
+ sendCalls,
6995
+ refresh: () => initialize2({ throwOnError: true, signerMode: "prompt" })
6996
+ };
7208
6997
  }
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
7219
- }
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()
7220
7007
  );
7008
+ const topic = event?.topics[3];
7009
+ if (!topic || topic.length !== 66) return void 0;
7010
+ return getAddress(`0x${topic.slice(26)}`);
7221
7011
  }
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
- );
7012
+ function getZeroDevReadinessMessage(params) {
7013
+ if (!params.ready) return "Privy wallet context is still loading";
7014
+ if (params.hostedSignerAvailable) return "Fluent hosted signer is preparing";
7015
+ if (!params.authenticated) return "Fluent session is connected, but Privy embedded wallet is not authenticated on this page";
7016
+ if (params.embeddedWalletCount === 0) {
7017
+ return `Privy is authenticated, but no embedded wallet is available (${params.walletCount} linked wallets found)`;
7018
+ }
7019
+ return "Fluent ZeroDev account is still preparing. Try again in a moment.";
7231
7020
  }
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
- }
7021
+ async function createFluentZeroDevPermissionSession(params) {
7022
+ const sessionAccount = privateKeyToAccount(params.sessionPrivateKey);
7023
+ const signer = await toECDSASigner({ signer: sessionAccount });
7024
+ const policies = [
7025
+ toCallPolicy({
7026
+ policyVersion: CallPolicyVersion.V0_0_5,
7027
+ permissions: params.calls.map(
7028
+ (call) => call.abi && call.functionName ? {
7029
+ target: call.target,
7030
+ abi: call.abi,
7031
+ functionName: call.functionName,
7032
+ args: call.args,
7033
+ callType: call.callType,
7034
+ valueLimit: call.valueLimit ?? 0n
7035
+ } : {
7036
+ target: call.target,
7037
+ selector: call.selector,
7038
+ callType: call.callType,
7039
+ valueLimit: call.valueLimit ?? 0n
7040
+ }
7041
+ )
7042
+ })
7043
+ ];
7044
+ if (params.expiresAt) {
7045
+ policies.push(toTimestampPolicy({ validUntil: params.expiresAt }));
7046
+ }
7047
+ const permissionPlugin = await toPermissionValidator(params.kernel.publicClient, {
7048
+ signer,
7049
+ policies,
7050
+ entryPoint: getEntryPoint("0.7"),
7051
+ kernelVersion: KERNEL_V3_3
7052
+ });
7053
+ const serializedPermissionAccount = await serializePermissionAccount(
7054
+ params.kernel.account,
7055
+ params.sessionPrivateKey,
7056
+ void 0,
7057
+ void 0,
7058
+ permissionPlugin,
7059
+ true
7243
7060
  );
7061
+ return {
7062
+ serializedPermissionAccount,
7063
+ sessionSignerAddress: sessionAccount.address,
7064
+ smartAccountAddress: params.kernel.smartAccountAddress
7065
+ };
7244
7066
  }
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
- );
7067
+ function confirmationToSignerMode(confirmation) {
7068
+ return confirmation === "session" ? "silent" : "prompt";
7259
7069
  }
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
- }
7070
+ async function createFluentZeroDevAuthorizedSessionKernel(authorizationSession, chain) {
7071
+ const zeroDevRpcUrl = `https://rpc.zerodev.app/api/v3/${FLUENT_CONNECT_ZERODEV_PROJECT_ID}/chain/${chain.id}`;
7072
+ const publicClient = createPublicClient({
7073
+ chain,
7074
+ transport: createFluentRpcTransport(chain)
7075
+ });
7076
+ const entryPoint = getEntryPoint("0.7");
7077
+ const sessionSigner = await toECDSASigner({
7078
+ signer: privateKeyToAccount(authorizationSession.sessionPrivateKey)
7079
+ });
7080
+ const account = await deserializePermissionAccount(
7081
+ publicClient,
7082
+ entryPoint,
7083
+ KERNEL_V3_3,
7084
+ authorizationSession.serializedPermissionAccount,
7085
+ sessionSigner
7279
7086
  );
7280
- }
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" });
7291
- }
7292
- if (type === "error") {
7293
- icon = /* @__PURE__ */ jsx(OctagonXIcon, { className: "text-destructive", "aria-hidden": "true" });
7294
- }
7295
- if (type === "loading") {
7296
- icon = /* @__PURE__ */ jsx(Loader2Icon, { className: "animate-spin", "aria-hidden": "true" });
7087
+ const client2 = createKernelAccountClient({
7088
+ account,
7089
+ chain,
7090
+ bundlerTransport: createFluentBundlerTransport(zeroDevRpcUrl),
7091
+ client: publicClient
7092
+ });
7093
+ return {
7094
+ account,
7095
+ client: client2,
7096
+ publicClient,
7097
+ smartAccountAddress: account.address,
7098
+ zeroDevRpcUrl,
7099
+ chain,
7100
+ signerMode: "silent",
7101
+ signerSource: "session"
7102
+ };
7103
+ }
7104
+ async function createFluentZeroDevKernel(params) {
7105
+ if (!params.wallet && !params.hostedSigner) throw new Error("Fluent signer is unavailable");
7106
+ if (params.wallet) {
7107
+ debugLog("[fluent zerodev] ensuring Fluent chain", params.chain.id);
7108
+ await ensureWalletOnFluentChain(params.wallet, params.chain);
7109
+ debugLog("[fluent zerodev] Fluent chain ready", params.chain.id);
7297
7110
  }
7298
- if (!icon) {
7299
- return null;
7111
+ const zeroDevRpcUrl = `https://rpc.zerodev.app/api/v3/${FLUENT_CONNECT_ZERODEV_PROJECT_ID}/chain/${params.chain.id}`;
7112
+ const publicClient = createPublicClient({
7113
+ chain: params.chain,
7114
+ transport: createFluentRpcTransport(params.chain)
7115
+ });
7116
+ const entryPoint = getEntryPoint("0.7");
7117
+ let signer;
7118
+ if (params.hostedSigner) {
7119
+ signer = toHostedSignerLocalAccount(params.hostedSigner, params.signerMode);
7120
+ } else if (params.wallet && params.signerMode === "prompt") {
7121
+ signer = toPromptedPrivyLocalAccount(params.wallet, params.promptedSigners, params.chain);
7122
+ } else if (params.wallet) {
7123
+ signer = toSilentPrivyLocalAccount(params.wallet, params.chain);
7124
+ } else {
7125
+ throw new Error("Fluent signer is unavailable");
7300
7126
  }
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
7127
+ const ecdsaValidator = await signerToEcdsaValidator(publicClient, {
7128
+ signer,
7129
+ entryPoint,
7130
+ kernelVersion: KERNEL_V3_3
7131
+ });
7132
+ const account = await createKernelAccount(publicClient, {
7133
+ entryPoint,
7134
+ plugins: { sudo: ecdsaValidator },
7135
+ kernelVersion: KERNEL_V3_3
7136
+ });
7137
+ const client2 = createKernelAccountClient({
7138
+ account,
7139
+ chain: params.chain,
7140
+ bundlerTransport: createFluentBundlerTransport(zeroDevRpcUrl),
7141
+ client: publicClient
7142
+ });
7143
+ return {
7144
+ account,
7145
+ client: client2,
7146
+ publicClient,
7147
+ smartAccountAddress: account.address,
7148
+ zeroDevRpcUrl,
7149
+ chain: params.chain,
7150
+ signerMode: params.signerMode,
7151
+ signerSource: params.hostedSigner ? "hosted" : "privy"
7152
+ };
7153
+ }
7154
+ function toHostedSignerLocalAccount(signer, signerMode) {
7155
+ const confirmation = signerMode === "silent" ? "session" : "always";
7156
+ const source = {
7157
+ address: signer.address,
7158
+ async signMessage({ message }) {
7159
+ return signer.signMessage(formatSignableMessageForPrivy(message), confirmation);
7160
+ },
7161
+ async signTransaction() {
7162
+ throw new Error("Fluent ZeroDev signer does not sign raw transactions");
7163
+ },
7164
+ async signTypedData(typedData) {
7165
+ return signer.signTypedData(
7166
+ {
7167
+ domain: typedData.domain,
7168
+ types: typedData.types,
7169
+ primaryType: typedData.primaryType,
7170
+ message: typedData.message
7171
+ },
7172
+ confirmation
7173
+ );
7307
7174
  }
7308
- );
7175
+ };
7176
+ return toAccount(source);
7309
7177
  }
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));
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
+ });
7323
7189
  }
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
- ] });
7190
+ var promptSigningContext = {};
7191
+ function setPromptSigningContext(context) {
7192
+ promptSigningContext = context;
7333
7193
  }
7334
- Toast$1.createToastManager;
7335
- Toast$1.useToastManager;
7336
-
7337
- // src/utils/formatAddress.ts
7338
- function formatAddress(address) {
7339
- return `${address.slice(0, 6)}...${address.slice(-4)}`;
7194
+ function clearPromptSigningContext() {
7195
+ promptSigningContext = {};
7340
7196
  }
7341
-
7342
- // src/utils/copyAddress.ts
7343
- async function copyAddressToClipboard(address) {
7197
+ async function withFluentSignaturePrompt(sign) {
7198
+ setPromptSigningContext({ intent: "signature" });
7344
7199
  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
- });
7200
+ return await sign();
7201
+ } finally {
7202
+ clearPromptSigningContext();
7358
7203
  }
7359
7204
  }
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
7371
- };
7205
+ function buildPromptSigningUiOptions() {
7206
+ if (promptSigningContext.intent === "signature") {
7207
+ return {
7208
+ title: "Sign with Fluent",
7209
+ description: "Sign this request with your Fluent account. Nothing is sent on chain.",
7210
+ buttonText: "Sign"
7211
+ };
7212
+ }
7213
+ const gasTokenSymbol = promptSigningContext.gasTokenSymbol;
7372
7214
  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
7215
+ title: "Confirm Fluent transaction",
7216
+ description: gasTokenSymbol ? `Gas will be paid in ${gasTokenSymbol}. Confirm this Fluent transaction.` : "Confirm this Fluent transaction.",
7217
+ buttonText: "Sign"
7218
+ };
7219
+ }
7220
+ function toPromptedPrivyLocalAccount(wallet, promptedSigners, chain) {
7221
+ const source = {
7222
+ address: wallet.address,
7223
+ async signMessage({ message }) {
7224
+ await ensureWalletOnFluentChain(wallet, chain);
7225
+ const { signature } = await promptedSigners.signMessage(
7226
+ { message: formatSignableMessageForPrivy(message) },
7227
+ {
7228
+ address: wallet.address,
7229
+ uiOptions: buildPromptSigningUiOptions()
7230
+ }
7231
+ );
7232
+ return signature;
7379
7233
  },
7380
- wallet: {
7381
- signerAddress: params.signerAddress,
7382
- smartAccountAddress: params.smartAccountAddress
7234
+ async signTransaction() {
7235
+ throw new Error("Fluent ZeroDev signer does not sign raw transactions");
7383
7236
  },
7384
- scopes: params.scopes,
7385
- issuedAt,
7386
- metadata: {
7387
- authMode: "direct",
7388
- origin: params.app.origin
7237
+ async signTypedData(typedData) {
7238
+ await ensureWalletOnFluentChain(wallet, chain);
7239
+ const { signature } = await promptedSigners.signTypedData(
7240
+ {
7241
+ domain: typedData.domain,
7242
+ types: typedData.types,
7243
+ primaryType: typedData.primaryType,
7244
+ message: typedData.message
7245
+ },
7246
+ {
7247
+ address: wallet.address,
7248
+ uiOptions: buildPromptSigningUiOptions()
7249
+ }
7250
+ );
7251
+ return signature;
7252
+ }
7253
+ };
7254
+ return toAccount(source);
7255
+ }
7256
+ function toSilentPrivyLocalAccount(wallet, chain) {
7257
+ const source = {
7258
+ address: wallet.address,
7259
+ async signMessage({ message }) {
7260
+ debugLog("[fluent zerodev] requesting embedded provider signature", {
7261
+ signerAddress: wallet.address,
7262
+ messageKind: typeof message === "string" ? "string" : "raw" in message ? "raw" : typeof message
7263
+ });
7264
+ await ensureWalletOnFluentChain(wallet, chain);
7265
+ const provider = await wallet.getEthereumProvider();
7266
+ if (!provider?.request) throw new Error("Fluent embedded wallet provider is unavailable");
7267
+ const formattedMessage = formatSignableMessageForPrivy(message);
7268
+ try {
7269
+ const signature = await provider.request({
7270
+ method: "personal_sign",
7271
+ params: [isHex(formattedMessage) ? formattedMessage : stringToHex(formattedMessage), wallet.address]
7272
+ });
7273
+ if (typeof signature !== "string") throw new Error("Privy embedded wallet returned an invalid signature");
7274
+ debugLog("[fluent zerodev] embedded provider signature ready", {
7275
+ signerAddress: wallet.address,
7276
+ signatureLength: signature.length
7277
+ });
7278
+ return signature;
7279
+ } catch (err) {
7280
+ debugError("[fluent zerodev] embedded provider signature failed", err);
7281
+ throw err;
7282
+ }
7283
+ },
7284
+ async signTransaction() {
7285
+ throw new Error("Fluent ZeroDev signer does not sign raw transactions");
7286
+ },
7287
+ async signTypedData(typedData) {
7288
+ debugLog("[fluent zerodev] requesting embedded provider typed-data signature", {
7289
+ signerAddress: wallet.address,
7290
+ primaryType: typedData.primaryType
7291
+ });
7292
+ await ensureWalletOnFluentChain(wallet, chain);
7293
+ const provider = await wallet.getEthereumProvider();
7294
+ if (!provider?.request) throw new Error("Fluent embedded wallet provider is unavailable");
7295
+ try {
7296
+ const signature = await provider.request({
7297
+ method: "eth_signTypedData_v4",
7298
+ params: [
7299
+ wallet.address,
7300
+ stringifyTypedDataForProvider({
7301
+ domain: typedData.domain,
7302
+ types: typedData.types,
7303
+ primaryType: typedData.primaryType,
7304
+ message: typedData.message
7305
+ })
7306
+ ]
7307
+ });
7308
+ if (typeof signature !== "string") {
7309
+ throw new Error("Privy embedded wallet returned an invalid typed-data signature");
7310
+ }
7311
+ debugLog("[fluent zerodev] embedded provider typed-data signature ready", {
7312
+ signerAddress: wallet.address,
7313
+ signatureLength: signature.length
7314
+ });
7315
+ return signature;
7316
+ } catch (err) {
7317
+ debugError("[fluent zerodev] embedded provider typed-data signature failed", err);
7318
+ throw err;
7319
+ }
7389
7320
  }
7390
7321
  };
7322
+ return toAccount(source);
7391
7323
  }
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();
7324
+ function stringifyTypedDataForProvider(value) {
7325
+ return stringifyWithBigInt(value);
7402
7326
  }
7403
- function isAlreadyClaimed(status, message) {
7404
- const statusNorm = normalize(status);
7405
- const messageNorm = normalize(message);
7406
- return statusNorm.includes("already") || messageNorm.includes("already");
7327
+ function formatSignableMessageForPrivy(message) {
7328
+ if (typeof message === "string") return message;
7329
+ if ("raw" in message) return typeof message.raw === "string" ? message.raw : bytesToHex(message.raw);
7330
+ return String(message);
7407
7331
  }
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;
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);
7416
7338
  }
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
- });
7422
- }
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."
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 }]
7430
7347
  });
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."
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 }]
7438
7365
  });
7439
- return;
7440
7366
  }
7441
- toast.add({
7442
- type: "error",
7443
- title: "Faucet request failed",
7444
- description: error.message || `Request failed with ${error.status}`
7445
- });
7367
+ const nextChainId = await getProviderChainId(provider);
7368
+ debugLog("[fluent zerodev] provider chain after switch", nextChainId);
7369
+ if (nextChainId !== targetChainId) {
7370
+ throw new Error(`Unsupported chainId ${Number(BigInt(nextChainId))}; switch to ${chain.name}`);
7371
+ }
7446
7372
  return;
7447
7373
  }
7448
- toast.add({
7449
- type: "error",
7450
- title: "Faucet request failed",
7451
- description: error instanceof Error ? error.message : "Something went wrong."
7452
- });
7374
+ throw new Error("Fluent embedded wallet provider is unavailable");
7453
7375
  }
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
7471
- );
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();
7380
+ }
7381
+ function isUnknownChainError(err) {
7382
+ const code = err?.code;
7383
+ const nestedCode = err?.data?.originalError?.code;
7384
+ return code === 4902 || nestedCode === 4902;
7472
7385
  }
7473
7386
 
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
7387
+ // src/widget/permissionSession.ts
7388
+ function createFluentPermissionApi(executor) {
7389
+ return {
7390
+ createPermissionSession: (input) => createFluentPermissionSession(input, executor),
7391
+ policies: createFluentPermissionPolicyBuilders()
7392
+ };
7393
+ }
7394
+ function createFluentPermissionPolicyBuilders() {
7395
+ return {
7396
+ call: (input) => ({
7397
+ kind: "call",
7398
+ id: input.id,
7399
+ call: input
7400
+ }),
7401
+ batch: (input) => ({
7402
+ kind: "batch",
7403
+ id: input.id,
7404
+ calls: input.calls
7405
+ })
7406
+ };
7407
+ }
7408
+ async function createFluentPermissionSession(input, executor) {
7409
+ if (!executor?.kernel || executor.smartAccountReady === false) {
7410
+ throw new Error("ZeroDev smart account is not ready");
7411
+ }
7412
+ if (input.policies.length === 0) {
7413
+ throw new Error("A permission session requires at least one policy");
7414
+ }
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
7483
7424
  });
7425
+ return {
7426
+ ...permission,
7427
+ label: input.label,
7428
+ delegate: input.delegate,
7429
+ expiresAt,
7430
+ policies: input.policies
7431
+ };
7484
7432
  }
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;
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
+ };
7491
7444
  }
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");
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 };
7496
7459
  }
7497
- if (balance.decimals <= maximumFractionDigits) {
7498
- return formatFluentLocaleAmount(balance.formatted, maximumFractionDigits);
7460
+ if ("max" in rule) {
7461
+ return { condition: ParamCondition.LESS_THAN_OR_EQUAL, value: rule.max };
7499
7462
  }
7500
- const maxDigits = Math.max(
7501
- maximumFractionDigits,
7502
- Math.min(balance.decimals, GAS_BALANCE_MAX_FRACTION_DIGITS)
7463
+ return { condition: ParamCondition.GREATER_THAN_OR_EQUAL, value: rule.min };
7464
+ }
7465
+ function findAbiFunction(abi, functionName) {
7466
+ const matches = abi.filter(
7467
+ (item) => item.type === "function" && item.name === functionName
7503
7468
  );
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);
7508
- }
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
+ );
7509
7473
  }
7510
- return formatFluentLocaleAmount(0, maximumFractionDigits);
7474
+ return matches[0];
7475
+ }
7476
+ function toUnixSeconds(value) {
7477
+ if (value === void 0) return void 0;
7478
+ if (value instanceof Date) return Math.floor(value.getTime() / 1e3);
7479
+ return value > 1e12 ? Math.floor(value / 1e3) : Math.floor(value);
7511
7480
  }
7512
7481
 
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
7482
+ // package.json
7483
+ var version = "0.3.1";
7484
+
7485
+ // src/core/analytics.ts
7486
+ var INSTANCE_NAME = "fluent";
7487
+ var POSTHOG_UI_HOST = "https://us.posthog.com";
7488
+ var BLOCK_SELECTOR = 'body > *:not([data-slot="dialog-portal"]):not([data-slot="drawer-portal"])';
7489
+ var UNLOAD_CAPTURE_OPTIONS = {
7490
+ transport: "sendBeacon",
7491
+ send_instantly: true
7492
+ };
7493
+ var client = null;
7494
+ var loading = null;
7495
+ var loadFailed = false;
7496
+ var pending = [];
7497
+ var widgetLoadedTracked = false;
7498
+ function analyticsEnabled(config) {
7499
+ return !config.disableAnalytics && Boolean(config.analyticsHost);
7500
+ }
7501
+ function initFluentAnalytics(config) {
7502
+ if (!analyticsEnabled(config) || loading) return;
7503
+ loading = import('posthog-js').then(({ default: posthog }) => {
7504
+ client = posthog.init(
7505
+ FLUENT_CONNECT_POSTHOG_TOKEN,
7506
+ {
7507
+ api_host: config.analyticsHost,
7508
+ ui_host: POSTHOG_UI_HOST,
7509
+ persistence: "localStorage",
7510
+ // The widget is a guest in someone else's page — no automatic collection.
7511
+ // Every one of these must be set explicitly: the project's remote config
7512
+ // turns performance capture, heatmaps and console recording ON, so leaving
7513
+ // an option out is not the same as switching it off.
7514
+ autocapture: false,
7515
+ capture_pageview: false,
7516
+ capture_pageleave: false,
7517
+ rageclick: false,
7518
+ capture_performance: false,
7519
+ capture_heatmaps: false,
7520
+ capture_dead_clicks: false,
7521
+ // Widget console logs carry session ids and wallet addresses.
7522
+ enable_recording_console_log: false,
7523
+ session_recording: { blockSelector: BLOCK_SELECTOR }
7528
7524
  },
7529
- scopes: session.scopes,
7530
- issuedAt: session.issuedAt,
7531
- idToken: session.idToken
7532
- },
7533
- null,
7534
- 2
7535
- );
7525
+ INSTANCE_NAME
7526
+ );
7527
+ for (const queued of pending.splice(0)) {
7528
+ capture(queued.eventName, queued.payload, queued.unload);
7529
+ }
7530
+ }).catch(() => {
7531
+ loadFailed = true;
7532
+ pending = [];
7533
+ });
7536
7534
  }
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;
7535
+ function sanitise(properties) {
7536
+ if (!properties) return properties;
7537
+ const safe = {};
7538
+ for (const [key, value] of Object.entries(properties)) {
7539
+ const type = typeof value;
7540
+ if (value === null || type === "string" || type === "number" || type === "boolean") {
7541
+ safe[key] = value;
7542
+ }
7543
+ }
7544
+ return safe;
7546
7545
  }
7547
-
7548
- // src/utils/getHighResTwitterAvatar.ts
7549
- function getHighResTwitterAvatar(url) {
7550
- if (!url) return "";
7551
- return url.replace("_normal", "");
7546
+ function capture(eventName, payload, unload) {
7547
+ if (unload) {
7548
+ client?.capture(eventName, payload, UNLOAD_CAPTURE_OPTIONS);
7549
+ return;
7550
+ }
7551
+ client?.capture(eventName, payload);
7552
7552
  }
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;
7553
+ function send(eventName, payload, unload) {
7554
+ if (client) {
7555
+ capture(eventName, payload, unload);
7556
+ return;
7561
7557
  }
7558
+ if (loadFailed) return;
7559
+ pending.push({ eventName, payload, unload });
7560
+ }
7561
+ function createTracker(config, getContext) {
7562
+ const enabled = analyticsEnabled(config);
7563
+ if (enabled) initFluentAnalytics(config);
7564
+ const base = {
7565
+ app_id: config.appId,
7566
+ network: config.network,
7567
+ auth_mode: config.authMode,
7568
+ source: config.source,
7569
+ campaign: config.campaign,
7570
+ sdk_version: version
7571
+ };
7572
+ const track = (eventName, properties, options) => {
7573
+ if (!enabled) return;
7574
+ const payload = { ...sanitise(properties), ...base, ...getContext?.() };
7575
+ send(eventName, payload, Boolean(options?.unload));
7576
+ };
7577
+ track.live = enabled;
7578
+ return track;
7579
+ }
7580
+ function trackWidgetLoadedOnce(track, properties) {
7581
+ if (widgetLoadedTracked) return;
7582
+ track("widget_loaded", properties);
7583
+ if (track.live) widgetLoadedTracked = true;
7562
7584
  }
7563
7585
  var REOWN_PROJECT_ID = FLUENT_CONNECT_REOWN_PROJECT_ID;
7564
7586
  var queryClient = new QueryClient();
@@ -9620,12 +9642,16 @@ function useIsMobile() {
9620
9642
  }, []);
9621
9643
  return !!isMobile;
9622
9644
  }
9623
- function BatchOperationReviewModal({
9624
- operation,
9645
+ function ReviewDialog({
9646
+ eyebrow,
9647
+ title,
9648
+ ariaLabel,
9649
+ address,
9650
+ footnote,
9625
9651
  onConfirm,
9626
- onCancel
9652
+ onCancel,
9653
+ children
9627
9654
  }) {
9628
- if (!operation) return null;
9629
9655
  return /* @__PURE__ */ jsx(
9630
9656
  "div",
9631
9657
  {
@@ -9640,48 +9666,21 @@ function BatchOperationReviewModal({
9640
9666
  className: "w-full max-w-[520px] rounded-[18px] border border-[#49eded]/30 bg-[#030213] p-[18px] text-white shadow-2xl",
9641
9667
  role: "dialog",
9642
9668
  "aria-modal": "true",
9643
- "aria-label": "Confirm Fluent transaction",
9669
+ "aria-label": ariaLabel,
9644
9670
  children: [
9645
9671
  /* @__PURE__ */ jsxs("div", { className: "mb-3.5 flex items-start justify-between gap-3", children: [
9646
9672
  /* @__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" })
9673
+ /* @__PURE__ */ jsx("span", { className: "text-xs font-black uppercase text-[#49eded]", children: eyebrow }),
9674
+ /* @__PURE__ */ jsx("h2", { className: "mt-1 text-2xl leading-[30px] font-medium", children: title })
9649
9675
  ] }),
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
- )
9676
+ /* @__PURE__ */ jsx(Button, { type: "button", variant: "secondary", size: "icon", "aria-label": "Close", onClick: onCancel, children: "x" })
9661
9677
  ] }),
9662
9678
  /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-3 rounded-xl border border-[#49eded]/20 bg-[#49eded]/10 p-3", children: [
9663
9679
  /* @__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" })
9680
+ /* @__PURE__ */ jsx("strong", { className: "text-sm", children: address ? formatAddress(address) : "Fluent account" })
9665
9681
  ] }),
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." }),
9682
+ children,
9683
+ /* @__PURE__ */ jsx("p", { className: "text-xs leading-[18px] text-white/65", children: footnote }),
9685
9684
  /* @__PURE__ */ jsxs("div", { className: "mt-3 grid grid-cols-[minmax(0,0.8fr)_minmax(0,1.2fr)] gap-2.5", children: [
9686
9685
  /* @__PURE__ */ jsx(Button, { type: "button", variant: "secondary", onClick: onCancel, children: "Cancel" }),
9687
9686
  /* @__PURE__ */ jsx(Button, { type: "button", onClick: onConfirm, children: "Confirm and sign" })
@@ -9692,6 +9691,85 @@ function BatchOperationReviewModal({
9692
9691
  }
9693
9692
  );
9694
9693
  }
9694
+ function BatchOperationReviewModal({
9695
+ operation,
9696
+ onConfirm,
9697
+ onCancel
9698
+ }) {
9699
+ if (!operation) return null;
9700
+ return /* @__PURE__ */ jsx(
9701
+ ReviewDialog,
9702
+ {
9703
+ eyebrow: "Fluent transaction review",
9704
+ title: operation.reviewTitle ?? "Confirm transaction",
9705
+ ariaLabel: "Confirm Fluent transaction",
9706
+ address: operation.account?.address,
9707
+ footnote: "Confirming allows the Fluent embedded signer to sign this ZeroDev UserOperation.",
9708
+ onConfirm,
9709
+ onCancel,
9710
+ children: /* @__PURE__ */ jsx("ul", { className: "my-3 flex list-none flex-col gap-2 p-0", "aria-label": "Transaction calls", children: operation.encodedCalls.map((call, index) => /* @__PURE__ */ jsxs(
9711
+ "li",
9712
+ {
9713
+ className: "flex flex-col gap-1 rounded-xl border border-[#49eded]/20 bg-[#49eded]/10 p-3",
9714
+ children: [
9715
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-3", children: [
9716
+ /* @__PURE__ */ jsx("strong", { className: "text-sm", children: call.label ?? operation.calls[index]?.method ?? operation.calls[index]?.functionName ?? "Contract call" }),
9717
+ /* @__PURE__ */ jsx("span", { className: "text-xs text-white/65", children: formatAddress(call.to) })
9718
+ ] }),
9719
+ call.value > 0n ? /* @__PURE__ */ jsxs("small", { className: "text-xs text-white/65", children: [
9720
+ "Value ",
9721
+ call.value.toString(),
9722
+ " wei"
9723
+ ] }) : null
9724
+ ]
9725
+ },
9726
+ call.id ?? `${call.to}-${index}`
9727
+ )) })
9728
+ }
9729
+ );
9730
+ }
9731
+ function formatMessage(message) {
9732
+ if (typeof message === "string") return message;
9733
+ return typeof message.raw === "string" ? message.raw : bytesToHex(message.raw);
9734
+ }
9735
+ var ROW = "rounded-xl border border-[#49eded]/20 bg-[#49eded]/10 p-3";
9736
+ var CODE = "max-h-60 overflow-auto whitespace-pre-wrap break-all text-xs";
9737
+ function SignatureReviewModal({
9738
+ review,
9739
+ onConfirm,
9740
+ onCancel
9741
+ }) {
9742
+ if (!review) return null;
9743
+ return /* @__PURE__ */ jsx(
9744
+ ReviewDialog,
9745
+ {
9746
+ eyebrow: "Fluent signature review",
9747
+ title: review.kind === "message" ? "Sign message" : "Sign typed data",
9748
+ ariaLabel: "Confirm Fluent signature",
9749
+ address: review.address,
9750
+ footnote: review.account.type === "smart" ? "Confirming signs this request with your Fluent ID. Nothing is sent on chain." : "Confirming opens your wallet's own signature prompt. Nothing is sent on chain.",
9751
+ onConfirm,
9752
+ onCancel,
9753
+ children: /* @__PURE__ */ jsxs("div", { className: "my-3 flex flex-col gap-2", children: [
9754
+ /* @__PURE__ */ jsxs("div", { className: `flex items-center justify-between gap-3 ${ROW}`, children: [
9755
+ /* @__PURE__ */ jsx("span", { className: "text-xs text-white/65", children: "Requested by" }),
9756
+ /* @__PURE__ */ jsx("strong", { className: "break-all text-sm", children: review.origin })
9757
+ ] }),
9758
+ review.kind === "message" ? /* @__PURE__ */ jsx("pre", { className: `${ROW} ${CODE}`, "aria-label": "Message", children: formatMessage(review.message) }) : /* @__PURE__ */ jsxs(Fragment, { children: [
9759
+ /* @__PURE__ */ jsxs("div", { className: `flex flex-col gap-1 ${ROW}`, children: [
9760
+ /* @__PURE__ */ jsx("span", { className: "text-xs text-white/65", children: "Domain" }),
9761
+ /* @__PURE__ */ jsx("pre", { className: CODE, children: stringifyWithBigInt(review.typedData.domain ?? {}, 2) })
9762
+ ] }),
9763
+ /* @__PURE__ */ jsxs("div", { className: `flex items-center justify-between gap-3 ${ROW}`, children: [
9764
+ /* @__PURE__ */ jsx("span", { className: "text-xs text-white/65", children: "Primary type" }),
9765
+ /* @__PURE__ */ jsx("strong", { className: "text-sm", children: review.typedData.primaryType })
9766
+ ] }),
9767
+ /* @__PURE__ */ jsx("pre", { className: `${ROW} ${CODE}`, "aria-label": "Message", children: stringifyWithBigInt(review.typedData.message, 2) })
9768
+ ] })
9769
+ ] })
9770
+ }
9771
+ );
9772
+ }
9695
9773
  function deriveWidgetAccount(input) {
9696
9774
  const { smartAccount, wallet, sessionUserId, sessionSmartAccountAddress, directAuth } = input;
9697
9775
  const fluentAccountAddress = smartAccount.smartAccountAddress ?? sessionSmartAccountAddress;
@@ -9792,41 +9870,67 @@ function useGasPaymentSelection(params) {
9792
9870
  const defaultConfirmationMode = silentSigningEnabled ? "session" : "always";
9793
9871
  return { selectedGasPaymentToken, defaultConfirmationMode };
9794
9872
  }
9795
- function useBatchReview(options) {
9796
- const [batchReview, setBatchReview] = useState(null);
9873
+ function useReviewPrompt(options) {
9874
+ const { label, onOpen } = options;
9875
+ const [review, setReview] = useState(null);
9797
9876
  const resolution = useRef(null);
9798
- const onOpen = options?.onOpen;
9799
- const confirmBatchOperation = useCallback(
9800
- (operation) => {
9877
+ const request = useCallback(
9878
+ (next) => {
9801
9879
  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 };
9880
+ resolution.current?.reject(new Error(`A newer Fluent ${label} review replaced this request`));
9881
+ setReview(next);
9882
+ return new Promise((resolve, reject2) => {
9883
+ resolution.current = { resolve, reject: reject2 };
9808
9884
  });
9809
9885
  },
9810
- [onOpen]
9886
+ [label, onOpen]
9811
9887
  );
9812
- const acceptBatchReview = useCallback(() => {
9888
+ const accept = useCallback(() => {
9813
9889
  resolution.current?.resolve();
9814
9890
  resolution.current = null;
9815
- setBatchReview(null);
9891
+ setReview(null);
9816
9892
  }, []);
9817
- const rejectBatchReview = useCallback(() => {
9818
- resolution.current?.reject(new Error("User rejected Fluent transaction review"));
9893
+ const reject = useCallback(() => {
9894
+ resolution.current?.reject(new Error(`User rejected Fluent ${label} review`));
9819
9895
  resolution.current = null;
9820
- setBatchReview(null);
9896
+ setReview(null);
9821
9897
  }, []);
9822
9898
  useEffect(
9823
9899
  () => () => {
9824
- resolution.current?.reject(new Error("Fluent transaction review was closed"));
9900
+ resolution.current?.reject(new Error(`Fluent ${label} review was closed`));
9825
9901
  resolution.current = null;
9826
9902
  },
9827
- []
9903
+ [label]
9828
9904
  );
9829
- return { batchReview, confirmBatchOperation, acceptBatchReview, rejectBatchReview };
9905
+ return { review, request, accept, reject };
9906
+ }
9907
+
9908
+ // src/widget/hooks/useBatchReview.ts
9909
+ function useBatchReview(options) {
9910
+ const { review, request, accept, reject } = useReviewPrompt({
9911
+ label: "transaction",
9912
+ onOpen: options?.onOpen
9913
+ });
9914
+ return {
9915
+ batchReview: review,
9916
+ confirmBatchOperation: request,
9917
+ acceptBatchReview: accept,
9918
+ rejectBatchReview: reject
9919
+ };
9920
+ }
9921
+
9922
+ // src/widget/hooks/useSignatureReview.ts
9923
+ function useSignatureReview(options) {
9924
+ const { review, request, accept, reject } = useReviewPrompt({
9925
+ label: "signature",
9926
+ onOpen: options?.onOpen
9927
+ });
9928
+ return {
9929
+ signatureReview: review,
9930
+ confirmSignature: request,
9931
+ acceptSignatureReview: accept,
9932
+ rejectSignatureReview: reject
9933
+ };
9830
9934
  }
9831
9935
  function useFaucet(params) {
9832
9936
  const {
@@ -9955,6 +10059,81 @@ function useFluentSession(params) {
9955
10059
  return { session, setSession };
9956
10060
  }
9957
10061
 
10062
+ // src/widget/signRequest.ts
10063
+ function externalWalletSigner(wallet) {
10064
+ const walletClient = wallet.walletClient;
10065
+ const account = walletClient?.account ?? wallet.address;
10066
+ if (!walletClient || !account) return null;
10067
+ const address = typeof account === "string" ? account : account.address;
10068
+ return {
10069
+ address,
10070
+ async resolve() {
10071
+ return {
10072
+ signMessage: ({ message }) => walletClient.signMessage({ account, message }),
10073
+ signTypedData: (typedData) => walletClient.signTypedData({ account, ...typedData })
10074
+ };
10075
+ }
10076
+ };
10077
+ }
10078
+ function createFluentSignApi(executor) {
10079
+ const assertDirectMode = () => {
10080
+ if (executor.authMode === "hosted") {
10081
+ throw new FluentAuthError(
10082
+ "hosted_not_supported",
10083
+ 'Signing needs authMode: "direct" \u2014 there is no hosted signer to ask.'
10084
+ );
10085
+ }
10086
+ };
10087
+ const smartAccountSigner = () => ({
10088
+ address: executor.account.address,
10089
+ async resolve() {
10090
+ const kernel = await executor.ensureReady({ confirmation: "always" });
10091
+ if (kernel.signerSource !== "privy") {
10092
+ throw new FluentAuthError(
10093
+ "root_signer_required",
10094
+ "Only the Fluent ID root signer can sign for the smart account."
10095
+ );
10096
+ }
10097
+ return kernel.account;
10098
+ }
10099
+ });
10100
+ const pickSigner = () => {
10101
+ assertDirectMode();
10102
+ if (executor.account.type === "smart" && executor.account.address) return smartAccountSigner();
10103
+ if (executor.account.type === "eoa") {
10104
+ const signer = executor.wallet ? externalWalletSigner(executor.wallet) : null;
10105
+ if (!signer) throw new FluentAuthError("not_connected", "External wallet has no signer.");
10106
+ return signer;
10107
+ }
10108
+ throw new FluentAuthError("not_connected", "Connect a Fluent ID or an External wallet first.");
10109
+ };
10110
+ return {
10111
+ async signMessage({ message }) {
10112
+ const signer = pickSigner();
10113
+ await executor.confirm({
10114
+ kind: "message",
10115
+ origin: executor.origin,
10116
+ account: executor.account,
10117
+ address: signer.address,
10118
+ message
10119
+ });
10120
+ return (await signer.resolve()).signMessage({ message });
10121
+ },
10122
+ async signTypedData(typedData) {
10123
+ const signer = pickSigner();
10124
+ const request = typedData;
10125
+ await executor.confirm({
10126
+ kind: "typedData",
10127
+ origin: executor.origin,
10128
+ account: executor.account,
10129
+ address: signer.address,
10130
+ typedData: request
10131
+ });
10132
+ return (await signer.resolve()).signTypedData(request);
10133
+ }
10134
+ };
10135
+ }
10136
+
9958
10137
  // src/widget/sendCallsViaExternalWallet.ts
9959
10138
  async function sendCallsViaExternalWallet(calls, wallet, chain, publicClient) {
9960
10139
  const walletClient = wallet.walletClient;
@@ -9993,6 +10172,8 @@ function useWidgetExecution(params) {
9993
10172
  defaultConfirmationMode,
9994
10173
  selectedGasPaymentToken,
9995
10174
  confirmBatchOperation,
10175
+ authMode,
10176
+ confirmSignature,
9996
10177
  refreshBalances,
9997
10178
  track
9998
10179
  } = params;
@@ -10052,15 +10233,43 @@ function useWidgetExecution(params) {
10052
10233
  }),
10053
10234
  [smartAccount.kernel, smartAccount.smartAccountReady]
10054
10235
  );
10236
+ const signApi = useMemo(
10237
+ () => createFluentSignApi({
10238
+ authMode,
10239
+ account: widgetAccount,
10240
+ origin: window.location.origin,
10241
+ confirm: confirmSignature,
10242
+ ensureReady: async (options) => {
10243
+ const kernel = await smartAccount.ensureExecutionReady(options);
10244
+ return {
10245
+ signerSource: kernel.signerSource,
10246
+ account: {
10247
+ signMessage: (params2) => withFluentSignaturePrompt(() => kernel.account.signMessage(params2)),
10248
+ signTypedData: (typedData) => withFluentSignaturePrompt(() => kernel.account.signTypedData(typedData))
10249
+ }
10250
+ };
10251
+ },
10252
+ wallet: wallet?.connected ? wallet : void 0
10253
+ }),
10254
+ [authMode, widgetAccount, confirmSignature, smartAccount.ensureExecutionReady, wallet]
10255
+ );
10055
10256
  return useMemo(
10056
10257
  () => ({
10057
10258
  account: widgetAccount,
10058
10259
  confirmationMode: defaultConfirmationMode,
10059
10260
  gasPayment: selectedGasPaymentToken,
10060
10261
  createBatchOp,
10061
- ...permissionApi
10262
+ ...permissionApi,
10263
+ ...signApi
10062
10264
  }),
10063
- [widgetAccount, defaultConfirmationMode, selectedGasPaymentToken, createBatchOp, permissionApi]
10265
+ [
10266
+ widgetAccount,
10267
+ defaultConfirmationMode,
10268
+ selectedGasPaymentToken,
10269
+ createBatchOp,
10270
+ permissionApi,
10271
+ signApi
10272
+ ]
10064
10273
  );
10065
10274
  }
10066
10275
  function useZeroDevInitializer(params) {
@@ -11091,6 +11300,7 @@ function FluentWidgetContent({
11091
11300
  }, [directAuth, handleDisconnect, openConnectFlow, startDirectFluentLogin]);
11092
11301
  const closeAccountMenu = useCallback(() => setAccountOpen(false), [setAccountOpen]);
11093
11302
  const { batchReview, confirmBatchOperation, acceptBatchReview, rejectBatchReview } = useBatchReview({ onOpen: closeAccountMenu });
11303
+ const { signatureReview, confirmSignature, acceptSignatureReview, rejectSignatureReview } = useSignatureReview({ onOpen: closeAccountMenu });
11094
11304
  const widgetApi = useWidgetExecution({
11095
11305
  chain,
11096
11306
  fluentAccountReady,
@@ -11100,6 +11310,8 @@ function FluentWidgetContent({
11100
11310
  defaultConfirmationMode,
11101
11311
  selectedGasPaymentToken,
11102
11312
  confirmBatchOperation,
11313
+ authMode: resolvedConfig.authMode,
11314
+ confirmSignature,
11103
11315
  refreshBalances,
11104
11316
  track
11105
11317
  });
@@ -11245,6 +11457,14 @@ function FluentWidgetContent({
11245
11457
  onConfirm: acceptBatchReview,
11246
11458
  onCancel: rejectBatchReview
11247
11459
  }
11460
+ ),
11461
+ /* @__PURE__ */ jsx(
11462
+ SignatureReviewModal,
11463
+ {
11464
+ review: signatureReview,
11465
+ onConfirm: acceptSignatureReview,
11466
+ onCancel: rejectSignatureReview
11467
+ }
11248
11468
  )
11249
11469
  ] })
11250
11470
  ] }) });
@@ -11439,6 +11659,6 @@ function FluentWidget(props) {
11439
11659
  ) });
11440
11660
  }
11441
11661
 
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 };
11662
+ export { AccountAvatar, Button, Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogOverlay, DialogPortal, DialogTitle, DialogTrigger, FLUENT_CONNECT_DEFAULT_ASSETS, FLUENT_GAS_PAYMENT_DEFAULT_ETH_RATES, FLUENT_USER_TOKEN_LIMIT, FLUENT_WIDGET_SESSION_STORAGE_KEY, FLUENT_WIDGET_USER_TOKENS_STORAGE_KEY, FLUENT_ZERODEV_ERC20_PAYMASTER_QUERY, FLUENT_ZERODEV_PAYMASTER_DEMO_RECIPIENT, FluentAccountDrawer, FluentAuthError, FluentPortalContainerProvider, FluentWidget, FluentWidgetConnectButton, FluentWidgetNetworkProvider, Icon, Label, Separator, Switch, WIDGET_STYLE_SCOPE, WalletMenuActionCard, buttonVariants, clearPrivyRecentLoginMethod, createFluentBatchOp, createFluentClient, createFluentFamiliesClient, createFluentPermissionApi, createFluentPermissionClient, createFluentPermissionPolicyBuilders, createFluentPermissionSession, createFluentSponsorshipRpcUrl, createFluentUserTokenStore, createFluentZeroDevErc20Paymaster, createFluentZeroDevErc20PaymasterApprovalCall, createFluentZeroDevErc20PaymasterClient, createFluentZeroDevErc20PaymasterRpcUrl, createFluentZeroDevPermissionSession, createFluentZeroDevRpcUrl, createFluentZeroDevSponsoredPaymaster, findFluentSymbolCollisions, fluent2 as fluent, apps as fluentApps, fluentBridgeAbi, fluent as fluentChain, fluentChains, fluentDefinitionToViemChain, integrations as fluentIntegrations, l1Chains as fluentL1Chains, fluentMainnet, fluentMainnetTokenDefaults, fluentTestnet, fluentTestnetTokenDefaults, fluentTokenIdentity, fluentZeroDevChainIds, getApp, getContractAddressFromChain, getFluentChain, getFluentChainByChainId, getFluentChainForNetwork, getFluentDefaultWidgetDisplayTokens, getFluentDefaultWidgetGasTokens, getFluentExplorerBaseUrl, getFluentGasPaymentEthValue, getFluentGasPaymentTokens, getFluentGasPaymentValueTier, getFluentGasTokenAddress, getFluentTokenDefaults, getFluentTokenDefaultsForNetwork, getFluentZeroDevErc20PaymasterTokens, getL1Chain, getL1ForFluentChain, getZeroDevRpcUrl, getZerodevIntegration, isFaucetNetwork, isFluentDefaultToken, isFluentNativeToken, isFluentZeroDevChain, l1DefinitionToViemChain, mergeFluentDisplayTokens, normalizeFluentWidgetNetwork, readFluentTokenBalances, readFluentTokenMetadata, registryVersion, resolveBridgeAddresses, resolveFluentWidgetNetworkFromEnv, resolveFluentZeroDevErc20PaymasterToken, resolveL1Definition, selectFluentGasPaymentToken, sendFluentZeroDevErc20PaymasterDemo, sortFluentGasTokens, useFluentUserTokens, useFluentWidget, useFluentWidgetNetwork, useFluentZeroDevAccount, useWidget, withFluentSignaturePrompt };
11443
11663
  //# sourceMappingURL=index.js.map
11444
11664
  //# sourceMappingURL=index.js.map