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