# 1auth > Passkey-based authentication and transaction signing for smart accounts. ## Architecture Understanding how 1auth components work together to provide secure, gasless authentication and transactions. ### Overview 1auth is built on top of the [Rhinestone SDK](https://docs.rhinestone.dev/home/introduction/welcome-to-rhinestone), adding a passkey-based authentication layer to Rhinestone's chain abstraction and smart account infrastructure. The result: fully chain-abstracted accounts secured by passkeys. 1. **Security through passkeys** - WebAuthn provides hardware-backed, biometric authentication 2. **Full chain abstraction** - One account, one balance, works across all supported chains (one per app — see [Per-App Accounts](/architecture/accounts)) 3. **Simplicity through abstraction** - Complex blockchain operations are hidden from users 4. **Flexibility through standards** - Built on [ERC-7579](https://erc7579.com) modular accounts with EIP-1193 compatibility for wide tooling support ### System Components 1auth system architecture diagram ### 1auth Service The 1auth service runs at `passkey.1auth.app` and consists of two main parts: #### Passkey Provider (iframe) The passkey provider runs in an iframe embedded in your application and handles identity and review: * Email and OAuth identity verification * Transaction, message, and EIP-712 review * Intent preparation and user approval The WebAuthn ceremony itself runs in your top-level page, bound to your domain. Private keys never leave the user's authenticator. :::note[White-Labeling] The `passkey.1auth.app` domain can be whitelabeled to your own domain, so the wallet experience is fully branded and siloed to your application. Contact us for whitelabel setup. ::: ##### Session Scope Because the passkey provider runs on a dedicated domain (`passkey.1auth.app`), every 1auth passkey is stored by the browser and password manager under that one relying party, and credentials are never exposed to the embedding app. Sessions and accounts are scoped to the app: a user signed in to one 1auth app is not signed in to another, and a passkey registered on one app cannot sign in to a different one. See [Per-App Accounts](/architecture/accounts). #### 1auth Backend The backend integrates the [Rhinestone Orchestrator SDK](https://docs.rhinestone.dev) to handle onchain execution: * Receives signed intents from the passkey provider * Uses Rhinestone SDK to convert intents into executable transactions * Submits transactions across multiple chains * Handles gas sponsorship and transaction monitoring ### Chain Abstraction 1auth accounts are fully chain abstracted, powered by the Rhinestone SDK. Users interact with a single account that works seamlessly across all supported chains: | Feature | Description | | ------------------------- | ------------------------------------------------------------------- | | **Cross-chain execution** | Execute transactions on any supported chain from a single signature | | **Unified balances** | Users see aggregated balances across chains | | **Automatic bridging** | Assets are bridged as needed to fulfill transactions | | **Gas sponsorship** | Users never need native tokens for gas | | **MEV protection** | Transactions are protected from front-running and sandwich attacks | ### Crosschain Keystore The 1auth keystore maps a user's passkey-secured identity to their smart account ownership across supported chains. Instead of asking users to register and recover accounts chain-by-chain, 1auth keeps ownership changes coordinated so the same passkey and recovery configuration can apply wherever the account is used. This is what lets a recovered account regain access across chains with one authorization. The passkey remains the user's signing root, while the onchain account configuration gives every supported chain the same view of who can sign and who can authorize recovery. ### Smart Account Each user gets a fully [self-custodial](/self-custody) smart contract account that supports modular functionality via [ERC-7579](https://erc7579.com). The account is controlled by a passkey validator module that verifies WebAuthn signatures onchain—only the user can authorize transactions. Key features: * Counterfactual deployment (account exists before first transaction) * Modular architecture for extensibility * Same address on EVM chains * Address derived from your app's origin ([per-app accounts](/architecture/accounts)) ### Request Flow 1. **User Action** - User clicks PayButton or initiates transaction in your app 2. **SDK Request** - 1auth SDK sends the transaction request to the passkey provider iframe 3. **Passkey Signing** - User reviews and authenticates with Face ID/Touch ID 4. **Backend Processing** - Signed intent is sent to 1auth backend 5. **Rhinestone Execution** - Backend uses Rhinestone SDK to execute onchain 6. **Confirmation** - SDK receives confirmation, updates UI ### Learn More * [Rhinestone Documentation](https://docs.rhinestone.dev/home/introduction/welcome-to-rhinestone) - Deep dive into the underlying infrastructure * [Security](/architecture/security) - Threat model, origin isolation, and intent integrity * [Passkeys](/passkey) - How passkeys provide secure, non-custodial authentication ## FAQ ### General #### What is 1auth? 1auth is a passkey-based authentication and transaction signing SDK for smart accounts. It lets users authenticate and sign transactions using biometrics (Face ID, Touch ID, Windows Hello) instead of seed phrases or browser extensions. #### Do users need a wallet extension? No. 1auth uses passkeys which are built into modern browsers and operating systems. No extensions or apps required. #### Which chains are supported? 1auth supports any EVM-compatible chain. Transactions are executed via cross-chain intents, so users can pay from any chain. ### Accounts #### What type of account do users get? Each user gets a smart contract account (ERC-7579 modular account) controlled by their passkey. The account is fully self-custodial—only the user can authorize transactions. #### Is my account address the same on every chain? Yes. Your 1auth account has the same address on all EVM chains. You can receive funds on any chain to the same address. #### What is chain abstraction? Chain abstraction means users don't need to think about which chain they're on. Powered by [Rhinestone](https://rhinestone.wtf), 1auth handles bridging assets and executing transactions across chains automatically. Users see a unified balance and can pay from any chain. #### Do I need to bridge tokens manually? No. When you make a transaction, 1auth automatically bridges assets as needed. You never need to manually bridge or worry about having the right tokens on the right chain. #### Can I use the same account across different apps? No. Each app gets its own account for the same user — the address is derived from the app's origin, so a user's account on one app is not their account on another. See [Per-App Accounts](/architecture/accounts). ### Compatibility #### Which browsers are supported? Passkeys work in all modern browsers: | Browser | Support | | ------- | -------------------- | | Chrome | Full support (v109+) | | Safari | Full support (v16+) | | Firefox | Full support (v122+) | | Edge | Full support (v109+) | #### Which devices support passkeys? | Platform | Passkey Storage | | ----------- | -------------------------------------------- | | macOS / iOS | iCloud Keychain (syncs across Apple devices) | | Windows | Windows Hello | #### Do password managers work with passkeys? Yes. These password managers support passkey storage and sync: | Password Manager | Passkey Support | | ---------------- | ---------------------- | | 1Password | Full support | | Bitwarden | Full support | | iCloud Keychain | Native (Apple devices) | Using a password manager lets you sync passkeys across all your devices and browsers. ### Integration #### Do I need viem or wagmi? No. The React components work standalone without any web3 libraries. If you already use viem/wagmi, we provide adapters for those too. #### Can I test against 1auth from localhost? Not over plain HTTP. Passkeys (WebAuthn) require a [secure context](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts), which browsers grant to `http://localhost`, but the hosted provider (`passkey.1auth.app`) rejects a non-HTTPS app origin. Plain `http://localhost` therefore only works against a provider you run yourself in development mode. To develop locally, use one of these approaches: * **Self-signed certificate + `/etc/hosts`** — Generate a self-signed TLS cert, add an entry like `127.0.0.1 local.myapp.dev` to `/etc/hosts`, and serve your app over HTTPS on that hostname. * **[Tailscale](https://tailscale.com/kb/1153/enabling-https/)** — Tailscale can provision valid HTTPS certificates for your machine via `tailscale cert`, giving you a `*.ts.net` domain that works out of the box. * **[Caddy](https://caddyserver.com/)** — Use Caddy as a local reverse proxy; it automatically provisions locally-trusted TLS certificates. #### Is there a testnet? Yes. Pass `testnets: true` when creating your client to operate on testnet chains only: ```tsx const client = new OneAuthClient({ clientId: 'my-app', testnets: true }); ``` ### Security #### How are passkeys secured? Passkeys use public key cryptography. The private key never leaves the user's device and is protected by the device's secure enclave (TPM, Secure Enclave, etc.). #### What happens if a user loses their device? Passkeys sync across devices via iCloud Keychain, Google Password Manager, or Windows Hello. Users can also register multiple passkeys as backup. ## Introduction Passkey-based authentication and transaction signing for smart accounts. Build secure, gasless, cross-chain applications without the complexity. ### What is 1auth? 1auth provides a complete authentication and transaction signing solution built on top of WebAuthn passkeys and smart contract accounts. It enables your users to interact with blockchain applications using just their device's biometrics - no seed phrases, no browser extensions, no gas fees. ### Motivation Traditional wallet experiences create friction at every step. Users must manage seed phrases, install browser extensions, manage gas tokens, and understand complex blockchain concepts before they can interact with applications. The goal of 1auth is to abstract all this with a simple, but powerful, embedded wallet solution that leverages passkeys. Passkeys are an open source tool that any developer can leverage. So why use 1auth? Building a produciton-ready passkey wallet from scratch is hard: * **Key recovery** - If a user loses their device, how do they regain access? Passkeys sync across devices via platform providers (such as iCloud and Google), but coordinating this with onchain accounts in a self-custodial manner requires careful architecture. * **Crosschain key management (i.e., keystore)** - Passkey credentials must be mapped to smart account ownership across multiple chains, with proper validation methods deployed and maintained onchain. * **Crosschain complexity** - A single user action might require bridging assets, managing random gas tekens to execute on a different chain, and monitoring multiple transactions. * **Gas abstraction** - Users shouldn't need native tokens on every chain. Sponsoring gas requires paymaster integration and infrastructure across all supported chains. 1auth handles all of this so you can focus on your application. ### The advantages of 1auth * **Full self-custody** - Users hold their own keys in device secure hardware. 1auth never has access to private key material. * **Transact on any chain** - Your app's account works across all supported chains with automatic bridging and unified balances. * **No seed phrases, no extensions** - Users authenticate with Face ID or Touch ID, in any modern browser. * **Gasless by default** - Transactions are sponsored. Users never need native tokens. ### 1auth Use Cases #### Fintechs Build applications with crypto functionality while maintaining a non-custodial architecture. Because 1auth never holds keys, your application can align with unhosted wallet classifications under MiCA, SEC, and FinCEN frameworks. See [Self-Custody & Compliance](/self-custody). #### Crypto Consumer Apps Create a clean new user onboarding experience using familiar web2 flows (Oauth, SSO, etc) that is fully self-custodial, highly performant (with transaction signing local to the user), and with great economics (passkeys leverage existing device hardware at zero infrastructure cost). #### DeFi Onboarding Bring new users into DeFi without the traditional wallet setup barrier. 1auth's EIP-1193 provider works with viem, wagmi, and ethers, so you can integrate with existing DeFi tooling while offering a Web2-like sign-up experience. #### Multi-Chain Applications Build applications that work across chains without users managing multiple wallets or bridging assets manually. 1auth accounts have unified balances and execute transactions on any supported chain from a single signature. #### Agents Generate wallets for AI agents or enable co-piloted self-custodial wallets between your users and agents using session keys for scoped agent spending authorisations. ### Self-Custody 1auth is built on a fully self-custodial architecture. Private keys are generated and stored exclusively in the user's device secure hardware (Secure Enclave, TPM). 1auth cannot access, reconstruct, or use private keys—and cannot sign transactions or censor users on their behalf. This means users have true ownership of their assets with no third-party risk, while developers benefit from reduced compliance burden. [Learn more about Self-Custody & Compliance →](/self-custody) ## Why Passkeys Passkeys are the foundation of 1auth's security model. They provide a user-friendly alternative to passwords and seed phrases, while ensuring your users maintain full custody of their private keys. ### What are Passkeys? Passkeys are a modern authentication standard based on [WebAuthn (FIDO2)](https://www.w3.org/TR/webauthn-2/). Instead of remembering passwords or securing seed phrases, users authenticate with their device's built-in biometrics: * **Face ID** or **Touch ID** on Apple devices * **Windows Hello** on Windows devices * **Fingerprint sensors** on Android devices Each passkey is bound to a specific domain and protected by the device's secure hardware. They cannot be reused on a different site, which makes credential theft through fake websites ineffective. ### How Passkeys Work Passkeys use public key cryptography: 1. **Registration**: When a user creates an account, their device generates a key pair. The private key is stored in secure hardware (Secure Enclave, TPM), while the public key is sent to the server. 2. **Authentication**: When signing in or signing a transaction, the server sends a challenge. The device signs this challenge with the private key after biometric verification. 3. **Verification**: The server verifies the signature using the stored public key. The critical point: **the private key never leaves the device**. The server only ever sees the public key and signed challenges. ``` ┌─────────────────────────────────────────────────────────┐ │ User's Device │ │ │ │ ┌──────────────────┐ ┌─────────────────────────┐ │ │ │ Biometric │ │ Secure Hardware │ │ │ │ Verification │─────▶│ (Secure Enclave) │ │ │ │ │ │ │ │ │ │ Face ID │ │ Private Key Stored │ │ │ │ Touch ID │ │ Signing Operations │ │ │ └──────────────────┘ └───────────┬─────────────┘ │ │ │ │ └────────────────────────────────────────┼────────────────┘ │ Signed Intent ▼ ┌─────────────────────┐ │ 1auth Server │ │ │ │ Public Key Only │ │ No Key Material │ └─────────────────────┘ ``` ### Benefits #### For Users * **Full self-custody** - Private keys live in your device's secure hardware. No third party—including 1auth—can access or move your assets. Secure enough for anyone to use. * **No passwords or seed phrases** - Just use Face ID or Touch ID. Nothing to remember, write down, or lose. * **Cross-platform sync** - Passkeys sync across your devices via iCloud Keychain, Google Password Manager, or Windows Hello, so you're never locked to a single device. * **Simple and familiar** - The same biometric experience as unlocking your phone or making an Apple Pay purchase. #### For Developers * **Self-custody = regulatory hedge** - Because users hold their own keys, your application can align with non-custodial wallet classifications. No custody license required. * **Clean user onboarding** - No wallet downloads, no seed phrase UX, no browser extension requirements. Users sign up with a single biometric prompt. * **Fast conversion** - Users are more likely to complete sign-up without password friction or extension install steps. * **Cost-effective** - No MPC infrastructure, no key management servers, no HSMs. Passkeys leverage existing device hardware at zero infrastructure cost. * **Standard browser APIs** - WebAuthn is supported in all modern browsers with no dependencies. ### Passkey Support Passkey support is effectively universal on modern hardware. | Platform | Passkey Support | Source | | --------------- | --------------- | ---------------------------------------------------- | | **iOS / macOS** | 95%+ | [passkeys.dev](https://passkeys.dev/device-support/) | | **Android** | 95%+ | [passkeys.dev](https://passkeys.dev/device-support/) | | **Windows** | \~75% | [passkeys.dev](https://passkeys.dev/device-support/) | :::note[Windows Support] TPM 2.0—which enables Windows Hello and passkey support—has been built into essentially all CPUs since 2015 (Intel PTT, AMD fTPM). Microsoft **mandated** it for all new Windows device certifications **starting 2016**. ::: #### Password Manager Support Major password managers also support passkey storage and sync, extending coverage beyond platform-native implementations: | Password Manager | Passkey Support | | ---------------- | ------------------------------- | | **1Password** | Full support (all platforms) | | **Dashlane** | Full support (all platforms) | | **Bitwarden** | Full support (all platforms) | | **Enpass** | Full support (desktop + mobile) | | **NordPass** | Full support (all platforms) | This means users can store and sync passkeys through their preferred password manager, independent of their device platform. ### How 1auth Uses Passkeys 1auth leverages passkeys throughout the authentication and transaction flow: 1. **Account Creation** - User registers a passkey, creating a smart account controlled by that passkey 2. **Authentication** - Users authenticate with biometrics via WebAuthn 3. **Transaction Signing** - EIP-712 typed data is signed using the passkey's private key 4. **Origin Binding** - The WebAuthn ceremony runs in your page, and 1auth verifies the exact origin and RP ID before accepting a signature This architecture ensures that even if your application is compromised, the user's private keys remain protected in their device's secure hardware. ## Quick Start :::info[Local HTTPS required] Passkeys need a [secure context](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts), and the hosted provider requires an HTTPS app origin — plain `http://localhost` is accepted only by a provider you run yourself in development. [Three ways to set up local HTTPS →](/faq#can-i-test-against-1auth-from-localhost) ::: ::::steps #### Install the SDK :::code-group ```bash [npm] npm install @rhinestone/1auth ``` ```bash [yarn] yarn add @rhinestone/1auth ``` ```bash [pnpm] pnpm add @rhinestone/1auth ``` ::: #### Get a JWT signing key Every user intent is authenticated with your app's JWT — there is no anonymous fallback. Create an app in the [Rhinestone dashboard](https://dashboard.rhinestone.dev) to generate a signing key, then expose two same-origin endpoints that mint the JWTs the SDK attaches to each intent. See [Fee Sponsorship](/guides/fee-sponsorship) for the full server setup. #### Initialize Client ```tsx import { OneAuthClient } from "@rhinestone/1auth"; const client = new OneAuthClient({ providerUrl: "https://passkey.1auth.app", clientId: "my-app", // Required for intents — points at the endpoints you created above. sponsorship: { accessTokenUrl: "/api/sponsorship/access-token", extensionTokenUrl: "/api/sponsorship/extension-token", }, }); ``` The WebAuthn ceremony runs in your own page, and every distinct hostname gets its own passkey and smart account. See [App-origin passkeys](/guides/app-origin-passkeys). :::tip A client without `sponsorship` configured rejects every `sendIntent` call with `MISSING_APP_CREDENTIALS`. See [Fee Sponsorship](/guides/fee-sponsorship) to wire up the token endpoints. ::: #### Send your first transaction A sponsored intent needs nothing sourced from the user, so this runs on a brand-new account with a zero balance. Mint yourself 1 mUSD — a faucet token on Base Sepolia that anyone can mint — and the whole chain proves out at once: credentials, origin, passkey, orchestrator, sponsorship. ```tsx import { encodeFunctionData, parseAbi, parseUnits } from "viem"; const MUSD_BASE_SEPOLIA = "0x2f6fdE5E2AeAB6335d8f978B4d8B2a9c1129AcFb"; const auth = await client.authenticate(); if (!auth.success) throw new Error(auth.error.message); const result = await client.sendIntent({ accountAddress: auth.session.accountAddress, targetChain: 84532, // Base Sepolia calls: [ { to: MUSD_BASE_SEPOLIA, data: encodeFunctionData({ abi: parseAbi(["function mint(address to, uint256 amount)"]), functionName: "mint", args: [auth.session.accountAddress, parseUnits("1", 6)], }), label: "Mint", sublabel: "1 mUSD", }, ], }); console.log(result.success ? result.intentId : result.error?.code); ``` There is no `tokenRequests` here, which is why an empty account works — nothing has to be sourced or bridged. Add `tokenRequests` once a target-chain call needs tokens delivered to it first; see [Crosschain](/guides/crosschain), which starts from the mUSD you just minted. :::: ### Next Steps
React Components

Drop-in components like PayButton and BatchQueue. No viem or wagmi required.

Viem / Wagmi

Use createPasskeyWalletClient for viem-compatible signing in existing web3 apps.

