# 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 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
### 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
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 (