import { Chain, Address, Abi } from 'viem'; import { Permission, OriginSignature } from '@rhinestone/sdk'; type CrossChainSettlementLayer = "SAME_CHAIN" | "ECO" | "ACROSS"; interface CrossChainPermit { /** Allowed source legs: chain + token, with an optional amount cap. */ from: Array<{ chain: Chain; token: Address; maxAmount?: bigint; }>; /** Allowed destination legs: chain + token, with an optional recipient pin. */ to: Array<{ chain: Chain; token: Address; recipient?: Address | "any"; }>; /** Upper bound on the Permit2 deadline, expressed as Unix seconds. */ validUntil?: bigint; /** Lower bound on the Permit2 deadline, expressed as Unix seconds. */ validAfter?: bigint; /** Per-destination fill-deadline windows, expressed as Unix seconds. */ fillDeadline?: Array<{ chain: Chain; min?: bigint; max?: bigint; }>; /** When true, the destination recipient must be the smart account. */ recipientIsAccount?: boolean; /** Allowed settlement layers. Omit or pass an empty array to allow any supported layer. */ settlementLayers?: CrossChainSettlementLayer[]; } interface FromLeg { chain: Chain; token: Address | string; maxAmount?: bigint; } interface ToLeg { chain: Chain; token: Address | string; recipient?: Address | "any"; } interface CreateCrossChainPermissionInput { /** Source chain + token, with an optional amount cap. Pass an array for multi-leg permits. */ from: FromLeg | FromLeg[]; /** Destination chain + token, with an optional recipient pin. Pass an array for fan-out destinations. */ to: ToLeg | ToLeg[]; /** Upper bound on the Permit2 deadline. Accepts Unix-seconds bigint or Date. */ validUntil?: bigint | Date; /** Lower bound on the Permit2 deadline. Accepts Unix-seconds bigint or Date. */ validAfter?: bigint | Date; /** Per-destination fill-deadline windows, expressed as Unix seconds. */ fillDeadline?: Array<{ chain: Chain; min?: bigint; max?: bigint; }>; /** * Allow the destination recipient to differ from the smart account. * Defaults to false so bridge permissions are bridge-to-self unless the * caller explicitly broadens the grant. */ allowRecipientNotAccount?: boolean; /** Settlement layers this session is permitted to use. */ settlementLayers?: CrossChainSettlementLayer[]; } /** * Build a CrossChainPermit for Permit2-backed bridge settlement. * * The returned object is JSON-safe after callers stringify bigint fields at * the iframe/API boundary and can be passed as * `grantPermissions({ crossChainPermits: [...] })`. */ declare function createCrossChainPermission(input: CreateCrossChainPermissionInput): CrossChainPermit; /** * Backdrop (scrim) configuration for the modal dialog. * * The 1auth dialog floats over a full-viewport scrim that tints and blurs the * host page behind it. By default the scrim is a near-black wash * (`rgba(0,0,0,0.4)`) — which can be hard to distinguish from a dark host app, * making it unclear where the host ends and the dialog begins. Set a custom * `color` (e.g. a mid-gray) so the dialog reads as a distinct surface lifted * off a dark background. * * All fields are optional and each falls back to the current default * independently, so passing only `color` keeps the default opacity and blur. */ interface DialogBackdropConfig { /** * Scrim tint color as a 6-digit hex literal (e.g. `"#52525c"`). Only * `#rrggbb` is accepted; shorthand, alpha hex, and named colors are * rejected by the dialog. Defaults to `"#000000"`. */ color?: string; /** * Scrim opacity in the `0`–`1` range. Higher values dim the host page more. * Values outside the range are clamped. Defaults to `0.4`. */ opacity?: number; /** * Gaussian blur radius applied to the host page behind the dialog, in CSS * pixels. Clamped to `0`–`40`. Defaults to `8`. */ blur?: number; } /** * Theme configuration for the dialog UI */ interface ThemeConfig { /** Color mode: 'light', 'dark', or 'system' (follows user's OS preference) */ mode?: 'light' | 'dark' | 'system'; /** * Primary brand color (hex, e.g. `"#5436f5"`). Drives interactive accents: * primary CTAs, the spinner, link/account-bar text, and the focus glow * around input fields (RHI-4026). The dialog derives lighter tints * automatically by alpha-blending this color for the soft inner stroke * and diffused outer halo, so apps only need to pass one hex value. * * Falls back to {@link ThemeConfig.accent} when unset. */ primaryColor?: string; /** @deprecated Use {@link ThemeConfig.primaryColor}. Kept as alias for back-compat. */ accent?: string; /** * Optional tint/blur for the full-viewport scrim behind the dialog. Useful * for dark host apps where the default near-black scrim blends into the page * — a mid-gray `color` separates the dialog from the background. Omit to * keep the default `rgba(0,0,0,0.4)` + `blur(8px)`. */ backdrop?: DialogBackdropConfig; } type OneAuthTelemetryAttributeValue = string | number | boolean | null | undefined; type OneAuthTelemetryAttributes = Record; type OneAuthTelemetryFlow = "client" | "auth" | "connect" | "authenticate" | "sign" | "intent" | "batch_intent" | "grant_permission" | "assets" | "status" | "history"; type OneAuthTelemetryEventName = "client.init" | "dialog.opened" | "dialog.ready" | "dialog.cancelled" | "auth.succeeded" | "auth.failed" | "connect.succeeded" | "connect.failed" | "sign.succeeded" | "sign.failed" | "intent.prepare.started" | "intent.prepare.succeeded" | "intent.prepare.failed" | "intent.sign.succeeded" | "intent.sign.failed" | "intent.execute.started" | "intent.execute.succeeded" | "intent.execute.failed" | "intent.status.started" | "intent.status.succeeded" | "intent.status.failed" | "intent.completed" | "batch.prepare.started" | "batch.prepare.succeeded" | "batch.prepare.failed" | "batch.sign.succeeded" | "batch.sign.failed" | "batch.completed" | "grant_permission.succeeded" | "grant_permission.failed" | "assets.succeeded" | "assets.failed" | "status.succeeded" | "status.failed" | "history.succeeded" | "history.failed"; interface OneAuthTelemetryTraceContext { /** W3C traceparent header value supplied by the host app's tracer. */ traceparent?: string; /** W3C tracestate header value supplied by the host app's tracer. */ tracestate?: string; /** Optional trace id for SDK event callbacks that do not use traceparent. */ traceId?: string; /** Optional span id for SDK event callbacks that do not use traceparent. */ spanId?: string; } interface OneAuthTelemetryEvent { /** Low-cardinality event name emitted by the SDK. */ name: OneAuthTelemetryEventName; /** Per-operation correlation id generated by the SDK. */ operationId: string; /** High-level SDK flow that owns the event. */ flow: OneAuthTelemetryFlow; /** ISO timestamp when the event was emitted. */ timestamp: string; /** Milliseconds since the SDK operation started, when applicable. */ durationMs?: number; /** Human outcome for dashboards and SDK-side spans. */ outcome?: "success" | "failure" | "cancelled" | "started"; clientId?: string; providerUrl?: string; dialogUrl?: string; targetChain?: number; targetChains?: number[]; intentCount?: number; status?: string; errorCode?: string; errorMessage?: string; trace?: OneAuthTelemetryTraceContext; attributes?: OneAuthTelemetryAttributes; } interface OneAuthTelemetryConfig { /** * Enable SDK telemetry callbacks and trace propagation. Defaults to true * when a telemetry object is provided. */ enabled?: boolean; /** * Optional callback for host apps to bridge SDK events into their own * OpenTelemetry tracer/logger. The SDK catches callback errors so telemetry * can never break an auth or signing flow. */ onEvent?: (event: OneAuthTelemetryEvent) => void; /** * Current host-app trace context. When supplied, the SDK forwards it to * 1auth dialogs and passkey API calls through W3C-compatible fields. */ traceContext?: OneAuthTelemetryTraceContext | (() => OneAuthTelemetryTraceContext | undefined); /** Static or lazily computed attributes attached to every SDK event. */ attributes?: OneAuthTelemetryAttributes | (() => OneAuthTelemetryAttributes | undefined); } interface PasskeyProviderConfig { /** Base URL of the auth API. Defaults to https://passkey.1auth.app */ providerUrl?: string; /** Client identifier for this application (optional for development) */ clientId?: string; /** Optional redirect URL for redirect flow */ redirectUrl?: string; /** Optional URL of the dialog UI. Defaults to providerUrl */ dialogUrl?: string; /** Optional theme configuration for the dialog */ theme?: ThemeConfig; /** * Control whether the 1auth signing review iframe is hidden. * * When blind signing is on, the 1auth transaction, message, and EIP-712 * review UI is skipped and the WebAuthn signature auto-starts; the browser's * own WebAuthn prompt is still shown. * * Defaults to blind signing (see the `DEFAULT_BLIND_SIGNING` switch in the * SDK). Set `blind_signing: false` to *opt in* to 1auth's visible review UI * (clear signing) for this app. Per-call overrides still take precedence. */ blind_signing?: boolean; /** When true, operate chain queries on testnets. `wallet_getAssets` returns grouped mainnet and testnet balances. */ testnets?: boolean; /** * Sponsorship configuration for app-sponsored intents. Set once on the * client; applied automatically to every sendIntent / sendCalls / batch. * Accepts either a callback pair (full control) or a pair of URLs (SDK * handles fetching). */ sponsorship?: SponsorshipConfig; /** * Optional SDK telemetry bridge. Core SDK stays dependency-free: integrators * can use this callback to create spans/logs in their own OTEL setup. */ telemetry?: OneAuthTelemetryConfig; /** * Called when the trusted passkey dialog invalidates the current application * session, including deployment-forced logout. Use this to clear host-app * in-memory auth state that cannot be inferred from localStorage alone. */ onDisconnect?: () => void; /** * When `true`, the SDK schedules a one-time {@link OneAuthClient.prewarm} on * an idle callback after construction — loading the dialog bundle into a * hidden iframe so the first real dialog open paints from cache instead of a * cold load. * * Off by default: prewarming opens a cross-origin iframe, so a page that * never triggers auth would pay for it needlessly. Prefer calling * `client.prewarm()` yourself on a likely-intent signal (button hover/focus) * for the same benefit without the page-load cost; use this flag only when * auth is highly likely on the current view (e.g. a dedicated checkout page). */ prewarm?: boolean; } /** * Authentication dialog entry point. * * `auto` preserves the legacy SDK behavior: the passkey app decides whether * to show sign-in or account creation from local iframe-origin state. */ type AuthFlow = "auto" | "login" | "create-account"; /** * Options for {@link OneAuthClient.authWithModal}. */ interface AuthWithModalOptions { /** Override the theme for this modal invocation. */ theme?: ThemeConfig; /** Set to false to hide OAuth sign-in buttons in account creation. */ oauthEnabled?: boolean; /** Force a specific auth entry route instead of the default auto-router. */ flow?: AuthFlow; /** * Opt the dialog into "wallet as signer" mode: when the user picks a * traditional wallet, connect that EOA as the account signer (a `signerType: * "eoa"` session whose transactions bypass Rhinestone intents) instead of * using the wallet only to prove identity for a passkey signup. Passkey * selection is unaffected. Set by {@link createOneAuthConnection}; the default * (`false`/absent) preserves the existing wallet-assisted passkey signup. */ eoaConnect?: boolean; } /** * Options for {@link OneAuthClient.loginWithModal}. */ interface LoginWithModalOptions { /** Override the theme for this modal invocation. */ theme?: ThemeConfig; } /** * Options for {@link OneAuthClient.createAccountWithModal}. */ interface CreateAccountWithModalOptions { /** Override the theme for this modal invocation. */ theme?: ThemeConfig; /** Set to false to hide OAuth sign-in buttons. */ oauthEnabled?: boolean; } /** * Signer backing the authenticated session. Defaults to `"passkey"` when absent * for back-compat with clients that predate the wallet-connect flow. */ type SignerType = "passkey" | "eoa"; /** * Result of {@link OneAuthClient.authWithModal} — covers both sign-in and sign-up. * * @example * ```typescript * const result = await client.authWithModal(); * if (result.success) { * console.log(result.user?.address); // "0x1234..." * } * ``` */ interface AuthResult { success: boolean; /** Authenticated user details (present when `success` is true) */ user?: { id: string; address: `0x${string}`; }; /** * Which signer produced this session. Absent = treat as `"passkey"` so older * clients keep working; new wallet flows populate explicitly. */ signerType?: SignerType; error?: { code: string; message: string; }; } /** * Result of the connect modal (lightweight connection without passkey auth) */ interface ConnectResult { success: boolean; /** Connected user details (present when `success` is true) */ user?: { address: `0x${string}`; }; /** * Which signer produced this connection. Absent = treat as `"passkey"` for * back-compat; wallet-connect flows set this to `"eoa"`. */ signerType?: SignerType; /** Whether this was auto-connected (user had auto-connect enabled) */ autoConnected?: boolean; /** Action to take when connection was not successful */ action?: "switch" | "cancel"; error?: { code: string; message: string; }; } /** * Options for the authenticate() method */ interface AuthenticateOptions { /** * Human-readable challenge message for the user to sign. * The provider will hash this with a domain separator to prevent * the signature from being reused for transaction signing. */ challenge?: string; } /** * Result of {@link OneAuthClient.authenticate} — extends {@link AuthResult} * with challenge-signing fields. * * @example * ```typescript * const result = await client.authenticate({ * challenge: `Login to MyApp\nNonce: ${crypto.randomUUID()}` * }); * if (result.success && result.challenge) { * await verifyOnServer(result.user?.address, result.challenge.signature, result.challenge.signedHash); * } * ``` */ interface AuthenticateResult extends AuthResult { /** Challenge signing result (present when a challenge was provided) */ challenge?: { /** WebAuthn signature of the hashed challenge */ signature: WebAuthnSignature; /** * The hash that was actually signed (so apps can verify server-side). * Computed as: keccak256("\x19Ethereum Signed Message:\n" + len + challenge) (EIP-191) */ signedHash: `0x${string}`; }; } /** * Options for signMessage */ interface SignMessageOptions { /** Account address of the signer — the sole signer identity. */ accountAddress: string; /** Human-readable message to sign */ message: string; /** Optional custom challenge (defaults to message hash) */ challenge?: string; /** Description shown to user in the dialog */ description?: string; /** Optional metadata to display to the user */ metadata?: Record; /** Theme configuration */ theme?: ThemeConfig; /** Override the client's blind signing setting for this request. */ blind_signing?: boolean; } /** A sanitized candidate failure returned by intent preparation. */ interface OneAuthCandidateError { code?: string; message?: string; details?: OneAuthErrorDetails; } /** Provider and orchestrator diagnostics safe to expose to the integrating app. */ interface OneAuthErrorDetails { /** Rhinestone request trace ID for support and log correlation. */ traceId?: string; /** Machine-readable Rhinestone error code, when supplied. */ providerCode?: string; /** HTTP status returned by the upstream provider, when supplied. */ statusCode?: number; /** Execution-error category returned by the orchestrator. */ errorType?: string; /** Tenderly or provider simulation links for failed execution. */ simulationUrls?: string[]; /** Human-readable reason supplied by a prepare-stage failure. */ reason?: string; /** Sanitized alternatives returned when no preparation candidate succeeded. */ candidateErrors?: OneAuthCandidateError[]; } /** Common structured error returned by signing and intent operations. */ interface OneAuthResultError { code: Code; message: string; details?: OneAuthErrorDetails; } /** Runtime signing codes accepted from redirects, HTTP results, and dialog messages. */ declare const SIGNING_ERROR_CODES: readonly ["USER_REJECTED", "EXPIRED", "INVALID_REQUEST", "NETWORK_ERROR", "POPUP_BLOCKED", "SIGNING_FAILED", "UNKNOWN"]; type SigningErrorCode = (typeof SIGNING_ERROR_CODES)[number]; /** Returns whether an untrusted value is a public signing error code. */ declare function isSigningErrorCode(value: unknown): value is SigningErrorCode; /** * Base result for all signing operations (message signing, typed data signing). */ interface SigningResultBase { success: boolean; /** WebAuthn signature if successful */ signature?: WebAuthnSignature; /** The hash that was signed */ signedHash?: `0x${string}`; /** Passkey credentials used for signing */ passkey?: PasskeyCredentials; /** Error details if failed */ error?: OneAuthResultError; } /** * Result of signMessage */ interface SignMessageResult extends SigningResultBase { /** The original message that was signed */ signedMessage?: string; } interface ClearSignData { decoded: boolean; verified: boolean; functionName?: string; intent?: string; args?: Array<{ name: string; type: string; value: string; label?: string; }>; selector?: string; } interface TransactionAction { type: 'send' | 'receive' | 'approve' | 'swap' | 'mint' | 'custom' | 'module_install'; label: string; sublabel?: string; amount?: string; icon?: string; clearSign?: ClearSignData; recipient?: TransactionRecipient; } interface TransactionRecipient { address: string; label?: string; display: string; source: "decoded_transfer" | "token_request"; } interface TransactionFees { estimated: string; network: { name: string; icon?: string; }; } interface BalanceRequirement { token: string; amount: string; faucetUrl?: string; } interface TransactionDetails { actions: TransactionAction[]; fees?: TransactionFees; requiredBalance?: BalanceRequirement; account?: { address: string; label?: string; }; } interface SigningRequestOptions { challenge: string; /** Smart account address of the signer — the sole signer identity. */ accountAddress: string; description?: string; metadata?: Record; transaction?: TransactionDetails; /** Override the client's blind signing setting for this request. */ blind_signing?: boolean; } interface WebAuthnSignature { authenticatorData: string; clientDataJSON: string; challengeIndex: number; typeIndex: number; r: string; s: string; topOrigin: string | null; } /** Passkey identity returned after server-side verification. */ interface PasskeyCredentials { credentialId: string; publicKeyX: string; publicKeyY: string; /** Server-owned on-chain slot. Optional for compatibility with pre-slot SDK consumers. */ keyId?: number; } interface SigningSuccess { success: true; requestId?: string; /** WebAuthn signature - present for message/typedData signing */ signature?: WebAuthnSignature; /** Array of signatures for multi-origin cross-chain intents (one per source chain) */ originSignatures?: WebAuthnSignature[]; /** Credentials of the passkey used for signing - present for message/typedData signing */ passkey?: PasskeyCredentials; /** Intent ID - present for intent signing (after execute in dialog) */ intentId?: string; } interface EmbedOptions { container: HTMLElement; width?: string; height?: string; onReady?: () => void; onClose?: () => void; } interface SigningError { success: false; requestId?: string; error: OneAuthResultError; } type SigningResult = SigningSuccess | SigningError; interface CreateSigningRequestResponse { requestId: string; nonce: string; signingUrl: string; expiresAt: string; } interface SigningRequestStatus { id: string; status: "PENDING" | "COMPLETED" | "REJECTED" | "EXPIRED" | "FAILED"; signature?: WebAuthnSignature; error?: OneAuthResultError; } /** * Low-level sponsorship config: caller supplies callbacks that produce tokens. * The SDK invokes `accessToken()` before each sponsored intent and * `getExtensionToken(intentOp)` in parallel with the signing ceremony. */ interface SponsorshipCallbackConfig { accessToken: () => Promise; getExtensionToken: (intentOp: string) => Promise; } /** * High-level sponsorship config: the SDK fetches tokens from the app's own * endpoints (same-origin recommended so session cookies authenticate the user). * `accessTokenUrl` is GET → `{ token }`, `extensionTokenUrl` is POST * `{ intentOp }` → `{ token }`. */ interface SponsorshipUrlConfig { accessTokenUrl: string; extensionTokenUrl: string; } type SponsorshipConfig = SponsorshipCallbackConfig | SponsorshipUrlConfig; /** * Options for querying a unified 1auth wallet asset portfolio. */ interface GetAssetsOptions { /** Account address whose unified portfolio should be queried. */ accountAddress: Address; } /** * Single token balance on one chain in the normalized assets response. */ interface AssetBalance { /** Chain ID where this balance lives. */ chainId: number; /** Token contract address on the chain. */ token: string; /** Human token symbol, e.g. USDC. */ symbol: string; /** Token decimals used to format balance. */ decimals: number; /** Raw base-unit token balance as a decimal string. */ balance: string; /** Optional fiat value when supplied by the passkey portfolio API. */ usdValue?: number; /** True when the chain is a known testnet. */ isTestnet?: boolean; } /** * Network bucket in the grouped assets response. */ interface AssetBalanceBucket { /** Balances in this network bucket. */ balances: AssetBalance[]; } /** * Normalized response returned by client.getAssets and wallet_getAssets. */ interface AssetsResponse { /** Flat portfolio rows across all supported chains. */ balances: AssetBalance[]; /** Mainnet portfolio rows. */ mainnets: AssetBalanceBucket; /** Testnet portfolio rows. */ testnets: AssetBalanceBucket; /** Raw passkey portfolio asset groups, when the provider includes them. */ assets?: unknown; } /** * A call to execute on the target chain */ interface IntentCall { /** Target contract address */ to: string; /** Calldata to send */ data?: string; /** Value in wei (as string for serialization) */ value?: string; /** * Optional label for the transaction review UI (bold title row in the * sign dialog's action card, e.g. "Send", "Approve"). * * Hard-capped by the SDK at 20 characters before being sent to the * passkey service; longer strings are truncated with a trailing ellipsis. * The dialog additionally applies CSS `truncate` as a defense-in-depth * single-line guarantee — design column is only ~200–260px wide at * `text-[16px] bold`, so anything past ~17 typical glyphs would wrap. */ label?: string; /** * Optional sublabel for additional context (the secondary row underneath * `label`, e.g. token amount or destination). * * Same 20-character SDK cap as {@link IntentCall.label}. */ sublabel?: string; /** * Optional icon shown in the sign dialog's action card. Used as a * fallback only — when 1auth can resolve a built-in token icon for this * call (USDC, ETH, …) that one wins, so apps cannot impersonate * well-known tokens with a custom glyph. * * Must be an `https://` URL or a `data:image/;...` URL * (svg+xml, png, webp, jpeg, gif). Max 8 KB. Other schemes * (`http:`, `javascript:`, `file:`, …) are rejected by the server. * * Note: HTTPS URLs are fetched directly by the user's browser, which * leaks IP/UA/Referer to the host you point at. Use a `data:` URL if * you don't want the user's browser making a third-party request. */ icon?: string; /** * Optional ABI used by the sign dialog to render a human-readable * preview of `data` (decoded function name + args) under the action * card's label/sublabel. * * App-supplied and unverified — same trust model as {@link IntentCall.label}, * {@link IntentCall.sublabel}, and {@link IntentCall.icon}, and the same * as the ABI in {@link GrantPermissionContractMetadata}. The dialog renders * it with an "Unverified" badge and never uses it for authorization; the * raw `to` + selector is always shown alongside as ground truth. * * The dialog decodes via viem's `decodeFunctionData(abi, data)`. If the * ABI doesn't cover the selector in `data` (or decoding throws for any * reason) the preview is silently dropped — no hard failure. */ abi?: readonly unknown[]; } /** * Token request for the intent */ interface IntentTokenRequest { /** Token contract address */ token: string; /** Amount in base units (use parseUnits for decimals) */ amount: bigint; } /** * Funding policy for an intent. * * - `required`: app sponsorship must succeed or the intent fails. * - `preferred`: try app sponsorship, then explicitly re-quote as self-funded. * - `disabled`: quote and submit as self-funded without an extension grant. */ type SponsorshipMode = "required" | "preferred" | "disabled"; /** * Options for sendIntent */ interface SendIntentOptions { /** Account address of the signer — the sole signer identity. */ accountAddress: string; /** Target chain ID */ targetChain?: number; /** Calls to execute on the target chain */ calls?: IntentCall[]; /** Optional token requests */ tokenRequests?: IntentTokenRequest[]; /** * Constrain which tokens can be used as input/payment. * If not specified, orchestrator picks from all available balances. * Example: ['USDC'] or ['0x...'] to only use USDC as input. */ sourceAssets?: string[]; /** * Source chain ID for the assets. * When specified with sourceAssets containing addresses, tells orchestrator * which chain to look for those tokens on. */ sourceChainId?: number; /** When to close the dialog and return success. Defaults to "preconfirmed" */ closeOn?: CloseOnStatus; /** * Wait for a transaction hash before resolving. * Defaults to false to preserve existing behavior. */ waitForHash?: boolean; /** Maximum time to wait for a transaction hash in ms. */ hashTimeoutMs?: number; /** Poll interval for transaction hash in ms. */ hashIntervalMs?: number; /** * Funding policy. Defaults to `required`, so sponsorship failures never * silently charge the user. Use `preferred` to opt into a reviewed, * self-funded fallback, or `disabled` to request self-funding directly. */ sponsorshipMode?: SponsorshipMode; /** @deprecated Use `sponsorshipMode: "disabled"` instead of `sponsor: false`. */ sponsor?: boolean; /** Override the client's blind signing setting for this request. */ blind_signing?: boolean; } /** * Quote from the Rhinestone orchestrator */ interface IntentQuote { /** Total cost in input tokens */ cost: { total: string; breakdown?: { gas?: string; bridge?: string; swap?: string; }; }; /** Token requirements to fulfill the intent */ tokenRequirements: Array<{ token: string; amount: string; chainId: number; }>; } /** * Status of an intent (local states) */ type IntentStatus = "pending" | "quoted" | "signed" | "submitted" | "claimed" | "preconfirmed" | "filled" | "completed" | "failed" | "expired" | "unknown"; /** * Orchestrator status (from Rhinestone) * These are the statuses we can receive when polling */ type OrchestratorStatus = "PENDING" | "CLAIMED" | "PRECONFIRMED" | "FILLED" | "COMPLETED" | "FAILED" | "EXPIRED"; /** * When to consider the transaction complete and close the dialog * - "claimed" - Close when a solver has claimed the intent (fastest) * - "preconfirmed" - Close on pre-confirmation (recommended) * - "filled" - Close when the transaction is filled * - "completed" - Wait for full completion (slowest, most certain) */ type CloseOnStatus = "claimed" | "preconfirmed" | "filled" | "completed"; /** * Result of sendIntent */ interface SendIntentResult { /** Whether the intent was successfully submitted */ success: boolean; /** Intent ID for tracking */ intentId: string; /** Current status */ status: IntentStatus; /** Transaction hash if completed */ transactionHash?: string; /** Operation ID from orchestrator */ operationId?: string; /** Error details if failed */ error?: OneAuthResultError; } /** * Prepare intent response from auth service */ interface PrepareIntentResponse { quote: IntentQuote; transaction: TransactionDetails; challenge: string; expiresAt: string; /** Account address for the sign dialog to detect self-transfer vs external send */ accountAddress?: string; /** Serialized PreparedTransactionData from orchestrator - needed for execute */ intentOp: string; /** User ID for creating intent record on execute */ userId: string; /** Target chain ID */ targetChain: number; /** JSON stringified calls */ calls: string; /** Origin message hashes for multi-source cross-chain intents */ originMessages?: Array<{ chainId: number; messageHash: string; }>; /** Serialized DigestResult from module SDK (EIP-712 wrapped challenge + merkle proofs) */ digestResult?: string; /** * Opaque, server-minted HMAC binding this prepared intent to /execute. * The SDK treats it as a pass-through token: forward it unchanged to the * dialog and back to /api/intent/execute. Never parse or mutate it. */ binding?: string; } /** * Execute intent response from auth service */ interface ExecuteIntentResponse { success: boolean; intentId: string; operationId?: string; status: IntentStatus; transactionHash?: string; /** Transaction result data needed for waiting via POST /api/intent/wait */ transactionResult?: unknown; error?: OneAuthResultError; } /** * EIP-712 Domain parameters */ interface EIP712Domain { /** Name of the signing domain (e.g., "Dai Stablecoin") */ name: string; /** Version of the signing domain (e.g., "1") */ version: string; /** Chain ID (optional) */ chainId?: number; /** Verifying contract address (optional) */ verifyingContract?: `0x${string}`; /** Salt for disambiguation (optional) */ salt?: `0x${string}`; } /** * EIP-712 Type field definition */ interface EIP712TypeField { /** Field name */ name: string; /** Solidity type (e.g., "address", "uint256", "bytes32") */ type: string; } /** * EIP-712 Types map - maps type names to their field definitions */ type EIP712Types = { [typeName: string]: EIP712TypeField[]; }; /** * Options for signTypedData */ interface SignTypedDataOptions { /** Account address of the signer — the sole signer identity. */ accountAddress: string; /** EIP-712 domain parameters */ domain: EIP712Domain; /** Type definitions for all types used in the message */ types: EIP712Types; /** Primary type being signed (must be a key in types) */ primaryType: string; /** Message values matching the primaryType structure */ message: Record; /** Optional description shown in the dialog */ description?: string; /** Theme configuration */ theme?: ThemeConfig; /** Override the client's blind signing setting for this request. */ blind_signing?: boolean; } /** * Result of signTypedData */ interface SignTypedDataResult extends SigningResultBase { } /** * Options for querying intent history */ interface IntentHistoryOptions { /** Maximum number of intents to return (default: 50, max: 100) */ limit?: number; /** Number of intents to skip for pagination */ offset?: number; /** Filter by intent status */ status?: IntentStatus; /** Filter by creation date (ISO string) - intents created on or after this date */ from?: string; /** Filter by creation date (ISO string) - intents created on or before this date */ to?: string; } /** * Single intent item in history response */ interface IntentHistoryItem { /** Intent identifier (orchestrator's ID, used as primary key) */ intentId: string; /** Current status of the intent */ status: IntentStatus; /** Transaction hash (if completed) */ transactionHash?: string; /** Target chain ID */ targetChain: number; /** Calls that were executed */ calls: IntentCall[]; /** When the intent was created (ISO string) */ createdAt: string; /** When the intent was last updated (ISO string) */ updatedAt: string; } /** * Result of getIntentHistory */ interface IntentHistoryResult { /** List of intents */ intents: IntentHistoryItem[]; /** Total count of matching intents */ total: number; /** Whether there are more intents beyond this page */ hasMore: boolean; } /** * A single intent within a batch */ interface BatchIntentItem { /** Target chain ID */ targetChain: number; /** Calls to execute on the target chain */ calls?: IntentCall[]; /** Optional token requests */ tokenRequests?: IntentTokenRequest[]; /** Constrain which tokens can be used as input */ sourceAssets?: string[]; /** Source chain ID for the assets */ sourceChainId?: number; /** Install an ERC-7579 module instead of executing calls */ moduleInstall?: { moduleType: "validator" | "executor" | "fallback" | "hook"; moduleAddress: string; initData?: string; }; /** Funding policy for this item. Defaults to `required`. */ sponsorshipMode?: SponsorshipMode; /** @deprecated Use `sponsorshipMode: "disabled"` instead of `sponsor: false`. */ sponsor?: boolean; } /** * Options for sendBatchIntent */ interface SendBatchIntentOptions { /** Account address of the signer — the sole signer identity. */ accountAddress: string; /** Array of intents to execute as a batch */ intents: BatchIntentItem[]; /** When to close the dialog for each intent. Defaults to "preconfirmed" */ closeOn?: CloseOnStatus; /** Override the client's blind signing setting for this request. */ blind_signing?: boolean; } /** * Result for a single intent within a batch */ interface BatchIntentItemResult { /** Index in the original batch */ index: number; /** Whether this intent succeeded */ success: boolean; /** Intent ID from orchestrator */ intentId: string; /** Current status */ status: IntentStatus; /** Error details if failed */ error?: { code: string; message: string; }; } /** * Result of sendBatchIntent */ interface SendBatchIntentResult { /** Whether ALL intents succeeded */ success: boolean; /** Per-intent results */ results: BatchIntentItemResult[]; /** Count of successful intents */ successCount: number; /** Count of failed intents */ failureCount: number; /** Top-level error message when batch-prepare itself fails */ error?: string; } /** * Prepared intent data within a batch response */ interface PreparedBatchIntent { /** Index in the original batch */ index: number; /** Quote from orchestrator */ quote: IntentQuote; /** Decoded transaction details for UI */ transaction: TransactionDetails; /** Serialized PreparedTransactionData from orchestrator */ intentOp: string; /** Expiry for this specific intent */ expiresAt: string; /** Target chain ID */ targetChain: number; /** JSON stringified calls */ calls: string; /** Origin message hashes for this intent */ originMessages: Array<{ chainId: number; messageHash: string; }>; } /** * Prepare batch intent response from auth service */ interface PrepareBatchIntentResponse { /** Per-intent prepared data (successful quotes only) */ intents: PreparedBatchIntent[]; /** Intents that failed to get quotes (unsupported chains, etc.) */ failedIntents?: Array<{ index: number; targetChain: number; error: string; }>; /** Shared challenge (merkle root of ALL origin hashes across ALL intents) */ challenge: string; /** User ID */ userId: string; /** Account address */ accountAddress?: string; /** Global expiry (earliest of all intent expiries) */ expiresAt: string; /** * Opaque, server-minted HMAC binding this prepared batch to /batch-execute. * Pass-through token: forward unchanged to the dialog and back to * /api/intent/batch-execute. Never parse or mutate it. */ binding?: string; } /** @deprecated Data-sharing consent is disabled. */ type ConsentField = "email" | "deviceNames"; /** @deprecated Data-sharing consent is disabled. */ interface ConsentData { email?: string; deviceNames?: string[]; } /** @deprecated Data-sharing consent is disabled. */ interface CheckConsentOptions { /** Account address — the sole account identity. */ accountAddress: string; /** Fields to check */ fields: ConsentField[]; /** Override clientId from SDK config */ clientId?: string; } /** @deprecated Data-sharing consent is disabled. */ interface CheckConsentResult { /** Whether consent has been granted for ALL requested fields */ hasConsent: boolean; /** Shared data (present when hasConsent is true) */ data?: ConsentData; /** When consent was granted (ISO timestamp) */ grantedAt?: string; } /** @deprecated Data-sharing consent is disabled. */ interface RequestConsentOptions { /** Account address — the sole account identity. */ accountAddress: string; /** Fields to request access to */ fields: ConsentField[]; /** Override clientId from SDK config */ clientId?: string; /** Theme configuration */ theme?: ThemeConfig; } /** @deprecated Data-sharing consent is disabled. */ interface RequestConsentResult { success: boolean; /** Shared data (present when success is true) */ data?: ConsentData; /** When consent was granted (ISO timestamp) */ grantedAt?: string; /** Whether data came from an existing grant (no dialog shown) */ cached?: boolean; /** Error details */ error?: { code: "USER_REJECTED" | "USER_CANCELLED" | "INVALID_REQUEST" | "NETWORK_ERROR" | "UNKNOWN"; message: string; }; } /** * Options for one-time SmartSession install. The host app generates an * ECDSA key locally (or imports one), passes its public address as the * session-key signer, and a permission spec defining what the session * key may do. This triggers a passkey-signed management transaction * that installs the SmartSession validator and registers the session. */ interface InstallSmartSessionBaseOptions { /** Account address of the owner — the sole account identity. */ accountAddress: string; /** Target chain to install the validator on. */ targetChain: number; /** Public address of the ECDSA session-key the app holds in localStorage. */ sessionKeyAddress: `0x${string}`; /** Per-contract permission specs re-validated by 1auth before signing. */ permissions: Permission[]; /** Cross-chain asset movement permits used by the SmartSession policies. */ crossChainPermits?: CrossChainPermit[]; /** Unix seconds. Session is invalid after this time. */ validUntil?: number; /** Unix seconds. Session is invalid before this time. */ validAfter?: number; /** Optional max number of uses across the session lifetime. */ maxUses?: number; /** Optional human label shown in the install dialog. */ label?: string; } /** * A WebAuthn enable signature must name the exact credential that produced it. * Unsigned discovery/preflight requests intentionally omit both fields. */ type InstallSmartSessionOptions = InstallSmartSessionBaseOptions & ({ enableSessionSignature: WebAuthnSignature; credentialId: string; } | { enableSessionSignature?: `0x${string}` | undefined; credentialId?: never; }); interface SmartSessionEnableRequest { alreadyEnabled: boolean; /** * EIP-712 payload to pass to `OneAuthClient.signTypedData` when * `alreadyEnabled` is false. Big integer fields are JSON-encoded as * decimal strings by the provider and should be revived before signing. */ typedData?: { domain: EIP712Domain; types: EIP712Types; primaryType: string; message: Record; }; } interface InstallSmartSessionResult { install: { targetChain: number; calls: Array<{ to: string; data: string; value: string; label?: string; sublabel?: string; }>; alreadyInstalled: boolean; }; sessionKeyHandle: SessionKeyHandle; sessionEnable: SmartSessionEnableRequest; } /** * Legacy low-level SmartSession policy descriptors used by passkey review * APIs. New app integrations should prefer `definePermissions()` parameter * constraints plus `grantPermissions()` session limits (`maxUses`, * `validAfter`, `validUntil`) instead of hand-authoring raw policy arrays. */ type SmartSessionPolicy = { type: "usage-limit"; limit: bigint; } | { type: "time-frame"; validAfter: number; validUntil: number; } | { type: "value-limit"; limit: bigint; } | { type: "universal-action"; valueLimitPerUse?: bigint; rules: [ UniversalActionPolicyRule, ...UniversalActionPolicyRule[] ]; }; interface UniversalActionPolicyRule { condition: "equal" | "greaterThan" | "lessThan" | "greaterThanOrEqual" | "lessThanOrEqual" | "notEqual" | "inRange"; calldataOffset: bigint; referenceValue: `0x${string}` | bigint; usageLimit?: bigint; } interface GrantPermissionContractMetadata { address: `0x${string}`; name?: string; /** App-supplied ABI is used for readable labels only and is not verified. */ abi?: readonly unknown[]; } interface GrantPermissionsOptions { /** Account address of the owner — the sole account identity. */ accountAddress: `0x${string}`; /** * Chains where this permission should be installed/enabled. * * SmartSession owner authorization is multi-chain: 1auth asks for one * passkey signature that commits to every requested chain session, then * submits the per-chain install/enable intents internally. */ targetChains?: number[]; /** @deprecated Use targetChains. Kept as a single-chain compatibility alias. */ targetChain?: number; /** * Source/funding chains that need SmartSession coverage for cross-chain * claim signatures, but where selector permissions should not be installed. */ sourceChains?: number[]; /** Public address of the ECDSA session signer owned by the app. */ sessionKeyAddress: `0x${string}`; /** Per-contract permission specs from `definePermissions()`. */ permissions: Permission[]; /** * Cross-chain asset movement permits, usually created with * `createCrossChainPermission()`. These are reviewed and installed together * with selector permissions so headless bridge/swap intents have claim * authority. */ crossChainPermits?: CrossChainPermit[]; /** Optional session-wide policy hints applied to every function. */ validUntil?: number; validAfter?: number; maxUses?: number; /** Optional ABI/name metadata for non-verified human-readable review. */ contracts?: GrantPermissionContractMetadata[]; /** Whether the app sponsors the install/enable transaction. Defaults to true. */ sponsor?: boolean; theme?: ThemeConfig; } interface GrantPermissionsResult { success: boolean; grantId?: string; sessionKeyHandle?: SessionKeyHandle; permissionId?: `0x${string}`; permissionIdsByChain?: Record; intentId?: string; intentIds?: string[]; status?: IntentStatus | string; statusesByChain?: Record; transactionHash?: string; transactionHashesByChain?: Record; statusUrl?: string; statusUrlsByChain?: Record; waitUrl?: string; waitUrlsByChain?: Record; chainResults?: Array<{ chainId: number; intentId?: string; status?: IntentStatus | string; transactionHash?: string; statusUrl?: string; waitUrl?: string; alreadyInstalled?: boolean; }>; error?: { code: string; message: string; }; } interface ListSessionGrantsOptions { /** Account address of the owner — the sole account identity. */ accountAddress: `0x${string}`; /** Include grants that 1auth has marked revoked. Defaults to false. */ includeRevoked?: boolean; } interface SessionGrantChain { chainId: number; permissionId: `0x${string}`; status: string; intentId?: string; transactionHash?: string; statusUrl?: string; waitUrl?: string; revokeStatus?: string; revokeIntentId?: string; revokeTransactionHash?: string; revokedAt?: string; } interface SessionGrantRecord { grantId: string; origin: string; app?: { id: string; name: string; clientId: string; }; accountAddress: `0x${string}`; sessionKeyAddress: `0x${string}`; permissionId: `0x${string}`; permissionIdsByChain?: Record; chainIds: number[]; chains: SessionGrantChain[]; sessionKeyHandle?: SessionKeyHandle; /** Per-contract permission specs echoed for app bookkeeping. */ permissions?: Permission[]; /** Cross-chain permits echoed for app bookkeeping. */ crossChainPermits?: CrossChainPermit[]; expiresAt?: string; createdAt: string; updatedAt: string; revokedAt?: string; } interface ListSessionGrantsResult { success: boolean; grants?: SessionGrantRecord[]; error?: { code: string; message: string; }; } /** * Returned to the caller of {@link InstallSmartSessionOptions}. 1auth stores * this public handle for origin-scoped recovery, but the host app still owns * and stores the private signer material or KMS reference. */ interface SessionKeyHandle { sessionKeyAddress: `0x${string}`; /** Deterministic on-chain permission ID for this session key. */ permissionId: `0x${string}`; /** Account this permission is scoped to. */ accountAddress: `0x${string}`; /** Echoed per-contract permission specs (for app's own bookkeeping). */ permissions: Permission[]; /** Echoed cross-chain permit specs required to rebuild the session hash. */ crossChainPermits?: CrossChainPermit[]; /** Unix seconds. Session is invalid after this time. */ validUntil?: number; /** Unix seconds. Session is invalid before this time. */ validAfter?: number; /** Optional max number of uses across the session lifetime. */ maxUses?: number; /** Chains where the permission was requested. */ chainIds?: number[]; /** Chains where selector permissions are installed. */ targetChains?: number[]; /** Source/funding chains covered only for cross-chain claim signatures. */ sourceChains?: number[]; /** Per-chain permission IDs. In most SmartSession flows these are stable per session, but callers should key by chain. */ permissionIdsByChain?: Record; /** First chain in `chainIds`; kept for single-chain compatibility. */ chainId: number; /** Mirror of `validUntil` if provided. */ expiresAt?: number; } /** * Options for {@link OneAuthHeadlessClient.prepareIntent}. Mirrors the * subset of {@link SendIntentOptions} that's relevant when there is no * dialog UI involved (no `closeOn`, no `waitForHash`, etc.). */ interface HeadlessIntentOptions { /** Account address of the signer — the sole signer identity. */ accountAddress: string; targetChain: number; calls: IntentCall[]; tokenRequests?: IntentTokenRequest[]; sourceAssets?: string[]; sourceChainId?: number; /** Persisted handle from `installSmartSession`; required for SmartSession headless quotes. */ sessionKeyHandle?: SessionKeyHandle; /** Funding policy chosen at prepare time. Defaults to `required`. */ sponsorshipMode?: SponsorshipMode; } /** * Result of {@link OneAuthHeadlessClient.prepareIntent}. The host app * feeds `intentOp` and `digestResult` to its own SmartSession encoder * to produce signatures. */ interface HeadlessPrepareResult { /** * Serialized PreparedTransactionData from the orchestrator. Treat as * opaque on the wire; pass through to your validator's signer. */ intentOp: string; /** Serialized DigestResult (EIP-712 wrapped challenge + merkle proofs). */ digestResult: string; /** Per-origin EIP-712 message hashes. */ originMessages?: Array<{ chainId: number; messageHash: `0x${string}`; hash?: `0x${string}`; }>; /** Destination EIP-712 message hash for SmartSession destination signing. */ destinationMessageHash?: `0x${string}`; /** Target execution hash for same-chain / IntentExecutor settlements. */ targetExecutionMessageHash?: `0x${string}`; /** Top-level challenge (destination message hash for single-chain, merkle root otherwise). */ challenge: `0x${string}`; targetChain: number; /** JSON-stringified calls array (echoed for the submit step). */ calls: string; expiresAt: string; accountAddress: `0x${string}`; /** Cost / token-requirement breakdown from the orchestrator quote. */ quote?: IntentQuote; /** Funding mode of the authoritative quote. */ sponsorshipMode?: "sponsored" | "self-funded"; } /** * Options for {@link OneAuthHeadlessClient.submitIntent}. The caller supplies * pre-encoded validator-prefixed signatures; 1auth forwards them unchanged. * Funding mode and authorization come from the authoritative prepare result. */ interface HeadlessSubmitOptions { /** Echoed verbatim from the prepare result. */ intentOp: string; digestResult: string; /** Public smart account address; 1auth resolves the internal user server-side. */ accountAddress: `0x${string}`; targetChain: number; /** JSON-stringified calls array from the prepare result. */ calls: string; expiresAt: string; /** One per intent element. Each must already be validator-prefixed. */ originSignatures: OriginSignature[]; /** Validator-prefixed destination signature. */ destinationSignature: `0x${string}`; /** Extra SmartSession signature required by SAME_CHAIN / INTENT_EXECUTOR execution. */ targetExecutionSignature?: `0x${string}`; /** Funding mode returned by prepareIntent; sponsored submit mints a fresh grant. */ sponsorshipMode: "sponsored" | "self-funded"; } /** Result of {@link OneAuthHeadlessClient.submitIntent}. */ interface HeadlessSubmitResult { success: boolean; /** Orchestrator's intent ID (use with status / wait endpoints). */ intentId: string; status: string; /** Transaction hash when the submit endpoint can resolve it immediately. */ transactionHash?: string; /** Opaque transaction result required by POST /api/intent/wait. */ transactionResult?: unknown; statusUrl: string; waitUrl: string; } /** Result of the headless status and wait endpoints. */ interface HeadlessIntentStatusResult { intentId?: string; operationId?: string; status: string; transactionHash?: string; } export { type OneAuthCandidateError as $, type AuthResult as A, type CreateAccountWithModalOptions as B, type CloseOnStatus as C, type ConnectResult as D, type EmbedOptions as E, type AuthenticateOptions as F, type AuthenticateResult as G, type HeadlessIntentOptions as H, type InstallSmartSessionOptions as I, type SigningResultBase as J, type SignMessageOptions as K, type LoginWithModalOptions as L, type SignMessageResult as M, type SignTypedDataOptions as N, type SignTypedDataResult as O, type PasskeyProviderConfig as P, type EIP712Domain as Q, type EIP712Types as R, type SponsorshipConfig as S, type ThemeConfig as T, type EIP712TypeField as U, type TransactionAction as V, type WebAuthnSignature as W, type TransactionFees as X, type BalanceRequirement as Y, type TransactionDetails as Z, type OneAuthErrorDetails as _, type HeadlessPrepareResult as a, type OneAuthResultError as a0, type IntentTokenRequest as a1, type SendIntentOptions as a2, type IntentQuote as a3, type IntentStatus as a4, type OrchestratorStatus as a5, type PrepareIntentResponse as a6, type ExecuteIntentResponse as a7, type IntentHistoryOptions as a8, type IntentHistoryItem as a9, type SponsorshipUrlConfig as aA, type OneAuthTelemetryAttributeValue as aB, type OneAuthTelemetryAttributes as aC, type OneAuthTelemetryConfig as aD, type OneAuthTelemetryEvent as aE, type OneAuthTelemetryEventName as aF, type OneAuthTelemetryFlow as aG, type OneAuthTelemetryTraceContext as aH, type IntentHistoryResult as aa, type GetAssetsOptions as ab, type AssetBalance as ac, type AssetBalanceBucket as ad, type AssetsResponse as ae, type ConsentField as af, type ConsentData as ag, type CheckConsentOptions as ah, type CheckConsentResult as ai, type RequestConsentOptions as aj, type RequestConsentResult as ak, type GrantPermissionsOptions as al, type GrantPermissionsResult as am, type ListSessionGrantsOptions as an, type ListSessionGrantsResult as ao, type SessionGrantRecord as ap, type SessionGrantChain as aq, type GrantPermissionContractMetadata as ar, type SmartSessionPolicy as as, type BatchIntentItem as at, type SendBatchIntentOptions as au, type SendBatchIntentResult as av, type BatchIntentItemResult as aw, type PreparedBatchIntent as ax, type PrepareBatchIntentResponse as ay, type SponsorshipCallbackConfig as az, type HeadlessSubmitOptions as b, type HeadlessSubmitResult as c, type HeadlessIntentStatusResult as d, type InstallSmartSessionResult as e, type SessionKeyHandle as f, type SmartSessionEnableRequest as g, type SignerType as h, type IntentCall as i, type SendIntentResult as j, SIGNING_ERROR_CODES as k, isSigningErrorCode as l, createCrossChainPermission as m, type CreateCrossChainPermissionInput as n, type CrossChainPermit as o, type CrossChainSettlementLayer as p, type SigningRequestOptions as q, type SigningResult as r, type SigningSuccess as s, type SigningError as t, type SigningErrorCode as u, type PasskeyCredentials as v, type CreateSigningRequestResponse as w, type SigningRequestStatus as x, type AuthFlow as y, type AuthWithModalOptions as z };