### References * [API Reference](/sdk) - Full SDK documentation * [RPC Reference](/rpc) - EIP-1193 provider methods * [npm](https://www.npmjs.com/package/@rhinestone/1auth) - Install the SDK package * [Example App](https://github.com/rhinestonewtf/1auth-example-app) - Reference integration ## Self-Custody & Compliance Passkeys enable true self-custody of crypto assets, which has significant implications for regulatory compliance. ### Self-Custody Tests 1auth's architecture passes the key tests that distinguish a self-custodial wallet from a custodial service: | Test | 1auth | | ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | **Provider cannot access private keys** | Keys are generated and stored exclusively in user device hardware (Secure Enclave, TPM). 1auth never sees key material. | | **Provider cannot sign transactions** | All signing happens on-device via WebAuthn. 1auth has no technical ability to produce valid signatures. | | **Provider cannot censor or block users** | 1auth cannot prevent a user from signing or submitting transactions. Users can also interact with their smart account directly onchain. | | **Provider cannot freeze or seize funds** | Assets are held in user-owned smart contract accounts. 1auth has no admin keys or backdoors. | | **User can recover access independently** | Passkeys sync across devices via platform providers (iCloud Keychain, Google Password Manager). Users can also add backup passkeys or recovery modules to their smart account. | | Test | 1auth | | ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | **The "Reconstruction" Test:** Provider cannot access or reconstruct the private keys | Keys are generated and stored exclusively in user device hardware (Secure Enclave, TPM). 1auth never sees the key material. | | **The "Seizure" Test:** Provider cannot sign transactions or withdraw funds | All signing happens on-device via WebAuthn. 1auth has no technical ability to produce valid signatures. | | **The "Censorship" Test:** Provider cannot block users | 1auth cannot prevent a user from signing or submitting transactions. Users can also interact with their smart account directly onchain. | | **The "Independency" Test:** User can recover access independently | Passkeys sync across devices via platform providers (iCloud Keychain, Google Password Manager). 1auth also provides a recovery module with a recovery path that is independent of 1auth systems. | #### Portability A common concern with any wallet provider: what happens if the service shuts down? * **Passkeys are synced by platform providers** - iCloud Keychain, Google Password Manager, and password managers like 1Password store and sync passkeys independently of 1auth. * **Smart accounts are onchain** - User accounts exist as smart contracts on public blockchains. They continue to function regardless of whether 1auth's service is running. * **Direct onchain interaction** - Users can interact with their smart account directly through any EVM-compatible tool (e.g., Etherscan, Cast) using their passkey-derived signature. * **Module-based recovery** - Users can install recovery modules (social recovery, backup keys) on their smart account for additional portability. ### Regulatory Framework Alignment This self-custodial design aligns with major regulatory frameworks: **European Union (MiCA)** * Custody requires safekeeping crypto-assets or means of access (like private keys) * 1auth doesn't hold assets or keys—users retain exclusive control * Meets requirements for non-custodial service classification **United States (SEC/FinCEN)** * Guidance distinguishes "hosted" (custodial) from "unhosted" (non-custodial) wallets * Unhosted wallets: users independently control keys and transact directly * 1auth's architecture aligns with unhosted wallet classification ### What This Means for You | Stakeholder | Benefit | | --------------- | ---------------------------------------------------------------------------- | | **Developers** | Reduced compliance burden when adding crypto functionality to your app | | **Users** | Full ownership of assets with no third-party risk | | **Enterprises** | Architecture compatible with self-custodial positioning in regulated markets | ### Passkeys vs Traditional Approaches
| | Seed Phrases | Browser Extensions | Custodial | MPC | TEE (server) | **Passkeys (1auth)** | | ------------------------- | ----------------------------------------------- | ----------------------------------------------- | ----------------------------------------------- | --------------------------------------------------- | --------------------------------------------------- | ----------------------------------------------- | | **Key on User Device** | **Yes** | **Yes** | **No** | **No** | **No** | **Yes** | | **Hardware-Protected** | **No** | **No** | **No** | **Depends** | **Depends** | **Yes** | | **Self-Custody** | **Yes** | **Yes** | **No** | **No** | **No** | **Yes** | | **Provider Can't Sign** | **Yes** | **Yes** | **No** | **No** | **No** | **Yes** | | **Provider Can't Censor** | **Yes** | **Yes** | **No** | **Depends** | **No** | **Yes** | | **Recoverable** | **No** | **No** | **Yes** | **Yes** | **Yes** | **Yes** | | **Great UX** | **No** | **No** | **Yes** | **Yes** | **Yes** | **Yes** |
import { GrantPermissionDemo } from "../../layout"; ### Overview `OneAuthClient` is the core class of the 1auth SDK. It handles all interactions with the passkey authentication system including: * User registration and authentication * Transaction signing with multiple UX modes * Cross-chain intent submission * Token swaps ### Constructor ```tsx import { OneAuthClient } from "@rhinestone/1auth"; const client = new OneAuthClient({ providerUrl: "https://passkey.1auth.app", clientId: "my-app", sponsorship: { accessTokenUrl: "/api/sponsorship/access-token", extensionTokenUrl: "/api/sponsorship/extension-token", }, theme: { mode: "dark", accent: "#6366f1", }, recovery: { // Passkey recovery is attempted first. This controls only the fallback. fallback: { type: "verified-identity" }, }, }); ``` #### Config Options | Option | Type | Required | Description | | ---------------------------- | ------------------------ | -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `providerUrl` | `string` | No | URL of the 1auth provider (defaults to `https://passkey.1auth.app`) | | `clientId` | `string` | For app sponsorship/developer features | Identifies app metadata for sponsorship, attribution, recovery guardians, and related features. It does not select the browser WebAuthn RP namespace. | | `webauthn` | `{ rpId?: string }` | No | WebAuthn runs in your top-level page with the exact page hostname as RP ID unless `rpId` selects a shared namespace. A custom `rpId` requires `clientId`. | | `sponsorship` | `SponsorshipConfig` | For intents and assets | Endpoints (or callbacks) that mint your app's JWT. Required by `sendIntent`, `sendBatchIntent`, `grantPermissions`, and `getAssets`; setting an individual intent's `sponsor` flag to `false` skips its extension token, not the app access token. Each method reports missing or failed credentials through its own result/exception contract, detailed below. Get a signing key from the [Rhinestone dashboard](https://dashboard.rhinestone.dev); see [Fee Sponsorship](/guides/fee-sponsorship). | | `dialogUrl` | `string` | No | URL for the dialog UI (defaults to `providerUrl`) | | `storageKey` | `string` | No | Provider session storage key cleared on disconnect (defaults to `"1auth-user"`). A `storageKey` supplied to `createOneAuthProvider()` or `createOneAuthConnection()` takes precedence for that bound client. | | `theme` | `ThemeConfig` | No | UI customization options | | `experimental_clear_signing` | `boolean` | No | Experimental. Show the 1auth signing review iframe before WebAuthn. Defaults to `false`; [blind signing](/guides/signing) remains the established flow. | | `testnets` | `boolean` | No | When `true`, chain queries prefer testnets. `wallet_getAssets` always returns grouped mainnet and testnet balances. | | `prewarm` | `boolean` | No | When `true`, schedules a one-time [`prewarm()`](#prewarm) on an idle callback after construction. Off by default — prefer calling `prewarm()` on button hover/focus. | | `recovery` | `AccountRecoveryConfig` | No | Controls account creation when passkey-based recovery is unavailable. Defaults to an encrypted backup file. Options: `backup-file`, `verified-identity`, or `block`. | | `telemetry` | `OneAuthTelemetryConfig` | No | Bridges SDK events and trace context into the host app's observability setup. Enabled by default when configured; set `enabled: false` to disable it. | | `onDisconnect` | `() => void` | No | Called after the SDK clears its session when a trusted passkey dialog invalidates it, including deployment-forced logout. Use it to clear host-app in-memory authentication state. | #### Account recovery fallback Passkey-based recovery is always attempted first. Configure `recovery.fallback` to decide what account creation does when the selected passkey provider cannot support it: ```tsx const client = new OneAuthClient({ recovery: { fallback: { type: "verified-identity" }, }, }); ``` * `backup-file` — default; ask the user to save an encrypted recovery file. * `verified-identity` — rely on the verified email or OAuth recovery guardian. * `block` — refuse account creation unless passkey-based recovery succeeds. ### Authentication Methods #### authenticate Authenticate using the verified identity's current account state. The server selects registration when no account exists, login when a usable passkey exists, and recovery when the account has no usable passkey or the authentication ceremony is rejected. Identity and recovery UI stay in 1auth, while WebAuthn runs in the top-level app page. ```tsx const result = await client.authenticate(); if (result.success) { console.log("Address:", result.session.accountAddress); // typed `0x${string}` } ``` `authenticate({ flow: "login" })` and `authenticate({ flow: "create-account" })` pass the requested intent as a hint; the server remains authoritative for account-state classification. #### getSession Return the current session as an `AuthResult`. The stored bearer is verified with the passkey service, and a rejected session disconnects the client. ```tsx const session = await client.getSession(); if (session.success) { console.log("Address:", session.session.accountAddress); } else if (session.error.code === "APP_ORIGIN_SESSION_REQUIRED") { await client.authenticate(); } ``` ### Asset Methods #### getAssets Fetches a unified portfolio across mainnets and testnets by account address. This uses your configured `sponsorship.accessToken` to send an app JWT to the 1auth provider before any balance data is returned. ```tsx const assets = await client.getAssets({ accountAddress: "0x1111111111111111111111111111111111111111", }); console.log("All balances:", assets.balances); console.log("Mainnet balances:", assets.mainnets.balances); console.log("Testnet balances:", assets.testnets.balances); ``` `getAssets()` is exception-based. Missing sponsorship, token callback failures, and portfolio request failures reject with an `Error`; handle the call with `try`/`catch`. ### Signing Methods #### signWithModal Full-screen modal with transaction details: ```tsx const result = await client.signWithModal({ accountAddress: "0x...", challenge: "0x...", description: "Review and sign", transaction: { actions: [{ type: "custom", label: "Approve action" }], }, }); ``` The 1auth iframe renders review, then the SDK runs WebAuthn on the exact top-level application origin and returns the verified signature. The flow requires an active session and correlates iframe approval by exact window source, provider origin, request ID, and per-modal nonce. #### experimental\_clear\_signing Set `experimental_clear_signing: true` to evaluate 1auth's visible review iframe for supported signing flows. The user reviews the payload before the passkey ceremony starts; the browser's WebAuthn prompt is still shown. ```tsx const client = new OneAuthClient({ providerUrl: "https://passkey.1auth.app", clientId: "my-app", experimental_clear_signing: true, }); const result = await client.sendIntent({ accountAddress: "0x...", targetChain: 8453, calls: [{ to: "0x...", data: "0x..." }], }); ``` Per-call options can override the client setting: ```tsx await client.sendIntent({ accountAddress: "0x...", targetChain: 8453, calls: [{ to: "0x...", data: "0x..." }], experimental_clear_signing: false, }); ``` The option applies to `sendIntent` and `sendBatchIntent`. `signMessage`, `signTypedData`, and `signWithModal` always show the review before WebAuthn. It does not apply to signup, login, recovery, or permission-grant dialogs. See [Signing](/guides/signing) for limitations and failure behavior. ### Intent Execution #### sendIntent Submit cross-chain intents to the Rhinestone orchestrator. ```tsx const result = await client.sendIntent({ accountAddress: "0x...", targetChain: 8453, calls: [ { to: "0x...", data: "0x...", value: parseEther("0.1"), label: "Mint NFT", // Optional — shown in the sign dialog sublabel: "0.10 USDC", icon: "https://your-app.example/nft.svg", // Optional fallback icon }, ], closeOn: "completed", }); if (result.success) { console.log("TX Hash:", result.transactionHash); } ``` `sendIntent()` is result-based for sponsorship failures. Missing configuration returns `success: false` with `error.code === 'MISSING_APP_CREDENTIALS'`. Access-token or extension-token failures return `success: false` with `error.code === 'SPONSORSHIP_FETCH_FAILED'`; the visible dialog may first offer its prepare retry flow. `sendBatchIntent()` uses a different result shape. It reports top-level failures through its own optional `errorCode` and `error` fields rather than a nested `error.code`, and some paths populate neither — a failed access-token fetch returns only `success: false` with empty `results`, surfacing the reason through SDK telemetry instead. Missing sponsorship sets `error`. See [Troubleshooting](/guides/troubleshooting) for the full list and how to read it. Each call in `calls` is an `IntentCall` and accepts four optional UI fields: | Field | Description | | ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `label` | Primary line in the sign dialog action card (e.g. `"Mint NFT"`) | | `sublabel` | Secondary line under the label (e.g. `"0.10 USDC"`) | | `icon` | Fallback icon URL (SVG / square PNG / `data:` URL, ≤ 8 KB) shown when 1auth's built-in token registry can't resolve a logo. **Built-in icons always win** — USDC / ETH / MATIC etc. ignore `icon`. | | `abi` | Optional ABI used by the sign dialog to render an **unverified** human-readable decode of `data` (function name + args). Same trust model as `label` / `sublabel` / `icon` — the dialog renders the decoded preview behind an "Unverified" badge and always shows the raw `to` + selector alongside as ground truth. See [Per-call ABIs](/sdk/wallet-client#per-call-abis). | ##### With Token Requests (Output-First) Use `tokenRequests` to specify what tokens a target-chain call needs before it executes. The orchestrator determines the optimal path to deliver them from the user's assets across any chain. ```tsx import { encodeFunctionData, parseUnits } from "viem"; const USDC_BASE = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"; const amount = parseUnits("100", 6); const transferData = encodeFunctionData({ abi: erc20Abi, functionName: "transfer", args: ["0xRecipient...", amount], }); const result = await client.sendIntent({ accountAddress: "0x...", targetChain: 8453, calls: [ { to: USDC_BASE, data: transferData, label: "Send USDC", sublabel: "100 USDC", }, ], tokenRequests: [ { token: USDC_BASE, amount, }, ], closeOn: "completed", }); ``` This is ideal for app actions such as transfers, deposits, and purchases that need an output token before execution. For a plain swap where the user only receives the output token, call `sendIntent` with `calls: []` rather than adding placeholder calldata. Pass `waitForHash: true` if you need a transaction hash. Otherwise, rely on `intentId` + `getIntentStatus`. #### grantPermissions Grant a scoped SmartSession permission to an app-owned session key. 1auth opens the permission review, collects the user's passkey approval, and submits the install/enable transaction. Your app sends only the public `sessionKeyAddress`; keep the private key in your own signer. ```tsx import { definePermissions, OneAuthClient } from "@rhinestone/1auth"; import { generatePrivateKey, privateKeyToAccount } from "viem/accounts"; import { parseUnits } from "viem"; const oneAuth = new OneAuthClient({ providerUrl: "https://passkey.1auth.app", clientId: "my-app", sponsorship: { accessTokenUrl: "/api/sponsorship/access-token", extensionTokenUrl: "/api/sponsorship/extension-token", }, }); const privateKey = generatePrivateKey(); const sessionKeyAddress = privateKeyToAccount(privateKey).address; const now = Math.floor(Date.now() / 1000); const validUntil = now + 24 * 60 * 60; const permissions = definePermissions({ address: mUSD, name: "mUSD", abi: erc20Abi, functions: { mint: { params: { to: { condition: "equal", value: accountAddress }, amount: { condition: "equal", value: parseUnits("0.1", 6) }, }, }, }, }); const result = await oneAuth.grantPermissions({ accountAddress, targetChains: [84532], sessionKeyAddress, validAfter: now, validUntil, maxUses: 25, ...permissions, }); ``` `grantPermissions()` also reports sponsorship failures as structured results: `MISSING_APP_CREDENTIALS` when sponsorship is not configured and `SPONSORSHIP_FETCH_FAILED` when the access-token callback fails. After this grant succeeds, the app can prepare and submit a matching `mUSD.mint(accountAddress, parseUnits('0.1', 6))` intent with its session key. That later mint does not open another 1auth user-signature dialog; the SmartSession validator enforces the `to` and `amount` constraints on-chain. For bridge or cross-chain swap sessions, include a bridge claim permission with `crossChainPermits`. Selector permissions still describe the destination-chain calls; `crossChainPermits` describes the source-chain Permit2 claim that funds the route. ```tsx import { createCrossChainPermission, definePermissions, } from "@rhinestone/1auth"; import { parseUnits } from "viem"; import { arbitrumSepolia, baseSepolia } from "viem/chains"; const ARB_SEPOLIA = 421614; const BASE_SEPOLIA = 84532; const amount = parseUnits("0.1", 6); const now = Math.floor(Date.now() / 1000); const validUntil = now + 86400; const usdcOnArb = "0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d"; const swap = definePermissions({ address: rwaSwap, name: "RWASwap", abi: rwaSwapAbi, functions: { swap: { params: { usdcIn: { condition: "equal", value: amount }, recipient: { condition: "equal", value: accountAddress }, }, }, }, }); const bridge = createCrossChainPermission({ from: { chain: baseSepolia, token: mUSDOnBase, maxAmount: amount }, to: { chain: arbitrumSepolia, token: usdcOnArb, recipient: accountAddress }, validAfter: BigInt(now), validUntil: BigInt(validUntil), settlementLayers: ["ACROSS"], }); await oneAuth.grantPermissions({ accountAddress, // Destination chain for swap; source chain for Permit2 claim. targetChains: [ARB_SEPOLIA], sourceChains: [BASE_SEPOLIA], sessionKeyAddress, validAfter: now, validUntil, maxUses: 25, permissions: swap.permissions, crossChainPermits: [bridge], contracts: swap.contracts, }); ``` The source chain must be in `sourceChains`. During settlement, Permit2 verifies the claim by calling `isValidSignature` on the source-chain account, so the SmartSession validator must be installed and enabled there too. #### Plain swaps Plain swaps use `sendIntent` with an empty `calls` array and one or more `tokenRequests`: ```tsx import { parseUnits } from "viem"; const USDC_BASE = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"; const result = await client.sendIntent({ accountAddress: "0x...", targetChain: 8453, calls: [], tokenRequests: [ { token: USDC_BASE, amount: parseUnits("100", 6), }, ], sourceAssets: ["0x0000000000000000000000000000000000000000"], }); ``` For routes that fund target-chain execution, use `sendIntent` or [`walletClient.sendCalls`](/sdk/wallet-client) with real calls plus explicit `tokenRequests`. Do not pass dummy `data: '0x'` calls or self-transfers just to make an intent shape fit. ### Utility Methods #### getIntentStatus Poll for transaction completion: ```tsx const status = await client.getIntentStatus(intentId); console.log(status.status); // 'pending' | 'completed' | 'failed' ``` #### setTheme Update theme at runtime: ```tsx client.setTheme({ accent: "#10b981", mode: "dark", }); ``` #### prewarm Load the dialog ahead of the first user interaction so it opens instantly. The SDK already pre-connects (DNS/TLS) at construction; `prewarm()` goes further and loads the dialog bundle + font into a hidden iframe, so when the user opens a real dialog it paints from cache instead of doing a cold load. Call it on a **likely-intent signal** — hover or focus of your sign-in / pay button — so pages where the user never authenticates don't pay for the dialog iframe: ```tsx ``` `prewarm()` is idempotent and best-effort: it never throws and never blocks a real open (a failed warm just falls back to a normal load). It resolves `true` once the dialog bundle has loaded. It loads a dedicated, side-effect-free warm route (it runs no auth flow and creates no backend state), which still warms the shared bundle every dialog flow reuses. Call `client.destroyPrewarm()` to release the hidden iframe when auth is no longer likely on the current view. :::tip Prefer hover/focus warming over the `prewarm: true` config flag — the flag warms on every page load (even ones with no auth), while hover/focus warms only when the user reaches for the button. ::: ### Error handling SDK methods preserve machine-readable codes and provider diagnostics for signing, intent, simulation, sponsorship, and network failures. ```tsx const result = await client.sendIntent({ ... }) if (!result.success) { console.error(result.error?.code, result.error?.details) } ``` See [Error Codes and Diagnostics](/guides/error-handling) for the complete code reference, `OneAuthError` usage, simulation links, trace IDs, and recommended application behavior. ### Supported Networks 1auth supports all chains in the Rhinestone orchestrator network. Query supported chains at runtime: ```tsx import { getSupportedChainIds, getSupportedChains } from "@rhinestone/1auth"; // Catalog IDs include every orchestrator-supported EVM chain. const chainIds = await getSupportedChainIds(); // viem Chain objects are returned when the installed viem version defines them. const chains = await getSupportedChains(); // Include testnets or restrict discovery to an explicit allowlist. const testnets = await getSupportedChains({ includeTestnets: true }); const selected = await getSupportedChains({ chainIds: [1, 8453] }); ``` Mainnet chains include Ethereum, Base, Arbitrum, Optimism, Polygon, and others. The `targetChain` parameter in `sendIntent()` accepts any supported chain ID. ### Transaction Lifecycle When you call `sendIntent()`, the transaction progresses through these stages: | Status | Description | | -------------- | ------------------------------------------------- | | `pending` | Intent created, waiting for quote | | `quoted` | Quote received from orchestrator | | `signed` | User has signed with their passkey | | `submitted` | Submitted to the Rhinestone orchestrator | | `claimed` | A solver has claimed the intent | | `preconfirmed` | Pre-confirmation received (typically \< 1 second) | | `filled` | Transaction filled on the target chain | | `completed` | Fully confirmed on-chain | | `failed` | Intent failed | | `expired` | Intent expired before execution | The `closeOn` option controls when `sendIntent()` resolves: * `"preconfirmed"` (default) — Resolves quickly, recommended for most use cases * `"claimed"` — Resolves at first solver claim (fastest, less certain) * `"filled"` — Resolves when the transaction hits the target chain * `"completed"` — Waits for full on-chain confirmation (slowest) For a transaction hash, pass `waitForHash: true` or poll with `getIntentStatus()` after the intent resolves. ### Notes * Create one client instance and reuse it * Use the `closeOn` parameter to control when promises resolve * The client handles identity verification and WebAuthn orchestration internally. * Browser credentials and accounts are isolated by the exact hostname unless a registered shared RP ID and exact server-authorized `rpOrigins` are configured. The SDK sends only `rpId`; origins are never client-owned configuration. import { LivePreview, WalletConnectDemo } from "../../layout" `createOneAuthConnection` gives the host application one connection lifecycle for two distinct signer types: * an **app-origin passkey** smart account authenticated by `OneAuthClient`; or * an **external EIP-1193 wallet** selected and connected by the host application's wallet UI. The host owns the choice. The SDK calls `selectConnection()` every time `connect()` runs and opens only the selected branch. It never tries the other branch after cancellation or failure. ### Live preview This demo calls the public `wallet_connect` provider method. It opens an explicit choice between the user's 1auth passkey account and an external wallet. Use `eth_requestAccounts` instead for the normal passkey-only authentication flow. Use `eth_accounts` to passively read the currently authorized account without opening any connection UI. ### Complete example This example uses a simple host-owned selector and an injected wallet such as MetaMask or Rabby. In a production application, replace `window.confirm` with your own account selector and injected-provider discovery UI. ```tsx import { createOneAuthConnection, type OneAuthConnectionSelection, } from '@rhinestone/1auth'; import type { EIP1193Provider } from 'viem'; declare global { interface Window { ethereum?: EIP1193Provider; } } async function selectConnection(): Promise { return window.confirm('Use your app passkey?') ? 'passkey' : 'external_wallet'; } const connection = createOneAuthConnection({ clientId: 'my-app', selectConnection, connectExternalWallet: async () => { const provider = window.ethereum; if (!provider) throw new Error('No injected wallet found'); const accounts = await provider.request({ method: 'eth_requestAccounts', }) as `0x${string}`[]; const chainIdHex = await provider.request({ method: 'eth_chainId', }) as string; if (!accounts[0]) throw new Error('The wallet returned no account'); return { provider, address: accounts[0], chainId: Number.parseInt(chainIdHex, 16), }; }, }); const session = await connection.connect(); if (session.signerType === 'passkey') { // App-origin 1auth smart account. Sends route through 1auth intents. console.log(session.accountAddress); } else { // Host-connected EOA. Requests route to the selected external wallet. console.log(session.chainId); } // Use the returned wrapper for both session types, not the injected provider. await session.provider.request({ method: 'eth_sendTransaction', params: [{ from: session.accountAddress, to: '0x1111111111111111111111111111111111111111', value: '0x1', }], }); ``` `connectExternalWallet()` must return the provider, selected address, and current numeric chain ID: ```ts interface OneAuthExternalWalletConnection { provider: EIP1193Provider; address: `0x${string}`; chainId: number; } ``` The `provider` returned in the session is the 1auth EIP-1193 wrapper, not the raw injected provider. Keep using the session provider so routing remains bound to the selected signer and account. ### Session union `connect()` and `getSession()` return a discriminated union: ```ts type OneAuthConnectionSession = | { signerType: 'passkey'; accountAddress: `0x${string}`; provider: OneAuthProvider; chainId: number; autoConnected: boolean; } | { signerType: 'eoa'; accountAddress: `0x${string}`; provider: OneAuthProvider; chainId: number; autoConnected: boolean; }; ``` Branch on `signerType`, not on the address shape. Both variants use an Ethereum address, but only the passkey variant sends transactions through 1auth intents. The EOA variant forwards supported account, signing, transaction, and chain requests to the host-connected external provider. New sessions returned by `connect()` have `autoConnected: false`. At construction time, `getSession()` can restore a persisted app-origin passkey identity for the configured `storageKey`; external-wallet provider connections are host-owned and are not reconstructed from passkey storage. ### Request routing and account safety The active session determines all later provider routing: * Passkey signing and transaction requests use the app-origin passkey account and 1auth intent path. * EOA requests use the external provider returned by `connectExternalWallet()`. * `eth_accounts` exposes only the selected account. * External wallet account, chain, and disconnect events are mirrored through the returned wrapper. For methods that name a signer, including `personal_sign`, typed-data signing, `eth_sendTransaction`, and `wallet_sendCalls`, the SDK fills a missing signer with `session.accountAddress`. If a request explicitly supplies a different address, it rejects with `ACCOUNT_MISMATCH` instead of forwarding the request to the wallet. ### Reconnect, switch, and disconnect Call `connect()` again whenever the user asks to connect or switch accounts. `selectConnection()` runs again, so the host can choose either branch: ```ts const unsubscribe = connection.subscribe((session) => { // A new session is published after a successful connect or switch. // null is published after disconnect. renderConnection(session); }); const nextSession = await connection.connect(); await connection.disconnect(); unsubscribe(); ``` A successful switch replaces the active signer before `connect()` resolves. Switching away from a passkey clears its provider session; switching external wallets clears the previous external routing. Later requests therefore use only the newly selected signer. `disconnect()` clears the active passkey or external-wallet routing, removes persisted passkey connection state, mirrors provider disconnect events, and publishes `null` to subscribers. Calling it with no active session is a no-op. ### Cancellation and failure `selectConnection()` and `connectExternalWallet()` are host callbacks, so they can reject with the host's cancellation error. A selector result other than `'passkey'` or `'external_wallet'` is rejected with code `USER_CANCELLED`. An invalid external connection is rejected with code `EXTERNAL_WALLET_INVALID`. Cancellation or failure leaves the previous successful session active. The unselected branch is not invoked. For example, a cancelled external-wallet flow does not open passkey authentication, and failed passkey authentication does not call `connectExternalWallet()`. ### Configuration You can construct the client from ordinary `OneAuthClient` configuration or provide an existing client: ```ts const connection = createOneAuthConnection({ client: appOriginClient, selectConnection, connectExternalWallet, }); ``` | Option | Type | Required | Description | | ----------------------- | ------------------------------------------------------- | -------- | --------------------------------------------------------------------------------------------------- | | `selectConnection` | `() => 'passkey' \| 'external_wallet' \| Promise<...>` | Yes | Host-owned signer selector, called for every `connect()`. | | `connectExternalWallet` | `() => OneAuthExternalWalletConnection \| Promise<...>` | Yes | Opens the host wallet UI and returns its EIP-1193 provider, selected address, and numeric chain ID. | | `client` | `OneAuthClient` | No | Reuses an existing client instead of constructing one. | | `webauthn` | `{ rpId?: string }` | No | Shared RP ID when constructing the client. | | `defaultChainId` | `number` | No | Chain reported for passkey sessions. Defaults to Base mainnet (`8453`). | | `storageKey` | `string` | No | Storage key for the app-origin passkey identity. Defaults to `"1auth-user"`. | | `closeOn` | `CloseOnStatus` | No | Passkey intent dialog completion status. | | `waitForHash` | `boolean` | No | Whether passkey intent sends wait for a transaction hash. | | `hashTimeoutMs` | `number` | No | Passkey intent hash polling timeout. | | `hashIntervalMs` | `number` | No | Passkey intent hash polling interval. | ## API Reference The 1auth SDK provides everything you need to add passkey authentication and transaction signing to your app. * **React components** - Drop-in components that work standalone, no viem or wagmi required * **Client API** - Full control over auth flows, signing, and intent execution * **Viem/Wagmi integration** - Optional adapters for existing web3 apps ### Installation :::code-group ```bash [npm] npm install @rhinestone/1auth ``` ```bash [yarn] yarn add @rhinestone/1auth ``` ```bash [pnpm] pnpm add @rhinestone/1auth ``` ::: ### Quick Links #### Client Core SDK classes for authentication and transaction signing. * [**OneAuthClient**](/sdk/client) - Main SDK client for auth, signing, and intents * [**Sign in with 1auth**](/sdk/sign-in) - Passkey authentication flow * [**PayButton**](/sdk/pay-button) - One-click payment component #### React React components and hooks for building passkey-powered UIs. * [**React Components & Hooks**](/sdk/react) - PayButton, BatchQueue, useBatchQueue #### Utilities Helper functions for signing and verification. * [**signTypedData**](/sdk/sign-typed-data) - EIP-712 typed data signing ### Basic Example ```tsx import { OneAuthClient } from '@rhinestone/1auth'; const client = new OneAuthClient({ providerUrl: 'https://passkey.1auth.app', clientId: 'my-app', }); // Authenticate const auth = await client.authenticate(); if (!auth.success) throw new Error(auth.error.message); console.log('Logged in as:', auth.session.accountAddress); // Send a transaction const result = await client.sendIntent({ accountAddress: auth.session.accountAddress, targetChain: 8453, calls: [{ to: '0x...', value: parseEther('0.1') }], }); ``` import { PayButtonDemo } from '../../layout' ## PayButton One-click payment button with built-in authentication. Users click, authenticate with their passkey, and the transaction executes. ### Usage ```tsx import { PayButton } from '@rhinestone/1auth/react'; console.log('Paid:', result.transactionHash)} onError={(error) => console.error(error)} /> ``` ### Props | Prop | Type | Required | Description | | ----------- | ------------------ | -------- | --------------------------------------- | | `client` | `OneAuthClient` | Yes | SDK client instance | | `intent` | `IntentParams` | Yes | Transaction parameters | | `onSuccess` | `(result) => void` | No | Called on successful transaction | | `onError` | `(error) => void` | No | Called on error | | `children` | `ReactNode` | No | Button text (default: "Pay with 1auth") | | `className` | `string` | No | Custom CSS class | | `disabled` | `boolean` | No | Disabled state | ### IntentParams ```tsx import type { Address } from 'viem'; interface IntentParams { targetChain: number; // Chain ID to execute on calls: IntentCall[]; // Array of calls to execute tokenRequests?: TokenRequest[]; // Optional: tokens to receive (output-first) } interface IntentCall { to: Address; // Target contract address value?: bigint; // ETH value to send data?: `0x${string}`; // Encoded calldata } interface TokenRequest { token: Address; // ERC-20 token contract address amount: bigint; // Amount in base units } ``` ### Examples #### Simple Payment ```tsx Pay $10 ``` #### Contract Interaction ```tsx { toast.success('NFT minted!'); router.push(`/nft/${tokenId}`); }} > Mint NFT ``` #### Custom Styling ```tsx Complete Purchase ``` #### ERC20 Payment with tokenRequests For payments in ERC20 tokens (like USDC), use `tokenRequests` to tell the orchestrator what tokens are needed. This enables cross-chain funding - users can pay even if their funds are on a different chain. ```tsx import { encodeFunctionData, parseUnits } from 'viem'; const USDC_BASE = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913'; const amount = parseUnits('10', 6); // 10 USDC const transferData = encodeFunctionData({ abi: erc20Abi, functionName: 'transfer', args: [merchantAddress, amount], }); toast.success('Payment complete!')} > Pay 10 USDC ``` :::tip When `tokenRequests` is specified, the orchestrator automatically bridges or swaps from any chain where the user has funds. The user doesn't need to have USDC on Base - they can pay with ETH on Arbitrum and 1auth handles the conversion. ::: ### Chain Abstraction The user can pay from any chain they have funds on. If their balance is on Arbitrum but `targetChain` is Base, 1auth automatically bridges the assets. Users see a unified balance and never worry about which chain they're on. import { AuthDemo, PayButtonDemo, BatchQueueDemo } from '../../layout' ## React Components Drop-in React components for passkey authentication and crypto payments. No viem, wagmi, or web3 knowledge required. ```tsx import { PayButton, BatchQueueProvider, BatchQueueWidget, useBatchQueue } from '@rhinestone/1auth/react'; ``` ### Why Use React Components? Building a crypto-enabled app shouldn't require deep web3 expertise. Our React components abstract away the complexity: * **No web3 libraries required** - Works without viem, wagmi, ethers, or any other dependency * **Built-in passkey flow** - Authentication, signing, and status updates handled for you * **Chain abstraction included** - Users pay from any chain, bridging happens automatically * **Production-ready UI** - Styled components that work out of the box ### Overview These components work standalone - just pass a `OneAuthClient` instance and they handle everything: wallet connection, passkey prompts, transaction signing, and status updates. **Zero web3 boilerplate.** No provider setup, no wallet connectors, no chain configuration. Your users click a button, authenticate with their passkey, and the transaction executes. | Export | Type | Description | | ------------------------------------------- | --------- | -------------------------------------------------- | | [`PayButton`](#paybutton) | Component | One-click payment button with built-in auth flow | | [`BatchQueueProvider`](#batchqueueprovider) | Component | Context provider for queuing multiple transactions | | [`BatchQueueWidget`](#batchqueuewidget) | Component | Floating UI to review and sign queued transactions | | [`useBatchQueue`](#usebatchqueue) | Hook | Access batch queue state and methods | **When to use these components:** * **PayButton** - E-commerce checkouts, donations, tips, or any single-action payment * **BatchQueue** - Shopping carts, multi-step workflows, or batching gas-efficient operations All components handle the complete passkey flow internally: authentication prompts, transaction signing, and status updates. *** ### AuthDemo Interactive authentication component with message signing. #### Authentication ```tsx const client = new OneAuthClient({ providerUrl: 'https://passkey.1auth.app', clientId: 'my-app', }); const auth = await client.authenticate(); if (!auth.success) throw new Error(auth.error.message); const accountAddress = auth.session.accountAddress; // `0x${string}` — the signer identity console.log('Connected as:', accountAddress); ``` #### Message Signing ```tsx const result = await client.signMessage({ accountAddress, message: `Sign in to MyApp\nTimestamp: ${Date.now()}`, description: 'Verify your identity', }); if (result.success) { console.log('Signature:', result.signature); } ``` #### SignMessageOptions | Property | Type | Required | Description | | ---------------- | ------------------------- | -------- | ----------------------------------- | | `accountAddress` | `string` | Yes | Smart account address of the signer | | `message` | `string` | Yes | Human-readable message to sign | | `description` | `string` | No | Description shown in dialog | | `metadata` | `Record` | No | Additional data to display | | `theme` | `ThemeConfig` | No | Theme configuration for the dialog | *** ### PayButton One-click payment button with built-in authentication. The live demo passes the shared app-origin account explicitly, so `PayButton` uses the same hostname-bound bearer, credential, signer, and smart account instead of consulting the legacy default storage key. #### Usage ```tsx import { PayButton } from '@rhinestone/1auth/react'; console.log('Paid:', result.transactionHash)} onError={(error) => console.error(error)} /> ``` #### Props | Prop | Type | Required | Description | | ---------------- | ------------------------------------ | -------- | -------------------------------------------------------------------------------------------------------------------------------- | | `client` | `OneAuthClient` | Yes | SDK client instance | | `accountAddress` | `string` | No | Existing account address. Supply this for a controlled app-origin session so PayButton never selects a legacy storage namespace. | | `intent` | `SendIntentOptions` | Yes | Transaction parameters (calls, targetChain, tokenRequests) | | `onSuccess` | `(result: SendIntentResult) => void` | No | Called on successful transaction | | `onError` | `(error: Error) => void` | No | Called on error | | `closeOn` | `CloseOnStatus` | No | When to close dialog: "claimed", "preconfirmed", "filled", or "completed". Default: "preconfirmed" | | `children` | `ReactNode` | No | Button text (default: "Pay with 1auth") | | `className` | `string` | No | Custom CSS class | | `style` | `React.CSSProperties` | No | Custom inline styles (merged with defaults) | | `disabled` | `boolean` | No | Disabled state | | `hideIcon` | `boolean` | No | Hide the fingerprint icon | See the full [PayButton reference](/sdk/pay-button) for more details. *** ### BatchQueueProvider Context provider for managing batched transaction queues with localStorage persistence. #### Usage ```tsx import { BatchQueueProvider, BatchQueueWidget } from '@rhinestone/1auth/react'; function App() { return ( ); } ``` #### Props | Prop | Type | Required | Description | | ---------------- | --------------- | -------- | ------------------------------------------------------ | | `client` | `OneAuthClient` | Yes | SDK client instance | | `accountAddress` | `Address` | No | Smart account address for signing and localStorage key | | `children` | `ReactNode` | Yes | Child components | #### Chain Validation All calls in a batch must target the same chain: ```tsx const { addToBatch } = useBatchQueue(); addToBatch({ to: '0x...', label: 'Action 1' }, 8453); // Base // This will fail - different chain const result = addToBatch({ to: '0x...', label: 'Action 2' }, 1); if (!result.success) { console.log(result.error); // "Batch is set to Base..." } ``` *** ### BatchQueueWidget Floating widget UI showing queued transactions. #### Usage ```tsx import { BatchQueueWidget, useBatchQueue } from '@rhinestone/1auth/react'; function SignAllHandler() { const { signAll } = useBatchQueue(); const handleSignAll = async () => { const result = await signAll({ accountAddress: '0x...' }); if (result.success) { console.log('All signed!', result.transactionHash); } }; return ; } ``` #### Props | Prop | Type | Required | Description | | ----------- | ------------ | -------- | ----------------------------------- | | `onSignAll` | `() => void` | Yes | Callback when "Sign All" is clicked | #### Features * Collapsible header with call counter badge * Chain indicator for current batch * Remove individual calls on hover * Clear all button * Bounce animation on new calls * Auto-hide when queue is empty *** ### useBatchQueue Hook to access batch queue context. #### Usage ```tsx import { useBatchQueue } from '@rhinestone/1auth/react'; function AddToCartButton({ item }) { const { addToBatch, queue } = useBatchQueue(); const handleClick = () => { const result = addToBatch( { to: item.contractAddress, data: item.calldata, label: `Buy ${item.name}`, }, 8453 ); if (!result.success) alert(result.error); }; return ; } ``` #### Return Value | Property | Type | Description | | ----------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | | `queue` | `BatchedCall[]` | Array of queued calls | | `batchChainId` | `number \| null` | Chain ID of the batch (set by first call) | | `addToBatch` | `(call: IntentCall, chainId: number) => { success: boolean; error?: string }` | Add a call to queue | | `removeFromBatch` | `(id: string) => void` | Remove a specific call | | `clearBatch` | `() => void` | Clear all calls | | `signAll` | `(identity?: Address \| { accountAddress: Address }) => Promise` | Sign and submit all calls (a bare address is treated as the account address) | | `isSigning` | `boolean` | Whether signing is in progress | | `isExpanded` | `boolean` | Whether the widget is expanded | | `setExpanded` | `(expanded: boolean) => void` | Set widget expanded state | #### BatchedCall Type ```tsx interface BatchedCall { id: string; call: IntentCall; targetChain: number; addedAt: number; } ``` import { AuthDemo } from '../../layout' ## Sign in with 1auth Add passkey authentication to your app with a single method call. Users authenticate with Face ID or Touch ID - no passwords, no seed phrases. ### Authentication ```tsx import { OneAuthClient } from '@rhinestone/1auth'; const client = new OneAuthClient({ providerUrl: 'https://passkey.1auth.app', clientId: 'my-app', }); // Authenticate or create an account const auth = await client.authenticate(); if (!auth.success) throw new Error(auth.error.message); const accountAddress = auth.session.accountAddress; // typed `0x${string}` console.log('Connected as:', accountAddress); ``` ### How It Works 1. **User clicks sign in** — your app calls `authenticate()`. 2. **Identity dialog opens** — the user verifies email or OAuth identity. 3. **Top-level passkey prompt opens** — WebAuthn runs on your app origin. 4. **Success** — you receive the smart-account address. The passkey private key never leaves the authenticator. 1auth remains authoritative for identity, credential persistence, and account derivation. ### Message Signing Request the user to sign a message for verification: ```tsx const result = await client.signMessage({ accountAddress, message: `Sign in to MyApp\nTimestamp: ${Date.now()}`, description: 'Verify your identity', }); if (result.success) { console.log('Signature:', result.signature); // Verify signature on your backend } ``` ### SignMessageOptions | Property | Type | Required | Description | | ---------------- | ------------------------- | -------- | --------------------------------------- | | `accountAddress` | `string` | Yes | Smart account address of the signer | | `message` | `string` | Yes | Human-readable message to sign | | `description` | `string` | No | Description shown in the signing dialog | | `metadata` | `Record` | No | Additional data to display | ### AuthResult `authenticate()` returns an `AuthResult`: ```tsx import type { AuthResult } from '@rhinestone/1auth'; type AuthResult = | { success: true; session: { accountAddress: `0x${string}`; signerType: 'passkey' | 'eoa'; }; } | { success: false; error: { code: string; // e.g. "USER_CANCELLED" message: string; }; }; ``` ### Challenge-Based Authentication Sign an application message with the authenticated account: ```tsx const client = new OneAuthClient({ clientId: 'my-app', }) const auth = await client.authenticate(); if (!auth.success) throw new Error(auth.error.message); const result = await client.signMessage({ accountAddress: auth.session.accountAddress, message: `Login to MyApp\nTimestamp: ${Date.now()}\nNonce: ${crypto.randomUUID()}`, description: 'Verify your identity', }) ``` Authentication and message signing are separate operations. Compose them when your application needs a signed login challenge. ### Example: Protected Route ```tsx import { useState, useEffect } from 'react'; import { OneAuthClient } from '@rhinestone/1auth'; const client = new OneAuthClient({ clientId: 'my-app', }); function App() { const [user, setUser] = useState(null); const handleSignIn = async () => { const result = await client.authenticate(); if (result.success) { setUser({ address: result.session.accountAddress }); } }; if (!user) { return ( ); } return (

Welcome!

Address: {user.address}

); } ``` import { SignTypedDataDemo } from "../../layout" ## signTypedData Sign [EIP-712](https://eips.ethereum.org/EIPS/eip-712) structured data using passkeys. Used for gasless approvals, off-chain voting, order signing, and meta-transactions. EIP-712 provides human-readable signing - users see exactly what they're signing instead of a raw hash. ### Live Demo ### Overview Sign EIP-712 structured data with a human-readable preview. The dialog displays: 1. **Domain info** - Application name, version, chain, and contract 2. **Message fields** - Formatted values with type-aware display 3. **Signature** - WebAuthn signature with the EIP-712 hash ### Basic Usage Use an authenticated app-origin passkey account. A configured `clientId` defaults the client to app-origin WebAuthn, so the signing ceremony stays on the application's top-level hostname and uses that hostname's account namespace. ```tsx import { OneAuthClient } from '@rhinestone/1auth'; const client = new OneAuthClient({ providerUrl: 'https://passkey.1auth.app', clientId: 'my-app', }); const auth = await client.authenticate(); if (!auth.success) throw new Error(auth.error.message); const accountAddress = auth.session.accountAddress; const result = await client.signTypedData({ accountAddress, domain: { name: 'My dApp', version: '1', chainId: 8453, verifyingContract: '0x...', }, types: { Vote: [ { name: 'proposalId', type: 'uint256' }, { name: 'support', type: 'bool' }, { name: 'voter', type: 'address' }, ], }, primaryType: 'Vote', message: { proposalId: '42', support: true, voter: '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045', }, description: 'Cast your vote', }); if (result.success) { console.log('Signature:', result.signature); console.log('EIP-712 Hash:', result.signedHash); } ``` ### ERC-2612 Permit Example Sign a token approval without an onchain transaction: ```tsx const result = await client.signTypedData({ accountAddress, domain: { name: 'Dai Stablecoin', version: '1', chainId: 1, verifyingContract: '0x6B175474E89094C44Da98b954EecdeCB5BE3830F', }, types: { Permit: [ { name: 'owner', type: 'address' }, { name: 'spender', type: 'address' }, { name: 'value', type: 'uint256' }, { name: 'nonce', type: 'uint256' }, { name: 'deadline', type: 'uint256' }, ], }, primaryType: 'Permit', message: { owner: '0xabc...', spender: '0xdef...', value: '1000000000000000000', nonce: '0', deadline: '1735689600', }, description: 'Allow spending of DAI', }); ``` ### SignTypedDataOptions | Property | Type | Required | Description | | ---------------- | ------------------------- | -------- | ----------------------------------- | | `accountAddress` | `string` | Yes | Smart account address of the signer | | `domain` | `EIP712Domain` | Yes | EIP-712 domain parameters | | `types` | `EIP712Types` | Yes | Type definitions | | `primaryType` | `string` | Yes | Primary type to sign | | `message` | `Record` | Yes | Message values | | `description` | `string` | No | Description shown in dialog | | `theme` | `ThemeConfig` | No | Theme override | ### EIP712Domain | Property | Type | Required | Description | | ------------------- | ------------- | -------- | ------------------- | | `name` | `string` | Yes | Application name | | `version` | `string` | Yes | Application version | | `chainId` | `number` | No | Chain ID | | `verifyingContract` | `0x${string}` | No | Contract address | | `salt` | `0x${string}` | No | Salt value | ### SignTypedDataResult | Property | Type | Description | | ------------- | -------------------- | -------------------------------------------------- | | `success` | `boolean` | Whether signing succeeded | | `signature?` | `WebAuthnSignature` | The WebAuthn signature (only on success) | | `signedHash?` | `0x${string}` | The EIP-712 hash that was signed (only on success) | | `passkey?` | `PasskeyCredentials` | Passkey used for signing (only on success) | | `error?` | `{ code, message }` | Error details (only on failure) | ### Use Cases * **ERC-2612 Permits** - Gasless token approvals * **Governance** - Off-chain voting with typed signatures * **Order signing** - DEX limit orders (EIP-712 format) * **Meta-transactions** - Relay-compatible signatures ### How It Works 1. The SDK sends the typed data (domain, types, message) to the sign dialog 2. The sign dialog displays the data in human-readable format for user review 3. **The sign dialog computes the EIP-712 hash locally** using viem's `hashTypedData` 4. The user signs the locally-computed hash with their passkey 5. The signature and hash are returned to your app ### Security Model The EIP-712 hash is computed **inside the sign dialog**, not by the calling application. This ensures users sign exactly what they see displayed: ``` ┌─────────────────────────────────────┐ │ Your App (SDK Client) │ │ │ │ 1. Calls client.signTypedData() │ │ 2. SDK sends typed data to dialog │ └──────────────┬──────────────────────┘ │ postMessage (typed data only) ▼ ┌─────────────────────────────────────┐ │ Sign Dialog (Trusted) │ │ │ │ 3. Displays data for user review │ │ 4. Computes EIP-712 hash locally │ ◄── Hash computed HERE │ 5. Signs hash with passkey │ │ 6. Returns signature + hash │ └─────────────────────────────────────┘ ``` This prevents a malicious app from displaying one thing while getting the user to sign something different. The sign dialog is the trusted component that ensures **what you see is what you sign**. ### Overview `PasskeyWalletClient` is a viem-compatible wallet client that extends the standard `WalletClient` with passkey-authenticated transaction signing. It provides a familiar viem API while handling all WebAuthn operations internally. Use this when you want: * A standard viem `WalletClient` interface * Batched transaction support via `sendCalls()` * Output-first token requests (specify what tokens you want to receive) ### Creating a Wallet Client ```typescript import { createPasskeyWalletClient } from '@rhinestone/1auth'; import { base } from 'viem/chains'; import { http } from 'viem'; const walletClient = createPasskeyWalletClient({ accountAddress: '0x...', // User's smart account address clientId: 'my-dapp', experimental_clear_signing: true, // experimental visible 1auth review; WebAuthn stays app-origin chain: base, transport: http(), }); ``` #### Config Options | Option | Type | Required | Description | | ---------------------------- | ------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `accountAddress` | `Address` | Yes | User's smart account address | | `chain` | `Chain` | Yes | viem chain configuration | | `transport` | `Transport` | Yes | viem transport (e.g., `http()`) | | `providerUrl` | `string` | No | URL of the 1auth provider (defaults to `https://passkey.1auth.app`) | | `dialogUrl` | `string` | No | URL for the dialog UI | | `clientId` | `string` | Yes | App metadata identifier | | `webauthn` | `{ rpId?: string }` | No | Optionally set `rpId` for a shared verified namespace — see [App-origin passkeys](/guides/app-origin-passkeys). | | `experimental_clear_signing` | `boolean` | No | Experimental. Show the 1auth transaction review iframe before signing; the subsequent WebAuthn ceremony still runs on the app origin. Defaults to `false`; [blind signing](/guides/signing) remains the established flow. | | `waitForHash` | `boolean` | No | Wait for transaction hash before resolving (default: `true`) | | `hashTimeoutMs` | `number` | No | Maximum time to wait for hash in ms | | `hashIntervalMs` | `number` | No | Poll interval for hash in ms | With [`experimental_clear_signing: true`](/guides/signing), the passkey-origin iframe displays the authoritative server-prepared transaction review. Approval returns to the SDK, then `navigator.credentials.get()` runs in the application's top-level page using its hostname as the RP ID. The bearer, credential, signer, and smart account stay bound to that origin/RP pair. Omit the option — the default — only when your app presents the complete transaction details itself. The server still binds and verifies the exact prepared intent, WebAuthn challenge, browser origin, RP ID, account, and credential before submitting anything on-chain. See [Signing](/guides/signing). ### sendCalls Send one or more calls as a single intent. App-origin WebAuthn runs on the app's top-level origin. Set [`experimental_clear_signing: true`](/guides/signing) to show the authoritative 1auth review dialog first. ```typescript const hash = await walletClient.sendCalls({ calls: [ { to: '0x...', // Contract address data: '0x...', // Encoded calldata value: parseEther('0.1'), // Optional ETH value label: 'Swap ETH for USDC', // Optional: shown in signing UI sublabel: '0.1 ETH → 250 USDC', // Optional: additional context icon: 'https://your-app.example/icons/swap.svg', // Optional fallback icon }, ], chainId: 8453, // Optional: override chain }); ``` #### Parameters | Property | Type | Required | Description | | --------------- | -------------------------------------- | -------- | ----------------------------- | | `calls` | `TransactionCall[]` | Yes | Array of calls to execute | | `chainId` | `number` | No | Override the default chain ID | | `tokenRequests` | `{ token: Address; amount: bigint }[]` | No | Output tokens to deliver | #### TransactionCall | Property | Type | Required | Description | | ---------- | -------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `to` | `Address` | Yes | Target contract address | | `data` | `Hex` | No | Encoded calldata | | `value` | `bigint` | No | ETH value in wei | | `label` | `string` | No | Label shown in signing UI | | `sublabel` | `string` | No | Additional context for UI | | `icon` | `string` | No | Fallback icon URL (SVG / square PNG / `data:` URL) shown in the sign dialog when 1auth's built-in token registry can't resolve a logo for this call. See [Per-call icons](#per-call-icons). | | `abi` | `readonly unknown[]` | No | Optional ABI used by the sign dialog to render an unverified decode of `data` (function name + args). See [Per-call ABIs](#per-call-abis). | #### Returns `Promise` - The transaction hash once confirmed. ### Per-call icons The sign dialog shows a 48px icon next to every action card. By default 1auth resolves the icon from the token's symbol / address (USDC, ETH, MATIC …) using a built-in registry, and falls back to a neutral letter avatar for unknown contracts. For demos, custom NFT mints, or any contract 1auth doesn't recognise, pass `icon` on the call so the dialog renders your glyph instead of the fallback: ```typescript await walletClient.sendCalls({ calls: [ { to: MOCK_NFT_ADDRESS, data: encodeFunctionData({ abi: mockNftAbi, functionName: 'mint', args: [price] }), label: 'Mint NFT', sublabel: '0.10 USDC', icon: 'https://your-app.example/nft-glyph.svg', }, ], chainId: 421614, }); ``` #### Rules * **Built-in icons always win.** If 1auth recognises the call's token (USDC, ETH, …), it uses that icon and ignores `icon`. This keeps apps from impersonating well-known assets with a custom SVG. * **Allowed schemes**: `https://...` or `data:image/(svg+xml|png|webp|jpeg|gif);...`. Other schemes (`http:`, `javascript:`, `file:`, …) are rejected by the server with a 400. Maximum length 8 KB. * **Same field on every call shape.** `IntentCall`, `TransactionCall` (`walletClient.sendCalls`), and the EIP-1193 `wallet_sendCalls` params all accept the same `icon?: string` field — mix and match as you would `label` and `sublabel`. #### Privacy note HTTPS icon URLs are fetched directly by the user's browser when the sign dialog renders. That leaks the user's IP, User-Agent, and Referer to whatever host you point at — turning the icon URL into a real-time beacon for "user is signing right now." If you don't want to make a third-party request from inside the dialog, use a `data:image/svg+xml,…` URL instead (the SVG is inlined into the call payload, never fetched). ### Per-call ABIs By default the sign dialog can only decode calls whose contract+selector is in 1auth's ERC-7730 clear-signing registry, or matches the built-in ERC-20 fallback (`transfer` / `approve` / `transferFrom`). Calls to a custom contract — your own marketplace, an NFT mint, a game state update — render as `Unverified` with just the raw selector. Pass `abi` on the call so the dialog can decode `data` into a human-readable function signature with named arguments: ```typescript import { encodeFunctionData } from 'viem'; const myAppAbi = [ { name: 'mintWithReferral', type: 'function', inputs: [ { name: 'tokenId', type: 'uint256' }, { name: 'referrer', type: 'address' }, ], outputs: [{ type: 'bool' }], }, ] as const; await walletClient.sendCalls({ calls: [ { to: MY_NFT_ADDRESS, data: encodeFunctionData({ abi: myAppAbi, functionName: 'mintWithReferral', args: [42n, referrerAddress], }), label: 'Mint NFT', sublabel: '0.10 USDC', icon: 'https://your-app.example/nft-glyph.svg', abi: myAppAbi, }, ], chainId: 421614, }); ``` The sign dialog's expanded action card now shows: ``` [Unverified] mintWithReferral(uint256 tokenId, address referrer) tokenId 42 referrer 0xabcd…1234 ``` #### Trust model `abi` is **app-supplied and unverified** — the same trust treatment as `label`, `sublabel`, and `icon`. The dialog: * Always renders the decoded preview behind an **amber "Unverified" badge** so users can tell it didn't come from a verified clear-signing entry. * Always shows the raw `to` address alongside the decode, so ground truth is never hidden. * **Silently drops the preview** if `decodeFunctionData` throws — e.g. when the ABI doesn't include a function with a matching selector. The call still goes through; it just falls back to the unverified-selector display. This is the same model used by `client.grantPermissions({ contracts })`'s ABI metadata in the SmartSession review surface. #### Rules * **Verified entries always win.** If the call's contract+selector matches a registry entry (ERC-7730 clear-signing data, ERC-20 fallback), that decoded display is used and `abi` is ignored. An app cannot override USDC's verified `transfer` row with its own ABI definition. * **Same field on every call shape.** `IntentCall`, `TransactionCall` (`walletClient.sendCalls`), and the EIP-1193 `wallet_sendCalls` params all accept the same `abi?: readonly unknown[]` field. * **Size cap.** The server rejects ABIs with more than 256 top-level items to keep prepare-time JSON parsing bounded. #### Pairing with viem The natural pairing is to use the same ABI for both encoding and the preview, so the bytes on the wire and the displayed function are guaranteed to match by construction: ```typescript const abi = myAppAbi; await walletClient.sendCalls({ calls: [ { to: MY_NFT_ADDRESS, data: encodeFunctionData({ abi, functionName: 'mint', args: [42n] }), abi, // same ABI used for both encoding and display }, ], }); ``` ### Token Requests (Output-First Model) The `tokenRequests` parameter lets you specify what tokens and amounts you want to receive as the output of your transaction. This is the **output-first model** - you declare the desired result, and the orchestrator figures out how to achieve it. ```typescript import { encodeFunctionData, parseUnits } from 'viem'; const hash = await walletClient.sendCalls({ calls: [ { to: '0xUSDC_ADDRESS', data: encodeFunctionData({ abi: erc20Abi, functionName: 'transfer', args: [recipient, parseUnits('100', 6)], }), abi: erc20Abi, label: 'Send USDC', }, ], tokenRequests: [ { token: '0xUSDC_ADDRESS', // Token contract address amount: parseUnits('100', 6), // 100 USDC (6 decimals) }, ], }); ``` #### Type Signature ```typescript import type { Address } from 'viem'; tokenRequests?: { token: Address; // ERC-20 token contract address amount: bigint; // Amount in base units (use parseUnits) }[]; ``` #### When to Use Token Requests * **Swaps**: Specify the output token and amount, then include any real target calls that consume or settle that output * **Cross-chain transfers**: Declare the destination token and amount * **Multi-step operations**: Let the orchestrator optimize the path The orchestrator will automatically: 1. Determine required input tokens from your portfolio 2. Find the optimal route across chains 3. Execute bridging and swaps as needed ### Example: Token Swap ```typescript import { encodeFunctionData, parseUnits } from 'viem'; // Swap-funded payment: receive 100 USDC on Base, then transfer it const hash = await walletClient.sendCalls({ calls: [ { to: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913', // USDC on Base data: encodeFunctionData({ abi: erc20Abi, functionName: 'transfer', args: [recipient, parseUnits('100', 6)], }), abi: erc20Abi, label: 'Send USDC', sublabel: '100 USDC', }, ], tokenRequests: [ { token: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913', amount: parseUnits('100', 6), }, ], chainId: 8453, // Base }); console.log('Transaction hash:', hash); ``` ### Notes * The client extends viem's `WalletClient`, so standard methods like `getAddresses()` work as expected * A configured `clientId` defaults to app-origin WebAuthn, while the exact page hostname—not registration metadata—selects the credential and account namespace * App-origin `sendCalls()` packages multiple calls into one intent and one passkey ceremony * `experimental_clear_signing: true` shows the 1auth review iframe, then returns approval to the app for app-origin WebAuthn and execution * Use `waitForHash: false` if you only need intent confirmation (faster, but no hash) * Token amounts use `bigint` for viem compatibility - use `parseUnits()` for decimals import { AccountsDemo } from "../../layout" ### eth\_accounts Returns the list of accounts that the user has previously connected. This allows your dApp to check if a user is already connected on page load without prompting them to authenticate again. Unlike `eth_requestAccounts`, this method never shows a modal. ### Try it ### Parameters None. ### Returns `string[]` - Array of account addresses. Returns an empty array if not connected. ### Example ```typescript const accounts = await provider.request({ method: 'eth_accounts' }); if (accounts.length > 0) { console.log('Connected as:', accounts[0]); } else { console.log('Not connected'); } ``` ### Notes * Returns addresses from localStorage if the user has previously connected * Does not prompt the user to connect - use `eth_requestAccounts` for that * Always returns an array (empty if not connected) import { ChainIdDemo } from "../../layout" ### eth\_chainId Returns the chain ID of the currently selected network. This is useful for verifying which blockchain your dApp is connected to before initiating transactions, and for displaying network information to users. ### Try it ### Parameters None. ### Returns `string` - The current chain ID as a hexadecimal string (e.g., `"0x1"` for Ethereum mainnet). ### Example ```typescript const chainId = await provider.request({ method: 'eth_chainId' }); console.log(chainId); // "0x1" (mainnet), "0x89" (polygon), etc. ``` ### Notes * The chain ID is returned as a hex-encoded string, not a number * Use `parseInt(chainId, 16)` to convert to a number if needed * This method does not require the user to be connected import { ConnectionDemo } from "../../layout" ### eth\_requestAccounts Prompts the user to authenticate with 1auth and authorize their passkey account for your dApp. If the user has not authenticated before, this opens the normal passkey registration/login flow. It does not offer external-wallet selection; use `wallet_connect` only when your interface intentionally offers a passkey-or-external-wallet choice. ### Try it ### Parameters None. ### Returns `string[]` - Array of account addresses that the user has authorized. ### Example ```typescript try { const accounts = await provider.request({ method: 'eth_requestAccounts' }); console.log('Connected as:', accounts[0]); } catch (error) { if (error.message.includes('cancelled')) { console.log('User cancelled the connection'); } } ``` ### Behavior 1. If the user is already connected, returns the stored passkey account immediately 2. Otherwise, opens the normal 1auth passkey registration/login flow 3. The user can approve or cancel the authentication request ### Notes * Use `eth_requestAccounts` for the normal 1auth passkey authentication flow * This method does not expose external-wallet selection * `eth_accounts` is passive: it reports currently authorized accounts without opening authentication or connection UI * The returned address is the user's smart account address import { SendTransactionDemo } from "../../layout" ### eth\_sendTransaction Sends a single transaction through the 1auth intent system. The user reviews the transaction details and approves with their passkey. Gas is automatically sponsored, so users don't need ETH for fees. Returns an intent ID that you can poll with `wallet_getCallsStatus` to track execution. ### Try it ### Parameters | Position | Type | Description | | -------- | -------- | ---------------------- | | 0 | `object` | The transaction object | #### Transaction Object | Field | Type | Description | | --------------- | ------------------ | -------------------------------------------------------- | | `to` | `string` | The recipient address or contract | | `data` | `string` | The calldata (optional, defaults to `"0x"`) | | `value` | `string \| number` | The value in wei (optional, defaults to `"0"`) | | `chainId` | `number` | Target chain ID (optional, uses current chain) | | `tokenRequests` | `array` | Tokens needed for this transaction (optional, see below) | #### Token Requests For direct same-chain ERC20 transfers, encode the ERC20 `transfer` call and omit `tokenRequests`. Add `tokenRequests` only when you want 1auth to route or swap the user's available assets so the target-chain call has the requested token before execution. | Field | Type | Description | | -------- | -------- | ------------------------------------------------ | | `token` | `string` | Token contract address on target chain | | `amount` | `bigint` | Amount in base units (e.g., 6 decimals for USDC) | ### Returns `string` - The intent ID (can be used with `wallet_getCallsStatus`). ### Example ```typescript import { encodeFunctionData, parseUnits } from 'viem'; // Simple ETH transfer (no tokenRequests needed) const intentId = await provider.request({ method: 'eth_sendTransaction', params: [{ to: '0x...', value: '1000000000000000000', // 1 ETH in wei }], }); // Swap-funded ERC20 payment with tokenRequests const USDC = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913'; const amount = parseUnits('100', 6); // 100 USDC const transferData = encodeFunctionData({ abi: erc20Abi, functionName: 'transfer', args: [recipientAddress, amount], }); const intentId = await provider.request({ method: 'eth_sendTransaction', params: [{ to: USDC, data: transferData, tokenRequests: [{ token: USDC, amount }], }], }); ``` :::tip When you include `tokenRequests`, the orchestrator automatically bridges or swaps tokens from any chain where the user has funds. If you already want to spend the selected token on the same chain, omit `tokenRequests` to keep the transaction as a direct transfer. ::: ### Notes * Returns an intent ID, not a transaction hash * Use `wallet_getCallsStatus` to track the transaction status * The transaction is executed via the 1auth intent system * Gas is automatically sponsored - no ETH needed for fees import { SignTypedDataDemo } from "../../layout" ### eth\_signTypedData\_v4 Signs structured data according to EIP-712. Unlike `personal_sign`, this method understands the structure of your data and displays it in a human-readable format. Use this for permit signatures, order signing, and any protocol that requires typed structured data signatures. ### Try it ### Parameters | Position | Type | Description | | -------- | ------------------ | -------------------------------------- | | 0 | `string` | The account address | | 1 | `string \| object` | The typed data object (or JSON string) | ### Typed Data Structure ```typescript interface TypedData { domain: { name?: string; version?: string; chainId?: number; verifyingContract?: string; }; types: { [typeName: string]: Array<{ name: string; type: string }>; }; primaryType: string; message: Record; } ``` ### Returns `string` - The signature as a hex string. ### Example ```typescript const typedData = { domain: { name: 'My App', version: '1', chainId: 1, verifyingContract: '0x...', }, types: { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], }, primaryType: 'Person', message: { name: 'Alice', wallet: '0x...', }, }; const signature = await provider.request({ method: 'eth_signTypedData_v4', params: [accounts[0], typedData], }); ``` ### Notes * Shows a human-readable preview of the structured data * Also available as `eth_signTypedData` (alias) * The typed data is validated before signing import { SignMessageDemo } from "../../layout" ### eth\_sign Signs arbitrary hex-encoded data. This is a legacy method - prefer `personal_sign` for new implementations. The data is decoded and displayed to the user for review before signing. Internally, this method behaves identically to `personal_sign`. ### Try it ### Parameters | Position | Type | Description | | -------- | -------- | ------------------------------ | | 0 | `string` | The account address | | 1 | `string` | The data to sign (hex-encoded) | ### Returns `string` - The signature as a hex string. ### Example ```typescript const accounts = await provider.request({ method: 'eth_accounts' }); const data = '0x' + Buffer.from('Hello').toString('hex'); const signature = await provider.request({ method: 'eth_sign', params: [accounts[0], data], }); ``` ### Notes * This method is deprecated in favor of `personal_sign` * The data is displayed to the user after hex decoding * Works the same as `personal_sign` internally ## RPC Reference The 1auth provider implements the [EIP-1193](https://eips.ethereum.org/EIPS/eip-1193) interface, making it compatible with viem, wagmi, ethers, and other Ethereum libraries. ### Overview All RPC methods can be called via the standard `request` interface: ```tsx const result = await provider.request({ method: 'method_name', params: [...], }) ``` ### Supported Methods The docs client uses app-origin WebAuthn for ordinary provider methods. Account reads, chain methods, transactions, message signing, typed-data signing, status, capabilities, and assets use the docs-hostname passkey account. `wallet_connect` is the explicit opt-in exception: it opens an interactive chooser for either the 1auth passkey account or an external wallet. #### Ethereum Standard | Method | Description | EIP | | -------------------------------------------------- | ---------------------------- | ---- | | [`eth_chainId`](/rpc/eth-chainid) | Returns the current chain ID | 695 | | [`eth_accounts`](/rpc/eth-accounts) | Returns connected accounts | - | | [`eth_requestAccounts`](/rpc/eth-request-accounts) | Requests account access | 1102 | | [`eth_sendTransaction`](/rpc/eth-send-transaction) | Sends a transaction | - | #### Message Signing | Method | Description | EIP | | -------------------------------------------------- | ------------------------- | --- | | [`personal_sign`](/rpc/personal-sign) | Signs a message (EIP-191) | 191 | | [`eth_sign`](/rpc/eth-sign) | Signs raw message hash | - | | [`eth_signTypedData_v4`](/rpc/eth-sign-typed-data) | Signs typed data | 712 | #### Wallet Namespace | Method | Description | EIP | | ----------------------------------------------------------------- | ----------------------------------------------------- | ---- | | [`wallet_connect`](/rpc/wallet-connect) | Opens the explicit passkey-or-external-wallet chooser | - | | [`wallet_disconnect`](/rpc/wallet-disconnect) | Disconnects wallet session | - | | [`wallet_switchEthereumChain`](/rpc/wallet-switch-ethereum-chain) | Switches to a different chain | 3326 | | [`wallet_sendCalls`](/rpc/wallet-send-calls) | Sends batched calls atomically | 5792 | | [`wallet_getCallsStatus`](/rpc/wallet-get-calls-status) | Gets batch execution status | 5792 | | [`wallet_getCapabilities`](/rpc/wallet-get-capabilities) | Gets wallet capabilities | 5792 | | [`wallet_getAssets`](/rpc/wallet-get-assets) | Gets user's token balances | - | ### Usage Example ```tsx import { createOneAuthProvider, OneAuthClient } from '@rhinestone/1auth' const client = new OneAuthClient({ providerUrl: 'https://passkey.1auth.app', clientId: 'my-app', sponsorship, }) const provider = createOneAuthProvider({ client, chainId: 8453, // Base }) // Request accounts const accounts = await provider.request({ method: 'eth_requestAccounts', }) // App-origin supports transaction, message-signing, and typed-data methods. const callsId = await provider.request({ method: 'eth_sendTransaction', params: [{ to: recipient, value: 1n }], }) ``` ### Cross-Chain with tokenRequests For ERC20 transfers and contract calls that need tokens, include `tokenRequests` to enable automatic cross-chain funding. The user can pay from any chain - the orchestrator handles bridging and swaps automatically. ```tsx import { encodeFunctionData, parseUnits } from 'viem'; const amount = parseUnits('100', 6); // 100 USDC const transferData = encodeFunctionData({ abi: erc20Abi, functionName: 'transfer', args: [recipient, amount], }); await provider.request({ method: 'eth_sendTransaction', params: [{ to: USDC_ADDRESS, data: transferData, tokenRequests: [{ token: USDC_ADDRESS, amount }], }], }); ``` See [Token Requests](/guides/token-requests) for detailed documentation. import { SignMessageDemo } from "../../layout" ### personal\_sign Signs a plaintext message using the user's passkey. This opens a signing modal where the user can review the message before approving. Use this for "Sign in with Ethereum" flows, proving account ownership, or any scenario where you need a cryptographic signature on arbitrary text. ### Try it ### Parameters | Position | Type | Description | | -------- | -------- | ------------------------------------------------------ | | 0 | `string` | The message to sign (can be hex-encoded or plain text) | | 1 | `string` | The account address (optional, uses connected account) | ### Returns `string` - The signature as a hex string, encoded for smart account verification. ### Example ```typescript const message = 'Hello, 1auth!'; const accounts = await provider.request({ method: 'eth_accounts' }); const signature = await provider.request({ method: 'personal_sign', params: [message, accounts[0]], }); console.log('Signature:', signature); ``` ### Notes * Opens the signing modal showing the message to the user * The user must approve the signature with their passkey * Returns a WebAuthn-encoded signature compatible with ERC-6492 * Hex-encoded messages are automatically decoded for display import { WalletConnectDemo } from "../../layout" ### wallet\_connect Opens the interactive connection UI so the user can continue with their 1auth passkey account or choose an external wallet. Use this public EIP-1193 method only when your interface intentionally offers both choices. ### Try it ### Parameters None. ### Returns `string[]` - Array of account addresses that the user has authorized. ### Example ```typescript const accounts = await provider.request({ method: 'wallet_connect' }); console.log('Connected as:', accounts[0]); ``` ### Behavior * `wallet_connect` always opens the passkey-or-external-wallet connection choice. * The normal 1auth passkey path remains available in the chooser. * Use `eth_requestAccounts` for normal passkey-only authentication. * `eth_accounts` is passive: it reports currently authorized accounts without opening authentication or connection UI. import { DisconnectDemo } from "../../layout" ### wallet\_disconnect Disconnects the user's wallet from your dApp and clears the stored session. After disconnecting, the user will need to reconnect to interact with your app again. This is a client-side disconnect only - it doesn't revoke any onchain permissions. ### Try it ### Parameters None. ### Returns `boolean` - Returns `true` on success. ### Example ```typescript await provider.request({ method: 'wallet_disconnect' }); console.log('Disconnected'); ``` ### Events After disconnecting, the provider emits: * `accountsChanged` with an empty array `[]` * `disconnect` ```typescript provider.on('accountsChanged', (accounts) => { if (accounts.length === 0) { console.log('User disconnected'); } }); provider.on('disconnect', () => { console.log('Wallet disconnected'); }); ``` ### Notes * Clears the stored session from localStorage * The user will need to reconnect to use the wallet again * Does not revoke any onchain permissions import { GetAssetsDemo } from "../../layout" ### wallet\_getAssets Fetches the user's token balances and portfolio across all supported chains. This provides a unified view of the user's holdings with USD values when available. Use this to display wallet balances or to check if the user has sufficient funds for a transaction. Asset reads require the same app JWT setup as intent flows. Configure `OneAuthClient` with `sponsorship` so the SDK can fetch your app access token and forward it to the 1auth provider. When you are already using `OneAuthClient`, prefer the native SDK helper: ```typescript const assets = await client.getAssets({ accountAddress: "0x1111111111111111111111111111111111111111", }); ``` ### Try it ### Parameters Optional. Connected EIP-1193 apps can call with no params. Apps that already have a verified account address can pass it explicitly: ```typescript await provider.request({ method: "wallet_getAssets", params: [{ accountAddress: "0x1111111111111111111111111111111111111111" }], }); ``` ### Returns Returns the user's portfolio data including token balances across all supported chains. ```typescript interface AssetsResponse { balances: Array<{ chainId: number; token: string; symbol: string; decimals: number; balance: string; usdValue?: number; isTestnet?: boolean; }>; mainnets: { balances: AssetsResponse["balances"] }; testnets: { balances: AssetsResponse["balances"] }; } ``` ### Example ```typescript const assets = await provider.request({ method: 'wallet_getAssets', }); console.log('Portfolio:', assets); // Display balances for (const balance of assets.balances) { const amount = Number(balance.balance) / 10 ** balance.decimals; console.log(`${balance.symbol}: ${amount} ($${balance.usdValue})`); } console.log("Mainnet balances:", assets.mainnets.balances); console.log("Testnet balances:", assets.testnets.balances); ``` ### Notes * Requires the user to be connected * Requires `OneAuthClient.sponsorship` so the SDK can send an app JWT * Fetches data from the 1auth portfolio API * Returns balances across all supported chains * Also returns `mainnets.balances` and `testnets.balances` so apps can render network-specific views without changing SDK configuration * USD values are fetched from price feeds when available import { SendCallsDemo } from "../../layout" ### wallet\_getCallsStatus Checks the execution status of a previously submitted transaction or batch. After calling `eth_sendTransaction` or `wallet_sendCalls`, use this method to poll for confirmation. Returns the current status (pending or confirmed) along with transaction receipts when complete. ### Try it ### Parameters | Position | Type | Description | | -------- | -------- | --------------------------------------------- | | 0 | `string` | The calls ID returned from `wallet_sendCalls` | ### Returns ```typescript interface CallsStatus { status: 'PENDING' | 'CONFIRMED'; receipts: Array<{ logs: any[]; status: '0x1' | '0x0'; // success or failure blockHash?: string; blockNumber?: string; transactionHash?: string; }>; } ``` ### Example ```typescript const callsId = await provider.request({ method: 'wallet_sendCalls', params: [{ calls: [...] }], }); // Poll for status const checkStatus = async () => { const result = await provider.request({ method: 'wallet_getCallsStatus', params: [callsId], }); if (result.status === 'CONFIRMED') { const receipt = result.receipts[0]; if (receipt.status === '0x1') { console.log('Transaction succeeded:', receipt.transactionHash); } else { console.log('Transaction failed'); } } else { console.log('Still pending...'); setTimeout(checkStatus, 2000); } }; checkStatus(); ``` ### Status Values | Status | Description | | ----------- | ------------------------------------------------------------------------------- | | `PENDING` | Transaction is being processed | | `CONFIRMED` | Transaction has been confirmed (check `receipts[0].status` for success/failure) | ### Notes * The intent system handles cross-chain execution * `PENDING` includes both preconfirmed and in-flight states * Transaction hash is available once confirmed import { CapabilitiesDemo } from "../../layout" ### wallet\_getCapabilities Returns the wallet's supported features for each chain. Use this to discover capabilities like atomic batching, gas sponsorship, and cross-chain fund sourcing. This helps your dApp adapt its UX based on what the wallet supports. ### Try it ### Parameters | Position | Type | Description | | -------- | ---------- | -------------------------------------------------------------- | | 0 | `string` | The wallet address (optional, ignored) | | 1 | `string[]` | Array of chain IDs to query (optional, returns all if omitted) | ### Returns ```typescript type Capabilities = { [chainId: `0x${string}`]: { atomic: { status: 'supported' }; paymasterService: { supported: boolean }; auxiliaryFunds: { supported: boolean }; }; }; ``` ### Example ```typescript const capabilities = await provider.request({ method: 'wallet_getCapabilities', params: [], }); console.log(capabilities); // { // "0x1": { // atomic: { status: "supported" }, // paymasterService: { supported: true }, // auxiliaryFunds: { supported: true } // }, // "0x89": { ... }, // ... // } ``` ### Capabilities | Capability | Description | | ------------------ | ---------------------------------------------------- | | `atomic` | Batch calls are executed atomically (all-or-nothing) | | `paymasterService` | Gas fees are sponsored - users don't need ETH | | `auxiliaryFunds` | Cross-chain funds can be used for transactions | *** #### atomic Multiple calls sent via `wallet_sendCalls` execute atomically. If any call fails, all calls are reverted. ```typescript // All calls execute together or none execute const callsId = await provider.request({ method: 'wallet_sendCalls', params: [{ chainId: 8453, calls: [ { to: tokenAddress, data: approveData }, { to: dexAddress, data: swapData }, ], }], }); ``` *** #### paymasterService Gas fees are sponsored. Users don't need to hold ETH to pay for transactions. **How it works:** 1. User submits a transaction via `eth_sendTransaction` or `wallet_sendCalls` 2. The 1auth intent system handles gas payment automatically 3. User signs with their passkey - no ETH required *** #### auxiliaryFunds Funds from other supported chains can be used to fulfill transactions. The 1auth intent system automatically sources funds cross-chain when needed. **How it works:** 1. User initiates a transaction on Chain A 2. If insufficient funds on Chain A, the system checks other chains 3. Funds are automatically bridged to complete the transaction 4. User only signs once - cross-chain complexity is abstracted away ### Notes * Returns capabilities for all supported chains by default * All 1auth accounts have the same capabilities * Use this to check if features like gas sponsorship are available import { SendCallsDemo } from "../../layout" ### wallet\_sendCalls Sends multiple contract calls as a single atomic batch. All calls execute together or none execute, preventing partial failures. This is ideal for multi-step operations like "approve + swap" that must succeed together. Gas is sponsored and the user signs once for the entire batch. ### Try it ### Parameters | Position | Type | Description | | -------- | -------- | ----------------------- | | 0 | `object` | The batch calls payload | #### Payload Object | Field | Type | Description | | --------------- | ---------------- | ------------------------------------------------ | | `chainId` | `number` | **Required**: Target chain ID for execution | | `calls` | `Call[]` | Array of calls to execute | | `tokenRequests` | `TokenRequest[]` | Optional: tokens to receive (output-first model) | #### Call Object | Field | Type | Description | | ---------- | ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `to` | `string` | The recipient address | | `data` | `string` | The calldata (optional) | | `value` | `string \| number` | The value in wei (optional) | | `label` | `string` | Optional human-readable label shown in the sign dialog (e.g. `"Mint NFT"`) | | `sublabel` | `string` | Optional secondary line shown under the label (e.g. `"0.10 USDC"`) | | `icon` | `string` | Optional fallback icon URL (SVG / square PNG / `data:` URL, max 8 KB). Rendered in the sign dialog when 1auth's built-in token registry can't resolve a logo for the call. Built-in icons always win — apps cannot override USDC / ETH / MATIC etc. | | `abi` | `unknown[]` | Optional ABI used by the sign dialog to render an unverified human-readable decode of `data` (function name + named args). Same trust model as `label` / `sublabel` / `icon` — rendered behind an "Unverified" badge with the raw `to` + selector always shown alongside. Max 256 items. See [Per-call ABIs](/sdk/wallet-client#per-call-abis) for the trust model and usage. | #### TokenRequest Object | Field | Type | Description | | -------- | -------- | ------------------------------------------------- | | `token` | `string` | ERC-20 token contract address | | `amount` | `string` | Amount in base units (e.g., "1000000" for 1 USDC) | ### Returns `string` - The calls ID (intent ID) for tracking status. ### Example The `chainId` parameter specifies which chain the calls execute on. This enables crosschain transactions - the user's funds can be on any chain and the orchestrator handles bridging automatically. ```typescript // Batch multiple contract calls const callsId = await provider.request({ method: 'wallet_sendCalls', params: [{ chainId: 8453, // Target chain is required! // [!code ++] calls: [ { to: '0x...', // Token contract data: '0x...', // approve() }, { to: '0x...', // DEX contract data: '0x...', // swap() }, ], }], }); // Track the status const status = await provider.request({ method: 'wallet_getCallsStatus', params: [callsId], }); ``` ### Crosschain execution The `chainId` parameter is the key to crosschain transactions. Set it to the chain where you want the calls to execute: ```typescript // Execute on Base (chainId: 8453) const callsId = await provider.request({ method: 'wallet_sendCalls', params: [{ chainId: 8453, // Calls execute on Base // [!code ++] calls: [{ to: '0x...', // Contract on Base data: '0x...', }], }], }); ``` The orchestrator finds the cheapest route to fund the transaction, regardless of where the user's assets are. User signs once with their passkey. ### Token requests (output-first) Use `tokenRequests` to specify what tokens the target-chain calls need before they execute. The orchestrator automatically determines the best path to deliver those tokens from the user's available assets across chains. ```typescript import { encodeFunctionData } from 'viem'; const USDC_BASE = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913'; const amount = 100000000n; // 100 USDC const transferData = encodeFunctionData({ abi: erc20Abi, functionName: 'transfer', args: ['0xRecipient...', amount], }); const callsId = await provider.request({ method: 'wallet_sendCalls', params: [{ chainId: 8453, // Base // [!code ++] calls: [{ to: USDC_BASE, data: transferData }], // [!code ++] tokenRequests: [ // [!code ++] { // [!code ++] token: USDC_BASE, // USDC on Base // [!code ++] amount: '100000000', // 100 USDC (6 decimals) // [!code ++] }, // [!code ++] ], // [!code ++] }], }); ``` This is useful for transfers, deposits, purchases, or any operation where real calldata consumes the requested output token. Do not add a dummy `{ data: '0x' }` call or a self-transfer to model a plain swap; plain swaps should use `sendIntent({ calls: [], tokenRequests })`. ### Notes * All calls are executed atomically - if one fails, all fail * User sees a summary of all calls before signing * Gas is sponsored - no ETH needed for fees * Use `wallet_getCallsStatus` to track execution status * `tokenRequests.amount` is a string at the RPC level; the SDK accepts `bigint` and converts automatically import { SwitchChainDemo } from "../../layout" ### wallet\_switchEthereumChain Changes the active network to a different supported chain. The switch is instant and doesn't require user approval. After switching, subsequent transactions will target the new chain. Use this when your dApp needs to operate on a specific network. ### Try it ### Parameters | Position | Type | Description | | -------- | -------- | --------------------------- | | 0 | `object` | Object containing `chainId` | #### Parameter Object | Field | Type | Description | | --------- | ------------------ | ----------------------------------- | | `chainId` | `string \| number` | The chain ID (hex string or number) | ### Returns `null` - Returns `null` on success. ### Example ```typescript // Switch to Polygon (chainId: 137) await provider.request({ method: 'wallet_switchEthereumChain', params: [{ chainId: '0x89' }], // 137 in hex }); // Or using a number await provider.request({ method: 'wallet_switchEthereumChain', params: [{ chainId: 137 }], }); ``` ### Events After switching, the provider emits: ```typescript provider.on('chainChanged', (chainId) => { console.log('Switched to chain:', chainId); }); ``` ### Supported Chains The provider supports all chains configured in the 1auth registry. Common chains include: * Ethereum Mainnet (`0x1`) * Polygon (`0x89`) * Arbitrum (`0xa4b1`) * Optimism (`0xa`) * Base (`0x2105`) ### Notes * Chain switching is instant - no user approval required * Unsupported chain IDs will throw an error import { AccountRecoveryDemo } from '../../components/demos/AccountRecoveryDemo' ## Account Recovery `setupRecovery()` opens an interactive backup flow for the signed-in app-origin account. The user explicitly approves a WebAuthn PRF assertion on your app's top-level page, copies a recovery passphrase, initiates an encrypted `1auth.recovery-key` file download, and confirms the backup steps: ```ts const result = await client.setupRecovery() if (!result.completed) { if (result.error.code === 'USER_CANCELLED') { // The user closed or cancelled the backup flow. } else { throw new Error(result.error.message) } } ``` ### Configure the client Choose the recovery fallback when constructing the same app-origin client used for signup and login: ```ts const client = new OneAuthClient({ providerUrl: 'https://passkey.1auth.app', clientId: 'your-app-id', recovery: { fallback: { type: 'verified-identity' } }, }) ``` The browser hostname remains the WebAuthn RP and account namespace. `clientId` selects app metadata only. ### Run the backup flow Call `setupRecovery()` only after login or account creation, and keep the UI in a pending state until its promise settles: ```ts const auth = await client.authenticate({ flow: 'login' }) if (!auth.success) throw new Error(auth.error?.message ?? 'Login failed') setRecoveryStatus('pending') const result = await client.setupRecovery() if (result.completed) { setRecoveryStatus('success') } else if (result.error.code === 'USER_CANCELLED') { setRecoveryStatus('cancelled') } else { setRecoveryError(result.error.message) } ``` `completed: true` means the user approved the real app-origin assertion, copied the passphrase, initiated the encrypted backup-file download, and pressed **Finish**. `completed: false` is not always cancellation: only `error.code === 'USER_CANCELLED'` means the user dismissed the flow. Treat every other error code, including `AUTH_FAILED`, as a failed setup and show its error message. ### Keep the two backup parts separate The passphrase decrypts the downloaded file. Ask the user to keep them in different secure locations. The SDK keeps the assertion, PRF output, guardian private key, passphrase, and encrypted-file key in browser memory only. These secrets are never sent to your server or 1auth, placed in URLs or browser storage, written to logs, or delivered through `postMessage`. Clipboard access happens only when the user clicks **Copy passphrase**. The encrypted `1auth.recovery-key` file is safe to store, but it is useless without the separately saved passphrase. ### What happens after passkey loss 1. The user starts login and verifies the same configured email or OAuth identity in 1auth's identity UI. 2. 1auth finds the existing account in the current app-origin namespace. 3. The SDK runs recovery registration in your app's top-level page. 4. The new passkey is activated for the existing smart account. 5. The SDK stores a fresh app-origin session for subsequent signing. The passkey service may render identity and recovery instructions, but the WebAuthn registration ceremony stays on the integrator's top-level origin. :::tip Recovery is namespace-specific. A credential created for another hostname cannot recover this account. ::: ### Next steps * [Signup & Login](/guides/signup-login) — create or authenticate the account * [App-origin passkeys](/guides/app-origin-passkeys) — understand RP and account namespaces import { AppOriginDemo, Mermaid } from "../../layout"; ## App-origin passkeys 1auth creates and uses passkeys in your application's top-level page. By default, each hostname has a separate passkey and smart account. Configure one RP ID plus exact server-authorized `rpOrigins` to share a passkey/account namespace across same-site deployment origins. > `clientId` identifies your registered application, but it is not itself the WebAuthn RP ID or browser origin. ### RP ID and RP origin, in plain language WebAuthn binds every passkey to two related values: * **RP ID**: the passkey's website namespace. It is a hostname with no `https://` and no port, for example `example.com`. A passkey created for one RP ID cannot silently be used for another. * **RP origin**: the exact page that runs the ceremony, including the scheme and any non-default port, for example `https://checkout.example.com`. The browser writes this value into the signed WebAuthn response; the SDK cannot forge or replace it. For a page at `https://checkout.example.com`, the default is: ```text RP ID: checkout.example.com RP origin: https://checkout.example.com Account key: https://checkout.example.com ``` With a configured shared RP ID of `example.com`, the same page uses: ```text RP ID: example.com RP origin: https://checkout.example.com Account key: https://example.com ``` The RP ID selects the passkey, signer, and smart-account namespace. The RP origin proves which exact webpage performed the ceremony. >SDK: Start login or signing SDK->>API: Request options with clientId and rpId example.com API->>API: Select active app by clientId API->>API: Require exact rpOrigins membership API-->>SDK: Options scoped to RP ID example.com SDK->>Browser: navigator.credentials.get() Browser-->>SDK: Signed response with origin checkout.example.com SDK->>API: Complete ceremony API->>API: Verify selected exact origin and RP ID `} /> The SDK sends only the configured RP ID. The browser supplies the exact request origin and signs the ceremony origin. The server selects the registered app by `clientId`, requires the RP ID to match its saved configuration, and requires exact membership in the server-owned `rpOrigins` allowlist. Configure the registered application in the developer dashboard before deploying the client: ```json { "rpId": "example.com", "rpOrigins": ["https://test1.example.com", "https://test2.example.com"] } ``` Every hostname must be an exact verified non-wildcard application domain. Origins are exact: scheme and non-default port are significant. Each origin hostname must equal the RP ID or be its subdomain. \:::warning Explicit RP sharing requires both configurations Saving `rpId` and `rpOrigins` in the developer dashboard only authorizes the namespace; it does not activate it for a client. The client must also send the same value as `webauthn.rpId`. If the client omits `webauthn.rpId`, 1auth intentionally uses the page's exact hostname and does not consult the registered shared-RP configuration. On a canonical page whose hostname equals the saved RP ID, both configurations may produce the same visible hostname. That does not prove the explicit path is active. Verify that the client sends `webauthn.rpId`, especially before expecting another authorized subdomain to reuse the same passkey and smart account. \::: ### Configure the client ```ts [oneauth.ts] import { OneAuthClient } from "@rhinestone/1auth"; export const oneAuth = new OneAuthClient({ providerUrl: "https://passkey.1auth.app", clientId: "my-app", webauthn: { rpId: "example.com", }, experimental_clear_signing: true, sponsorship: { accessTokenUrl: "/api/sponsorship/access-token", extensionTokenUrl: "/api/sponsorship/extension-token", }, }); ``` Providing `webauthn.rpId` automatically selects app-origin mode. The RP ID must be the page hostname or one of its parent domains: ```text Page: checkout.example.com Allowed: checkout.example.com or example.com Denied: accounts.other-company.com ``` Your `clientId` must belong to the registered application serving the current page. Omit `rpId` to preserve the default exact-host behavior. In the developer dashboard, choose the verified RP ID and add every exact page origin that may run WebAuthn. `rpOrigins` is server-owned configuration and is not an SDK option. `authenticate()`, `authenticate({ flow: "create-account" })`, and `authenticate({ flow: "login" })` first open the identity-only 1auth dialog. After identity verification, registration or authentication continues in your top-level page using the configured RP ID or, by default, that page's hostname. ```ts const auth = await oneAuth.authenticate(); if (!auth.success) { throw new Error(auth.error?.message ?? "Authentication failed"); } const result = await oneAuth.sendIntent({ accountAddress: auth.session.accountAddress, targetChain: 84532, calls, sponsorshipMode: "required", experimental_clear_signing: true, }); ``` ### Security boundary With [`experimental_clear_signing: true`](/guides/signing), the passkey-origin iframe displays the authoritative server-prepared transaction review. Approval returns to the SDK, then `navigator.credentials.get()` runs in the application's top-level page. The server binds and verifies the exact prepared intent, challenge, browser origin, RP ID, registered app, account, and credential before submitting anything on-chain. ### Supported surface * Fresh email or OAuth account creation * Login with an app-origin credential * `getSession()`, `disconnect()`, and the interactive authenticated `setupRecovery()` backup flow; only `USER_CANCELLED` is a dismissal, while other false results are setup errors * `signMessage()`, `signTypedData()`, and `signWithModal()` * One `sendIntent()` call with visible review or app-owned blind review, directly, through `PayButton`, through EIP-1193 `eth_sendTransaction` / `wallet_sendCalls`, or through wallet-client `sendTransaction()` / `sendCalls()` * Multiple calls submitted atomically as one intent * Origin/RP-bound passkey listing, addition, removal, recovery, and matching-intent finalization * SmartSession permission grants and bearer-bound headless execution through `OneAuthHeadlessClient` ### Deployment requirements * Serve every calling hostname over HTTPS. `http://localhost` is accepted only for development and is not provider evidence. * The exact browser origin is always verified. Ports stay in the RP origin but never appear in the RP ID or account namespace. * Without `webauthn.rpId`, every distinct hostname creates distinct passkeys and smart accounts. * With `webauthn.rpId`, the value must be the exact caller hostname or one of its parent domains. * Adding or changing `webauthn.rpId` changes the SDK bearer storage key, so existing browser sessions must authenticate again. * The registered application's RP ID and every `rpOrigins` hostname must be exact verified, non-wildcard application domains. * Wildcard origins and unrelated-site Related Origin Requests are unsupported. 1auth does not fetch `/.well-known/webauthn` for this configuration. * Configure sponsorship endpoints before sending an intent. `clientId` identifies application metadata and authorization; it does not override browser-origin verification. * Changing an RP ID or WebAuthn mode selects a different passkey keypair, on-chain signer, and smart account. 1auth does not migrate accounts between namespaces, so treat the change as a user-facing account switch, not a configuration-only rollout. * Validate the deployed flow on a real domain with the password managers and browsers you support. ## Authentication After sign-in, request a passkey-backed message signature and verify it on your backend. ### Using wagmi Use Wagmi to request message signatures. ::::steps #### Install the SDK ```bash npm install @rhinestone/1auth wagmi @wagmi/core ``` #### Create config.ts Create a wagmi config file with the 1auth connector: ```ts [config.ts] import { createConfig, http } from 'wagmi' import { base } from 'wagmi/chains' import { OneAuthClient } from '@rhinestone/1auth' // [!code ++] import { oneAuth } from '@rhinestone/1auth/wagmi' // [!code ++] // Create the 1auth client const client = new OneAuthClient({ // [!code ++] providerUrl: 'https://passkey.1auth.app', // [!code ++] clientId: 'my-app', // [!code ++] }) // [!code ++] // Create the wagmi config with 1auth connector export const config = createConfig({ chains: [base], connectors: [oneAuth({ client })], // [!code ++] transports: { [base.id]: http(), }, }) ``` #### Sign a message Request a signature with `useSignMessage`: :::code-group ```tsx [Example.tsx] import { useSignMessage, useAccount } from 'wagmi' export function SignMessage() { const { address } = useAccount() const { signMessage, data: signature } = useSignMessage() const handleSign = () => { signMessage({ message: `Sign in to MyApp\nTimestamp: ${Date.now()}`, }) } if (!address) return

Connect wallet first

return (
{signature &&

Signature: {(signature.length - 2) / 2} bytes

}
) } ``` ::: #### Verify on your backend Verify the signature on your backend: :::code-group ```tsx [Example.tsx] import { useSignMessage, useAccount } from 'wagmi' export function AuthenticatedAction() { const { address } = useAccount() const { signMessageAsync } = useSignMessage() const handleAuth = async () => { const message = `Sign in to MyApp\nTimestamp: ${Date.now()}` const signature = await signMessageAsync({ message }) // Send to your backend for verification const response = await fetch('/api/verify', { method: 'POST', body: JSON.stringify({ message, signature, address }), }) if (response.ok) { console.log('Authenticated!') } } return } ``` ```ts [api/verify.ts] import { createPublicClient, http } from 'viem' import { base } from 'viem/chains' const publicClient = createPublicClient({ chain: base, transport: http(), }) export async function POST(req: Request) { const { message, signature, address } = await req.json() // verifyMessage supports ERC-1271 for smart accounts const isValid = await publicClient.verifyMessage({ // [!code ++] address, // [!code ++] message, // [!code ++] signature, // [!code ++] }) // [!code ++] if (!isValid) { return new Response('Invalid signature', { status: 401 }) } // Create session, return token, etc. return new Response('OK') } ``` ::: Verify signatures before creating an application session. :::: ### Using the SDK directly Without wagmi, use `signMessage`: ```tsx const auth = await client.authenticate() if (!auth.success) throw new Error(auth.error.message) const result = await client.signMessage({ accountAddress: auth.session.accountAddress, message: `Sign in to MyApp\nTimestamp: ${Date.now()}`, description: 'Verify your identity', }) if (result.success) { console.log('Signature:', result.signature) // Send to backend for verification } ``` ### SignMessageOptions | Property | Type | Required | Description | | ---------------- | ------------------------- | -------- | --------------------------------------- | | `accountAddress` | `string` | Yes | Smart account address of the signer | | `message` | `string` | Yes | Human-readable message to sign | | `description` | `string` | No | Description shown in the signing dialog | | `metadata` | `Record` | No | Additional data to display | | `theme` | `ThemeConfig` | No | Theme configuration for the dialog | ### Security considerations * **Include timestamps** to prevent replay attacks * **Include a server-issued nonce** and reject a message you did not issue * **Expire the message** so an old signature stops being accepted * **Include domain** to prevent cross-site signature reuse * **Verify on backend** - never trust client-side verification alone * **Use HTTPS** for all API calls A verified signature proves the user controls the account; it is not itself an application session. Issue your own session after verification. ### Next steps * [Checkout](/guides/checkout) - Add payments with PayButton * [Crosschain](/guides/crosschain) - Execute transactions on any chain import { BatchQueueDemo } from '../../layout' ## Batch Transactions Queue separate intents and authorize the batch with one passkey ceremony. Use it when each action needs its own intent result. ### Using BatchQueue Each queue entry remains an independent intent; one passkey ceremony authorizes the complete batch. This is not a single atomic multicall or `wallet_sendCalls` request, so intents can have independent outcomes. ::::steps #### Install the SDK ```bash npm install @rhinestone/1auth ``` #### Configure BatchQueueProvider Wrap the app with `BatchQueueProvider`: ```tsx [App.tsx] import { OneAuthClient } from '@rhinestone/1auth' // [!code ++] import { BatchQueueProvider } from '@rhinestone/1auth/react' // [!code ++] const client = new OneAuthClient({ // [!code ++] providerUrl: 'https://passkey.1auth.app', // [!code ++] clientId: 'my-app', // [!code ++] }) // [!code ++] export function App({ accountAddress }: { accountAddress?: string }) { return ( // [!code ++] // [!code ++] ) } ``` #### Add items to the queue Use `useBatchQueue` to add transactions: :::code-group ```tsx [AddToCart.tsx] import { useBatchQueue } from '@rhinestone/1auth/react' // [!code ++] export function AddToCartButton({ item }) { const { addToBatch, queue } = useBatchQueue() // [!code ++] const handleClick = () => { // [!code ++] const result = addToBatch( // [!code ++] { // [!code ++] to: item.contractAddress, // [!code ++] data: item.calldata, // [!code ++] label: `Buy ${item.name}`, // [!code ++] }, // [!code ++] 8453 // Base chain ID // [!code ++] ) // [!code ++] // [!code ++] if (!result.success) { // [!code ++] alert(result.error) // [!code ++] } // [!code ++] } // [!code ++] return ( ) } ``` ::: #### Display the queue widget Render `BatchQueueWidget` for queued items: :::code-group ```tsx [App.tsx] import { BatchQueueProvider, BatchQueueWidget, useBatchQueue } from '@rhinestone/1auth/react' import type { Address } from 'viem' function SignAllHandler({ accountAddress }: { accountAddress: Address }) { const { signAll } = useBatchQueue() // [!code ++] const handleSignAll = async () => { // Every queue entry remains a separate intent; one passkey ceremony // authorizes the complete batch. const result = await signAll(accountAddress) // [!code ++] if (result.success) console.log(`${result.successCount} intents submitted`) } return // [!code ++] } export function App() { return ( ) } ``` ::: :::: ### Chain validation All calls in a batch must target the same chain: ```tsx const { addToBatch } = useBatchQueue() // First call sets the batch chain addToBatch({ to: '0x...', label: 'Action 1' }, 8453) // Base // This will fail - different chain const result = addToBatch({ to: '0x...', label: 'Action 2' }, 1) // Ethereum if (!result.success) { console.log(result.error) // "Batch is set to Base..." } ``` ### BatchQueueProvider props | Prop | Type | Required | Description | | ---------------- | --------------- | -------- | ----------------------------------------------------------------------------------------------------------- | | `client` | `OneAuthClient` | Yes | SDK client instance | | `accountAddress` | `Address` | No | Smart account address used for signing and localStorage persistence (enables queue to survive page refresh) | | `children` | `ReactNode` | Yes | Child components | ### useBatchQueue reference | Property | Type | Description | | ----------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | | `queue` | `BatchedCall[]` | Array of queued calls | | `batchChainId` | `number \| null` | Chain ID of the batch (set by first call) | | `addToBatch` | `(call: IntentCall, chainId: number) => { success: boolean; error?: string }` | Add a call to queue | | `removeFromBatch` | `(id: string) => void` | Remove a specific call | | `clearBatch` | `() => void` | Clear all calls | | `signAll` | `(identity?: Address \| { accountAddress: Address }) => Promise` | Sign and submit all calls (a bare address is treated as the account address) | | `isSigning` | `boolean` | Whether signing is in progress | | `isExpanded` | `boolean` | Whether the widget is expanded | | `setExpanded` | `(expanded: boolean) => void` | Set widget expanded state | See the [React Components reference](/sdk/react) for widget options. ### Next steps * [Crosschain](/guides/crosschain) - Execute transactions on any chain * [Deposits](https://docs.rhinestone.dev/deposits/overview) - Fund user accounts import { PayButtonDemo } from '../../layout' ## Checkout Use `PayButton` to authenticate with a passkey and submit a payment intent. ### Using PayButton `PayButton` handles authentication, signing, and execution. ::::steps #### Install the SDK ```bash npm install @rhinestone/1auth ``` #### Create client.ts Create the client: ```ts [client.ts] import { OneAuthClient } from '@rhinestone/1auth' // [!code ++] // Create the 1auth client // [!code ++] export const client = new OneAuthClient({ // [!code ++] providerUrl: 'https://passkey.1auth.app', // [!code ++] clientId: 'my-app', // [!code ++] }) // [!code ++] ``` Checkout flows that already show payment details use [blind signing](/guides/signing) by default. Enable [experimental clear signing](/guides/signing#clear-signing) on the shared client to show 1auth's review UI: ```ts [client.ts] export const client = new OneAuthClient({ providerUrl: 'https://passkey.1auth.app', clientId: 'my-app', experimental_clear_signing: true, }) ``` #### Add PayButton Render `PayButton`: :::code-group ```tsx [Checkout.tsx] import { PayButton } from '@rhinestone/1auth/react' // [!code ++] import { parseEther } from 'viem' export function Checkout() { return ( { // [!code ++] console.log('Paid:', result.transactionHash) // [!code ++] }} // [!code ++] onError={(error) => console.error(error.code, error.details)} // [!code ++] > // [!code ++] Pay $10 // [!code ++] // [!code ++] ) } ``` ::: #### Handle success Use `onSuccess` for post-payment work: :::code-group ```tsx [Checkout.tsx] import { PayButton, SendIntentResult } from '@rhinestone/1auth/react' import { parseEther } from 'viem' import { useRouter } from 'next/navigation' export function Checkout({ orderId }: { orderId: string }) { const router = useRouter() const handleSuccess = async (result: SendIntentResult) => { // [!code ++] // Update your backend // [!code ++] await fetch('/api/orders/complete', { // [!code ++] method: 'POST', // [!code ++] body: JSON.stringify({ // [!code ++] orderId, // [!code ++] txHash: result.transactionHash, // [!code ++] }), // [!code ++] }) // [!code ++] // [!code ++] // Redirect to confirmation // [!code ++] router.push(`/order/${orderId}/confirmation`) // [!code ++] } // [!code ++] return ( Complete Purchase ) } ``` ::: #### Handle failures `PayButton` converts structured `sendIntent()` result failures to `OneAuthError`, preserving their machine-readable code and provider diagnostics. Other caught exceptions can still reach `onError` as generic `Error` objects, so keep the fallback branch shown below. ```tsx [Checkout.tsx] import { OneAuthError, PayButton } from '@rhinestone/1auth/react' const handleError = (error: Error) => { if (error instanceof OneAuthError) { console.error('Payment failed', { code: error.code, providerCode: error.details?.providerCode, traceId: error.details?.traceId, simulationUrls: error.details?.simulationUrls, }) return } console.error('Payment failed', error) } Complete Purchase ``` Use `INVALID_SIGNATURE` to route the user to account recovery. For `PREPARE_FAILED` or `EXECUTE_FAILED`, keep `traceId` and `simulationUrls` in developer logs so the failed quote or simulation can be investigated. :::: ### Contract interactions `PayButton` also accepts contract calls: ```tsx import { encodeFunctionData } from 'viem' toast.success('NFT minted!')} > Mint NFT ``` ### Custom styling Use `className` for custom styles: ```tsx Complete Purchase ``` ### Props reference | Prop | Type | Required | Description | | ----------- | ------------------------------------ | -------- | -------------------------------------------------------------------------------------------------- | | `client` | `OneAuthClient` | Yes | SDK client instance | | `intent` | `SendIntentOptions` | Yes | Transaction parameters (calls, targetChain, tokenRequests) | | `onSuccess` | `(result: SendIntentResult) => void` | No | Called on successful transaction | | `onError` | `(error: Error) => void` | No | Called on error | | `closeOn` | `CloseOnStatus` | No | When to close dialog: "claimed", "preconfirmed", "filled", or "completed". Default: "preconfirmed" | | `children` | `ReactNode` | No | Button text (default: "Pay with 1auth") | | `className` | `string` | No | Custom CSS class | | `style` | `React.CSSProperties` | No | Custom inline styles (merged with defaults) | | `disabled` | `boolean` | No | Disabled state | | `hideIcon` | `boolean` | No | Hide the fingerprint icon | See the full [PayButton API reference](/sdk/pay-button) for more details. ### Next steps * [Crosschain](/guides/crosschain) - Execute transactions on any chain * [Batch Transactions](/guides/batch-transactions) - Queue multiple operations ## Crosschain Use intents to execute target-chain calls with funds sourced from another chain. ### How it works 1. Define the calls, target chain, and required tokens. 2. The orchestrator prepares a funding route. 3. The user approves the intent with a passkey. 4. The orchestrator funds and executes it. ### Using wagmi Wagmi provides hooks to integrate crosschain transactions into your React app. ::::steps #### Install the SDK ```bash npm install @rhinestone/1auth ``` #### Create config.ts Create a wagmi config file with the 1auth connector. For crosschain transactions, add all the chains you want to support: ```ts [config.ts] import { createConfig, http } from 'wagmi' import { base, mainnet, optimism, arbitrum } from 'wagmi/chains' import { OneAuthClient } from '@rhinestone/1auth' // [!code ++] import { oneAuth } from '@rhinestone/1auth/wagmi' // [!code ++] // Create the 1auth client const client = new OneAuthClient({ // [!code ++] providerUrl: 'https://passkey.1auth.app', // [!code ++] clientId: 'my-app', // [!code ++] }) // [!code ++] // Create the wagmi config with 1auth connector export const config = createConfig({ chains: [mainnet, base, optimism, arbitrum], // [!code ++] connectors: [oneAuth({ client })], // [!code ++] transports: { [mainnet.id]: http(), [base.id]: http(), [optimism.id]: http(), [arbitrum.id]: http(), }, }) ``` #### Build your calls Each call has a `to` address, optional `data` (calldata), and optional `value` (ETH amount). Calls within this intent execute atomically. ```ts import { encodeFunctionData, parseUnits } from 'viem' // Example: Approve + Swap in a single atomic batch const calls = [ { to: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913', // USDC contract data: encodeFunctionData({ abi: erc20Abi, functionName: 'approve', args: [DEX_ADDRESS, parseUnits('100', 6)], }), }, { to: DEX_ADDRESS, // DEX contract data: encodeFunctionData({ abi: dexAbi, functionName: 'swap', args: [USDC, WETH, parseUnits('100', 6)], }), }, ] ``` #### Send to any chain Use `useSendCalls` with your calls array. The key crosschain parameters are: * **`chainId`** - specifies which chain the calls execute on (required) * **`tokenRequests`** - specifies what tokens the user needs for the transaction (optional) ```ts sendCalls({ calls, chainId: 8453, // Execute on Base // [!code ++] tokenRequests: [{ // [!code ++] token: USDC_ADDRESS, // [!code ++] amount: parseUnits('100', 6), // [!code ++] }], // [!code ++] }) ``` `tokenRequests` specifies the tokens required on the target chain; the orchestrator selects a route from the user's available assets. :::code-group ```tsx [SwapOnBase.tsx] import { useSendCalls } from 'wagmi' import { encodeFunctionData, parseUnits } from 'viem' export function SwapOnBase() { const { sendCalls, isPending } = useSendCalls() const calls = [ { to: USDC_ADDRESS, data: encodeFunctionData({ abi: erc20Abi, functionName: 'approve', args: [DEX_ADDRESS, parseUnits('100', 6)], }), }, { to: DEX_ADDRESS, data: encodeFunctionData({ abi: dexAbi, functionName: 'swap', args: [USDC, WETH, parseUnits('100', 6)], }), }, ] const handleSwap = () => { sendCalls({ calls, chainId: 8453, // Execute on Base // [!code ++] tokenRequests: [{ // [!code ++] token: USDC_ADDRESS, // USDC needed for swap // [!code ++] amount: parseUnits('100', 6), // [!code ++] }], // [!code ++] }) } return ( ) } ``` ::: See [Token Requests](/guides/crosschain/token-requests) for the output-first model. :::: ### Using the SDK directly Use `sendIntent` without wagmi: ```tsx import { OneAuthClient } from '@rhinestone/1auth' import { parseEther } from 'viem' const client = new OneAuthClient({ providerUrl: 'https://passkey.1auth.app', clientId: 'my-app', }) const auth = await client.authenticate() if (!auth.success) throw new Error(auth.error.message) const result = await client.sendIntent({ accountAddress: auth.session.accountAddress, targetChain: 8453, // Base // [!code ++] calls: [ { to: '0x...', // Contract on Base data: '0x...', // Calldata value: parseEther('0.1'), }, ], closeOn: 'completed', }) if (result.success) { console.log('TX Hash:', result.transactionHash) } ``` ### Next steps * [Token Requests](/guides/crosschain/token-requests) - Deep dive into the output-first model * [Batch Transactions](/guides/batch-transactions) - Queue multiple transactions with a shopping cart UI * [Fee Sponsorship](/guides/fee-sponsorship) - Sponsor gas fees for your users ## Error Codes and Diagnostics Branch on machine-readable error codes and log normalized diagnostic details. This page identifies each API's result shape; for symptom-first fixes, see [Troubleshooting](/guides/troubleshooting). ### Result-based SDK methods `sendIntent()`, `grantPermissions()`, `signMessage()`, and `signTypedData()` return structured failure results. `sendBatchIntent()` is also result-based, but uses flat top-level `errorCode` / `error` fields instead of an `error.code` object — see below. ```ts const result = await client.sendIntent({ accountAddress, targetChain: 8453, calls, }) if (!result.success) { console.error('1auth request failed', { code: result.error?.code, message: result.error?.message, providerCode: result.error?.details?.providerCode, traceId: result.error?.details?.traceId, statusCode: result.error?.details?.statusCode, errorType: result.error?.details?.errorType, simulationUrls: result.error?.details?.simulationUrls, }) } ``` Sponsorship behavior is method-specific: * `sendIntent()` and `grantPermissions()` return `MISSING_APP_CREDENTIALS` or `SPONSORSHIP_FETCH_FAILED` in `result.error.code`. * `sendBatchIntent()` uses top-level `errorCode` and `error`. Missing configuration sets `error`; failed access-token fetches report only through SDK telemetry. * `getAssets()` rejects for configuration, token-callback, or portfolio failures; use `try`/`catch`. ### Exception-based integrations The EIP-1193 provider, viem accounts, and passkey wallet client throw `OneAuthError`, preserving structured codes and diagnostics. ```ts import { OneAuthError } from '@rhinestone/1auth' try { await walletClient.signMessage({ message: 'Approve login' }) } catch (error) { if (error instanceof OneAuthError) { console.error('1auth request failed', { code: error.code, message: error.message, providerCode: error.details?.providerCode, traceId: error.details?.traceId, simulationUrls: error.details?.simulationUrls, }) } } ``` `PayButton` converts unsuccessful `sendIntent()` results to `OneAuthError` for `onError`; other failures remain ordinary `Error` objects, so keep a fallback: ```tsx import { OneAuthError, PayButton } from '@rhinestone/1auth/react' { if (error instanceof OneAuthError) { console.error(error.code, error.details) return } console.error('Unexpected payment error', error) }} > Pay ``` ### Common error codes | Code | Stage | Application behavior | | -------------------------- | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `USER_REJECTED` | Signing dialog | Keep the user on the current screen and allow a new attempt. | | `USER_CANCELLED` | Dialog or status wait | Preserve current state; the user deliberately closed the flow. | | `PREPARE_FAILED` | Quote or pre-sign simulation | Inspect the returned details. Correct unsupported calldata, balances, or route constraints before retrying. A `No viable route found` message usually means an empty balance, not an unsupported route. | | `INVALID_SIGNATURE` | Execution simulation | Start account recovery. Retrying with the same stale passkey will fail again. | | `EXECUTE_FAILED` | Submission or execution simulation | Log `providerCode`, `traceId`, and `simulationUrls` for investigation. | | `NETWORK_ERROR` | SDK transport | Retry after connectivity recovers. | | `SPONSORSHIP_FETCH_FAILED` | App sponsorship | Check the app's access-token or extension-token endpoint. | | `HASH_TIMEOUT` | Transaction confirmation | Keep the intent ID and query its status later. | | `MISSING_APP_CREDENTIALS` | Client configuration | Configure SDK sponsorship credentials before sponsored operations or asset queries. | | `INVALID_OPTIONS` | Client validation | Correct the request before opening another dialog. | ### Diagnostic fields | Field | Purpose | | ---------------- | ---------------------------------------------------------- | | `providerCode` | Machine-readable code returned by the Rhinestone provider. | | `traceId` | Correlation ID to include in logs and support requests. | | `statusCode` | Upstream HTTP status, when available. | | `errorType` | Orchestrator execution-error category. | | `simulationUrls` | Links to available transaction simulation traces. | Use these only in developer logs and support tooling. Never render raw simulation URLs or provider diagnostics to users. import { UserPaidIntentDemo } from '../../components/demos/UserPaidIntentDemo'; ## Fee Sponsorship Every user-initiated intent authenticates with the calling app's JWT. The app independently chooses, per intent, whether to **sponsor** (pay the gas/bridge fees) or to let the user pay from their source assets. ### Sponsored vs. user-paid | Mode | SDK call | App JWT | Extension token | Who pays | | ------------------- | -------------------------------------------------- | -------- | --------------- | -------- | | Sponsored (default) | `sendIntent({ ... })` | required | required | app | | User-paid | `sendIntent({ ..., sponsorshipMode: "disabled" })` | required | not fetched | user | `sponsorshipMode` is an explicit per-call policy. `required` is the default and fails closed. `preferred` opts into a newly reviewed self-funded quote only when sponsorship fails. `disabled` requests self-funding directly and skips the grant. ### Set up sponsorship on the server Your backend mints the short-lived JWTs used to sign every intent. Expose two same-origin endpoints; the SDK calls them with the user's session cookie attached: * **Access token** — identifies your app to the orchestrator. Minted once and reused; expires after **1 hour**. * **Extension token** — scoped to a single intent's digest, authorizing that exact operation. Minted per intent; expires after **5 minutes**. Short expiries mean a leaked token has a small blast radius — but it's no substitute for guarding the endpoints (see the warning below). #### Environment variables Create a Rhinestone app in the [Rhinestone dashboard](https://dashboard.rhinestone.dev), then register a JWT signing key under **API keys → JWT keys**. The keypair is generated in your browser; the private half downloads as `.jwk.json`. | Variable | Description | | ---------------------------- | ------------------------------------------------------------------------------------- | | `RHINESTONE_JWT_PRIVATE_KEY` | The downloaded JWK, minified to one line (EC P-256 / ES256 recommended, RSA accepted) | | `RHINESTONE_INTEGRATOR_ID` | Integrator ID you set when registering the key (JWT `iss`) | | `RHINESTONE_PROJECT_ID` | Project ID, from the dashboard project page (JWT `sub`) | | `RHINESTONE_APP_ID` | **A label you pick** — `prod`, `staging`, one per deployment (JWT `app_id`) | | `RHINESTONE_KEY_ID` | Key ID you set when registering the key (`kid` header) | `.jwk.json` is pretty-printed across several lines, but an env var holds one — minify it, single-quoted: ```bash printf "RHINESTONE_JWT_PRIVATE_KEY='%s'\n" "$(jq -c . prod-2026-06.jwk.json)" >> .env ``` ```bash # .env RHINESTONE_JWT_PRIVATE_KEY='{"crv":"P-256","d":"uUXnoBer-9yC2sC77Yua21EZnjSGY-X9Q1-d0Ubrn1M","ext":true,"key_ops":["sign"],"kty":"EC","x":"YbfueCnHp97cMIi98g9wQG6Z_6ftBBCHSsrUMw5KBvc","y":"pKyNjQtZ6jO1DIQ2SUCesJABKDmgE95U3pqg2I0-0YU"}' RHINESTONE_INTEGRATOR_ID=acme RHINESTONE_PROJECT_ID=cmd7k2a0h0001x8n4v2q9wbz3 RHINESTONE_APP_ID=prod RHINESTONE_KEY_ID=prod-2026-06 ``` #### Next.js App Router ```ts // app/api/sponsorship/access-token/route.ts import { NextResponse } from "next/server"; import { createSponsorshipSigner } from "@rhinestone/1auth/server"; import { getSession } from "@/lib/session"; // your auth const signer = createSponsorshipSigner(); export async function GET() { const session = await getSession(); if (!session.userId) return NextResponse.json({ error: "unauthorized" }, { status: 401 }); return NextResponse.json({ token: await signer.accessToken() }); } ``` ```ts // app/api/sponsorship/extension-token/route.ts import { NextRequest, NextResponse } from "next/server"; import { createSponsorshipSigner } from "@rhinestone/1auth/server"; import { getSession } from "@/lib/session"; // `shouldSponsor` runs server-side *before* the grant is signed, so it // protects you against every caller — including scripted requests that // ignore CORS. Scope it as tightly as your product allows. const signer = createSponsorshipSigner({ shouldSponsor: { // Only chains you actually operate on. chain: ({ id }) => SUPPORTED_CHAIN_IDS.has(id), // Only your own contracts — stops an attacker from billing you for // gas on arbitrary (e.g. gas-heavy) contracts. calls: (calls) => calls.every((c) => ALLOWED_CONTRACTS.has(c.to.toLowerCase())), }, }); export async function POST(req: NextRequest) { const session = await getSession(); if (!session.userId) return NextResponse.json({ error: "unauthorized" }, { status: 401 }); const { intentOp } = await req.json(); try { return NextResponse.json({ token: await signer.extensionToken(intentOp) }); } catch (err) { // `shouldSponsor` rejected this intent — expected, not a server fault. if (err instanceof Error && err.name === "SponsorshipDeniedError") { return NextResponse.json({ error: "not sponsorable" }, { status: 403 }); } throw err; } } ``` `createSponsorshipSigner()` reads all five env vars automatically. Pass `{ credentials: { ... } }` to override them, or `{ shouldSponsor }` to filter which intents you'll sponsor. ### Securing the sponsorship endpoints These endpoints **mint tokens billed against your Rhinestone project** — treat a sponsorship grant as money, not as an identity. The extension token is the grant that actually says "the app pays this intent's gas" (the access token only identifies your app). Because the SDK calls these endpoints from the browser, anyone who can reach them can request a grant unless you stop them. No single control is enough — defend in layers, because each covers a different class of caller: | Layer | What it stops | Covers scripted (non-browser) callers? | | ------------------------------------------------------------- | ----------------------------------------------------- | ------------------------------------------------------ | | **1. `shouldSponsor` policy** (chain / contract / value caps) | Billing you for intents you never meant to sponsor | ✅ Yes — enforced before signing, regardless of caller | | **2. Session auth** (httpOnly + Secure + `SameSite` cookie) | Anonymous & cross-site browser abuse | ❌ No — cookies/CORS only constrain browsers | | **3. Intent binding** (built in) | Replaying a leaked grant against a *different* intent | ✅ Yes — the 5-min token is pinned to the intent digest | | **4. Budget cap + rate limits** (Rhinestone dashboard) | Bounding total damage if anything else leaks | ✅ Yes | **A session cookie is necessary but not sufficient.** It stops opportunistic browser abuse, but a `curl` attacker ignores cookies and CORS entirely — so `shouldSponsor` is your only protection against them. #### Bind the grant to the logged-in user `shouldSponsor.account` receives the smart-account address the intent will execute from. Combined with your session, this stops one authenticated user from minting grants for *other* accounts: ```ts export async function POST(req: NextRequest) { const session = await getSession(); if (!session.userId) return NextResponse.json({ error: "unauthorized" }, { status: 401 }); // Resolve the account this user is allowed to spend for, then bind the // grant to it so a logged-in user can't sponsor someone else's intents. const usersAccount = await getOneAuthAddressForUser(session.userId); const signer = createSponsorshipSigner({ shouldSponsor: { chain: ({ id }) => SUPPORTED_CHAIN_IDS.has(id), account: (address) => address.toLowerCase() === usersAccount.toLowerCase(), }, }); const { intentOp } = await req.json(); return NextResponse.json({ token: await signer.extensionToken(intentOp) }); } ``` `verifyOneAuthAccount()` (also exported from `@rhinestone/1auth/server`) lets you confirm server-side that an address really belongs to a known 1auth account before you bind to it. :::warning **Never put `Access-Control-Allow-Origin: *` on a token-minting endpoint.** Keep it same-origin so `SameSite` and your session cookie actually gate it. And always set a **project-level budget cap** in the Rhinestone dashboard as a final backstop — assume a key or token can leak, and bound the blast radius. ::: #### Any HTTP server The factory returns plain async functions, so it works with any HTTP framework — or with a dev server's middleware, when your app is a static SPA with no backend of its own. Both routes are plain JSON: `GET` → `{ token }`, `POST { intentOp }` → `{ token }`. The signer itself is runtime-agnostic (`jose` + WebCrypto, no `node:` imports), so Workers, Deno, and Bun work too — but there is no `process.env` to read there, so pass `credentials` explicitly instead of relying on the default lookup. :::code-group ```ts [Express] import express from "express"; import { createSponsorshipSigner } from "@rhinestone/1auth/server"; const signer = createSponsorshipSigner(); const app = express(); app.get("/api/sponsorship/access-token", requireSession, async (_req, res) => { res.json({ token: await signer.accessToken() }); }); app.post("/api/sponsorship/extension-token", requireSession, async (req, res) => { res.json({ token: await signer.extensionToken(req.body.intentOp) }); }); ``` ```ts [Vite dev server] // vite.config.ts import type { ServerResponse } from "node:http"; import { json as readJson } from "node:stream/consumers"; import { defineConfig, type Plugin } from "vite"; import { createSponsorshipSigner } from "@rhinestone/1auth/server"; // Vite loads .env for your app code, not for this config file. Node 20.12+. process.loadEnvFile(); function sponsorship(): Plugin { const signer = createSponsorshipSigner(); const reply = async (res: ServerResponse, mint: () => Promise) => { res.setHeader("content-type", "application/json"); try { res.end(JSON.stringify({ token: await mint() })); } catch (err) { // The SDK folds this `error` into the Error it throws, so an unusable // signing key surfaces at the call site instead of as an opaque 500. res.statusCode = 500; res.end(JSON.stringify({ error: err instanceof Error ? err.message : String(err) })); } }; return { name: "sponsorship-endpoints", apply: "serve", configureServer(server) { server.middlewares.use("/api/sponsorship/access-token", (_req, res) => reply(res, () => signer.accessToken()), ); server.middlewares.use("/api/sponsorship/extension-token", (req, res) => reply(res, async () => { const { intentOp } = (await readJson(req)) as { intentOp: string }; return signer.extensionToken(intentOp); }), ); }, }; } export default defineConfig({ plugins: [sponsorship()] }); ``` ::: The Vite plugin is a local stand-in for the backend you ship, not a substitute for it: it only runs under `vite dev` (`vite build` emits static files with no server attached), and it has neither a session check nor a `shouldSponsor` filter. Both are fine to omit on a loopback dev server and are the first things to add anywhere else. #### Advanced: custom claims If you need a custom audience or additional claims, drop down to the raw `createJwtSigner` from `@rhinestone/sdk/jwt-server`, also re-exported from `@rhinestone/1auth/server`. ### Configure sponsorship on the client Configure the SDK with both endpoints: ```ts import { OneAuthClient } from "@rhinestone/1auth"; const client = new OneAuthClient({ providerUrl: "https://passkey.1auth.app", clientId: "my-app", sponsorship: { accessTokenUrl: "/api/sponsorship/access-token", extensionTokenUrl: "/api/sponsorship/extension-token", }, }); ``` `sponsorship` is required whenever the client submits user intents — there is no anonymous fallback. A client without `sponsorship` configured will reject `sendIntent` calls with `MISSING_APP_CREDENTIALS`. ### Demo ## Headless Mode Headless mode submits a 1auth intent with signatures produced outside the passkey dialog. Use it when the ERC-7579 account has another installed validator and your app can produce its expected signatures. 1auth prepares the intent and forwards opaque signature bytes; the installed on-chain validator decides whether they are valid. For example, the non-passkey signer might be: * an app-managed ECDSA signer, * a backend or AWS KMS signing service, * another ERC-7579 validator your app has installed out of band. Use `OneAuthClient.sendIntent` when every intent should show a passkey approval dialog. ### What 1auth does Headless mode still provides: * `/api/intent/prepare?signingMode=headless` quotes the intent, performs balance checks, and returns the message hashes your validator signer must sign. * Sponsorship helpers mint access and extension JWTs for apps that sponsor intents. * `/api/intent/headless-execute` forwards your pre-encoded validator signatures to the orchestrator. * Status and wait endpoints work the same way as the passkey flow. 1auth treats the submitted signatures as opaque bytes. It does not open clear signing UI and does not verify the validator signature locally. ### Requirements Before using headless mode: * the account must already have a validator installed that can authorize the intent, * your app must know how to sign the prepared hashes for that validator, * your app must encode the signatures in the validator-prefixed format expected by the orchestrator, * submitted calls must stay inside whatever policy or authorization the installed validator enforces. This guide covers only the prepare-sign-submit path. For SmartSession validators, use the [Permissions](/guides/permissions) flow for setup, policy review, and session-key handling. ### Prepare ```ts import { OneAuthHeadlessClient } from "@rhinestone/1auth/headless"; const headless = new OneAuthHeadlessClient({ providerUrl: "https://passkey.1auth.app", sponsorship: { accessTokenUrl: "/api/sponsorship/access-token", extensionTokenUrl: "/api/sponsorship/extension-token", }, }); const prepared = await headless.prepareIntent({ accountAddress, targetChain: 84532, calls: [ { to: vault, data: depositCalldata, value: 0n, }, ], }); ``` `prepareIntent()` returns `intentOp` and `digestResult` for unchanged submission, per-origin hashes, destination and target-execution hashes when required, and the echoed account, calls, target chain, and expiry. ### Sign Sign the prepared hashes with the non-passkey validator your app controls. 1auth does not prescribe the signer or encoding here; use the encoder for your validator. ```ts const { originSignatures, destinationSignature, targetExecutionSignature, } = await signWithInstalledValidator({ prepared, validatorContext, }); ``` The contents of `validatorContext` depend on the installed validator. ### Submit ```ts const result = await headless.submitIntent({ intentOp: prepared.intentOp, digestResult: prepared.digestResult, binding: prepared.binding, accountAddress: prepared.accountAddress, targetChain: prepared.targetChain, calls: prepared.calls, expiresAt: prepared.expiresAt, originSignatures, destinationSignature, targetExecutionSignature, }); ``` `prepareIntent()` fixes the funding mode before signing and returns the quote-time `sponsorshipToken` for sponsored submission. Use `sponsorshipMode: "preferred"` to allow a self-funded re-quote, or `"disabled"` to request self-funding. ### Wait ```ts const final = await headless.waitForIntent( result.intentId, result.transactionResult, ); ``` `waitForIntent()` returns the latest orchestrator status and any available transaction hash. ### Trust Model Headless mode removes the per-intent passkey dialog, so your app decides what to sign. 1auth binds a sponsored intent's extension token to the prepared `intentOp`, but a malicious or buggy app-side signer can still sign the wrong thing. The safety boundary is the installed validator: * if the validator approves the submitted signature, the intent can execute, * if the calls drift outside that validator's policy, the validator should reject on-chain. import { GrantPermissionDemo } from '../../layout' ## Permissions Permissions add an app-controlled, scoped session key to an account. 1auth handles approval, passkey authorization, and installation; it never receives the session private key. Start with one target contract, one selector, and a 24-hour validity window. The app can then execute that action without another passkey dialog. After granting, use [Headless Mode](/guides/headless-mode) to prepare, sign, and submit intents. Explicit `targetChains` install contract-and-selector authority; no chain is selected implicitly. For cross-chain routes, put the destination execution chain in `targetChains` and every funding chain in `sourceChains`. An Arbitrum Sepolia swap funded by mUSD on Base Sepolia needs swap permission on Arbitrum and source-chain Permit2-claim coverage on Base. Omitting both `sourceChains` and `crossChainPermits` grants no Permit2 or cross-chain claim authority. ### Grant scoped access :::steps #### Create or load a signer Create or load the ECDSA signer your app will use for headless execution. It may live in the browser, backend, KMS/HSM, or another system that can produce SmartSession signatures. Send only its public `sessionKeyAddress` to 1auth. #### Define permissions Use `definePermissions()` so app code does not hardcode selectors or calldata offsets. Start with one named function on one target contract. When granting the permission, the application explicitly supplies `validAfter` and a `validUntil` 24 hours later. ```ts import { definePermissions } from "@rhinestone/1auth"; const mockUsdMintAbi = [ { type: "function", name: "mint", stateMutability: "nonpayable", inputs: [ { name: "to", type: "address" }, { name: "amount", type: "uint256" }, ], outputs: [], }, ] as const; const validAfter = Math.floor(Date.now() / 1000); const validUntil = validAfter + 24 * 60 * 60; const permissions = definePermissions({ address: mUSD, name: "mUSD", abi: mockUsdMintAbi, functions: { mint: {}, }, }); ``` `definePermissions()` returns the `permissions` and `contracts` for `grantPermissions()`. This scopes the action to the contract and `mint(address,uint256)` selector, leaving `to` and `amount` unconstrained. 1auth does not choose an expiry: the application must pass `validUntil`. #### Grant permissions ```ts import { OneAuthClient } from "@rhinestone/1auth"; const oneAuth = new OneAuthClient({ providerUrl: "https://passkey.1auth.app", clientId: "webshop", sponsorship: { accessTokenUrl: "/api/sponsorship/access-token", extensionTokenUrl: "/api/sponsorship/extension-token", }, }); const sessionKeyAddress = await appSigner.getAddress(); const result = await oneAuth.grantPermissions({ accountAddress, targetChains: [8453, 84532], sessionKeyAddress, validAfter, validUntil, maxUses: 25, ...permissions, }); if (!result.success) { throw new Error(result.error.message); } ``` After this one-time grant, the app can submit calldata accepted by `mint(address,uint256)` during the validity window without another signature dialog. On-chain SmartSession enforcement checks the contract, selector, time window, and `maxUses` approved by the user. This starting pattern is selector-scoped. Add `params` for fixed recipients, amount ceilings, or other calldata rules; use `maxUses` to cap executions. The embedded `GrantPermissionDemo` also constrains recipient and mint amount. #### Add a bridge claim permission Selector permissions cover calls on the destination chain. If the headless intent is funded by a source-chain asset through Permit2 and a settlement layer such as Across, add a `crossChainPermits` entry as well. This tells the SmartSession what source token may be claimed, which destination token may be delivered, who may receive it, and which settlement layer is allowed. ```ts import { createCrossChainPermission, definePermissions, } from "@rhinestone/1auth"; import { parseUnits } from "viem"; import { arbitrumSepolia, baseSepolia } from "viem/chains"; const ARB_SEPOLIA_CHAIN_ID = 421614; const BASE_SEPOLIA_CHAIN_ID = 84532; const usdcOnArb = "0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d"; const maxBridgeSpend = parseUnits("0.1", 6); const now = Math.floor(Date.now() / 1000); const validUntil = now + 24 * 60 * 60; const swap = definePermissions({ address: rwaSwap, name: "RWASwap", abi: rwaSwapAbi, functions: { swap: { params: { usdcIn: { condition: "equal", value: maxBridgeSpend }, recipient: { condition: "equal", value: accountAddress }, }, }, }, }); const bridge = createCrossChainPermission({ from: { chain: baseSepolia, token: mUSDOnBase, maxAmount: maxBridgeSpend, }, to: { chain: arbitrumSepolia, token: usdcOnArb, recipient: accountAddress, }, validAfter: BigInt(now), validUntil: BigInt(validUntil), settlementLayers: ["ACROSS"], }); const result = await oneAuth.grantPermissions({ accountAddress, // Arbitrum verifies the swap call. Base only verifies the Permit2 claim. targetChains: [ARB_SEPOLIA_CHAIN_ID], sourceChains: [BASE_SEPOLIA_CHAIN_ID], sessionKeyAddress, validAfter: now, validUntil, maxUses: 25, permissions: swap.permissions, crossChainPermits: [bridge], contracts: swap.contracts, }); ``` The grant dialog shows the bridge's source token and chain, destination token, recipient, cap, validity window, and settlement layer before approval. Labels and ABIs improve readability only; the structured bridge permit and selector policies are signed. Do not omit the source chain: Permit2 calls `isValidSignature` on the source-chain account. A SmartSession enabled only on the destination cannot make the later headless claim, even when destination swap permission exists. `grantPermissions()` returns: ```ts { success: true, grantId, sessionKeyHandle: { sessionKeyAddress, permissionId, permissionIdsByChain, accountAddress, permissions, chainId, chainIds, expiresAt, }, permissionId, permissionIdsByChain, intentId, intentIds, status, chainResults, transactionHash, transactionHashesByChain, statusUrl, waitUrl, } ``` Persist the private key, KMS key ID, or other signer reference needed later; 1auth never stores that capability. It stores public grant metadata, including the recoverable `sessionKeyHandle`, permission IDs, chain status, transaction hashes, and requesting origin. Grants are keyed by exact browser origin, not `clientId`: `https://checkout.example.com` cannot recover grants created by `https://app.example.com`. Your app can recover existing grants from the same registered origin: ```ts const grants = await oneAuth.listSessionGrants({ accountAddress, }); const activeGrant = grants.success ? grants.grants.find((grant) => !grant.revokedAt) : undefined; ``` The registry is only a UX and recovery index. The on-chain SmartSession validator remains the execution authority, and the app signer must produce headless signatures. Use the handle's `chainIds` and `permissionIdsByChain` for the executing chain. Users can inspect and revoke grants in the 1auth account dialog. Revocation submits SmartSession `removeConfig`; 1auth marks the registry entry revoked only after submission. #### Review in 1auth The permission review answers *what this signer can do later*, rather than clear signing's *what happens now*. It groups actions by contract and function, showing applicable chains, ABI/selector trust badge, usage/time/parameter policies, unconstrained values, and warnings for app-supplied ABIs, raw selectors, no expiry, or broad permissions. Only 1auth's clear-signing registry produces a verified badge; app-supplied ABI metadata is an unverified readability hint. #### Execute headlessly Use the returned handle with the headless client. This opens no additional approval dialog: your app signs with the session key and on-chain SmartSession enforces the approved scope. ```ts import { OneAuthHeadlessClient } from "@rhinestone/1auth/headless"; const headless = new OneAuthHeadlessClient({ providerUrl: "https://passkey.1auth.app", clientId: "your-client-id", sponsorship: { accessTokenUrl: "/api/sponsorship/access-token", extensionTokenUrl: "/api/sponsorship/extension-token", }, }); const prepared = await headless.prepareIntent({ accountAddress, targetChain: 84532, calls, sessionKeyHandle: stored.handle, }); // Sign prepared SmartSession hashes with your app-managed signer, // encode the validator-prefixed signatures, then submit. const submitted = await headless.submitIntent({ intentOp: prepared.intentOp, digestResult: prepared.digestResult, binding: prepared.binding, accountAddress: prepared.accountAddress, targetChain: prepared.targetChain, calls: prepared.calls, expiresAt: prepared.expiresAt, originSignatures, destinationSignature, targetExecutionSignature, }); ``` See the [Headless Mode guide](/guides/headless-mode) for the signing and submit details, including validator-prefixed signature encoding and intent status polling. ::: ### Advanced example: approve and deposit The same pattern can grant a small workflow instead of one function. For an ERC-4626 vault deposit, the session key needs permission to approve USDC for the vault and then call `deposit` on the vault. Keep both actions scoped to the same spender, receiver, and maximum amount. ```ts import { definePermissions } from "@rhinestone/1auth"; import { parseUnits } from "viem"; const erc20ApproveAbi = [ { type: "function", name: "approve", stateMutability: "nonpayable", inputs: [ { name: "spender", type: "address" }, { name: "amount", type: "uint256" }, ], outputs: [{ name: "", type: "bool" }], }, ] as const; const erc4626DepositAbi = [ { type: "function", name: "deposit", stateMutability: "nonpayable", inputs: [ { name: "assets", type: "uint256" }, { name: "receiver", type: "address" }, ], outputs: [{ name: "shares", type: "uint256" }], }, ] as const; const maxDeposit = parseUnits("500", 6); const validAfter = Math.floor(Date.now() / 1000); const validUntil = validAfter + 24 * 60 * 60; const usdcApproval = definePermissions({ address: USDC, name: "USDC", abi: erc20ApproveAbi, functions: { approve: { params: { spender: { condition: "equal", value: vault, }, amount: { condition: "lessThanOrEqual", value: maxDeposit, }, }, }, }, }); const vaultDeposit = definePermissions({ address: vault, name: "USDC Vault", abi: erc4626DepositAbi, functions: { deposit: { params: { assets: { condition: "lessThanOrEqual", value: maxDeposit, }, receiver: { condition: "equal", value: accountAddress, }, }, }, }, }); const permissions = { permissions: [...usdcApproval.permissions, ...vaultDeposit.permissions], contracts: [...usdcApproval.contracts, ...vaultDeposit.contracts], validAfter, validUntil, maxUses: 25, }; ``` The review groups `USDC.approve(spender, amount)` and `USDC Vault.deposit(assets, receiver)`, including their shared limits and constraints. With multiple `targetChains`, one approval covers every requested chain while 1auth installs/enables the session on each needed chain. ### Session limits #### Usage limit Limits how many times the session may use its granted actions. ```ts await oneAuth.grantPermissions({ // ... maxUses: 100, }); ``` #### Time frame Limits when the action may be used. ```ts await oneAuth.grantPermissions({ // ... validAfter: 0, validUntil: Math.floor(Date.now() / 1000) + 24 * 60 * 60, }); ``` Pass `validAfter` and `validUntil` as Unix timestamps in seconds, not milliseconds. #### Value limit Limits the native value for a use. Add it as a function config field inside `definePermissions()`. ```ts functions: { deposit: { valueLimitPerUse: parseEther("0.1"), params: { /* ... */ }, }, } ``` #### Universal action Constrains calldata parameters. Prefer writing this through `definePermissions()`: ```ts params: { asset: { condition: "equal", value: USDC }, amount: { condition: "lessThanOrEqual", value: parseUnits("50000", 6) }, onBehalfOf: { condition: "equal", value: treasury }, } ``` `definePermissions()` derives the required calldata constraints. ### Security notes * Do not send private session keys to 1auth. * Prefer exact parameter constraints over broad selector access. * Treat app-supplied ABI labels as unverified readability hints. * Show short expiries and usage limits for automated sessions. * Rotate or revoke session keys when users disconnect or change devices. ## Signing Every 1auth signature uses a signing dialog to prepare and verify the payload, then a browser WebAuthn prompt that the user must approve. Choose who shows the human-readable review before that prompt: * **Blind signing** (default): the signing dialog stays hidden and your app is the review UI. * **Clear signing**: a visible 1auth review iframe appears before the passkey prompt. ### Blind signing By default, the signing dialog is invisible; 1auth renders no review UI. The browser WebAuthn prompt is always shown, and nothing is signed without a user gesture. Before invoking the SDK, show the recipient, amount, token, chain, fees, and risk context in your UI. See [Checkout](/guides/checkout). "Blind" describes the review UX, not the security model. The server still binds and verifies the exact prepared intent, WebAuthn challenge, browser origin, RP ID, account, and credential before submitting anything on-chain, so your app cannot swap the payload after the user approves. #### Choosing a mode | | Blind signing | Clear signing | | ----------------------- | -------------------------------- | --------------------------------------- | | 1auth review UI | Hidden | Visible review iframe before WebAuthn | | Who shows the action | Your app, before calling the SDK | 1auth, from the server-prepared payload | | Browser WebAuthn prompt | Always shown | Always shown, after review approval | Use blind signing when your app owns the review UI. Use clear signing to show the authoritative 1auth-prepared action before approval. ### Clear signing Shows a 1auth transaction, message, or EIP-712 review iframe before the passkey prompt. This experimental API can change while the review UX and integration contract are validated. #### Enable Set `experimental_clear_signing: true` on `OneAuthClient`: ```ts import { OneAuthClient } from "@rhinestone/1auth"; export const client = new OneAuthClient({ providerUrl: "https://passkey.1auth.app", clientId: "wallet-dashboard", experimental_clear_signing: true, sponsorship: { accessTokenUrl: "/api/sponsorship/access-token", extensionTokenUrl: "/api/sponsorship/extension-token", }, }); ``` Supported signing calls show the review iframe before WebAuthn starts. Authentication, signup, recovery, and permission grants are unchanged. #### Supported methods * `sendIntent()` * `sendBatchIntent()` * `createPasskeyWalletClient()` `sendTransaction()` and `sendCalls()` flows `signMessage()`, `signTypedData()`, and `signWithModal()` always show the review iframe before WebAuthn, whatever this option says. App-origin `sendIntent()` also supports the experiment: the 1auth iframe shows the authoritative review, then WebAuthn still runs on the integrating application's own origin after approval. See [App-origin passkeys](/guides/app-origin-passkeys). #### Per-call overrides Disable it for one request on a client that enabled it globally: ```ts await client.sendIntent({ accountAddress, targetChain: 8453, calls: [paymentCall], experimental_clear_signing: false, }); ``` For viem wallet-client integrations, enable it on the factory because the factory creates its own internal `OneAuthClient`: ```ts const walletClient = createPasskeyWalletClient({ accountAddress, clientId: "wallet-dashboard", chain, transport, experimental_clear_signing: true, }); ``` #### What users see The review iframe renders the signable action before WebAuthn: * verified actions from 1auth's clear-signing registry, * decoded ERC-20 transfers and approvals when possible, * app-supplied ABI labels marked as app supplied, * raw contract calls when no safe decode exists, * chain, amount, recipient, and policy details when available. Verified badges only come from 1auth's registry. App-supplied ABI metadata can make a custom contract readable, but it is not marked verified. ### Signing vs Headless Mode Blind and clear signing both use 1auth's passkey signer. [Headless Mode](/guides/headless-mode) instead accepts signatures from another validator or signer and does not run the passkey dialog. import { AuthDemo } from '../../layout' ## Signup & Login Add passkey authentication to your app with a single method call. ### Using wagmi Use the 1auth connector with Wagmi. ::::steps #### Install the SDK ```bash npm install @rhinestone/1auth ``` #### Create config.ts Create a wagmi config file with the 1auth connector: ```ts [config.ts] import { createConfig, http } from 'wagmi' import { base } from 'wagmi/chains' import { OneAuthClient } from '@rhinestone/1auth' // [!code ++] import { oneAuth } from '@rhinestone/1auth/wagmi' // [!code ++] // Create the 1auth client const client = new OneAuthClient({ // [!code ++] providerUrl: 'https://passkey.1auth.app', // [!code ++] clientId: 'my-app', // [!code ++] }) // [!code ++] // Create the wagmi config with 1auth connector export const config = createConfig({ chains: [base], connectors: [oneAuth({ client, chainId: base.id })], // [!code ++] transports: { [base.id]: http(), }, }) ``` #### Display sign in button Connect with the 1auth connector from your config: ```tsx [SignInButton.tsx] import { useConnect } from 'wagmi' export function SignInButton() { const { connectors, connect } = useConnect() const connector = connectors.find((c) => c.id === '1auth') // [!code ++] return ( ) } ``` #### Display account & sign out Display the connected account and provide sign-out: :::code-group ```tsx [Example.tsx] import { useAccount, useConnect, useDisconnect } from 'wagmi' export function Account() { const { address } = useAccount() // [!code ++] const { disconnect } = useDisconnect() // [!code ++] const { connectors, connect } = useConnect() const connector = connectors.find((c) => c.id === '1auth') if (address) { // [!code ++] return ( // [!code ++]
// [!code ++]

{address.slice(0, 6)}...{address.slice(-4)}

// [!code ++] // [!code ++]
// [!code ++] ) // [!code ++] } // [!code ++] return ( ) } ``` ::: :::: ### Using the SDK directly Without wagmi, call `authenticate()` directly: ```tsx import { OneAuthClient } from '@rhinestone/1auth' const client = new OneAuthClient({ providerUrl: 'https://passkey.1auth.app', clientId: 'my-app', }) // Authenticate or create an account const result = await client.authenticate() if (result.success) { console.log('Address:', result.session.accountAddress) } ``` ### How it works 1. **User clicks sign in** — your app calls `authenticate()` or uses the wagmi connector. 2. **Identity dialog opens** — the user verifies email or OAuth identity. 3. **Passkey prompt opens in the app page** — WebAuthn uses the exact page hostname as its RP ID. 4. **Success** — you receive the smart-account address derived from `https://`. `clientId` supplies app metadata but does not select the RP namespace. ### Custom ENS names Custom ENS names are available on request. Contact Rhinestone to configure resolution for your app. ### Next steps * [Authentication](/guides/authentication) - Learn about message signing and verification * [Checkout](/guides/checkout) - Add payments with PayButton ## Theming Set the color mode, accent, and dialog backdrop when creating your client: ```ts import { OneAuthClient } from '@rhinestone/1auth' const client = new OneAuthClient({ providerUrl: 'https://passkey.1auth.app', clientId: 'my-app', theme: { mode: 'dark', accent: '#4F41EF', backdrop: { color: '#52525c', opacity: 0.5, blur: 12, }, }, }) ``` ### Theme options | Property | Type | Description | | ------------------ | ------------------------------- | ----------------------------------------------------- | | `mode` | `'light' \| 'dark' \| 'system'` | Color mode. `system` follows the user's OS preference | | `accent` | `string` | Hex color for buttons and interactive elements | | `backdrop.color` | `string` | Six-digit hex tint. Default: `#000000` | | `backdrop.opacity` | `number` | Opacity from `0` to `1`. Default: `0.4` | | `backdrop.blur` | `number` | Blur radius from `0` to `40` pixels. Default: `8` |
On dark pages, use a lighter backdrop tint to distinguish the dialog from the background. Each backdrop field defaults independently; the same settings apply while the dialog loads. ### Update theme at runtime ```ts client.setTheme({ mode: 'dark', accent: '#ec4899' }) ``` ### Per-method theming Individual methods such as `signMessage()` also accept a `theme` option for request-specific overrides. ## Token Requests `tokenRequests` declares tokens that must be available on the target chain before the transaction executes. ### Rhinestone Warp [Rhinestone Warp](https://docs.rhinestone.dev/intents/use-cases/chain-abstracted-swaps) routes source assets to the requested target-chain tokens as part of the intent. ### User Experience The signing dialog shows the requested token details before approval.
Token requests shown in signing dialog
It includes the token, amount, destination chain, and cross-chain source when applicable. ### When to Use tokenRequests Use `tokenRequests` when your intent requires specific tokens to be delivered on the target chain. `tokenRequests` are not calldata. They describe the token output the orchestrator must provide before any app call executes. | Scenario | tokenRequests | | ------------------------------- | -------------------------------------------------------------------------------------------------- | | Plain swap via `sendIntent` | **Required** - specify the output token and amount, and set `calls: []` | | ERC20 transfer via `sendIntent` | **Required** - specify the token and amount being sent, and include the real `ERC20.transfer` call | | Contract call needing tokens | **Required** - specify tokens the contract will consume | | Native ETH transfer | Not needed - use `value` field instead | :::info Plain swaps are `sendIntent` calls with `tokenRequests` and an empty `calls` array. If the output token must be consumed by an app action, include the real target-chain calldata in `calls`. ::: :::tip Think of `tokenRequests` and `calls` as separate layers: `tokenRequests` say "deliver 100 USDC on Base"; `calls` say "now call this contract." A plain swap uses only the first layer. App workflows such as payments, deposits, approvals, and marketplace swaps need both layers, and the calls must be real calldata rather than placeholders. ::: ### How It Works 1. Specify target-chain tokens with `tokenRequests`. 2. The orchestrator checks available balances. 3. It prepares funding for the requested tokens. 4. The user approves the intent. 5. Tokens are delivered before the calls execute atomically. ### Interface ```tsx import type { Address } from 'viem'; interface TokenRequest { token: Address; // Token contract address on target chain amount: bigint; // Amount in base units (use parseUnits) } ``` ### Example: ERC20 Transfer When sending USDC, tell the orchestrator you need USDC: ```tsx import { encodeFunctionData, parseUnits } from 'viem'; const USDC_BASE = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913'; const amount = parseUnits('100', 6); // 100 USDC const transferData = encodeFunctionData({ abi: erc20Abi, functionName: 'transfer', args: [recipientAddress, amount], }); const result = await client.sendIntent({ accountAddress, targetChain: 8453, // Base calls: [{ to: USDC_BASE, data: transferData, label: 'Send USDC', sublabel: '100 USDC', }], tokenRequests: [{ token: USDC_BASE, amount: amount, }], }); ``` The orchestrator can fund the transfer from eligible assets on other chains before executing it on Base. ### Using with EIP-1193 Provider The `tokenRequests` parameter also works with [`eth_sendTransaction`](/rpc/eth-send-transaction) and [`wallet_sendCalls`](/rpc/wallet-send-calls): ```tsx import { createOneAuthProvider } from '@rhinestone/1auth'; const provider = createOneAuthProvider({ client, chainId: 84532 }); // Single transaction with tokenRequests await provider.request({ method: 'eth_sendTransaction', params: [{ to: USDC_ADDRESS, data: transferData, tokenRequests: [{ token: USDC_ADDRESS, amount }], }], }); // Batch calls with tokenRequests await provider.request({ method: 'wallet_sendCalls', params: [{ chainId: 84532, calls: [ { to: USDC_ADDRESS, data: transfer1Data }, { to: USDC_ADDRESS, data: transfer2Data }, ], tokenRequests: [{ token: USDC_ADDRESS, amount: totalAmount }], }], }); ``` ### Constraining Source Assets Use `sourceAssets` to limit which tokens the orchestrator can use as input. Entries are ERC-20 addresses; token symbols are not accepted: ```tsx const result = await client.sendIntent({ accountAddress, targetChain: 8453, calls: [{ to: USDC_BASE, data: transferData }], tokenRequests: [{ token: USDC_BASE, amount }], sourceAssets: [USDC_BASE], // Only use this token as input }); ``` Without `sourceAssets`, the orchestrator can select from available balances. ### Usage in Components #### PayButton ```tsx Pay 100 USDC ``` See [PayButton](/sdk/pay-button) for more details. ## Troubleshooting Start with the observed symptom. For API-specific error shapes and diagnostic fields, see [Error Codes & Diagnostics](/guides/error-handling). ### Capture diagnostics first Log the code and normalized details on every failure path: ```ts const result = await client.sendIntent({ accountAddress, targetChain: 8453, calls }) if (!result.success) { console.error('1auth failed', { code: result.error?.code, message: result.error?.message, providerCode: result.error?.details?.providerCode, traceId: result.error?.details?.traceId, simulationUrls: result.error?.details?.simulationUrls, }) } ``` Enable telemetry for support correlation. The SDK forwards one `operationId` per operation to the dialog and 1auth API: ```ts const client = new OneAuthClient({ clientId: 'my-app', telemetry: { onEvent: (event) => { console.debug('[1auth]', event.name, event.operationId, event.outcome) }, }, }) ``` :::tip The dialog logs at `warn` and above in production. To see its full debug output, open DevTools, select the `passkey.1auth.app` frame, and run `localStorage.setItem('1auth:console-log-level', 'debug')`. Remove the key to restore the default. ::: ### Setup and local development #### The passkey prompt never appears on `http://localhost` WebAuthn requires a [secure context](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts), and the hosted provider rejects non-HTTPS app origins. Plain `http://localhost` works only with a development-mode provider you run yourself. Serve the app over HTTPS on a real hostname. `tailscale cert` and [Caddy](https://caddyserver.com/) issue locally trusted certificates. A self-signed certificate must be installed in the OS trust store; clicking through Chrome's interstitial is not enough. #### Requests to the 1auth API fail with a CORS error 1auth does not reject unknown origins at CORS. Check the failing network request for a `providerUrl` typo, CSP omission, or proxy stripping headers before changing app registration. #### The dialog shows a warning icon and asks users to confirm they trust the site Your origin is `EXTERNAL`, which adds a warning and trust confirmation. 1auth returns `TRUSTED`, `REGISTERED`, or `EXTERNAL` in `X-Origin-Tier`; `GET /api/cors/check` reports it directly. To become `REGISTERED`, verify the exact scheme and host. `https://app.example.com` and `https://www.app.example.com` are distinct origins and both need registration. ### Sign-in and passkeys #### The user dismissed the system prompt `USER_CANCELLED` or `USER_REJECTED` is deliberate. Preserve form state and let the user retry; do not auto-retry, because browsers may suppress another unprompted WebAuthn call. #### The browser reports `NotAllowedError` and no passkey was created The ceremony ended before credential creation. Common causes: * The user dismissed the picker, or the ceremony timed out. * A password-manager extension claimed the prompt and the user rejected *its* dialog. On Chrome this cancels the entire WebAuthn request rather than falling back to the platform authenticator — the user must retry and choose the device's built-in passkey. * The call was not close enough to the trusted click. Anything awaited between the click and the ceremony — a fetch, a quote refresh, a dynamic import — can cost the user-activation window. If it reproduces with one passkey provider but not another on the same browser and OS, report the provider; that distinction is actionable. #### Registration fails with "Passkey was created by \ instead of your device" `PASSWORD_MANAGER_CREDENTIAL`. The deployment is configured to require a platform authenticator, and the credential came from a password manager's vault instead. The user should dismiss the password-manager prompt and pick the device's built-in passkey (Touch ID, Windows Hello, Android screen lock). #### The user has a passkey but 1auth says there is no account Accounts are namespaced by origin: the same passkey on another origin resolves to another user and smart account. Check the registration/sign-in origin and that `rpId` has not changed; see [Per-App Accounts](/architecture/accounts). #### The account address changed unexpectedly An address is derived from the app's account namespace, so it moves whenever that namespace moves. Check `webauthn.rpId` first, then whether the app moved to a new hostname. Each of those selects a different passkey, signer, and account, and 1auth does not migrate accounts between namespaces. See [App-origin passkeys](/guides/app-origin-passkeys). #### `WEBAUTHN_CONTEXT_MISMATCH` The WebAuthn context at verification did not match the context the challenge was issued under — origin, RP ID, expected origin, or app identity changed mid-ceremony. Check for: * A client that changes `clientId` or `webauthn.rpId` between starting and completing a flow. * A proxy or CDN rewriting `Origin` / `Referer` on the request to the 1auth API. * A ceremony started on one origin and completed on another, for example after a redirect between `example.com` and `www.example.com`. Challenges are short-lived, so a stale one also surfaces here. Restart the flow before investigating further. #### `APP_ORIGIN_SESSION_REQUIRED` The call needs an authenticated app-origin session and there isn't one. Call `client.authenticate()` first, and use `client.getSession()` to check state before issuing signing or intent calls. Register `onDisconnect` on the client so your app clears in-memory auth state when the dialog invalidates a session: ```ts const client = new OneAuthClient({ clientId: 'my-app', onDisconnect: () => setAccount(null), }) ``` ### Signing and transactions #### `PREPARE_FAILED` Quoting or pre-sign simulation rejected the intent. Read `error.details.reason` and `error.details.candidateErrors` before changing anything — the message names the constraint. A `No viable route found` message almost always means the account has no balance to source from, not that the route is unsupported. Fund the account, or send a sponsored intent with no token requirements to verify the rest of the integration first. #### `INVALID_SIGNATURE` On-chain simulation rejected the passkey signature: the account signer diverged from this credential. Retrying with the same passkey will fail; use [account recovery](/architecture/lost-passkey). #### `EXECUTE_FAILED` Submission or execution failed downstream. Log `providerCode`, `traceId`, and `simulationUrls`; they identify the execution and its revert. Never expose these developer diagnostics to users. #### `HASH_TIMEOUT` or `STATUS_TIMEOUT` The intent was accepted but not confirmed in the wait window. **It has not necessarily failed.** Keep `result.intentId`, unblock the UI, and poll `client.getIntentStatus(intentId)`; treating timeout as failure causes duplicates. #### `NETWORK_ERROR` SDK-to-1auth transport failure. Retry after connectivity returns; if persistent, check `providerUrl` requests for corporate proxy, ad-blocker, or CSP blocking. ### Sponsorship and app credentials Every user intent carries the app's JWT, so a sponsorship misconfiguration surfaces as an intent failure rather than a configuration warning. See [Fee Sponsorship](/guides/fee-sponsorship) for the full setup. #### `MISSING_APP_CREDENTIALS` No sponsorship is configured on the client. Pass `sponsorship` to the `OneAuthClient` constructor — either the callback pair or the URL pair — before sending intents or querying assets. #### `SPONSORSHIP_FETCH_FAILED` Sponsorship is configured, but fetching a token failed. **Read the error message before anything else** — when your endpoint returns a JSON `error` or `message` field, the SDK folds it into the thrown error, so the server's own reason (missing env var, bad JWK, expired session) is already there. If the message is unhelpful, call the endpoints directly: * The access-token endpoint must return `{ "token": "..." }`. * The extension-token endpoint must accept `POST` with `{ "intentOp": "" }` and return `{ "token": "..." }`. The usual causes are a missing `RHINESTONE_JWT_PRIVATE_KEY` on the server, a private key pasted as a multi-line JSON file rather than a single-line JSON string, or same-origin `/api/sponsorship/*` URLs configured in an app that has no server to host them. #### `APP_JWT_REQUIRED` The 1auth API received the request without a usable app access token. The token was missing, expired, or minted with credentials that do not match the app. Mint a fresh token and confirm `RHINESTONE_INTEGRATOR_ID`, `RHINESTONE_PROJECT_ID`, `RHINESTONE_APP_ID`, and `RHINESTONE_KEY_ID` all belong to the same app. #### `sendBatchIntent()` returned `success: false` with nothing to go on `SendBatchIntentResult` reports top-level failures through `errorCode` (a machine-readable string) and `error` (a message) — not a nested `error.code` object like the single-intent path. Read both: ```ts const batch = await client.sendBatchIntent({ accountAddress, intents }) if (!batch.success) { console.error('1auth batch failed', { errorCode: batch.errorCode, error: batch.error, results: batch.results, }) } ``` **Several failure paths populate neither field**, returning only `success: false` with an empty `results` array — including a failed access-token fetch, a missing `accountAddress`, an empty `intents` array, and a dialog closed before it was ready. For those, the reason exists only in the SDK telemetry event, which is the practical reason to wire up `telemetry.onEvent` before debugging batches: ```ts telemetry: { onEvent: (event) => { if (event.outcome === 'failure' || event.outcome === 'cancelled') { console.error('[1auth]', event.name, event.errorCode, event.errorMessage) } }, } ``` `batch.prepare.failed` carries `SPONSORSHIP_FETCH_FAILED` or `MISSING_APP_CREDENTIALS`; `dialog.cancelled` carries `USER_CANCELLED`. ### Contacting support Include all of these — each one narrows the search from thousands of ceremonies to one: | Field | Where to get it | | --------------------------------- | ------------------------------------------------------------------------------------------- | | `clientId` | Your client configuration | | App origin | The exact scheme and host the user was on | | SDK `operationId` | The telemetry event's `operationId` — not `result.operationId`, which is the orchestrator's | | `traceId` | `error.details.traceId` | | `providerCode` | `error.details.providerCode` | | Intent ID | `result.intentId`, for intent failures | | Account address | The address passed to the failing call | | Approximate timestamp | With time zone | | Browser, OS, and passkey provider | e.g. "Chrome 131 / macOS / iCloud Keychain" | The browser and passkey provider matter more than they look: a large share of WebAuthn failures are specific to one provider on one platform, and naming them lets us go straight to the matching telemetry. ## Integrate into viem / wagmi Use 1auth as an EIP-1193 wallet provider with viem, wagmi, ethers, or another compatible library. ### Setup :::code-group ```bash [npm] npm install @rhinestone/1auth ``` ```bash [yarn] yarn add @rhinestone/1auth ``` ```bash [pnpm] pnpm add @rhinestone/1auth ``` ::: ```typescript import { OneAuthClient, createOneAuthProvider } from '@rhinestone/1auth'; const client = new OneAuthClient({ providerUrl: 'https://passkey.1auth.app', clientId: 'my-app', }); const provider = createOneAuthProvider({ client, chainId: 8453 }); ``` ### With viem ```typescript import { createWalletClient, custom } from 'viem'; import { base } from 'viem/chains'; const walletClient = createWalletClient({ chain: base, transport: custom(provider), }); // Connect const [address] = await walletClient.requestAddresses(); // Send transaction const hash = await walletClient.sendTransaction({ to: '0x...', value: parseEther('0.01'), }); ``` ### With wagmi ```typescript import { createConfig, http } from 'wagmi'; import { base } from 'wagmi/chains'; import { oneAuth } from '@rhinestone/1auth/wagmi'; const config = createConfig({ chains: [base], connectors: [oneAuth({ client, chainId: base.id })], transports: { [base.id]: http() }, }); ``` Use standard wagmi hooks: ```tsx import { useConnect, useAccount } from 'wagmi'; function App() { const { connect, connectors } = useConnect(); const { address, isConnected } = useAccount(); if (!isConnected) { return ; } return
Connected: {address}
; } ``` ### Supported Methods | Method | Description | | ------------------------ | ----------------------------- | | `eth_requestAccounts` | Connect and get address | | `eth_accounts` | Get connected address | | `personal_sign` | Sign message (EIP-191) | | `eth_signTypedData_v4` | Sign typed data (EIP-712) | | `eth_sendTransaction` | Send transaction | | `wallet_sendCalls` | Batch transactions (EIP-5792) | | `wallet_getCallsStatus` | Check batch status | | `wallet_getCapabilities` | Query wallet capabilities | ### Events ```typescript provider.on('accountsChanged', (accounts) => console.log('Account:', accounts[0])); provider.on('chainChanged', (chainId) => console.log('Chain:', chainId)); provider.on('disconnect', () => console.log('Disconnected')); ``` See [SDK Reference](/sdk). ## Swap A swap intent requests an output token and amount on the target chain. For a plain swap, send no calldata: ```ts calls: [] ``` Do not add a dummy token transfer, `{ data: '0x' }`, or a self-transfer to make the intent look like a transaction. Placeholder calldata changes the review UI and can cause the quoter to reject the route as unsupported destination calldata. :::steps #### Install the SDK ```bash npm install @rhinestone/1auth viem ``` #### Create client ```ts [client.ts] import { OneAuthClient } from '@rhinestone/1auth' export const client = new OneAuthClient({ providerUrl: 'https://passkey.1auth.app', clientId: 'my-app', }) ``` #### Send a swap intent ```ts import { parseUnits } from 'viem' const usdcOnBase = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913' const result = await client.sendIntent({ accountAddress: '0x...', targetChain: 8453, calls: [], tokenRequests: [{ token: usdcOnBase, amount: parseUnits('0.1', 6), }], sourceAssets: ['0x0000000000000000000000000000000000000000'], }) if (result.success) { console.log('Swap intent:', result.intentId) } ``` #### Done The orchestrator routes the input asset into the requested output token. ::: ### Cross-chain swap Use the same shape for cross-chain routes. Constrain the source chain when your source asset address only exists on one chain: ```ts import { parseUnits } from 'viem' const BASE_SEPOLIA = 84532 const ARB_SEPOLIA = 421614 const mUSDOnBaseSepolia = '0x2f6fdE5E2AeAB6335d8f978B4d8B2a9c1129AcFb' const usdcOnArbitrumSepolia = '0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d' await client.sendIntent({ accountAddress, targetChain: ARB_SEPOLIA, calls: [], tokenRequests: [{ token: usdcOnArbitrumSepolia, amount: parseUnits('0.1', 6), }], sourceAssets: [mUSDOnBaseSepolia], sourceChainId: BASE_SEPOLIA, }) ``` The route delivers the requested USDC on the target chain. ### Token requests vs calls Use this distinction when deciding what to send: | Intent shape | Use it for | What to send | | -------------------------------- | ----------------------------------------- | ----------------------------------------------------------------- | | Plain swap | User receives an output token | `sendIntent({ calls: [], tokenRequests })` | | ERC20 payment | User sends tokens to a recipient | Real `ERC20.transfer(...)` calldata plus matching `tokenRequests` | | Contract action requiring tokens | Contract consumes tokens during execution | Real app calldata plus matching `tokenRequests` | `tokenRequests` specify the target-chain output; `calls` specify the contract action that consumes it. Plain swaps need only `tokenRequests`; payments and contract actions need both. ### Funding target-chain execution When the delivered token must be consumed by a contract call, include the real call and the token request together: ```ts import { encodeFunctionData, parseUnits } from 'viem' const USDC_BASE = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913' const amount = parseUnits('100', 6) const transferData = encodeFunctionData({ abi: erc20Abi, functionName: 'transfer', args: [recipientAddress, amount], }) await client.sendIntent({ accountAddress, targetChain: 8453, calls: [{ to: USDC_BASE, data: transferData, label: 'Send USDC', sublabel: '100 USDC', }], tokenRequests: [{ token: USDC_BASE, amount, }], }) ``` ### Constraining source assets Omit `sourceAssets` to use available balances, or pass it with optional `sourceChainId` to constrain the input side: ```ts const USDC_BASE = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913' await client.sendIntent({ accountAddress, targetChain: 8453, calls: [], tokenRequests: [{ token: USDC_BASE, amount: parseUnits('100', 6), }], sourceAssets: [ '0x0000000000000000000000000000000000000000', // ETH '0x4200000000000000000000000000000000000006', // WETH ], }) ``` Use token addresses for both output requests and source-asset constraints. ### Tracking status `sendIntent` returns an intent id. Pass `waitForHash: true` when you need the transaction hash before the promise resolves: ```ts const USDC_BASE = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913' const result = await client.sendIntent({ accountAddress, targetChain: 8453, calls: [], tokenRequests: [{ token: USDC_BASE, amount: parseUnits('0.1', 6), }], waitForHash: true, closeOn: 'completed', }) if (result.success) { console.log(result.intentId) console.log(result.transactionHash) } ``` Poll later with `getIntentStatus(result.intentId)`. ### Next steps * [Token Requests](/guides/crosschain/token-requests) - Request specific token outputs * [Batch Transactions](/guides/batch-transactions) - Queue multiple operations ## Token Requests `tokenRequests` declares the token outputs required on the target chain. The orchestrator routes available source assets to satisfy them. ### Using token requests Add `tokenRequests` to your `sendCalls` to specify what tokens you need: :::code-group ```tsx [Example.tsx] import { useSendCalls } from 'wagmi' import { parseUnits } from 'viem' const USDC_BASE = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913' export function BuyWithUSDC() { const { sendCalls, isPending } = useSendCalls() const handlePurchase = () => { sendCalls({ calls: [{ to: '0x...', // Your contract data: '0x...', // Purchase calldata }], chainId: 8453, // Execute on Base tokenRequests: [ // [!code ++] { // [!code ++] token: USDC_BASE, // [!code ++] amount: parseUnits('50', 6), // 50 USDC // [!code ++] }, // [!code ++] ], // [!code ++] }) } return ( ) } ``` ::: ### How it works 1. Declare the target-chain token outputs. 2. The orchestrator evaluates available balances. 3. It prepares funding and token delivery. 4. The requested tokens arrive before the calls execute; funding and calls succeed or fail together. ### TokenRequest object | Field | Type | Description | | -------- | -------- | ---------------------------------------------------------------- | | `token` | `string` | ERC-20 token contract address on the target chain | | `amount` | `bigint` | Amount in base units (e.g., `parseUnits('100', 6)` for 100 USDC) | ### Multiple token requests Request multiple target-chain tokens in one intent: ```tsx sendCalls({ calls: [{ to: '0x...', data: '0x...' }], chainId: 8453, tokenRequests: [ { token: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913', // USDC amount: parseUnits('100', 6), }, { token: '0x4200000000000000000000000000000000000006', // WETH amount: parseUnits('0.05', 18), }, ], }) ``` ### Common use cases #### E-commerce checkout User wants to buy an item priced in USDC, but only has ETH on mainnet: ```tsx sendCalls({ calls: [{ to: SHOP_CONTRACT, data: encodeFunctionData({ abi: shopAbi, functionName: 'purchase', args: [itemId], }), }], chainId: 8453, // Shop is on Base tokenRequests: [{ token: USDC_BASE, amount: parseUnits('29.99', 6), // Item price }], }) ``` #### DeFi interactions Provide liquidity with tokens from any chain: ```tsx sendCalls({ calls: [{ to: LP_CONTRACT, data: encodeFunctionData({ abi: lpAbi, functionName: 'addLiquidity', args: [amount0, amount1], }), }], chainId: 42161, // Arbitrum tokenRequests: [ { token: USDC_ARB, amount: parseUnits('1000', 6) }, { token: WETH_ARB, amount: parseUnits('0.5', 18) }, ], }) ``` #### NFT minting Mint an NFT with payment in any token: ```tsx sendCalls({ calls: [{ to: NFT_CONTRACT, data: encodeFunctionData({ abi: nftAbi, functionName: 'mint', args: [tokenId], }), }], chainId: 8453, tokenRequests: [{ token: USDC_BASE, amount: parseUnits('0.5', 6), // Mint price }], }) ``` ### Next steps * [Crosschain](/guides/crosschain) - Back to crosschain overview * [Batch Transactions](/guides/batch-transactions) - Combine multiple operations ## Per-App Accounts A user's smart account address is derived from your app's account namespace. The same person signing up on two different 1auth apps gets **two different accounts** — separate addresses, separate balances, separate recovery setups. This is deliberate. Accounts are isolated by the app that created them: your app only ever sees the accounts in its own namespace, and a passkey registered on another app cannot sign in to yours. ### What "one account" means Two claims are easy to confuse: * **One account across chains** — true. A 1auth account has the same address on every supported EVM chain, one unified balance, and executes anywhere. That is [chain abstraction](/architecture#chain-abstraction). * **One account across apps** — not true. Each app gets its own account for the same user. ### What this means for your integration * **Account management lives in your app.** Integrations provide their own account-management UI. There is no central 1auth dashboard listing a user's accounts across apps — the architecture has no single account to show. * **Recovery is per app.** Guardians a user sets up in your app recover your app's account only. See [Lost Passkey Recovery](/architecture/lost-passkey). * **Funding is per app.** Deposits go to the address your app reports; funds in an account created by another app are not reachable from yours. * **Users authenticate per app.** Signing in to one 1auth app does not sign a user in to another, and each app's sign-up registers its own passkey. ### Your namespace is part of your configuration The namespace is `https://` — the RP ID hostname, with the port excluded. Anything that changes the namespace changes your users' addresses: | | | | ------------------------------------------------------- | ------------------ | | `https://app.example.com` vs `https://beta.example.com` | different accounts | | `https://example.com` vs `https://www.example.com` | different accounts | | `http://localhost:3000` vs `http://localhost:3001` | same account | So staging and production hold separate accounts, which is usually what you want. And **moving your app to a new domain moves your users to new, empty accounts** — treat the production hostname as fixed once you have users, and talk to us before changing it. ### Native apps A native app is its own namespace by default and does not see your web app's accounts. Sharing is supported but explicit: we register your native app's identifier against the web origin whose accounts it may use, so native and web resolve to the same accounts. Contact us to set this up. ## Lost Passkey Recovery If a user loses their phone, gets a new laptop, or their passkey simply stops working, they can recover their account through **guardians** — trusted backup signers that can authorize adding a new passkey. ### Guardians A guardian is someone (or something) that can vouch for the account owner during recovery. 1auth supports two types: * **Google account** — The user links their Google account during setup. During recovery, they sign in with Google to prove their identity. This is the recommended default. * **Personal backup** — The user creates a passphrase-based backup key. The passphrase never leaves the browser — it's used locally to derive a signing key. This works fully offline, but the user must remember or securely store the passphrase. Both guardians can be set up together with a threshold: require **one** (either guardian can authorize recovery) or **both** (both must approve). Most users should use a threshold of one for simplicity. ### Setting Up Recovery Users set up recovery directly in the 1auth dialog — the same popup they use to sign in and approve transactions. The setup flow walks them through three steps: 1. **Link a Google account** — Sign in with Google to register it as an external guardian. This binds the user's Google identity to the account on-chain. 2. **Optional personal backup** — Create a passphrase-based backup key, or connect an external wallet as a second guardian 3. **Confirm with biometrics** — Approve the guardian configuration with Face ID, Touch ID, or another authenticator. The setup is deployed on-chain across all supported chains. Once configured, the user's account can be recovered even if their original passkey device is completely lost. Recovery is scoped to the account in your app — guardians configured in one app do not recover a user's account in another. See [Per-App Accounts](/architecture/accounts). ### Recovering an Account When a user needs to recover, they open the recovery flow from any app that integrates 1auth: 1. **Identify their account** — Enter their account address or username. The system looks up the guardian configuration on-chain. 2. **Register a new passkey** — Create a new passkey on their current device using Face ID, Touch ID, or another authenticator 3. **Prove their identity** — Sign in with Google (or enter their passphrase) to authenticate with the guardian. The guardian verifies this against the identity linked during setup. 4. **Automatic execution** — The recovery transaction is submitted across all chains where the account is deployed. Once confirmed, the user can sign in with their new passkey immediately. The entire process takes a few minutes. No funds are at risk during recovery — the account remains secure and unchanged until the recovery transaction completes. ### For Developers Use `client.setupRecovery()` and your own account-management UI to let users configure recovery. If a user has lost their passkey and needs to recover, the recovery flow is accessible from the 1auth login dialog — users click "Recover" to start the process. No additional SDK integration is needed. ## Recovery With traditional authentication, losing access usually means losing your account. Password resets depend on email providers. Seed phrases, once lost, are gone forever. 1auth takes a different approach. Every 1auth account is a smart contract on the blockchain. The account's rules — who can sign, who can authorize recovery — are stored on-chain, not in any single company's database. This means recovery can work through multiple independent paths, and no single point of failure can permanently lock a user out. ### Two Recovery Scenarios Recovery in 1auth is designed around two fundamentally different situations: #### The user loses their passkey A phone breaks, a laptop is stolen, or a passkey simply stops working. The user is fine — they just need a way to prove who they are and register a new passkey on a new device. This is handled by **guardians**: trusted signers that the user sets up in advance (like a linked Google account) that can vouch for their identity and authorize adding a new passkey. [Learn how lost passkey recovery works](/architecture/lost-passkey) #### The service goes offline The 1auth service itself becomes unavailable — temporarily or permanently. In this case, the user still has their passkey, but the infrastructure they normally interact with is gone. Because the account and its recovery configuration live entirely on-chain, **independent signers** that operate outside of 1auth can step in. The user proves their identity directly to these signers, who authorize recovery by reading verification data straight from the blockchain. [Learn how trustless recovery works](/architecture/trustless-recovery) ### The Underlying Principle Both scenarios share the same design principle: the user's account is defined by on-chain state, not by any service's availability. Guardians, identity commitments, and signer configurations are all stored in the smart contract. Any authorized party — whether it's the 1auth backend, an independent signer, or a decentralized network — can read that state and help the user recover, as long as the user can prove they are who they say they are. ## Security Most wallet and authentication products ask you to trust them: trust their servers, trust their key management, trust that a breach won't expose your users. 1auth takes a different approach — the architecture is designed so that trust isn't required. Private keys live in your users' devices, signing happens under their biometrics, and the rules that protect their accounts are enforced on-chain, not by anyone's servers. This chapter explains what makes 1auth secure, in the terms you'd use when comparing authentication providers. ### The short version Four guarantees define 1auth's security model: 1. **1auth cannot move your users' funds.** Private keys are generated and stored in the secure hardware of the user's own device. Our servers only ever see public keys — there is nothing to steal that could sign a transaction. 2. **Passkeys only work in their intended domain.** Passkeys are bound to the app's verified domain; a lookalike site on another domain cannot use the credential. 3. **Apps are quarantined from each other.** Every app gets its own isolated account. A malicious or compromised app cannot touch accounts, approvals, or session keys belonging to another app. 4. **No one can lock users out — including us.** Accounts are smart contracts on public blockchains with on-chain recovery. If 1auth disappeared tomorrow, users could still recover and use their accounts. ### How this compares to the alternatives | | Seed phrases | Browser extensions | Custodial / MPC / TEE | **1auth** | | ------------------------------------- | ------------ | ------------------ | --------------------- | --------- | | Key lives on user device | Yes | Yes | No | **Yes** | | Protected by secure hardware | No | No | Varies | **Yes** | | Provider can be breached for keys | N/A | N/A | **Yes** | **No** | | Phishing-resistant by design | No | No | No | **Yes** | | Users can recover access | No | No | Yes | **Yes** | | Works without extensions or downloads | Yes | No | Yes | **Yes** | The trade-offs that used to define this space — security *or* usability, self-custody *or* recovery — come from managing keys in software or on servers. Passkeys remove that trade-off: the key is hardware-protected *and* synced across the user's devices *and* recoverable, with no seed phrase to write down and no extension to install. For the full custody and regulatory analysis, see [Self-Custody & Compliance](/self-custody). ### Your users' keys never touch a server When a user signs up, their device generates a key pair inside its secure hardware — the Secure Enclave on Apple devices, the TPM on Windows, or a password manager like 1Password or Bitwarden. The private key never leaves that hardware. What reaches 1auth is the public key, which is registered as the signer on the user's smart account and verified on-chain for every transaction. Two consequences matter when you're evaluating providers: * **A breach of 1auth's servers yields nothing usable.** An attacker would find public keys, credential IDs, and account metadata — none of which can produce a signature. Compare this to custodial, MPC, or TEE-based wallets, where key material (or key shares) lives on infrastructure an attacker can target. * **Every sensitive action requires the user's biometrics.** Registration, transaction signing, message signing, and consent flows all require Face ID, Touch ID, Windows Hello, or a device PIN — verified on the device and enforced again server-side. There is no session token an attacker can steal that authorizes spending. ### Apps cannot cross security boundaries The passkey ceremony runs on the app's verified domain, and the credential works only in the app's configured RP namespace. 1auth verifies the app origin, RP ID, credential, account, prepared intent, and challenge before submitting anything on-chain. A different domain cannot reuse that passkey, even if it serves copied app code. 1auth derives app identity from browser-proven origin data rather than trusting what the app claims about itself. Accounts and permissions remain isolated per app. A compromised integration can abuse only the authority its own users granted; it cannot cross into another app's accounts, approvals, or session keys. ### Clear signing is available when your app needs it Blind signing is the SDK default. In these flows, the app is responsible for showing users complete and accurate transaction details before triggering the browser's passkey prompt. Integrations can opt into 1auth's clear-signing review UI with `experimental_clear_signing: true`. The dialog decodes the actual transaction and computes the signature from that payload, so the app cannot swap the transaction after review without invalidating the signature. Clear signing is an optional defense for high-risk actions, not a guarantee that every 1auth integration displays a 1auth review screen. See [Signing](/guides/signing). ### Every signature is single-use and short-lived Replay attacks — reusing a captured signature or approval — fail by construction: * **Challenges are single-use.** Each authentication or signing challenge can be consumed exactly once. Even a perfectly timed race between two copies of the same request produces exactly one success; a failed attempt still burns the challenge. * **Everything expires.** Challenges live for five minutes. Prepared transactions carry the quote's expiry and are rejected after it. Sponsorship tokens live for one hour (app identity) or five minutes (individual transaction grant). * **Signatures are bound to their payload.** The signature presented at execution must provably match the exact transaction being executed — identity, app, payload, expiry, and chain. A signature over transaction A cannot be attached to transaction B, even by someone who can see both. * **Batch transactions sign one commitment.** When a user approves multiple transactions at once, they sign a single cryptographic commitment covering all of them — removing or reordering any item breaks the batch. ### Apps are quarantined from each other Credentials are bound to the RP namespace that created them, and every app sees a **different account address** for the same user. The account is derived from the app's own namespace, cryptographically and deterministically, so a passkey created for one app cannot be used by another. This is a genuine differentiator, and it's worth understanding why it matters: * **Blast radius is contained per app.** If a user approves something risky on `sketchy-app.example`, their funds and approvals under `your-app.example` are untouched — they're a different account entirely. * **Session keys and grants stay with the app that earned them.** A permission granted to one app can only be used or revoked by that app. Learning another app's grant identifiers is useless. * **Identity remains private to the authentication flow.** Apps do not receive the user's email address or cross-app activity. Sessions are bound to the user, app, account, provider, and calling origin. ### Your users' passkeys can live on your domain Apps use **app-origin passkeys**: credentials created for your verified domain, with the WebAuthn ceremony running in your top-level app rather than on a shared provider domain. * **Phishing resistance stays with your brand.** A passkey bound to `wallet.yourapp.com` only works in that configured RP namespace. A lookalike site on another domain — even one serving copied 1auth integration code — cannot use it. * **Credential trust does not depend on 1auth's domain.** The passkey remains anchored to a domain you control. 1auth stays authoritative for identity, credential registration, account derivation, and intent verification, but the WebAuthn ceremony runs on your origin. * **The boundary is enforced, not taken on trust.** The RP ID and every exact server-authorized `rpOrigins` hostname must be verified app domains, and 1auth checks the selected exact ceremony origin, RP ID, app, account, credential, prepared intent, and challenge before execution. Sessions are short-lived tokens bound to the user, app, and account — not a shared 1auth cookie. Setup: [App-origin Passkeys](/guides/app-origin-passkeys). ### Session keys with hard, on-chain limits For automation — subscriptions, agents, background jobs — apps can ask users to grant a **scoped session key** instead of prompting for every transaction: * The user approves exact limits in the dialog: which contract, which function, which parameter values, how much value, how many uses, and until when. * Those limits are enforced **on-chain by the smart account's validator module** — not by 1auth and not by the app. A session key that drifts outside its policy simply fails on-chain. * 1auth never receives the session key itself — only its public address. The key lives wherever the app keeps its own signing infrastructure. Details: [Permissions](/guides/permissions) and [Headless Mode](/guides/headless-mode). ### Recovery without custodians Self-custody traditionally means "lose your key, lose everything." 1auth's recovery is designed so users get safety nets **without** handing anyone the power to move their funds: * **Passkeys sync across devices** via iCloud Keychain, Google Password Manager, or the user's password manager — a lost phone is usually a non-event. * **Guardians can authorize adding a new passkey — and nothing else.** A guardian (a linked Google account, or a passphrase-based backup key) can vouch for the user's identity during recovery. Guardians cannot sign transactions, cannot move funds, and cannot change spending rules. * **Apps can bring their own guardian.** A registered app can install an Ethereum guardian address it controls and provide its own recovery authorization flow. 1auth verifies the guardian against the app's registered configuration, installs only the public address, and never receives the guardian private key. This lets teams keep recovery within their own trust model instead of depending on a 1auth-operated recovery signer. * **Backup files are two-factor by construction.** The downloadable backup is encrypted with AES-256-GCM; the passphrase that unlocks it is stored separately by the user. Neither piece alone recovers anything. The recovery key itself is derived from the user's passkey on-device — it is never stored by 1auth. * **Recovery works even if 1auth doesn't.** Independent recovery signers read the account's guardian configuration directly from the blockchain and verify identity with the identity provider — no dependency on 1auth's infrastructure. See [Trustless Recovery](/architecture/trustless-recovery). * **The guardian signer is moving to a hardware enclave.** The service that signs recovery authorizations is being migrated to an AWS Nitro Enclave — a hardware-isolated Trusted Execution Environment: * In the enclave deployment, the guardian key will exist only inside the enclave's memory. It will be encrypted at rest, and the cloud key service will only decrypt it for the exact, hardware-measured image of the recovery code. No engineer — at 1auth or at the cloud provider — will be able to read it. * The verification policy will be *welded to the key*. Changing a single byte of the identity-checking code will change the hardware measurement, make the key undecryptable, and prevent signatures. The policy won't be bypassable on an operator-controlled server because there will be no operator-controlled server in the trust path. * Even an attacker with full cloud console access will only be able to restart or silence the service — not make it sign for the wrong identity. The Nitro Enclave build is in final production rollout. These enclave-specific guarantees apply once recovery signing runs there. ### Sponsorship is guarded like money If your app sponsors gas fees, the endpoints that mint sponsorship tokens are spending your budget — and 1auth's model treats them that way: * Sponsorship grants are **bound to one specific transaction** and expire in minutes, so a leaked token can't be reused against a different intent. * Your server decides **which transactions you'll sponsor** (chains, contracts, accounts, caps) before any token is signed — this check works even against scripted attackers that ignore browsers, cookies, and CORS. * Project-level budget caps in the Rhinestone dashboard bound the worst case if anything else goes wrong. Full setup: [Fee Sponsorship](/guides/fee-sponsorship). ### Questions to ask any auth provider When comparing 1auth against alternatives, these are the questions that separate architectural security from marketing: | Question | 1auth | | ---------------------------------------------- | -------------------------------------------------------------------------------------------------- | | Where do private keys live? | User's device hardware. Nowhere else. | | What does a server breach expose? | Public keys and metadata — nothing that can sign. | | Can the provider sign without the user? | No — every signature requires on-device biometrics. | | Can a lookalike domain use the user's passkey? | No — the credential is bound to the app's verified RP namespace. | | Can one app touch another app's accounts? | No — accounts are derived per app domain. | | Whose domain are passkeys bound to? | The app's verified domain. | | Who enforces session-key limits? | The blockchain, not the provider. | | Can recovery guardians move funds? | No — they can only authorize adding a new passkey. | | Who can access the recovery signing key? | The signer is moving to an attested hardware enclave, where no one will be able to access the key. | | What happens if the provider shuts down? | Users recover via independent signers reading on-chain state. | If a competitor's answer to any of these is "trust us," that's the difference. ### Your responsibilities as an integrator 1auth secures the authentication and signing layers; a few things remain yours: 1. **Serve your app over HTTPS** — passkeys require a secure context. 2. **Register your domains** in the developer portal so users skip the unknown-origin warning. 3. **Use clear signing for high-risk actions** — and when you blind-sign, present the full payload in your own UI first. 4. **Guard sponsorship endpoints like money** — authenticate callers, scope what you'll sponsor, and set a budget cap. 5. **Scope session keys narrowly** — exact functions, tight limits, short windows, and revoke when users disconnect. 6. **Verify signatures on your backend** for your own APIs, with a domain and timestamp in the signed message. 7. **Never ask users for secrets** — no flow should ever need a passkey, passphrase, or session private key. If one seems to, it's a bug. ### Related pages * [Why Passkeys](/passkey) — the technology behind the guarantees * [Self-Custody & Compliance](/self-custody) — custody analysis and regulatory framing * [Architecture](/architecture) — how the components fit together * [Recovery](/architecture/recovery) — guardian-based and trustless recovery * [Signing](/guides/signing) — blind signing and the review UI * [Fee Sponsorship](/guides/fee-sponsorship) — securing token-minting endpoints * [Permissions](/guides/permissions) — scoping session keys ## Trustless Recovery 1auth accounts are self-custodial smart contracts deployed on-chain. If the 1auth service goes offline — whether temporarily or permanently — users never lose access to their funds or their account. This page explains the safeguards that make this possible. ### Your Account Lives On-Chain When a user creates a 1auth account, a smart contract is deployed to the blockchain. This contract holds the user's assets and enforces who can authorize transactions. The 1auth service helps manage this account, but it does not control it — only the user's passkey (or their recovery guardians) can authorize changes. If 1auth becomes unavailable: * **Funds remain safe** — Assets are in the on-chain smart contract, not in any 1auth database * **Account state is unchanged** — The account's signers, guardians, and configuration are all stored on-chain * **No one can lock you out** — 1auth has no admin key or backdoor into user accounts ### Independent Recovery Signers To ensure recovery works without the 1auth backend, the guardian system uses **independent recovery signers** — services that run separately from 1auth and can authorize recovery on their own. When a user sets up recovery with their Google account, the linked guardian is an independent signing service. This service: * Runs on its own infrastructure, separate from 1auth * Reads the user's guardian configuration directly from the blockchain * Verifies the user's identity through Google sign-in * Authorizes recovery without contacting the 1auth backend at any point Because the signer reads all verification data from the blockchain and the identity provider directly, it has no dependency on 1auth being online. ### Lit Protocol: Decentralized Recovery :::note[Coming Soon] Lit Protocol integration is currently in development. Once live, it will provide a fully decentralized recovery path with no single point of failure. ::: For even stronger guarantees, 1auth will use [Lit Protocol](https://litprotocol.com) as a decentralized recovery signer. Instead of relying on a single signing service, the recovery key is split across a distributed network of nodes. How it works: * **No single point of failure** — The signing key is distributed across the Lit network. No single node holds the complete key. * **Threshold signing** — A minimum number of nodes must agree before a recovery signature is produced. Compromising a few nodes is not enough to forge a signature. * **Programmable conditions** — Recovery is only authorized when the user proves their identity (e.g., Google sign-in), enforced by the network itself * **Fully independent** — The Lit network operates independently of 1auth, its infrastructure, and its team This means that even in the worst case — 1auth shuts down entirely, its servers go offline, and its team is unreachable — users will be able to recover their accounts through the Lit network by proving their identity. ### The Self-Custody Guarantee Traditional wallets and auth providers create a dependency: if the service disappears, users may lose access. 1auth is built differently: | Scenario | What happens | | ----------------------------------- | ------------------------------------------------------------------------------ | | 1auth service goes down temporarily | Users can still transact via recovery signers or wait for service to return | | 1auth shuts down permanently | Users recover via independent signers and Lit Protocol | | A recovery signer goes offline | Other guardians (personal backup, Lit Protocol) can still authorize recovery | | User loses their passkey | Guardians authorize adding a new passkey — no dependency on any single service | The account is always the user's. The infrastructure around it is designed so that no single failure — technical or organizational — can lock them out.