# Accounts
The SDK of Tempo ID. Sign users in, and keep their session, their access key, and a Viem client that signs with it.
# Getting started \[Get started with Tempo ID in an app.]
## Overview
The Accounts SDK provides what an app needs to sign users in with Tempo ID, act onchain on [Tempo](https\://tempo.xyz), and call the Tempo API.
## Demo
The demo signs in through Tempo ID's dialog, and pays 1 OUSD on Tempo testnet with the sign-in's [access key](/docs/guides/access-keys), with no approval.
## Quick prompt
To add the flow of the demo to an app, paste this prompt into a coding agent.
```prompt
Read https://accounts.tempo.com/llms-full.txt. Then add Tempo ID sign-in to this app with the `accounts` package. Follow the "Getting started" steps of this app's platform.
```
## Walkthrough
Each tab builds the flow on one platform, on Tempo testnet.
### Web
The [`web`](https\://github.com/tempoxyz/accounts/tree/main/examples/web) example runs these steps in a React app.
::::steps
### Install the packages
:::code-group
```sh [npm]
npm install accounts react react-dom viem
```
```sh [pnpm]
pnpm add accounts react react-dom viem
```
```sh [bun]
bun add accounts react react-dom viem
```
:::
### Create the instance
Create one instance for the app with `Accounts.create` . Each sign-in requests an [access key](/docs/guides/access-keys) with these limits.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [react(), viem()],
})
```
### Sign the user in
`useSession` returns the session, and renders again when it changes. Without a session, `dialog.signIn` opens Tempo ID's sign-in in a dialog over the page.
:::code-group
```tsx [App.tsx]
import { accounts } from './tempo.config.js'
export function App() {
const { session } = accounts.useSession()
// [!code hl:start]
if (!session)
return (
accounts.dialog.signIn()} type="button">
Sign in with Tempo
)
// [!code hl:end]
return
Signed in as {session.user.email}
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [react(), viem()],
})
```
:::
### Send a payment
`pay` sends 1 OUSD from the user's Tempo Account. If the access key's limits hold the amount, the access key signs it, and the user approves nothing. Otherwise, Tempo ID's payment page asks the user to approve it.
:::code-group
```tsx [Send.tsx]
import { accounts } from './tempo.config.js'
export function Send() {
return (
{
// [!code hl:start]
const { transaction } = await accounts.pay({
amount: '1',
to: '0x000000000000000000000000000000000000dEaD',
token: 'ousd',
})
// [!code hl:end]
console.log(transaction)
}}
type="button"
>
Send 1 OUSD
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [react(), viem()],
})
```
:::
Render the button once the user signs in.
::::
### CLI
The [`cli`](https\://github.com/tempoxyz/accounts/tree/main/examples/cli) example runs these steps as the commands of one CLI.
::::steps
### Install the packages
:::code-group
```sh [npm]
npm install accounts viem
```
```sh [pnpm]
pnpm add accounts viem
```
```sh [bun]
bun add accounts viem
```
:::
### Create the instance
A CLI names its own client ID, `cli:` and a name, so it needs no registration. The instance saves the session to `~/.tempo/id/store.json`, which only the user can read.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { device, viem } from 'accounts/plugins'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for 7 days.
accessKey: () => ({
expiry: '7d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
clientId: 'cli:acme-example', // [!code hl]
plugins: [
device({
onCode: (code) =>
console.log(
`Open ${code.verificationUriComplete} and confirm the code ${code.userCode}.`,
),
}),
viem(),
],
})
```
### Sign the user in
The `device` plugin runs the OAuth device authorization grant. `device.signIn` passes a code to `onCode` , the user approves it in any browser, and the call returns the session.
:::code-group
```ts [login.ts]
import { accounts } from './tempo.config.js'
const { user } = await accounts.device.signIn() // [!code hl]
console.log(`Signed in as ${user.email}.`)
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { device, viem } from 'accounts/plugins'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for 7 days.
accessKey: () => ({
expiry: '7d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
clientId: 'cli:acme-example',
plugins: [
device({
onCode: (code) =>
console.log(
`Open ${code.verificationUriComplete} and confirm the code ${code.userCode}.`,
),
}),
viem(),
],
})
```
:::
### Send a payment
Each later run reads the session from the file, and the access key signs the transfer. `accounts.pay` resolves once the chain includes the transfer. Without a session, it throws `Accounts.SignedOutError` .
:::code-group
```ts [send.ts]
import { accounts } from './tempo.config.js'
const session = await accounts.session.get()
if (!session?.accessKey) throw new Error('Not signed in. Run `login`.')
// The access key acts for the user's Tempo Account.
console.log(`${session.user.email} ${session.accessKey.account}`)
const { transaction } = await accounts.pay({ // [!code hl]
amount: '1',
to: '0x000000000000000000000000000000000000dEaD',
token: 'ousd',
})
console.log(`Sent in ${transaction}.`)
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { device, viem } from 'accounts/plugins'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for 7 days.
accessKey: () => ({
expiry: '7d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
clientId: 'cli:acme-example',
plugins: [
device({
onCode: (code) =>
console.log(
`Open ${code.verificationUriComplete} and confirm the code ${code.userCode}.`,
),
}),
viem(),
],
})
```
:::
::::
### React Native
The [`mobile`](https\://github.com/tempoxyz/accounts/tree/main/examples/mobile) example runs these steps in an Expo app.
::::steps
### Install the packages
:::code-group
```sh [npm]
npm install accounts viem expo-secure-store expo-web-browser react-native-get-random-values
```
```sh [pnpm]
pnpm add accounts viem expo-secure-store expo-web-browser react-native-get-random-values
```
```sh [bun]
bun add accounts viem expo-secure-store expo-web-browser react-native-get-random-values
```
:::
### Set the scheme of the app
Tempo ID returns the user to the app through its custom scheme.
```json [app.json]
{
"expo": {
"scheme": "com.example.app"
}
}
```
A custom scheme needs a [registration](https\://github.com/tempoxyz/id/blob/main/docs/apps.md#registration) with Tempo ID, which issues the app's client ID and names its redirect URI.
### Configure Metro
Metro reads the TypeScript source of ox in place of its build, and the bundle fails. This resolver skips the source.
```js [metro.config.js]
const { getDefaultConfig } = require('expo/metro-config')
const config = getDefaultConfig(__dirname)
config.resolver.resolveRequest = (context, name, platform) =>
context.resolveRequest(
name.startsWith('ox/')
? {
...context,
sourceExts: context.sourceExts.filter((ext) => ext !== 'ts'),
}
: context,
name,
platform,
)
module.exports = config
```
The file is CommonJS, as Expo's own template is. Expo's base TypeScript config excludes it, so the type check skips it.
### Create the instance
The `expo` plugin opens Tempo ID in the system browser, and keeps the session in the device's secure store.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { expo } from 'accounts/expo'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
// The client ID of the app's registration.
clientId: 'example-mobile',
plugins: [
expo({ redirectUri: 'com.example.app:/callback' }), // [!code hl]
react(),
viem(),
],
})
```
### Sign the user in
`redirect.signIn` opens Tempo ID in an authentication sheet, and returns the session. `accounts.useSession` restores it after a restart of the app.
:::code-group
```tsx [App.tsx]
import { Button, Text } from 'react-native'
import { accounts } from './tempo.config.js'
export function App() {
const { session } = accounts.useSession()
// [!code hl:start]
if (!session?.accessKey)
return (
accounts.redirect.signIn()}
title="Sign in with Tempo"
/>
)
// [!code hl:end]
return (
Signed in as {session.user.email}, with the Tempo Account{' '}
{session.accessKey.account}
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { expo } from 'accounts/expo'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
// The client ID of the app's registration.
clientId: 'example-mobile',
plugins: [
expo({ redirectUri: 'com.example.app:/callback' }),
react(),
viem(),
],
})
```
:::
### Send a payment
The access key signs the transfer, so the user sees no prompt.
:::code-group
```tsx [Send.tsx]
import { Button } from 'react-native'
import { accounts } from './tempo.config.js'
export function Send() {
return (
{
// [!code hl:start]
const { transaction } = await accounts.pay({
amount: '1',
to: '0x000000000000000000000000000000000000dEaD',
token: 'ousd',
})
// [!code hl:end]
console.log(transaction)
}}
title="Send 1 OUSD"
/>
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { expo } from 'accounts/expo'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
// The client ID of the app's registration.
clientId: 'example-mobile',
plugins: [
expo({ redirectUri: 'com.example.app:/callback' }),
react(),
viem(),
],
})
```
:::
Render the button once the user signs in.
::::
### Backend
The server runs the sign-in through a redirect to Tempo ID, and keeps each session with its tokens and access key. The browser holds only a session ID, in an HTTP-only cookie, so the page needs no instance. The [`backend`](https\://github.com/tempoxyz/accounts/tree/main/examples/backend) example runs these steps in a Hono server.
::::steps
### Install the packages
:::code-group
```sh [npm]
npm install accounts hono viem
```
```sh [pnpm]
pnpm add accounts hono viem
```
```sh [bun]
bun add accounts hono viem
```
:::
### Create the instance
The server's instance keeps each session in its store, with the `backend` plugin. The `viem` plugin sends transactions with each session's access key. The app's origin, in `APP_URL`, is its client ID.
```ts [tempo.config.ts]
import { Accounts, Store } from 'accounts'
import { backend, viem } from 'accounts/plugins'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
clientId: process.env.APP_URL,
plugins: [backend({ store: Store.memory() }), viem()], // [!code hl]
})
```
:::note
`Store.memory` keeps sessions in the process, so a restart loses them. In production, use a store that each replica shares, such as `Store.postgres` or `Store.redis` .
:::
:::warning
Keep the store on the server. Each session holds a refresh token, and the private key of its access key.
:::
### Serve the sign-in routes
`accounts.handler` serves the sign-in routes under `/api/auth`. A deployed origin names the callback route in the `redirect_uris` of its [web app manifest](https\://github.com/tempoxyz/id/blob/main/docs/apps.md#origin-client-id).
:::code-group
```ts [server.ts]
import { Hono } from 'hono'
import { accounts } from './tempo.config.js'
const app = new Hono()
app.all('/api/*', (c) => accounts.handler.fetch(c.req.raw)) // [!code hl]
export default app
```
```ts [tempo.config.ts]
import { Accounts, Store } from 'accounts'
import { backend, viem } from 'accounts/plugins'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
clientId: process.env.APP_URL,
plugins: [backend({ store: Store.memory() }), viem()],
})
```
:::
| Route | Result |
| ------------------------ | --------------------------------------------------------------------------- |
| `GET /api/auth/login` | Starts a sign-in, and redirects the browser to Tempo ID |
| `GET /api/auth/callback` | Completes the sign-in, sets the session cookie, and redirects to `returnTo` |
| `POST /api/auth/logout` | Ends the session, and deletes the session cookie |
### Sign the user in
A link to the login route leaves the page for Tempo ID's sign-in. After the sign-in, the callback returns the browser to `returnTo` with the session cookie. `session.get` returns the session of the request's cookie, or `undefined`.
:::code-group
```ts [server.ts]
import { Hono } from 'hono'
import { html } from 'hono/html'
import { accounts } from './tempo.config.js'
const app = new Hono()
app.all('/api/*', (c) => accounts.handler.fetch(c.req.raw))
app.get('/', async (c) => {
// [!code hl:start]
const session = await accounts.session.get(c.req.raw)
if (session?.method !== 'tempo-id')
return c.html(
html`Sign in with Tempo `,
)
// [!code hl:end]
return c.html(html`Signed in as ${session.user.email}
`)
})
export default app
```
```ts [tempo.config.ts]
import { Accounts, Store } from 'accounts'
import { backend, viem } from 'accounts/plugins'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
clientId: process.env.APP_URL,
plugins: [backend({ store: Store.memory() }), viem()],
})
```
:::
### Send a payment
`pay` with `session` sends 1 OUSD with the access key of the request's session, so the user approves nothing. The server opens no payment page, so a payment above the access key's limits throws.
:::code-group
```ts [server.ts]
import { Hono } from 'hono'
import { csrf } from 'hono/csrf'
import { html } from 'hono/html'
import { accounts } from './tempo.config.js'
const app = new Hono()
app.all('/api/*', (c) => accounts.handler.fetch(c.req.raw))
// Another site cannot post the app's forms.
app.use(csrf())
app.get('/', async (c) => {
const session = await accounts.session.get(c.req.raw)
if (session?.method !== 'tempo-id')
return c.html(
html`Sign in with Tempo `,
)
return c.html(html`
Signed in as ${session.user.email}
`)
})
app.post('/pay', async (c) => {
const session = await accounts.session.get(c.req.raw)
if (session?.method !== 'tempo-id') return c.redirect('/')
// [!code hl:start]
const { transaction } = await accounts.pay({
amount: '1',
session,
to: '0x000000000000000000000000000000000000dEaD',
token: 'ousd',
})
// [!code hl:end]
return c.text(`Sent in ${transaction}.`)
})
export default app
```
```ts [tempo.config.ts]
import { Accounts, Store } from 'accounts'
import { backend, viem } from 'accounts/plugins'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
clientId: process.env.APP_URL,
plugins: [backend({ store: Store.memory() }), viem()],
})
```
:::
::::
## Examples
Each example is a small app that installs as it is.
The [`examples`](https\://github.com/tempoxyz/accounts/tree/main/examples) folder holds the others.
## Next steps
# Migration from v0 \[Replace each API of version 0 of the package with its API of version 1.]
Version 0 of `accounts` connects an app to Tempo Wallet through an EIP-1193 provider. The app sends RPC methods, such as `wallet_connect` and `eth_sendTransaction`, and Tempo Wallet's dialog signs each call that no access key covers.
Version 1 is the SDK of Tempo ID, an OAuth 2.0 and OpenID Connect provider. A sign-in returns a [session](/docs/guides/user-session) with the user, the tokens, and an [access key](/docs/guides/access-keys) that signs each transaction within the limits that the user approved. `Accounts.create` returns an instance in place of a provider, and plugins add its members.
[Notable changes](/docs/guides/migration#notable-changes) covers what affects most apps, and [Quick reference](/docs/guides/migration#quick-reference) lists each API of version 0. In each diff, removed lines are code of version 0, and added lines code of version 1.
## Installation
Viem is a peer dependency.
:::code-group
```sh [npm]
npm install accounts viem
```
```sh [pnpm]
pnpm add accounts viem
```
```sh [bun]
bun add accounts viem
```
:::
## Notable changes
### Instance creation
`Accounts.create` replaces `Provider.create`, and `chain` replaces `testnet`. A web app needs no registration, since the page's origin is its client ID. See [Instance](/docs/guides/migration#instance).
```ts [tempo.config.ts]
import { Provider, tempoWallet } from 'accounts' // [!code --]
import { Accounts } from 'accounts' // [!code ++]
import { dialog, viem } from 'accounts/plugins' // [!code ++]
const provider = Provider.create({ // [!code --]
adapter: tempoWallet(), // [!code --]
testnet: true, // [!code --]
}) // [!code --]
export const accounts = Accounts.create({ // [!code ++]
chain: 'testnet', // [!code ++]
plugins: [dialog(), viem()], // [!code ++]
}) // [!code ++]
```
### Sign-in plugins
A sign-in plugin replaces each adapter, and its `signIn` replaces `wallet_connect`. `dialog` shows Tempo ID's sign-in over the page, as `tempoWallet` showed Tempo Wallet. See [Sign-in](/docs/guides/migration#sign-in).
:::code-group
```ts [signIn.ts]
import { accounts } from './tempo.config.js' // [!code ++]
export async function signIn() {
const result = await provider.request({ method: 'wallet_connect' }) // [!code --]
const address = result.accounts[0]?.address // [!code --]
const session = await accounts.dialog.signIn() // [!code ++]
const address = session.accessKey?.account // [!code ++]
return address
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { dialog, viem } from 'accounts/plugins'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [dialog(), viem()],
})
```
:::
`session.accessKey.account` is the address of the Tempo Account that the access key acts for, not the access key's address. With the `accessKey` option set to `false`, a sign-in requests no access key, and `accounts.account.get()` reads the Tempo Account from Tempo ID.
:::code-group
```ts [account.ts]
import { accounts } from './tempo.config.js' // [!code ++]
export async function getAddress() { // [!code ++]
const account = await accounts.account.get() // [!code ++]
return account?.address // [!code ++]
} // [!code ++]
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { dialog, viem } from 'accounts/plugins'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [dialog(), viem()],
})
```
:::
### Sessions
One session, which `accounts.session` reads, replaces the accounts of `provider.store`. An instance does not read version 0's stored state, so each user signs in once after the upgrade. See [Session and storage](/docs/guides/migration#session-and-storage).
:::code-group
```ts [session.ts]
import { accounts } from './tempo.config.js' // [!code ++]
export async function watch(render: (address: string | undefined) => void) {
await provider.ready() // [!code --]
const [address] = await provider.request({ method: 'eth_accounts' }) // [!code --]
const session = await accounts.session.get() // [!code ++]
const address = session?.accessKey?.account // [!code ++]
render(address)
provider.on('accountsChanged', ([address]) => render(address)) // [!code --]
accounts.session.subscribe((session) => render(session?.accessKey?.account)) // [!code ++]
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { dialog, viem } from 'accounts/plugins'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [dialog(), viem()],
})
```
:::
### Access key requests
The app requests an access key at each sign-in with the `accessKey` option, which replaces `accessKey.authorize`. It takes a duration, a decimal limit, and a token symbol. See [Access keys](/docs/guides/migration#access-keys).
```ts [tempo.config.ts]
import { Expiry } from 'accounts' // [!code --]
import { Addresses } from 'viem/tempo' // [!code --]
import { Accounts } from 'accounts' // [!code ++]
import { dialog, viem } from 'accounts/plugins' // [!code ++]
const provider = Provider.create({ // [!code --]
accessKey: { // [!code --]
authorize: { // [!code --]
expiry: Expiry.days(1), // [!code --]
limits: [{ limit: 100_000_000n, token: Addresses.ousd }], // [!code --]
}, // [!code --]
}, // [!code --]
}) // [!code --]
export const accounts = Accounts.create({ // [!code ++]
accessKey: () => ({ // [!code ++]
expiry: '1d', // [!code ++]
limits: [{ limit: '100', token: 'ousd' }], // [!code ++]
}), // [!code ++]
chain: 'testnet', // [!code ++]
plugins: [dialog(), viem()], // [!code ++]
}) // [!code ++]
```
### Instance methods
A method of the instance replaces each RPC method. `accounts.pay` replaces `wallet_transfer`, with the same decimal amount, and the access key signs with no prompt. The `viem` plugin's actions take Viem's values, such as an amount in base units. See [RPC methods](/docs/guides/migration#rpc-methods).
:::code-group
```ts [send.ts]
import { Addresses } from 'viem/tempo'
import { accounts } from './tempo.config.js' // [!code ++]
const to = '0x000000000000000000000000000000000000dEaD'
export async function send() {
await provider.request({ // [!code --]
method: 'wallet_transfer', // [!code --]
params: [{ amount: '1', to, token: Addresses.ousd }], // [!code --]
}) // [!code --]
const { transaction } = await accounts.pay({ // [!code ++]
amount: '1', // [!code ++]
to, // [!code ++]
token: Addresses.ousd, // [!code ++]
}) // [!code ++]
return transaction // [!code ++]
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { dialog, viem } from 'accounts/plugins'
export const accounts = Accounts.create({
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [dialog(), viem()],
})
```
:::
### Wagmi connector
The `tempoId` connector of `accounts/wagmi` replaces `tempoWallet` of `wagmi/connectors`, and takes the options of `Accounts.create` . The hooks of Viem's actions replace `Hooks.wallet`, which sends Tempo Wallet's RPC methods. See [Wagmi](/docs/guides/migration#wagmi).
```ts
import { tempoId } from 'accounts/wagmi' // [!code ++]
import { createConfig, http } from 'wagmi'
import { tempoModerato } from 'wagmi/chains'
import { tempoWallet } from 'wagmi/connectors' // [!code --]
export const config = createConfig({
chains: [tempoModerato],
connectors: [tempoWallet()], // [!code --]
connectors: [ // [!code ++]
// The page's origin is a third-party client ID, whose connection needs an access key. // [!code ++]
tempoId({ accessKey: { expiry: '1d', limits: [{ limit: '100', token: 'ousd' }] } }), // [!code ++]
], // [!code ++]
transports: { [tempoModerato.id]: http() },
})
```
### Server plugins
One server instance replaces each `Handler` of `accounts/server`, and the `backend` plugin replaces `Handler.auth`. The backend holds the session and its access key, and the page holds only a cookie. See [Server](/docs/guides/migration#server).
```ts [server.ts]
import { Handler, Kv } from 'accounts/server' // [!code --]
import { Accounts, Store } from 'accounts' // [!code ++]
import { backend } from 'accounts/plugins' // [!code ++]
const auth = Handler.auth({ path: '/api/auth', store: Kv.memory() }) // [!code --]
const accounts = Accounts.create({ // [!code ++]
clientId: 'https://app.example', // [!code ++]
plugins: [backend({ store: Store.memory() })], // [!code ++]
}) // [!code ++]
export default {
fetch: (request: Request) => auth.fetch(request), // [!code --]
fetch: (request: Request) => accounts.handler.fetch(request), // [!code ++]
}
```
### Fee relay
The `relay` plugin replaces `Handler.relay`, and the `viem` plugin's `relay` option replaces `feePayer`. A relay is a JSON-RPC proxy whose fee payer co-signs each transaction.
Version 0's route checks no caller, and version 1's verifies each request's access token. See [Fee sponsorship](/docs/guides/migration#fee-sponsorship).
```ts [tempo.config.ts]
import { Accounts } from 'accounts' // [!code ++]
import { dialog, viem } from 'accounts/plugins' // [!code ++]
const provider = Provider.create({ // [!code --]
adapter: tempoWallet(), // [!code --]
feePayer: '/api/relay', // [!code --]
}) // [!code --]
export const accounts = Accounts.create({ // [!code ++]
chain: 'testnet', // [!code ++]
plugins: [dialog(), viem({ relay: '/api/relay' })], // [!code ++]
}) // [!code ++]
```
### Removed adapters
The `local` plugin replaces the `local` and `secp256k1` adapters\: it holds a secp256k1 owner key, and takes a version 0 file's account with `v0`. See [Local owner keys](/docs/guides/local). Version 1 has no replacement for the other adapters that hold an owner key in the app\: `webAuthn`, `turnkey`, and `privy`. See [Removed APIs](/docs/guides/migration#removed-apis).
### Removed surface
The root entry exports no EIP-1193 provider and no RPC schema, and only the wagmi connector's `getProvider` returns a provider. Version 1 has no wallet-side module, such as `Remote` and `Messenger`, since Tempo ID is the only wallet side, and no handler for a flow that Tempo ID serves. See [Removed APIs](/docs/guides/migration#removed-apis).
## Quick reference
Each export, option, member, and RPC method of version 0, in alphabetical order. An option belongs to `Provider.create` or to its adapter.
| Version 0 | Version 1 | Section |
| ----------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------- |
| `accessKey.authorize` (option) | `accessKey` | [Access keys](/docs/guides/migration#access-keys) |
| `accessKey.keystores` (option) | Removed. The instance creates and keeps the access key | [Access keys](/docs/guides/migration#access-keys) |
| `Adapter` | Removed. `Plugin.from` extends an instance | [Removed APIs](/docs/guides/migration#removed-apis) |
| `adapter` (option) | `plugins` | [Instance](/docs/guides/migration#instance) |
| `asyncStorage` | Removed. `expo` sets the store, or `Store.from` wraps one | [React Native](/docs/guides/migration#react-native) |
| `auth` (option) | `dialog({ backend: true })` | [Backend sessions](/docs/guides/migration#backend-sessions) |
| `authorizeAccessKey` (option) | `accessKey` | [Access keys](/docs/guides/migration#access-keys) |
| `chains` (option) | `chains` , as chain IDs | [Instance](/docs/guides/migration#instance) |
| `cli` | `device` | [CLI](/docs/guides/migration#cli) |
| `CliAuth` | Removed. Tempo ID serves the device grant | [Removed APIs](/docs/guides/migration#removed-apis) |
| `Connector` | `tempoId` | [Wagmi](/docs/guides/migration#wagmi) |
| `dangerous_secp256k1` | `local` | [Local owner keys](/docs/guides/local) |
| `deviceCode` | `device` | [CLI](/docs/guides/migration#cli) |
| `Dialog` | Removed. The `dialog` plugin owns the dialog | [Removed APIs](/docs/guides/migration#removed-apis) |
| `dialog` | `dialog` of `accounts/plugins` | [Sign-in](/docs/guides/migration#sign-in) |
| `eth_accounts` | `session.accessKey?.account` , or `accounts.account.get()` | [RPC methods](/docs/guides/migration#rpc-methods) |
| `eth_chainId` | `accounts.chain.get()` | [RPC methods](/docs/guides/migration#rpc-methods) |
| `eth_fillTransaction` | `accounts.fillTransaction` | [RPC methods](/docs/guides/migration#rpc-methods) |
| `eth_requestAccounts` | `accounts.dialog.signIn()` | [Sign-in](/docs/guides/migration#sign-in) |
| `eth_sendTransaction` | `accounts.sendTransaction` | [RPC methods](/docs/guides/migration#rpc-methods) |
| `eth_sendTransactionSync` | `accounts.sendTransactionSync` | [RPC methods](/docs/guides/migration#rpc-methods) |
| `eth_signTransaction` | `accounts.signTransaction` | [RPC methods](/docs/guides/migration#rpc-methods) |
| `eth_signTypedData_v4` | `accounts.signTypedData` | [RPC methods](/docs/guides/migration#rpc-methods) |
| `ExecutionError` | `ExecutionError` of `viem/tempo` | [Errors](/docs/guides/migration#errors) |
| `Expiry` | A duration, such as `'1d'`, or `Expiry` of `viem/tempo` | [Access keys](/docs/guides/migration#access-keys) |
| `feePayer` (option) | `viem({ relay })` | [Fee sponsorship](/docs/guides/migration#fee-sponsorship) |
| `getOrCreateMmkvEncryptionKey` | Removed | [React Native](/docs/guides/migration#react-native) |
| `Handler.auth` | `backend` | [Backend sessions](/docs/guides/migration#backend-sessions) |
| `Handler.codeAuth` | Removed. Tempo ID serves the device grant | [Removed APIs](/docs/guides/migration#removed-apis) |
| `Handler.compose` | `accounts.handler` | [Backend sessions](/docs/guides/migration#backend-sessions) |
| `Handler.deviceCode` | Removed. Tempo ID serves the device grant | [Removed APIs](/docs/guides/migration#removed-apis) |
| `Handler.exchange` | Removed. `accounts.dex` reads each quote | [Removed APIs](/docs/guides/migration#removed-apis) |
| `Handler.from` | `accounts.handler` | [Backend sessions](/docs/guides/migration#backend-sessions) |
| `Handler.oidcProvider` | Removed. Tempo ID issues each token | [Removed APIs](/docs/guides/migration#removed-apis) |
| `Handler.relay` | `relay` | [Fee sponsorship](/docs/guides/migration#fee-sponsorship) |
| `Handler.webAuthn` | Removed. Tempo ID runs each passkey ceremony | [Removed APIs](/docs/guides/migration#removed-apis) |
| `Handoff` | Removed. Version 1 has no phone handoff | [Removed APIs](/docs/guides/migration#removed-apis) |
| `handoff` (option) | Removed. Version 1 has no phone handoff | [Removed APIs](/docs/guides/migration#removed-apis) |
| `hc` | Removed. Import it from `hono/client` | [Removed APIs](/docs/guides/migration#removed-apis) |
| `Hooks.wallet.useDeposit` | `accounts.funding.open()` of an instance | [Wagmi](/docs/guides/migration#wagmi) |
| `Hooks.wallet.useSwap` | `Hooks.dex.useSellSync`, `Hooks.dex.useBuySync` | [Wagmi](/docs/guides/migration#wagmi) |
| `Hooks.wallet.useTransfer` | `Hooks.token.useTransferSync` | [Wagmi](/docs/guides/migration#wagmi) |
| `hydrationTimeout` (option) | Removed | [Session and storage](/docs/guides/migration#session-and-storage) |
| `icon`, `name`, `rdns`, `theme` (options) | Removed. Tempo ID names the app. The dialog follows the page's `color-scheme` | [Sign-in](/docs/guides/migration#sign-in) |
| `Identity` | Removed. The session holds the verified `user` | [Removed APIs](/docs/guides/migration#removed-apis) |
| `identity` (option) | Removed. The session holds the verified `user` | [Removed APIs](/docs/guides/migration#removed-apis) |
| `IntersectionObserver` | Removed. The `dialog` plugin reads the support of the browser | [Removed APIs](/docs/guides/migration#removed-apis) |
| `Keystore` | Removed. The instance creates and keeps the access key | [Access keys](/docs/guides/migration#access-keys) |
| `Kv.cloudflare` | `Store.workersKv` of `accounts/cloudflare` | [Stores](/docs/guides/migration#stores) |
| `Kv.durableObject` | `Sessions.durableObject` , or `Store.durableObject` , of `accounts/cloudflare` | [Stores](/docs/guides/migration#stores) |
| `Kv.from` | `Store.from` | [Stores](/docs/guides/migration#stores) |
| `Kv.memory` | `Store.memory` | [Stores](/docs/guides/migration#stores) |
| `Kv.NonceStorage` | `DurableObject.sessions` of `accounts/cloudflare` | [Stores](/docs/guides/migration#stores) |
| `local` | `local` | [Local owner keys](/docs/guides/local) |
| `Mach.fund` | `accounts.funding.open` | [RPC methods](/docs/guides/migration#rpc-methods) |
| `Mach.getFundingUrl` | Removed | [Removed APIs](/docs/guides/migration#removed-apis) |
| `Mach.token` | Removed. A limit names the token as `'mach'` | [Access keys](/docs/guides/migration#access-keys) |
| `maxAccounts` (option) | Removed. An instance holds one session | [Session and storage](/docs/guides/migration#session-and-storage) |
| `Messenger` | Removed | [Removed APIs](/docs/guides/migration#removed-apis) |
| `mobileWebAuth` | `expo` of `accounts/expo` | [React Native](/docs/guides/migration#react-native) |
| `Mount` | Removed | [Removed APIs](/docs/guides/migration#removed-apis) |
| `mpp` (option) | `mpp` of `accounts/mpp` | [MPP](/docs/guides/migration#mpp) |
| `openAuthSession` | `expo` of `accounts/expo` | [React Native](/docs/guides/migration#react-native) |
| `persistCredentials` (option) | Removed | [Session and storage](/docs/guides/migration#session-and-storage) |
| `personal_sign` | `accounts.signMessage` , or `accounts.dialog.signMessage` | [RPC methods](/docs/guides/migration#rpc-methods) |
| `postMessage` | Removed | [Removed APIs](/docs/guides/migration#removed-apis) |
| `privy` | Removed | [Removed APIs](/docs/guides/migration#removed-apis) |
| `PromptError` | Removed. `onCode` shows the code | [CLI](/docs/guides/migration#cli) |
| `provider.chains` | `accounts.chain.get()` , for the selected chain | [Instance](/docs/guides/migration#instance) |
| `Provider.create` | `Accounts.create` | [Instance](/docs/guides/migration#instance) |
| `provider.getAccessKeyStatus` | `session.accessKey` , `Session.expired` | [Access keys](/docs/guides/migration#access-keys) |
| `provider.getAccount` | Removed. No Viem action takes `account` | [Instance](/docs/guides/migration#instance) |
| `provider.getClient` | `accounts.viem` | [Instance](/docs/guides/migration#instance) |
| `provider.getMppxParameters` | `accounts.mpp()` , a payer | [MPP](/docs/guides/migration#mpp) |
| `provider.on` | `accounts.session.subscribe` , `accounts.chain.subscribe` | [Session and storage](/docs/guides/migration#session-and-storage) |
| `provider.ready` | `accounts.session.get` | [Session and storage](/docs/guides/migration#session-and-storage) |
| `provider.request` | A method of the instance | [RPC methods](/docs/guides/migration#rpc-methods) |
| `provider.store` | `accounts.session` | [Session and storage](/docs/guides/migration#session-and-storage) |
| `ProviderRequest` | Removed | [Removed APIs](/docs/guides/migration#removed-apis) |
| `relay` (option) | `transport` of `viem()` | [Instance](/docs/guides/migration#instance) |
| `Remote` | Removed | [Removed APIs](/docs/guides/migration#removed-apis) |
| `Rpc` | Removed | [Removed APIs](/docs/guides/migration#removed-apis) |
| `Schema` | Removed | [Removed APIs](/docs/guides/migration#removed-apis) |
| `secp256k1` | `local` | [Local owner keys](/docs/guides/local) |
| `secureMmkv` | Removed. `expo` sets the store, or `Store.from` wraps one | [React Native](/docs/guides/migration#react-native) |
| `storage` (option) | `store` | [Session and storage](/docs/guides/migration#session-and-storage) |
| `Storage.combine` | Removed | [Session and storage](/docs/guides/migration#session-and-storage) |
| `Storage.cookie` | Removed | [Session and storage](/docs/guides/migration#session-and-storage) |
| `Storage.filesystem` | `Store.file` | [CLI](/docs/guides/migration#cli) |
| `Storage.from` | `Store.from` | [Session and storage](/docs/guides/migration#session-and-storage) |
| `Storage.idb` | The default `store` of a browser | [Session and storage](/docs/guides/migration#session-and-storage) |
| `Storage.localStorage` | Removed | [Session and storage](/docs/guides/migration#session-and-storage) |
| `Storage.memory` | `Store.memory` | [Session and storage](/docs/guides/migration#session-and-storage) |
| `Store.HydrationError` | Removed | [Session and storage](/docs/guides/migration#session-and-storage) |
| `Store.waitForHydration` | `accounts.session.get` | [Session and storage](/docs/guides/migration#session-and-storage) |
| `tempoWallet` | `dialog` of `accounts/plugins`, `tempoId` of `accounts/wagmi` | [Sign-in](/docs/guides/migration#sign-in) |
| `testnet` (option) | `chain: 'testnet'` | [Instance](/docs/guides/migration#instance) |
| `TimeoutError` | `Accounts.RequestError` , with `expired_token` | [CLI](/docs/guides/migration#cli) |
| `transports` (option) | `transport` of `viem()` | [Instance](/docs/guides/migration#instance) |
| `TrustedHosts` | Tempo ID's verification of the app, which skips the frame's visibility check | [Sign-in](/docs/guides/migration#sign-in) |
| `turnkey` | Removed | [Removed APIs](/docs/guides/migration#removed-apis) |
| `wallet_authorizeAccessKey` | `accounts.dialog.signIn({ accessKey })` | [Access keys](/docs/guides/migration#access-keys) |
| `wallet_connect` | `accounts.dialog.signIn()` | [Sign-in](/docs/guides/migration#sign-in) |
| `wallet_deposit` | `accounts.funding.open()` | [RPC methods](/docs/guides/migration#rpc-methods) |
| `wallet_depositZone` | `accounts.zone.deposit` | [RPC methods](/docs/guides/migration#rpc-methods) |
| `wallet_disconnect` | `accounts.signOut()` | [RPC methods](/docs/guides/migration#rpc-methods) |
| `wallet_getBalances` | `accounts.token.getBalance` | [RPC methods](/docs/guides/migration#rpc-methods) |
| `wallet_getCallsStatus` | The receipt of a `Sync` action | [RPC methods](/docs/guides/migration#rpc-methods) |
| `wallet_getCapabilities` | Removed | [Removed APIs](/docs/guides/migration#removed-apis) |
| `wallet_revokeAccessKey` | `accounts.dialog.revokeAccessKey()` | [Access keys](/docs/guides/migration#access-keys) |
| `wallet_sendCalls` | `accounts.sendTransactionSync` , with `calls` | [RPC methods](/docs/guides/migration#rpc-methods) |
| `wallet_swap` | `accounts.dex.sellSync` , `accounts.dex.buySync` | [RPC methods](/docs/guides/migration#rpc-methods) |
| `wallet_switchEthereumChain` | `accounts.switchChain` | [RPC methods](/docs/guides/migration#rpc-methods) |
| `wallet_transfer` | `accounts.pay` | [RPC methods](/docs/guides/migration#rpc-methods) |
| `wallet_updateAccessKey` | `accounts.dialog.updateAccessKey` | [Access keys](/docs/guides/migration#access-keys) |
| `wallet_withdrawZone` | `accounts.zone.requestWithdrawal` | [RPC methods](/docs/guides/migration#rpc-methods) |
| `webAuthn` | Removed | [Removed APIs](/docs/guides/migration#removed-apis) |
| `WebAuthnCeremony` | Removed. Tempo ID runs each passkey ceremony | [Removed APIs](/docs/guides/migration#removed-apis) |
## Entrypoints
Plugins move to `accounts/plugins`, and each optional platform has its own entry.
| Version 0 | Version 1 |
| ----------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `accounts` | `accounts`\: `Accounts` , `Permissions` , `Plugin` , `Session` , `Store` |
| `accounts`, for each adapter | `accounts/plugins` ([Sign-in](/docs/guides/migration#sign-in)) |
| `accounts/cli`, `accounts/deviceCode` | `device` of `accounts/plugins` ([CLI](/docs/guides/migration#cli)) |
| `accounts/mobileWebAuth` | `accounts/expo` ([React Native](/docs/guides/migration#react-native)) |
| `accounts/postMessage` | Removed ([Removed APIs](/docs/guides/migration#removed-apis)) |
| `accounts/react`, with `Remote` | Removed. `accounts/react` now exports the `react` plugin, which adds `accounts.useSession()` |
| `accounts/react/privy` | Removed ([Removed APIs](/docs/guides/migration#removed-apis)) |
| `accounts/react-native/async-storage` | Removed ([React Native](/docs/guides/migration#react-native)) |
| `accounts/react-native/expo-secure-store` | Removed ([React Native](/docs/guides/migration#react-native)) |
| `accounts/react-native/expo-web-browser` | `accounts/expo` ([React Native](/docs/guides/migration#react-native)) |
| `accounts/react-native/secure-mmkv` | Removed ([React Native](/docs/guides/migration#react-native)) |
| `accounts/server` | `accounts/plugins`, and `accounts/cloudflare` for a Worker ([Server](/docs/guides/migration#server)) |
| `accounts/wagmi` | `accounts/wagmi`\: `tempoId` , `wagmi` ([Wagmi](/docs/guides/migration#wagmi)) |
The `mpp` plugin has its own entry, `accounts/mpp` ([MPP](/docs/guides/migration#mpp)).
## Instance
`Accounts.create` takes these options in place of those of `Provider.create`. [Instance creation](/docs/guides/migration#instance-creation) holds the main example.
| Version 0 | Version 1 |
| ------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `accessKey.authorize`, `authorizeAccessKey` | `accessKey` ([Access keys](/docs/guides/migration#access-keys)) |
| `adapter` | `plugins` ([Sign-in](/docs/guides/migration#sign-in)) |
| `auth` | `dialog({ backend: true })` ([Server](/docs/guides/migration#server)) |
| `chains`, as chain definitions | `chains` , as chain IDs |
| `feePayer` | `viem({ relay })` ([Fee sponsorship](/docs/guides/migration#fee-sponsorship)) |
| `mpp` | `mpp()` of `accounts/mpp` ([MPP](/docs/guides/migration#mpp)) |
| `relay`, `transports` | `transport` of `viem()` |
| `storage` | `store` ([Session and storage](/docs/guides/migration#session-and-storage)) |
| `testnet: true` | `chain: 'testnet'` |
| `hydrationTimeout`, `identity`, `maxAccounts`, `persistCredentials` | Removed |
An instance needs a client ID. In a browser, `clientId` defaults to the page's origin. A CLI passes a `cli:` name, and a backend its public origin.
The `viem` plugin takes the transport of the instance's chain, or a function that returns the options of each chain.
```ts [tempo.config.ts]
import { Accounts } from 'accounts' // [!code ++]
import { dialog, viem } from 'accounts/plugins' // [!code ++]
import { http } from 'viem'
import { tempo, tempoModerato } from 'viem/chains' // [!code --]
const provider = Provider.create({ // [!code --]
chains: [tempoModerato, tempo], // [!code --]
transports: { // [!code --]
[tempo.id]: http('https://rpc.example/tempo'), // [!code --]
[tempoModerato.id]: http('https://rpc.example/moderato'), // [!code --]
}, // [!code --]
}) // [!code --]
export const accounts = Accounts.create({ // [!code ++]
chain: 'testnet', // [!code ++]
plugins: [ // [!code ++]
dialog(), // [!code ++]
viem((chainId) => ({ // [!code ++]
transport: http(`https://rpc.example/${chainId}`), // [!code ++]
})), // [!code ++]
], // [!code ++]
}) // [!code ++]
```
The provider's members map to the instance's\:
| Version 0 | Version 1 |
| ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `provider.chains` | `accounts.chain.get()` , the ID of the selected chain |
| `provider.getAccessKeyStatus()` | `session.accessKey` , `Session.expired(session)` |
| `provider.getAccount()` | Removed. No Viem action of the instance takes `account` |
| `provider.getClient()` | `accounts.viem` |
| `provider.getMppxParameters()` | `accounts.mpp()` , a payer of the `mpp` plugin |
| `provider.on(event)` | `accounts.session.subscribe` , `accounts.chain.subscribe` |
| `provider.ready()` | `accounts.session.get()` |
| `provider.request({ method })` | A method of the instance ([RPC methods](/docs/guides/migration#rpc-methods)) |
| `provider.store` | `accounts.session` |
## Sign-in
A Tempo ID sign-in plugin replaces each adapter that reaches Tempo Wallet. An instance without a sign-in plugin receives `dialog` .
| Version 0 | Version 1 |
| -------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- |
| `tempoWallet()`, `dialog()`, or no `adapter` | `dialog()` |
| `cli()`, `deviceCode()` | `device()` ([CLI](/docs/guides/migration#cli)) |
| `mobileWebAuth()`, `tempoWallet()` of `accounts/mobileWebAuth` | `expo()` ([React Native](/docs/guides/migration#react-native)) |
| `local()`, `secp256k1()` | `local()` ([Local owner keys](/docs/guides/local)) |
| `turnkey()`, `webAuthn()`, `privy()` | Removed ([Removed APIs](/docs/guides/migration#removed-apis)) |
| `postMessage()` | Removed ([Removed APIs](/docs/guides/migration#removed-apis)) |
These adapter options have no replacement\:
| Adapter | Options |
| ------------- | ------------------------------------------------- |
| `dialog` | `dialog`, `host`, `icon`, `name`, `rdns`, `theme` |
| `tempoWallet` | `handoff`, `icon`, `mount`, `theme` |
Tempo ID's approval page names the app\: the host for an origin client ID, or the name of the app's [registration](https\://github.com/tempoxyz/id/blob/main/docs/apps.md#registration).
Tempo ID's [verification](https\://github.com/tempoxyz/id/blob/main/docs/apps.md#verification) of a registered app replaces `TrustedHosts`. In Safari and Firefox, which lack IntersectionObserver v2, the dialog frames Tempo ID's pages only for a first-party or verified app. Any other app's pages open in a popup.
The sign-in's parameters replace the capabilities of `wallet_connect`\:
| Version 0, `capabilities` | Version 1, `accounts.dialog.signIn` |
| ------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `auth` | `backend` of `dialog()` , with `method: 'siwe'` for a SIWE message |
| `authorizeAccessKey` | `accessKey` |
| `personalSign`, `digest` | `challenge` , whose signature is `session.challengeSignature` |
| `showDeposit` | `funding` |
| `identity` | Removed. `session.user` holds the verified email |
| `method: 'register'`, `name`, `userId`, `credentialId` | Removed. Tempo ID's page selects the sign-in or the registration |
:::code-group
```ts [signIn.ts]
import { accounts } from './tempo.config.js' // [!code ++]
export async function signIn(message: string) {
const result = await provider.request({ // [!code --]
method: 'wallet_connect', // [!code --]
params: [{ capabilities: { personalSign: { message } } }], // [!code --]
}) // [!code --]
const signature = result.accounts[0]?.capabilities.signature // [!code --]
const session = await accounts.dialog.signIn({ challenge: message }) // [!code ++]
const signature = session.challengeSignature // [!code ++]
return signature
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { dialog, viem } from 'accounts/plugins'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [dialog(), viem()],
})
```
:::
### CLI
The `device` plugin, the OAuth device authorization grant (RFC 8628), replaces `Provider.create` of `accounts/cli`. Version 0 opens the browser itself. In version 1, `onCode` shows the code and its URL.
A `cli:` client ID needs no registration, and its instance saves the session to `~/.tempo/id/store.json` with no `store` option. `Store.file` replaces `Storage.filesystem` for another file.
:::code-group
```ts [index.ts]
import { accounts } from './tempo.config.js' // [!code ++]
await provider.request({ method: 'wallet_connect' }) // [!code --]
const session = await accounts.device.signIn() // [!code ++]
```
```ts [tempo.config.ts]
import { Provider } from 'accounts/cli' // [!code --]
import { Accounts } from 'accounts' // [!code ++]
import { device, viem } from 'accounts/plugins' // [!code ++]
const provider = Provider.create({ testnet: true }) // [!code --]
export const accounts = Accounts.create({ // [!code ++]
accessKey: () => ({ // [!code ++]
expiry: '7d', // [!code ++]
limits: [{ limit: '100', token: 'ousd' }], // [!code ++]
}), // [!code ++]
chain: 'testnet', // [!code ++]
clientId: 'cli:acme', // [!code ++]
plugins: [ // [!code ++]
device({ // [!code ++]
onCode: (code) => console.log(code.verificationUriComplete), // [!code ++]
}), // [!code ++]
viem(), // [!code ++]
], // [!code ++]
}) // [!code ++]
```
:::
| Version 0 | Version 1 |
| ------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `host`, `name`, `rdns` | `clientId` |
| `open` | `onCode` of `device()` |
| `Storage.filesystem()` | The default `store` of a `cli:` client ID |
| `TimeoutError` of `accounts/deviceCode` | `Accounts.RequestError` , with `expired_token` |
| `PromptError` of `accounts/deviceCode` | Removed. `onCode` shows the code |
| `pollingInterval`, `retryCount`, `timeout` | Removed. Tempo ID sets the interval and the expiry |
### React Native
The `expo` preset of `accounts/expo` replaces `accounts/mobileWebAuth` and the `accounts/react-native` entries. It keeps the session in the device's secure store, and signs in on Tempo ID's pages in the system browser. A native app passes its registration's client ID, since the registration names the app's custom scheme.
:::code-group
```tsx [App.tsx]
import { Button } from 'react-native'
import { accounts } from './tempo.config.js' // [!code ++]
export function App() {
async function signIn() {
await provider.request({ method: 'wallet_connect' }) // [!code --]
await accounts.redirect.signIn() // [!code ++]
}
return
}
```
```ts [tempo.config.ts]
import { Provider } from 'accounts' // [!code --]
import { tempoWallet } from 'accounts/mobileWebAuth' // [!code --]
import { asyncStorage } from 'accounts/react-native/async-storage' // [!code --]
import { openAuthSession } from 'accounts/react-native/expo-web-browser' // [!code --]
import { Accounts } from 'accounts' // [!code ++]
import { expo } from 'accounts/expo' // [!code ++]
const redirectUri = 'com.example.app:/callback'
const provider = Provider.create({ // [!code --]
adapter: tempoWallet({ // [!code --]
baseUrl: 'https://app.example', // [!code --]
openAuthSession, // [!code --]
redirectUri, // [!code --]
}), // [!code --]
storage: asyncStorage(), // [!code --]
}) // [!code --]
export const accounts = Accounts.create({ // [!code ++]
clientId: 'client_…', // [!code ++]
plugins: [expo({ redirectUri })], // [!code ++]
}) // [!code ++]
```
:::
| Version 0 | Version 1 |
| -------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `baseUrl` | `clientId` |
| `openAuthSession` | Removed. `expo` opens the system browser |
| `asyncStorage()`, `secureMmkv()` | The secure store of `expo` , or `Store.from` as `store` |
| `getOrCreateMmkvEncryptionKey()` | Removed |
## Session and storage
`accounts.session` replaces `provider.store`, version 0's Zustand store. [Sessions](/docs/guides/migration#sessions) holds the main example.
| Version 0 | Version 1 |
| ----------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| `provider.store.getState().accounts` | `accounts.session.get()` |
| `provider.store.subscribe` | `accounts.session.subscribe` |
| `provider.ready()`, `Store.waitForHydration` | `accounts.session.get()` , which loads the saved session |
| `Store.HydrationError`, `hydrationTimeout` | Removed |
| `provider.on('accountsChanged')` | `accounts.session.subscribe` |
| `provider.on('chainChanged')` | `accounts.chain.subscribe` |
| `provider.on('connect')`, `provider.on('disconnect')` | `accounts.session.status` |
| `maxAccounts` | Removed. An instance holds one session |
| `persistCredentials` | Removed. The `store` holds the whole session |
`accounts.session.status` holds `pending`, `reauthorizing`, `signedIn`, or `signedOut`.
:::code-group
```ts [status.ts]
import { accounts } from './tempo.config.js' // [!code ++]
export function watch(render: (status: string) => void) {
provider.on('connect', () => render('connected')) // [!code --]
provider.on('disconnect', () => render('disconnected')) // [!code --]
accounts.session.status.subscribe(() => { // [!code ++]
render(accounts.session.status.get().status) // [!code ++]
}) // [!code ++]
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { dialog, viem } from 'accounts/plugins'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [dialog(), viem()],
})
```
:::
The `store` option replaces `storage`. A store holds values without serializing them, since a browser's access key is a non-extractable `CryptoKey`.
| Version 0 | Version 1 |
| ----------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
| `Storage.idb()` | The default `store` of a browser |
| `Storage.memory()` | `Store.memory()` |
| `Storage.from()` | `Store.from()` |
| `Storage.filesystem()` of `accounts/cli` | `Store.file()` |
| `Storage.combine()`, `Storage.cookie()`, `Storage.localStorage()` | Removed |
Outside a browser, an instance with a `cli:` client ID saves its session to the file of `Store.file()` . Any other instance holds a session only with a `store` .
## Access keys
The `accessKey` option replaces `accessKey.authorize` and `authorizeAccessKey`. [Access key requests](/docs/guides/migration#access-key-requests) holds the main example.
| Version 0 | Version 1 |
| ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------ |
| `expiry: Expiry.days(1)` | `expiry: '1d'` , or Unix seconds |
| `limits: [{ limit: 100_000_000n, token }]` | `limits: [{ limit: '100', token: 'ousd' }]` |
| `Expiry.months()`, `Expiry.years()` | `Expiry` of `viem/tempo`. A duration has no such unit |
| `Mach.token` | `token: 'mach'` |
| `accessKey.keystores`, `Keystore`, `reuse` | Removed. The instance creates and keeps the access key |
Without `scopes` , the instance fills them from `limits` . Size `limits` for the app's transactions, since no dialog signs a transaction outside them. Tempo ID's approval page, in the dialog, replaces each RPC method of an access key, and each call defaults to the session's access key.
:::code-group
```ts [revoke.ts]
import { accounts } from './tempo.config.js' // [!code ++]
export async function revoke() {
await provider.request({ // [!code --]
method: 'wallet_revokeAccessKey', // [!code --]
params: [{ accessKeyAddress, address }], // [!code --]
}) // [!code --]
await accounts.dialog.revokeAccessKey() // [!code ++]
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { dialog, viem } from 'accounts/plugins'
export const accounts = Accounts.create({
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [dialog(), viem()],
})
```
:::
| Version 0 | Version 1 |
| ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `wallet_authorizeAccessKey` | `accounts.dialog.signIn({ accessKey })` |
| `wallet_updateAccessKey` | `accounts.dialog.updateAccessKey({ limits })` |
| `wallet_revokeAccessKey` | `accounts.dialog.revokeAccessKey()` , or `accounts.accessKey.revokeSync` |
| `provider.getAccessKeyStatus()` | `session.accessKey` , and `Session.expired(session)` |
The session replaces the access key's status. `accounts.session.get()` empties a saved session whose access key expired.
:::code-group
```ts [usable.ts]
import { Session } from 'accounts' // [!code ++]
import { accounts } from './tempo.config.js' // [!code ++]
export async function isUsable() {
const status = await provider.getAccessKeyStatus() // [!code --]
const usable = status === 'pending' || status === 'published' // [!code --]
const session = await accounts.session.get() // [!code ++]
const usable = !!session?.accessKey && !Session.expired(session) // [!code ++]
return usable
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { dialog, viem } from 'accounts/plugins'
export const accounts = Accounts.create({
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [dialog(), viem()],
})
```
:::
## RPC methods
A method of the instance replaces each RPC method of `provider.request`. [Instance methods](/docs/guides/migration#instance-methods) holds the main example.
| Version 0 | Version 1 |
| --------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `eth_accounts` | `session.accessKey?.account` , or `accounts.account.get()` |
| `eth_chainId` | `accounts.chain.get()` |
| `eth_fillTransaction`, `eth_signTransaction` | `accounts.fillTransaction` , `accounts.signTransaction` |
| `eth_requestAccounts`, `wallet_connect` | `accounts.dialog.signIn()` ([Sign-in](/docs/guides/migration#sign-in)) |
| `eth_sendTransaction` | `accounts.sendTransaction` |
| `eth_sendTransactionSync`, `wallet_sendCalls` | `accounts.sendTransactionSync` , with `calls` |
| `eth_signTypedData_v4` | `accounts.signTypedData` |
| `personal_sign` | `accounts.signMessage` , or `accounts.dialog.signMessage` |
| `wallet_deposit`, `Mach.fund` | `accounts.funding.open()` |
| `wallet_depositZone`, `wallet_withdrawZone` | `accounts.zone.deposit` , `accounts.zone.requestWithdrawal` |
| `wallet_disconnect` | `accounts.signOut()` |
| `wallet_getBalances` | `accounts.token.getBalance` , for each token |
| `wallet_getCallsStatus` | The receipt of a `Sync` action, or `accounts.waitForTransactionReceipt` |
| `wallet_getCapabilities` | Removed |
| `wallet_swap` | `accounts.dex.sellSync` , `accounts.dex.buySync` |
| `wallet_switchEthereumChain` | `accounts.switchChain({ chainId })` |
| `wallet_transfer` | `accounts.pay` |
[Access keys](/docs/guides/migration#access-keys) lists the RPC methods of an access key.
The access key signs each transaction. Without one, a transaction throws `Accounts.AccessKeyRequiredError` , except `accounts.token.transfer` and `transferSync` on a page, which Tempo ID's [payment page](/docs/guides/payments/self-managed#pay-without-an-access-key) sends. On a page, if the node refuses a transaction for a low balance or a spent limit, Tempo ID's screen fixes it, and the transaction sends again.
`accounts.signMessage` signs with the access key, in a keychain envelope for the Tempo Account. `accounts.dialog.signMessage` shows the message on Tempo ID's page, and the Tempo Account signs it, as `personal_sign` did.
:::code-group
```ts [sign.ts]
import { accounts } from './tempo.config.js' // [!code ++]
export async function sign(message: string) {
const signature = await provider.request({ // [!code --]
method: 'personal_sign', // [!code --]
params: [Hex.fromString(message), address], // [!code --]
}) // [!code --]
const { signature } = await accounts.dialog.signMessage({ message }) // [!code ++]
return signature
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { dialog, viem } from 'accounts/plugins'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [dialog(), viem()],
})
```
:::
`wallet_sendCalls` returns an ID for `wallet_getCallsStatus`. A `Sync` action returns the receipt itself.
:::code-group
```ts [send.ts]
import { parseUnits } from 'viem'
import { Actions, Addresses } from 'viem/tempo'
import { accounts } from './tempo.config.js' // [!code ++]
const calls = [
Actions.token.transfer.call({
amount: parseUnits('1', 6),
to: '0x000000000000000000000000000000000000dEaD',
token: Addresses.ousd,
}),
]
export async function send() {
const { id } = await provider.request({ // [!code --]
method: 'wallet_sendCalls', // [!code --]
params: [{ calls }], // [!code --]
}) // [!code --]
const { receipts } = await provider.request({ // [!code --]
method: 'wallet_getCallsStatus', // [!code --]
params: [id], // [!code --]
}) // [!code --]
const receipt = await accounts.sendTransactionSync({ calls }) // [!code ++]
return receipt // [!code ++]
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { dialog, viem } from 'accounts/plugins'
export const accounts = Accounts.create({
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [dialog(), viem()],
})
```
:::
## Wagmi
`tempoId` replaces `tempoWallet`, and takes the options of `Accounts.create` , with the config's `chains` and `transports`. [Wagmi connector](/docs/guides/migration#wagmi-connector) holds the main example.
```ts
import { viem } from 'accounts/plugins' // [!code ++]
import { tempoId } from 'accounts/wagmi' // [!code ++]
import { Expiry } from 'accounts' // [!code --]
import { Addresses } from 'viem/tempo' // [!code --]
import { tempoWallet } from 'wagmi/connectors' // [!code --]
const connector = tempoWallet({ // [!code --]
authorizeAccessKey: () => ({ // [!code --]
expiry: Expiry.days(1), // [!code --]
limits: [{ limit: 100_000_000n, token: Addresses.ousd }], // [!code --]
}), // [!code --]
feePayer: '/api/relay', // [!code --]
}) // [!code --]
const connector = tempoId({ // [!code ++]
accessKey: () => ({ // [!code ++]
expiry: '1d', // [!code ++]
limits: [{ limit: '100', token: 'ousd' }], // [!code ++]
}), // [!code ++]
plugins: [viem({ relay: '/api/relay' })], // [!code ++]
}) // [!code ++]
```
| Version 0 | Version 1 |
| -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `tempoWallet()` of `wagmi/connectors` | `tempoId()` of `accounts/wagmi` |
| `Connector`, `dialog`, `tempoWallet` of `accounts/wagmi` | `tempoId()` of `accounts/wagmi` |
| `dangerous_secp256k1` of `accounts/wagmi` | `local` ([Local owner keys](/docs/guides/local)) |
| `webAuthn` of `accounts/wagmi` | Removed ([Removed APIs](/docs/guides/migration#removed-apis)) |
| `Hooks.wallet.useTransfer` of `wagmi/tempo` | `Hooks.token.useTransferSync` of `wagmi/tempo` |
| `Hooks.wallet.useSwap` of `wagmi/tempo` | `Hooks.dex.useSellSync`, `Hooks.dex.useBuySync` of `wagmi/tempo` |
| `Hooks.wallet.useDeposit` of `wagmi/tempo` | `accounts.funding.open()` of an instance |
| `capabilities` of `connect` | `accessKey` and `signIn` of `connect` |
The `wagmi` plugin of `accounts/wagmi` adds `accounts.wagmi` , a wagmi config for an instance that the app creates itself.
## Server
One instance replaces each `Handler` of `accounts/server`. `accounts.handler` serves each server plugin's routes, so it replaces `Handler.compose` and `Handler.from`.
### Backend sessions
`accounts.handler` serves the `backend` plugin's routes under `/api/auth`, and `accounts.session.get` reads a request's session. On the page, `dialog({ backend: true })` replaces the `auth` option.
:::code-group
```ts [server.ts]
import { Handler, Kv } from 'accounts/server' // [!code --]
import { Accounts, Store } from 'accounts' // [!code ++]
import { backend } from 'accounts/plugins' // [!code ++]
import { Hono } from 'hono'
const auth = Handler.auth({ path: '/api/auth', store: Kv.memory() }) // [!code --]
const accounts = Accounts.create({ // [!code ++]
accessKey: () => ({ // [!code ++]
expiry: '1d', // [!code ++]
limits: [{ limit: '100', token: 'ousd' }], // [!code ++]
}), // [!code ++]
chain: 'testnet', // [!code ++]
clientId: 'https://app.example', // [!code ++]
plugins: [backend({ store: Store.memory() })], // [!code ++]
}) // [!code ++]
const app = new Hono()
app.all('/api/*', (c) => auth.fetch(c.req.raw)) // [!code --]
app.all('/api/*', (c) => accounts.handler.fetch(c.req.raw)) // [!code ++]
app.get('/me', async (c) => {
const session = await auth.getSession(c.req.raw) // [!code --]
if (!session) return c.json({ error: 'unauthenticated' }, 401) // [!code --]
return c.json({ address: session.address }) // [!code --]
const session = await accounts.session.get(c.req.raw) // [!code ++]
if (session?.method !== 'tempo-id') // [!code ++]
return c.json({ error: 'unauthenticated' }, 401) // [!code ++]
return c.json({ address: session.accessKey?.account }) // [!code ++]
})
export default app
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts' // [!code ++]
import { dialog } from 'accounts/plugins' // [!code ++]
const provider = Provider.create({ // [!code --]
adapter: tempoWallet(), // [!code --]
auth: '/api/auth', // [!code --]
}) // [!code --]
export const accounts = Accounts.create({ // [!code ++]
chain: 'testnet', // [!code ++]
plugins: [dialog({ backend: true })], // [!code ++]
}) // [!code ++]
```
:::
The session names a Tempo Account only through its access key, so the backend's instance sets `accessKey` . A deployed origin lists `/api/auth/callback` in the `redirect_uris` of its [web app manifest](https\://github.com/tempoxyz/id/blob/main/docs/apps.md#origin-client-id).
| Version 0 | Version 1 |
| ------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `/api/auth/challenge`, `/api/auth`, `/api/auth/logout` | `/api/auth/login`, `/api/auth/callback`, `/api/auth/session`, `/api/auth/logout` |
| The EIP-4361 message that the user signs | `siwe()` , with `signIn({ method: 'siwe' })` of the `dialog` plugin |
| `auth.getSession(request)` | `accounts.session.get(request)` |
| `session.address`, `session.email` | `session.accessKey?.account` , `session.user.email` |
| `Handler.compose`, `Handler.from` | `accounts.handler` |
### Fee sponsorship
The `relay` plugin replaces `Handler.relay`, and `accounts.relay.fetch` serves its route. [Fee relay](/docs/guides/migration#fee-relay) shows the page's change.
```ts [server.ts]
import { Handler } from 'accounts/server' // [!code --]
import { Accounts } from 'accounts' // [!code ++]
import { relay } from 'accounts/plugins' // [!code ++]
import { Hono } from 'hono'
import { privateKeyToAccount } from 'viem/accounts'
const account = privateKeyToAccount(
process.env.FEE_PAYER_PRIVATE_KEY as `0x${string}`,
)
const handler = Handler.relay({ feePayer: { account }, path: '/api/relay' }) // [!code --]
const accounts = Accounts.create({ // [!code ++]
chain: 'testnet', // [!code ++]
clientId: 'https://app.example', // [!code ++]
plugins: [relay({ account })], // [!code ++]
}) // [!code ++]
const app = new Hono()
app.post('/api/relay', (c) => handler.fetch(c.req.raw)) // [!code --]
app.post('/api/relay', (c) => accounts.relay.fetch(c.req.raw)) // [!code ++]
export default app
```
:::warning
Version 0's route checks no caller. Version 1's route verifies each request's access token, so only the app's signed-in users spend the fee payer's balance. Limit each user with `authorize` .
:::
| Version 0 | Version 1 |
| ------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `autoSwap` | `Relay.autoSwap()` of `viem/tempo`, in `plugins` |
| `cacheTtl`, `kv` | Removed |
| `chains`, `transports` | The chain of the instance, and the `viem` plugin |
| `feePayer.account` | `account` , or `apiKey` for the sponsor of the Tempo API |
| `feePayer.feeToken`, `feePayer.name`, `feePayer.url`, `feePayer.validate` | The options of `Relay.feePayer()` of `viem/tempo`, in `plugins` |
| `features: 'all'` | The relay plugins of `viem/tempo`, in `plugins` |
| `onRequest` | `authorize` , which receives the request and its verified token |
| `path` | The path of the app's own route, or `handler: { relay: true }` for `/api/relay` |
| `resolveTokens` | `resolveTokens` |
`Relay.feePayer` takes the fee payer and its policy, so a `relay` plugin with `plugins` takes no `account` , and throws with both. The plugins run in order, and the plugins after `Relay.feePayer` do not run for a transaction that it signs.
```ts [server.ts]
import { Handler } from 'accounts/server' // [!code --]
import { Accounts } from 'accounts' // [!code ++]
import { relay } from 'accounts/plugins' // [!code ++]
import { Hono } from 'hono'
import { privateKeyToAccount } from 'viem/accounts'
import { Relay } from 'viem/tempo' // [!code ++]
const account = privateKeyToAccount(
process.env.FEE_PAYER_PRIVATE_KEY as `0x${string}`,
)
const allowed = '0x000000000000000000000000000000000000dEaD'
const handler = Handler.relay({ // [!code --]
autoSwap: true, // [!code --]
feePayer: { // [!code --]
account, // [!code --]
validate: (request) => request.to === allowed, // [!code --]
}, // [!code --]
path: '/api/relay', // [!code --]
}) // [!code --]
const accounts = Accounts.create({ // [!code ++]
chain: 'testnet', // [!code ++]
clientId: 'https://app.example', // [!code ++]
plugins: [ // [!code ++]
relay({ // [!code ++]
plugins: [ // [!code ++]
Relay.feePayer({ // [!code ++]
account, // [!code ++]
validate: (request) => request.to === allowed, // [!code ++]
}), // [!code ++]
Relay.autoSwap(), // [!code ++]
], // [!code ++]
}), // [!code ++]
], // [!code ++]
}) // [!code ++]
const app = new Hono()
app.post('/api/relay', (c) => handler.fetch(c.req.raw)) // [!code --]
app.post('/api/relay', (c) => accounts.relay.fetch(c.req.raw)) // [!code ++]
export default app
```
With `verify: false` , the route checks no caller, as in version 0. Use it only behind the app's own guard, such as a backend session.
### Stores
`Store` replaces `Kv` of `accounts/server`. The `backend` plugin's `store` holds each backend session.
| Version 0 | Version 1 |
| -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Kv.memory()` | `Store.memory()` |
| `Kv.from()` | `Store.from()` |
| `Kv.durableObject()` | `Sessions.durableObject()` of `accounts/cloudflare`, for the sessions of `backend` |
| `Kv.NonceStorage` | `DurableObject.sessions()` of `accounts/cloudflare` |
| `Kv.cloudflare()` | `Store.workersKv()` of `accounts/cloudflare` |
`Store.postgres` and `Store.redis` are new server stores. `Store.durableObject` of `accounts/cloudflare` keeps values in the app's own Durable Object.
## MPP
The `mpp` plugin of `accounts/mpp` replaces the `mpp` option. Version 0's option is on by default, and replaces the global `fetch`. Version 1 leaves the global `fetch`, and adds `accounts.fetch` , which pays each HTTP 402 challenge with the session's access key.
:::code-group
```ts [fortune.ts]
import { accounts } from './tempo.config.js' // [!code ++]
export async function fortune() {
const response = await fetch('https://api.example.com/fortune') // [!code --]
const response = await accounts.fetch('https://api.example.com/fortune') // [!code ++]
return response.text()
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts' // [!code ++]
import { mpp } from 'accounts/mpp' // [!code ++]
import { dialog, viem } from 'accounts/plugins' // [!code ++]
const provider = Provider.create({ mpp: true }) // [!code --]
export const accounts = Accounts.create({ // [!code ++]
accessKey: () => ({ // [!code ++]
expiry: '1d', // [!code ++]
limits: [{ limit: '100', token: 'ousd' }], // [!code ++]
}), // [!code ++]
chain: 'testnet', // [!code ++]
plugins: [dialog(), mpp(), viem()], // [!code ++]
}) // [!code ++]
```
:::
`provider.getMppxParameters()` returns the parameters of an `mppx` client that the app creates. `accounts.mpp()` returns a payer with its own `fetch`, and `accounts.mpp.session()` returns a payment session's manager.
:::code-group
```ts [fortune.ts]
import { accounts } from './tempo.config.js' // [!code ++]
export async function fortune() { // [!code ++]
const payer = accounts.mpp({ maxAmount: '1' }) // [!code ++]
const response = await payer.fetch('https://api.example.com/fortune') // [!code ++]
return response.text() // [!code ++]
} // [!code ++]
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { mpp } from 'accounts/mpp'
import { dialog, viem } from 'accounts/plugins'
export const accounts = Accounts.create({
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [dialog(), mpp(), viem()],
})
```
:::
## Errors
`ExecutionError` moves to `viem/tempo`, and `ExecutionError.from` replaces `ExecutionError.parse`.
```ts [parse.ts]
import { ExecutionError } from 'accounts' // [!code --]
import { ExecutionError } from 'viem/tempo' // [!code ++]
export function parse(error: Error) {
const parsed = ExecutionError.parse(error) // [!code --]
const parsed = ExecutionError.from(error) // [!code ++]
return parsed
}
```
Version 0's provider rejects with an RPC error and its code. An instance throws named errors\:
| Version 1 | Condition |
| --------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| `Accounts.RequestError` | Tempo ID refuses a request. Its `reason` names the cause |
| `Accounts.AccessKeyRequiredError` | The session holds no access key for the call |
| `Accounts.SignedOutError` | A Viem action runs while the instance holds no session |
## Removed APIs
Version 1 has no replacement for these APIs.
| Version 0 | Reason |
| ------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------- |
| `turnkey`, `webAuthn`, `privy` | An instance holds no owner key but the `local` plugin's |
| `Adapter` | A plugin of `Plugin.from` extends an instance |
| `Remote`, `Dialog`, `Messenger`, `Mount`, `postMessage` | Tempo ID is the only wallet side |
| `Handoff`, `handoff` | Version 1 has no phone handoff |
| `IntersectionObserver` | The `dialog` plugin reads the support of the browser |
| `Keystore`, `accessKey.keystores` | The instance creates and keeps the access key |
| `Schema`, `Rpc`, `ProviderRequest`, `wallet_getCapabilities` | The instance serves no RPC request |
| `Handler.codeAuth`, `Handler.deviceCode`, `CliAuth` | Tempo ID serves the device grant |
| `Handler.webAuthn`, `WebAuthnCeremony` | Tempo ID runs each passkey ceremony |
| `Handler.oidcProvider`, `Identity`, `identity` | Tempo ID issues each token, with the verified `user` |
| `Handler.exchange` | The page reads each quote through `accounts.dex` |
| `hc` | `hono/client` exports it |
| `Mach.getFundingUrl` | `accounts.funding.open()` opens the deposit page |
| `icon`, `name`, `rdns`, `theme` | Tempo ID names the app. The dialog follows the page's `color-scheme` |
| `cacheTtl`, `kv` of `Handler.relay` | The `relay` plugin holds no cache |
## Next steps
# Web \[Sign a user in through Tempo ID's dialog on the page of the app.]
## Overview
The dialog shows Tempo ID's sign-in in a frame over the app's page, which never sees the user's email code or passkey. It is the default sign-in flow for a web page, and needs no registration. For a full-page sign-in, use a [redirect](/docs/guides/redirect).
The dialog and Tempo ID's page in it draw in the `color-scheme` that the app's page declares, on its root element or in its meta tag. A page that declares both schemes, or none, takes the browser's preference.
The demo signs a user in from a button, shows the user, and signs the user out.
## Walkthrough
The [`web`](https\://github.com/tempoxyz/accounts/tree/main/examples/web) example runs these steps.
::::steps
### Install the packages
:::code-group
```sh [npm]
npm install accounts react react-dom viem
```
```sh [pnpm]
pnpm add accounts react react-dom viem
```
```sh [bun]
bun add accounts react react-dom viem
```
:::
### Create the instance
An instance with no sign-in plugin uses the dialog, so the code names none.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [react()],
})
```
### Sign the user in
Call `dialog.signIn` in a click handler, before any `await`, since its popup fallback opens only within a click. Without an [access key](/docs/guides/access-keys) request, the sign-in requests an access key that may transfer up to 5 OUSD for a day.
:::code-group
```tsx [SignIn.tsx]
import { accounts } from './tempo.config.js'
export function SignIn() {
return (
accounts.dialog.signIn()} type="button">
Sign in with Tempo
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [react()],
})
```
:::
:::note
Tempo ID frames its sign-in only on an HTTPS page. On an HTTP page, such as one on localhost, and in Safari and Firefox for an app that is neither [first-party](https\://github.com/tempoxyz/id/blob/main/docs/apps.md#first-party-apps) nor [verified](https\://github.com/tempoxyz/id/blob/main/docs/apps.md#verification), the call opens a popup instead.
:::
If the user closes the dialog, or denies the app on the approval page, the call rejects. [Errors](/docs/guides/errors#ignore-a-closed-dialog) shows which errors the app ignores.
### Read the session
`accounts.useSession` returns the [session](/docs/guides/user-session), and restores the saved one at the first render, so a later visit opens no dialog.
:::code-group
```tsx [App.tsx]
import { accounts } from './tempo.config.js'
export function App() {
const { isPending, session } = accounts.useSession() // [!code hl]
if (isPending) return Checking the session…
if (!session)
return (
accounts.dialog.signIn()} type="button">
Sign in with Tempo
)
return Signed in as {session.user.email}
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [react()],
})
```
:::
### Sign the user out
`signOut` empties the session, and revokes its refresh token. The user stays signed in to Tempo ID.
:::code-group
```tsx [SignOut.tsx]
import { accounts } from './tempo.config.js'
export function SignOut() {
return (
accounts.signOut()} type="button">
Sign out
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [react()],
})
```
:::
::::
## Use cases
Each use case sets one option of `dialog.signIn` , or of the `dialog` plugin.
### Request an access key
`accessKey` requests an [access key](/docs/guides/access-keys) with the sign-in. The session then signs transactions within these limits, with no prompt. Without it, the sign-in takes the instance's own access key, if the instance sets one.
:::code-group
```tsx [SignIn.tsx]
import { accounts } from './tempo.config.js'
export function SignIn() {
return (
accounts.dialog.signIn({
// [!code hl:start]
// The access key sends up to 100 OUSD for a day.
accessKey: {
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
},
// [!code hl:end]
})
}
type="button"
>
Sign in with Tempo
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [react()],
})
```
:::
### Bind a challenge
`challenge` has the user sign a server's message at the sign-in. A function fetches the message after the dialog opens, so the click still opens it. The server checks the session's `challengeSignature` , as [Sign challenges](/docs/guides/account-proof/sign-challenges) shows.
:::code-group
```tsx [SignIn.tsx]
import { accounts } from './tempo.config.js'
export function SignIn() {
async function signIn() {
const session = await accounts.dialog.signIn({
// [!code hl:start]
challenge: async (signal) => {
const response = await fetch('/challenge', { method: 'POST', signal })
return response.text()
},
// [!code hl:end]
})
await fetch('/verify', {
body: JSON.stringify({
address: session.address,
signature: session.challengeSignature,
}),
headers: { 'content-type': 'application/json' },
method: 'POST',
})
}
return (
Sign in with Tempo
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [react()],
})
```
:::
### Ask for funds
`funding` names the amount that the app needs in the user's Tempo Account. If the account holds less, Tempo ID's deposit page opens after the sign-in. The call resolves once that page returns or closes.
:::code-group
```tsx [SignIn.tsx]
import { accounts } from './tempo.config.js'
export function SignIn() {
return (
accounts.dialog.signIn({
funding: { amount: '10', currency: 'USD' }, // [!code hl]
})
}
type="button"
>
Sign in with Tempo
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [react()],
})
```
:::
### Fill in the email
`loginHint` fills in the email field of Tempo ID's sign-in, and the user can still change it. An app passes it for a session that ended, such as after a refused refresh. A browser with a Tempo ID session ignores it.
:::code-group
```tsx [SignIn.tsx]
import { accounts } from './tempo.config.js'
export function SignIn() {
return (
accounts.dialog.signIn({
loginHint: 'alice@example.com', // [!code hl]
})
}
type="button"
>
Sign in with Tempo
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [react()],
})
```
:::
### Sign in in a popup
`mode: 'popup'` shows the sign-in in a popup window, with no frame. The plugin's `mode` sets it for every sign-in, and loads no frame ahead.
:::code-group
```tsx [SignIn.tsx]
import { accounts } from './tempo.config.js'
export function SignIn() {
return (
accounts.dialog.signIn({ mode: 'popup' })} // [!code hl]
type="button"
>
Sign in with Tempo
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [react()],
})
```
:::
### Sign in for an API
`resource` names a [registered resource](https\://github.com/tempoxyz/id/blob/main/docs/resources.md), such as an MCP server. Each access token then names it as its audience, so only that API accepts the token. The sign-in runs in the dialog's frame if the preloaded frame reports that it issues tokens for a resource, and in a popup otherwise.
After the sign-in, `accounts.session.accessToken` returns the resource's access token.
`scope` adds the API's own scopes to the instance's. The frame refuses an access key beside an API's scopes, so the sign-in requests none.
:::code-group
```tsx [SignIn.tsx]
import { accounts } from './tempo.config.js'
export function SignIn() {
return (
accounts.dialog.signIn({
accessKey: false,
resource: 'https://api.tempo.xyz', // [!code hl]
scope: 'rpc-relay:read rpc-relay:sponsor', // [!code hl]
})
}
type="button"
>
Sign in with Tempo
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [react()],
})
```
:::
### Cancel a sign-in
`signal` ends a sign-in from the page, such as after a time limit. Its abort closes the dialog, and rejects the call with the signal's reason.
:::code-group
```tsx [SignIn.tsx]
import { accounts } from './tempo.config.js'
export function SignIn() {
return (
accounts.dialog.signIn({
// The dialog closes after two minutes without a sign-in.
signal: AbortSignal.timeout(120_000), // [!code hl]
})
}
type="button"
>
Sign in with Tempo
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [react()],
})
```
:::
### Offer a guest checkout
`guest: true` shows Continue as guest on the sign-in, in a frame or a popup. If the visitor selects it, `dialog.signIn` resolves with a guest session, whose key pair the instance keeps in its store. [Guest checkout](/docs/guides/guest-checkout) covers the guest session, and `dialog.session` never returns one.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
guest: true, // [!code hl]
plugins: [react()],
})
```
### Load the frame at the first sign-in
A page without a session loads the dialog's frame, hidden, as the instance starts, so the first sign-in shows at once. `preload: false` loads the frame at the first sign-in instead.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { dialog } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [dialog({ preload: false }), react()], // [!code hl]
})
```
### Isolate the page from popups
A page that sends the `Cross-Origin-Opener-Policy: same-origin` header cuts the popup off from the page. `crossOriginOpenerPolicy: 'same-origin'` then has the page redeem each sign-in's code itself.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { dialog } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [dialog({ crossOriginOpenerPolicy: 'same-origin' }), react()], // [!code hl]
})
```
### Push each request
`par: true` sends each request to Tempo ID first, as [Pushed authorization requests](https\://github.com/tempoxyz/id/blob/main/docs/pushed-authorization-requests.md) describes. A pushed request signs in with a popup only.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { dialog } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [dialog({ par: true }), react()], // [!code hl]
})
```
### Keep the session on a server
`backend` runs the dialog's sign-in through the app's server, which keeps the session, so the page holds no token. [Backend](/docs/guides/backend#sign-in-with-the-dialog) shows the server and the page.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { dialog } from 'accounts/plugins'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [dialog({ backend: true })], // [!code hl]
})
```
## Next steps
# CLI \[A CLI signs a user in with a code that the user approves in a browser.]
## Overview
A CLI has no page for Tempo ID to redirect back to, and the package supports no loopback redirect.
A CLI thus signs in with the [device grant](https\://github.com/tempoxyz/id/blob/main/docs/device-grant.md) (RFC 8628)\: the user approves the CLI's code on Tempo ID's device page, in a browser on any device, and the CLI receives the [session](/docs/guides/user-session).
Choose this flow over the other sign-in flows for a terminal program, or another client without a browser. It is the only flow of a `cli:` client ID, which needs no registration.
```mermaid
sequenceDiagram
participant CLI
participant ID as Tempo ID
participant Browser
CLI->>ID: Request a code
ID-->>CLI: Code, and URL of the device page
Note over CLI: Show the code and the URL
Browser->>ID: Open the URL, and approve the code
loop Until the user decides
CLI->>ID: Poll
end
ID-->>CLI: Session
```
No demo runs in this page, since the client is a terminal program. The program below signs a user in and saves the session. The output is of one run against `id.tempo.xyz`.
:::code-group
```console [Terminal]
$ node --import tsx index.ts whoami
Not signed in. Run `login`.
$ node --import tsx index.ts login
Open https://id.tempo.xyz/device?code=ZZVF-JWQT and confirm the code ZZVF-JWQT.
Signed in as alice@example.com.
$ node --import tsx index.ts whoami
alice@example.com 0xB93163e0dbC07Ee5744Fb519907ed922d0F1Cc1C
```
```ts [index.ts]
import { accounts } from './tempo.config.js'
const [command] = process.argv.slice(2)
const session = await accounts.session.get()
if (command === 'login') {
const { user } = await accounts.device.signIn()
console.log(`Signed in as ${user.email}.`)
} else if (!session?.accessKey) {
console.log('Not signed in. Run `login`.')
} else if (command === 'whoami') {
console.log(`${session.user.email} ${session.accessKey.account}`)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { device } from 'accounts/plugins'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for 7 days.
accessKey: () => ({
expiry: '7d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
clientId: 'cli:acme-example',
plugins: [
device({
onCode: (code) =>
console.log(
`Open ${code.verificationUriComplete} and confirm the code ${code.userCode}.`,
),
}),
],
})
```
:::
The [`cli`](https\://github.com/tempoxyz/accounts/tree/main/examples/cli) example is this program, with `send` and `logout` commands.
## Walkthrough
The CLI tab of [Getting started](/#walkthrough) installs the packages. These steps build the [`cli`](https\://github.com/tempoxyz/accounts/tree/main/examples/cli) example's sign-in.
::::steps
### Create the instance
The `device` plugin adds the device grant.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { device } from 'accounts/plugins'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for 7 days.
accessKey: () => ({
expiry: '7d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
clientId: 'cli:acme-example',
plugins: [device()],
})
```
For a local Tempo ID or another chain, [Use another Tempo ID or chain](/docs/guides/viem#use-another-tempo-id-or-chain) sets the instance.
The client ID is `cli:` and the CLI's name\: 3 to 32 lowercase letters, digits, or `-`, which start with a letter and hold no `tempo`. Tempo ID's device page marks such an [unregistered CLI](https\://github.com/tempoxyz/id/blob/main/docs/apps.md#unregistered-clis) as unverified. If its [access key](/docs/guides/access-keys) names no `limits` , Tempo ID refuses the code request with `missing_permissions`.
### Request a code
`device.signIn` passes the code to `onCode` before it waits. Print the code and the device page's URL. Without `onCode` , `device.signIn` throws.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { device } from 'accounts/plugins'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for 7 days.
accessKey: () => ({
expiry: '7d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
clientId: 'cli:acme-example',
plugins: [device()], // [!code --]
plugins: [ // [!code ++]
device({ // [!code ++]
onCode: (code) => // [!code ++]
console.log( // [!code ++]
`Open ${code.verificationUriComplete} and confirm the code ${code.userCode}.`, // [!code ++]
), // [!code ++]
}), // [!code ++]
], // [!code ++]
})
```
| Property | Value |
| -------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------- |
| `expiresIn` | Seconds until the code expires, such as `600` |
| `userCode` | Code that the user confirms, such as `ZZVF-JWQT` |
| `verificationUri` | URL of the device page, where the user enters a code |
| `verificationUriComplete` | URL of the device page, with the code filled in |
The device page shows the code, the CLI's name, the access key's limits, and the request's device, place, and age. The user thus recognizes a code that another person started.
### Wait for the approval
`device.signIn` polls until the user decides, and returns the session.
:::code-group
```ts [index.ts]
import { accounts } from './tempo.config.js'
const { user } = await accounts.device.signIn() // [!code hl]
console.log(`Signed in as ${user.email}.`)
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { device } from 'accounts/plugins'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for 7 days.
accessKey: () => ({
expiry: '7d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
clientId: 'cli:acme-example',
plugins: [
device({
onCode: (code) =>
console.log(
`Open ${code.verificationUriComplete} and confirm the code ${code.userCode}.`,
),
}),
],
})
```
:::
If the user denies the code, or the code expires, `device.signIn` throws `Accounts.RequestError` . Its `code` names the fault, and [Errors](/docs/guides/errors) lists the others.
| `code` | `message` |
| ------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- |
| `access_denied` | The user denied the request. |
| `expired_token` | Device code expired. Request a new code. |
### Read the saved session
With a `cli:` client ID and no `store` option, the instance saves its session to `~/.tempo/id/store.json`. Every CLI of the user shares the file, with one session for each client ID and chain.
Only the user can read the file and its folder, since the file holds a refresh token and the access key's private key.
A command that sends with the access key, such as the example's `send`, awaits `session.get()` first. A transfer before the read throws `Accounts.SignedOutError` . The `viem` plugin adds the token actions, as [Send with Viem's token actions](/docs/guides/payments/self-managed#send-with-viems-token-actions) shows.
:::code-group
```ts [index.ts]
import { accounts } from './tempo.config.js'
const session = await accounts.session.get() // [!code hl]
if (session?.accessKey)
console.log(`${session.user.email} ${session.accessKey.account}`)
else console.log('Not signed in. Run `login`.')
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { device } from 'accounts/plugins'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for 7 days.
accessKey: () => ({
expiry: '7d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
clientId: 'cli:acme-example',
plugins: [
device({
onCode: (code) =>
console.log(
`Open ${code.verificationUriComplete} and confirm the code ${code.userCode}.`,
),
}),
],
})
```
:::
:::tip
To keep the session in another file, set `store` to `Store.file` with its path. If `TEMPO_HOME` is set, the default file is `id/store.json` in that folder. A service that signs in many users with a `cli:` client ID sets `store` to `false`, so it keeps no session and writes no file.
:::
::::
## Use cases
Each use case sets one option of `device.signIn` , or uses an action of the `device` plugin.
### Request another access key
`accessKey` names the [access key](/docs/guides/access-keys) of one sign-in, in place of the instance's `accessKey` . The device page shows its limits for approval.
:::code-group
```ts [index.ts]
import { accounts } from './tempo.config.js'
const { user } = await accounts.device.signIn({
// [!code hl:start]
// The access key sends up to 500 OUSD for a day.
accessKey: {
expiry: '1d',
limits: [{ limit: '500', token: 'ousd' }],
},
// [!code hl:end]
})
console.log(`Signed in as ${user.email}.`)
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { device } from 'accounts/plugins'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for 7 days.
accessKey: () => ({
expiry: '7d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
clientId: 'cli:acme-example',
plugins: [
device({
onCode: (code) =>
console.log(
`Open ${code.verificationUriComplete} and confirm the code ${code.userCode}.`,
),
}),
],
})
```
:::
### Stop waiting for the approval
`signal` stops the polls, such as at a timeout or at Ctrl+C. The sign-in then rejects with the signal's reason. If a poll in flight returns an approval, the sign-in still signs the user in.
:::code-group
```ts [index.ts]
import { accounts } from './tempo.config.js'
const controller = new AbortController()
const cancel = () => controller.abort(new Error('Cancelled.'))
process.once('SIGINT', cancel)
try {
const { user } = await accounts.device.signIn({
// [!code hl:start]
// Stops the polls after 2 minutes, or at Ctrl+C.
signal: AbortSignal.any([controller.signal, AbortSignal.timeout(120_000)]),
// [!code hl:end]
})
console.log(`Signed in as ${user.email}.`)
} finally {
// Ctrl+C ends the process again once the sign-in settles.
process.off('SIGINT', cancel)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { device } from 'accounts/plugins'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for 7 days.
accessKey: () => ({
expiry: '7d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
clientId: 'cli:acme-example',
plugins: [
device({
onCode: (code) =>
console.log(
`Open ${code.verificationUriComplete} and confirm the code ${code.userCode}.`,
),
}),
],
})
```
:::
### Bind a challenge
`challenge` has the user sign a server's message on the device page. The session's `challengeSignature` holds the signature, which the server checks, as [Sign challenges](/docs/guides/account-proof/sign-challenges) shows.
:::code-group
```ts [index.ts]
import { accounts } from './tempo.config.js'
// The server issues the message to sign.
const response = await fetch('https://api.example.com/challenge', {
method: 'POST',
})
const session = await accounts.device.signIn({
challenge: await response.text(), // [!code hl]
})
await fetch('https://api.example.com/verify', {
body: JSON.stringify({
address: session.address,
signature: session.challengeSignature,
}),
headers: { 'content-type': 'application/json' },
method: 'POST',
})
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { device } from 'accounts/plugins'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for 7 days.
accessKey: () => ({
expiry: '7d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
clientId: 'cli:acme-example',
plugins: [
device({
onCode: (code) =>
console.log(
`Open ${code.verificationUriComplete} and confirm the code ${code.userCode}.`,
),
}),
],
})
```
:::
### Ask for funds
`funding` names the amount that the CLI needs in the user's Tempo Account. If the account holds less, the device page opens Tempo ID's deposit page after the approval.
:::code-group
```ts [index.ts]
import { accounts } from './tempo.config.js'
const { user } = await accounts.device.signIn({
funding: { amount: '10', currency: 'USD' }, // [!code hl]
})
console.log(`Signed in as ${user.email}.`)
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { device } from 'accounts/plugins'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for 7 days.
accessKey: () => ({
expiry: '7d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
clientId: 'cli:acme-example',
plugins: [
device({
onCode: (code) =>
console.log(
`Open ${code.verificationUriComplete} and confirm the code ${code.userCode}.`,
),
}),
],
})
```
:::
### Continue as a guest
With `guest: true` , the device page offers Continue as guest. If the user selects it, `device.signIn` resolves with a guest session, whose key pair the instance keeps in its store, such as `Store.file` . The guest session pays with `pay`, sends with Viem, and pays MPP charges, with no page. A short guest account receives the faucet's funds on a test chain, and a funding code through `onCode` on another chain. See [Guest checkout](/docs/guides/guest-checkout#pay-from-a-cli).
```ts [index.ts]
import { Session } from 'accounts'
import { accounts } from './tempo.config.js'
const session = await accounts.device.signIn()
// [!code hl:start]
if (Session.guest(session)) console.log(`Signed in as guest ${session.address}.`)
else console.log(`Signed in as ${session.user.email}.`)
// [!code hl:end]
```
### Sign in for an API
`resource` names a [registered resource](https\://github.com/tempoxyz/id/blob/main/docs/resources.md), such as an MCP server. Each access token then names it as its audience, so only that API accepts the token.
:::code-group
```ts [index.ts]
import { accounts } from './tempo.config.js'
const { user } = await accounts.device.signIn({
resource: 'https://mcp.example.com/mcp', // [!code hl]
})
console.log(`Signed in as ${user.email}.`)
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { device } from 'accounts/plugins'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for 7 days.
accessKey: () => ({
expiry: '7d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
clientId: 'cli:acme-example',
plugins: [
device({
onCode: (code) =>
console.log(
`Open ${code.verificationUriComplete} and confirm the code ${code.userCode}.`,
),
}),
],
})
```
:::
### Request an API's scopes
An API can define [scopes of its own](https\://github.com/tempoxyz/id/blob/main/docs/resources.md#resource-scopes), such as the Tempo API's `data:read`. `scope` requests them beside `resource`, in addition to the instance's `scope`, for an app that an admin linked to the API's scopes. The device page lists them, the user can uncheck any, and the tokens carry those the user kept. A scope that the API does not define, or that the app may not request, fails with `invalid_scope`.
:::code-group
```ts [index.ts]
import { accounts } from './tempo.config.js'
const { user } = await accounts.device.signIn({
resource: 'https://api.tempo.xyz',
scope: 'data:read routes:read', // [!code hl]
})
console.log(`Signed in as ${user.email}.`)
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { device } from 'accounts/plugins'
export const accounts = Accounts.create({
chain: 'testnet',
// A registered app that a Tempo ID admin linked to the API's scopes.
clientId: 'acme-cli',
plugins: [
device({
onCode: (code) =>
console.log(
`Open ${code.verificationUriComplete} and confirm the code ${code.userCode}.`,
),
}),
],
})
```
:::
### Sign in without a wallet
With `account: false` , the device grant requests no access key, and the session holds only the user and the tokens. Tempo ID creates no Tempo Account for an app whose [first account](https\://github.com/tempoxyz/id/blob/main/docs/realms.md#apps-without-a-first-account) is `none`. With `accessKey: false`, the user receives a Tempo Account, and no access key.
:::code-group
```ts [index.ts]
import { accounts } from './tempo.config.js'
const { user } = await accounts.device.signIn()
console.log(`Signed in as ${user.email}.`)
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { device } from 'accounts/plugins'
export const accounts = Accounts.create({
account: false, // [!code hl]
chain: 'testnet',
clientId: 'cli:acme-example',
plugins: [
device({
onCode: (code) =>
console.log(
`Open ${code.verificationUriComplete} and confirm the code ${code.userCode}.`,
),
}),
],
})
```
:::
### Send above the limit or the balance
With the `viem` plugin, a transfer above the limit of the access key, or above the balance, starts a new device grant. `onCode` shows its code. After the approval, the transfer sends again.
A payment of `accounts.pay` above the limit retries in the same way. A payment above the balance rejects with the node's error.
| Refusal | The grant requests |
| ----------- | ------------------------------------------------------------------------------------------ |
| Spent limit | A new access key with a higher limit of the token |
| Low balance | A new access key with the same limits, and a deposit on Tempo ID's page after the approval |
After a deposit grant, the transfer waits up to 10 minutes for the deposit. If the user denies the code, or no deposit arrives, the transfer rejects with `Plugins.viem.RetryClosedError` . If the session holds another user or Tempo Account after the approval, the transfer rejects with `Plugins.viem.RetryAccountError` .
:::code-group
```ts [index.ts]
import { parseUnits } from 'viem'
import { Addresses } from 'viem/tempo'
import { accounts } from './tempo.config.js'
// A transfer before the read of the session throws `Accounts.SignedOutError`.
await accounts.session.get()
try {
await accounts.token.transferSync({
amount: parseUnits('150', 6),
to: '0x000000000000000000000000000000000000dEaD',
token: Addresses.ousd,
})
} catch (error) {
if ((error as Error).name !== 'Plugins.viem.RetryClosedError') throw error // [!code hl]
console.error('Approve the code to send the transfer.')
process.exitCode = 1
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { device, viem } from 'accounts/plugins'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for 7 days.
accessKey: () => ({
expiry: '7d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
clientId: 'cli:acme-example',
plugins: [
device({
onCode: (code) =>
console.log(
`Open ${code.verificationUriComplete} and confirm the code ${code.userCode}.`,
),
}),
viem(),
],
})
```
:::
### Poll across requests
A server cannot hold one request open until the user approves. `device.authorize` starts the grant in one request, and `device.poll` sends one poll in each later request.
Neither call sets a session. `poll` names the access key of `authorize` again, so the server generates the access key, and keeps its private key with the device code until the code expires.
:::note
`Store.memory` keeps the grants in the process, so a restart loses them. In production, use a store that each replica shares, such as `Store.postgres` or `Store.redis` .
:::
:::code-group
```ts [server.ts]
import { Store } from 'accounts'
import { Hono } from 'hono'
import { generatePrivateKey } from 'viem/accounts'
import { Account } from 'viem/tempo'
import { accounts } from './tempo.config.js'
/** What the server keeps of a grant until a poll redeems it. */
type Grant = { deviceCode: string; privateKey: `0x${string}` }
const grants = Store.memory()
export default new Hono()
// The first request starts the grant, with an access key that the server holds.
.post('/login', async (c) => {
const privateKey = generatePrivateKey()
const grant = await accounts.device.authorize({ // [!code hl]
accessKey: {
account: Account.fromSecp256k1(privateKey),
expiry: '1d',
limits: [{ limit: '10', token: 'ousd' }],
},
})
const id = crypto.randomUUID()
await grants.setItem(
id,
{ deviceCode: grant.deviceCode, privateKey },
{ expiresAt: Date.now() + grant.expiresIn * 1000 },
)
return c.json({
id,
interval: grant.interval,
userCode: grant.userCode,
verificationUriComplete: grant.verificationUriComplete,
})
})
// Each later request sends one poll.
.get('/login/:id', async (c) => {
const id = c.req.param('id')
const grant = (await grants.getItem(id)) as Grant | undefined
if (!grant) return c.json({ error: 'not_found' }, 404)
const result = await accounts.device.poll({ // [!code hl]
accessKey: { account: Account.fromSecp256k1(grant.privateKey) },
deviceCode: grant.deviceCode,
})
if (result.status === 'pending') return c.json(result)
await grants.removeItem(id)
const { accessKey, user } = result.authorization
return c.json({
account: accessKey.account,
email: user.email,
status: result.status,
})
})
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { device } from 'accounts/plugins'
export const accounts = Accounts.create({
chain: 'testnet',
clientId: 'cli:acme-example',
plugins: [device()],
})
```
:::
* The client waits `interval` seconds between requests. An earlier poll returns `slowDown` .
* `authorization.signer` is a Viem account that signs with the access key.
* A poll of a denied or an expired code throws, as [Wait for the approval](/docs/guides/cli#wait-for-the-approval) lists.
:::warning
Keep the device code and the private key as secret as a session. Whoever polls with them receives the approved access key.
:::
## Next steps
# Mobile \[Sign a user in from an Expo app, in an authentication sheet over the app.]
## Overview
An Expo app signs in through the redirect flow in the system browser, not a web view, so the app never sees the user's credentials. The `expo` preset shows Tempo ID's pages in an authentication sheet over the app, and keeps the [session](/docs/guides/user-session) in the device's secure store. It is the sign-in flow for Expo, and a React Native app without Expo uses the [same plugin](/docs/guides/mobile#sign-in-without-expo).
A custom scheme is not an origin, so the app needs a [registration](https\://github.com/tempoxyz/id/blob/main/docs/apps.md#registration) with Tempo ID, which issues its client ID and lists its redirect URI.
An Expo app runs only on a device, so the page holds no demo. This component runs the whole flow\: a sign-in, the session, and a sign-out.
:::code-group
```tsx [App.tsx]
import { Button, Text, View } from 'react-native'
import { accounts } from './tempo.config.js'
export function App() {
const { isPending, session } = accounts.useSession()
if (isPending) return null
if (!session)
return (
accounts.redirect.signIn()}
title="Sign in with Tempo"
/>
)
return (
Signed in as {session.user.email}
accounts.signOut()} title="Sign out" />
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { expo } from 'accounts/expo'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
// The client ID of the app's registration.
clientId: 'example-mobile',
plugins: [expo({ redirectUri: 'com.example.app:/callback' }), react()],
})
```
:::
## Walkthrough
The [`mobile`](https\://github.com/tempoxyz/accounts/tree/main/examples/mobile) example runs these steps. The React Native tab of [Getting started](/#walkthrough) installs the packages, sets the app's scheme, and configures Metro.
::::steps
### Create the instance
`expo` returns two plugins. The first sets the instance's store to the secure store, and its `redirectUri` on the app's scheme. The second is the `redirect` plugin, whose sign-in opens the sheet.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { expo } from 'accounts/expo'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
// The client ID of the app's registration.
clientId: 'example-mobile',
plugins: [expo({ redirectUri: 'com.example.app:/callback' }), react()],
})
```
For a local Tempo ID or another chain, [Use another Tempo ID or chain](/docs/guides/viem#use-another-tempo-id-or-chain) sets the instance.
| Platform | Secure store | Authentication sheet |
| -------- | ------------------------------------------------ | ---------------------------- |
| iOS | Keychain | `ASWebAuthenticationSession` |
| Android | `SharedPreferences`, encrypted with the Keystore | Custom Tab |
An app has no page, so only the session's access key sends a payment of `accounts.pay` , through the `viem` plugin. Add `viem()` to `plugins` to send payments\: without it, `pay` throws `Actions.account.PageRequiredError` , whose message names the missing plugin.
:::note
`accounts` installs `crypto.getRandomValues`, which React Native lacks. If a module imports `viem` or `ox` before `accounts`, import `react-native-get-random-values` first, since their hash library reads `crypto` once as it loads.
:::
### Sign the user in
`redirect.signIn` opens Tempo ID in the sheet, redeems the callback's code, saves the session, and returns it.
:::code-group
```tsx [SignIn.tsx]
import { Button } from 'react-native'
import { accounts } from './tempo.config.js'
export function SignIn() {
return (
{
const session = await accounts.redirect.signIn() // [!code hl]
// The user closed the sheet.
if (!session) return
console.log(`Signed in as ${session.user.email}`)
}}
title="Sign in with Tempo"
/>
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { expo } from 'accounts/expo'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
// The client ID of the app's registration.
clientId: 'example-mobile',
plugins: [expo({ redirectUri: 'com.example.app:/callback' }), react()],
})
```
:::
| The user | `redirect.signIn` |
| -------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| Approves the request | Returns the session |
| Closes the sheet | Returns `undefined` |
| Denies the request | Throws an `Accounts.RequestError` with the code `access_denied` |
If Tempo ID does not know the client ID or the redirect URI, the sheet shows an error page, and no callback returns.
### Render the session
`accounts.useSession` reads the secure store at the first render, with `isPending` until the read ends, so a restart needs no sign-in.
If the read fails, such as while the device is locked, the hook throws the store's error to the nearest error boundary, and the status stays pending. The next mount reads the store again.
:::code-group
```tsx [App.tsx]
import { Button, Text } from 'react-native'
import { accounts } from './tempo.config.js'
export function App() {
const { isPending, session } = accounts.useSession() // [!code hl]
if (isPending) return null
if (!session)
return (
accounts.redirect.signIn()}
title="Sign in with Tempo"
/>
)
return Signed in as {session.user.email}
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { expo } from 'accounts/expo'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
// The client ID of the app's registration.
clientId: 'example-mobile',
plugins: [expo({ redirectUri: 'com.example.app:/callback' }), react()],
})
```
:::
The session ends with its [access key](/docs/guides/access-keys). After the access key's `expiry` , the hook restores no session.
### Sign the user out
`signOut` empties the session, deletes it from the secure store, and revokes its refresh token. Every other instance in the app on an `expo` preset empties its session at once.
:::code-group
```tsx [SignOut.tsx]
import { Button } from 'react-native'
import { accounts } from './tempo.config.js'
export function SignOut() {
return accounts.signOut()} title="Sign out" />
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { expo } from 'accounts/expo'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
// The client ID of the app's registration.
clientId: 'example-mobile',
plugins: [expo({ redirectUri: 'com.example.app:/callback' }), react()],
})
```
:::
The next sign-in always shows Tempo ID's sign-in page, so another user can sign in. Offline, `signOut` rejects, but the session stays empty, and the next `signOut` revokes the refresh token that the secure store keeps.
::::
## Use cases
Each use case sets one option of `redirect.signIn` , of the `expo` preset, or of the `redirect` plugin.
### Bind a challenge
`challenge` has the user sign a server's message at the sign-in. The returned session's `challengeSignature` holds the signature, which the server checks, as [Sign challenges](/docs/guides/account-proof/sign-challenges) shows.
:::code-group
```tsx [SignIn.tsx]
import { Button } from 'react-native'
import { accounts } from './tempo.config.js'
export function SignIn() {
async function signIn() {
const response = await fetch('https://api.example.com/challenge', {
method: 'POST',
})
// [!code hl:start]
const session = await accounts.redirect.signIn({
challenge: await response.text(),
})
// [!code hl:end]
if (!session) return
await fetch('https://api.example.com/verify', {
body: JSON.stringify({
address: session.address,
signature: session.challengeSignature,
}),
headers: { 'content-type': 'application/json' },
method: 'POST',
})
}
return
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { expo } from 'accounts/expo'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
// The client ID of the app's registration.
clientId: 'example-mobile',
plugins: [expo({ redirectUri: 'com.example.app:/callback' }), react()],
})
```
:::
### Ask for funds
`funding` names the amount that the app needs in the user's Tempo Account. If the account holds less, Tempo ID's deposit page opens in the sheet after the approval.
:::code-group
```tsx [SignIn.tsx]
import { Button } from 'react-native'
import { accounts } from './tempo.config.js'
export function SignIn() {
return (
accounts.redirect.signIn({
funding: { amount: '10', currency: 'USD' }, // [!code hl]
})
}
title="Sign in with Tempo"
/>
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { expo } from 'accounts/expo'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
// The client ID of the app's registration.
clientId: 'example-mobile',
plugins: [expo({ redirectUri: 'com.example.app:/callback' }), react()],
})
```
:::
### Fill in the email
`loginHint` fills in the email field of Tempo ID's sign-in page, and the user can still change it. It defaults to the saved session's email. A refused refresh ends the session, so the app then passes the email that it kept.
:::code-group
```tsx [SignIn.tsx]
import { Button } from 'react-native'
import { accounts } from './tempo.config.js'
export function SignIn() {
return (
accounts.redirect.signIn({
loginHint: 'alice@example.com', // [!code hl]
})
}
title="Sign in with Tempo"
/>
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { expo } from 'accounts/expo'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
// The client ID of the app's registration.
clientId: 'example-mobile',
plugins: [expo({ redirectUri: 'com.example.app:/callback' }), react()],
})
```
:::
### Sign in for an API
`resource` names a [registered resource](https\://github.com/tempoxyz/id/blob/main/docs/resources.md), such as an MCP server. Each access token then names it as its audience, so only that API accepts the token.
:::code-group
```tsx [SignIn.tsx]
import { Button } from 'react-native'
import { accounts } from './tempo.config.js'
export function SignIn() {
return (
accounts.redirect.signIn({
resource: 'https://mcp.example.com/mcp', // [!code hl]
})
}
title="Sign in with Tempo"
/>
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { expo } from 'accounts/expo'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
// The client ID of the app's registration.
clientId: 'example-mobile',
plugins: [expo({ redirectUri: 'com.example.app:/callback' }), react()],
})
```
:::
### Share the browser's Tempo ID session
On iOS, the sheet shares no cookies with the system browser, so each sign-in shows Tempo ID's sign-in page. With `ephemeral` set to `false`, it shares them, and a user signed in to Tempo ID there only approves the request.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { expo } from 'accounts/expo'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
// The client ID of the app's registration.
clientId: 'example-mobile',
plugins: [
expo({ ephemeral: false, redirectUri: 'com.example.app:/callback' }), // [!code hl]
react(),
],
})
```
On Android, the sheet always shares them, so the option has no effect.
### Sign in without Expo
An app without Expo passes `redirect` with its own `open` , and its own `store` . `native.ts` stands for the app's native modules.
:::code-group
```ts [tempo.config.ts]
import { Accounts, Store } from 'accounts'
import { redirect } from 'accounts/plugins'
import { keychain, openAuthSession } from './native.js'
export const accounts = Accounts.create({
chain: 'testnet',
clientId: 'example-mobile',
plugins: [
redirect({
open: (url, options) => openAuthSession(url, options.redirectUri),
}),
],
redirectUri: 'com.example.app:/callback',
store: Store.from(keychain),
})
```
```ts [native.ts]
import type { Store } from 'accounts'
// Each declaration stands for a native module of the app.
export declare const keychain: Store.Store
export declare function openAuthSession(
url: string,
redirectUri: string,
): Promise
```
:::
| Module | Contract |
| ----------------- | ----------------------------------------------------------------------------------------------------------------- |
| `keychain` | Returns each value as it was set, a `bigint` included. A store of strings serializes with ox's `Json`. |
| `openAuthSession` | Shows the URL, closes at the redirect URI, and resolves with the callback URL, or `undefined` for a closed sheet. |
The app also installs `react-native-get-random-values`, since React Native links only the native modules of the app's own `package.json`.
## Next steps
# Backend \[The server of an app signs a user in with a redirect, and keeps the session.]
## Overview
The `backend` plugin runs the Tempo ID sign-in on the app's server, through a redirect to Tempo ID's pages. The server keeps each [session](/docs/guides/user-session) in a store.
The browser holds only a session ID in an `HttpOnly` cookie, so the page needs no instance, and no page script reads a token. Choose this flow over the [dialog](/docs/guides/dialog) or [redirect](/docs/guides/redirect) flow if the server acts for the user, or if the page must hold no token. The app's origin is its client ID, with no registration or client secret.
The demo signs a user in on the site's server, reads the user, and signs out.
## Walkthrough
The [`backend`](https\://github.com/tempoxyz/accounts/tree/main/examples/backend) example runs this flow in a Hono server.
::::steps
### Install the packages
:::code-group
```sh [npm]
npm install accounts hono
```
```sh [pnpm]
pnpm add accounts hono
```
```sh [bun]
bun add accounts hono
```
:::
### Create the instance
`APP_URL` holds the app's origin. Create one instance for the process\: Tempo ID refuses a reused refresh token, so the instance holds each refresh in progress, and concurrent requests of a session share it.
```ts [tempo.config.ts]
import { Accounts, Store } from 'accounts'
import { backend } from 'accounts/plugins'
export const accounts = Accounts.create({
chain: 'testnet',
clientId: process.env.APP_URL,
plugins: [backend({ store: Store.memory() })],
})
```
:::note
`Store.memory` keeps sessions in the process, so a restart loses them. In production, use a store that each replica shares, such as `Store.postgres` or `Store.redis` .
:::
To send transactions with the access key of each session, add `accessKey` and the `viem` plugin, as the Backend tab of [Getting started](/#walkthrough) shows. For a local Tempo ID or another chain, [Use another Tempo ID or chain](/docs/guides/viem#use-another-tempo-id-or-chain) sets the instance.
| Store | Sessions live in |
| ----------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
| `Store.memory` | The process. A restart signs each user out |
| `Store.postgres` | A table of a Postgres database |
| `Store.redis` | Redis 6.2 or later |
| `Store.durableObject` | The storage of the app's own Durable Object |
| `Store.workersKv` | A Workers KV namespace. Another location can read a sign-out up to 60 seconds late |
If replicas share a store, route each session to one replica.
:::warning
Keep the store on the server. Each session holds a refresh token and its [access key](/docs/guides/access-keys)'s private key.
:::
### Serve the sign-in routes
`accounts.handler` serves the sign-in routes under `/api/auth`. Mount it on the page's origin, since each `POST` route refuses a request of another origin with 403.
:::code-group
```ts [server.ts]
import { Hono } from 'hono'
import { accounts } from './tempo.config.js'
const app = new Hono()
app.all('/api/*', (c) => accounts.handler.fetch(c.req.raw)) // [!code hl]
export default app
```
```ts [tempo.config.ts]
import { Accounts, Store } from 'accounts'
import { backend } from 'accounts/plugins'
export const accounts = Accounts.create({
chain: 'testnet',
clientId: process.env.APP_URL,
plugins: [backend({ store: Store.memory() })],
})
```
:::
| Route | Result |
| ------------------------ | --------------------------------------------------------------------------- |
| `GET /api/auth/login` | Starts a sign-in, and redirects the browser to Tempo ID |
| `GET /api/auth/callback` | Completes the sign-in, sets the session cookie, and redirects to `returnTo` |
| `GET /api/auth/session` | Returns the session without its tokens, or `null` |
| `POST /api/auth/logout` | Ends the session, and deletes the session cookie |
### Name the redirect URI
Tempo ID returns a sign-in only to a redirect URI of the app. A localhost origin accepts any path. A deployed origin lists `/api/auth/callback` in `redirect_uris` of its [web app manifest](https\://github.com/tempoxyz/id/blob/main/docs/apps.md#origin-client-id), which its root page links.
```json [manifest.webmanifest]
{
"name": "Example",
"redirect_uris": ["https://app.example/api/auth/callback"]
}
```
Without `redirect_uris`, the only redirect URI is the origin's root.
### Sign the user in
A link to `/api/auth/login` leaves the page for Tempo ID's sign-in. The server keeps the PKCE verifier, so only the server can redeem the code.
After the sign-in, the callback returns the browser to `returnTo` with the session cookie. `session.get(request)` returns the session of the request's cookie, or `undefined`. It refreshes an [access token](/docs/guides/api-authentication/authenticate-requests) that expires within 30 seconds.
:::code-group
```ts [server.ts]
import { Hono } from 'hono'
import { html } from 'hono/html'
import { accounts } from './tempo.config.js'
const app = new Hono()
app.all('/api/*', (c) => accounts.handler.fetch(c.req.raw))
app.get('/', async (c) => {
// [!code hl:start]
const session = await accounts.session.get(c.req.raw)
if (session?.method !== 'tempo-id')
return c.html(
html`Sign in with Tempo `,
)
// [!code hl:end]
return c.html(html`Signed in as ${session.user.email}
`)
})
export default app
```
```ts [tempo.config.ts]
import { Accounts, Store } from 'accounts'
import { backend } from 'accounts/plugins'
export const accounts = Accounts.create({
chain: 'testnet',
clientId: process.env.APP_URL,
plugins: [backend({ store: Store.memory() })],
})
```
:::
| Query parameter of the login route | Effect |
| ---------------------------------- | -------------------------------------------------------------------------------------- |
| `loginHint` | Fills the email field of Tempo ID's sign-in page |
| `prompt=login` | Requests a new sign-in, such as to switch to another account |
| `returnTo` | Names the path that the callback returns to, with `error=access_denied` after a denial |
The browser sends the session cookie with each request, so guard each route that changes state against cross-site requests, such as with Hono's CSRF middleware.
### End the session
The logout route revokes the refresh token, and deletes the session and its cookie. It returns 204, so the page reloads after it.
:::code-group
```ts [server.ts]
import { Hono } from 'hono'
import { html } from 'hono/html'
import { accounts } from './tempo.config.js'
const app = new Hono()
app.all('/api/*', (c) => accounts.handler.fetch(c.req.raw))
app.get('/', async (c) => {
const session = await accounts.session.get(c.req.raw)
if (session?.method !== 'tempo-id')
return c.html(
html`Sign in with Tempo `,
)
return c.html(html`
Signed in as ${session.user.email}
Sign out
`)
})
export default app
```
```ts [tempo.config.ts]
import { Accounts, Store } from 'accounts'
import { backend } from 'accounts/plugins'
export const accounts = Accounts.create({
chain: 'testnet',
clientId: process.env.APP_URL,
plugins: [backend({ store: Store.memory() })],
})
```
:::
::::
## Use cases
Each use case uses one option or action of the `backend` plugin, or the dialog's `backend` option.
### Sign in with the dialog
A page can open Tempo ID's sign-in in a dialog over the page, in place of a redirect. Pass `backend` to the `dialog` plugin of the page's instance.
`dialog.signIn` runs the sign-in through `POST` requests to the login and callback routes, and the server still keeps the PKCE verifier and the session. After the sign-in, the page reloads, and the server renders it with the session.
The [`authenticated-api`](https\://github.com/tempoxyz/accounts/tree/main/examples/authenticated-api) example runs this flow in a React page.
:::code-group
```tsx [SignIn.tsx]
import { accounts } from './tempo.config.js'
export function SignIn() {
return (
{
await accounts.dialog.signIn() // [!code hl]
location.reload()
}}
type="button"
>
Sign in with Tempo
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { dialog } from 'accounts/plugins'
export const accounts = Accounts.create({
// `true` names `/api`, the default path of the handler.
plugins: [dialog({ backend: true })], // [!code hl]
})
```
```ts [server.ts]
import { Accounts, Store } from 'accounts'
import { backend } from 'accounts/plugins'
import { Hono } from 'hono'
const accounts = Accounts.create({
chain: 'testnet',
clientId: process.env.APP_URL,
plugins: [backend({ store: Store.memory() })],
})
const app = new Hono()
app.all('/api/*', (c) => accounts.handler.fetch(c.req.raw))
export default app
```
:::
If the user closes the dialog, the call rejects with an `AbortError`. If the backend does not answer, such as offline, it rejects with `Accounts.RequestError` , with the code `server_error` and status 0, and with `signedIn` once the user signed in on Tempo ID.
### Restore the session on load
A page that renders without the server reads the session with `dialog.session` . With `backend`, it returns the session of `GET /api/auth/session`, or `null`. Its first call takes the read that the dialog's preload started as the instance was created, while it is pending or for 10 seconds after it settles, so the page reads the route once, signed in or out.
```ts [main.ts]
import { accounts } from './tempo.config.js'
const session = await accounts.dialog.session() // [!code hl]
if (session?.method === 'tempo-id') render(session.user.email)
else if (session) render(session.account)
else button.onclick = () => accounts.dialog.signIn()
```
### Write sign-in routes
An app with its own paths or cookie names calls the plugin's actions in place of `accounts.handler` , and sets the cookie itself.
```ts [server.ts]
import { Accounts, Store } from 'accounts'
import { backend } from 'accounts/plugins'
import { Hono } from 'hono'
import { deleteCookie, getCookie, setCookie } from 'hono/cookie'
import { csrf } from 'hono/csrf'
const accounts = Accounts.create({
chain: 'testnet',
clientId: process.env.APP_URL,
plugins: [backend({ store: Store.memory() })],
})
const app = new Hono()
const cookie = {
httpOnly: true,
path: '/',
prefix: 'host',
sameSite: 'Lax',
secure: true,
} as const
app.use(csrf())
// Start: stores the sign-in under a new session ID, and redirects to Tempo ID.
app.get('/auth/start', async (c) => {
const { id, url } = await accounts.backend.start({
redirectUri: new URL('/auth/callback', c.req.url).href,
})
setCookie(c, 'session', id, cookie)
return c.redirect(url)
})
// Callback: redeems the code, and stores the session under the same session ID.
app.get('/auth/callback', async (c) => {
const id = getCookie(c, 'session', 'host')
if (!id) return c.redirect('/auth/start')
await accounts.backend.complete({ id, url: c.req.url })
return c.redirect('/')
})
// Session: returns the user of the session ID.
app.get('/auth/session', async (c) => {
const id = getCookie(c, 'session', 'host')
const session = id ? await accounts.backend.get({ id }) : undefined
if (session?.method !== 'tempo-id') return c.json({ user: null })
return c.json({ user: session.user })
})
// Sign-out: revokes the refresh token, and deletes the session.
app.post('/auth/logout', async (c) => {
const id = getCookie(c, 'session', 'host')
if (id) await accounts.backend.end({ id })
deleteCookie(c, 'session', cookie)
return c.body(null, 204)
})
export default app
```
`backend.start` keeps a sign-in for 10 minutes, or 20 with `funding` . `backend.complete` throws `Accounts.RequestError` for a denial, and `Accounts.PendingNotFoundError` without a sign-in in progress.
### Ask for funds
`funding` of `backend.start` names the amount that the app needs in the user's Tempo Account. If the account holds less, Tempo ID's deposit page opens after the approval, before the callback. The callback route stays the same as in [Write sign-in routes](/docs/guides/backend#write-sign-in-routes).
:::code-group
```ts [server.ts]
import { Hono } from 'hono'
import { setCookie } from 'hono/cookie'
import { accounts } from './tempo.config.js'
const app = new Hono()
app.get('/auth/start', async (c) => {
const { id, url } = await accounts.backend.start({
funding: { amount: '10', currency: 'USD' }, // [!code hl]
redirectUri: new URL('/auth/callback', c.req.url).href,
})
setCookie(c, 'session', id, {
httpOnly: true,
path: '/',
prefix: 'host',
sameSite: 'Lax',
secure: true,
})
return c.redirect(url)
})
export default app
```
```ts [tempo.config.ts]
import { Accounts, Store } from 'accounts'
import { backend } from 'accounts/plugins'
export const accounts = Accounts.create({
chain: 'testnet',
clientId: process.env.APP_URL,
plugins: [backend({ store: Store.memory() })],
})
```
:::
### Call an API for the user
`session.fetch(request, options)` sends a request with the [access token](/docs/guides/api-authentication/authenticate-requests) of the request's session, after a refresh if necessary. It returns `undefined` without a Tempo ID session, and sends nothing. If the API refuses the access token with `invalid_token`, the call refreshes the session once and sends the request again.
:::code-group
```ts [server.ts]
import { Hono } from 'hono'
import { accounts } from './tempo.config.js'
const app = new Hono()
app.all('/api/*', (c) => accounts.handler.fetch(c.req.raw))
app.get('/me', async (c) => {
// [!code hl:start]
const response = await accounts.session.fetch(c.req.raw, {
url: 'https://api.example.com/me',
})
// [!code hl:end]
if (!response) return c.json({ error: 'invalid_token' }, 401)
return response
})
export default app
```
```ts [tempo.config.ts]
import { Accounts, Store } from 'accounts'
import { backend } from 'accounts/plugins'
export const accounts = Accounts.create({
chain: 'testnet',
clientId: process.env.APP_URL,
plugins: [backend({ store: Store.memory() })],
})
```
:::
### Accept access tokens
`accessToken: true` has `session.get(request)` also accept an access token of the app in the request's authorization header, such as from the app's CLI. Such a session holds the verified token's claims. A request with a session cookie reads the cookie's session first.
:::code-group
```ts [server.ts]
import { Hono } from 'hono'
import { accounts } from './tempo.config.js'
const app = new Hono()
app.all('/api/*', (c) => accounts.handler.fetch(c.req.raw))
app.get('/me', async (c) => {
const session = await accounts.session.get(c.req.raw)
if (session?.method === 'tempo-id') return c.json({ userId: session.user.id })
// [!code hl:start]
if (session?.method === 'access-token')
return c.json({ userId: session.token.userId })
// [!code hl:end]
return c.json({ error: 'invalid_token' }, 401)
})
export default app
```
```ts [tempo.config.ts]
import { Accounts, Store } from 'accounts'
import { backend } from 'accounts/plugins'
export const accounts = Accounts.create({
chain: 'testnet',
clientId: process.env.APP_URL,
plugins: [backend({ accessToken: true, store: Store.memory() })], // [!code hl]
})
```
:::
A DPoP-bound token carries a proof, which the route refuses once used, as [Bind DPoP keys](/docs/guides/api-authentication/bind-dpop-keys#refuse-a-repeated-proof) shows.
### Authenticate with a private key
A backend whose client ID is its origin sends no client authentication, so any holder of a session's refresh token can refresh the session. A backend that publishes a [metadata document](https\://github.com/tempoxyz/id/blob/main/docs/apps.md#confidential-backends) with `private_key_jwt` signs a client assertion for each token request instead, with no registration. The document's URL is the client ID.
Generate an ES256 key pair once, as [Pay for users](/docs/guides/connections/pay-for-users#store-the-connections) shows, and store the private key as the `APP_PRIVATE_KEY` secret. The document publishes the public key and the redirect URI, on the app's origin.
:::code-group
```json [client.json]
{
"client_id": "https://app.example/client.json",
"client_name": "Example",
"grant_types": ["authorization_code", "refresh_token"],
"jwks": {
"keys": [{ "alg": "ES256", "crv": "P-256", "kid": "…", "kty": "EC", "x": "…", "y": "…" }]
},
"redirect_uris": ["https://app.example/api/auth/callback"],
"token_endpoint_auth_method": "private_key_jwt"
}
```
```ts [tempo.config.ts]
import { Accounts, Store } from 'accounts'
import { ClientAssertion } from 'accounts/internal'
import { backend } from 'accounts/plugins'
export const accounts = Accounts.create({
chain: 'testnet',
// [!code hl:start]
clientAssertion: ClientAssertion.fromPrivateKey({
privateKey: JSON.parse(process.env.APP_PRIVATE_KEY!),
}),
clientId: 'https://app.example/client.json',
// [!code hl:end]
plugins: [backend({ store: Store.memory() })],
})
```
:::
The instance then pushes each authorization request, and signs each code redemption and refresh. Tempo ID still shows the approval page with the app's host. It reads the document again after 5 minutes, so publish a new public key beside the old one at least 5 minutes before the instance signs with it.
## Next steps
# Sign-In With Ethereum \[Sign a user in on a backend with a message that the user's Tempo Account signs.]
## Overview
Sign-In With Ethereum ([EIP-4361](https\://eips.ethereum.org/EIPS/eip-4361)) signs a user in to a backend with a signed message, in place of OAuth tokens. The backend issues the message, the user's Tempo Account signs it in Tempo ID's dialog, and the backend verifies the signature and keeps the session behind a cookie.
Choose this flow over the [Backend flow](/docs/guides/backend) if the app needs only the account's address\: a SIWE session holds no tokens, no [access key](/docs/guides/access-keys), and no email address. Another wallet, such as a browser extension, can sign in the same way.
The demo signs a message, which the site's server verifies, and shows the session's account.
## Walkthrough
The [`siwe`](https\://github.com/tempoxyz/accounts/tree/main/examples/siwe) example runs these steps in a React app and a Hono server, with an API that keeps notes for each account.
::::steps
### Install the packages
:::code-group
```sh [npm]
npm install accounts hono react react-dom viem
```
```sh [pnpm]
pnpm add accounts hono react react-dom viem
```
```sh [bun]
bun add accounts hono react react-dom viem
```
:::
### Create the instances
The page and the backend share one origin, `APP_URL`, which is the client ID, with no registration. The `siwe` plugin needs the `backend` plugin, which stores the sessions.
Each message names `origin` as its domain, and shows `statement` . A signature thus signs in to this app only.
```ts [server.ts]
import { Accounts, Store } from 'accounts'
import { backend, siwe } from 'accounts/plugins'
const accounts = Accounts.create({
chain: 'testnet',
clientId: process.env.APP_URL,
plugins: [
backend({ store: Store.memory() }),
siwe({
origin: process.env.APP_URL,
statement: 'Sign in to the notes example.',
}),
],
})
```
:::note
`Store.memory` keeps sessions and challenges in the process, so a restart loses them. In production, use a store that each replica shares, such as `Store.postgres` or `Store.redis` .
:::
On the page, `backend` set to `true` names the default path of the backend routes, `/api`.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { dialog } from 'accounts/plugins'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [dialog({ backend: true })],
})
```
With `backend` , the dialog's redirect URI is `/api/auth/callback`. A deployed origin lists it in `redirect_uris` of its [web app manifest](https\://github.com/tempoxyz/id/blob/main/docs/apps.md#origin-client-id), or sets the instance's `redirectUri` to its root, such as `https://app.example/`.
### Serve the SIWE routes
`accounts.handler` serves the sign-in routes under `/api/auth`.
```ts [server.ts]
import { Accounts, Store } from 'accounts'
import { backend, siwe } from 'accounts/plugins'
import { Hono } from 'hono'
const accounts = Accounts.create({
chain: 'testnet',
clientId: process.env.APP_URL,
plugins: [
backend({ store: Store.memory() }),
siwe({
origin: process.env.APP_URL,
statement: 'Sign in to the notes example.',
}),
],
})
const app = new Hono()
app.all('/api/*', (c) => accounts.handler.fetch(c.req.raw)) // [!code hl]
export default app
```
| Route | Result |
| ------------------------------- | --------------------------------------------------- |
| `POST /api/auth/siwe/challenge` | Issues the message, and sets the challenge cookie |
| `POST /api/auth/siwe` | Verifies the signature, and sets the session cookie |
| `GET /api/auth/session` | Returns the session of the page |
| `POST /api/auth/logout` | Ends the session |
`POST /api/auth/siwe/verify` verifies in the same way, for the `dialog` plugin with `backend` .
A message lasts 10 minutes, and verifies once. The verify route answers a message other than the challenge with 400 `invalid_request`, and a signature of another account with 403 `access_denied`.
:::note
Each request to the challenge route stores a challenge. Limit the route's rate.
:::
### Sign the message
Call `dialog.signIn` with `method` set to `'siwe'` from a click handler. The dialog opens before it requests the message, so the popup opens within the click. The account's owner signs, since the plugin refuses an access key's signature.
:::code-group
```tsx [App.tsx]
import * as React from 'react'
import { accounts } from './tempo.config.js'
type Session = { account: `0x${string}`; method: 'siwe' }
export function App() {
const [session, setSession] = React.useState()
if (!session)
return (
setSession(await accounts.dialog.signIn({ method: 'siwe' })) // [!code hl]
}
type="button"
>
Sign in with Ethereum
)
return Signed in as {session.account}
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { dialog } from 'accounts/plugins'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [dialog({ backend: true })],
})
```
:::
The call returns the SIWE session with its account. If the user denies the request, it rejects with `Accounts.RequestError` and the code `access_denied`. If the user closes the dialog, it rejects with an `AbortError`. If the backend does not answer, such as offline, it rejects with `Accounts.RequestError`, with the code `server_error` and status 0.
### Read the session
`session.get(request)` returns the session of the request's cookie, or `undefined`. A SIWE session never refreshes, and lasts one day, or the `siwe` plugin's `lifetime` .
```ts [server.ts]
import { Accounts, Store } from 'accounts'
import { backend, siwe } from 'accounts/plugins'
import { Hono } from 'hono'
import { csrf } from 'hono/csrf'
const accounts = Accounts.create({
chain: 'testnet',
clientId: process.env.APP_URL,
plugins: [
backend({ store: Store.memory() }),
siwe({
origin: process.env.APP_URL,
statement: 'Sign in to the notes example.',
}),
],
})
const app = new Hono()
app.all('/api/*', (c) => accounts.handler.fetch(c.req.raw))
// Another site cannot post to the routes of the app.
app.use('/v1/*', csrf())
app.get('/v1/account', async (c) => {
const session = await accounts.session.get(c.req.raw) // [!code hl]
if (session?.method !== 'siwe') return c.json({ error: 'invalid_token' }, 401)
return c.json({ account: session.address })
})
export default app
```
### Restore the session
On a later visit, the click reads the session route before it opens the dialog.
:::code-group
```tsx [App.tsx]
import * as React from 'react'
import { accounts } from './tempo.config.js'
type Session = { account: `0x${string}`; method: 'siwe' }
export function App() {
const [session, setSession] = React.useState()
async function signIn() {
// [!code hl:start]
const response = await fetch('/api/auth/session')
const body = (await response.json()) as { session: Session | null }
// [!code hl:end]
setSession(body.session ?? (await accounts.dialog.signIn({ method: 'siwe' })))
}
if (!session)
return (
Sign in with Ethereum
)
return Signed in as {session.account}
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { dialog } from 'accounts/plugins'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [dialog({ backend: true })],
})
```
:::
### Sign the user out
The logout route ends the session, and deletes its cookie.
:::code-group
```tsx [App.tsx]
import * as React from 'react'
import { accounts } from './tempo.config.js'
type Session = { account: `0x${string}`; method: 'siwe' }
export function App() {
const [session, setSession] = React.useState()
if (!session)
return (
setSession(await accounts.dialog.signIn({ method: 'siwe' }))
}
type="button"
>
Sign in with Ethereum
)
return (
<>
Signed in as {session.account}
{
await fetch('/api/auth/logout', { method: 'POST' }) // [!code hl]
setSession(null)
}}
type="button"
>
Sign out
>
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { dialog } from 'accounts/plugins'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [dialog({ backend: true })],
})
```
:::
::::
## Use cases
Each use case uses one option or action of the `siwe` plugin.
### Write SIWE routes
An app that sets its own cookies calls `siwe.start` and `siwe.complete` in its own routes. Each throws an error named `Plugins.siwe.InvalidError` for a fault of the caller\:
| Call | Throws for |
| ----------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `siwe.start` | A request from another origin, or a chain outside the plugin's `chains` , which defaults to the instance's chain |
| `siwe.complete` | A sign-in that does not verify, such as a spent challenge |
The package exports no class for the error, so the handler matches its name.
```ts [server.ts]
import { Accounts, Store } from 'accounts'
import { backend, siwe } from 'accounts/plugins'
import { Hono } from 'hono'
import { deleteCookie, getCookie, setCookie } from 'hono/cookie'
import { csrf } from 'hono/csrf'
const accounts = Accounts.create({
chain: 'testnet',
clientId: process.env.APP_URL,
plugins: [
backend({ store: Store.memory() }),
siwe({
origin: process.env.APP_URL,
statement: 'Sign in to the notes example.',
}),
],
})
const app = new Hono()
const cookie = {
httpOnly: true,
path: '/',
sameSite: 'Lax',
secure: true,
} as const
app.use('/siwe/*', csrf())
// A sign-in that does not verify is the fault of the caller.
app.onError((error, c) => {
if (error.name === 'Plugins.siwe.InvalidError')
return c.json({ error: 'access_denied' }, 403)
throw error
})
app.post('/siwe/challenge', async (c) => {
// `siwe({ auth })` on the page sends the chain of the sign-in or the payment.
const { chainId } = await c.req.json<{ chainId?: number }>()
const { id, message } = await accounts.siwe.start({ chainId, request: c.req.raw }) // [!code hl]
setCookie(c, 'challenge', id, { ...cookie, maxAge: 600 })
return c.json({ message })
})
app.post('/siwe/verify', async (c) => {
const id = getCookie(c, 'challenge')
if (!id) return c.json({ error: 'invalid_request' }, 400)
// The challenge verifies once.
deleteCookie(c, 'challenge', cookie)
const body = await c.req.json<{
address: `0x${string}`
message: string
signature: `0x${string}`
}>()
const session = await accounts.siwe.complete({ ...body, id }) // [!code hl]
setCookie(c, 'session', session.id, { ...cookie, maxAge: 86_400 })
return c.json({ account: session.address })
})
export default app
```
`accounts.backend.get` returns the session of a later request, and `accounts.backend.end` ends it.
The page signs with `dialog.signMessage` . Its `message` is a function, so the dialog opens on the click and requests the message after.
:::code-group
```tsx [SignIn.tsx]
import { accounts } from './tempo.config.js'
async function post(path: string, body: object = {}) {
const response = await fetch(path, {
body: JSON.stringify(body),
headers: { 'content-type': 'application/json' },
method: 'POST',
})
return (await response.json()) as data
}
export function SignIn() {
return (
{
const signed = await accounts.dialog.signMessage({ // [!code hl]
message: async () =>
(await post<{ message: string }>('/siwe/challenge')).message,
})
await post('/siwe/verify', signed)
}}
type="button"
>
Sign in with Ethereum
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { dialog } from 'accounts/plugins'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [dialog({ backend: true })],
})
```
:::
### Sign in with the plugin on the page
The `siwe` plugin on the page signs the user in to the app's routes at each `dialog.signIn` . Its `auth` names the challenge and verify routes, such as those of [Write SIWE routes](/docs/guides/siwe#write-siwe-routes). The dialog opens at the click, then requests the message, and the call returns the verify route's JSON object as `auth` .
```tsx [App.tsx]
import { Accounts } from 'accounts'
import { siwe } from 'accounts/plugins'
const accounts = Accounts.create({
chain: 'testnet',
plugins: [siwe({ auth: { challenge: '/siwe/challenge', verify: '/siwe/verify' } })],
})
const { auth } = await accounts.dialog.signIn()
// { account }, the response of the verify route
```
A string in `auth` names the verify route, and the challenge route at its `/challenge` path. `/api/auth/siwe` names the routes of `accounts.handler` .
| Route | Receives | Answers |
| --------- | ------------------------------------------------------ | ------------------------------------ |
| Challenge | `{ chainId }`, the chain of the sign-in or the payment | `{ message }`, or `{ id, message }` |
| Verify | `{ address, id, message, signature }` | The JSON object of the call's `auth` |
`accounts.pay` without an account signs the user in in the same way, beside the payment.
With `guest: true` , the sign-in also offers Continue as guest. The guest key pair then signs the message, and the verify route receives the guest account's address and P256 signature. [Guest checkout](/docs/guides/guest-checkout#sign-a-guest-in-to-the-app) covers the guest session.
A sign-in with an access key needs one passkey prompt too. The account signs the key authorization, whose witness is the message's EIP-191 hash.
The verify route then receives `{ address, id, keyAuthorization, message }`, with the sign-in's access token in its `Authorization` header, and `accounts.handler` checks that the token names the access key for the app. Any app may set a witness, so the token binds the proof to this app. With the client IDs of several apps, `accessTokens` accepts the tokens of each.
### Serve an API on another origin
A session cookie reaches only the routes' own origin. With `token` set to `true`, the routes hand the session to the page as a token instead, so an API on one origin serves a page on another.
`origin` names the page, which each message names, and which the routes answer with CORS headers. A list of origins serves several pages. The API's own routes add CORS headers for the page themselves.
```ts [server.ts]
import { Accounts, Store } from 'accounts'
import { backend, siwe } from 'accounts/plugins'
import { Hono } from 'hono'
import { cors } from 'hono/cors'
const accounts = Accounts.create({
chain: 'testnet',
clientId: 'https://app.example.com',
plugins: [
backend({ store: Store.memory() }),
siwe({ origin: 'https://app.example.com', token: true }), // [!code hl]
],
})
const app = new Hono()
app.all('/api/*', (c) => accounts.handler.fetch(c.req.raw))
// The page sends its token from another origin, so the API's own routes answer it with CORS headers.
app.use(
'/v1/*',
cors({ allowHeaders: ['authorization'], origin: 'https://app.example.com' }),
)
app.get('/v1/account', async (c) => {
// Reads the session of `Authorization: Bearer `.
const session = await accounts.session.get(c.req.raw)
if (session?.method !== 'siwe') return c.json({ error: 'invalid_token' }, 401)
return c.json({ account: session.address })
})
export default app
```
```tsx [App.tsx]
import { Accounts } from 'accounts'
import { siwe } from 'accounts/plugins'
const accounts = Accounts.create({
chain: 'testnet',
plugins: [siwe({ auth: 'https://api.example.com/api/auth/siwe' })],
})
export async function signIn() {
const { auth } = await accounts.dialog.signIn()
// auth: { session: { account, method: 'siwe' }, token }
const response = await fetch('https://api.example.com/v1/account', {
headers: { authorization: `Bearer ${auth!.token}` },
})
return await response.json()
}
```
The challenge route returns `{ id, message }`, and the verify route takes `id` in its body and returns `{ session, token }`. Neither sets a cookie.
The session and logout routes read the token from the `Authorization` header. The page keeps the token, and ends the session with the logout route.
### Approve a change
A change that deletes data or moves funds needs more than a cookie. `siwe.challenge` issues a message that states the change, and `siwe.approve` verifies that the session's account signs it. Both routes derive the statement from the session, so an approval of another change fails.
```ts [server.ts]
import { Accounts, Store } from 'accounts'
import { backend, siwe } from 'accounts/plugins'
import { Hono } from 'hono'
import { csrf } from 'hono/csrf'
const accounts = Accounts.create({
chain: 'testnet',
clientId: process.env.APP_URL,
plugins: [
backend({ store: Store.memory() }),
siwe({
origin: process.env.APP_URL,
statement: 'Sign in to the notes example.',
}),
],
})
const app = new Hono()
app.all('/api/*', (c) => accounts.handler.fetch(c.req.raw))
// Another site cannot post to the routes of the app.
app.use('/v1/*', csrf())
// An approval that does not verify is the fault of the caller.
app.onError((error, c) => {
if (error.name === 'Plugins.siwe.InvalidError')
return c.json({ error: 'access_denied' }, 403)
throw error
})
app.post('/v1/notes/clear/challenge', async (c) => {
const session = await accounts.session.get(c.req.raw)
if (session?.method !== 'siwe') return c.json({ error: 'invalid_token' }, 401)
const { message } = await accounts.siwe.challenge({ // [!code hl]
request: c.req.raw,
session,
statement: `Delete every note of ${session.address}.`,
})
return c.json({ message })
})
app.post('/v1/notes/clear', async (c) => {
const session = await accounts.session.get(c.req.raw)
if (session?.method !== 'siwe') return c.json({ error: 'invalid_token' }, 401)
const body = await c.req.json<{ message: string; signature: `0x${string}` }>()
// Throws for an approval that does not verify, such as a spent one.
await accounts.siwe.approve({ // [!code hl]
...body,
request: c.req.raw,
session,
statement: `Delete every note of ${session.address}.`,
})
return c.json({ notes: [] })
})
export default app
```
An approval lasts 5 minutes, and verifies once. The page signs it with `dialog.signMessage` , and the error handler answers a failed one with 403, as in [Write SIWE routes](/docs/guides/siwe#write-siwe-routes).
### Accept other chains
`chains` lists the IDs of the chains that a sign-in's message may name, such as the chains of the app's payments. It defaults to the instance's chain, and the challenge route refuses any other.
```ts [server.ts]
import { Accounts, Store } from 'accounts'
import { backend, siwe } from 'accounts/plugins'
import { Hono } from 'hono'
const accounts = Accounts.create({
chain: 'testnet',
clientId: process.env.APP_URL,
plugins: [
backend({ store: Store.memory() }),
siwe({
// Tempo testnet and Tempo mainnet.
chains: [42431, 4217], // [!code hl]
origin: process.env.APP_URL,
statement: 'Sign in to the notes example.',
}),
],
})
const app = new Hono()
app.all('/api/*', (c) => accounts.handler.fetch(c.req.raw))
export default app
```
### Shorten the session
`lifetime` sets how long a SIWE session lasts after its sign-in, in milliseconds. It defaults to one day. The store deletes the session at its expiry, and the user signs the next message.
```ts [server.ts]
import { Accounts, Store } from 'accounts'
import { backend, siwe } from 'accounts/plugins'
import { Hono } from 'hono'
const accounts = Accounts.create({
chain: 'testnet',
clientId: process.env.APP_URL,
plugins: [
backend({ store: Store.memory() }),
siwe({
// A session lasts one hour.
lifetime: 60 * 60 * 1000, // [!code hl]
origin: process.env.APP_URL,
statement: 'Sign in to the notes example.',
}),
],
})
const app = new Hono()
app.all('/api/*', (c) => accounts.handler.fetch(c.req.raw))
export default app
```
### Sign in with another wallet
A wallet that connects first, such as a browser extension, knows its account. Send it as `address` to the challenge route, so only that account signs in. `post` is the helper of [Write SIWE routes](/docs/guides/siwe#write-siwe-routes).
```tsx [SignInWithWallet.tsx]
import { createWalletClient, custom } from 'viem'
import 'viem/window'
async function post(path: string, body: object = {}) {
const response = await fetch(path, {
body: JSON.stringify(body),
headers: { 'content-type': 'application/json' },
method: 'POST',
})
return (await response.json()) as data
}
export function SignInWithWallet() {
return (
{
const wallet = createWalletClient({
transport: custom(window.ethereum!),
})
const [address] = await wallet.requestAddresses()
const { message } = await post<{ message: string }>(
'/api/auth/siwe/challenge',
{ address }, // [!code hl]
)
const signature = await wallet.signMessage({
account: address!,
message,
})
await post('/api/auth/siwe/verify', { address, message, signature })
}}
type="button"
>
Sign in with a wallet
)
}
```
## Next steps
# Local owner keys \[An app holds a Tempo Account's owner key, and signs in without Tempo ID.]
## Overview
The `local` plugin keeps a secp256k1 private key in the instance's [store](/docs/guides/sessions) and makes its account the session's. Each sign-in authorizes an [access key](/docs/guides/access-keys) that the owner key signs, so `viem` , `pay`, and `mpp` send with it as with a Tempo ID sign-in, and the owner key signs only access keys and the app's challenge.
Choose it for a program that holds its own funds, such as a CLI's wallet, a test, or a demo. For a user's account, sign in with Tempo ID\: the user's passkey stays with the user, and only an access key reaches the app.
:::warning
The store keeps the private key as it is, and whoever reads it holds the account. `Store.file` keeps it in a `0600` file. A store that other parties read, such as `Store.postgres` or `Store.redis`, refuses it with `SharedStoreError` .
:::
```ts [tempo.config.ts]
import { Accounts, Store } from 'accounts'
import { local, viem } from 'accounts/plugins'
export const accounts = Accounts.create({
// Each sign-in authorizes an access key that sends up to 100 OUSD for 7 days.
accessKey: () => ({
expiry: '7d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
clientId: 'cli:acme-example',
plugins: [local({ name: 'Acme' }), viem()],
store: Store.file('~/.acme/accounts.json'),
})
```
```ts [index.ts]
import { accounts } from './tempo.config.js'
const session = (await accounts.local.get())
? await accounts.local.signIn()
: await accounts.local.create()
console.log(`Fund ${session.address} to pay.`)
```
An instance with `local` receives no default `dialog` . It can hold `device` or `dialog` beside it, for a program that offers both.
## Actions
| Action | Does |
| ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `local.create()` | Creates an owner key, stores it, and signs in. Throws `ExistsError` while the store holds one |
| `local.signIn()` | Signs in with the stored owner key. A live access key on the chain serves a call without `accessKey`. Throws `MissingError` without an owner key |
| `local.import({ privateKey })` | Stores the private key as the owner key, and signs in |
| `local.get()` | Returns the owner key's address, name, and creation, or `undefined` |
| `local.export()` | Returns the private key, such as for a backup |
| `local.remove()` | Signs out, and deletes the owner key. The account and its funds stay on chain |
Each sign-in takes `accessKey`, the access key's [permissions](/docs/guides/access-keys), else the instance's `accessKey`, else up to 5 OUSD for a day.
## The local session
A local session's `kind` is `'local'`, and its `address` is the owner key's account. Tempo ID issues it no tokens and names no user, so `Session.local` tells it apart\:
```ts
import { Session } from 'accounts'
const session = await accounts.session.get()
if (session && !Session.local(session)) console.log(session.user.email)
```
An instance's session type is `Session.Any` with the `local` plugin, and `Session.Session` without it. It expires with its access keys, since it holds no tokens to refresh. A sign-out keeps the owner key, which the next `local.signIn` takes.
The calls that read Tempo ID throw `Accounts.LocalSessionError` with a local session\: `session.accessToken`, `account.get`, `connections`, the `funding` plugin, and `backend.save`. A backend signs in a local account with `siwe` instead\: `local.signIn` signs its challenge with the owner key, and returns its result as `auth`.
## Migrate from version 0
Version 0's `secp256k1` adapter kept its private key in a `Storage.filesystem` file of `accounts/cli`. With `v0`, the first read of a store without an owner key takes the file's active secp256k1 account, so its address and funds carry over\:
```ts [tempo.config.ts]
export const accounts = Accounts.create({
plugins: [
local({
name: 'Acme',
v0: '~/.acme/wallet.json', // [!code ++]
}),
viem(),
],
store: Store.file('~/.acme/accounts.json'),
})
```
The plugin takes the first secp256k1 account among the file's `.store` entries, whatever v0's storage `key` was. The v0 file stays as it is, and its access keys stay unused\: the owner signs a new one at the first sign-in.
# Guest checkout \[A visitor pays from a guest account, whose key pair the app keeps in its store, with no Tempo ID user.]
## Overview
A guest session signs a visitor in with no Tempo ID user. The instance keeps a P256 key pair in its [store](/docs/guides/user-session/store-sessions), and the key pair owns a root Tempo Account, the guest account.
Tempo ID issues a guest session no tokens and no [access key](/docs/guides/access-keys). The key pair signs each payment and transaction of the visitor in the app. [Guest sessions](https\://github.com/tempoxyz/id/blob/main/docs/guest-checkout.md) describes the side of Tempo ID.
The demo signs a visitor in as a guest, and pays 1 OUSD from the guest account. A new guest account holds no funds, so Deposit on the payment page offers the testnet faucet.
## Walkthrough
These steps build a React app that signs a visitor in as a guest, and takes a payment from the guest account.
::::steps
### Install the packages
:::code-group
```sh [npm]
npm install accounts react react-dom viem
```
```sh [pnpm]
pnpm add accounts react react-dom viem
```
```sh [bun]
bun add accounts react react-dom viem
```
:::
### Create the instance
With `guest: true` , each sign-in offers Continue as guest, beside the passkey and the emailed code. An instance without it never holds a guest session.
In a browser, the default store is IndexedDB. It keeps the key pair as a non-extractable `CryptoKey`.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
guest: true, // [!code hl]
plugins: [react(), viem()],
})
```
### Sign the visitor in
`dialog.signIn` opens the sign-in of Tempo ID. If the visitor selects Continue as guest, the instance loads or creates the key pair, and resolves with a guest session.
A guest session holds the address of the guest account, and its `kind` is `'guest'`. The store keeps the key pair under its own entry, so the session holds no private key.
:::code-group
```tsx [App.tsx]
import { Checkout } from './Checkout.js'
import { accounts } from './tempo.config.js'
export function App() {
const { session } = accounts.useSession()
if (!session)
return (
accounts.dialog.signIn()} type="button">
Sign in with Tempo
)
// [!code hl:start]
const label =
session.kind === 'guest'
? `Guest account ${session.address}`
: `Signed in as ${session.user.email}`
// [!code hl:end]
return (
{label}
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
guest: true,
plugins: [react(), viem()],
})
```
:::
A call that reads Tempo ID, such as a read of the access token, throws `Accounts.GuestSessionError` with a guest session.
### Pay
With a guest session, `accounts.pay` opens the payment page of Tempo ID for the guest account, in a dialog. The visitor selects Pay, and the key pair signs the transfer in the page of the app.
The token is a symbol that the chain lists, such as `ousd`, or the address of a TIP-20 token. The key pair signs one transaction for each call, which makes exactly the requested transfer.
:::code-group
```tsx [Checkout.tsx]
import { useState } from 'react'
import { accounts } from './tempo.config.js'
export function Checkout() {
const [transaction, setTransaction] = useState()
return (
<>
{
// [!code hl:start]
const { transaction } = await accounts.pay({
amount: '5',
to: '0x000000000000000000000000000000000000dEaD',
token: 'ousd',
})
// [!code hl:end]
setTransaction(transaction)
}}
type="button"
>
Pay 5 OUSD
{transaction && Paid in {transaction}.
}
>
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
guest: true,
plugins: [react(), viem()],
})
```
:::
A new guest account holds no funds. If it holds less than the payment, Deposit on the payment page opens the deposit pages of Tempo ID for the guest account.
| Deposit method | For a guest |
| --------------------- | ------------------------------------------------------ |
| Tempo transfer | Offered on every chain, to the guest account's address |
| EVM bridge | Offered on Tempo mainnet, for an OUSD payment |
| Buy MACH | Not offered, since its cards and receipts need a user |
| Swap from the balance | Not offered, since the key pair signs only the payment |
Done returns to the same checkout, and Pay enables once the funds arrive. On a test chain, the deposit pages also offer the faucet of the token.
::::
## Use cases
### Pay without a session
With `guest: true` and no session, `accounts.pay` opens the signed-out payment page, which offers Continue as guest. That selection starts the guest session, and the same page pays from the guest account.
If the visitor signs in instead, the page pays from the account of the user. A call with `challenge`, or an instance with the `siwe` plugin, offers no guest.
:::code-group
```tsx [Checkout.tsx]
import { accounts } from './tempo.config.js'
export function Checkout() {
return (
{
// With no session, the payment page signs the visitor in, or starts a guest session.
const { transaction } = await accounts.pay({
amount: '5',
to: '0x000000000000000000000000000000000000dEaD',
token: 'ousd',
})
console.log(transaction)
}}
type="button"
>
Pay 5 OUSD
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
guest: true,
plugins: [react(), viem()],
})
```
:::
### Offer a guest in each sign-in flow
With `guest: true`, each sign-in plugin offers Continue as guest, and resolves with a guest session after that selection.
| Sign-in | Returns the selection |
| ---------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
| `dialog.signIn` , in a frame or a popup | The frame's or the popup's message |
| `redirect.signIn` | The redirect URI with `guest=1`, which the next load of the page completes |
| `device.signIn` | The refusal `guest_selected` of the next poll, which the plugin turns into the session |
Outside a browser, `Store.file` keeps the key pair in a file that only the user reads. The `expo` preset keeps it in the secure store of the device.
A store that other parties read, such as `Store.postgres` , refuses the key pair. So does `Store.memory` in a page, since a reload loses the funds.
```ts [tempo.config.ts]
import { Accounts, Store } from 'accounts'
import { device } from 'accounts/plugins'
export const accounts = Accounts.create({
chain: 'testnet',
clientId: 'cli:acme-example',
guest: true, // [!code hl]
plugins: [
device({
onCode: (code) =>
console.log(
`Open ${code.verificationUriComplete} and confirm the code ${code.userCode}.`,
),
}),
],
// The key pair of the guest account stays in this file.
store: Store.file('~/.acme/accounts.json'),
})
```
### Sign a guest in to the app
With the `siwe` plugin on the page, `dialog.signIn` offers Continue as guest too. After that selection, the guest key pair signs the plugin's message, and the call posts the signature to the verify route before it sets the guest session.
The call returns the verify route's JSON object as `auth`, as for a Tempo ID sign-in. The guest account is a root Tempo Account, so the route verifies its P256 signature as the account's own. [Sign in with the plugin on the page](/docs/guides/siwe#sign-in-with-the-plugin-on-the-page) describes the routes.
:::code-group
```tsx [SignIn.tsx]
import { accounts } from './tempo.config.js'
export function SignIn() {
return (
{
// A guest or a Tempo ID user, signed in to the app's routes either way.
const { auth } = await accounts.dialog.signIn()
console.log(auth)
}}
type="button"
>
Sign in
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { siwe, viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
guest: true,
plugins: [react(), siwe({ auth: '/api/auth' }), viem()], // [!code hl]
})
```
:::
### Pay from a CLI
Outside a page, `accounts.pay` pays from the guest account through the routes of Tempo ID, with no page. `Actions.guest.pay` describes each request and check.
| Guest account | What `pay` does |
| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| Holds the payment | Pays at once |
| Short, on a test chain | Requests the chain's faucet, then pays |
| Short, on another chain | Passes a funding code to the `device` plugin's `onCode`, waits for the funds until the code expires, then pays |
| Short, without `device` | Rejects with `Accounts.RequestError` and the reason `insufficient_balance` |
If Tempo ID and the chain confirm no outcome, the call rejects with `Actions.guest.PendingError` , which names the checkout. The store keeps no record of the checkout, so the app confirms its outcome before it pays again.
:::code-group
```ts [index.ts]
import { accounts } from './tempo.config.js'
const session = (await accounts.session.get()) ?? (await accounts.device.signIn())
if (session.kind === 'guest') console.log(`Paying as guest ${session.address}.`)
// [!code hl:start]
const { transaction } = await accounts.pay({
amount: '5',
to: '0x000000000000000000000000000000000000dEaD',
token: 'ousd',
})
// [!code hl:end]
console.log(`Paid in ${transaction}.`)
```
```ts [tempo.config.ts]
import { Accounts, Store } from 'accounts'
import { device } from 'accounts/plugins'
export const accounts = Accounts.create({
chain: 'testnet',
clientId: 'cli:acme-example',
guest: true,
plugins: [
device({
// Shows the sign-in code, and the funding code of a short guest account.
onCode: (code) =>
console.log(
`Open ${code.verificationUriComplete} and confirm the code ${code.userCode}.`,
),
}),
],
store: Store.file('~/.acme/accounts.json'),
})
```
:::
### Send a transaction with Viem
The `viem` plugin's client signs each transaction of a guest session with the key pair, as the root account. Its `relay` pays fees as for any session. [Viem](/docs/guides/viem) covers the client.
:::code-group
```tsx [Send.tsx]
import { parseUnits } from 'viem'
import { Addresses } from 'viem/tempo'
import { accounts } from './tempo.config.js'
export function Send() {
return (
{
// [!code hl:start]
const { receipt } = await accounts.viem.token.transferSync({
amount: parseUnits('1', 6),
to: '0x000000000000000000000000000000000000dEaD',
token: Addresses.ousd,
})
// [!code hl:end]
console.log(receipt.transactionHash)
}}
type="button"
>
Send 1 OUSD
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
guest: true,
plugins: [react(), viem()],
})
```
:::
### Pay MPP charges
With a guest session, the `mpp` plugin pays each charge and voucher with the key pair. No access key limits the guest account, so a charge needs `maxAmount` , and a payment session `maxDeposit` .
| Without the cap | Error |
| ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| A charge above 0 | `mpp.MaxAmountRequiredError` , before the key pair signs |
| A payment session | `mpp.MaxDepositRequiredError` , before any request |
| A malformed `maxDeposit` | `mpp.MaxDepositInvalidError` , for a value other than a decimal above 0 with at most 6 decimals |
:::code-group
```tsx [Fortune.tsx]
import { accounts } from './tempo.config.js'
export function Fortune() {
return (
{
const response = await accounts
.mpp({ maxAmount: '0.05' }) // [!code hl]
.fetch('https://api.example.com/fortune')
console.log(await response.json())
}}
type="button"
>
Fetch a fortune
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { mpp } from 'accounts/mpp'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
guest: true,
// Each payment session holds at most 1 OUSD.
plugins: [mpp({ maxDeposit: '1' }), react()],
})
```
:::
### Forget the guest account
`accounts.signOut` ends the guest session and keeps the key pair, so the next guest session holds the same guest account. `accounts.guest.get` returns its address.
`accounts.guest.disconnect` removes the key pair from the store, and signs out a guest session. The funds stay on the address, and no key signs for it again.
:::code-group
```tsx [Forget.tsx]
import { accounts } from './tempo.config.js'
export function Forget() {
return (
{
const address = await accounts.guest.get()
if (!address) return
// The funds of `address` stay there, with no signer.
await accounts.guest.disconnect() // [!code hl]
}}
type="button"
>
Forget the guest account
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
guest: true,
plugins: [react(), viem()],
})
```
:::
## Limitations
* A guest pays only in the token of the payment. A payment that needs a swap shows a shortfall.
* The deposit pages offer a guest no Buy MACH and no swap. The EVM bridge pays only an OUSD payment on Tempo mainnet.
* A guest session holds no access key. It takes no `accessKey` or `challenge` sign-in, and pays no MPP subscription.
* The guest key pair signs the `siwe` plugin's message only in `dialog.signIn`. A payment with the plugin and without a session offers no guest.
* A sign-in through the `backend` plugin never offers a guest.
* A guest account has no passkey and no Tempo ID user. No sign-in turns it into a configurable account.
* Outside a page, a short guest account on a chain without a faucet needs the `device` plugin's `onCode` to show its funding code.
## Next steps
# End-to-end tests \[An app's end-to-end tests sign in with no dialog, and send transactions on Tempo testnet.]
## Overview
A test in a browser cannot sign in through Tempo ID's dialog. The `dialog` plugin of `accounts/test` replaces the `dialog` plugin in a test build. Its sign-in shows no dialog, and sends no request to Tempo ID.
A local Tempo Account signs the key authorization of a new [access key](/docs/guides/access-keys), as Tempo ID's cloud wallet does after a sign-in. The [session](/docs/guides/user-session) then holds the access key, and the app sends transactions on the chain as it does in production.
The demo signs in with the plugin, funds the new Tempo Account from the testnet faucet, and sends 1 OUSD.
:::warning
The session holds a placeholder access token, so each request to Tempo ID fails, such as `accounts.account.get` and `session.fetch`. Import `accounts/test` only in a test build.
:::
## Walkthrough
These steps test a React app built with Vite, with [Playwright](https\://playwright.dev).
::::steps
### Install the packages
`@playwright/test` runs the tests in a browser.
:::code-group
```sh [npm]
npm install accounts react react-dom viem
npm install --save-dev @playwright/test
```
```sh [pnpm]
pnpm add accounts react react-dom viem
pnpm add --save-dev @playwright/test
```
```sh [bun]
bun add accounts react react-dom viem
bun add --dev @playwright/test
```
:::
### Swap the dialog plugin
A build with `VITE_E2E` uses the `dialog` plugin of `accounts/test`. It has the ID `dialog`, so `accounts.dialog.signIn` signs in with it, and the app's code stays the same. Vite replaces `import.meta.env.VITE_E2E` at build time, so a production bundle holds none of `accounts/test`.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { dialog, viem } from 'accounts/plugins'
import { react } from 'accounts/react'
import * as test from 'accounts/test' // [!code ++]
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [
react(),
import.meta.env.VITE_E2E ? test.dialog() : dialog(), // [!code ++]
viem(),
],
})
```
### Sign in from a click
`accounts.dialog.signIn` creates the access key, sets the session, and runs the plugins' `afterSignIn` hooks, as a sign-in in the dialog does. Each sign-in of the same instance signs in the same Tempo Account.
:::code-group
```tsx [App.tsx]
import { accounts } from './tempo.config.js'
export function App() {
const { session } = accounts.useSession()
// [!code hl:start]
if (!session)
return (
accounts.dialog.signIn()} type="button">
Sign in
)
// [!code hl:end]
return Signed in as {session.user.email}
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { dialog, viem } from 'accounts/plugins'
import { react } from 'accounts/react'
import * as test from 'accounts/test'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [
react(),
import.meta.env.VITE_E2E ? test.dialog() : dialog(),
viem(),
],
})
```
:::
### Serve the test build
Playwright's `webServer` builds the app with `VITE_E2E`, and serves the build before the tests run.
```ts [playwright.config.ts]
import { defineConfig } from '@playwright/test'
export default defineConfig({
testDir: 'e2e',
use: { baseURL: 'http://localhost:4173' },
// [!code hl:start]
webServer: {
command: 'VITE_E2E=true vite build && vite preview --port 4173',
url: 'http://localhost:4173',
},
// [!code hl:end]
})
```
### Write the test
The test clicks the app's own button, and reads the session that the page shows.
```ts [e2e/sign-in.test.ts]
import { expect, test } from '@playwright/test'
test('signs in', async ({ page }) => {
await page.goto('/')
await page.getByRole('button', { name: 'Sign in' }).click()
await expect(page.getByText('Signed in as test@example.com')).toBeVisible()
})
```
::::
## Use cases
Each use case sets an option of the `dialog` plugin of `accounts/test`, or of its sign-in, except the last, which signs in through Tempo ID's dialog.
### Use a funded account
`privateKey` names the Tempo Account's private key, such as one that a global setup funded. Without it, each instance signs in a new account, and each page load creates a new instance.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { dialog, viem } from 'accounts/plugins'
import * as test from 'accounts/test'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [
import.meta.env.VITE_E2E
? test.dialog({ privateKey: import.meta.env.VITE_E2E_PRIVATE_KEY }) // [!code hl]
: dialog(),
viem(),
],
})
```
:::warning
A build holds the private key in its bundle. Use an account that holds only testnet funds.
:::
### Name the user
`user` sets the signed-in user. Without it, the email is `test@example.com`, and the ID is `test:` followed by the account's address.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { dialog } from 'accounts/plugins'
import * as test from 'accounts/test'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [
import.meta.env.VITE_E2E
? test.dialog({ user: { email: 'ada@example.com', id: 'user_ada' } }) // [!code hl]
: dialog(),
],
})
```
### Request an access key without bounds
`accessKey` of a sign-in names the access key's permissions, in place of the instance's. An access key with `scopes: 'any'` and no `limits` makes any call and spends any amount, so a test needs no new access key for each contract. Tempo ID refuses such an access key on a page, so only a test build requests it.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { dialog, viem } from 'accounts/plugins'
import * as test from 'accounts/test'
export const accounts = Accounts.create({
// [!code hl:start]
accessKey: import.meta.env.VITE_E2E
? { expiry: '1h', scopes: 'any' }
: { expiry: '1d', limits: [{ limit: '100', token: 'ousd' }] },
// [!code hl:end]
chain: 'testnet',
plugins: [import.meta.env.VITE_E2E ? test.dialog() : dialog(), viem()],
})
```
### Turn off the retry of transactions
The `viem` plugin's `retry` signs in again for a refused transaction, such as a transfer above the limit. That sign-in opens Tempo ID's dialog, which a test cannot complete. A test build sets `retry: false`, so the transaction rejects with the node's error.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { dialog, viem } from 'accounts/plugins'
import * as test from 'accounts/test'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [
import.meta.env.VITE_E2E ? test.dialog() : dialog(),
viem({ retry: !import.meta.env.VITE_E2E }), // [!code hl]
],
})
```
### Sign in without an access key
`accessKey: false` signs in with no access key. The session still holds the Tempo Account, which signs nothing.
```tsx [SignIn.tsx]
import { accounts } from './tempo.config.js'
export function SignIn() {
return (
accounts.dialog.signIn({ accessKey: false })} // [!code hl]
type="button"
>
Sign in
)
}
```
### Connect wagmi
The `tempoId` connector takes the plugin among its `plugins`. Its `connect` signs in with the plugin's `dialog.signIn`.
```ts [config.ts]
import { dialog } from 'accounts/plugins'
import * as test from 'accounts/test'
import { tempoId } from 'accounts/wagmi'
import { tempoModerato } from 'viem/tempo/chains'
import { createConfig, http } from 'wagmi'
export const config = createConfig({
chains: [tempoModerato],
connectors: [
tempoId({
plugins: [import.meta.env.VITE_E2E ? test.dialog() : dialog()], // [!code hl]
}),
],
transports: { [tempoModerato.id]: http() },
})
```
### Sign in at a local Tempo ID
A test that covers Tempo ID's dialog itself signs in at an `id-dev` instance of Tempo ID, whose inbox returns each sign-in code. `accounts/test/playwright` holds the selectors of the dialog. `dialog` returns the dialog's frame once it holds still, `signIn` completes the sign-in form, and `code` reads the inbox.
```ts [e2e/dialog.test.ts]
import { expect, test } from '@playwright/test'
import { code, dialog, signIn } from 'accounts/test/playwright'
test('signs in through the dialog', async ({ page }) => {
const email = `test+${crypto.randomUUID()}@example.org`
await page.goto('/')
await page.getByRole('button', { name: 'Sign in' }).click()
// [!code hl:start]
await signIn(await dialog(page), {
code: (email) => code({ email, url: 'http://localhost:8787' }),
email,
})
// [!code hl:end]
await expect(page.getByText(`Signed in as ${email}`)).toBeVisible()
})
```
## Next steps
# Access keys \[An access key signs for the user's Tempo Account within limits that the user approves.]
## Overview
An access key signs transactions for the user's Tempo Account with no wallet prompt. The account owner approves it once on Tempo ID's approval page, with a spending limit and an expiry. The chain refuses each transfer above the limit.
An app needs an access key to send [payments](/docs/guides/payments), pay [subscriptions](/docs/guides/subscriptions), or send transactions with [Viem](/docs/guides/viem). An app that only signs users in needs none.
## Guides
# Authorize access keys \[Name what an access key may spend and when it expires, and request it at sign-in or later.]
## Overview
An access key signs for the user's Tempo Account within the limits and the expiry that the user approves on Tempo ID's approval page. An app requests it at sign-in, or later for a signed-in user, such as at the first payment. The [session](/docs/guides/user-session) then holds the access key.
| Request | Call | Tempo ID shows |
| ----------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------- |
| [At sign-in](/docs/guides/access-keys/authorize-access-keys#request-the-access-key-at-sign-in) | `dialog.signIn` , with the instance's `accessKey` | The sign-in and the approval page |
| [After sign-in](/docs/guides/access-keys/authorize-access-keys#authorize-an-access-key-after-sign-in) | `dialog.signIn` , with the call's `accessKey` | Only the approval page |
| [After sign-in, in a first-party app](/docs/guides/access-keys/authorize-access-keys#authorize-with-no-page-in-a-first-party-app) | `accounts.authorize` | No page |
The demo signs a user in with an access key of the selected limit and expiry, then authorizes a new access key for the signed-in user.
## Walkthrough
The [`web`](https\://github.com/tempoxyz/accounts/tree/main/examples/web) example runs these steps in a React app.
::::steps
### Name the permissions
The `accessKey` option of `Accounts.create` returns each sign-in's permissions. A duration counts from the sign-in, and a limit is in the token's units.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [react()],
})
```
| Property | Value |
| ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `expiry` | A duration, or Unix seconds. Absent, Tempo ID fills its [default expiry](https\://github.com/tempoxyz/id/blob/main/docs/permissions.md#default-expiry) |
| `limits` | The amount of each token that the access key may spend, in total or for each `period` |
| `scopes` | The calls that the access key may make. Absent, the package fills transfers of each token of the limits |
Tempo ID refuses an [access key without bounds](https\://github.com/tempoxyz/id/blob/main/docs/permissions.md#access-keys-without-bounds), such as one without `limits` .
### Request the access key at sign-in
Call `dialog.signIn` in a click handler, since a popup opens only within a user gesture. If the user approves the limits and the expiry on Tempo ID's approval page, the call returns the session.
:::code-group
```tsx [SignIn.tsx]
import { accounts } from './tempo.config.js'
export function SignIn() {
return (
accounts.dialog.signIn()} type="button">
Sign in with Tempo
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [react()],
})
```
:::
If the user denies the access key, the call rejects with `Accounts.RequestError` , whose `code` is `access_denied`.
### Read the access key
`Permissions.fromAccessKey` returns the key authorization's limits and scopes, with each limit in base units.
:::code-group
```tsx [App.tsx]
import { Permissions } from 'accounts'
import { formatUnits } from 'viem'
import { accounts } from './tempo.config.js'
export function App() {
const { session } = accounts.useSession()
if (!session?.accessKey)
return (
accounts.dialog.signIn()} type="button">
Sign in with Tempo
)
const { account, keyAuthorization } = session.accessKey
const { limits } = Permissions.fromAccessKey(session.accessKey) // [!code hl]
// The expiry is in Unix seconds.
const expiry = new Date(Number(keyAuthorization.expiry) * 1000)
return (
Tempo Account {account}
Access key {keyAuthorization.keyId}
Expires {expiry.toLocaleString()}
{limits?.map((entry) => (
Sends up to {formatUnits(BigInt(entry.limit), 6)} of {entry.token}
))}
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [react()],
})
```
:::
::::
## Use cases
Each use case sets one property of the `Permissions` that `accessKey` returns, or requests the access key with another call.
### Authorize an access key after sign-in
An app can sign a user in without an access key, and request one at the first payment. An instance with `accessKey` set to `false` requests none at sign-in. Without it, each sign-in requests an access key that may transfer up to 5 OUSD for a day. For one sign-in without an access key, pass `false` as the sign-in's `accessKey` .
A second button calls `dialog.signIn` with `accessKey` , which overrides the instance's. The user holds a Tempo ID session, so the dialog opens on the approval page only, and the returned session replaces the instance's session.
:::code-group
```tsx [App.tsx]
import { Permissions } from 'accounts'
import { accounts } from './tempo.config.js'
// Sends up to 10 OUSD each day, for 30 days.
const daily = Permissions.from({
expiry: '30d',
limits: [{ limit: '10', period: '1d', token: 'ousd' }],
})
export function App() {
const { session } = accounts.useSession()
if (!session)
return (
accounts.dialog.signIn()} type="button">
Sign in with Tempo
)
// [!code hl:start]
if (!session.accessKey)
return (
accounts.dialog.signIn({ accessKey: daily })}
type="button"
>
Authorize payments
)
// [!code hl:end]
return Tempo Account {session.accessKey.account}
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
accessKey: false,
chain: 'testnet',
plugins: [react()],
})
```
:::
### Authorize with no page in a first-party app
`accounts.authorize` requests an access key for the browser's Tempo ID session, and shows no page. The access key must fit the [headless ceiling](https\://github.com/tempoxyz/id/blob/main/docs/permissions.md#headless-ceiling), unless the app holds the `tempo-id:sign` scope. A third-party app receives the reason `rejected`, so the handler falls back to the dialog.
:::code-group
```tsx [Authorize.tsx]
import { Accounts, Permissions } from 'accounts'
import { accounts } from './tempo.config.js'
const permissions = Permissions.from({
expiry: '1d',
limits: [{ limit: '10', token: 'ousd' }],
})
export function Authorize() {
async function authorize() {
try {
await accounts.authorize({ accessKey: permissions }) // [!code hl]
} catch (error) {
if (
!(error instanceof Accounts.RequestError) ||
error.reason !== 'rejected'
)
throw error
await accounts.dialog.signIn({ accessKey: permissions })
}
}
return (
Authorize payments
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({ chain: 'testnet', plugins: [react()] })
```
:::
Without a Tempo ID session, the call returns `undefined`, and empties the instance's session.
### Sign with a passkey on the page
If a passkey owns the Tempo Account, `accounts.authorize` rejects with the reason `webauthn_required`. With `passkey` set to `true`, the passkey's ceremony runs on the page, so the call needs a click.
:::code-group
```tsx [Authorize.tsx]
import { Permissions } from 'accounts'
import { accounts } from './tempo.config.js'
const permissions = Permissions.from({
expiry: '1d',
limits: [{ limit: '10', token: 'ousd' }],
})
export function Authorize() {
return (
accounts.authorize({ accessKey: permissions, passkey: true }) // [!code hl]
}
type="button"
>
Authorize payments
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({ chain: 'testnet', plugins: [react()] })
```
:::
### Reset a limit each period
`period` resets a limit after each period, such as each day. Without it, the limit is a total for the life of the access key.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
accessKey: () => ({
expiry: '30d',
limits: [{ limit: '10', period: '1d', token: 'ousd' }], // [!code hl]
}),
chain: 'testnet',
plugins: [react()],
})
```
### Approve a spender
`spenders` names the contracts that the access key may approve to spend the token. Without it, the filled scopes hold no approval.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
accessKey: () => ({
expiry: '1d',
limits: [
{
limit: '100',
spenders: ['0x000000000000000000000000000000000000bEEF'], // [!code hl]
token: 'ousd',
},
],
}),
chain: 'testnet',
plugins: [react()],
})
```
### Name the scopes
Named `scopes` , built with Viem's `Scopes`, replace the filled ones. This access key sends OUSD to one recipient only.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
import { Addresses, Scopes } from 'viem/tempo'
export const accounts = Accounts.create({
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
// [!code hl:start]
scopes: [
Scopes.tip20(Addresses.ousd).transfer({
recipients: ['0x000000000000000000000000000000000000dEaD'],
}),
],
// [!code hl:end]
}),
chain: 'testnet',
plugins: [react()],
})
```
### Pay fees without a stablecoin limit
Tempo charges an access key's fees to its limit of the fee token, so limits without a stablecoin, such as MACH alone, pay no fee. For such limits with named `scopes` , the package adds a fee allowance\: 0.1 of each fee stablecoin on the chain, which no scope can send.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
import { Scopes } from 'viem/tempo'
const mach = '0x20c000000000000000000000f37de3740adec032'
export const accounts = Accounts.create({
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '2', token: 'mach' }], // [!code hl]
scopes: [Scopes.tip20(mach).transferWithMemo()], // [!code hl]
}),
chain: 'testnet',
plugins: [react()],
})
```
Filled scopes receive no allowance, since they call the payment channel reserve, which could spend it. Without named scopes, add a stablecoin limit that holds the fees.
## Next steps
# Revoke access keys \[Change the limits of an access key, or revoke it, on Tempo ID's approval page.]
## Overview
The chain accepts a change to an [access key](/docs/guides/access-keys) only from the account owner. An app thus changes or revokes its own access key on Tempo ID's approval page, in the dialog, where the owner signs.
The demo signs a user in with an access key that sends up to 10 OUSD, then lowers the limit to 5 OUSD or revokes the access key.
## Walkthrough
::::steps
### Sign the user in with an access key
The `viem` plugin adds the transaction actions of the last step.
:::code-group
```tsx [App.tsx]
import { accounts } from './tempo.config.js'
export function App() {
const { session } = accounts.useSession()
if (!session?.accessKey)
return (
accounts.dialog.signIn()} type="button">
Sign in with Tempo
)
return Tempo Account {session.accessKey.account}
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '10', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [react(), viem()],
})
```
:::
### Change the limits
`dialog.updateAccessKey` returns the hash of the change's transaction. Each limit sets the amount that the access key can still spend, in base units, and keeps its period. A token that the list leaves out keeps its limit. A negative limit, or two limits on one token, throws `Accounts.RequestError` with `invalid_field` before the dialog opens.
:::code-group
```tsx [AccessKey.tsx]
import { useState } from 'react'
import { parseUnits } from 'viem'
import { Addresses } from 'viem/tempo'
import { accounts } from './tempo.config.js'
export function AccessKey() {
const [status, setStatus] = useState()
async function change() {
// [!code hl:start]
const { transaction } = await accounts.dialog.updateAccessKey({
limits: [{ limit: parseUnits('5', 6), token: Addresses.ousd }],
})
// [!code hl:end]
setStatus(`Changed in ${transaction}.`)
}
return (
<>
Lower the limit to 5 OUSD
{status}
>
)
}
```
```tsx [App.tsx]
import { AccessKey } from './AccessKey.js'
import { accounts } from './tempo.config.js'
export function App() {
const { session } = accounts.useSession()
if (!session?.accessKey)
return (
accounts.dialog.signIn()} type="button">
Sign in with Tempo
)
return // [!code hl]
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '10', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [react(), viem()],
})
```
:::
The app renders the access key component once the user signs in. The later steps grow that component.
### Revoke the access key
A second button of the same component calls `dialog.revokeAccessKey` . The returned transaction is `null` if the chain already held the access key revoked.
:::code-group
```tsx [AccessKey.tsx]
import { useState } from 'react'
import { parseUnits } from 'viem'
import { Addresses } from 'viem/tempo'
import { accounts } from './tempo.config.js'
export function AccessKey() {
const [status, setStatus] = useState()
async function change() {
const { transaction } = await accounts.dialog.updateAccessKey({
limits: [{ limit: parseUnits('5', 6), token: Addresses.ousd }],
})
setStatus(`Changed in ${transaction}.`)
}
// [!code hl:start]
async function revoke() {
const { transaction } = await accounts.dialog.revokeAccessKey()
setStatus(transaction ? `Revoked in ${transaction}.` : 'Revoked before.')
}
// [!code hl:end]
return (
<>
Lower the limit to 5 OUSD
Revoke the access key
{status}
>
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '10', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [react(), viem()],
})
```
:::
The session stays, but its access key signs no further transaction.
### Handle a refused change
**Cancel** rejects each call with `Accounts.RequestError` , whose `code` is `access_denied`. A closed dialog rejects with an `AbortError`.
:::code-group
```tsx [AccessKey.tsx]
import { Accounts } from 'accounts'
import { useState } from 'react'
import { parseUnits } from 'viem'
import { Addresses } from 'viem/tempo'
import { accounts } from './tempo.config.js'
export function AccessKey() {
const [status, setStatus] = useState()
async function change() {
const { transaction } = await accounts.dialog.updateAccessKey({
limits: [{ limit: parseUnits('5', 6), token: Addresses.ousd }],
})
setStatus(`Changed in ${transaction}.`)
}
async function revoke() {
// [!code hl:start]
try {
const { transaction } = await accounts.dialog.revokeAccessKey()
setStatus(transaction ? `Revoked in ${transaction}.` : 'Revoked before.')
} catch (error) {
if (
error instanceof Accounts.RequestError &&
error.code === 'access_denied'
)
return setStatus('The access key stays.')
throw error
}
// [!code hl:end]
}
return (
<>
Lower the limit to 5 OUSD
Revoke the access key
{status}
>
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '10', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [react(), viem()],
})
```
:::
### Handle a revoked access key
If the node refuses a revoked access key's transaction, the `viem` plugin signs in for a new access key with the same limits and scopes, and sends again. If the user closes that sign-in, the call rejects with `Plugins.viem.RetryClosedError` , matched by its name.
:::code-group
```tsx [Send.tsx]
import { useState } from 'react'
import { parseUnits } from 'viem'
import { Addresses } from 'viem/tempo'
import { accounts } from './tempo.config.js'
export function Send() {
const [status, setStatus] = useState()
async function send() {
try {
await accounts.token.transferSync({
amount: parseUnits('1', 6),
to: '0x000000000000000000000000000000000000dEaD',
token: Addresses.ousd,
})
} catch (error) {
// [!code hl:start]
if (
error instanceof Error &&
error.name === 'Plugins.viem.RetryClosedError'
)
return setStatus('The transaction did not send.')
// [!code hl:end]
throw error
}
}
return (
<>
Send 1 OUSD
{status}
>
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '10', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [react(), viem()],
})
```
:::
::::
## Use cases
Each use case sets one option of `dialog.updateAccessKey` or `dialog.revokeAccessKey` , or of the `viem` plugin.
### Change the scopes
`scopes` replaces the calls that the access key may make. Without it, the scopes stay.
:::code-group
```tsx [Scopes.tsx]
import { Addresses, Scopes } from 'viem/tempo'
import { accounts } from './tempo.config.js'
export function ChangeScopes() {
async function change() {
// [!code hl:start]
await accounts.dialog.updateAccessKey({
scopes: [
Scopes.tip20(Addresses.ousd).transfer({
recipients: ['0x000000000000000000000000000000000000dEaD'],
}),
],
})
// [!code hl:end]
}
return (
Send to one recipient only
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '10', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [react(), viem()],
})
```
:::
### Show the approval page in a popup
`mode: 'popup'` shows the approval page in a popup window, with no frame. A popup opens only within a click. Without it, the call takes the plugin's `mode` .
:::code-group
```tsx [Revoke.tsx]
import { accounts } from './tempo.config.js'
export function Revoke() {
return (
accounts.dialog.revokeAccessKey({ mode: 'popup' })} // [!code hl]
type="button"
>
Revoke the access key
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '10', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [react(), viem()],
})
```
:::
### Cancel a revocation
`signal` ends a change or a revocation from the page, such as after a time limit. Its abort closes the dialog or the popup, and rejects the call with the signal's reason.
:::code-group
```tsx [Revoke.tsx]
import { accounts } from './tempo.config.js'
export function Revoke() {
return (
accounts.dialog.revokeAccessKey({
// The dialog closes after two minutes without an approval.
signal: AbortSignal.timeout(120_000), // [!code hl]
})
}
type="button"
>
Revoke the access key
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '10', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [react(), viem()],
})
```
:::
### Reject in place of a new sign-in
The `viem` plugin's `retry` , with `accessKey` set to `false`, turns off the sign-in for a new access key. The transaction then rejects with the node's refusal, `KeyAlreadyRevoked`.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '10', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [react(), viem({ retry: { accessKey: false } })], // [!code hl]
})
```
### Revoke an access key that a server holds
Each call takes the `accessKey` and `account` of another of the app's access keys. An access key on several other chains also needs `chainId` .
:::code-group
```tsx [Revoke.tsx]
import { accounts } from './tempo.config.js'
export function Revoke() {
async function revoke() {
// [!code hl:start]
await accounts.dialog.revokeAccessKey({
accessKey: '0x9f10aF4d1a3F1a2bD3C6f1B8e7a5D2c4E6b80f08',
account: '0xe8Eb65558c6c437bC38F07cF0D66CF74E87fD946',
})
// [!code hl:end]
}
return (
Revoke the server's access key
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '10', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [react(), viem()],
})
```
:::
If Tempo ID did not sign that access key for the app, the call rejects with [`unknown_key`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#unknown_key).
## Next steps
# Bind challenges \[Bind a server's challenge to an access key at sign-in, so the server knows the access key that signs.]
## Overview
A sign-in can carry a server's [challenge](https\://github.com/tempoxyz/id/blob/main/docs/challenges.md), whose EIP-191 hash the key authorization holds as its [witness](https\://github.com/tempoxyz/id/blob/main/docs/witnesses.md). The account owner's one signature thus proves to the server which [access key](/docs/guides/access-keys) the user authorized for the app.
The demo requests a challenge from a route of the site, signs a user in with it, and sends the key authorization to a second route, which verifies it.
## Walkthrough
::::steps
### Issue the challenge
The message names the server's origin and a nonce, and the store keeps it for five minutes. Tempo ID's approval page shows it to the user.
:::note
`Store.memory` keeps the challenges in the process, so a restart loses them. In production, use a store that each replica shares, such as `Store.postgres` or `Store.redis` .
:::
```ts [server.ts]
import { Store } from 'accounts'
import { Hono } from 'hono'
const challenges = Store.memory()
const app = new Hono()
app.post('/challenge', async (c) => {
const id = crypto.randomUUID()
const challenge = `app.example asks for proof of this sign-in.\n\nNonce: ${id}`
await challenges.setItem(id, challenge, { expiresAt: Date.now() + 300_000 })
return c.json({ challenge, id })
})
export default app
```
### Bind the challenge at sign-in
The click requests the challenge, and passes it to the sign-in as `challenge` .
:::code-group
```tsx [App.tsx]
import { useState } from 'react'
import { accounts } from './tempo.config.js'
type Issued = { challenge: string; id: string }
type Proven = { accessKey: string; account: string }
export function App() {
const [proven, setProven] = useState()
async function signIn() {
// [!code hl:start]
const response = await fetch('/challenge', { method: 'POST' })
const issued: Issued = await response.json()
const session = await accounts.dialog.signIn({
challenge: issued.challenge,
})
// [!code hl:end]
}
if (proven) return The server verified access key {proven.accessKey}.
return (
Sign in with Tempo
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '10', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [react()],
})
```
:::
### Send the proof
`session.fetch` posts the signed key authorization with the session's [access token](/docs/guides/api-authentication/authenticate-requests). The access key itself never leaves the page.
:::code-group
```tsx [App.tsx]
import { useState } from 'react'
import { accounts } from './tempo.config.js'
type Issued = { challenge: string; id: string }
type Proven = { accessKey: string; account: string }
export function App() {
const [proven, setProven] = useState()
async function signIn() {
const challenge = await fetch('/challenge', { method: 'POST' })
const issued: Issued = await challenge.json()
const session = await accounts.dialog.signIn({
challenge: issued.challenge,
})
// [!code hl:start]
const response = await accounts.session.fetch({
init: {
body: JSON.stringify({
id: issued.id,
keyAuthorization: session.accessKey!.keyAuthorization,
}),
headers: { 'content-type': 'application/json' },
method: 'POST',
},
url: '/verify',
})
setProven(await response.json())
// [!code hl:end]
}
if (proven) return The server verified access key {proven.accessKey}.
return (
Sign in with Tempo
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '10', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [react()],
})
```
:::
### Verify the proof
The store's `takeItem` reads and deletes the challenge atomically, so each challenge verifies at most once.
The `tokens` plugin accepts only the access tokens of the app's own client ID. `tokens.verifyChallenge` then checks the witness, that the token names the access key, and the owner's signature, on the instance's chain.
```ts [server.ts]
import { Accounts, Challenge, Store } from 'accounts'
import { tokens } from 'accounts/plugins'
import { Hono } from 'hono'
// [!code hl:start]
const accounts = Accounts.create({
chain: 'testnet',
clientId: 'https://app.example',
plugins: [tokens()],
})
// [!code hl:end]
const challenges = Store.memory()
const app = new Hono()
app.post('/challenge', async (c) => {
const id = crypto.randomUUID()
const challenge = `app.example asks for proof of this sign-in.\n\nNonce: ${id}`
await challenges.setItem(id, challenge, { expiresAt: Date.now() + 300_000 })
return c.json({ challenge, id })
})
// [!code hl:start]
app.post('/verify', async (c) => {
const { id, keyAuthorization } = await c.req.json()
const token = await accounts.tokens.verifyAccessToken(c.req.raw)
if (!token) return c.json({ error: 'invalid_token' }, 401)
// The chain spends no witness, so the server spends the challenge.
const challenge = await challenges.takeItem?.(id)
if (typeof challenge !== 'string')
return c.json({ error: 'invalid_request' }, 400)
try {
const { accessKey, account } = await accounts.tokens.verifyChallenge({
accessToken: token,
challenge,
keyAuthorization,
})
return c.json({ accessKey, account })
} catch (error) {
if (error instanceof Challenge.InvalidError)
return c.json({ error: 'invalid_proof' }, 400)
throw error
}
})
// [!code hl:end]
export default app
```
:::warning
Any app may set an access key's witness, so the witness and the signature alone also accept an access key that another app requested with the same challenge. Only the access token binds the proof to the app, so `tokens.verifyChallenge` takes the verified token, and rejects for a plugin whose `clientIds` is `'any'`.
:::
::::
## Use cases
Each use case passes the `challenge` of a sign-in in another form, or to another call.
### Fetch the challenge after the dialog opens
A function as `challenge` fetches the message after the dialog or the popup opens. The click thus opens a popup also where the page cannot frame the dialog, since no request runs before it.
:::code-group
```tsx [App.tsx]
import { accounts } from './tempo.config.js'
type Issued = { challenge: string; id: string }
export function App() {
async function signIn() {
const issued: Issued[] = []
const session = await accounts.dialog.signIn({
// [!code hl:start]
challenge: async (signal) => {
const response = await fetch('/challenge', { method: 'POST', signal })
issued.push(await response.json())
return issued[0]!.challenge
},
// [!code hl:end]
})
await accounts.session.fetch({
init: {
body: JSON.stringify({
id: issued[0]!.id,
keyAuthorization: session.accessKey!.keyAuthorization,
}),
headers: { 'content-type': 'application/json' },
method: 'POST',
},
url: '/verify',
})
}
return (
Sign in with Tempo
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '10', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [react()],
})
```
:::
### Bind a challenge with no page
`accounts.authorize` takes a `challenge` too, and shows no page. Only a [first-party app](https\://github.com/tempoxyz/id/blob/main/docs/apps.md#first-party-apps) with the `tempo-id:sign` scope may send it, and the call returns `undefined` without a Tempo ID session.
:::code-group
```tsx [App.tsx]
import { accounts } from './tempo.config.js'
type Issued = { challenge: string; id: string }
export function App() {
async function authorize() {
const response = await fetch('/challenge', { method: 'POST' })
const issued: Issued = await response.json()
const session = await accounts.authorize({ challenge: issued.challenge }) // [!code hl]
if (!session?.accessKey) return
await accounts.session.fetch({
init: {
body: JSON.stringify({
id: issued.id,
keyAuthorization: session.accessKey.keyAuthorization,
}),
headers: { 'content-type': 'application/json' },
method: 'POST',
},
url: '/verify',
})
}
return (
Prove the access key
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '10', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [react()],
})
```
:::
## Next steps
# Connections \[An API pays for a user with an access key that it holds for one connection.]
## Overview
A connection is an OAuth grant of one user, through one app, to one API, such as a paid MCP server. The API, not the app, holds the [access key](/docs/guides/access-keys), and pays from the user's Tempo Account within the limits that the user approved.
An API uses connections if it charges the user for its own work, and the app only calls it. If the app itself pays, the app's own access key signs, as [Payments](/docs/guides/payments) shows.
## Guides
# Pay for users \[An API pays for a user with an access key that it holds for one connection.]
## Overview
A connection is an OAuth grant of one user, through one app, to one API, such as a paid MCP server. The API, not the app, holds the [access key](/docs/guides/access-keys), and pays from the user's Tempo Account within the limits that the user approved. The app holds only an [access token](/docs/guides/api-authentication/authenticate-requests) for the API.
Tempo ID discovers the API from metadata that the API publishes, with no registration. These terms name its parts\:
| Term | Meaning |
| ------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- |
| [Discovered resource](https\://github.com/tempoxyz/id/blob/main/docs/resources.md#discovered-resources) | An API that Tempo ID knows by its RFC 8707 identifier, such as `https://api.example/pay` |
| [Access key policy](https\://github.com/tempoxyz/id/blob/main/docs/api-access-keys.md#access-key-policy) | The API's OAuth app, and the limits of each access key that the API holds |
| Connection | One user's approval of one app for the resource |
The approval reaches the API inside the access token. The API redeems the token at Tempo ID with its own client authentication, as in a token exchange, for the key authorization of an access key that it generated\:
```mermaid
sequenceDiagram
participant App
participant ID as Tempo ID
participant API
participant Chain as Tempo chain
App->>ID: Sign in, with resource
Note over ID: The user approves the policy's limits
ID-->>App: Access token, with the resource as aud
App->>API: Request, with the access token
API->>ID: Redeem the token, with a new access key's public key
ID-->>API: Signed key authorization
API->>Chain: Transaction signed by the access key
```
The demo signs a user in for this site's API, which then pays 1 OUSD on Tempo testnet with the access key that it holds for the connection.
## Walkthrough
The steps build the app that opens a connection, then the API with Hono.
::::steps
### Install the packages
:::code-group
```sh [npm]
npm install accounts hono react react-dom viem
```
```sh [pnpm]
pnpm add accounts hono react react-dom viem
```
```sh [bun]
bun add accounts hono react react-dom viem
```
:::
### Sign the user in for the API
In the app, name the resource in the sign-in. The user's approval of the policy's limits authorizes the API's access key.
:::code-group
```tsx [App.tsx]
import { accounts } from './tempo.config.js'
export function App() {
const { session } = accounts.useSession()
if (!session)
return (
accounts.dialog.signIn({
mode: 'popup',
resource: 'https://api.example/pay', // [!code hl]
})
}
type="button"
>
Sign in with Tempo
)
return Signed in as {session.user.email}
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
accessKey: false,
chain: 'testnet',
plugins: [react()],
})
```
:::
Tempo ID approves a connection only on its own page, so the sign-in sets `mode` to `'popup'`, which opens it in a window. Each access token of the [session](/docs/guides/user-session) names the API as its audience. With `accessKey` set to `false`, the app requests no access key of its own.
### Call the API
`session.fetch` sends the request with the session's access token.
:::code-group
```tsx [Pay.tsx]
import { accounts } from './tempo.config.js'
export function Pay() {
return (
{
// [!code hl:start]
const response = await accounts.session.fetch({
init: { method: 'POST' },
url: 'https://api.example/pay',
})
// [!code hl:end]
console.log(await response.json())
}}
type="button"
>
Pay 1 OUSD
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
accessKey: false,
chain: 'testnet',
plugins: [react()],
})
```
:::
### Store the connections
`connections` names the resource and the store of the connections. Its `metadata` names the access key policy and the private key of the API's app, an ES256 JWK with a `kid` that only the API's server holds.
The private key is a long-lived secret, like a client secret. Generate it once, and store `privateKey` as the API's `API_PRIVATE_KEY` secret. The app's document publishes only its public half. Keep `publicKey` for a later rotation.
```ts [generate-key.ts]
import { Base64, Bytes, P256 } from 'ox'
const privateKey = P256.randomPrivateKey()
const { x, y } = P256.getPublicKey({ privateKey })
const base64 = (value: bigint) =>
Base64.fromBytes(Bytes.fromNumber(value, { size: 32 }), {
pad: false,
url: true,
})
const publicKey = {
alg: 'ES256',
crv: 'P-256',
kid: crypto.randomUUID(),
kty: 'EC',
x: base64(x),
y: base64(y),
}
console.log({
privateKey: JSON.stringify({
...publicKey,
d: Base64.fromHex(privateKey, { pad: false, url: true }),
}),
publicKey: JSON.stringify(publicKey),
})
```
```sh
npm install ox
node generate-key.ts
```
`accounts.handler` serves the API's [protected resource metadata](https\://www.rfc-editor.org/rfc/rfc9728) with the policy, and the [metadata document](https\://github.com/tempoxyz/id/blob/main/docs/apps.md#api-apps) of its app. The instance authenticates as that app, with client assertions that the private key signs.
:::note
`Store.memory` keeps the connections and their access keys in the process, so a restart loses them. In production, use a store that each replica shares, such as `Store.postgres` or `Store.redis` .
:::
```ts [api.ts]
import { Accounts, Store } from 'accounts'
import { viem } from 'accounts/plugins'
import { Hono } from 'hono'
const accounts = Accounts.create({
chain: 'testnet',
connections: {
metadata: {
accessKey: { limits: [{ limit: '25', token: 'ousd' }] },
privateKey: JSON.parse(process.env.API_PRIVATE_KEY!),
},
resource: 'https://api.example/pay',
store: Store.memory(),
},
plugins: [viem()],
})
const app = new Hono()
app.all('/api/*', (c) => accounts.handler.fetch(c.req.raw))
app.get('/.well-known/oauth-protected-resource/*', (c) =>
accounts.handler.fetch(c.req.raw),
)
export default app
```
At the first sign-in that names the resource, Tempo ID reads the metadata and stores the policy, with no registration. It reads the metadata again after 5 minutes, at the next sign-in. The approval page names the API by its host.
The store holds each access key's private key, so it stays on the server. Route every request of a connection to one process, since the instance serializes them in memory.
### Read the access token
The route reads the Bearer token that `session.fetch` sends.
```ts [api.ts]
import { Accounts, Store } from 'accounts'
import { viem } from 'accounts/plugins'
import { Hono } from 'hono'
const accounts = Accounts.create({
chain: 'testnet',
connections: {
metadata: {
accessKey: { limits: [{ limit: '25', token: 'ousd' }] },
privateKey: JSON.parse(process.env.API_PRIVATE_KEY!),
},
resource: 'https://api.example/pay',
store: Store.memory(),
},
plugins: [viem()],
})
const app = new Hono()
app.all('/api/*', (c) => accounts.handler.fetch(c.req.raw))
app.get('/.well-known/oauth-protected-resource/*', (c) =>
accounts.handler.fetch(c.req.raw),
)
app.post('/pay', async (c) => {
const accessToken = c.req.header('authorization')?.replace(/^Bearer /, '') // [!code hl]
if (!accessToken) return c.json({ error: 'invalid_token' }, 401) // [!code hl]
return c.json({})
})
export default app
```
### Redeem the connection
`connections.connect` verifies the access token, and returns the connection. The first request generates an access key, and redeems the approval for its key authorization. Later requests read the store, with no call to Tempo ID.
```ts [api.ts]
import { Accounts, Store } from 'accounts'
import { viem } from 'accounts/plugins'
import { Hono } from 'hono'
const accounts = Accounts.create({
chain: 'testnet',
connections: {
metadata: {
accessKey: { limits: [{ limit: '25', token: 'ousd' }] },
privateKey: JSON.parse(process.env.API_PRIVATE_KEY!),
},
resource: 'https://api.example/pay',
store: Store.memory(),
},
plugins: [viem()],
})
const app = new Hono()
app.all('/api/*', (c) => accounts.handler.fetch(c.req.raw))
app.get('/.well-known/oauth-protected-resource/*', (c) =>
accounts.handler.fetch(c.req.raw),
)
app.post('/pay', async (c) => {
const accessToken = c.req.header('authorization')?.replace(/^Bearer /, '')
if (!accessToken) return c.json({ error: 'invalid_token' }, 401)
const { connection } = await accounts.connections.connect({ accessToken }) // [!code ++]
return c.json({ userId: connection.userId }) // [!code ++]
})
export default app
```
Tempo ID signs the key authorization at redemption, with the Tempo Account's owner key. A passkey signs only with the user present, so Tempo ID refuses a Tempo Account that only a passkey owns with `webauthn_required`. With an [access key endpoint](/docs/guides/connections/serve-access-keys), the owner signs at the approval instead.
### Pay with the access key
`accounts.pay` takes the connection as `session` , and the connection's access key sends the transfer. The first transfer carries the key authorization, which registers the access key on the chain.
```ts [api.ts]
import { Accounts, Store } from 'accounts'
import { viem } from 'accounts/plugins'
import { Hono } from 'hono'
const accounts = Accounts.create({
chain: 'testnet',
connections: {
metadata: {
accessKey: { limits: [{ limit: '25', token: 'ousd' }] },
privateKey: JSON.parse(process.env.API_PRIVATE_KEY!),
},
resource: 'https://api.example/pay',
store: Store.memory(),
},
plugins: [viem()],
})
const app = new Hono()
app.all('/api/*', (c) => accounts.handler.fetch(c.req.raw))
app.get('/.well-known/oauth-protected-resource/*', (c) =>
accounts.handler.fetch(c.req.raw),
)
app.post('/pay', async (c) => {
const accessToken = c.req.header('authorization')?.replace(/^Bearer /, '')
if (!accessToken) return c.json({ error: 'invalid_token' }, 401)
const { connection } = await accounts.connections.connect({ accessToken })
const { transaction } = await accounts.pay({ // [!code ++]
amount: '1', // [!code ++]
session: connection, // [!code ++]
to: '0x000000000000000000000000000000000000dEaD', // [!code ++]
token: 'ousd', // [!code ++]
}) // [!code ++]
return c.json({ transaction }) // [!code ++]
})
export default app
```
An API shows no payment page, so a payment above the approved limits rejects with `Actions.account.PageRequiredError` . On testnet, Viem's `faucet.fundSync` funds the Tempo Account first.
::::
## Use cases
Each use case passes the connection that `connections.connect` returns to another API, or sets one property of the `connections` option.
### Pay an MPP endpoint
`accounts.mpp` takes the connection as `session` , and pays an upstream endpoint's 402 charge with the access key.
```ts [api.ts]
import { Accounts, Store } from 'accounts'
import { mpp } from 'accounts/mpp'
import { Hono } from 'hono'
const accounts = Accounts.create({
chain: 'testnet',
connections: {
metadata: {
accessKey: { limits: [{ limit: '25', token: 'ousd' }] },
privateKey: JSON.parse(process.env.API_PRIVATE_KEY!),
},
resource: 'https://api.example/pay',
store: Store.memory(),
},
plugins: [mpp({ maxAmount: '1' })], // [!code hl]
})
const app = new Hono()
app.all('/api/*', (c) => accounts.handler.fetch(c.req.raw))
app.get('/.well-known/oauth-protected-resource/*', (c) =>
accounts.handler.fetch(c.req.raw),
)
app.post('/tool', async (c) => {
const accessToken = c.req.header('authorization')?.replace(/^Bearer /, '')
if (!accessToken) return c.json({ error: 'invalid_token' }, 401)
const { connection } = await accounts.connections.connect({ accessToken })
// [!code hl:start]
const response = await accounts
.mpp({ session: connection })
.fetch('https://upstream.example/tool')
// [!code hl:end]
return c.json(await response.json())
})
export default app
```
### Pay outside a request
`connections.get` reads the stored connection without an access token, such as in a scheduled job. It returns `undefined` without a live access key. The client ID and the user ID are those of the token that `connections.connect` returns.
```ts [api.ts]
import { Accounts, Store } from 'accounts'
import { viem } from 'accounts/plugins'
const accounts = Accounts.create({
chain: 'testnet',
connections: {
metadata: {
accessKey: { limits: [{ limit: '25', token: 'ousd' }] },
privateKey: JSON.parse(process.env.API_PRIVATE_KEY!),
},
resource: 'https://api.example/pay',
store: Store.memory(),
},
plugins: [viem()],
})
export async function pay(clientId: string, userId: string) {
const connection = await accounts.connections.get({ clientId, userId }) // [!code hl]
if (connection)
await accounts.pay({
amount: '1',
session: connection,
to: '0x000000000000000000000000000000000000dEaD',
token: 'ousd',
})
}
```
### Accept only named apps
`clientIds` names the apps whose access tokens the API accepts. It defaults to `'any'`, since any app may open a connection to the resource. Another app's token then fails `connections.connect` with `AccessToken.InvalidError` .
```ts [api.ts]
import { Accounts, Store } from 'accounts'
import { viem } from 'accounts/plugins'
export const accounts = Accounts.create({
chain: 'testnet',
connections: {
clientIds: ['https://app.example'], // [!code hl]
metadata: {
accessKey: { limits: [{ limit: '25', token: 'ousd' }] },
privateKey: JSON.parse(process.env.API_PRIVATE_KEY!),
},
resource: 'https://api.example/pay',
store: Store.memory(),
},
plugins: [viem()],
})
```
### Rotate the app's private key
Tempo ID keeps the keys of the app's document for 5 minutes, so an assertion of a new key fails until it reads the document again. `publicKeys` publishes the next key first\:
1. Generate the next key with its own `kid`, and deploy only its `publicKey` in `publicKeys`. The API still signs with the current key, and holds no second private key.
2. After 5 minutes, deploy the next `privateKey`, with the earlier key's `publicKey` in `publicKeys`, so that replicas of the earlier deploy still authenticate.
3. After every replica runs the second deploy, remove the earlier key from `publicKeys`.
```ts [api.ts]
import { Accounts, Store } from 'accounts'
import { viem } from 'accounts/plugins'
export const accounts = Accounts.create({
chain: 'testnet',
connections: {
metadata: {
accessKey: { limits: [{ limit: '25', token: 'ousd' }] },
privateKey: JSON.parse(process.env.API_PRIVATE_KEY!),
publicKeys: [JSON.parse(process.env.API_NEXT_PUBLIC_KEY!)], // [!code hl]
},
resource: 'https://api.example/pay',
store: Store.memory(),
},
plugins: [viem()],
})
```
## Next steps
# Serve access keys \[An API serves the access key endpoint, so that the user signs the access key at the approval.]
## Overview
An [access key endpoint](https\://github.com/tempoxyz/id/blob/main/docs/api-access-keys.md#access-key-endpoint) is an API route that returns a new [access key](/docs/guides/access-keys)'s public key. Tempo ID calls it during the approval, so the Tempo Account's owner signs the access key there. A passkey signs only with the user present, so a Tempo Account that only a passkey owns connects only this way.
| Policy | Access key | Tempo Account that only a passkey owns |
| --------------------------- | -------------------------------------- | -------------------------------------- |
| With an access key endpoint | Tempo ID requests it at the approval | Connects |
| Without one | The API creates it at its next request | Refused with `webauthn_required` |
The demo runs the [Pay for users](/docs/guides/connections/pay-for-users) demo beside a log of this site's access key endpoint, which shows each request of Tempo ID and marks the access key that signs the payment.
## Walkthrough
The API of [Pay for users](/docs/guides/connections/pay-for-users#walkthrough) already serves the endpoint, since the policy of its metadata names the handler's route. The steps show the route and the policy that names it.
::::steps
### Mount the handler
`accounts.handler` serves the endpoint at `POST /access-keys`, under `basePath` , which defaults to `/api`. The API's client ID also sits under it, so a new `basePath` makes a new app, which holds none of the earlier connections.
:::note
`Store.memory` keeps the connections and their access keys in the process, so a restart loses them. In production, use a store that each replica shares, such as `Store.postgres` or `Store.redis` .
:::
```ts [api.ts]
import { Accounts, Store } from 'accounts'
import { viem } from 'accounts/plugins'
import { Hono } from 'hono'
const accounts = Accounts.create({
chain: 'testnet',
connections: {
metadata: {
accessKey: { limits: [{ limit: '25', token: 'ousd' }] },
privateKey: JSON.parse(process.env.API_PRIVATE_KEY!),
},
resource: 'https://api.example/pay',
store: Store.memory(),
},
plugins: [viem()],
})
const app = new Hono()
app.all('/api/*', (c) => accounts.handler.fetch(c.req.raw)) // [!code hl]
app.get('/.well-known/oauth-protected-resource/*', (c) =>
accounts.handler.fetch(c.req.raw),
)
export default app
```
The handler verifies Tempo ID's signed request token, and refuses a repeated one with 401. It then generates an access key, keeps its private key in the store, and returns its public key.
Tempo ID calls the route without the app's session, so no sign-in guards it. Tempo ID waits 5 seconds for the response, and never retries.
### Check the policy
The access key policy of `metadata` names the route's URL as its access key endpoint, such as `https://api.example/api/access-keys`. Tempo ID reads it at the next sign-in after 5 minutes.
The API's routes do not change\: `connections.connect` claims the access key that the connection's first access token names.
::::
## Use cases
Each use case sets one property of the `connections` option, which the handler's access key endpoint reads.
### Discard unclaimed access keys sooner
The API never learns whether the user approved, so `pendingLifetime` sets how long, in milliseconds, a prepared access key waits for a token that names it. After it, the store discards the access key, and the user approves again. It defaults to 7 days.
```ts [api.ts]
import { Accounts, Store } from 'accounts'
import { viem } from 'accounts/plugins'
import { Hono } from 'hono'
const accounts = Accounts.create({
chain: 'testnet',
connections: {
metadata: {
accessKey: { limits: [{ limit: '25', token: 'ousd' }] },
privateKey: JSON.parse(process.env.API_PRIVATE_KEY!),
},
pendingLifetime: 24 * 60 * 60 * 1000, // [!code hl]
resource: 'https://api.example/pay',
store: Store.memory(),
},
plugins: [viem()],
})
const app = new Hono()
app.all('/api/*', (c) => accounts.handler.fetch(c.req.raw))
app.get('/.well-known/oauth-protected-resource/*', (c) =>
accounts.handler.fetch(c.req.raw),
)
export default app
```
## Next steps
# Revoke connections \[An API revokes the access keys of a connection, and handles a connection that Tempo ID refuses.]
## Overview
A [connection](/docs/guides/connections) gives an API an [access key](/docs/guides/access-keys) for one user of one app. The API revokes its access keys with its own client authentication and no user token, as an OAuth client revokes its own grant. Tempo ID then refuses a new access key for the connection until the user approves the API again.
The demo signs a user in for this site's API, which pays 1 OUSD, revokes the connection, and refuses a second payment with 403.
## Walkthrough
The steps add two parts to the API of [Pay for users](/docs/guides/connections/pay-for-users#walkthrough).
::::steps
### Revoke the access keys of a connection
The token that `connections.connect` returns names the connection\: the app's client ID and the user's ID. `connections.revoke` revokes each of the connection's access keys on the chain, and deletes the connection from the store.
:::note
`Store.memory` keeps the connections and their access keys in the process, so a restart loses them. In production, use a store that each replica shares, such as `Store.postgres` or `Store.redis` .
:::
```ts [api.ts]
import { Accounts, Store } from 'accounts'
import { viem } from 'accounts/plugins'
import { Hono } from 'hono'
const accounts = Accounts.create({
chain: 'testnet',
connections: {
metadata: {
accessKey: { limits: [{ limit: '25', token: 'ousd' }] },
privateKey: JSON.parse(process.env.API_PRIVATE_KEY!),
},
resource: 'https://api.example/pay',
store: Store.memory(),
},
plugins: [viem()],
})
const app = new Hono()
app.all('/api/*', (c) => accounts.handler.fetch(c.req.raw))
app.get('/.well-known/oauth-protected-resource/*', (c) =>
accounts.handler.fetch(c.req.raw),
)
app.post('/revoke', async (c) => {
const accessToken = c.req.header('authorization')?.replace(/^Bearer /, '')
if (!accessToken) return c.json({ error: 'invalid_token' }, 401)
const { token } = await accounts.connections.connect({ accessToken })
// [!code hl:start]
const receipts = await accounts.connections.revoke({
clientId: token.clientId,
userId: token.userId,
})
// [!code hl:end]
return c.json({
transactionHashes: receipts.map((receipt) => receipt.transactionHash),
})
})
export default app
```
### Handle a refused connection
`connections.connect` throws for an access token that does not verify, and for a connection that Tempo ID refuses.
| Error | `reason` | Cause | Status |
| ------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | ------------------------------------------------------------------ | ------ |
| `AccessToken.InvalidError` | | The access token does not verify, or names another audience | 401 |
| `Accounts.RequestError` | `connection_mismatch` | The approval is for another access key, such as after a revocation | 403 |
| `Accounts.RequestError` | `unknown_allowance` | The user approved no connection, or the approval ended | 403 |
```ts [api.ts]
import { AccessToken, Accounts, Store } from 'accounts'
import { viem } from 'accounts/plugins'
import { Hono } from 'hono'
const accounts = Accounts.create({
chain: 'testnet',
connections: {
metadata: {
accessKey: { limits: [{ limit: '25', token: 'ousd' }] },
privateKey: JSON.parse(process.env.API_PRIVATE_KEY!),
},
resource: 'https://api.example/pay',
store: Store.memory(),
},
plugins: [viem()],
})
const app = new Hono()
app.all('/api/*', (c) => accounts.handler.fetch(c.req.raw))
app.get('/.well-known/oauth-protected-resource/*', (c) =>
accounts.handler.fetch(c.req.raw),
)
app.post('/revoke', async (c) => {
const accessToken = c.req.header('authorization')?.replace(/^Bearer /, '')
if (!accessToken) return c.json({ error: 'invalid_token' }, 401)
const { token } = await accounts.connections.connect({ accessToken })
const receipts = await accounts.connections.revoke({
clientId: token.clientId,
userId: token.userId,
})
return c.json({
transactionHashes: receipts.map((receipt) => receipt.transactionHash),
})
})
// [!code hl:start]
app.onError((error, c) => {
if (error instanceof AccessToken.InvalidError)
return c.json({ error: 'invalid_token' }, 401)
if (
error instanceof Accounts.RequestError &&
(error.reason === 'connection_mismatch' ||
error.reason === 'unknown_allowance')
)
return c.json({ error: error.reason }, 403)
return c.json({ error: 'server_error' }, 500)
})
// [!code hl:end]
export default app
```
If the API responds with 403, the app signs the user in again with `resource` . After the approval, the next request redeems a new access key.
::::
## Use cases
Each use case revokes the access keys of a connection with another member of `accounts.connections` .
### Revoke one access key
`connections.revokeAccessKey` revokes one of the connection's access keys. It returns the receipt, or `null` if the connection holds no such access key, or Tempo ID holds it no longer.
```ts [api.ts]
import { Accounts, Store } from 'accounts'
import { viem } from 'accounts/plugins'
import { Hono } from 'hono'
const accounts = Accounts.create({
chain: 'testnet',
connections: {
metadata: {
accessKey: { limits: [{ limit: '25', token: 'ousd' }] },
privateKey: JSON.parse(process.env.API_PRIVATE_KEY!),
},
resource: 'https://api.example/pay',
store: Store.memory(),
},
plugins: [viem()],
})
const app = new Hono()
app.all('/api/*', (c) => accounts.handler.fetch(c.req.raw))
app.get('/.well-known/oauth-protected-resource/*', (c) =>
accounts.handler.fetch(c.req.raw),
)
app.post('/revoke-access-key', async (c) => {
const accessToken = c.req.header('authorization')?.replace(/^Bearer /, '')
if (!accessToken) return c.json({ error: 'invalid_token' }, 401)
const { connection, token } = await accounts.connections.connect({
accessToken,
})
// [!code hl:start]
const receipt = await accounts.connections.revokeAccessKey({
accessKey: connection.accessKey.keyAuthorization.keyId,
clientId: token.clientId,
userId: token.userId,
})
// [!code hl:end]
return c.json({ transactionHash: receipt?.transactionHash ?? null })
})
export default app
```
## Next steps
# Fee sponsorship \[A fee payer pays the fees of the transactions of users.]
## Overview
Tempo has no native gas token, so the sender of a transaction pays its fee in a stablecoin. A Tempo transaction can also name a fee payer\: a second account that co-signs the transaction and pays its fee.
An app sponsors fees so that a user with no stablecoin can still send a transaction. Each guide uses a different fee payer.
## Guides
# Use Tempo API \[The sponsor of a Tempo API key pays the fees of the transactions of users.]
## Overview
Tempo has no native gas token, so the sender of a transaction pays its fee in a stablecoin. A Tempo transaction can also name a fee payer\: a second account that co-signs the transaction and pays its fee, so the sender's Tempo Account pays none. An app sponsors fees in one of two ways\:
| Guide | Fee payer | Sent by | The app holds |
| --------------------------------------------------------------- | -------------------------------------- | ------------------------------------- | -------------------------------------- |
| Use Tempo API | The sponsor of the app's Tempo API key | A page, through the app's relay route | A Tempo API key |
| [Host fee payers](/docs/guides/fee-sponsorship/host-fee-payers) | An account of the app's server | A page, through the app's relay route | A private key, and the account's funds |
The Tempo API, at `https://api.tempo.xyz`, is Tempo's hosted API. Its sponsor endpoint fills a transaction and co-signs it as the fee payer, and charges the fee to the sponsor of the request's Tempo API key.
A page must not hold the API key, so it sends each fill through a relay route on the app's server\: a JSON-RPC proxy that verifies the caller and adds the API key. The `relay` plugin serves this route.
The demo sends 1 OUSD through the site's relay route, which sponsors 3 payments a minute for each user, and shows the account that paid the fee.
## Walkthrough
The [`sponsored-tempo-api`](https\://github.com/tempoxyz/accounts/tree/main/examples/sponsored-tempo-api) example runs this flow.
```mermaid
sequenceDiagram
participant Page
participant Route as Relay route
participant API as Tempo API
participant RPC as Chain RPC
Page->>Route: eth_fillTransaction, with the access token
Route->>Route: Verify the access token
Route->>API: eth_fillTransaction, with the API key
API-->>Page: The transaction, with the sponsor's signature
Page->>RPC: eth_sendRawTransactionSync
```
::::steps
### Create a Tempo API key
In the [Tempo Console](https\://console.tempo.xyz), select **API Keys**, and create an API key with the `rpc-relay:sponsor` scope. The console shows the API key once. Set it as `TEMPO_API_KEY` in the server's environment.
:::warning
Keep the API key on the server. Each request with it spends the sponsor's balance, and a browser or mobile bundle shows it to anyone.
:::
### Install the packages
:::code-group
```sh [npm]
npm install accounts hono react react-dom viem
```
```sh [pnpm]
pnpm add accounts hono react react-dom viem
```
```sh [bun]
bun add accounts hono react react-dom viem
```
:::
### Add the relay route to the page
Pass the route's path to the `viem` plugin as `relay` . The page then sends each transaction's sponsorship requests to the route with the [session](/docs/guides/user-session)'s [access token](/docs/guides/api-authentication/authenticate-requests), and every other request to the chain's RPC.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [react(), viem({ relay: '/api/relay' })], // [!code hl]
})
```
### Serve the relay route
On the server, the `relay` plugin adds `accounts.relay` , which forwards each request to the Tempo API with `apiKey` . Its `fetch` is a function of the Fetch API, so any Fetch server runs it, such as this Hono app.
The route accepts only the access tokens of its `clientId` , here the page's origin. Each signed-in user can then spend the sponsor's balance, within the API key's limits. To limit each user, add `authorize` , as [Limit each user](/docs/guides/fee-sponsorship/use-tempo-api#limit-each-user) shows.
```ts [server.ts]
import { Accounts } from 'accounts'
import { relay } from 'accounts/plugins'
import { Hono } from 'hono'
const accounts = Accounts.create({
chain: 'testnet',
clientId: process.env.APP_URL,
plugins: [relay({ apiKey: process.env.TEMPO_API_KEY! })],
})
export default new Hono().post('/api/relay', (c) =>
accounts.relay.fetch(c.req.raw),
)
```
### Send a transaction
The page sends as it does without a sponsor. The [access key](/docs/guides/access-keys) signs as the sender, and the receipt's `feePayer` names the account that paid the fee.
:::code-group
```tsx [Send.tsx]
import { useState } from 'react'
import { parseUnits } from 'viem'
import { Addresses } from 'viem/tempo'
import { accounts } from './tempo.config.js'
export function Send() {
const [feePayer, setFeePayer] = useState()
return (
<>
{
const { receipt } = await accounts.token.transferSync({
amount: parseUnits('1', 6),
to: '0x000000000000000000000000000000000000dEaD',
token: Addresses.ousd,
})
setFeePayer(receipt.feePayer) // [!code hl]
}}
type="button"
>
Send 1 OUSD
{feePayer && Fee paid by {feePayer}
}
>
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [react(), viem({ relay: '/api/relay' })],
})
```
:::
::::
## Use cases
Each use case sets one option of the `relay` plugin on the server, or of the `viem` plugin's `relay` on the page.
### Limit each user
`authorize` accepts or refuses each caller whose access token verified. A response that it returns refuses the request, and the sender then pays its own fee.
Here a count in a `Store` allows 10 requests a minute for each user. It takes two store calls, so concurrent requests can pass the limit. For an exact limit, count in one atomic database step.
:::note
`Store.memory` keeps the counts in the process, so a restart loses them. In production, use a store that each replica shares, such as `Store.postgres` or `Store.redis` .
:::
```ts [server.ts]
import { Accounts, Store } from 'accounts'
import { relay } from 'accounts/plugins'
import { Hono } from 'hono'
const store = Store.memory()
const accounts = Accounts.create({
chain: 'testnet',
clientId: process.env.APP_URL,
plugins: [
relay({
apiKey: process.env.TEMPO_API_KEY!,
// [!code hl:start]
async authorize(options) {
const minute = Math.floor(Date.now() / 60_000)
const key = `relay-limit:${options.token.userId}:${minute}`
const count = Number((await store.getItem(key)) ?? 0)
if (count >= 10)
return Response.json({ error: 'slow_down' }, { status: 429 })
await store.setItem(key, count + 1, { expiresAt: (minute + 1) * 60_000 })
},
// [!code hl:end]
}),
],
})
export default new Hono().post('/api/relay', (c) =>
accounts.relay.fetch(c.req.raw),
)
```
### Accept the tokens of a resource
`verify` also takes the options of the route's token verifier. If the app's access tokens name a [registered resource](https\://github.com/tempoxyz/id/blob/main/docs/resources.md), set it as `audience` . The route then also accepts each token that the resource's API holds, so that API can spend the sponsor's balance.
```ts [server.ts]
import { Accounts } from 'accounts'
import { relay } from 'accounts/plugins'
import { Hono } from 'hono'
const accounts = Accounts.create({
chain: 'testnet',
clientId: process.env.APP_URL,
plugins: [
relay({
apiKey: process.env.TEMPO_API_KEY!,
verify: { audience: 'https://mcp.example.com/mcp' }, // [!code hl]
}),
],
})
export default new Hono().post('/api/relay', (c) =>
accounts.relay.fetch(c.req.raw),
)
```
### Send to a route at another origin
By default, only a route at one of the app's origins receives the access token. A route at another origin, such as a mobile app's server, receives it with `credentials` set to `'include'`.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [
react(),
viem({
relay: { credentials: 'include', url: 'https://api.example.com/relay' }, // [!code hl]
}),
],
})
```
### Sponsor more than one chain
A route sponsors one chain, its instance's `chain` . For more chains, serve one instance and one route for each, and return each chain's route from a function of the `viem` plugin. The relay's `chainId` sets a route's chain in place of the instance's.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [
react(),
viem((chainId) => ({ relay: `/api/relay/${chainId}` })), // [!code hl]
],
})
```
### Serve the route behind a proxy
Each DPoP proof (RFC 9449) names the route's public URL. Behind a proxy that terminates TLS, the request's URL is the internal URL, so pass the public one as `url` .
Several processes that serve the route refuse a repeated proof in `authorize` , as [Bind DPoP keys](/docs/guides/api-authentication/bind-dpop-keys#refuse-a-repeated-proof) shows.
```ts [server.ts]
import { Accounts } from 'accounts'
import { relay } from 'accounts/plugins'
import { Hono } from 'hono'
const accounts = Accounts.create({
chain: 'testnet',
clientId: process.env.APP_URL,
plugins: [
relay({
apiKey: process.env.TEMPO_API_KEY!,
url: 'https://app.example/api/relay', // [!code hl]
}),
],
})
export default new Hono().post('/api/relay', (c) =>
accounts.relay.fetch(c.req.raw),
)
```
### Check the caller without an access token
With `verify` set to `false`, the route checks no access token, so any caller that reaches it spends the sponsor's balance. Serve it only behind the app's own check, such as a `backend` session cookie.
```ts [server.ts]
import { Accounts, Store } from 'accounts'
import { backend, relay } from 'accounts/plugins'
import { Hono } from 'hono'
import { csrf } from 'hono/csrf'
const accounts = Accounts.create({
chain: 'testnet',
clientId: process.env.APP_URL,
plugins: [
backend({ store: Store.memory() }),
relay({ apiKey: process.env.TEMPO_API_KEY!, verify: false }), // [!code hl]
],
})
const app = new Hono()
app.all('/api/auth/*', (c) => accounts.handler.fetch(c.req.raw))
// The cookie authenticates the relay, so another site's request is refused.
app.use('/api/relay', csrf())
app.post('/api/relay', async (c) => {
// [!code hl:start]
// The app's own check of the caller: the backend's session cookie.
const session = await accounts.session.get(c.req.raw)
if (session?.method !== 'tempo-id')
return c.json({ error: 'forbidden' }, 403)
// [!code hl:end]
return accounts.relay.fetch(c.req.raw)
})
export default app
```
## Next steps
# Host fee payers \[An account of the app's server pays the fees of the transactions of users.]
## Overview
Here the [fee payer](/docs/guides/fee-sponsorship/use-tempo-api#overview) is an account whose private key the app's server holds, so the app needs no Tempo API key. Nothing outside the app limits its spending, so the relay route checks the caller, the sender, and the transaction before it co-signs.
The demo sends 1 OUSD through the site's relay route, which sponsors 3 payments a minute for each user, and shows the server's account that paid the fee.
## Walkthrough
The [`sponsored-self-hosted`](https\://github.com/tempoxyz/accounts/tree/main/examples/sponsored-self-hosted) example runs these steps. It uses the page of [Use Tempo API](/docs/guides/fee-sponsorship/use-tempo-api#add-the-relay-route-to-the-page).
::::steps
### Add the fee payer
Pass the account to the `relay` plugin, whose route then co-signs each transaction through Viem's `Relay.feePayer`. With the `relay` option of `handler` , `accounts.handler` serves the route.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { relay } from 'accounts/plugins'
import { privateKeyToAccount } from 'viem/accounts'
const feePayer = privateKeyToAccount(
process.env.FEE_PAYER_PRIVATE_KEY as `0x${string}`,
)
export const accounts = Accounts.create({
chain: 'testnet',
clientId: process.env.APP_URL,
handler: { relay: true }, // [!code hl]
plugins: [relay({ account: feePayer })], // [!code hl]
})
```
:::warning
Keep the private key in a server secret, and fund the account only with what the app can lose.
:::
### Check the sender
`authorize` receives a copy of the request and its [access token](/docs/guides/api-authentication/authenticate-requests)'s claims. The fee payer signs at the fill, whose body names the sender. The token's `accessKeys` name the Tempo Account of each [access key](/docs/guides/access-keys) that Tempo ID signed for the app.
Refuse each request that is not a fill, and each fill whose sender is none of these accounts, so a user cannot sponsor another account's transactions.
:::code-group
```ts [server.ts]
import { Hono } from 'hono'
import { accounts } from './tempo.config.js'
export default new Hono().all('/api/relay', (c) =>
accounts.handler.fetch(c.req.raw),
)
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { relay } from 'accounts/plugins'
import { TempoAddress } from 'ox/tempo'
import { isAddressEqual } from 'viem'
import { privateKeyToAccount } from 'viem/accounts'
const feePayer = privateKeyToAccount(
process.env.FEE_PAYER_PRIVATE_KEY as `0x${string}`,
)
export const accounts = Accounts.create({
chain: 'testnet',
clientId: process.env.APP_URL,
handler: { relay: true },
plugins: [
relay({
account: feePayer,
async authorize(options) {
// [!code hl:start]
const body = (await options.request.json().catch(() => undefined)) as
| { method?: unknown; params?: readonly { from?: unknown }[] }
| undefined
const sender = (() => {
const from = body?.params?.[0]?.from
if (typeof from !== 'string') return undefined
try {
return TempoAddress.resolve(from as TempoAddress.Address)
} catch {
return undefined
}
})()
if (
body?.method !== 'eth_fillTransaction' ||
!sender ||
!options.token.accessKeys.some(
(accessKey) =>
accessKey.chainId === accounts.config.chainId &&
isAddressEqual(accessKey.account, sender),
)
)
return Response.json({ error: 'forbidden' }, { status: 403 })
// [!code hl:end]
},
}),
],
})
```
:::
### Limit each user
Each signed-in user can spend the fee payer's balance, so `authorize` refuses a request above its user's limit. The sender then pays its own fee.
Here a count in a `Store` allows 10 requests a minute for each user. It takes two store calls, so concurrent requests can pass the limit. For an exact limit, count in one atomic database step.
:::note
`Store.memory` keeps the counts in the process, so a restart loses them. In production, use a store that each replica shares, such as `Store.postgres` or `Store.redis` .
:::
:::code-group
```ts [server.ts]
import { Hono } from 'hono'
import { accounts } from './tempo.config.js'
export default new Hono().all('/api/relay', (c) =>
accounts.handler.fetch(c.req.raw),
)
```
```ts [tempo.config.ts]
import { Accounts, Store } from 'accounts'
import { relay } from 'accounts/plugins'
import { TempoAddress } from 'ox/tempo'
import { isAddressEqual } from 'viem'
import { privateKeyToAccount } from 'viem/accounts'
const feePayer = privateKeyToAccount(
process.env.FEE_PAYER_PRIVATE_KEY as `0x${string}`,
)
const store = Store.memory() // [!code hl]
export const accounts = Accounts.create({
chain: 'testnet',
clientId: process.env.APP_URL,
handler: { relay: true },
plugins: [
relay({
account: feePayer,
async authorize(options) {
const body = (await options.request.json().catch(() => undefined)) as
| { method?: unknown; params?: readonly { from?: unknown }[] }
| undefined
const sender = (() => {
const from = body?.params?.[0]?.from
if (typeof from !== 'string') return undefined
try {
return TempoAddress.resolve(from as TempoAddress.Address)
} catch {
return undefined
}
})()
if (
body?.method !== 'eth_fillTransaction' ||
!sender ||
!options.token.accessKeys.some(
(accessKey) =>
accessKey.chainId === accounts.config.chainId &&
isAddressEqual(accessKey.account, sender),
)
)
return Response.json({ error: 'forbidden' }, { status: 403 })
// [!code hl:start]
const minute = Math.floor(Date.now() / 60_000)
const key = `relay-limit:${options.token.userId}:${minute}`
const count = Number((await store.getItem(key)) ?? 0)
if (count >= 10)
return Response.json({ error: 'slow_down' }, { status: 429 })
await store.setItem(key, count + 1, { expiresAt: (minute + 1) * 60_000 })
// [!code hl:end]
},
}),
],
})
```
:::
### Limit what the fee payer signs
Viem's `Relay.feePayer` takes `validate`, which accepts or refuses each filled transaction. Pass the plugin in `plugins` , in place of `account` . Here its own module holds it, and it allows only OUSD transfers within a gas limit and a fee cap.
The sender pays the fee of a refused transaction. An access key's first transaction carries its key authorization and takes about 5 million gas, so the gas limit allows it.
:::warning
`relay` throws if `plugins` comes with `account` or `apiKey` . The plugins run in order, and `Relay.feePayer` answers a raw transaction or a complete fill without the plugins after it. Put each fee payer limit in `validate`, or in a plugin before `Relay.feePayer`.
:::
:::code-group
```ts [server.ts]
import { Hono } from 'hono'
import { accounts } from './tempo.config.js'
export default new Hono().all('/api/relay', (c) =>
accounts.handler.fetch(c.req.raw),
)
```
```ts [tempo.config.ts]
import { Accounts, Store } from 'accounts'
import { relay } from 'accounts/plugins'
import { TempoAddress } from 'ox/tempo'
import { isAddressEqual } from 'viem'
import { feePayer } from './fee-payer.js'
const store = Store.memory()
export const accounts = Accounts.create({
chain: 'testnet',
clientId: process.env.APP_URL,
handler: { relay: true },
plugins: [
relay({
async authorize(options) {
const body = (await options.request.json().catch(() => undefined)) as
| { method?: unknown; params?: readonly { from?: unknown }[] }
| undefined
const sender = (() => {
const from = body?.params?.[0]?.from
if (typeof from !== 'string') return undefined
try {
return TempoAddress.resolve(from as TempoAddress.Address)
} catch {
return undefined
}
})()
if (
body?.method !== 'eth_fillTransaction' ||
!sender ||
!options.token.accessKeys.some(
(accessKey) =>
accessKey.chainId === accounts.config.chainId &&
isAddressEqual(accessKey.account, sender),
)
)
return Response.json({ error: 'forbidden' }, { status: 403 })
const minute = Math.floor(Date.now() / 60_000)
const key = `relay-limit:${options.token.userId}:${minute}`
const count = Number((await store.getItem(key)) ?? 0)
if (count >= 10)
return Response.json({ error: 'slow_down' }, { status: 429 })
await store.setItem(key, count + 1, { expiresAt: (minute + 1) * 60_000 })
},
plugins: [feePayer], // [!code hl]
}),
],
})
```
```ts [fee-payer.ts]
import { TempoAddress } from 'ox/tempo'
import { decodeFunctionData, isAddressEqual } from 'viem'
import { privateKeyToAccount } from 'viem/accounts'
import { Abis, Addresses, Relay } from 'viem/tempo'
// [!code hl:start]
const maxGas = 6_000_000n
const maxFeePerGas = 10_000_000_000n
// [!code hl:end]
export const feePayer = Relay.feePayer({
account: privateKeyToAccount(
process.env.FEE_PAYER_PRIVATE_KEY as `0x${string}`,
),
// [!code hl:start]
validate(request) {
if (!request.gas || request.gas > maxGas) return false
if (!request.maxFeePerGas || request.maxFeePerGas > maxFeePerGas)
return 'tx_fee_limit_exceeded'
const calls = request.calls ?? [
{ data: request.data, to: request.to, value: request.value },
]
return (
calls.length > 0 &&
calls.every((call) => {
if (
!call.to ||
!isAddressEqual(TempoAddress.resolve(call.to), Addresses.ousd)
)
return false
if (call.value) return false
const { functionName } = (() => {
try {
return decodeFunctionData({
abi: Abis.tip20,
data: call.data ?? '0x',
})
} catch {
return { functionName: undefined }
}
})()
return (
functionName === 'transfer' || functionName === 'transferWithMemo'
)
})
)
},
// [!code hl:end]
})
```
:::
### Limit the body
The route reads at most 1 MiB of a body, and returns 413 with the reason `body_too_large` above it. It parses the body before `authorize` runs, also for a caller that `authorize` refuses.
A fill of one transfer takes about 1 KiB, so refuse a body above a smaller limit, or without a length, before the route reads it.
:::code-group
```ts [server.ts]
import { Hono } from 'hono'
import { accounts } from './tempo.config.js'
const maxBodySize = 16 * 1024 // [!code hl]
export default new Hono().all('/api/relay', async (c) => {
// [!code hl:start]
const length = Number(c.req.header('content-length'))
if (c.req.method === 'POST' && (!length || length > maxBodySize))
return c.json({ error: 'invalid_request' }, 413)
// [!code hl:end]
return accounts.handler.fetch(c.req.raw)
})
```
```ts [tempo.config.ts]
import { Accounts, Store } from 'accounts'
import { relay } from 'accounts/plugins'
import { TempoAddress } from 'ox/tempo'
import { isAddressEqual } from 'viem'
import { feePayer } from './fee-payer.js'
const store = Store.memory()
export const accounts = Accounts.create({
chain: 'testnet',
clientId: process.env.APP_URL,
handler: { relay: true },
plugins: [
relay({
async authorize(options) {
const body = (await options.request.json().catch(() => undefined)) as
| { method?: unknown; params?: readonly { from?: unknown }[] }
| undefined
const sender = (() => {
const from = body?.params?.[0]?.from
if (typeof from !== 'string') return undefined
try {
return TempoAddress.resolve(from as TempoAddress.Address)
} catch {
return undefined
}
})()
if (
body?.method !== 'eth_fillTransaction' ||
!sender ||
!options.token.accessKeys.some(
(accessKey) =>
accessKey.chainId === accounts.config.chainId &&
isAddressEqual(accessKey.account, sender),
)
)
return Response.json({ error: 'forbidden' }, { status: 403 })
const minute = Math.floor(Date.now() / 60_000)
const key = `relay-limit:${options.token.userId}:${minute}`
const count = Number((await store.getItem(key)) ?? 0)
if (count >= 10)
return Response.json({ error: 'slow_down' }, { status: 429 })
await store.setItem(key, count + 1, { expiresAt: (minute + 1) * 60_000 })
},
plugins: [feePayer],
}),
],
})
```
```ts [fee-payer.ts]
import { TempoAddress } from 'ox/tempo'
import { decodeFunctionData, isAddressEqual } from 'viem'
import { privateKeyToAccount } from 'viem/accounts'
import { Abis, Addresses, Relay } from 'viem/tempo'
const maxGas = 6_000_000n
const maxFeePerGas = 10_000_000_000n
export const feePayer = Relay.feePayer({
account: privateKeyToAccount(
process.env.FEE_PAYER_PRIVATE_KEY as `0x${string}`,
),
validate(request) {
if (!request.gas || request.gas > maxGas) return false
if (!request.maxFeePerGas || request.maxFeePerGas > maxFeePerGas)
return 'tx_fee_limit_exceeded'
const calls = request.calls ?? [
{ data: request.data, to: request.to, value: request.value },
]
return (
calls.length > 0 &&
calls.every((call) => {
if (
!call.to ||
!isAddressEqual(TempoAddress.resolve(call.to), Addresses.ousd)
)
return false
if (call.value) return false
const { functionName } = (() => {
try {
return decodeFunctionData({
abi: Abis.tip20,
data: call.data ?? '0x',
})
} catch {
return { functionName: undefined }
}
})()
return (
functionName === 'transfer' || functionName === 'transferWithMemo'
)
})
)
},
})
```
:::
::::
## Use cases
Each use case sets one option of the `relay` plugin, or serves its route.
### Serve the route without the handler
`accounts.relay` is the route's own handler, so a server can serve it with no `handler.relay` option. Its `fetch` serves the route at any path.
:::code-group
```ts [server.ts]
import { Hono } from 'hono'
import { accounts } from './tempo.config.js'
export default new Hono().post('/api/relay', (c) =>
accounts.relay.fetch(c.req.raw), // [!code hl]
)
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { relay } from 'accounts/plugins'
import { privateKeyToAccount } from 'viem/accounts'
const feePayer = privateKeyToAccount(
process.env.FEE_PAYER_PRIVATE_KEY as `0x${string}`,
)
export const accounts = Accounts.create({
chain: 'testnet',
clientId: process.env.APP_URL,
plugins: [relay({ account: feePayer })],
})
```
:::
### Serve the route behind a proxy
Each DPoP proof (RFC 9449) names the route's public URL. Behind a proxy that terminates TLS, the request's URL is the internal URL, so pass the public one as `url` .
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { relay } from 'accounts/plugins'
import { privateKeyToAccount } from 'viem/accounts'
const feePayer = privateKeyToAccount(
process.env.FEE_PAYER_PRIVATE_KEY as `0x${string}`,
)
export const accounts = Accounts.create({
chain: 'testnet',
clientId: process.env.APP_URL,
handler: { relay: true },
plugins: [
relay({
account: feePayer,
url: 'https://app.example/api/relay', // [!code hl]
}),
],
})
```
### Accept the tokens of a resource
`verify` also takes the options of the route's token verifier. If the app's access tokens name a [registered resource](https\://github.com/tempoxyz/id/blob/main/docs/resources.md), set it as `audience` . The route then also accepts each token that the resource's API holds, so that API can spend the fee payer's balance.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { relay } from 'accounts/plugins'
import { privateKeyToAccount } from 'viem/accounts'
const feePayer = privateKeyToAccount(
process.env.FEE_PAYER_PRIVATE_KEY as `0x${string}`,
)
export const accounts = Accounts.create({
chain: 'testnet',
clientId: process.env.APP_URL,
handler: { relay: true },
plugins: [
relay({
account: feePayer,
verify: { audience: 'https://mcp.example.com/mcp' }, // [!code hl]
}),
],
})
```
### Allow a slow fill
The `relay` plugin also takes Viem's relay options, such as `timeout`, the time in milliseconds that a fill may take, with its callbacks. It defaults to 10 seconds, so raise it for a `validate` that reads a slow service.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { relay } from 'accounts/plugins'
import { privateKeyToAccount } from 'viem/accounts'
const feePayer = privateKeyToAccount(
process.env.FEE_PAYER_PRIVATE_KEY as `0x${string}`,
)
export const accounts = Accounts.create({
chain: 'testnet',
clientId: process.env.APP_URL,
handler: { relay: true },
plugins: [
relay({
account: feePayer,
timeout: 20_000, // [!code hl]
}),
],
})
```
## Next steps
# Charge tool calls \[An MCP server authorizes each client through Tempo ID, and charges each tool call over MPP.]
## Overview
An MCP server names Tempo ID as its authorization server, and accepts only the access tokens for its own [registered resource](https\://github.com/tempoxyz/id/blob/main/docs/resources.md). Each paid tool answers its call with a charge of the [Machine Payments Protocol](https\://mpp.dev) (MPP), in the JSON-RPC response. The client pays the charge with the access key of its sign-in, then calls the tool again.
An agent thus signs in once. Each later call pays with no approval, until the access key's limit refuses a charge.
```mermaid
sequenceDiagram
participant Agent
participant Server as MCP server
participant ID as Tempo ID
participant Chain as Tempo chain
Agent->>Server: Read the metadata
Server-->>Agent: Resource, and Tempo ID
Agent->>ID: Device grant for the resource
ID-->>Agent: Access token for the server, and access key
Agent->>Server: Call a tool, with the access token
Server-->>Agent: Error -32042, with a charge
Agent->>Server: Call again, with the access key's credential
Server->>Chain: Transfer
Server-->>Agent: Result, and receipt
```
No demo runs in this page, since the client is a terminal program, and the server's resource needs a registration at Tempo ID. The terminal output is of one run of the [`mcp`](https\://github.com/tempoxyz/accounts/tree/main/examples/mcp) example against a local Tempo ID and Tempo testnet.
```console [Terminal]
$ node --import tsx agent.ts login
Open http://localhost:8787/device?code=DSVS-PQBD and confirm the code DSVS-PQBD.
Signed in as alice-1794514374@example.com.
$ node --import tsx agent.ts call whoami
{"app":"cli:mcp-example","user":"user_01M78P9JQ7MW4PNQ1B94CWK7MN"}
$ node --import tsx agent.ts call fortune
The access key that spends little spends well.
Paid in 0x7f07443256a81f10541d3fd425c6ccbb7b7e07596d41f3ea1899c6df6bb0979f.
$ node --import tsx agent.ts call fortune
Today a payment required error turns into a result.
Paid in 0x2598b7638659b693f8dfee456ba7883b163bcd6e10bc5c6303d387c87d3da772.
$ node --import tsx agent.ts call report
The call failed: The charge of 5 exceeds the access key's limit of 0.977046 left for token 0x20c0000000000000000000006a37DA5C996874BE. Sign in with an access key whose limit covers the charge.
```
## Walkthrough
The [`mcp`](https\://github.com/tempoxyz/accounts/tree/main/examples/mcp) example runs these steps\: the server in `server.ts`, and the agent in `agent.ts`.
::::steps
### Register the resource
The resource's identifier is the `https` URL of the server's MCP endpoint, such as `https://mcp.example.com/mcp`. An admin of Tempo ID registers it. Each access token for it names it as `aud`, so no other API accepts the token.
The resource needs no [access key policy](https\://github.com/tempoxyz/id/blob/main/docs/api-access-keys.md#access-key-policy), since each client pays with its own access key.
An MCP client that signs in with its own OAuth flow, such as with a [metadata document](https\://github.com/tempoxyz/id/blob/main/docs/apps.md#metadata-document) or [dynamic client registration](https\://github.com/tempoxyz/id/blob/main/docs/apps.md#dynamic-client-registration), holds no access key. The server then holds an access key for each user's connection instead, as [Pay for users](/docs/guides/connections/pay-for-users) describes.
### Install the packages
The server and the agent use the MCP SDK, and pay through [mppx](https\://github.com/wevm/mppx).
:::code-group
```sh [npm]
npm install accounts @modelcontextprotocol/sdk hono mppx viem zod
```
```sh [pnpm]
pnpm add accounts @modelcontextprotocol/sdk hono mppx viem zod
```
```sh [bun]
bun add accounts @modelcontextprotocol/sdk hono mppx viem zod
```
:::
### Publish the metadata
The server publishes its [protected resource metadata](https\://www.rfc-editor.org/rfc/rfc9728), which names the resource and Tempo ID. Its path is the well-known path, then the resource's path.
```ts [server.ts]
import { Hono } from 'hono'
const resource = process.env.RESOURCE! // https://mcp.example.com/mcp
const metadataPath = `/.well-known/oauth-protected-resource${new URL(resource).pathname}`
const app = new Hono()
// [!code hl:start]
app.get(metadataPath, (c) =>
c.json({
authorization_servers: ['https://id.tempo.xyz'],
bearer_methods_supported: ['header'],
resource,
scopes_supported: ['openid', 'email', 'offline_access'],
}),
)
// [!code hl:end]
export default app
```
### Verify the access token
The `tokens` plugin verifies the access token of each request. Any MCP client may call the server, so it accepts the token of every app with `clientIds` , and only for the resource with `audience` . The server's origin is its client ID, which needs no registration.
```ts [server.ts]
import { Accounts } from 'accounts'
import { tokens } from 'accounts/plugins'
import { Hono } from 'hono'
const resource = process.env.RESOURCE! // https://mcp.example.com/mcp
const metadataPath = `/.well-known/oauth-protected-resource${new URL(resource).pathname}`
// [!code hl:start]
const accounts = Accounts.create({
clientId: new URL(resource).origin,
plugins: [tokens({ audience: resource, clientIds: 'any' })],
})
// [!code hl:end]
const app = new Hono()
app.get(metadataPath, (c) =>
c.json({
authorization_servers: ['https://id.tempo.xyz'],
bearer_methods_supported: ['header'],
resource,
scopes_supported: ['openid', 'email', 'offline_access'],
}),
)
export default app
```
`accounts.tokens.verifyAccessToken` returns the verified token, or nothing for a request without a valid one. It throws `Accounts.RequestError` with status 0 while Tempo ID's key set is unavailable. The server records no DPoP proof, so it refuses a DPoP token and accepts only Bearer tokens.
### Charge a tool
mppx's MCP SDK transport carries the charge in the messages of the call. A call without a credential throws the challenge, which the client pays.
A paid call returns the result with its receipt. mppx verifies the credential and broadcasts its transfer, so the server holds no key.
```ts [tools.ts]
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import type { AccessToken } from 'accounts'
import { Transport } from 'mppx/mcp-sdk/server'
import { Mppx, tempo } from 'mppx/server'
import { Addresses } from 'viem/tempo'
const resource = process.env.RESOURCE! // https://mcp.example.com/mcp
const mppx = Mppx.create({
methods: [
tempo.charge({
currencies: [Addresses.ousd],
recipient: process.env.RECIPIENT as `0x${string}`,
testnet: true,
}),
],
realm: new URL(resource).host,
secretKey: process.env.MPP_SECRET_KEY,
transport: Transport.mcpSdk(),
})
export function create(token: AccessToken.create.Token) {
const server = new McpServer({ name: 'example', version: '1.0.0' })
server.registerTool(
'fortune',
{ description: 'Returns a fortune. Costs 0.01 OUSD.' },
async (extra) => {
// [!code hl:start]
const result = await mppx.charge({ amount: '0.01' })(extra)
if (result.status === 402) throw result.challenge
// [!code hl:end]
return result.withReceipt({
content: [{ text: 'A small payment opens a large door.', type: 'text' }],
})
},
)
return server
}
```
A tool reads the caller from the token, such as its `userId` . An MCP client usually has no registration, so its token names no Tempo Account.
### Serve the MCP endpoint
A request without a valid token receives 401, whose challenge names the metadata. Each request holds its own server and transport, so the server keeps no MCP session.
:::code-group
```ts [server.ts]
import { WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js'
import { Accounts } from 'accounts'
import { tokens } from 'accounts/plugins'
import { Hono } from 'hono'
import { create } from './tools.js'
const resource = process.env.RESOURCE! // https://mcp.example.com/mcp
const metadataPath = `/.well-known/oauth-protected-resource${new URL(resource).pathname}`
const accounts = Accounts.create({
clientId: new URL(resource).origin,
plugins: [tokens({ audience: resource, clientIds: 'any' })],
})
const app = new Hono()
app.get(metadataPath, (c) =>
c.json({
authorization_servers: ['https://id.tempo.xyz'],
bearer_methods_supported: ['header'],
resource,
scopes_supported: ['openid', 'email', 'offline_access'],
}),
)
// [!code hl:start]
app.all('/mcp', async (c) => {
const token = await accounts.tokens.verifyAccessToken(c.req.raw)
// A DPoP token sets `boundTo`, and the server records no DPoP proof.
if (!token || token.boundTo)
return c.json({ error: 'invalid_token' }, 401, {
'WWW-Authenticate': `Bearer resource_metadata="${new URL(metadataPath, resource)}"`,
})
const server = create(token)
const transport = new WebStandardStreamableHTTPServerTransport({
enableJsonResponse: true,
})
await server.connect(transport)
return transport.handleRequest(c.req.raw)
})
// [!code hl:end]
export default app
```
```ts [tools.ts]
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import type { AccessToken } from 'accounts'
import { Transport } from 'mppx/mcp-sdk/server'
import { Mppx, tempo } from 'mppx/server'
import { Addresses } from 'viem/tempo'
const resource = process.env.RESOURCE! // https://mcp.example.com/mcp
const mppx = Mppx.create({
methods: [
tempo.charge({
currencies: [Addresses.ousd],
recipient: process.env.RECIPIENT as `0x${string}`,
testnet: true,
}),
],
realm: new URL(resource).host,
secretKey: process.env.MPP_SECRET_KEY,
transport: Transport.mcpSdk(),
})
export function create(token: AccessToken.create.Token) {
const server = new McpServer({ name: 'example', version: '1.0.0' })
server.registerTool(
'fortune',
{ description: 'Returns a fortune. Costs 0.01 OUSD.' },
async (extra) => {
const result = await mppx.charge({ amount: '0.01' })(extra)
if (result.status === 402) throw result.challenge
return result.withReceipt({
content: [{ text: 'A small payment opens a large door.', type: 'text' }],
})
},
)
return server
}
```
:::
### Discover the server
The agent reads the server's metadata. A token for another resource reaches another API, so the agent signs in only for the URL that it calls ([RFC 9728 §3.3](https\://www.rfc-editor.org/rfc/rfc9728#section-3.3)), and only at Tempo ID.
```ts [agent.ts]
import { discoverOAuthProtectedResourceMetadata } from '@modelcontextprotocol/sdk/client/auth.js'
// [!code hl:start]
const url = new URL('https://mcp.example.com/mcp')
const metadata = await discoverOAuthProtectedResourceMetadata(url)
if (metadata.resource !== url.href)
throw new Error(`The server names another resource, ${metadata.resource}.`)
if (!metadata.authorization_servers?.includes('https://id.tempo.xyz'))
throw new Error('The server names another authorization server.')
// [!code hl:end]
```
### Sign in for the resource
The sign-in names the resource, so each access token of the sign-in is for the server alone. The access key's limit caps what the agent spends.
The instance names no resource, so a sign-out needs no answer from the server. `device.signIn` runs the device grant, as the [CLI](/docs/guides/cli) guide describes.
:::code-group
```ts [agent.ts]
import { discoverOAuthProtectedResourceMetadata } from '@modelcontextprotocol/sdk/client/auth.js'
import { accounts } from './tempo.config.js'
const url = new URL('https://mcp.example.com/mcp')
const metadata = await discoverOAuthProtectedResourceMetadata(url)
if (metadata.resource !== url.href)
throw new Error(`The server names another resource, ${metadata.resource}.`)
if (!metadata.authorization_servers?.includes('https://id.tempo.xyz'))
throw new Error('The server names another authorization server.')
await accounts.device.signIn({ resource: metadata.resource }) // [!code hl]
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { mpp } from 'accounts/mpp'
import { device } from 'accounts/plugins'
export const accounts = Accounts.create({
// Each sign-in requests an access key that spends up to 1 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '1', token: 'ousd' }],
}),
chain: 'testnet',
clientId: 'cli:mcp-example',
plugins: [
device({
onCode: (code) =>
console.log(
`Open ${code.verificationUriComplete} and confirm the code ${code.userCode}.`,
),
}),
mpp(),
],
})
```
:::
### Pay the tool calls
`session.fetch` sends each MCP request with the access token, and refreshes it before it expires. The `mcp` caller of the `mpp` plugin pays each charge with the access key of the session.
:::code-group
```ts [agent.ts]
import { discoverOAuthProtectedResourceMetadata } from '@modelcontextprotocol/sdk/client/auth.js'
import { Client } from '@modelcontextprotocol/sdk/client/index.js'
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'
import { accounts } from './tempo.config.js'
const url = new URL('https://mcp.example.com/mcp')
const metadata = await discoverOAuthProtectedResourceMetadata(url)
if (metadata.resource !== url.href)
throw new Error(`The server names another resource, ${metadata.resource}.`)
if (!metadata.authorization_servers?.includes('https://id.tempo.xyz'))
throw new Error('The server names another authorization server.')
await accounts.device.signIn({ resource: metadata.resource })
// [!code hl:start]
const client = new Client({ name: 'agent', version: '1.0.0' })
await client.connect(
new StreamableHTTPClientTransport(url, {
fetch: (input, init) => accounts.session.fetch({ init, url: input }),
}),
)
// [!code hl:end]
// [!code hl:start]
const result = await accounts
.mpp()
.mcp(client)
.callTool({ arguments: {}, name: 'fortune' })
// [!code hl:end]
console.log(result.content, result.receipt?.reference)
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { mpp } from 'accounts/mpp'
import { device } from 'accounts/plugins'
export const accounts = Accounts.create({
// Each sign-in requests an access key that spends up to 1 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '1', token: 'ousd' }],
}),
chain: 'testnet',
clientId: 'cli:mcp-example',
plugins: [
device({
onCode: (code) =>
console.log(
`Open ${code.verificationUriComplete} and confirm the code ${code.userCode}.`,
),
}),
mpp(),
],
})
```
:::
A charge above what the access key's limit leaves throws `mpp.LimitError` before the access key signs, so it pays nothing. The user then signs in again for a new access key.
::::
## Use cases
Each use case sets one option of the payer that `accounts.mpp` returns, whose `mcp` calls the tools, or of the sign-in for the resource.
### Cap each call
`maxAmount` caps each charge. A charge above it throws `mpp.MaxAmountError` before the access key signs.
A server can charge a call again after its payment, and one call pays at most three charges, so a call costs at most three times the cap. The access key's limit caps the total.
:::code-group
```ts [agent.ts]
import { discoverOAuthProtectedResourceMetadata } from '@modelcontextprotocol/sdk/client/auth.js'
import { Client } from '@modelcontextprotocol/sdk/client/index.js'
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'
import { accounts } from './tempo.config.js'
const url = new URL('https://mcp.example.com/mcp')
const metadata = await discoverOAuthProtectedResourceMetadata(url)
if (metadata.resource !== url.href)
throw new Error(`The server names another resource, ${metadata.resource}.`)
if (!metadata.authorization_servers?.includes('https://id.tempo.xyz'))
throw new Error('The server names another authorization server.')
await accounts.device.signIn({ resource: metadata.resource })
const client = new Client({ name: 'agent', version: '1.0.0' })
await client.connect(
new StreamableHTTPClientTransport(url, {
fetch: (input, init) => accounts.session.fetch({ init, url: input }),
}),
)
const caller = accounts.mpp({ maxAmount: '0.1' }).mcp(client) // [!code hl]
const result = await caller.callTool({ arguments: {}, name: 'fortune' })
console.log(result.content, result.receipt?.reference)
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { mpp } from 'accounts/mpp'
import { device } from 'accounts/plugins'
export const accounts = Accounts.create({
// Each sign-in requests an access key that spends up to 1 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '1', token: 'ousd' }],
}),
chain: 'testnet',
clientId: 'cli:mcp-example',
plugins: [
device({
onCode: (code) =>
console.log(
`Open ${code.verificationUriComplete} and confirm the code ${code.userCode}.`,
),
}),
mpp(),
],
})
```
:::
### Sign in from a page
A page signs in for the resource with `resource` on `dialog.signIn` . The sign-in runs in the dialog's frame if the preloaded frame reports that it issues tokens for a resource, and in a popup otherwise. Call it in a click handler.
:::code-group
```tsx [SignIn.tsx]
import { accounts } from './tempo.config.js'
export function SignIn() {
return (
accounts.dialog.signIn({ resource: 'https://mcp.example.com/mcp' }) // [!code hl]
}
type="button"
>
Sign in with Tempo
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { mpp } from 'accounts/mpp'
export const accounts = Accounts.create({
// Each sign-in requests an access key that spends up to 1 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '1', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [mpp()],
})
```
:::
### Attribute each payment
`clientId` names the app. Each charge's transfer memo then carries its fingerprint, so the server attributes the payment to the app.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { mpp } from 'accounts/mpp'
import { device } from 'accounts/plugins'
export const accounts = Accounts.create({
// Each sign-in requests an access key that spends up to 1 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '1', token: 'ousd' }],
}),
chain: 'testnet',
clientId: 'cli:mcp-example',
plugins: [
device({
onCode: (code) =>
console.log(
`Open ${code.verificationUriComplete} and confirm the code ${code.userCode}.`,
),
}),
mpp({ clientId: 'mcp-example' }), // [!code hl]
],
})
```
## Next steps
# Payment sessions \[An app pays for metered use through a payment channel, with vouchers of the access key.]
## Overview
A payment session pays for metered use, such as each request to an API, with one deposit and many offchain vouchers. The Tempo Account deposits in a payment channel, and the [access key](/docs/guides/access-keys) signs a voucher for each unit of use. The payee closes the channel with the highest voucher, and the rest returns to the account.
A payment session is not the [user session](/docs/guides/user-session). It suits many small payments to one payee, since a voucher pays no network fee.
## Guides
# Open payment channels \[An app opens a payment channel, and pays for metered use with vouchers of the access key.]
## Overview
The "Sessions" guides cover payment sessions over payment channels, not the package's sign-in [session](/docs/guides/user-session).
A payment channel pays for metered use with one deposit and many offchain vouchers. The Tempo Account deposits in the chain's TIP-1034 channel reserve, an escrow, and the [access key](/docs/guides/access-keys) signs a voucher for each unit of use, with no prompt. The payee closes the channel with the highest voucher, and the reserve returns the rest.
This guide opens the channel with Viem and verifies vouchers on the app's server. [Pay with sessions](/docs/guides/sessions/mpp) leaves both to MPP, a protocol of HTTP 402 payments.
The demo opens a 0.05 OUSD channel on Tempo testnet, pays 0.001 OUSD for each fortune, and after the close shows what the server received and the channel returned.
## Walkthrough
The steps build the demo's React app and server.
```mermaid
sequenceDiagram
participant App as App (accounts)
participant Server
participant Reserve as Channel reserve
App->>Reserve: openSync, with the deposit
loop Each request
App->>Server: Voucher for the new total
Server->>Reserve: getStates
Server-->>App: Paid content
end
App->>Server: Close request
Server->>Reserve: closeSync, with the highest voucher
Note over Reserve: Pays the payee, and returns the rest to the Tempo Account
```
::::steps
### Install the packages
The server verifies each voucher with ox, and serves its routes with Hono.
:::code-group
```sh [npm]
npm install accounts hono ox react react-dom viem
```
```sh [pnpm]
pnpm add accounts hono ox react react-dom viem
```
```sh [bun]
bun add accounts hono ox react react-dom viem
```
:::
### Create the instance
The `viem` plugin adds Viem's channel actions to the instance, as `accounts.channel`.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that spends up to 1 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '1', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [react(), viem()], // [!code hl]
})
```
Without `scopes` , the access key may open and top up a channel on the reserve, and each deposit counts against its token's limit.
### Sign the user in
`dialog.signIn` opens Tempo ID's dialog over the page.
:::code-group
```tsx [App.tsx]
import { accounts } from './tempo.config.js'
export function App() {
const { session } = accounts.useSession()
// [!code hl:start]
if (!session)
return (
accounts.dialog.signIn()} type="button">
Sign in with Tempo
)
// [!code hl:end]
return Signed in as {session.user.email}
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that spends up to 1 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '1', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [react(), viem()],
})
```
:::
### Open the channel
`openSync` deposits in the reserve, and returns the fields that name the channel in each voucher, top-up, and close. The component keeps them in its state.
:::code-group
```tsx [Open.tsx]
import type { Channel } from 'ox/tempo'
import { useState } from 'react'
import { parseUnits } from 'viem'
import { Addresses } from 'viem/tempo'
import { accounts } from './tempo.config.js'
export function Open() {
const { session } = accounts.useSession()
const [channel, setChannel] = useState()
if (channel) return The channel is open.
return (
{
// [!code hl:start]
const { channelId, deposit, receipt, ...channel } =
await accounts.channel.openSync({
// The access key signs each voucher.
authorizedSigner: session!.accessKey!.keyAuthorization.keyId,
deposit: parseUnits('0.05', 6),
feeToken: Addresses.ousd,
// The address of the server's account.
payee: '0x401a632ADBFCc5C8Ce7D2B80D16f7DFc47b642bc',
token: Addresses.ousd,
})
// [!code hl:end]
setChannel(channel)
}}
type="button"
>
Open a channel
)
}
```
```tsx [App.tsx]
import { Open } from './Open.js'
import { accounts } from './tempo.config.js'
export function App() {
const { session } = accounts.useSession()
if (!session)
return (
accounts.dialog.signIn()} type="button">
Sign in with Tempo
)
return // [!code hl]
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that spends up to 1 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '1', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [react(), viem()],
})
```
:::
* `authorizedSigner` names the access key as the voucher signer, or the reserve refuses its vouchers at the close.
* `feeToken` names a token of the access key's limits, since the access key pays fees in no other token. A transfer pays its fee in the token that it sends, but an open sends no token, so it names one.
### Pay with a voucher
A voucher names the channel's cumulative total, so each voucher replaces the last.
:::code-group
```tsx [Pay.tsx]
import type { Channel } from 'ox/tempo'
import { useState } from 'react'
import { parseUnits } from 'viem'
import { accounts } from './tempo.config.js'
export function Pay(props: Pay.Props) {
const { channel } = props
const [fortune, setFortune] = useState()
// The total of the last voucher that the server accepted, in base units.
const [spent, setSpent] = useState(0n)
return (
<>
{
// [!code hl:start]
const cumulativeAmount = spent + parseUnits('0.001', 6)
const signature = await accounts.channel.signVoucher({
channel,
cumulativeAmount,
})
// [!code hl:end]
const response = await fetch('/api/fortune', {
body: JSON.stringify({
channel,
cumulativeAmount: cumulativeAmount.toString(),
signature,
}),
headers: { 'content-type': 'application/json' },
method: 'POST',
})
// A refused voucher keeps the last total.
if (!response.ok) return
const { fortune } = (await response.json()) as { fortune: string }
setFortune(fortune)
setSpent(cumulativeAmount)
}}
type="button"
>
Pay 0.001 OUSD
{fortune}
>
)
}
export declare namespace Pay {
type Props = {
/** The channel, as its open returns it. */
channel: Channel.Resolved
}
}
```
```tsx [Open.tsx]
import type { Channel } from 'ox/tempo'
import { useState } from 'react'
import { parseUnits } from 'viem'
import { Addresses } from 'viem/tempo'
import { Pay } from './Pay.js'
import { accounts } from './tempo.config.js'
export function Open() {
const { session } = accounts.useSession()
const [channel, setChannel] = useState()
// [!code hl:start]
if (channel) return
// [!code hl:end]
return (
{
const { channelId, deposit, receipt, ...channel } =
await accounts.channel.openSync({
// The access key signs each voucher.
authorizedSigner: session!.accessKey!.keyAuthorization.keyId,
deposit: parseUnits('0.05', 6),
feeToken: Addresses.ousd,
// The address of the server's account.
payee: '0x401a632ADBFCc5C8Ce7D2B80D16f7DFc47b642bc',
token: Addresses.ousd,
})
setChannel(channel)
}}
type="button"
>
Open a channel
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that spends up to 1 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '1', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [react(), viem()],
})
```
:::
### Verify the voucher on the server
The server accepts a voucher only if it passes every check below, and keeps each channel's highest voucher in a store for the close. The later server steps import this module.
```ts [vouchers.ts]
import { Store } from 'accounts'
import { Address } from 'ox'
import { Channel, SignatureEnvelope } from 'ox/tempo'
import { createClient, type Hex, http, parseUnits } from 'viem'
import { privateKeyToAccount } from 'viem/accounts'
import { tempoModerato } from 'viem/chains'
import { Actions, Addresses } from 'viem/tempo'
export const client = createClient({
account: privateKeyToAccount(process.env.PAYEE_PRIVATE_KEY as Hex),
chain: tempoModerato.extend({ feeToken: Addresses.ousd }),
transport: http(),
})
// The highest voucher of each channel.
export const store = Store.memory()
export type Voucher = {
channel: Channel.Resolved
cumulativeAmount: bigint
signature: Hex
}
export async function accept(voucher: Voucher) {
const { channel, cumulativeAmount, signature } = voucher
const chainId = client.chain.id
const channelId = Channel.computeId(channel, { chainId })
if (!Address.isEqual(channel.payee, client.account.address)) return false
if (!Address.isEqual(channel.token, Addresses.ousd)) return false
const signed = SignatureEnvelope.verify(SignatureEnvelope.from(signature), {
address: channel.authorizedSigner,
payload: Channel.getVoucherSignPayload({
chainId,
channelId,
cumulativeAmount,
}),
})
if (!signed) return false
const last = (await store.getItem(channelId)) as Voucher | undefined
const paid = last?.cumulativeAmount ?? 0n
if (cumulativeAmount < paid + parseUnits('0.001', 6)) return false
const state = await Actions.channel.getStates(client, { channel: channelId })
if (state.closeRequestedAt !== 0) return false
if (cumulativeAmount > state.deposit) return false
await store.setItem(channelId, voucher)
return true
}
```
| Check | Refuses |
| --------------- | ----------------------------------------------------- |
| Payee and token | A channel that pays another account, or another token |
| Signature | A voucher that the access key did not sign |
| Amount | A voucher that pays less than the price of the unit |
| Close request | A channel whose payer requested a close |
| Deposit | A voucher that the deposit does not cover |
:::note
`Store.memory` keeps the vouchers in the process, so a restart loses them. In production, use a store that each replica shares, such as `Store.postgres` or `Store.redis` .
:::
:::warning
The store reads and writes in two calls, so two concurrent requests with one voucher can both pass. A server that answers one channel's requests in parallel updates the voucher atomically, such as in a Redis transaction.
:::
### Serve the paid route
The route answers 402 for a refused voucher. `Channel.from` throws for a malformed channel.
:::code-group
```ts [server.ts]
import { Hono } from 'hono'
import { Channel } from 'ox/tempo'
import { accept } from './vouchers.js'
const app = new Hono()
// [!code hl:start]
app.post('/api/fortune', async (c) => {
const body = await c.req.json()
const paid = await accept({
channel: Channel.from(body.channel),
cumulativeAmount: BigInt(body.cumulativeAmount),
signature: body.signature,
})
if (!paid) return c.json({ error: 'The voucher is refused.' }, 402)
return c.json({ fortune: 'Pay for what you use.' })
})
// [!code hl:end]
export default app
```
```ts [vouchers.ts]
import { Store } from 'accounts'
import { Address } from 'ox'
import { Channel, SignatureEnvelope } from 'ox/tempo'
import { createClient, type Hex, http, parseUnits } from 'viem'
import { privateKeyToAccount } from 'viem/accounts'
import { tempoModerato } from 'viem/chains'
import { Actions, Addresses } from 'viem/tempo'
export const client = createClient({
account: privateKeyToAccount(process.env.PAYEE_PRIVATE_KEY as Hex),
chain: tempoModerato.extend({ feeToken: Addresses.ousd }),
transport: http(),
})
// The highest voucher of each channel.
export const store = Store.memory()
export type Voucher = {
channel: Channel.Resolved
cumulativeAmount: bigint
signature: Hex
}
export async function accept(voucher: Voucher) {
const { channel, cumulativeAmount, signature } = voucher
const chainId = client.chain.id
const channelId = Channel.computeId(channel, { chainId })
if (!Address.isEqual(channel.payee, client.account.address)) return false
if (!Address.isEqual(channel.token, Addresses.ousd)) return false
const signed = SignatureEnvelope.verify(SignatureEnvelope.from(signature), {
address: channel.authorizedSigner,
payload: Channel.getVoucherSignPayload({
chainId,
channelId,
cumulativeAmount,
}),
})
if (!signed) return false
const last = (await store.getItem(channelId)) as Voucher | undefined
const paid = last?.cumulativeAmount ?? 0n
if (cumulativeAmount < paid + parseUnits('0.001', 6)) return false
const state = await Actions.channel.getStates(client, { channel: channelId })
if (state.closeRequestedAt !== 0) return false
if (cumulativeAmount > state.deposit) return false
await store.setItem(channelId, voucher)
return true
}
```
:::
### Close the channel on the server
`closeSync` sends the highest voucher to the reserve, which pays the payee its amount and returns the rest to the Tempo Account. The payee pays the fee, so its address holds OUSD.
:::code-group
```ts [server.ts]
import { Hono } from 'hono'
import { Channel } from 'ox/tempo'
import { Actions } from 'viem/tempo'
import { accept, client, store, type Voucher } from './vouchers.js'
const app = new Hono()
app.post('/api/fortune', async (c) => {
const body = await c.req.json()
const paid = await accept({
channel: Channel.from(body.channel),
cumulativeAmount: BigInt(body.cumulativeAmount),
signature: body.signature,
})
if (!paid) return c.json({ error: 'The voucher is refused.' }, 402)
return c.json({ fortune: 'Pay for what you use.' })
})
// [!code hl:start]
app.post('/api/close', async (c) => {
const body = await c.req.json()
const channelId = Channel.computeId(Channel.from(body.channel), {
chainId: client.chain.id,
})
const voucher = (await store.getItem(channelId)) as Voucher | undefined
if (!voucher) return c.json({ error: 'The channel holds no voucher.' }, 404)
const { refundedToPayer, settledToPayee } = await Actions.channel.closeSync(
client,
{ ...voucher, captureAmount: voucher.cumulativeAmount },
)
await store.removeItem(channelId)
return c.json({
refundedToPayer: refundedToPayer.toString(),
settledToPayee: settledToPayee.toString(),
})
})
// [!code hl:end]
export default app
```
```ts [vouchers.ts]
import { Store } from 'accounts'
import { Address } from 'ox'
import { Channel, SignatureEnvelope } from 'ox/tempo'
import { createClient, type Hex, http, parseUnits } from 'viem'
import { privateKeyToAccount } from 'viem/accounts'
import { tempoModerato } from 'viem/chains'
import { Actions, Addresses } from 'viem/tempo'
export const client = createClient({
account: privateKeyToAccount(process.env.PAYEE_PRIVATE_KEY as Hex),
chain: tempoModerato.extend({ feeToken: Addresses.ousd }),
transport: http(),
})
// The highest voucher of each channel.
export const store = Store.memory()
export type Voucher = {
channel: Channel.Resolved
cumulativeAmount: bigint
signature: Hex
}
export async function accept(voucher: Voucher) {
const { channel, cumulativeAmount, signature } = voucher
const chainId = client.chain.id
const channelId = Channel.computeId(channel, { chainId })
if (!Address.isEqual(channel.payee, client.account.address)) return false
if (!Address.isEqual(channel.token, Addresses.ousd)) return false
const signed = SignatureEnvelope.verify(SignatureEnvelope.from(signature), {
address: channel.authorizedSigner,
payload: Channel.getVoucherSignPayload({
chainId,
channelId,
cumulativeAmount,
}),
})
if (!signed) return false
const last = (await store.getItem(channelId)) as Voucher | undefined
const paid = last?.cumulativeAmount ?? 0n
if (cumulativeAmount < paid + parseUnits('0.001', 6)) return false
const state = await Actions.channel.getStates(client, { channel: channelId })
if (state.closeRequestedAt !== 0) return false
if (cumulativeAmount > state.deposit) return false
await store.setItem(channelId, voucher)
return true
}
```
:::
:::warning
A payer can close a channel without the payee\: it calls `requestClose` on the channel reserve, and withdraws the unsettled deposit after 15 minutes. A server thus closes each channel within 15 minutes of its close request. Without `scopes` , the access key may make neither call.
:::
### Request the close
`Close` posts the app's channel to the route.
:::code-group
```tsx [Close.tsx]
import type { Channel } from 'ox/tempo'
export function Close(props: Close.Props) {
const { channel } = props
return (
// [!code hl:start]
fetch('/api/close', {
body: JSON.stringify({ channel }),
headers: { 'content-type': 'application/json' },
method: 'POST',
})
// [!code hl:end]
}
type="button"
>
Close the channel
)
}
export declare namespace Close {
type Props = {
/** The channel, as its open returns it. */
channel: Channel.Resolved
}
}
```
```tsx [Open.tsx]
import type { Channel } from 'ox/tempo'
import { useState } from 'react'
import { parseUnits } from 'viem'
import { Addresses } from 'viem/tempo'
import { Close } from './Close.js'
import { Pay } from './Pay.js'
import { accounts } from './tempo.config.js'
export function Open() {
const { session } = accounts.useSession()
const [channel, setChannel] = useState()
// [!code hl:start]
if (channel)
return (
<>
>
)
// [!code hl:end]
return (
{
const { channelId, deposit, receipt, ...channel } =
await accounts.channel.openSync({
// The access key signs each voucher.
authorizedSigner: session!.accessKey!.keyAuthorization.keyId,
deposit: parseUnits('0.05', 6),
feeToken: Addresses.ousd,
// The address of the server's account.
payee: '0x401a632ADBFCc5C8Ce7D2B80D16f7DFc47b642bc',
token: Addresses.ousd,
})
setChannel(channel)
}}
type="button"
>
Open a channel
)
}
```
```tsx [Pay.tsx]
import type { Channel } from 'ox/tempo'
import { useState } from 'react'
import { parseUnits } from 'viem'
import { accounts } from './tempo.config.js'
export function Pay(props: Pay.Props) {
const { channel } = props
const [fortune, setFortune] = useState()
// The total of the last voucher that the server accepted, in base units.
const [spent, setSpent] = useState(0n)
return (
<>
{
const cumulativeAmount = spent + parseUnits('0.001', 6)
const signature = await accounts.channel.signVoucher({
channel,
cumulativeAmount,
})
const response = await fetch('/api/fortune', {
body: JSON.stringify({
channel,
cumulativeAmount: cumulativeAmount.toString(),
signature,
}),
headers: { 'content-type': 'application/json' },
method: 'POST',
})
// A refused voucher keeps the last total.
if (!response.ok) return
const { fortune } = (await response.json()) as { fortune: string }
setFortune(fortune)
setSpent(cumulativeAmount)
}}
type="button"
>
Pay 0.001 OUSD
{fortune}
>
)
}
export declare namespace Pay {
type Props = {
/** The channel, as its open returns it. */
channel: Channel.Resolved
}
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that spends up to 1 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '1', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [react(), viem()],
})
```
:::
::::
## Use cases
Each use case calls one more channel action\: on the page, through the client of the `viem` plugin, or on the server, through the payee's client.
### Top up the channel
`topUpSync` adds to the deposit, and the server reads the new deposit from `getStates`. Render `TopUp` beside `Pay`.
:::code-group
```tsx [TopUp.tsx]
import type { Channel } from 'ox/tempo'
import { parseUnits } from 'viem'
import { Addresses } from 'viem/tempo'
import { accounts } from './tempo.config.js'
export function TopUp(props: TopUp.Props) {
const { channel } = props
return (
// [!code hl:start]
accounts.channel.topUpSync({
additionalDeposit: parseUnits('0.05', 6),
channel,
feeToken: Addresses.ousd,
})
// [!code hl:end]
}
type="button"
>
Add 0.05 OUSD
)
}
export declare namespace TopUp {
type Props = {
/** The channel, as its open returns it. */
channel: Channel.Resolved
}
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that spends up to 1 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '1', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [react(), viem()],
})
```
:::
### Settle before the close
`settleSync` collects up to a voucher from a long-lived channel, and keeps it open. Add `settle` to the server of the close step.
:::code-group
```ts [server.ts]
import { Hono } from 'hono'
import { Channel } from 'ox/tempo'
import type { Hex } from 'viem'
import { Actions } from 'viem/tempo'
import { accept, client, store, type Voucher } from './vouchers.js'
const app = new Hono()
app.post('/api/fortune', async (c) => {
const body = await c.req.json()
const paid = await accept({
channel: Channel.from(body.channel),
cumulativeAmount: BigInt(body.cumulativeAmount),
signature: body.signature,
})
if (!paid) return c.json({ error: 'The voucher is refused.' }, 402)
return c.json({ fortune: 'Pay for what you use.' })
})
app.post('/api/close', async (c) => {
const body = await c.req.json()
const channelId = Channel.computeId(Channel.from(body.channel), {
chainId: client.chain.id,
})
const voucher = (await store.getItem(channelId)) as Voucher | undefined
if (!voucher) return c.json({ error: 'The channel holds no voucher.' }, 404)
const { refundedToPayer, settledToPayee } = await Actions.channel.closeSync(
client,
{ ...voucher, captureAmount: voucher.cumulativeAmount },
)
await store.removeItem(channelId)
return c.json({
refundedToPayer: refundedToPayer.toString(),
settledToPayee: settledToPayee.toString(),
})
})
// [!code hl:start]
async function settle(channelId: Hex) {
const voucher = (await store.getItem(channelId)) as Voucher | undefined
if (!voucher) return undefined
const { deltaPaid } = await Actions.channel.settleSync(client, voucher)
return deltaPaid
}
// [!code hl:end]
export default app
```
```ts [vouchers.ts]
import { Store } from 'accounts'
import { Address } from 'ox'
import { Channel, SignatureEnvelope } from 'ox/tempo'
import { createClient, type Hex, http, parseUnits } from 'viem'
import { privateKeyToAccount } from 'viem/accounts'
import { tempoModerato } from 'viem/chains'
import { Actions, Addresses } from 'viem/tempo'
export const client = createClient({
account: privateKeyToAccount(process.env.PAYEE_PRIVATE_KEY as Hex),
chain: tempoModerato.extend({ feeToken: Addresses.ousd }),
transport: http(),
})
// The highest voucher of each channel.
export const store = Store.memory()
export type Voucher = {
channel: Channel.Resolved
cumulativeAmount: bigint
signature: Hex
}
export async function accept(voucher: Voucher) {
const { channel, cumulativeAmount, signature } = voucher
const chainId = client.chain.id
const channelId = Channel.computeId(channel, { chainId })
if (!Address.isEqual(channel.payee, client.account.address)) return false
if (!Address.isEqual(channel.token, Addresses.ousd)) return false
const signed = SignatureEnvelope.verify(SignatureEnvelope.from(signature), {
address: channel.authorizedSigner,
payload: Channel.getVoucherSignPayload({
chainId,
channelId,
cumulativeAmount,
}),
})
if (!signed) return false
const last = (await store.getItem(channelId)) as Voucher | undefined
const paid = last?.cumulativeAmount ?? 0n
if (cumulativeAmount < paid + parseUnits('0.001', 6)) return false
const state = await Actions.channel.getStates(client, { channel: channelId })
if (state.closeRequestedAt !== 0) return false
if (cumulativeAmount > state.deposit) return false
await store.setItem(channelId, voucher)
return true
}
```
:::
The reserve refuses a voucher that is not above the settled amount.
### Withdraw without the payee
If the server never closes the channel, the app takes the deposit back itself. `requestCloseSync` starts the reserve's timer, and the server then accepts no voucher. After 15 minutes, `withdrawSync` returns the deposit that no voucher settled.
The filled `scopes` allow neither call. Named scopes replace them, so the access key names each call of the reserve that it makes.
:::code-group
```tsx [Withdraw.tsx]
import type { Channel } from 'ox/tempo'
import { Addresses } from 'viem/tempo'
import { accounts } from './tempo.config.js'
export function Withdraw(props: Withdraw.Props) {
const { channel } = props
return (
<>
accounts.channel.requestCloseSync({ channel, feeToken: Addresses.ousd }) // [!code hl]
}
type="button"
>
Request the close
{/* The reserve allows the withdrawal 15 minutes after the request. */}
accounts.channel.withdrawSync({ channel, feeToken: Addresses.ousd }) // [!code hl]
}
type="button"
>
Withdraw the deposit
>
)
}
export declare namespace Withdraw {
type Props = {
/** The channel, as its open returns it. */
channel: Channel.Resolved
}
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
import { Addresses, Scopes, Selectors } from 'viem/tempo'
const reserve = Scopes.contract(
Addresses.tip20ChannelReserve,
Selectors.tip20ChannelReserve,
)
export const accounts = Accounts.create({
// Each sign-in requests an access key that spends up to 1 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '1', token: 'ousd' }],
// [!code hl:start]
scopes: [
reserve.open(),
reserve.requestClose(),
reserve.topUp(),
reserve.withdraw(),
],
// [!code hl:end]
}),
chain: 'testnet',
plugins: [react(), viem()],
})
```
:::
## Next steps
# Pay with sessions \[An app pays a metered endpoint in an MPP session, with vouchers of the access key.]
## Overview
Here a "session" is an MPP payment session over a payment channel, not the package's sign-in [session](/docs/guides/user-session).
The [Machine Payments Protocol](https\://mpp.dev) (MPP) prices HTTP endpoints with status 402 Payment Required\: an endpoint answers an unpaid request with a 402 challenge, and serves the content once the retry carries a payment credential.
An MPP session pays for metered use through a payment channel. The first request opens the channel with a deposit, each later request pays with an offchain voucher of the [access key](/docs/guides/access-keys), and the close settles the channel and returns the rest.
The `mpp` plugin runs the session through [mppx](https\://github.com/wevm/mppx), MPP's TypeScript SDK. [Open payment channels](/docs/guides/sessions/self-managed) builds the same flow without MPP.
The demo starts a session that deposits at most 0.05 OUSD on Tempo testnet, pays 0.001 OUSD for each fortune, and after the close shows what the server received.
## Walkthrough
The [`mpp-session`](https\://github.com/tempoxyz/accounts/tree/main/examples/mpp-session) example runs these steps, and also pays over SSE and a WebSocket with the session manager's `sse` and `ws`.
::::steps
### Install the packages
The server serves its route with Hono.
:::code-group
```sh [npm]
npm install accounts hono mppx react react-dom viem
```
```sh [pnpm]
pnpm add accounts hono mppx react react-dom viem
```
```sh [bun]
bun add accounts hono mppx react react-dom viem
```
:::
### Create the instance
The `mpp` plugin adds MPP payments to the instance.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { mpp } from 'accounts/mpp'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that spends up to 1 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '1', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [react(), viem(), mpp()], // [!code hl]
})
```
Without `scopes` , the access key may open and top up a channel on the chain's TIP-1034 channel reserve, and each deposit counts against its token's limit.
### Sign the user in
`dialog.signIn` opens Tempo ID's dialog over the page.
:::code-group
```tsx [App.tsx]
import { accounts } from './tempo.config.js'
export function App() {
const { session } = accounts.useSession()
// [!code hl:start]
if (!session)
return (
accounts.dialog.signIn()} type="button">
Sign in with Tempo
)
// [!code hl:end]
return Signed in as {session.user.email}
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { mpp } from 'accounts/mpp'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that spends up to 1 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '1', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [react(), viem(), mpp()],
})
```
:::
### Start the payment session
`accounts.mpp.session` returns a session manager, which holds the channel in memory and opens none yet. `maxDeposit` caps the first deposit, each automatic top-up, and the session's total.
:::code-group
```tsx [Start.tsx]
import type { mpp } from 'accounts/mpp'
import { useState } from 'react'
import { accounts } from './tempo.config.js'
export function Start() {
const [manager, setManager] = useState()
// The manager opens no channel before its first request.
if (manager) return Session started
return (
setManager(accounts.mpp.session({ maxDeposit: '0.05' }))} // [!code hl]
type="button"
>
Start a session
)
}
```
```tsx [App.tsx]
import { Start } from './Start.js'
import { accounts } from './tempo.config.js'
export function App() {
const { session } = accounts.useSession()
if (!session)
return (
accounts.dialog.signIn()} type="button">
Sign in with Tempo
)
return // [!code hl]
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { mpp } from 'accounts/mpp'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that spends up to 1 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '1', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [react(), viem(), mpp()],
})
```
:::
### Pay each request
The manager's `fetch` pays each request with no prompt. The first opens the channel with the endpoint's suggested deposit, up to `maxDeposit` , and each later one pays with a voucher.
:::code-group
```tsx [Pay.tsx]
import type { mpp } from 'accounts/mpp'
import { useState } from 'react'
import { formatUnits } from 'viem'
export function Pay(props: Pay.Props) {
const { manager } = props
const [fortune, setFortune] = useState()
// The total that the vouchers of the session pay, in base units.
const [spent, setSpent] = useState(0n)
return (
<>
{
// [!code hl:start]
const response = await manager.fetch(
'https://api.example.com/fortune',
)
// [!code hl:end]
const { fortune } = (await response.json()) as { fortune: string }
setFortune(fortune)
setSpent(manager.cumulative)
}}
type="button"
>
Pay 0.001 OUSD
{fortune}
Spent {formatUnits(spent, 6)} OUSD
>
)
}
export declare namespace Pay {
type Props = {
/** The manager of the session. */
manager: mpp.SessionManager
}
}
```
```tsx [Start.tsx]
import type { mpp } from 'accounts/mpp'
import { useState } from 'react'
import { Pay } from './Pay.js'
import { accounts } from './tempo.config.js'
export function Start() {
const [manager, setManager] = useState()
// [!code hl:start]
if (manager) return
// [!code hl:end]
return (
setManager(accounts.mpp.session({ maxDeposit: '0.05' }))}
type="button"
>
Start a session
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { mpp } from 'accounts/mpp'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that spends up to 1 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '1', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [react(), viem(), mpp()],
})
```
:::
A request that needs a voucher above `maxDeposit` throws before any payment.
### Close the payment session
`close` settles the channel at the last voucher, and returns the endpoint's receipt. If the app drops the manager before `close`, the deposit stays in the channel.
:::code-group
```tsx [Close.tsx]
import type { mpp } from 'accounts/mpp'
import { useState } from 'react'
export function Close(props: Close.Props) {
const { manager } = props
const [hash, setHash] = useState()
return (
<>
{
const receipt = await manager.close() // [!code hl]
setHash(receipt?.txHash)
}}
type="button"
>
Close the session
{hash}
>
)
}
export declare namespace Close {
type Props = {
/** The manager of the session. */
manager: mpp.SessionManager
}
}
```
```tsx [Start.tsx]
import type { mpp } from 'accounts/mpp'
import { useState } from 'react'
import { Close } from './Close.js'
import { Pay } from './Pay.js'
import { accounts } from './tempo.config.js'
export function Start() {
const [manager, setManager] = useState()
// [!code hl:start]
if (manager)
return (
<>
>
)
// [!code hl:end]
return (
setManager(accounts.mpp.session({ maxDeposit: '0.05' }))}
type="button"
>
Start a session
)
}
```
```tsx [Pay.tsx]
import type { mpp } from 'accounts/mpp'
import { useState } from 'react'
import { formatUnits } from 'viem'
export function Pay(props: Pay.Props) {
const { manager } = props
const [fortune, setFortune] = useState()
// The total that the vouchers of the session pay, in base units.
const [spent, setSpent] = useState(0n)
return (
<>
{
const response = await manager.fetch(
'https://api.example.com/fortune',
)
const { fortune } = (await response.json()) as { fortune: string }
setFortune(fortune)
setSpent(manager.cumulative)
}}
type="button"
>
Pay 0.001 OUSD
{fortune}
Spent {formatUnits(spent, 6)} OUSD
>
)
}
export declare namespace Pay {
type Props = {
/** The manager of the session. */
manager: mpp.SessionManager
}
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { mpp } from 'accounts/mpp'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that spends up to 1 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '1', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [react(), viem(), mpp()],
})
```
:::
A session that paid no request holds no channel, so `close` returns `undefined`.
A handler that pays a run of requests closes its session in a `finally` block, so the deposit returns also if a request throws.
### Serve the metered route
The endpoint is an mppx route. `tempo.session` verifies each voucher, and closes the channel with the payee's account, which pays the fee and thus holds OUSD.
```ts [server.ts]
import { Hono } from 'hono'
import { Mppx, tempo } from 'mppx/hono'
import { Store } from 'mppx/server'
import type { Hex } from 'viem'
import { privateKeyToAccount } from 'viem/accounts'
import { tempoModerato } from 'viem/chains'
import { Addresses } from 'viem/tempo'
const [session] = tempo.session({
account: privateKeyToAccount(process.env.PAYEE_PRIVATE_KEY as Hex),
chainId: tempoModerato.id,
currencies: [Addresses.ousd],
store: Store.memory(),
})
const mppx = Mppx.create({
methods: [session],
realm: 'api.example.com',
secretKey: process.env.MPP_SECRET_KEY!,
})
const app = new Hono()
// The close of a session is a POST to the route of its requests.
app.on(
['GET', 'POST'],
'/fortune',
mppx.session({
amount: '0.001',
suggestedDeposit: '0.05',
unitType: 'request',
}),
(c) => c.json({ fortune: 'Pay for what you use.' }),
)
export default app
```
`mppx.session` answers a request without a credential with the 402 challenge, and adds the receipt to each paid response.
:::note
The memory store of mppx keeps the channels in the process, so a restart loses them. In production, use a store of mppx with atomic updates that each replica shares, such as its Postgres or Redis store.
:::
:::warning
A payer can close a channel without the endpoint\: it calls `requestClose` on the channel reserve, and withdraws the unsettled deposit after 15 minutes. A deployed endpoint thus runs `tempo.session.superviseCloses` on a schedule, as the example describes.
:::
::::
## Use cases
Each use case sets one option of `accounts.mpp.session` or of the `mpp` plugin, or calls a method of the session manager.
### Top up the channel
A request that needs more than the deposit tops up the channel on its own, up to `maxDeposit` . Once a request opened the channel, `topUp` adds a deposit ahead of need, such as before a stream. Render `TopUp` beside `Pay`.
```tsx [TopUp.tsx]
import type { mpp } from 'accounts/mpp'
export function TopUp(props: TopUp.Props) {
const { manager } = props
return (
manager.topUp('0.01')} type="button"> {/* [!code hl] */}
Add 0.01 OUSD
)
}
export declare namespace TopUp {
type Props = {
/** The manager of the session. */
manager: mpp.SessionManager
}
}
```
`topUp` adds its amount as given, so the deposit can exceed `maxDeposit` . It throws if the amount plus the session's paid total exceeds the cap.
### Cap every session
The plugin's `maxDeposit` is the default of every payment session of the instance. A session manager's own `maxDeposit` replaces it, and an absent one keeps it.
A [guest session](/docs/guides/guest-checkout) holds no access key, so only `maxDeposit` caps its deposit. Its session manager without one throws `mpp.MaxDepositRequiredError` , and a value that is no decimal amount above 0, such as `''`, throws `mpp.MaxDepositInvalidError` , before any request.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { mpp } from 'accounts/mpp'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that spends up to 1 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '1', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [react(), viem(), mpp({ maxDeposit: '0.05' })], // [!code hl]
})
```
### Turn off the deposit page
On a page, a deposit or a top-up that the balance does not cover opens Tempo ID's deposit page, then sends again. `retry: { balance: false }` turns the deposit page off, so the request rejects as it is.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { mpp } from 'accounts/mpp'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that spends up to 1 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '1', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [react(), viem(), mpp({ retry: { balance: false } })], // [!code hl]
})
```
### Swap into the channel's token
`autoSwap` swaps another stablecoin into the channel's token on Tempo's exchange before a deposit, if the Tempo Account holds too little of it. The access key's limits must cover the token that the swap sells.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { mpp } from 'accounts/mpp'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
import { Addresses } from 'viem/tempo'
export const accounts = Accounts.create({
accessKey: () => ({
expiry: '1d',
limits: [
{ limit: '1', token: 'ousd' },
{ limit: '1', token: 'pathusd' }, // [!code hl]
],
}),
chain: 'testnet',
plugins: [
react(),
viem(),
// A deposit in OUSD sells pathUSD for the OUSD that the account lacks.
mpp({ autoSwap: { fallback: false, tokenIn: [Addresses.pathUsd] } }), // [!code hl]
],
})
```
## Next steps
# Payments \[An app sends a stablecoin payment from the user's Tempo Account.]
## Overview
A payment is a stablecoin transfer from the user's Tempo Account. The session's [access key](/docs/guides/access-keys) signs it with no prompt, within a limit that the user approves once. If no access key can pay, the account owner signs it on Tempo ID's payment page.
An app sends a payment of its own, such as for an order, in one call. A visitor without a Tempo Account pays through a [guest checkout](/docs/guides/guest-checkout), with a key pair that the app keeps. An [MPP](https\://mpp.dev) endpoint charges with an HTTP 402 response, which the access key pays.
## Guides
# Send payments \[Send a payment from a Tempo Account with the access key of the session, or on Tempo ID's payment page.]
## Overview
`accounts.pay` sends one stablecoin transfer from the user's Tempo Account. The session's [access key](/docs/guides/access-keys) signs it with no prompt, within the spending limit that the user approves once at the sign-in.
If no access key can pay, such as for an amount above the limit, the account's owner signs the transfer on Tempo ID's payment page. As an OAuth authorization request returns a code, the page returns to the app's redirect URI with the hash of the transaction.
The demo signs a user in for an access key that sends up to 10 OUSD for a day. It pays 1 OUSD with the access key, then 12 OUSD on the payment page, and links each transaction.
## Walkthrough
The [`web`](https\://github.com/tempoxyz/accounts/tree/main/examples/web) example runs these steps.
::::steps
### Install the packages
:::code-group
```sh [npm]
npm install accounts react react-dom viem
```
```sh [pnpm]
pnpm add accounts react react-dom viem
```
```sh [bun]
bun add accounts react react-dom viem
```
:::
### Create the instance
`accessKey` sets the permissions that each sign-in requests. With the `viem` plugin, the access key sends each payment that its limits hold, in place of the payment page.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 10 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '10', token: 'ousd' }],
}),
chain: 'testnet',
// The `viem` plugin sends each payment within the limit with the access key.
plugins: [react(), viem()],
})
```
### Sign the user in
The payment comes from the [session's](/docs/guides/user-session) Tempo Account. If the Tempo Account holds less than `funding` , Tempo ID's deposit page opens after the user approves the limit.
:::code-group
```tsx [App.tsx]
import { accounts } from './tempo.config.js'
export function App() {
const { session } = accounts.useSession()
if (!session)
return (
accounts.dialog.signIn({
funding: { amount: '10', token: 'OUSD' }, // [!code hl]
})
}
type="button"
>
Sign in with Tempo
)
return Signed in as {session.user.email}
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 10 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '10', token: 'ousd' }],
}),
chain: 'testnet',
// The `viem` plugin sends each payment within the limit with the access key.
plugins: [react(), viem()],
})
```
:::
### Send the payment
`accounts.pay` resolves with `transaction` once the chain includes the transfer. The app renders `Pay` for a signed-in user.
:::code-group
```tsx [Pay.tsx]
import { useState } from 'react'
import { accounts } from './tempo.config.js'
export function Pay() {
const [transaction, setTransaction] = useState()
return (
<>
{
// [!code hl:start]
const { transaction } = await accounts.pay({
// A decimal string in whole units.
amount: '1',
to: '0x000000000000000000000000000000000000dEaD',
// A symbol in any case, or an address.
token: 'ousd',
})
// [!code hl:end]
setTransaction(transaction)
}}
type="button"
>
Pay 1 OUSD
{transaction && Paid in {transaction}.
}
>
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 10 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '10', token: 'ousd' }],
}),
chain: 'testnet',
// The `viem` plugin sends each payment within the limit with the access key.
plugins: [react(), viem()],
})
```
:::
The access key sends the transfer if it signs on the payment's chain, acts for the account, and its limits hold the amount. Its transaction pays its own fee, so the limit of the fee token must also hold 0.1 for the fee. The fee token is the plugin's `feeToken`, else the payment's token if it is a USD stablecoin other than MACH.
Otherwise the payment page opens in a frame in a dialog. The page loads in a hidden dialog while the access key sends, so a transfer that lands shows no dialog, and the page shows at once after a transfer that the chain refuses, such as for a spent limit. A transfer that the chain refuses for a low balance opens the deposit page first, and the access key sends again once the deposit arrives. The page returns to the instance's `redirectUri` , or to the root of the page's origin.
An `amount` that is not a decimal above 0 with at most 6 decimal places rejects with `Accounts.RequestError` and the reason `invalid_field`, before any transfer, and so does a `to` that is no address. Without a session, the call rejects with `Accounts.SignedOutError` .
A Reject on the page, or a close of the dialog, rejects `accounts.pay` , and the transfer does not send\:
| The user | The error |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Selects **Reject** | An `Accounts.RequestError` with the `code` `access_denied` |
| Closes the dialog | A `DOMException` with the name `AbortError` |
::::
## Use cases
Each use case sets one option of `accounts.pay` , or of the instance that it runs on.
### Attach a memo
`memo` is the transfer's memo, which the chain records, such as an order ID\: text, sent as its UTF-8 bytes, or hex, of 1 to 32 bytes. A value is hex only if it is `0x` and an even count of hex digits. A memo over 32 bytes rejects with `Accounts.RequestError` and the code `invalid_request`, before any transfer.
:::code-group
```tsx [PayOrder.tsx]
import { accounts } from './tempo.config.js'
export function PayOrder() {
return (
accounts.pay({
amount: '5',
memo: 'order-123', // [!code hl]
to: '0x1f9090aaE28b8a3dCeaDf281B0F12828e676c326',
token: 'ousd',
})
}
type="button"
>
Pay 5 OUSD
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 10 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '10', token: 'ousd' }],
}),
chain: 'testnet',
// The `viem` plugin sends each payment within the limit with the access key.
plugins: [react(), viem()],
})
```
:::
### Add a note
`note` states what the payment is for, in at most 140 characters. Only the payment page shows the note, and the chain records none.
:::code-group
```tsx [PayPlan.tsx]
import { accounts } from './tempo.config.js'
export function PayPlan() {
return (
accounts.pay({
amount: '50',
note: 'Pro plan, November', // [!code hl]
to: '0x1f9090aaE28b8a3dCeaDf281B0F12828e676c326',
token: 'ousd',
})
}
type="button"
>
Pay 50 OUSD
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 10 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '10', token: 'ousd' }],
}),
chain: 'testnet',
// The `viem` plugin sends each payment within the limit with the access key.
plugins: [react(), viem()],
})
```
:::
### Sponsor the fee
`relay` sends each transfer of the access key through the app's relay route, whose fee payer pays the fee. The fee then counts against no limit. A sponsoring `transport` counts as no relay. [Use Tempo API](/docs/guides/fee-sponsorship/use-tempo-api) serves the route.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 10 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '10', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [react(), viem({ relay: '/api/relay' })], // [!code hl]
})
```
### Pay without an access key
An instance without the `viem` plugin sends each payment on the payment page, and the user approves each one there. With `accessKey` set to `false`, the sign-in requests no access key. The payment page of a third-party app then pays from the account selected for the app, else the user's oldest.
With the plugin, the payment page also sends `accounts.token.transfer` and `transferSync` on a page, for a session whose access keys sign no transaction on the chain, and that no sign-in renews. Only the amount, the memo, the recipient, and the token apply, and the action returns what Viem's own action returns.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
// No access key and no `viem` plugin, so the payment page sends each payment.
export const accounts = Accounts.create({
accessKey: false,
chain: 'testnet',
plugins: [react()],
})
```
### Pay as a guest
With a guest session, `accounts.pay` opens the payment page for the guest account, and the key pair in the instance's store signs the transfer in one click. An instance starts guest sessions only with `guest` . [Guest checkout](/docs/guides/guest-checkout) covers the flow, its funds, and its fees.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
// Without a session, the payment page offers Continue as guest.
guest: true, // [!code hl]
plugins: [react(), viem()],
})
```
### Open a popup
`mode: 'popup'` opens the payment page in a popup window. A frame without a Tempo ID session signs the user in on its own page, as `dialog.signIn` does, and creates a new user's passkey account there.
A frame that the app's page covers, or whose sign-in cannot show the payment, such as in a browser that keeps no frame cookie, requests a popup. A deposit by card does the same, and opens Buy MACH in the popup. The popup opens at once within the click, else the dialog offers it.
A popup opens only within a click, so call `accounts.pay` in a click handler. If the browser blocks the popup, the call rejects with `Actions.account.BlockedError` .
:::code-group
```tsx [PayInPopup.tsx]
import { accounts } from './tempo.config.js'
export function PayInPopup() {
return (
accounts.pay({
amount: '50',
mode: 'popup', // [!code hl]
to: '0x000000000000000000000000000000000000dEaD',
token: 'ousd',
})
}
type="button"
>
Pay 50 OUSD
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 10 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '10', token: 'ousd' }],
}),
chain: 'testnet',
// The `viem` plugin sends each payment within the limit with the access key.
plugins: [react(), viem()],
})
```
:::
:::note
A page that sends `Cross-Origin-Opener-Policy: same-origin` has no handle to the popup. The call then stays pending until its `signal` aborts.
:::
### Pay on another chain
`chainId` names the payment's chain, in place of the instance's. Pass `account` too, so the call reads no account before the page opens.
Without `account` , the payment comes from the session's Tempo Account, or the account of its access key. If the session holds neither, the instance reads the account, which only a first-party app can do from its page.
:::code-group
```tsx [PayOnMainnet.tsx]
import { accounts } from './tempo.config.js'
// The user's Tempo Account on Tempo mainnet, such as from the app's server.
const account = '0x1f9090aaE28b8a3dCeaDf281B0F12828e676c326'
export function PayOnMainnet() {
return (
accounts.pay({
// [!code hl:start]
account,
chainId: 4217,
// [!code hl:end]
amount: '1',
to: '0x000000000000000000000000000000000000dEaD',
token: 'usdc.e',
})
}
type="button"
>
Pay 1 USDC.e
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 10 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '10', token: 'ousd' }],
}),
chain: 'testnet',
// The `viem` plugin sends each payment within the limit with the access key.
plugins: [react(), viem()],
})
```
:::
### Pay and sign in
An app that does not know the user yet passes a Sign-In with Ethereum message as `challenge` , and no `account` . Tempo ID's page signs the user in if needed, and pays from the account selected for the app, else the user's oldest. The access key never sends such a payment.
**Pay** has the account sign the message, then sends the transfer, so the app knows who paid from one approval. The call resolves with `address` and `challengeSignature` beside `transaction` . The approval grants the app no tokens and no access key.
The message must name the redirect URI's origin and the payment's chain, with no resources, as `siwe.start` of the `siwe` plugin issues it. [Sign-in with a payment](https\://github.com/tempoxyz/id/blob/main/docs/payments.md#sign-in-with-a-payment) describes the rules.
On the page, the `siwe` plugin's `auth` names the server's two routes. A payment without `account` , while the instance holds no session, then requests the message at the click, while the dialog or the popup opens, so the user waits for neither in turn. After **Pay**, the instance posts the signature to the verify route, and the call returns the route's JSON object as `auth` .
:::code-group
```tsx [PayAndSignIn.tsx]
import { accounts } from './tempo.config.js'
export function PayAndSignIn() {
return (
{
// [!code hl:start]
const { address, auth, authError, transaction } = await accounts.pay({
amount: '1',
to: '0x000000000000000000000000000000000000dEaD',
token: 'ousd',
})
// [!code hl:end]
// The transfer landed also when the verification failed, so sign the user in again then.
if (authError) return
// `auth` is the verify route's JSON object, such as `{ session }`, or `{ token }` of a
// server in token mode, which the page keeps for its requests and never logs.
console.log(address, transaction, auth !== undefined)
}}
type="button"
>
Pay 1 OUSD
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { siwe } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [
react(),
// The backend's routes of the `siwe` plugin: `POST /api/auth/siwe/challenge` and
// `POST /api/auth/siwe`.
siwe({ auth: '/api/auth/siwe' }),
],
})
```
:::
| Route | Receives | Returns |
| --------- | ------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
| Challenge | `{ chainId }` | `{ message }`, or `{ id, message }` |
| Verify | `{ address, id, message, signature }`, without `id` for a challenge without one | Any JSON object, returned as `auth` |
If the challenge route fails, the dialog or the popup closes, and the call rejects before any transfer. A `challenge` function does the same without the plugin\: it runs at the click, and the call returns `challengeSignature` for the app to verify.
### Cancel a payment
To end a payment from the page, such as after a time limit, pass a `signal` . Its abort closes the dialog or the popup, and rejects the call with the signal's reason.
:::code-group
```tsx [PayWithTimeout.tsx]
import { accounts } from './tempo.config.js'
export function PayWithTimeout() {
return (
accounts.pay({
amount: '50',
// The dialog closes after two minutes without an answer.
signal: AbortSignal.timeout(120_000), // [!code hl]
to: '0x000000000000000000000000000000000000dEaD',
token: 'ousd',
})
}
type="button"
>
Pay 50 OUSD
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 10 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '10', token: 'ousd' }],
}),
chain: 'testnet',
// The `viem` plugin sends each payment within the limit with the access key.
plugins: [react(), viem()],
})
```
:::
### Send with Viem's token actions
`accounts.token.transferSync` is Viem's `Actions.token.transferSync`, signed by the access key. It takes Viem's parameters, such as an amount in the token's units, and resolves with the receipt.
Each transfer and its network fee count against the limit. On a page, a transfer above what is left opens Tempo ID's sign-in for a new access key, in place of the payment page, then sends again. If the user closes the sign-in, the transfer rejects with `Plugins.viem.RetryClosedError` . With `retry: { limit: false }` , the transfer rejects with the chain's error, with no sign-in.
In a CLI, a device code takes the place of the sign-in, as [Send above the limit or the balance](/docs/guides/cli#send-above-the-limit-or-the-balance) shows.
:::code-group
```tsx [Send.tsx]
import { parseUnits } from 'viem'
import { Addresses } from 'viem/tempo'
import { accounts } from './tempo.config.js'
export function Send() {
return (
// [!code hl:start]
accounts.token.transferSync({
amount: parseUnits('1', 6),
to: '0x000000000000000000000000000000000000dEaD',
token: Addresses.ousd,
})
// [!code hl:end]
}
type="button"
>
Send 1 OUSD
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 10 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '10', token: 'ousd' }],
}),
chain: 'testnet',
// The `viem` plugin sends each payment within the limit with the access key.
plugins: [react(), viem()],
})
```
:::
### Send from a backend
With the `backend` plugin, a server holds the session. `accounts.pay` with that `session` sends with its access key, as the [`backend`](https\://github.com/tempoxyz/accounts/tree/main/examples/backend) example shows.
A backend shows no payment page, so the access key sends any amount within the whole limit. A payment that the access key does not send rejects with `Actions.account.PageRequiredError` . A payment of an access key that the chain holds revoked rejects with `Accounts.AccessKeyRequiredError` . A session whose every access key expired rejects with `Accounts.SignedOutError` , before any request. A session with a live access key only on another chain rejects with `Accounts.AccessKeyRequiredError` .
```ts [server.ts]
import { Accounts, Store } from 'accounts'
import { backend, viem } from 'accounts/plugins'
import { Hono } from 'hono'
const accounts = Accounts.create({
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '10', token: 'ousd' }],
}),
chain: 'testnet',
clientId: process.env.APP_URL,
plugins: [backend({ store: Store.memory() }), viem()],
})
const app = new Hono()
// The sign-in routes of the `backend` plugin.
app.all('/api/*', (c) => accounts.handler.fetch(c.req.raw))
app.post('/pay', async (c) => {
const session = await accounts.session.get(c.req.raw)
if (session?.method !== 'tempo-id') return c.body(null, 401)
const { transaction } = await accounts.pay({
amount: '1',
session, // [!code hl]
to: '0x000000000000000000000000000000000000dEaD',
token: 'ousd',
})
return c.json({ transaction })
})
export default app
```
:::note
`Store.memory` keeps the sessions in the process, so a restart loses them. In production, use a store that each replica shares, such as `Store.postgres` or `Store.redis` .
:::
## Next steps
# Pay MPP charges \[Pay the 402 charge of an MPP endpoint with the access key of the session.]
## Overview
The [Machine Payments Protocol](https\://mpp.dev) (MPP) prices HTTP endpoints with status 402 Payment Required\: an endpoint answers an unpaid request with a 402 challenge, and serves the content once the retry carries a payment credential. A charge is a one-time payment by one transfer. `accounts.fetch` pays each charge with the session's [access key](/docs/guides/access-keys), with no prompt.
The demo signs a user in for an access key that spends up to 1 OUSD for a day, then fetches a route of this site that charges 0.01 OUSD, and shows the content and the receipt.
## Walkthrough
The [`mpp-charge`](https\://github.com/tempoxyz/accounts/tree/main/examples/mpp-charge) example runs these steps. Its server charges with [mppx](https\://github.com/wevm/mppx), MPP's TypeScript SDK.
::::steps
### Install the packages
The `mpp` plugin pays through mppx, a peer dependency. Every instance holds the plugin, so an app passes `mpp()` only to set its options.
:::code-group
```sh [npm]
npm install accounts mppx react react-dom viem
```
```sh [pnpm]
pnpm add accounts mppx react react-dom viem
```
```sh [bun]
bun add accounts mppx react react-dom viem
```
:::
### Create the instance
The access key's limit caps the sum of the charges. The `mpp` plugin adds `accounts.fetch` , which works the same in a CLI, with the session of the `device` plugin.
The plugin pays on the chain and the transport of the `viem` plugin, or of Tempo's own RPC without one. For a local node, [Use another Tempo ID or chain](/docs/guides/viem#use-another-tempo-id-or-chain) sets both.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { mpp } from 'accounts/mpp'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that spends up to 1 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '1', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [mpp(), react()],
})
```
### Sign the user in
If the Tempo Account holds less than `funding` , Tempo ID's deposit page opens after the user approves the limit.
:::code-group
```tsx [App.tsx]
import { accounts } from './tempo.config.js'
export function App() {
const { session } = accounts.useSession()
if (!session)
return (
accounts.dialog.signIn({
funding: { amount: '1', token: 'OUSD' }, // [!code hl]
})
}
type="button"
>
Sign in with Tempo
)
return Signed in as {session.user.email}
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { mpp } from 'accounts/mpp'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that spends up to 1 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '1', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [mpp(), react()],
})
```
:::
### Fetch the paid content
`accounts.fetch` is `fetch` that pays each 402 charge\: the access key signs the charge's transfer, and the endpoint broadcasts it. A response header holds the receipt. The app renders `Fortune` for a signed-in user.
:::code-group
```tsx [Fortune.tsx]
import { Receipt } from 'mppx'
import { useState } from 'react'
import { accounts } from './tempo.config.js'
export function Fortune() {
const [paid, setPaid] = useState<{ fortune: string; hash: string }>()
return (
<>
{
// [!code hl:start]
const response = await accounts.fetch(
'https://api.example.com/fortune',
)
// [!code hl:end]
const { fortune } = (await response.json()) as { fortune: string }
// The hash of the transaction that paid the charge.
const { reference } = Receipt.fromResponse(response)
setPaid({ fortune, hash: reference })
}}
type="button"
>
Fetch a fortune
{paid && (
{paid.fortune} Paid in {paid.hash}.
)}
>
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { mpp } from 'accounts/mpp'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that spends up to 1 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '1', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [mpp(), react()],
})
```
:::
On a page, if the balance does not cover a charge, Tempo ID's deposit page opens, and the request sends again after the deposit. A spent limit opens the sign-in for a new access key in the same way. If the user closes the screen, the request rejects with `Plugins.viem.RetryClosedError` .
On a page, Tempo ID's [payment page](/docs/guides/payments/self-managed) also pays a charge that no access key pays, such as one above the access key's whole limit, in mppx's `push` mode. The user approves the transfer there, and a Reject rejects with `Accounts.RequestError` and the code `access_denied`.
The payment page sends one transfer, so a charge of zero or with splits still needs the access key. A backend and `mcp` show no screen, so such a charge rejects with `mpp.LimitError` , or with `Accounts.AccessKeyRequiredError` without an access key. In a CLI, a device code opens the deposit page after its approval, as [Send above the limit or the balance](/docs/guides/cli#send-above-the-limit-or-the-balance) shows.
::::
## Use cases
Each use case sets one option of the `mpp` plugin, or of the payer that `accounts.mpp` returns for one call.
### Cap each charge
`maxAmount` caps one charge. A larger charge rejects with `mpp.MaxAmountError` before the access key signs.
:::code-group
```tsx [Fortune.tsx]
import { accounts } from './tempo.config.js'
export function Fortune() {
return (
{
const response = await accounts
.mpp({ maxAmount: '0.05' }) // [!code hl]
.fetch('https://api.example.com/fortune')
console.log(await response.json())
}}
type="button"
>
Fetch a fortune
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { mpp } from 'accounts/mpp'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that spends up to 1 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '1', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [mpp(), react()],
})
```
:::
`mpp({ maxAmount: '0.05' })` sets it for the instance. On a page, Tempo ID's payment page pays a charge above the access key's whole limit, as [Fetch the paid content](/docs/guides/payments/mpp#fetch-the-paid-content) describes. Elsewhere, such a charge rejects with `mpp.LimitError` . So does a charge that a concurrent charge of the same access key left above the limit, such as in a Worker that pays a user's requests in parallel.
A [guest session](/docs/guides/guest-checkout) holds no access key, so only `maxAmount` caps its charges. Without it, a charge above 0 rejects with `mpp.MaxAmountRequiredError` before the key pair signs.
### Turn off the deposit page
`retry` names the failures that show a screen of Tempo ID, then pay again. With `balance: false`, a charge that the balance does not cover rejects as it is, with no deposit page.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { mpp } from 'accounts/mpp'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that spends up to 1 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '1', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [mpp({ retry: { balance: false } }), react()], // [!code hl]
})
```
### Pay from a backend
With the `backend` plugin, a server holds the session, and `accounts.mpp({ session })` pays with its access key.
```ts [server.ts]
import { Accounts, Store } from 'accounts'
import { mpp } from 'accounts/mpp'
import { backend } from 'accounts/plugins'
import { Hono } from 'hono'
const accounts = Accounts.create({
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '1', token: 'ousd' }],
}),
chain: 'testnet',
clientId: process.env.APP_URL,
plugins: [backend({ store: Store.memory() }), mpp()],
})
const app = new Hono()
// The sign-in routes of the `backend` plugin.
app.all('/api/*', (c) => accounts.handler.fetch(c.req.raw))
app.get('/fortune', async (c) => {
const session = await accounts.session.get(c.req.raw)
if (session?.method !== 'tempo-id') return c.body(null, 401)
const response = await accounts
.mpp({ session }) // [!code hl]
.fetch('https://api.example.com/fortune')
return c.json(await response.json())
})
export default app
```
:::note
`Store.memory` keeps the sessions in the process, so a restart loses them. In production, use a store that each replica shares, such as `Store.postgres` or `Store.redis` .
:::
A backend shows no screen, so a refused charge rejects with its error.
A 402 response whose every Tempo charge names another chain than the access key's rejects with `mpp.ChainError` before the access key signs, on a page as on a backend.
### Prove who pays
An endpoint that verifies Tempo ID with mppx's `mppx/extensions/identity/tempo` reads who the user is, and refuses a payment from an account that the user did not grant to the app. `identity.scope` names the origins that receive the session's access token and ID token.
:::code-group
```tsx [Fortune.tsx]
import { accounts } from './tempo.config.js'
export function Fortune() {
return (
{
// The request carries the session's identity to the endpoint.
const response = await accounts.fetch('https://api.example.com/fortune')
console.log(await response.json())
}}
type="button"
>
Fetch a fortune
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { mpp } from 'accounts/mpp'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that spends up to 1 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '1', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [
mpp({ identity: { scope: ['https://api.example.com'] } }), // [!code hl]
react(),
],
})
```
:::
The endpoint takes the payment credential in `Payment-Authorization` with mppx's `requiresAuth: true`, so the paid request carries both. An endpoint without it takes the credential in `Authorization`, so its paid request carries no identity.
For a DPoP token, each request carries a new proof of the instance's `dpop` key. A Bearer token, such as one that the store saved before the app set its `dpop` key, goes with the Bearer scheme and no proof.
The ID token carries the user's email address when the sign-in requests the email scope. The payer sends it only until it expires, after 10 hours, unless a refresh returns a new one. A payer of a fixed `session` sends no identity.
### Attribute each payment
`clientId` names the app. Each charge's transfer memo then carries its fingerprint, so an endpoint attributes the payment to the app.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { mpp } from 'accounts/mpp'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that spends up to 1 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '1', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [mpp({ clientId: 'example.com' }), react()], // [!code hl]
})
```
### Swap into the charged token
`autoSwap` swaps another stablecoin into the charged token on Tempo's exchange, if the Tempo Account holds too little of it. The access key's limits must cover the token that the swap sells.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { mpp } from 'accounts/mpp'
import { react } from 'accounts/react'
import { Addresses } from 'viem/tempo'
export const accounts = Accounts.create({
accessKey: () => ({
expiry: '1d',
limits: [
{ limit: '1', token: 'ousd' },
{ limit: '1', token: 'pathusd' }, // [!code hl]
],
}),
chain: 'testnet',
plugins: [
// A charge in OUSD sells pathUSD for the OUSD that the account lacks.
mpp({ autoSwap: { fallback: false, tokenIn: [Addresses.pathUsd] } }), // [!code hl]
react(),
],
})
```
### Broadcast each charge
`mode: 'push'` has the app broadcast each charge's transaction, in place of the endpoint. The credential then names the transaction's hash.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { mpp } from 'accounts/mpp'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that spends up to 1 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '1', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [mpp({ mode: 'push' }), react()], // [!code hl]
})
```
### Refuse subscription offers
`orderChallenges` filters and sorts the offers of a 402 response before the access key signs. The payer pays the first offer that it returns, and pays none for an empty array.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { mpp } from 'accounts/mpp'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that spends up to 1 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '1', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [
mpp({
// [!code hl:start]
orderChallenges: (candidates) =>
candidates.filter((candidate) => candidate.challenge.intent === 'charge'),
// [!code hl:end]
}),
react(),
],
})
```
## Next steps
# Manage sessions \[A React app signs a user in, renders the session, and signs the user out.]
## Overview
The `react` plugin of `accounts/react` adds `accounts.useSession` , a hook that returns the [session](/docs/guides/user-session) and its status, and renders the component again at each change. This guide builds a component that signs a user in and out with it.
The demo shows each status of the session as it signs a user in and out.
## Walkthrough
The [`web`](https\://github.com/tempoxyz/accounts/tree/main/examples/web) example reads the session with the same hook.
::::steps
### Install the packages
:::code-group
```sh [npm]
npm install accounts react react-dom viem
```
```sh [pnpm]
pnpm add accounts react react-dom viem
```
```sh [bun]
bun add accounts react react-dom viem
```
:::
### Create the instance
Create one instance for the page, outside any render, since the instance holds the session.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [react()],
})
```
### Read the session
The hook's first render restores the saved session.
:::code-group
```tsx [App.tsx]
import { accounts } from './tempo.config.js'
export function Account() {
const { status } = accounts.useSession() // [!code hl]
return status = {status}
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [react()],
})
```
:::
### Add the sign-in button
`dialog.signIn` opens Tempo ID's dialog, and the status changes to `signedIn`.
:::code-group
```tsx [App.tsx]
import { accounts } from './tempo.config.js'
export function Account() {
const { status } = accounts.useSession() // [!code --]
const { session, status } = accounts.useSession() // [!code ++]
return status = {status}
// [!code --]
return ( // [!code ++]
{/* [!code ++] */}
status = {status}
{/* [!code ++] */}
{!session && ( // [!code ++]
accounts.dialog.signIn()} type="button"> {/* [!code ++] */}
Sign in {/* [!code ++] */}
// [!code ++]
)} {/* [!code ++] */}
// [!code ++]
) // [!code ++]
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [react()],
})
```
:::
### Add the sign-out button
`accounts.signOut` empties the session at once, and the status changes to `signedOut`. The user stays signed in to Tempo ID.
:::code-group
```tsx [App.tsx]
import { accounts } from './tempo.config.js'
export function Account() {
const { session, status } = accounts.useSession()
return (
status = {status}
{!session && (
accounts.dialog.signIn()} type="button">
Sign in
)}
{session && ( // [!code ++]
<> {/* [!code ++] */}
Signed in as {session.user.email}
{/* [!code ++] */}
accounts.signOut()} type="button"> {/* [!code ++] */}
Sign out {/* [!code ++] */}
{/* [!code ++] */}
> // [!code ++]
)} {/* [!code ++] */}
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [react()],
})
```
:::
### Show the pending state
The status is `pending` until the instance reads the saved session. Disable the sign-in button meanwhile, so a signed-in user starts no second sign-in.
:::code-group
```tsx [App.tsx]
import { accounts } from './tempo.config.js'
export function Account() {
const { session, status } = accounts.useSession() // [!code --]
const { isPending, session, status } = accounts.useSession() // [!code ++]
return (
status = {status}
{!session && (
accounts.dialog.signIn()} type="button"> {/* [!code --] */}
accounts.dialog.signIn()} // [!code ++]
type="button" // [!code ++]
> {/* [!code ++] */}
Sign in
)}
{session && (
<>
Signed in as {session.user.email}
accounts.signOut()} type="button">
Sign out
>
)}
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [react()],
})
```
:::
::::
## Use cases
Each use case sets an option of the `react` plugin, or reads a member that `accounts.useSession` returns.
### Show a renewal
`isReauthorizing` is `true` while an authorization renews a session whose access key expired. The hook returns the expired session meanwhile, so the page keeps the user on screen.
:::code-group
```tsx [App.tsx]
import { accounts } from './tempo.config.js'
export function Account() {
const { isReauthorizing, session } = accounts.useSession() // [!code hl]
if (!session) return null
return (
Signed in as {session.user.email}
{isReauthorizing ? ' (renewing the access key…)' : null}
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [react()],
})
```
:::
### Renew without an access key
On a page of a [first-party app](https\://github.com/tempoxyz/id/blob/main/docs/apps.md#first-party-apps), the first render renews a missing or expired session from the browser's Tempo ID session. An object as `reauthorizeOnMount` passes the parameters of that authorization, such as no access key.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [react({ reauthorizeOnMount: { accessKey: false } })], // [!code hl]
})
```
### Turn off the renewal
`reauthorizeOnMount: false` restores only the saved session, so a first-party page without one shows its sign-in. Other apps renew nothing by default, since they hold no grant to read the Tempo ID session.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [react({ reauthorizeOnMount: false })], // [!code hl]
})
```
## Next steps
# Subscriptions \[A user approves a recurring charge once, and the payee charges each period.]
## Overview
A subscription charges the user's Tempo Account once each period, such as 1 OUSD each month. The user approves an [access key](/docs/guides/access-keys) whose spending limit resets each period, and the chain refuses a charge above that limit.
If the app charges, its backend holds the access key. If another merchant charges, such as an API, the user approves the merchant's own access key through [MPP](https\://mpp.dev), a protocol of HTTP 402 payments.
## Guides
# Charge each period \[A backend charges a subscription with an access key whose limit resets each period.]
## Overview
At sign-in, the user approves an [access key](/docs/guides/access-keys) whose spending limit resets each period. A backend keeps the [session](/docs/guides/user-session), and charges each period with one transfer that the access key signs.
The Tempo chain refuses a transfer above the period's limit, so no payment protocol is needed. The backend's client ID is its origin, so it needs no registration.
The demo approves 1 OUSD each minute, charges the period from the site's server, and shows the chain's refusal of a second charge in the same minute.
## Walkthrough
These steps add a periodic limit, a charge, and a React page to the [`backend`](https\://github.com/tempoxyz/accounts/tree/main/examples/backend) example, a Hono server.
::::steps
### Install the packages
:::code-group
```sh [npm]
npm install accounts hono react react-dom viem
```
```sh [pnpm]
pnpm add accounts hono react react-dom viem
```
```sh [bun]
bun add accounts hono react react-dom viem
```
:::
### Create the instance
`period` takes a duration or whole seconds, and the scope makes the merchant the only recipient. `APP_URL` holds the app's origin.
As in [Backend](/docs/guides/backend), the `backend` plugin keeps each session in a store on the server, since a session holds an access key's private key.
```ts [tempo.config.ts]
import { Accounts, Store } from 'accounts'
import { backend, viem } from 'accounts/plugins'
import { privateKeyToAccount } from 'viem/accounts'
import { Addresses, Scopes } from 'viem/tempo'
// The merchant receives each charge, and pays its fee.
export const merchant = privateKeyToAccount(
process.env.MERCHANT_PRIVATE_KEY as `0x${string}`,
)
export const accounts = Accounts.create({
// Each access key sends 10 OUSD each 30 days, for 360 days.
accessKey: () => ({
expiry: '360d',
limits: [{ limit: '10', period: '30d', token: 'ousd' }],
// The access key sends OUSD only to the merchant.
scopes: [
Scopes.tip20(Addresses.ousd).transfer({
recipients: [merchant.address],
}),
],
}),
chain: 'testnet',
clientId: process.env.APP_URL,
plugins: [
backend({ store: Store.memory() }),
viem(),
],
})
```
:::note
`Store.memory` keeps the sessions in the process, so a restart signs each user out. In production, use a store that each replica shares, such as `Store.postgres` or `Store.redis` .
:::
### Sign the user in
`accounts.handler` serves the sign-in routes under `/api/auth`. Tempo ID's approval page shows the limit and its period.
:::code-group
```ts [server.ts]
import { Hono } from 'hono'
import { accounts } from './tempo.config.js'
const app = new Hono()
app.all('/api/*', (c) => accounts.handler.fetch(c.req.raw)) // [!code hl]
export default app
```
```ts [tempo.config.ts]
import { Accounts, Store } from 'accounts'
import { backend, viem } from 'accounts/plugins'
import { privateKeyToAccount } from 'viem/accounts'
import { Addresses, Scopes } from 'viem/tempo'
// The merchant receives each charge, and pays its fee.
export const merchant = privateKeyToAccount(
process.env.MERCHANT_PRIVATE_KEY as `0x${string}`,
)
export const accounts = Accounts.create({
// Each access key sends 10 OUSD each 30 days, for 360 days.
accessKey: () => ({
expiry: '360d',
limits: [{ limit: '10', period: '30d', token: 'ousd' }],
// The access key sends OUSD only to the merchant.
scopes: [
Scopes.tip20(Addresses.ousd).transfer({
recipients: [merchant.address],
}),
],
}),
chain: 'testnet',
clientId: process.env.APP_URL,
plugins: [
backend({ store: Store.memory() }),
viem(),
],
})
```
:::
### Read the session
`/api/auth/session` returns the cookie's session, or `null`.
```tsx [App.tsx]
import { useState } from 'react'
type Subscriber = { user: { email?: string } }
export function App() {
const [subscriber, setSubscriber] = useState()
async function subscribe() {
const response = await fetch('/api/auth/session')
const body = (await response.json()) as { session: Subscriber | null }
if (!body.session) return location.assign('/api/auth/login')
setSubscriber(body.session)
}
if (!subscriber)
return (
Subscribe
)
return Subscribed as {subscriber.user.email}
}
```
### Charge the period
`accounts.viem({ session })` returns a Viem client that signs with that session's access key. The merchant pays the fee, since the chain charges fees to the access key's limit, which holds only the charge.
The limit bounds one access key, not the user, and a new sign-in starts with an unspent period. So record each charge by user ID, and check the record before each charge.
:::code-group
```ts [server.ts]
import { Hono } from 'hono'
import { csrf } from 'hono/csrf'
import { parseUnits } from 'viem'
import { Addresses } from 'viem/tempo'
import { accounts, merchant } from './tempo.config.js'
const app = new Hono()
app.all('/api/*', (c) => accounts.handler.fetch(c.req.raw))
// Another site cannot post a charge with the session cookie.
app.use(csrf())
app.post('/charge', async (c) => {
const session = await accounts.session.get(c.req.raw)
if (session?.method !== 'tempo-id' || !session.accessKey)
return c.json({ error: 'invalid_session' }, 401)
// [!code hl:start]
const { receipt } = await accounts.viem({ session }).token.transferSync({
amount: parseUnits('10', 6),
feePayer: merchant,
to: merchant.address,
token: Addresses.ousd,
})
// [!code hl:end]
return c.json({ reference: receipt.transactionHash })
})
export default app
```
```ts [tempo.config.ts]
import { Accounts, Store } from 'accounts'
import { backend, viem } from 'accounts/plugins'
import { privateKeyToAccount } from 'viem/accounts'
import { Addresses, Scopes } from 'viem/tempo'
// The merchant receives each charge, and pays its fee.
export const merchant = privateKeyToAccount(
process.env.MERCHANT_PRIVATE_KEY as `0x${string}`,
)
export const accounts = Accounts.create({
// Each access key sends 10 OUSD each 30 days, for 360 days.
accessKey: () => ({
expiry: '360d',
limits: [{ limit: '10', period: '30d', token: 'ousd' }],
// The access key sends OUSD only to the merchant.
scopes: [
Scopes.tip20(Addresses.ousd).transfer({
recipients: [merchant.address],
}),
],
}),
chain: 'testnet',
clientId: process.env.APP_URL,
plugins: [
backend({ store: Store.memory() }),
viem(),
],
})
```
:::
### Handle a refused charge
Viem's `AccessKeySpendingLimitExceededError` names the period's end as `periodEnd`.
A transfer above the balance fails with the node's `InsufficientBalance` instead, which Viem's `ExecutionError.from` reads.
:::code-group
```ts [server.ts]
import { Hono } from 'hono'
import { csrf } from 'hono/csrf'
import { parseUnits } from 'viem'
import { type Actions, Addresses } from 'viem/tempo'
import { accounts, merchant } from './tempo.config.js'
type Refusal = Actions.accessKey.AccessKeySpendingLimitExceededError
/** Returns the refusal of a spent limit among `error` and its causes. */
function spent(error: unknown) {
for (let cause = error; cause instanceof Error; cause = cause.cause)
if (cause.name === 'AccessKeySpendingLimitExceededError')
return cause as Refusal
return undefined
}
const app = new Hono()
app.all('/api/*', (c) => accounts.handler.fetch(c.req.raw))
// Another site cannot post a charge with the session cookie.
app.use(csrf())
app.post('/charge', async (c) => {
const session = await accounts.session.get(c.req.raw)
if (session?.method !== 'tempo-id' || !session.accessKey)
return c.json({ error: 'invalid_session' }, 401)
const { receipt } = await accounts.viem({ session }).token.transferSync({
amount: parseUnits('10', 6),
feePayer: merchant,
to: merchant.address,
token: Addresses.ousd,
})
return c.json({ reference: receipt.transactionHash })
})
// [!code hl:start]
app.onError((error, c) => {
const refusal = spent(error)
if (!refusal) throw error
// `periodEnd` is the end of the period, in Unix seconds.
return c.json(
{ error: 'limit_exceeded', periodEnd: Number(refusal.periodEnd) },
409,
)
})
// [!code hl:end]
export default app
```
```ts [tempo.config.ts]
import { Accounts, Store } from 'accounts'
import { backend, viem } from 'accounts/plugins'
import { privateKeyToAccount } from 'viem/accounts'
import { Addresses, Scopes } from 'viem/tempo'
// The merchant receives each charge, and pays its fee.
export const merchant = privateKeyToAccount(
process.env.MERCHANT_PRIVATE_KEY as `0x${string}`,
)
export const accounts = Accounts.create({
// Each access key sends 10 OUSD each 30 days, for 360 days.
accessKey: () => ({
expiry: '360d',
limits: [{ limit: '10', period: '30d', token: 'ousd' }],
// The access key sends OUSD only to the merchant.
scopes: [
Scopes.tip20(Addresses.ousd).transfer({
recipients: [merchant.address],
}),
],
}),
chain: 'testnet',
clientId: process.env.APP_URL,
plugins: [
backend({ store: Store.memory() }),
viem(),
],
})
```
:::
### Handle the expiry
Once the access key expires, `session.get` returns `undefined`, and the page signs the user in again for a new access key.
```tsx [Charge.tsx]
export function Charge() {
return (
{
const response = await fetch('/charge', { method: 'POST' })
if (response.status === 401) location.assign('/api/auth/login')
}}
type="button"
>
Charge the period
)
}
```
::::
## Use cases
Each use case reads or ends a session of the `backend` plugin, whose access key signs each charge through `accounts.viem({ session })` .
### Charge from a schedule
A scheduled job charges without a request, so it reads each session with `backend.get` , by the session ID of the session cookie.
:::code-group
```ts [schedule.ts]
import { parseUnits } from 'viem'
import { Addresses } from 'viem/tempo'
import { accounts, merchant } from './tempo.config.js'
/** Charges the period of the session `id`, and returns the transaction hash. */
export async function charge(id: string) {
const session = await accounts.backend.get({ id }) // [!code hl]
if (session?.method !== 'tempo-id' || !session.accessKey) return undefined
const { receipt } = await accounts.viem({ session }).token.transferSync({
amount: parseUnits('10', 6),
feePayer: merchant,
to: merchant.address,
token: Addresses.ousd,
})
return receipt.transactionHash
}
```
```ts [tempo.config.ts]
import { Accounts, Store } from 'accounts'
import { backend, viem } from 'accounts/plugins'
import { privateKeyToAccount } from 'viem/accounts'
import { Addresses, Scopes } from 'viem/tempo'
// The merchant receives each charge, and pays its fee.
export const merchant = privateKeyToAccount(
process.env.MERCHANT_PRIVATE_KEY as `0x${string}`,
)
export const accounts = Accounts.create({
// Each access key sends 10 OUSD each 30 days, for 360 days.
accessKey: () => ({
expiry: '360d',
limits: [{ limit: '10', period: '30d', token: 'ousd' }],
// The access key sends OUSD only to the merchant.
scopes: [
Scopes.tip20(Addresses.ousd).transfer({
recipients: [merchant.address],
}),
],
}),
chain: 'testnet',
clientId: process.env.APP_URL,
plugins: [
backend({ store: Store.memory() }),
viem(),
],
})
```
:::
:::warning
Without a registration, Tempo ID ends a session 30 days after its last refresh. Each `backend.get` refreshes an expired access token. With a period of 30 days or more, read each session between two charges, such as each day.
:::
### End a subscription
`backend.end` revokes the session's refresh token, and deletes the session with its access key. The backend then holds no access key to charge with, so the subscription ends.
:::code-group
```ts [cancel.ts]
import { accounts } from './tempo.config.js'
/** Ends the subscription of the session `id`. */
export async function cancel(id: string) {
await accounts.backend.end({ id }) // [!code hl]
}
```
```ts [tempo.config.ts]
import { Accounts, Store } from 'accounts'
import { backend, viem } from 'accounts/plugins'
import { privateKeyToAccount } from 'viem/accounts'
import { Addresses, Scopes } from 'viem/tempo'
// The merchant receives each charge, and pays its fee.
export const merchant = privateKeyToAccount(
process.env.MERCHANT_PRIVATE_KEY as `0x${string}`,
)
export const accounts = Accounts.create({
// Each access key sends 10 OUSD each 30 days, for 360 days.
accessKey: () => ({
expiry: '360d',
limits: [{ limit: '10', period: '30d', token: 'ousd' }],
// The access key sends OUSD only to the merchant.
scopes: [
Scopes.tip20(Addresses.ousd).transfer({
recipients: [merchant.address],
}),
],
}),
chain: 'testnet',
clientId: process.env.APP_URL,
plugins: [
backend({ store: Store.memory() }),
viem(),
],
})
```
:::
## Next steps
# Pay MPP subscriptions \[A page approves the access key of a merchant once, and the merchant charges each period.]
## Overview
A Machine Payments Protocol (MPP) subscription lets a merchant other than the app, such as an API, charge each period. The merchant's route responds with an HTTP 402 challenge that names its own [access key](/docs/guides/access-keys), the amount, the period, and the expiry.
`accounts.fetch` opens Tempo ID's dialog, where the user approves that access key once. The merchant then charges each period itself, and the chain enforces the approved limit.
Only a browser page subscribes, since the approval needs the dialog.
The demo subscribes to 1 OUSD each minute for 10 minutes, and shows each charge.
## Walkthrough
The [`mpp-subscription`](https\://github.com/tempoxyz/accounts/tree/main/examples/mpp-subscription) example runs a subscription against its own merchant, with the session on its backend, as [Pay for a backend's session](/docs/guides/subscriptions/mpp#pay-for-a-backends-session) shows.
::::steps
### Install the packages
:::code-group
```sh [npm]
npm install accounts mppx react react-dom viem
```
```sh [pnpm]
pnpm add accounts mppx react react-dom viem
```
```sh [bun]
bun add accounts mppx react react-dom viem
```
:::
### Create the instance
The `mpp` plugin adds `accounts.fetch` . `maxAmount` caps the cost of one period.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { mpp } from 'accounts/mpp'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// `accounts.fetch` needs an access key. A subscription never spends it.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '10', token: 'ousd' }],
}),
chain: 'testnet',
// A period of a subscription may charge at most 10 OUSD.
plugins: [mpp({ maxAmount: '10' }), react()],
})
```
### Sign the user in
`dialog.signIn` opens Tempo ID's dialog on the page, and sets the [session](/docs/guides/user-session).
:::code-group
```tsx [App.tsx]
import { accounts } from './tempo.config.js'
export function App() {
const { session } = accounts.useSession()
// [!code hl:start]
if (!session)
return (
accounts.dialog.signIn()} type="button">
Sign in with Tempo
)
// [!code hl:end]
return Signed in as {session.user.email}
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { mpp } from 'accounts/mpp'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// `accounts.fetch` needs an access key. A subscription never spends it.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '10', token: 'ousd' }],
}),
chain: 'testnet',
// A period of a subscription may charge at most 10 OUSD.
plugins: [mpp({ maxAmount: '10' }), react()],
})
```
:::
### Subscribe
Tempo ID's dialog shows the challenge's amount, period, and expiry. After the approval, the request sends again with the approval as its credential, and the merchant charges the first period. The session keeps its own access key.
The merchant serves the route with the subscription method of mppx's server, as [`api.ts`](https\://github.com/tempoxyz/accounts/blob/main/examples/mpp-subscription/api.ts) of the example shows. The dialog can approve with any Tempo Account of the user, so the merchant checks that the credential's signer belongs to its user.
:::code-group
```tsx [Subscribe.tsx]
import { Receipt } from 'mppx'
import { useState } from 'react'
import { accounts } from './tempo.config.js'
const url = 'https://merchant.example/api/subscription'
export function Subscribe() {
const [reference, setReference] = useState()
if (reference) return Charged in {reference}
return (
{
const response = await accounts.fetch(url) // [!code hl]
if (!response.ok)
throw new Error(`The merchant failed with ${response.status}.`)
// The receipt names the transaction of the first charge.
setReference(Receipt.fromResponse(response).reference)
}}
type="button"
>
Subscribe
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { mpp } from 'accounts/mpp'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// `accounts.fetch` needs an access key. A subscription never spends it.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '10', token: 'ousd' }],
}),
chain: 'testnet',
// A period of a subscription may charge at most 10 OUSD.
plugins: [mpp({ maxAmount: '10' }), react()],
})
```
:::
### Handle a refused subscription
`accounts.fetch` rejects before any payment\: with `Accounts.RequestError` for a denial, and with `MaxAmountError` for a period above `maxAmount` .
:::code-group
```tsx [Subscribe.tsx]
import { Accounts } from 'accounts'
import { MaxAmountError } from 'accounts/mpp'
import { useState } from 'react'
import { accounts } from './tempo.config.js'
const url = 'https://merchant.example/api/subscription'
export function Subscribe() {
const [refusal, setRefusal] = useState()
return (
<>
{
try {
await accounts.fetch(url)
} catch (error) {
// [!code hl:start]
if (error instanceof Accounts.RequestError)
setRefusal(`Tempo ID refused the subscription: ${error.code}.`)
else if (error instanceof MaxAmountError)
setRefusal('A period costs more than `maxAmount`.')
// [!code hl:end]
else throw error
}
}}
type="button"
>
Subscribe
{refusal && {refusal}
}
>
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { mpp } from 'accounts/mpp'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// `accounts.fetch` needs an access key. A subscription never spends it.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '10', token: 'ousd' }],
}),
chain: 'testnet',
// A period of a subscription may charge at most 10 OUSD.
plugins: [mpp({ maxAmount: '10' }), react()],
})
```
:::
### Handle the expiry
The subscription ends at its challenge's expiry, and the route responds with 402 again. A plain `fetch` reads that status with no payment.
```tsx [Status.tsx]
import { useState } from 'react'
const url = 'https://merchant.example/api/subscription'
export function Status() {
const [active, setActive] = useState()
async function check() {
const response = await fetch(url)
setActive(response.status !== 402) // [!code hl]
}
if (active === undefined)
return (
Check subscription
)
return {active ? 'Subscribed' : 'No active subscription'}
}
```
::::
## Use cases
Each use case sets an option of the `mpp` plugin, or of one payer.
### Pay for a backend's session
A page whose backend holds the session has no access key. `accounts.mpp({ account })` pays the subscription for the Tempo Account that the backend names. Such a payer pays only subscriptions, in a browser.
:::code-group
```tsx [App.tsx]
import { accounts } from './tempo.config.js'
export function App() {
async function subscribe() {
// The backend names the Tempo Account of its session.
const response = await fetch('/v1/me')
if (!response.ok) return location.assign('/login')
const me = (await response.json()) as { account: `0x${string}` }
await accounts
.mpp({ account: me.account }) // [!code hl]
.fetch(new URL('/v1/subscription', location.origin))
}
return (
Subscribe
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { mpp } from 'accounts/mpp'
// The backend holds the session, so the page's instance requests no access key.
export const accounts = Accounts.create({
accessKey: false,
chain: 'testnet',
plugins: [mpp({ maxAmount: '10' })],
})
```
:::
### Pay only subscriptions
A route can offer a one-time charge beside a subscription. `orderChallenges` filters and sorts the offers before any payment, and the payer pays the first that it returns.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { mpp } from 'accounts/mpp'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// `accounts.fetch` needs an access key. A subscription never spends it.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '10', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [
mpp({
maxAmount: '10',
// [!code hl:start]
orderChallenges: (candidates) =>
candidates.filter(
(candidate) => candidate.challenge.intent === 'subscription',
),
// [!code hl:end]
}),
react(),
],
})
```
### Identify the user to the merchant
`identity` sends the session's access token and ID token with each request to the origins of its scope. A merchant that verifies them with mppx's Tempo ID extension then keys the subscription by user.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { mpp } from 'accounts/mpp'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// `accounts.fetch` needs an access key. A subscription never spends it.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '10', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [
mpp({
identity: { scope: ['https://merchant.example'] }, // [!code hl]
maxAmount: '10',
}),
react(),
],
})
```
:::warning
Each origin of the scope receives tokens that act for the user. Name only merchants that verify Tempo ID.
:::
### Skip the deposit page
The merchant charges the first period at once, and refuses an unfunded account only after the approval, with a generic error. So for a balance below the first period, Tempo ID's deposit page shows before the dialog.
`retry` with `balance: false` turns that page off, such as for an app with its own deposit flow.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { mpp } from 'accounts/mpp'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// `accounts.fetch` needs an access key. A subscription never spends it.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '10', token: 'ousd' }],
}),
chain: 'testnet',
// A period of a subscription may charge at most 10 OUSD.
plugins: [mpp({ maxAmount: '10', retry: { balance: false } }), react()], // [!code hl]
})
```
## Next steps
# User session \[A session holds the user, the tokens, and the access key of a sign-in.]
## Overview
A sign-in returns a session, which holds the user, the tokens, and the [access key](/docs/guides/access-keys) of the sign-in. The instance saves it to its store, so a later load of the app restores it with no new sign-in.
With `guest` , a sign-in can also return a [guest session](/docs/guides/guest-checkout), which holds no user and no tokens. `Session.guest` and `Session.tempoId` tell the kinds apart.
Each app that signs users in holds a session. Its access token lets the app call its own API as the user, which [verifies the token](/docs/guides/api-authentication/authenticate-requests).
## Guides
# Restore sessions \[An app restores the session of a signed-in user at each load, with no new sign-in.]
## Overview
A session holds a sign-in's user, tokens, and access key. The instance saves it to its store, so a later load of the app restores it with no new sign-in.
The demo signs a user in through Tempo ID's dialog, and restores the session from the browser's store after a reload.
## Walkthrough
The [`web`](https\://github.com/tempoxyz/accounts/tree/main/examples/web) example runs these steps.
::::steps
### Create the instance
Create one instance for the app. The `react` plugin adds `accounts.useSession` , and a browser's default store is IndexedDB.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [react()],
})
```
### Restore the session
The first render of `accounts.useSession` reads the saved session. Without one, or after its [access key](/docs/guides/access-keys) expires, `session` is `undefined`.
On a page of a first-party app, the first render also renews a missing or expired session from the browser's Tempo ID session, with no prompt. [Manage sessions](/docs/guides/react/manage-sessions#renew-without-an-access-key) shows the options of that renewal.
:::code-group
```tsx [App.tsx]
import { accounts } from './tempo.config.js'
export function App() {
const { session } = accounts.useSession() // [!code hl]
if (!session) return Signed out
return Signed in as {session.user.email}
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [react()],
})
```
:::
### Read the status
The hook returns the status, with a flag for each value, and renders again at each change.
:::code-group
```tsx [App.tsx]
import { accounts } from './tempo.config.js'
export function App() {
const { isPending, session } = accounts.useSession() // [!code hl]
if (isPending) return Restoring the session…
// [!code hl]
if (!session) return Signed out
return Signed in as {session.user.email}
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [react()],
})
```
:::
| Status | Flag | Meaning | Session |
| --------------- | ------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------- | ------------------- |
| `pending` | `isPending` | The instance reads the saved session, or an authorization runs | `undefined` |
| `reauthorizing` | `isReauthorizing` | An authorization renews a saved session whose access key expired | The expired session |
| `signedIn` | `isSignedIn` | The instance holds a session | The session |
| `signedOut` | `isSignedOut` | The instance holds no session, and no authorization runs | `undefined` |
### Sign the user in
`dialog.signIn` saves the session that it returns, and the hook renders the signed-in branch.
:::code-group
```tsx [SignIn.tsx]
import { accounts } from './tempo.config.js'
export function SignIn() {
return (
accounts.dialog.signIn()} type="button">
Sign in with Tempo
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [react()],
})
```
:::
### Call the app's API
`session.fetch` sends a request with the session's [access token](/docs/guides/api-authentication/authenticate-requests). If the access token expires within 30 seconds, the tokens refresh beside the request. Without a session, the call throws `Accounts.SignedOutError` , and sends no request.
:::code-group
```tsx [Profile.tsx]
import { useState } from 'react'
import { accounts } from './tempo.config.js'
export function Profile() {
const [profile, setProfile] = useState()
return (
{
const response = await accounts.session.fetch({ url: '/api/me' }) // [!code hl]
setProfile(await response.text())
}}
type="button"
>
{profile ?? 'Load the profile'}
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [react()],
})
```
:::
### Sign the user out
`signOut` empties the session, deletes the saved one, and revokes the refresh token.
:::code-group
```tsx [SignOut.tsx]
import { accounts } from './tempo.config.js'
export function SignOut() {
return (
accounts.signOut()} type="button">
Sign out
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [react()],
})
```
:::
Render `SignIn` without a session, and `Profile` and `SignOut` with one.
::::
## Use cases
Each use case reads the session through `accounts.session` , which the hook also reads, or checks it with `Session.expired` .
### Restore without React
`session.get` reads the saved session, such as on a page without React or in a script. It returns `undefined` without a session, and after its access key expires.
:::code-group
```ts [main.ts]
import { accounts } from './tempo.config.js'
const session = await accounts.session.get() // [!code hl]
console.log(session ? `Signed in as ${session.user.email}` : 'Signed out')
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
export const accounts = Accounts.create({ chain: 'testnet' })
```
:::
### Renew an expired session
`reauthorize: true` renews a missing or expired session from the browser's Tempo ID session, with no prompt. The call returns `undefined` if only an interactive sign-in can renew it, so the page shows its sign-in. Outside a browser without `redirectUri` , such as in a CLI, it returns `undefined` with no request, and the program signs in again with the device grant.
:::code-group
```ts [main.ts]
import { accounts } from './tempo.config.js'
const session = await accounts.session.get({ reauthorize: true }) // [!code hl]
if (!session) console.log('Sign in again.')
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
export const accounts = Accounts.create({ chain: 'testnet' })
```
:::
### Follow the status
`session.status` returns the status of the table above, and calls a listener at each change. It suits code outside a component, such as a router guard.
:::code-group
```ts [main.ts]
import { accounts } from './tempo.config.js'
// [!code hl:start]
const unsubscribe = accounts.session.status.subscribe((status, previous) => {
if (previous.status === 'signedIn' && status.status === 'signedOut')
console.log('Signed out')
})
// [!code hl:end]
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
export const accounts = Accounts.create({ chain: 'testnet' })
```
:::
### Load the instance for returning visitors
The instance reads the saved session from IndexedDB, which has no synchronous read. With `hint` , the instance keeps a cookie while it holds a session. `Hint.has` of `accounts/hint`, which imports no other module, reads it at startup, so the page loads the instance only for a returning visitor.
A page that loads no instance renews no session from the browser's Tempo ID session at startup.
:::code-group
```ts [main.ts]
import { Hint } from 'accounts/hint'
// [!code hl:start]
if (Hint.has(document.cookie)) {
const { accounts } = await import('./tempo.config.js')
await accounts.session.get()
}
// [!code hl:end]
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
export const accounts = Accounts.create({
chain: 'testnet',
hint: { cookie: true }, // [!code hl]
})
```
:::
### Check the expiry in an open page
The hook empties an expired session only when it reads the store, so a page that stays open can hold a session whose access key expired. `Session.expired` reports it.
:::code-group
```tsx [App.tsx]
import { Session } from 'accounts'
import { accounts } from './tempo.config.js'
export function App() {
const { session } = accounts.useSession()
// [!code hl:start]
if (!session || Session.expired(session))
return (
accounts.dialog.signIn()} type="button">
Sign in with Tempo
)
// [!code hl:end]
return Signed in as {session.user.email}
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [react()],
})
```
:::
## Next steps
# Store sessions \[An app chooses the store that keeps the session on each platform.]
## Overview
An instance saves its [session](/docs/guides/user-session) to its `store` , which decides where the session lives, and for how long.
| Platform | Store | Keeps the session |
| ------------ | -------------------------------------------------------------------------------------------- | ----------------------------------- |
| Web | IndexedDB, the default | Across loads and tabs of the origin |
| CLI | `Store.file()` , the default | In a file that only the user reads |
| React Native | `expo()` of `accounts/expo` | In the secure store of the device |
| Backend | `backend({ store })` | On the server, one for each browser |
The demo signs a user in on two instances, one with a memory store and one with the default store. After a reload, only the default store returns its session.
## Walkthrough
### Web
::::steps
### Use the default store
In a browser, an instance without `store` uses IndexedDB. It keeps the session's [access key](/docs/guides/access-keys) across loads as a non-extractable `CryptoKey`, whose private key no script reads.
:::code-group
```tsx [App.tsx]
import { accounts } from './tempo.config.js'
export function App() {
const { session } = accounts.useSession()
if (!session)
return (
accounts.dialog.signIn()} type="button">
Sign in with Tempo
)
// A reload renders this branch again, with no sign-in.
return Signed in as {session.user.email}
// [!code hl]
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [react()],
})
```
:::
### Keep the session in memory
`Store.memory` keeps the session until the page unloads, such as for a test. A reload leaves no session to sign out, so request no refresh token.
```ts [tempo.config.ts]
import { Accounts, Store } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [react()],
// Without `offline_access`, Tempo ID issues no refresh token.
scope: 'openid', // [!code hl]
store: Store.memory(), // [!code hl]
})
```
::::
### CLI
The [`cli`](https\://github.com/tempoxyz/accounts/tree/main/examples/cli) example runs these steps.
::::steps
### Save the session to a file
Outside a browser, an instance with a `cli:` client ID saves its session to `~/.tempo/id/store.json`, with no `store` option. Every CLI of the user shares the file, which has mode `0600`. If the save of a sign-in replaces a later session that another instance's sign-in saved, such as in two runs of a login at once, the instance takes that session back and revokes its own refresh token. Any other instance holds a session only with a store.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { device } from 'accounts/plugins'
export const accounts = Accounts.create({
chain: 'testnet',
clientId: 'cli:acme-example', // [!code hl]
plugins: [
device({
onCode: (code) =>
console.log(
`Open ${code.verificationUriComplete} and confirm the code ${code.userCode}.`,
),
}),
],
})
```
:::tip
To keep the session in another file, pass `store: Store.file(path)` .
:::
### Read the saved session
:::code-group
```ts [index.ts]
import { accounts } from './tempo.config.js'
const session = await accounts.session.get() // [!code hl]
if (!session) console.log('Not signed in.')
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { device } from 'accounts/plugins'
export const accounts = Accounts.create({
chain: 'testnet',
clientId: 'cli:acme-example',
plugins: [
device({
onCode: (code) =>
console.log(
`Open ${code.verificationUriComplete} and confirm the code ${code.userCode}.`,
),
}),
],
})
```
:::
::::
### React Native
The [`mobile`](https\://github.com/tempoxyz/accounts/tree/main/examples/mobile) example runs these steps.
:::steps
### Add the `expo` plugin
The plugin sets the instance's store to the device's secure store, from `expo-secure-store`, which the app installs.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { expo } from 'accounts/expo'
export const accounts = Accounts.create({
chain: 'testnet',
// The client ID of the app's registration.
clientId: 'example-mobile',
plugins: [expo({ redirectUri: 'com.example.app:/callback' })], // [!code hl]
})
```
:::
### Backend
The [`backend`](https\://github.com/tempoxyz/accounts/tree/main/examples/backend) example runs these steps.
::::steps
### Pass a store to the `backend` plugin
A backend's instance serves many users, so it holds no session of its own. The `backend` plugin keeps one session for each session cookie in its store.
```ts [tempo.config.ts]
import { Accounts, Store } from 'accounts'
import { backend } from 'accounts/plugins'
export const accounts = Accounts.create({
chain: 'testnet',
clientId: process.env.APP_URL,
plugins: [backend({ store: Store.memory() })], // [!code hl]
})
```
:::note
`Store.memory` keeps the sessions in the process, so a restart loses them. In production, use a store that each replica shares, such as `Store.postgres` or `Store.redis` .
:::
| Store | Use |
| ------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
| `Store.memory()` | One process, such as in development |
| `Store.postgres(client)` | A `pg` pool. The store creates its table |
| `Store.redis(client)` | A `redis` client |
| `Sessions.durableObject(namespace)` | One Durable Object for each session |
| `Store.durableObject(storage)` | The storage of the app's own Durable Object |
| `Store.workersKv(namespace)` | A Workers KV namespace. Another location can read a sign-out up to 60 seconds late |
In a Cloudflare Worker, `Store.file` throws `Store.NodeRequiredError` , since `node:fs` there keeps each file in the memory of one isolate. Use a Durable Object or Workers KV store.
Each stored session holds a refresh token and an access key's private key. Give no other role access to the store.
### Read the session of a request
:::code-group
```ts [server.ts]
import { Hono } from 'hono'
import { accounts } from './tempo.config.js'
const app = new Hono()
app.all('/api/*', (c) => accounts.handler.fetch(c.req.raw))
app.get('/me', async (c) => {
const session = await accounts.session.get(c.req.raw) // [!code hl]
if (session?.method !== 'tempo-id') return c.text('Signed out', 401)
return c.json(session.user)
})
export default app
```
```ts [tempo.config.ts]
import { Accounts, Store } from 'accounts'
import { backend } from 'accounts/plugins'
export const accounts = Accounts.create({
chain: 'testnet',
clientId: process.env.APP_URL,
plugins: [backend({ store: Store.memory() })],
})
```
:::
::::
## Use cases
Each use case sets the `store` option, or builds a store with `Store.from` .
### Write a store
`Store.from` instantiates a store over any storage. This one keeps a backend's sessions in a SQLite file.
```ts [store.ts]
import { DatabaseSync } from 'node:sqlite'
import { Store } from 'accounts'
import { Json } from 'ox'
const database = new DatabaseSync('sessions.db')
database.exec(
'create table if not exists store (key text primary key, value text not null, expires_at integer)',
)
export const store = Store.from({
async getItem(key) {
const row = database
.prepare(
'select value from store where key = ? and (expires_at is null or expires_at > ?)',
)
.get(key, Date.now())
return row ? Json.parse(String(row.value)) : undefined
},
async removeItem(key) {
database.prepare('delete from store where key = ?').run(key)
},
async setItem(key, value, options = {}) {
database
.prepare('insert or replace into store values (?, ?, ?)')
.run(key, Json.stringify(value), options.expiresAt ?? null)
},
})
```
| Member | Contract |
| --------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `getItem` | Resolves with the value of the key, or `undefined` |
| `local` | Optional. `true` for a store of one process alone, such as one in the memory of a page, which a page load empties. A refused refresh then throws at once, and `redirect.signIn` without `open` refuses the store |
| `removeItem` | Deletes the value of the key |
| `setItem` | Writes the value. With `options.expiresAt` , in milliseconds, the entry may then expire |
| `takeItem` | Optional. Reads and deletes the value in one atomic step |
| `update` | Optional. Reads the value, writes the value that its function returns only if the key still holds the one it read, and otherwise runs the function again. The backend then keeps each concurrent sign-in of one `sid` across processes |
* A store that serializes uses ox's `Json`, which keeps a `bigint`.
* A browser's access key has no serialized form, so keep a browser's session in the default store.
### Separate the sessions of two instances
A saved session's key names the Tempo ID deployment, the client ID, and the chain. Instances that differ in `url` , `clientId` , or `chain` thus share one store, and each reads only its own session.
:::code-group
```tsx [App.tsx]
import { testnet } from './tempo.config.js'
export function App() {
const { session } = testnet.useSession()
return {session ? session.user.email : 'Signed out on testnet'}
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const mainnet = Accounts.create({ chain: 'mainnet', plugins: [react()] }) // [!code hl]
export const testnet = Accounts.create({ chain: 'testnet', plugins: [react()] }) // [!code hl]
```
:::
### Hold no session in a service
A service that signs in many users with a `cli:` client ID, such as a bot, holds no session of its own. `store: false` refuses the file of the default store, so each sign-in only returns its session.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { device } from 'accounts/plugins'
export const accounts = Accounts.create({
chain: 'testnet',
clientId: 'cli:acme-bot',
plugins: [
device({
onCode: (code) =>
console.log(`Open ${code.verificationUriComplete} to sign in.`),
}),
],
store: false, // [!code hl]
})
```
## Next steps
# Viem \[An app sends transactions and signs messages on Tempo with a Viem client whose account follows the session.]
## Overview
The `viem` plugin adds a [Viem](https\://viem.sh) client to the instance. A sign-in sets the client's account to the user's Tempo Account, and a sign-out empties it, so no action names an account.
The [session](/docs/guides/user-session)'s [access key](/docs/guides/access-keys) signs each transaction and message with no prompt. The instance also holds each action of the client, so an app calls them on the instance itself.
The demo signs a user in, and sends 1 OUSD on Tempo testnet. It then signs a message with the access key, and verifies the signature.
## Walkthrough
The [`web`](https\://github.com/tempoxyz/accounts/tree/main/examples/web) example runs these steps in a React app.
::::steps
### Install the packages
:::code-group
```sh [npm]
npm install accounts react react-dom viem
```
```sh [pnpm]
pnpm add accounts react react-dom viem
```
```sh [bun]
bun add accounts react react-dom viem
```
:::
### Create the instance
Add the `viem` plugin. The client uses the chain and the RPC of the instance. [Use another Tempo ID or chain](/docs/guides/viem#use-another-tempo-id-or-chain) changes them.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [react(), viem()], // [!code hl]
})
```
### Sign the user in
`dialog.signIn` sets the account of the client. Its address is the user's Tempo Account. Without a session, a read of the account throws `Accounts.SignedOutError` .
:::code-group
```tsx [App.tsx]
import { accounts } from './tempo.config.js'
export function App() {
const { session } = accounts.useSession()
if (!session)
return (
accounts.dialog.signIn()} type="button">
Sign in with Tempo
)
return (
// [!code hl:start]
Tempo Account {accounts.viem.account.address} on {accounts.viem.chain.name}
// [!code hl:end]
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [react(), viem()],
})
```
:::
### Send a transaction
Viem's [`token.transfer`](https\://viem.sh/tempo/actions/token.transfer) action sends 1 OUSD, and the access key signs it. The sync form waits for the receipt.
:::code-group
```tsx [Send.tsx]
import { parseUnits } from 'viem'
import { Addresses } from 'viem/tempo'
import { accounts } from './tempo.config.js'
export function Send() {
return (
{
// [!code hl:start]
const { receipt } = await accounts.viem.token.transferSync({
amount: parseUnits('1', 6),
to: '0x000000000000000000000000000000000000dEaD',
token: Addresses.ousd,
})
// [!code hl:end]
console.log(receipt.transactionHash)
}}
type="button"
>
Send 1 OUSD
)
}
```
```tsx [App.tsx]
import { Send } from './Send.js' // [!code ++]
import { accounts } from './tempo.config.js'
export function App() {
const { session } = accounts.useSession()
if (!session)
return (
accounts.dialog.signIn()} type="button">
Sign in with Tempo
)
return (
Tempo Account {accounts.viem.account.address} on{' '}
{accounts.viem.chain.name}
{/* [!code ++] */}
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [react(), viem()],
})
```
:::
Viem's docs list the client's [Tempo](https\://viem.sh/tempo/actions), [public](https\://viem.sh/docs/actions/public/introduction), and [wallet](https\://viem.sh/docs/actions/wallet/introduction) actions. The instance holds the same actions, so the call above also works without the client.
The chain lets the access key make only the calls of its scopes. With limits alone, it transfers each limited token, approves each limit's spenders, and opens and tops up TIP-1034 channels. Another call rejects with Viem's `AccessKeyCallNotAllowedError`.
::::
## Use cases
Each use case calls an action of the client of the `viem` plugin, or sets one option of the plugin or of a call of its client.
### Send several calls
Viem's [`sendTransactionSync`](https\://viem.sh/docs/actions/wallet/sendTransactionSync) sends several calls in one transaction, which the access key signs once. Each Tempo action of Viem builds one call.
:::code-group
```tsx [SendBoth.tsx]
import { parseUnits } from 'viem'
import { Actions, Addresses } from 'viem/tempo'
import { accounts } from './tempo.config.js'
export function SendBoth() {
return (
{
// [!code hl:start]
const receipt = await accounts.sendTransactionSync({
calls: [
Actions.token.transfer.call({
amount: parseUnits('1', 6),
to: '0x000000000000000000000000000000000000dEaD',
token: Addresses.ousd,
}),
Actions.token.transfer.call({
amount: parseUnits('2', 6),
to: '0x000000000000000000000000000000000000bEEF',
token: Addresses.ousd,
}),
],
})
// [!code hl:end]
console.log(receipt.transactionHash)
}}
type="button"
>
Send 3 OUSD
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [react(), viem()],
})
```
:::
### Pass the client to an action
A standalone Viem action takes `accounts.viem` as its client, and the access key signs.
:::code-group
```tsx [Send.tsx]
import { parseUnits } from 'viem'
import { Actions, Addresses } from 'viem/tempo'
import { accounts } from './tempo.config.js'
export function Send() {
return (
{
// [!code hl:start]
const { receipt } = await Actions.token.transferSync(accounts.viem, {
amount: parseUnits('1', 6),
to: '0x000000000000000000000000000000000000dEaD',
token: Addresses.ousd,
})
// [!code hl:end]
console.log(receipt.transactionHash)
}}
type="button"
>
Send 1 OUSD
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [react(), viem()],
})
```
:::
### Send on another chain
A call of the client with `chainId` returns the client of that chain, whose account keeps its address. That address is the Tempo Account there only if both chains have configurable accounts, or neither does. An access key signs on one chain, so on a page the first transaction shows Tempo ID's sign-in for an access key there, and elsewhere it throws `Accounts.AccessKeyRequiredError` .
:::code-group
```tsx [SendOnMainnet.tsx]
import { parseUnits } from 'viem'
import { Addresses } from 'viem/tempo'
import { tempo } from 'viem/tempo/chains'
import { accounts } from './tempo.config.js'
export function SendOnMainnet() {
return (
{
const mainnet = accounts.viem({ chainId: tempo.id }) // [!code hl]
const { receipt } = await mainnet.token.transferSync({
amount: parseUnits('1', 6),
to: '0x000000000000000000000000000000000000dEaD',
token: Addresses.ousd,
})
console.log(receipt.transactionHash)
}}
type="button"
>
Send 1 OUSD on mainnet
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [react(), viem()],
})
```
:::
### Retry a refused transaction
On a page, the client retries a transaction that the node refuses for these reasons. Tempo ID's screen shows first, then the transaction sends again.
| Kind | Refusal | Screen |
| ----------- | ------------------------------------------------------------------- | ------------ |
| `accessKey` | The chain does not hold the access key, or it expired or is revoked | Sign-in |
| `balance` | The Tempo Account holds too little of the token or of the fee token | Deposit page |
| `limit` | The access key spent its limit | Sign-in |
If the user closes the screen, the action rejects with `Plugins.viem.RetryClosedError` , and sends nothing.
:::code-group
```tsx [Send.tsx]
import { parseUnits } from 'viem'
import { Addresses } from 'viem/tempo'
import { accounts } from './tempo.config.js'
export function Send() {
return (
{
try {
await accounts.token.transferSync({
amount: parseUnits('1', 6),
to: '0x000000000000000000000000000000000000dEaD',
token: Addresses.ousd,
})
} catch (error) {
if ((error as Error).name !== 'Plugins.viem.RetryClosedError') // [!code hl]
throw error
console.log('The transaction did not send.')
}
}}
type="button"
>
Send 1 OUSD
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [react(), viem()],
})
```
:::
### Turn off a retry
The plugin's `retry` turns off kinds for every client. The `retry` of a client call turns them off for that client, and `false` turns off every kind.
:::code-group
```tsx [Send.tsx]
import { parseUnits } from 'viem'
import { Addresses } from 'viem/tempo'
import { accounts } from './tempo.config.js'
export function Send() {
return (
{
const client = accounts.viem({ retry: false }) // [!code hl]
const { receipt } = await client.token.transferSync({
amount: parseUnits('1', 6),
to: '0x000000000000000000000000000000000000dEaD',
token: Addresses.ousd,
})
console.log(receipt.transactionHash)
}}
type="button"
>
Send 1 OUSD
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [react(), viem({ retry: { limit: false } })], // [!code hl]
})
```
:::
### Stop waiting on a retry
The `signal` of a client call's retry rejects the call with the signal's reason, and ends its wait on the screen. The screen closes once no call waits on it.
:::code-group
```tsx [Send.tsx]
import { parseUnits } from 'viem'
import { Addresses } from 'viem/tempo'
import { accounts } from './tempo.config.js'
export function Send() {
return (
{
// The call stops its wait on a screen after two minutes.
const client = accounts.viem({
retry: { signal: AbortSignal.timeout(120_000) }, // [!code hl]
})
const { receipt } = await client.token.transferSync({
amount: parseUnits('1', 6),
to: '0x000000000000000000000000000000000000dEaD',
token: Addresses.ousd,
})
console.log(receipt.transactionHash)
}}
type="button"
>
Send 1 OUSD
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [react(), viem()],
})
```
:::
### Sponsor fees
The plugin's `relay` sends each transaction through the app's relay route, whose fee payer pays its fee. [Use Tempo API](/docs/guides/fee-sponsorship/use-tempo-api) serves the route.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [react(), viem({ relay: '/api/relay' })], // [!code hl]
})
```
### Relay through another origin
Each request to a relay route at the app's origin carries the session's access token, so the route can verify its caller. With `credentials: 'include'` , a route on another origin, such as the app's API, also receives it.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [
react(),
viem({
// [!code hl:start]
relay: { credentials: 'include', url: 'https://api.example.com/relay' },
// [!code hl:end]
}),
],
})
```
### Set the options of each chain
A function in place of the options of `viem` returns the options of each chain, such as a transport to the app's RPC provider.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
import { http } from 'viem'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [
react(),
viem((chainId) => ({ transport: http(`https://rpc.example/${chainId}`) })), // [!code hl]
],
})
```
### Sign a message as the Tempo Account
The access key signs a keychain envelope for the Tempo Account, with no prompt. A verifier accepts it only after the chain holds the access key, such as after the [walkthrough's](/docs/guides/viem#send-a-transaction) first transaction.
:::code-group
```tsx [Sign.tsx]
import { accounts } from './tempo.config.js'
const message = 'Hello from Tempo ID'
export function Sign() {
return (
{
// [!code hl:start]
const signature = await accounts.signMessage({ message })
const valid = await accounts.verifyMessage({
accessToken: await accounts.session.accessToken(),
address: accounts.viem.account.address,
message,
signature,
})
// [!code hl:end]
console.log(valid)
}}
type="button"
>
Sign a message
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [react(), viem()],
})
```
:::
The verification counts the signature only if the session's [access token](/docs/guides/api-authentication/authenticate-requests) names the access key that signed. Without an access token, it returns `false`, and an access token that does not verify throws `AccessToken.InvalidError` .
:::warning
A Viem client without the package verifies with the allowAccessKey mode of [`verifyMessage`](https\://viem.sh/docs/actions/public/verifyMessage). That mode accepts each access key that the chain holds for the Tempo Account, also another app's access key.
:::
### Sign typed data
Viem's [`signTypedData`](https\://viem.sh/docs/actions/wallet/signTypedData) and its verification follow the same rules for EIP-712 typed data.
:::code-group
```tsx [Sign.tsx]
import { accounts } from './tempo.config.js'
export function Sign() {
return (
{
const typedData = {
domain: { chainId: accounts.viem.chain.id, name: 'Example' },
message: { contents: 'Hello from Tempo ID' },
primaryType: 'Note',
types: { Note: [{ name: 'contents', type: 'string' }] },
} as const
// [!code hl:start]
const signature = await accounts.signTypedData(typedData)
const valid = await accounts.verifyTypedData({
...typedData,
accessToken: await accounts.session.accessToken(),
address: accounts.viem.account.address,
signature,
})
// [!code hl:end]
console.log(valid)
}}
type="button"
>
Sign a note
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [react(), viem()],
})
```
:::
### Approve a shared account's transaction
A configurable account with several owners sends once enough of them approve, as Viem's [coordinated signing](https\://viem.sh/tempo/guides/configurable-accounts/send#coordinated-signing) describes. If the user's passkey is one of its owners, `sendTransactionSync` approves without an `owner`\: with the account's transaction, or with the operation `hash` alone. Coordination needs the plugin's `relay`, and the passkey signs only on the page of a first-party app with the `tempo-id:sign` scope.
:::code-group
```tsx [Approve.tsx]
import { Account } from 'viem/tempo'
import { accounts } from './tempo.config.js'
// A 2-of-2 account of the user's passkey and the app's cosigner.
const account = Account.fromConfig('0x7a3f2c1d5e8b9a0f4c6d3e2b1a0f9e8d7c6b5a49')
export function Approve(props: Approve.Props) {
return (
{
// [!code hl:start]
const receipt = props.hash
? await accounts.viem.sendTransactionSync({ hash: props.hash })
: await accounts.viem.sendTransactionSync({
account,
calls: [{ to: '0x1f9090aaE28b8a3dCeaDf281B0F12828e676c326', value: 0n }],
})
// [!code hl:end]
console.log(receipt.status, receipt.operation)
}}
type="button"
>
Approve
)
}
export declare namespace Approve {
type Props = {
/** The operation hash of a transaction that another owner sent. */
hash?: `0x${string}` | undefined
}
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [react(), viem({ relay: '/api/relay' })],
})
```
:::
A pending receipt's `transactionHash` is the operation hash, which the app passes to the next owner. If no passkey of the user owns the account, the call throws `Plugins.viem.OwnerRequiredError` .
### Accept the tokens of several apps
The plugin's `accessTokens` takes the options of the verifier of the access tokens that a verification reads. With `clientIds` , a server counts the access keys of each named app, as [Verify signed messages](/docs/guides/account-proof/verify-signed-messages#accept-the-tokens-of-several-apps) shows.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
export const accounts = Accounts.create({
chain: 'testnet',
clientId: 'https://app.example',
plugins: [
viem({
// [!code hl:start]
accessTokens: {
clientIds: ['https://app.example', 'https://admin.example'],
},
// [!code hl:end]
}),
],
})
```
### Check the registration
Viem's [`accessKey.getMetadata`](https\://viem.sh/tempo/actions/accessKey.getMetadata) reads the access key from the chain. The chain returns the zero address for an access key that it does not hold, and marks a revoked one.
:::code-group
```tsx [Registration.tsx]
import { isAddressEqual } from 'viem'
import { accounts } from './tempo.config.js'
export function Registration() {
const { session } = accounts.useSession()
if (!session?.accessKey) return null
const { account, keyAuthorization } = session.accessKey
return (
{
// [!code hl:start]
const metadata = await accounts.accessKey.getMetadata({
accessKey: keyAuthorization.keyId,
account,
})
// [!code hl:end]
const registered =
!metadata.isRevoked &&
isAddressEqual(metadata.address, keyAuthorization.keyId)
console.log(registered)
}}
type="button"
>
Check the access key
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [react(), viem()],
})
```
:::
### Send with a server's session
With the `backend` plugin, a server holds the session, and the `session` of a client call signs with its access key. A server shows no screen, so a refused transaction rejects with its error.
```ts [server.ts]
import { Accounts, Store } from 'accounts'
import { backend, viem } from 'accounts/plugins'
import { Hono } from 'hono'
import { parseUnits } from 'viem'
import { Addresses } from 'viem/tempo'
const accounts = Accounts.create({
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '10', token: 'ousd' }],
}),
chain: 'testnet',
clientId: process.env.APP_URL,
plugins: [backend({ store: Store.memory() }), viem()],
})
const app = new Hono()
// The sign-in routes of the `backend` plugin.
app.all('/api/*', (c) => accounts.handler.fetch(c.req.raw))
app.post('/send', async (c) => {
const session = await accounts.session.get(c.req.raw)
if (session?.method !== 'tempo-id') return c.body(null, 401)
const { receipt } = await accounts.viem({ session }).token.transferSync({ // [!code hl]
amount: parseUnits('1', 6),
to: '0x000000000000000000000000000000000000dEaD',
token: Addresses.ousd,
})
return c.json({ hash: receipt.transactionHash })
})
export default app
```
:::note
`Store.memory` keeps the sessions in the process, so a restart loses them. In production, use a store that each replica shares, such as `Store.postgres` or `Store.redis` .
:::
### Use another Tempo ID or chain
The guides use Tempo ID's own origin, and Tempo testnet with its own RPC. Three options change them.
| Option | Sets | Default |
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------- | ------------------------------------ |
| `url` | The origin of Tempo ID, such as a self-hosted or a local deployment | `https://id.tempo.xyz` |
| `chain` | `'mainnet'`, `'testnet'`, or the ID of another chain, such as `1337` | `'mainnet'` |
| `viem({ chain })` , `viem({ transport })` | The Viem chain of that ID, and the transport of its RPC | Tempo's chain of the ID, and its RPC |
The instance's chain is an ID, not a Viem chain. Viem's chain of a local node uses an RPC on port 8545, so a node at another URL needs a transport.
The `mpp` plugin reads the chain and the transport of the `viem` plugin. Token symbols such as OUSD resolve on mainnet, testnet, devnet, and a local node.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { http } from 'viem'
import { tempoLocalnet } from 'viem/tempo/chains'
export const accounts = Accounts.create({
chain: tempoLocalnet.id,
plugins: [
viem({ chain: tempoLocalnet, transport: http('http://localhost:9545/1') }),
],
url: 'http://localhost:8787',
})
```
## Next steps
# Wagmi \[A wagmi app connects to Tempo ID, and sends a transfer with the access key of the connection.]
## Overview
The `wagmi` plugin of `accounts/wagmi` adds a [wagmi](https\://wagmi.sh) config whose one connector is the instance, a wallet that Tempo ID backs. A sign-in connects wagmi, a sign-out or the expiry of the session's access key disconnects it, and wagmi's hooks sign with the session's [access key](/docs/guides/access-keys), with no prompt. The page's origin is its client ID, so the app needs no registration.
The demo connects, sends 1 OUSD on Tempo testnet with a `wagmi/tempo` hook, and disconnects.
## Walkthrough
The [`wagmi`](https\://github.com/tempoxyz/accounts/tree/main/examples/wagmi) example runs these steps in a React app.
::::steps
### Install the packages
`@wagmi/core` is an optional peer dependency of `accounts`, so the app installs it beside wagmi.
:::code-group
```sh [npm]
npm install accounts wagmi @wagmi/core viem @tanstack/react-query react react-dom
```
```sh [pnpm]
pnpm add accounts wagmi @wagmi/core viem @tanstack/react-query react react-dom
```
```sh [bun]
bun add accounts wagmi @wagmi/core viem @tanstack/react-query react react-dom
```
:::
### Create the instance
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { wagmi } from 'accounts/wagmi' // [!code ++]
export const accounts = Accounts.create({
// Each connection requests an access key that sends up to 100 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [
viem(),
wagmi(), // [!code ++]
],
})
```
### Provide the config
Pass `accounts.wagmi` to wagmi's provider, which restores the connection of a saved [session](/docs/guides/user-session) at mount.
:::code-group
```tsx [main.tsx]
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { createRoot } from 'react-dom/client'
import { WagmiProvider } from 'wagmi'
import { App } from './App.js'
import { accounts } from './tempo.config.js'
const queryClient = new QueryClient()
// [!code hl:start]
createRoot(document.getElementById('root')!).render(
,
)
// [!code hl:end]
```
```tsx [App.tsx]
import { useConnect, useConnection, useConnectors } from 'wagmi'
export function App() {
const connection = useConnection()
const [connector] = useConnectors()
const connect = useConnect()
if (connection.status !== 'connected')
return (
connect.mutate({ connector: connector! })}
type="button"
>
Connect with Tempo
)
return Tempo Account {connection.address}
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { wagmi } from 'accounts/wagmi'
export const accounts = Accounts.create({
// Each connection requests an access key that sends up to 100 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [viem(), wagmi()],
})
```
:::
### Connect from a click
`connect.mutate` opens Tempo ID's dialog, which requests the access key. `useConnection` then returns the Tempo Account's address.
If the user closes the dialog or denies the request, `connect` throws Viem's `UserRejectedRequestError`, and wagmi stays disconnected.
```tsx [App.tsx]
import { useConnect, useConnection, useConnectors } from 'wagmi'
export function App() {
const connection = useConnection()
const [connector] = useConnectors()
const connect = useConnect()
if (connection.status !== 'connected')
return (
connect.mutate({ connector: connector! })} // [!code hl]
type="button"
>
Connect with Tempo
)
return Tempo Account {connection.address}
}
```
### Send a transfer
`Hooks.token.useTransferSync` sends a transfer, and returns its receipt.
An app without React passes `accounts.wagmi` to the actions of `@wagmi/core`, such as `Actions.token.transferSync` of `@wagmi/core/tempo`.
```tsx [App.tsx]
import { parseUnits } from 'viem' // [!code ++]
import { Addresses } from 'viem/tempo' // [!code ++]
import { useConnect, useConnection, useConnectors } from 'wagmi'
import { Hooks } from 'wagmi/tempo' // [!code ++]
export function App() {
const connection = useConnection()
const [connector] = useConnectors()
const connect = useConnect()
const send = Hooks.token.useTransferSync() // [!code ++]
if (connection.status !== 'connected')
return (
connect.mutate({ connector: connector! })}
type="button"
>
Connect with Tempo
)
return (
Tempo Account {connection.address}
{/* [!code ++:16] */}
send.mutate({
amount: parseUnits('1', 6),
to: '0x000000000000000000000000000000000000dEaD',
token: Addresses.ousd,
})
}
type="button"
>
Send OUSD
{send.data && `Sent in ${send.data.receipt.transactionHash}.`}
)
}
```
### Disconnect
`disconnect.mutate` signs the user out of the app with `accounts.signOut` .
```tsx [Disconnect.tsx]
import { useDisconnect } from 'wagmi'
export function Disconnect() {
const disconnect = useDisconnect()
return (
disconnect.mutate()} // [!code hl]
type="button"
>
Disconnect
)
}
```
::::
## Use cases
Each use case sets an option of the `wagmi` plugin or of its config, or uses the `tempoId` connector.
### Connect without an access key
`accessKey` of wagmi's `connect` overrides the instance's access key for one connection. `false` connects with no access key, and signs in again over a held session.
:::code-group
```ts [connect.ts]
import { connect } from '@wagmi/core'
import { accounts } from './tempo.config.js'
export function connectWithoutAccessKey() {
const [connector] = accounts.wagmi.connectors
return connect(accounts.wagmi, { accessKey: false, connector }) // [!code hl]
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { wagmi } from 'accounts/wagmi'
export const accounts = Accounts.create({
// Each connection requests an access key that sends up to 100 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [viem(), wagmi()],
})
```
:::
### Add other wallets
`connectors` adds connectors after the instance's, such as an injected wallet. Without it, the config holds only Tempo ID.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { wagmi } from 'accounts/wagmi'
import { injected } from 'wagmi/connectors'
export const accounts = Accounts.create({
// Each connection requests an access key that sends up to 100 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [viem(), wagmi({ connectors: [injected()] })], // [!code hl]
})
```
### Render on a server
`accounts.wagmi` called with overrides returns a new config, such as one with wagmi's `ssr` for a page that a server renders. A read without a call returns the default config.
:::code-group
```tsx [Providers.tsx]
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import type { ReactNode } from 'react'
import { WagmiProvider } from 'wagmi'
import { accounts } from './tempo.config.js'
const config = accounts.wagmi({ ssr: true }) // [!code hl]
const queryClient = new QueryClient()
export function Providers(props: { children: ReactNode }) {
return (
{props.children}
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { wagmi } from 'accounts/wagmi'
export const accounts = Accounts.create({
// Each connection requests an access key that sends up to 100 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [viem(), wagmi()],
})
```
:::
### Add Tempo ID to an existing config
An app with its own wagmi config adds the `tempoId` connector, which takes the options of `Accounts.create` but `chain` . It creates the instance on the config's first chain, unless its options name another chain of the config.
```ts [config.ts]
import { tempoId } from 'accounts/wagmi'
import { createConfig, http } from 'wagmi'
import { tempoModerato } from 'viem/tempo/chains'
export const config = createConfig({
chains: [tempoModerato],
connectors: [
tempoId({
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
}),
],
transports: { [tempoModerato.id]: http() },
})
```
## Next steps
# Read users \[A session holds the user of a sign-in\: an ID and a verified email address.]
## Overview
Each [session](/docs/guides/user-session) holds its user\: an ID and a verified email address. The ID stays the same at every sign-in and in every app.
The demo signs a user in through Tempo ID's dialog, and shows the session's user.
## Walkthrough
The [`web`](https\://github.com/tempoxyz/accounts/tree/main/examples/web) example runs these steps in a React app.
::::steps
### Install the packages
:::code-group
```sh [npm]
npm install accounts react react-dom viem
```
```sh [pnpm]
pnpm add accounts react react-dom viem
```
```sh [bun]
bun add accounts react react-dom viem
```
:::
### Create the instance
The `react` plugin adds `accounts.useSession` .
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [react()],
})
```
### Sign the user in
`dialog.signIn` returns the session.
:::code-group
```tsx [SignIn.tsx]
import { accounts } from './tempo.config.js'
export function SignIn() {
async function signIn() {
const session = await accounts.dialog.signIn() // [!code hl]
console.log(session.user)
// { email: 'user@example.com', id: 'user_01M76GM8JG5NG1TZVQF63YM2MS' }
}
return (
void signIn()} type="button">
Sign in with Tempo
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [react()],
})
```
:::
| Property | Value |
| ------------------------------------------------------------------------------ | -------------------------------------------------------------- |
| `user.email` | The user's verified email address |
| `user.id` | The user's ID, `user_` and a ULID. Each token's `sub` holds it |
Key the app's data by `user.id` , not by `email` .
### Render the user
`accounts.useSession` also returns a session restored on a later visit. Without React, `accounts.session.get()` returns it.
:::code-group
```tsx [App.tsx]
import { accounts } from './tempo.config.js'
async function signIn() {
const session = await accounts.dialog.signIn()
console.log(session.user)
}
export function App() {
const { isPending, session } = accounts.useSession() // [!code hl]
if (isPending) return Checking the session…
if (!session)
return (
void signIn()} type="button">
Sign in with Tempo
)
return Signed in as {session.user.email}
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [react()],
})
```
:::
### Identify the user to a server
A server reads the user only from a token that it verifies\:
| Token | Session property | Names | Lifetime |
| ------------ | --------------------------------------------------------------------------------------- | ---------------------------------------- | --------- |
| ID token | `idToken` | The ID and the email address, to the app | 10 hours |
| Access token | `accessToken` | The ID, to an API | 5 minutes |
The app's server [verifies the ID token](/docs/guides/identity/verify-id-tokens). An API verifies the [access token](/docs/guides/api-authentication/authenticate-requests), which `accounts.session.fetch` sends.
:::code-group
```tsx [Me.tsx]
import { accounts } from './tempo.config.js'
export function Me() {
return (
{
// [!code hl:start]
const response = await accounts.session.fetch({
url: 'https://api.example/me',
})
// [!code hl:end]
console.log(await response.json())
}}
type="button"
>
Ask the API who I am
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [react()],
})
```
:::
:::warning
A page can send any ID or email address, so a server never reads the user from a request field.
:::
::::
## Use cases
Each use case reads one property of the session, or the user of an access token with the `tokens` plugin.
### Read the account of the access key
`session.accessKey.account` holds the Tempo Account that the session's access key acts for. It is present only if the instance names `accessKey` , since each sign-in then requests an access key.
:::code-group
```tsx [Account.tsx]
import { accounts } from './tempo.config.js'
export function Account() {
const { session } = accounts.useSession()
return Tempo Account {session?.accessKey?.account}
// [!code hl]
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// [!code hl:start]
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
// [!code hl:end]
chain: 'testnet',
plugins: [react()],
})
```
:::
### Read the selected Tempo Account
`session.account` holds the Tempo Account that Tempo ID selects for the app. A sign-in through a redirect, a dialog, or a device reads none, so `accounts.account.get` reads it, and saves it in the session.
:::code-group
```tsx [Account.tsx]
import { accounts } from './tempo.config.js'
export function Account() {
async function read() {
const account = await accounts.account.get() // [!code hl]
console.log(account?.address)
}
return (
void read()} type="button">
Read the Tempo Account
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [react()],
})
```
:::
### Read the signer of a challenge
`session.address` holds the Tempo Account that signed the challenge of a sign-in, such as of [Sign-In With Ethereum](/docs/guides/siwe). After a sign-in without a challenge, it is absent. A server trusts it only after it verifies the signature, as [Sign challenges](/docs/guides/account-proof/sign-challenges) shows.
:::code-group
```tsx [SignIn.tsx]
import { accounts } from './tempo.config.js'
export function SignIn() {
async function signIn() {
const session = await accounts.dialog.signIn({
challenge: async (signal) => {
const response = await fetch('/challenge', { method: 'POST', signal })
return response.text()
},
})
console.log(session.address) // [!code hl]
}
return (
void signIn()} type="button">
Sign in with Tempo
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [react()],
})
```
:::
### Read the user on an API
An access token holds no email address. An API reads the user with `tokens.userInfo` , from the token that `tokens.verifyAccessToken` returns, as [Authenticate requests](/docs/guides/api-authentication/authenticate-requests#read-the-user) shows.
A refused access token throws `Accounts.RequestError` with the reason `invalid_token`.
```ts [server.ts]
import { Accounts } from 'accounts'
import { tokens } from 'accounts/plugins'
import { Hono } from 'hono'
const accounts = Accounts.create({
clientId: 'https://app.example',
plugins: [tokens()],
})
const app = new Hono()
app.get('/me', async (c) => {
const token = await accounts.tokens.verifyAccessToken(c.req.raw)
if (!token) return c.json({ error: 'invalid_token' }, 401)
const user = await accounts.tokens.userInfo({ accessToken: token }) // [!code hl]
// { email: 'user@example.com', id: 'user_01M76GM8JG5NG1TZVQF63YM2MS' }
return c.json(user)
})
export default app
```
## Next steps
# Verify ID tokens \[A server verifies the ID token of a sign-in before it reads the user from it.]
## Overview
The ID token is a JWT that names the user to the app. A server that receives one checks its signature, issuer, audience, and expiry, and only then reads its claims. The `tokens` plugin runs these checks against Tempo ID's key set.
The demo sends the session's ID token to the site's server, which returns its claims, then sends a copy with another email address, which the server refuses.
## Walkthrough
::::steps
### Install the packages
Install `accounts` with Viem, in the app and on the server.
:::code-group
```sh [npm]
npm install accounts react react-dom viem
```
```sh [pnpm]
pnpm add accounts react react-dom viem
```
```sh [bun]
bun add accounts react react-dom viem
```
:::
### Create the instance
The page's origin is its client ID, the ID token's `aud`.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
export const accounts = Accounts.create({ chain: 'testnet' })
```
### Send the ID token
The [session](/docs/guides/user-session) holds the ID token as `idToken` , which is optional, since a refresh can return none.
:::code-group
```tsx [Verify.tsx]
import { accounts } from './tempo.config.js'
export function Verify() {
async function verify() {
const session = await accounts.dialog.signIn()
const response = await fetch('/api/verify', {
body: JSON.stringify({ idToken: session.idToken }), // [!code hl]
headers: { 'content-type': 'application/json' },
method: 'POST',
})
console.log(await response.json())
}
return (
void verify()} type="button">
Sign in with Tempo
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
export const accounts = Accounts.create({ chain: 'testnet' })
```
:::
### Create the server instance
On the server, create an instance with the `tokens` plugin. Its `clientId` is the client ID of the app, the origin of the page. The instance keeps Tempo ID's key set for 10 minutes, so create it once.
```ts [server.ts]
import { Accounts } from 'accounts'
import { tokens } from 'accounts/plugins'
const accounts = Accounts.create({
clientId: 'https://app.example',
plugins: [tokens()],
})
```
### Verify the ID token
`tokens.verifyIdToken` returns the claims of the ID token, or `undefined` if a check fails.
```ts [server.ts]
import { Accounts } from 'accounts'
import { tokens } from 'accounts/plugins'
const accounts = Accounts.create({
clientId: 'https://app.example',
plugins: [tokens()],
})
export async function handle(request: Request) {
const { idToken } = (await request.json()) as { idToken: string }
const token = await accounts.tokens.verifyIdToken({ idToken }) // [!code hl]
if (!token)
return Response.json({ error: 'invalid_token' }, { status: 401 })
return Response.json({ email: token.email, id: token.userId })
}
```
| Check | Refuses |
| --------- | ------------------------------------------------------------------------ |
| Signature | A token that Tempo ID's key set did not sign with RS256 |
| Type | A header `typ` other than `JWT`, such as a logout token or access token |
| Issuer | A token of another issuer than Tempo ID |
| Audience | A token of another app, also one that names the app beside another app |
| Expiry | A token past its `exp` |
| Claims | A token without `email`, `email_verified`, `exp`, `iat`, `iss`, or `sub` |
The audience comes from the instance's `clientId` , never from a value of the request.
### Read the claims
The verified token names the user. Its `userId` is the `id` of `session.user` .
| Property | Claim | Value |
| --------------------------------------------------------------------------------------------------- | ---------------- | ----------------------------------------------------------------------- |
| `authTime` | `auth_time` | When the user signed in to Tempo ID, in milliseconds |
| `clientId` | `aud` | The client ID of the app |
| `email` | `email` | The email address of the user |
| `emailVerified` | `email_verified` | `true` |
| `expiresAt` | `exp` | When the ID token expires, in milliseconds\: 10 hours after issue |
| `issuedAt` | `iat` | When Tempo ID issued the ID token, in milliseconds |
| `sessionId` | `sid` | The Tempo ID session of the sign-in. Absent without a logout of the app |
| `userId` | `sub` | The ID of the user |
### Answer the request
Respond with 401 if `tokens.verifyIdToken` returns `undefined`. If the server cannot fetch Tempo ID's key set, it throws `Accounts.RequestError` with status 0. The ID token can still be valid, so respond with 503.
```ts [server.ts]
import { Accounts } from 'accounts'
import { tokens } from 'accounts/plugins'
const accounts = Accounts.create({
clientId: 'https://app.example',
plugins: [tokens()],
})
export async function handle(request: Request) {
const { idToken } = (await request.json()) as { idToken: string }
try {
const token = await accounts.tokens.verifyIdToken({ idToken })
if (!token)
return Response.json({ error: 'invalid_token' }, { status: 401 })
return Response.json({ email: token.email, id: token.userId })
} catch (error) {
// [!code hl:start]
if (error instanceof Accounts.RequestError && error.status === 0)
return Response.json(
{ error: 'temporarily_unavailable' },
{ status: 503 },
)
// [!code hl:end]
throw error
}
}
```
::::
:::warning
An ID token is no credential for an API\: its audience is the app, and it lasts 10 hours. An API verifies the request's [access token](/docs/guides/api-authentication/authenticate-requests).
:::
## Use cases
Each use case sets one option of the `tokens` plugin, which `tokens.verifyIdToken` uses.
### Accept several apps
A server that receives the ID tokens of several apps names their client IDs in `clientIds` . The `clientId` of the verified token names the app of each token.
An ID token names the app itself, so `clientIds` set to `'any'` verifies only the ID tokens of the instance's own `clientId` .
```ts [server.ts]
import { Accounts } from 'accounts'
import { tokens } from 'accounts/plugins'
const accounts = Accounts.create({
clientId: 'https://app.example',
plugins: [
tokens({ clientIds: ['https://app.example', 'https://admin.example'] }), // [!code hl]
],
})
```
### Reach Tempo ID at an internal address
If the instance's `url` reaches Tempo ID at another address, such as an internal host, `issuer` names Tempo ID's public origin. Each token names that origin as its issuer.
```ts [server.ts]
import { Accounts } from 'accounts'
import { tokens } from 'accounts/plugins'
const accounts = Accounts.create({
clientId: 'https://app.example',
plugins: [tokens({ issuer: 'https://id.tempo.xyz' })], // [!code hl]
url: 'http://tempo-id.internal',
})
```
### Refresh the key set sooner
`maxAge` sets how long Tempo ID's key set verifies, in milliseconds. A shorter time refuses the tokens of a removed signing key sooner. Defaults to 10 minutes. Few verifications wait for a fetch of the set\:
| Age of the key set | Verification |
| ------------------------------ | -------------------------------------------------------------- |
| Before half of `maxAge` | Verifies with the set |
| From half of `maxAge` | Verifies with the set, and fetches a new set in the background |
| From `maxAge`, or no set | Waits for a fetch |
| A token names an unknown `kid` | Waits for a fetch, at most once each 30 seconds |
```ts [server.ts]
import { Accounts } from 'accounts'
import { tokens } from 'accounts/plugins'
const accounts = Accounts.create({
clientId: 'https://app.example',
plugins: [tokens({ maxAge: 60_000 })], // [!code hl]
})
```
### Keep the key set across instances
Each new process starts without Tempo ID's key set. `keySet.cache` takes a `Store` that the instances share, so a new instance verifies with its copy, without a fetch. `keySet.defer` keeps the background fetches and writes running after the response.
```ts [tempo.config.ts]
import { Accounts, Store } from 'accounts'
import { createClient } from 'redis'
const redis = await createClient({ url: process.env.REDIS_URL }).connect()
export const accounts = Accounts.create({
chain: 'testnet',
keySet: { cache: Store.redis(redis) }, // [!code hl]
})
```
### Limit the fetch of the key set
`timeout` sets how long a fetch of the key set may take, in milliseconds. A slower fetch throws `Accounts.RequestError` with status 0, which the server answers with 503. Defaults to 5 seconds.
```ts [server.ts]
import { Accounts } from 'accounts'
import { tokens } from 'accounts/plugins'
const accounts = Accounts.create({
clientId: 'https://app.example',
plugins: [tokens({ timeout: 2_000 })], // [!code hl]
})
```
## Next steps
# Authenticate requests \[An app sends the access token of a session to an API, and the API verifies the token.]
## Overview
An app sends the session's access token, a JWT that names the user and the app. The API verifies it with the `tokens` plugin, against Tempo ID's key set, with no call to Tempo ID for each request.
The demo calls a route of the site with the session's access token, and the route returns the token's user ID. A call without the access token receives 401.
## Walkthrough
The steps build a React app and the API that it calls.
::::steps
### Install the packages
Install `accounts` with Viem, in the app and in the API.
:::code-group
```sh [npm]
npm install accounts react react-dom viem
```
```sh [pnpm]
pnpm add accounts react react-dom viem
```
```sh [bun]
bun add accounts react react-dom viem
```
:::
### Send the access token
`session.fetch` sends the access token as a Bearer token, and refreshes it first if it expires soon. The `react` plugin adds `useSession` .
:::code-group
```tsx [App.tsx]
import { useState } from 'react'
import { accounts } from './tempo.config.js'
export function App() {
const { isPending, session } = accounts.useSession()
const [userId, setUserId] = useState()
async function call() {
// [!code hl:start]
const response = await accounts.session.fetch({
url: 'https://api.example/me',
})
// [!code hl:end]
const body = (await response.json()) as { userId: string }
setUserId(body.userId)
}
if (isPending) return Checking your session…
if (!session)
return (
accounts.dialog.signIn()} type="button">
Sign in
)
return (
<>
Call the API
{userId && The API read the user {userId}.
}
>
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({ plugins: [react()] })
```
:::
:::note
A browser sends a cross-origin request only if the API's CORS policy allows the page's origin.
:::
### Create the instance
In the API, the `tokens` plugin adds `tokens.verifyAccessToken` . It accepts only the access tokens of the app's `clientId` , such as the page's origin. Create the instance once, since it keeps Tempo ID's key set for 10 minutes.
```ts [server.ts]
import { Accounts } from 'accounts'
import { tokens } from 'accounts/plugins'
const accounts = Accounts.create({
clientId: 'https://app.example',
plugins: [tokens()],
})
```
### Read the user
`tokens.verifyAccessToken` reads the token of the authorization header, and checks its signature, type, issuer, audience, expiry, and app. It returns the verified token, or `undefined` if the request holds no token that verifies.
Without a verified token, the API answers 401. The API also refuses a DPoP token, which names a `boundTo` , until it refuses a repeated proof, as [Bind DPoP keys](/docs/guides/api-authentication/bind-dpop-keys#refuse-a-repeated-proof) shows.
```ts [server.ts]
import { Accounts } from 'accounts'
import { tokens } from 'accounts/plugins'
const accounts = Accounts.create({
clientId: 'https://app.example',
plugins: [tokens()],
})
export default {
async fetch(request: Request) {
const token = await accounts.tokens.verifyAccessToken(request) // [!code hl]
if (!token || token.boundTo)
return Response.json({ error: 'invalid_token' }, { status: 401 })
return Response.json({ userId: token.userId })
},
}
```
If the key set cannot be fetched, the call throws `Accounts.RequestError` with status 0. The token can still be valid, so the API answers 503, and the app keeps its session, as [Limit the fetch of the key set](/docs/guides/api-authentication/authenticate-requests#limit-the-fetch-of-the-key-set) shows.
The token, never a request field, names whose data the API reads or changes\:
| Property | Names |
| --------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- |
| `accessKeys` | The user's live [access keys](/docs/guides/access-keys) for the app, from the `access_keys` claim |
| `accounts` | The user's Tempo Account addresses, from `tempo_accounts`. Empty for a third-party app |
| `clientId` | The app that received the token |
| `compliance` | The [screening state](https\://github.com/tempoxyz/id/blob/main/docs/compliance.md) of each address |
| `scope` | The scopes that the app received |
| `userId` | The user, from `sub` |
::::
## Use cases
Each use case sets one option of the `tokens` plugin, which `tokens.verifyAccessToken` uses, or calls another member of the plugin.
### Accept the tokens of several apps
`clientIds` names each app whose tokens the API accepts. The token's `clientId` names the app of each request.
```ts [server.ts]
import { Accounts } from 'accounts'
import { tokens } from 'accounts/plugins'
const accounts = Accounts.create({
clientId: 'https://app.example',
plugins: [
tokens({
clientIds: ['https://app.example', 'https://admin.app.example'], // [!code hl]
}),
],
})
```
### Accept the tokens of every app
A [registered resource](https\://github.com/tempoxyz/id/blob/main/docs/resources.md) that any app may call, such as an MCP server, sets `clientIds` to `'any'`. It then names itself in `audience` , so it accepts only the tokens issued for it. [Charge tool calls](/docs/guides/mcp/charge-tool-calls) shows such a server.
```ts [server.ts]
import { Accounts } from 'accounts'
import { tokens } from 'accounts/plugins'
const accounts = Accounts.create({
clientId: 'https://mcp.example.com',
plugins: [
// [!code hl:start]
tokens({ audience: 'https://mcp.example.com/mcp', clientIds: 'any' }),
// [!code hl:end]
],
})
```
### Refuse a removed signing key sooner
`maxAge` sets how long the key set verifies, in milliseconds. A shorter time refuses the tokens of a [removed signing key](https\://github.com/tempoxyz/id/blob/main/docs/access-tokens.md#signing-key-revocation) sooner. Defaults to 10 minutes. Few verifications wait for a fetch of the set\:
| Age of the key set | Verification |
| ------------------------------ | -------------------------------------------------------------- |
| Before half of `maxAge` | Verifies with the set |
| From half of `maxAge` | Verifies with the set, and fetches a new set in the background |
| From `maxAge`, or no set | Waits for a fetch |
| A token names an unknown `kid` | Waits for a fetch, at most once each 30 seconds |
```ts [server.ts]
import { Accounts } from 'accounts'
import { tokens } from 'accounts/plugins'
const accounts = Accounts.create({
clientId: 'https://app.example',
plugins: [tokens({ maxAge: 60_000 })], // [!code hl]
})
```
### Keep the key set across instances
Each new process starts without Tempo ID's key set. `keySet.cache` takes a `Store` that the instances share, so a new instance verifies with its copy, without a fetch. `keySet.defer` keeps the background fetches and writes running after the response.
```ts [tempo.config.ts]
import { Accounts, Store } from 'accounts'
import { createClient } from 'redis'
const redis = await createClient({ url: process.env.REDIS_URL }).connect()
export const accounts = Accounts.create({
clientId: 'https://app.example',
keySet: { cache: Store.redis(redis) }, // [!code hl]
})
```
### Reach Tempo ID at an internal address
If the instance's `url` reaches Tempo ID at another address, such as an internal host, `issuer` names Tempo ID's public origin. Each token names that origin as its issuer.
```ts [server.ts]
import { Accounts } from 'accounts'
import { tokens } from 'accounts/plugins'
const accounts = Accounts.create({
clientId: 'https://app.example',
plugins: [tokens({ issuer: 'https://id.tempo.xyz' })], // [!code hl]
url: 'http://tempo-id.internal',
})
```
### Limit the fetch of the key set
`timeout` sets how long a fetch of the key set may take, in milliseconds. Defaults to 5 seconds. A slower or failed fetch throws `Accounts.RequestError` with status 0, which the API answers with 503.
```ts [server.ts]
import { Accounts } from 'accounts'
import { tokens } from 'accounts/plugins'
const accounts = Accounts.create({
clientId: 'https://app.example',
plugins: [tokens({ timeout: 2_000 })], // [!code hl]
})
export default {
async fetch(request: Request) {
const token = await accounts.tokens
.verifyAccessToken(request)
.catch((error: unknown) => {
// [!code hl:start]
if (error instanceof Accounts.RequestError && error.status === 0)
return error
// [!code hl:end]
throw error
})
if (token instanceof Accounts.RequestError)
return Response.json(
{ error: 'temporarily_unavailable' },
{ status: 503 },
)
if (!token || token.boundTo)
return Response.json({ error: 'invalid_token' }, { status: 401 })
return Response.json({ userId: token.userId })
},
}
```
### Read the email address
An access token holds no email address. `tokens.userInfo` reads the user of a verified token from Tempo ID, as [Read users](/docs/guides/identity/read-users#read-the-user-on-an-api) shows.
```ts [server.ts]
import { Accounts } from 'accounts'
import { tokens } from 'accounts/plugins'
const accounts = Accounts.create({
clientId: 'https://app.example',
plugins: [tokens()],
})
export default {
async fetch(request: Request) {
const token = await accounts.tokens.verifyAccessToken(request)
if (!token || token.boundTo)
return Response.json({ error: 'invalid_token' }, { status: 401 })
const user = await accounts.tokens.userInfo({ accessToken: token }) // [!code hl]
return Response.json({ email: user.email })
},
}
```
## Next steps
# Use session cookies \[A backend keeps the tokens of a session, and a session cookie authenticates each request of the page.]
## Overview
If a page's API runs on its own backend, the page needs no token. The `backend` plugin signs the user in on the server, keeps the [session](/docs/guides/user-session) in a `Store` , and sets an HttpOnly session cookie. A deployed origin lists its callback in a web app manifest.
The demo signs in through the site's backend routes, and calls an API route with the cookie. It then signs out, and the same call receives 401.
## Walkthrough
The [`authenticated-api`](https\://github.com/tempoxyz/accounts/tree/main/examples/authenticated-api) example runs this flow with Hono, and serves a React app and its API at one origin.
::::steps
### Install the packages
:::code-group
```sh [npm]
npm install accounts hono react react-dom viem
```
```sh [pnpm]
pnpm add accounts hono react react-dom viem
```
```sh [bun]
bun add accounts hono react react-dom viem
```
:::
### Create the backend
The `backend` plugin keeps each session in a store on the server, since each session holds a refresh token and an access key's private key. The `APP_URL` variable names the app's origin, its `clientId` .
```ts [server.ts]
import { Accounts, Store } from 'accounts'
import { backend } from 'accounts/plugins'
const accounts = Accounts.create({
clientId: process.env.APP_URL,
plugins: [backend({ store: Store.memory() })],
})
```
:::note
`Store.memory` keeps the sessions in the process, so a restart loses them. In production, use a store that each replica shares, such as `Store.postgres` or `Store.redis` .
:::
### Serve the sign-in routes
`accounts.handler` serves the sign-in, callback, sign-out, and session routes under `/api/auth`. The callback sets the session cookie.
```ts [server.ts]
import { Accounts, Store } from 'accounts'
import { backend } from 'accounts/plugins'
import { Hono } from 'hono'
const accounts = Accounts.create({
clientId: process.env.APP_URL,
plugins: [backend({ store: Store.memory() })],
})
// [!code hl:start]
const app = new Hono().all('/api/*', (c) =>
accounts.handler.fetch(c.req.raw),
)
// [!code hl:end]
export default app
```
A deployed origin names `/api/auth/callback` in the `redirect_uris` of its [web app manifest](https\://github.com/tempoxyz/id/blob/main/docs/apps.md#origin-client-id). Without one, Tempo ID redirects only to the origin's root, so both instances set `redirectUri` to the root.
### Sign the user in
With `backend` , the `dialog` plugin runs the sign-in through the backend's routes, and `dialog.signIn` returns the user.
:::code-group
```tsx [App.tsx]
import { useState } from 'react'
import { accounts } from './tempo.config.js'
type Session = Awaited>
export function App() {
const [session, setSession] = useState()
if (!session)
return (
setSession(await accounts.dialog.signIn())} // [!code hl]
type="button"
>
Sign in
)
return Signed in as {session.user.email}
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { dialog } from 'accounts/plugins'
export const accounts = Accounts.create({
plugins: [dialog({ backend: true })], // [!code hl]
})
```
:::
### Authenticate each request
`session.get` returns the cookie's session, or `undefined`. The cookie is SameSite Lax, so a browser also sends it from another origin of the same site. Hono's CSRF middleware refuses a form post from another origin.
```ts [server.ts]
import { Accounts, Store } from 'accounts'
import { backend } from 'accounts/plugins'
import { Hono } from 'hono'
import { csrf } from 'hono/csrf'
import { createMiddleware } from 'hono/factory'
const accounts = Accounts.create({
clientId: process.env.APP_URL,
plugins: [backend({ store: Store.memory() })],
})
type Variables = { userId: string }
const auth = createMiddleware<{ Variables: Variables }>(async (c, next) => {
const session = await accounts.session.get(c.req.raw) // [!code hl]
if (session?.method !== 'tempo-id')
return c.json({ error: 'invalid_token' }, 401)
c.set('userId', session.user.id)
await next()
})
const app = new Hono().all('/api/*', (c) =>
accounts.handler.fetch(c.req.raw),
)
// [!code hl:start]
app
.use('/v1/*', csrf(), auth)
.get('/v1/me', (c) => c.json({ userId: c.get('userId') }))
// [!code hl:end]
export default app
```
### Call the API
The page calls the API at its own origin. A 401 means that the session ended. `App` renders `Me` for a signed-in user.
:::code-group
```tsx [App.tsx]
import { useState } from 'react'
import { Me } from './Me.js'
import { accounts } from './tempo.config.js'
type Session = Awaited>
export function App() {
const [session, setSession] = useState()
if (!session)
return (
setSession(await accounts.dialog.signIn())}
type="button"
>
Sign in
)
return // [!code hl]
}
```
```tsx [Me.tsx]
import { useState } from 'react'
export function Me() {
const [status, setStatus] = useState()
async function call() {
const response = await fetch('/v1/me') // [!code hl]
if (response.status === 401) return setStatus('The session ended.') // [!code hl]
const body = (await response.json()) as { userId: string }
setStatus(`The API read the session of ${body.userId}.`)
}
return (
<>
Call the API
{status}
>
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { dialog } from 'accounts/plugins'
export const accounts = Accounts.create({
plugins: [dialog({ backend: true })],
})
```
:::
::::
## Use cases
Each use case sets one option of the `backend` plugin, or uses one more of its reads or routes.
### Accept a cookie or an access token
If the backend also serves other clients, such as a CLI, `accessToken` accepts both. `session.get` reads the cookie first, then an [access token](/docs/guides/api-authentication/authenticate-requests) of the app in the authorization header.
```ts [server.ts]
import { Accounts, Store } from 'accounts'
import { backend } from 'accounts/plugins'
import { Hono } from 'hono'
import { csrf } from 'hono/csrf'
import { createMiddleware } from 'hono/factory'
const accounts = Accounts.create({
clientId: process.env.APP_URL,
plugins: [
backend({
accessToken: true, // [!code hl]
store: Store.memory(),
}),
],
})
type Variables = { userId: string }
const auth = createMiddleware<{ Variables: Variables }>(async (c, next) => {
const session = await accounts.session.get(c.req.raw)
if (session?.method === 'tempo-id') c.set('userId', session.user.id)
// [!code hl:start]
else if (session?.method === 'access-token')
c.set('userId', session.token.userId)
// [!code hl:end]
else return c.json({ error: 'invalid_token' }, 401)
await next()
})
const app = new Hono().all('/api/*', (c) =>
accounts.handler.fetch(c.req.raw),
)
app
.use('/v1/*', csrf(), auth)
.get('/v1/me', (c) => c.json({ userId: c.get('userId') }))
export default app
```
`accessToken` also takes the options of the `tokens` plugin, such as `clientIds` , and `url` , the public origin behind a proxy that terminates TLS, which each DPoP proof names.
### Call an API for the user
`session.fetch` sends a request with the access token of the cookie's session. It returns `undefined` without a session, and sends no request then.
```ts [server.ts]
import { Accounts, Store } from 'accounts'
import { backend } from 'accounts/plugins'
import { Hono } from 'hono'
const accounts = Accounts.create({
clientId: process.env.APP_URL,
plugins: [backend({ store: Store.memory() })],
})
const app = new Hono().all('/api/*', (c) =>
accounts.handler.fetch(c.req.raw),
)
app.get('/v1/profile', async (c) => {
// [!code hl:start]
const response = await accounts.session.fetch(c.req.raw, {
url: 'https://api.example/me',
})
// [!code hl:end]
if (!response) return c.json({ error: 'invalid_token' }, 401)
return c.json(await response.json())
})
export default app
```
### Read the session in the page
After a reload, the page holds no session. The session route of `accounts.handler` returns the cookie's session, or `null`, so the click opens the dialog only without one.
:::code-group
```tsx [App.tsx]
import { useState } from 'react'
import { accounts } from './tempo.config.js'
type Session = Awaited>
export function App() {
const [session, setSession] = useState()
async function signIn() {
// [!code hl:start]
const response = await fetch('/api/auth/session')
const body = (await response.json()) as { session: Session | null }
// [!code hl:end]
setSession(body.session ?? (await accounts.dialog.signIn()))
}
if (!session)
return (
Sign in
)
return Signed in as {session.user.email}
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { dialog } from 'accounts/plugins'
export const accounts = Accounts.create({
plugins: [dialog({ backend: true })],
})
```
:::
## Next steps
# Bind DPoP keys \[An app binds its tokens to a DPoP key, and an API verifies a proof of the DPoP key with each request.]
## Overview
With a DPoP key on the instance, Tempo ID binds the app's tokens to it ([DPoP](https\://github.com/tempoxyz/id/blob/main/docs/dpop.md), RFC 9449). The API's verifier checks each request's proof against the DPoP key that the token names, and the API refuses a repeated proof itself.
The demo calls an API route of the site with a bound access token and a proof, then repeats the proof, which the route refuses with 401.
## Walkthrough
The steps add a DPoP key to the app and the API of [Authenticate requests](/docs/guides/api-authentication/authenticate-requests#walkthrough).
::::steps
### Bind the tokens to a DPoP key
The `dpop` plugin gives the instance a DPoP key that the page cannot export. The instance sends a proof with each token request, and Tempo ID binds the session's tokens to the key. Tokens refresh only with the key that bound them, so the plugin keeps it in IndexedDB, beside the session.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { dpop } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
plugins: [await dpop(), react()], // [!code ++]
})
```
### Call the API
`session.fetch` sends a bound [access token](/docs/guides/api-authentication/authenticate-requests) with the DPoP scheme and a new proof, so the call of the app does not change.
:::code-group
```tsx [App.tsx]
import { useState } from 'react'
import { accounts } from './tempo.config.js'
export function App() {
const { isPending, session } = accounts.useSession()
const [userId, setUserId] = useState()
async function call() {
// [!code hl:start]
const response = await accounts.session.fetch({
url: 'https://api.example/me',
})
// [!code hl:end]
const body = (await response.json()) as { userId: string }
setUserId(body.userId)
}
if (isPending) return Checking your session…
if (!session)
return (
accounts.dialog.signIn()} type="button">
Sign in
)
return (
<>
Call the API
{userId && The API read the user {userId}.
}
>
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { dpop } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
plugins: [await dpop(), react()],
})
```
:::
### Verify each proof
In the API, `tokens.verifyAccessToken` checks the proof of a bound token against the DPoP key that the token names, over the method and the URL of the request. It reads the DPoP header and the authorization scheme itself, so the instance does not change. It returns `undefined` for a bound token without a valid proof, or with the Bearer scheme.
```ts [server.ts]
import { Accounts } from 'accounts'
import { tokens } from 'accounts/plugins'
const accounts = Accounts.create({
clientId: 'https://app.example',
plugins: [tokens()],
})
```
:::tip
Behind a proxy that terminates TLS, the URL of the request is the internal URL. Pass the public origin as `url` , and the path and query of each request apply to it. A function of the request can return the whole public URL instead.
```ts [server.ts]
import { Accounts } from 'accounts'
import { tokens } from 'accounts/plugins'
const accounts = Accounts.create({
clientId: 'https://app.example',
plugins: [tokens({ url: 'https://api.example' })], // [!code hl]
})
```
:::
### Refuse a repeated proof
`tokens.verifyAccessToken` accepts a proof again within its window of 5 minutes. The API thus records the ID of each `proof` until the proof expires, and refuses a recorded one. Here Redis records each ID in one atomic step.
```ts [server.ts]
import { Accounts } from 'accounts'
import { tokens } from 'accounts/plugins'
import { createClient } from 'redis'
const redis = await createClient({ url: process.env.REDIS_URL }).connect()
const accounts = Accounts.create({
clientId: 'https://app.example',
plugins: [tokens()],
})
export default {
async fetch(request: Request) {
const token = await accounts.tokens.verifyAccessToken(request)
if (!token)
return Response.json({ error: 'invalid_token' }, { status: 401 })
// [!code hl:start]
if (token.proof) {
// `NX` sets the ID only if Redis holds none, and returns `null` otherwise.
const first = await redis.sendCommand([
'SET',
`dpop:${token.proof.id}`,
'1',
'NX',
'PXAT',
String(token.proof.expiresAt),
])
if (!first)
return Response.json({ error: 'invalid_dpop_proof' }, { status: 401 })
}
// [!code hl:end]
return Response.json({ userId: token.userId })
},
}
```
:::warning
The store checks and adds an ID in one atomic step, such as `SET` with `NX` in Redis. An eventually consistent store can accept a repeated proof.
:::
A backend with the `backend` plugin and its `accessToken` option verifies each proof too, as [Use session cookies](/docs/guides/api-authentication/use-session-cookies) shows. Its `session.get` returns the token with its `proof` , which the backend records in the same way.
The plugin checks each proof against the URL of the request. Behind a proxy that terminates TLS, `accessToken` takes the public origin as `url` , as the `tokens` plugin does.
```ts [server.ts]
import { Accounts, Store } from 'accounts'
import { backend } from 'accounts/plugins'
const accounts = Accounts.create({
clientId: 'https://app.example',
plugins: [
backend({
accessToken: { url: 'https://api.example' }, // [!code hl]
store: Store.memory(),
}),
],
})
```
::::
## Use cases
Each use case sets one option of the `dpop` plugin, or the DPoP key of the instance itself.
### Keep the DPoP key in the app's store
The `store` option names where the DPoP key stays across runs. An instance with its own `store` passes the same store, so the DPoP key stays beside the session, such as for a CLI.
```ts [tempo.config.ts]
import { Accounts, Store } from 'accounts'
import { device, dpop } from 'accounts/plugins'
// A file in the user's home directory, which only the user reads.
const store = Store.file('~/.acme/store.json')
export const accounts = Accounts.create({
chain: 'testnet',
clientId: 'cli:acme-example',
plugins: [
device({
onCode: (code) =>
console.log(
`Open ${code.verificationUriComplete} and confirm the code ${code.userCode}.`,
),
}),
await dpop({ store }), // [!code hl]
],
store, // [!code hl]
})
```
:::warning
In a browser, the store must keep a `CryptoKey` as it is, as IndexedDB and `Store.memory` do. Outside a browser, `Store.file` keeps the private key as a JWK, beside the refresh token, so the next run of a CLI refreshes its session. Two first runs on one file at once keep one DPoP key, since `dpop` creates it under the file's lock. A shared store, such as `Store.postgres` or `Store.redis` , keeps no private key, so a session that another process's DPoP key binds never refreshes there.
:::
Outside a browser, the wagmi connector's `reconnect` skips such a session, and its `connect` signs in again.
### Set the DPoP key of the instance
The instance's `dpop` sets the DPoP key directly, and wins over the plugin's. A DPoP key of `Dpop.create` lasts as long as the process, so a session that it binds refreshes only in that process.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { Dpop } from 'accounts/internal'
export const accounts = Accounts.create({
chain: 'testnet',
dpop: await Dpop.create(), // [!code hl]
})
```
## Next steps
# Sign challenges \[A Tempo Account signs a challenge of a server at sign-in, and the server verifies it.]
## Overview
A server that acts for an address, such as a credit to it, needs proof that the user controls it. The server issues a one-time challenge, the Tempo Account signs it at sign-in, and the server spends it and verifies the signature.
The demo signs a challenge of the site's server in Tempo ID's dialog. The server returns the proven address, then refuses the same proof.
## Walkthrough
The steps build a React page and a Hono server.
```mermaid
sequenceDiagram
participant Server as App's server
participant Page as App's page
participant ID as Tempo ID
Server-->>Page: Challenge
Page->>ID: Sign-in with the challenge
ID-->>Page: Account and signature
Page->>Server: Account, challenge, and signature
Note over Server: Spend the challenge, then verify the signature
```
::::steps
### Install the packages
:::code-group
```sh [npm]
npm install accounts hono react react-dom viem
```
```sh [pnpm]
pnpm add accounts hono react react-dom viem
```
```sh [bun]
bun add accounts hono react react-dom viem
```
:::
### Issue the challenge
Issue a message, and keep it in a store until it expires. Tempo ID's dialog shows the message to the user before the signature.
* Name the app's host, so the signature serves no other server.
* Add a random value, so no two challenges are equal.
* Use plain text, with newlines. Tempo ID refuses control and format characters, such as a bidi override.
```ts [api.ts]
import { Store } from 'accounts'
import { Hono } from 'hono'
const app = new Hono()
const challenges = Store.memory()
app.post('/api/challenge', async (c) => {
const { host } = new URL(c.req.url)
const challenge = [
`${host} asks for a proof of your Tempo Account.`,
`Nonce: ${crypto.randomUUID()}`,
].join('\n')
// The challenge lasts 5 minutes.
const expiresAt = Date.now() + 5 * 60 * 1000
await challenges.setItem(challenge, true, { expiresAt })
return c.json({ challenge })
})
export default app
```
:::note
`Store.memory` keeps the challenges in the process, so a restart loses them. In production, use a store that each replica shares, such as `Store.postgres` or `Store.redis` . Both take a challenge in one atomic step, so servers that share one spend each challenge once.
:::
### Create the instance
The page's origin is its client ID, so the app needs no registration.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
export const accounts = Accounts.create({ chain: 'testnet' })
```
### Sign in with the challenge
Pass the challenge as `challenge` of `dialog.signIn` , with `accessKey` set to false. Tempo ID's dialog shows it, and the account's owner signs its EIP-191 hash, as `personal_sign` does. With an access key, the key authorization signs it instead, as [Bind challenges](/docs/guides/access-keys/bind-challenges) describes.
The sign-ins of other plugins take a challenge too, such as `redirect.signIn` and `device.signIn` .
:::code-group
```tsx [App.tsx]
import { accounts } from './tempo.config.js'
export function App() {
return (
{
const issued = await fetch('/api/challenge', { method: 'POST' })
const { challenge } = await issued.json()
// [!code hl:start]
const session = await accounts.dialog.signIn({
accessKey: false,
challenge,
})
// [!code hl:end]
}}
type="button"
>
Sign in with Tempo
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
export const accounts = Accounts.create({ chain: 'testnet' })
```
:::
The session holds the account as `address` , and the signature as `challengeSignature` .
### Send the proof
Send the account, the challenge, and the signature to the server, with no token.
:::code-group
```tsx [App.tsx]
import { useState } from 'react' // [!code ++]
import { accounts } from './tempo.config.js'
export function App() {
const [proven, setProven] = useState() // [!code ++]
if (proven) return The server verified {proven}.
// [!code ++]
return (
{
const issued = await fetch('/api/challenge', { method: 'POST' })
const { challenge } = await issued.json()
const session = await accounts.dialog.signIn({
accessKey: false,
challenge,
})
const response = await fetch('/api/verify', { // [!code ++]
body: JSON.stringify({ // [!code ++]
address: session.address, // [!code ++]
challenge, // [!code ++]
signature: session.challengeSignature, // [!code ++]
}), // [!code ++]
headers: { 'content-type': 'application/json' }, // [!code ++]
method: 'POST', // [!code ++]
}) // [!code ++]
const { address } = await response.json() // [!code ++]
setProven(address) // [!code ++]
}}
type="button"
>
Sign in with Tempo
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
export const accounts = Accounts.create({ chain: 'testnet' })
```
:::
### Spend the challenge
The chain does not spend a challenge, so a copied signature verifies again. Take the challenge from the store with `takeItem` before the signature check, so the server refuses an unknown or spent challenge.
```ts [api.ts]
import { Store } from 'accounts'
import { Hono } from 'hono'
import { isAddress, isHex } from 'viem'
const app = new Hono()
const challenges = Store.memory()
app.post('/api/challenge', async (c) => {
const { host } = new URL(c.req.url)
const challenge = [
`${host} asks for a proof of your Tempo Account.`,
`Nonce: ${crypto.randomUUID()}`,
].join('\n')
// The challenge lasts 5 minutes.
const expiresAt = Date.now() + 5 * 60 * 1000
await challenges.setItem(challenge, true, { expiresAt })
return c.json({ challenge })
})
app.post('/api/verify', async (c) => {
const { address, challenge, signature } = await c.req.json()
if (
!isAddress(address) ||
typeof challenge !== 'string' ||
!isHex(signature)
)
return c.json({ error: 'invalid_request' }, 400)
// `takeItem` reads and deletes in one step, so one request spends it.
// [!code hl:start]
if (!(await challenges.takeItem?.(challenge)))
return c.json({ error: 'invalid_challenge' }, 400)
// [!code hl:end]
return c.json({})
})
export default app
```
### Verify the signature
Viem's `verifyMessage` counts the account owner's signature on the instance's chain, and refuses an access key's.
```ts [api.ts]
import { Store } from 'accounts'
import { Hono } from 'hono'
import { isAddress, isHex } from 'viem' // [!code --]
import { createClient, http, isAddress, isHex } from 'viem' // [!code ++]
import { verifyMessage } from 'viem/actions' // [!code ++]
import { tempoTestnet } from 'viem/chains' // [!code ++]
const app = new Hono()
const challenges = Store.memory()
const client = createClient({ chain: tempoTestnet, transport: http() }) // [!code ++]
app.post('/api/challenge', async (c) => {
const { host } = new URL(c.req.url)
const challenge = [
`${host} asks for a proof of your Tempo Account.`,
`Nonce: ${crypto.randomUUID()}`,
].join('\n')
// The challenge lasts 5 minutes.
const expiresAt = Date.now() + 5 * 60 * 1000
await challenges.setItem(challenge, true, { expiresAt })
return c.json({ challenge })
})
app.post('/api/verify', async (c) => {
const { address, challenge, signature } = await c.req.json()
if (
!isAddress(address) ||
typeof challenge !== 'string' ||
!isHex(signature)
)
return c.json({ error: 'invalid_request' }, 400)
// `takeItem` reads and deletes in one step, so one request spends it.
if (!(await challenges.takeItem?.(challenge)))
return c.json({ error: 'invalid_challenge' }, 400)
const valid = await verifyMessage(client, { // [!code ++]
address, // [!code ++]
message: challenge, // [!code ++]
signature, // [!code ++]
}) // [!code ++]
if (!valid) return c.json({ error: 'invalid_signature' }, 400) // [!code ++]
// The user controls `address`. // [!code ++]
return c.json({ address }) // [!code ++]
})
export default app
```
::::
## Use cases
Each use case sets the `challenge` of `dialog.signIn` in another form, or beside another option.
### Fetch the challenge in the dialog
A function as `challenge` returns the challenge after the dialog opens. The call then comes before any `await` of the click handler, as the dialog's popup fallback needs. Its signal aborts once the call ends.
:::code-group
```tsx [App.tsx]
import { accounts } from './tempo.config.js'
export function App() {
async function signIn() {
let challenge = ''
const session = await accounts.dialog.signIn({
accessKey: false,
// [!code hl:start]
challenge: async (signal) => {
const issued = await fetch('/api/challenge', { method: 'POST', signal })
challenge = ((await issued.json()) as { challenge: string }).challenge
return challenge
},
// [!code hl:end]
})
await fetch('/api/verify', {
body: JSON.stringify({
address: session.address,
challenge,
signature: session.challengeSignature,
}),
headers: { 'content-type': 'application/json' },
method: 'POST',
})
}
return (
void signIn()} type="button">
Sign in with Tempo
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
export const accounts = Accounts.create({ chain: 'testnet' })
```
:::
### Bind the challenge to an access key
With an `accessKey` request, the key authorization of the access key binds the challenge, and `challengeSignature` is its signature. Viem's `verifyMessage` refuses such a signature, so the server verifies it as [Bind challenges](/docs/guides/access-keys/bind-challenges) shows.
:::code-group
```tsx [App.tsx]
import { accounts } from './tempo.config.js'
export function App() {
return (
accounts.dialog.signIn({
// [!code hl:start]
accessKey: {
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
},
// [!code hl:end]
challenge: async (signal) => {
const issued = await fetch('/api/challenge', {
method: 'POST',
signal,
})
return ((await issued.json()) as { challenge: string }).challenge
},
})
}
type="button"
>
Sign in with Tempo
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
export const accounts = Accounts.create({ chain: 'testnet' })
```
:::
## Next steps
# Verify signed messages \[A server verifies a message that the access key signs for a Tempo Account.]
## Overview
After a sign-in, the [access key](/docs/guides/access-keys) signs messages for the Tempo Account with no prompt. The chain accepts every live access key of the account, also another app's, so a server counts the signature only if the user's [access token](/docs/guides/api-authentication/authenticate-requests) names the access key. A signature verifies only after the access key's first transaction registers it.
The demo signs in, sends 0.01 OUSD as the access key's first transaction, and signs a message, which the site's server verifies. Before the transaction, the server refuses the signature.
## Walkthrough
The steps build a React page and a Hono server.
::::steps
### Install the packages
:::code-group
```sh [npm]
npm install accounts hono react react-dom viem
```
```sh [pnpm]
pnpm add accounts hono react react-dom viem
```
```sh [bun]
bun add accounts hono react react-dom viem
```
:::
### Create the instance
The `react` plugin adds `useSession` , and the `viem` plugin adds `signMessage`.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [react(), viem()],
})
```
### Sign the user in
The session's `accessKey.account` is the Tempo Account that the access key signs for.
:::code-group
```tsx [App.tsx]
import { accounts } from './tempo.config.js'
export function App() {
const { session } = accounts.useSession()
const address = session?.accessKey?.account // [!code hl]
if (!address)
return (
accounts.dialog.signIn()} type="button">
Sign in with Tempo
)
return (
Tempo Account {address}
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [react(), viem()],
})
```
:::
### Send the first transaction
The first transaction carries the key authorization, and registers the access key on the chain.
:::code-group
```tsx [App.tsx]
import { accounts } from './tempo.config.js'
export function App() {
const { session } = accounts.useSession()
const address = session?.accessKey?.account
if (!address)
return (
accounts.dialog.signIn()} type="button">
Sign in with Tempo
)
return (
Tempo Account {address}
// [!code ++]
accounts.pay({ // [!code ++]
amount: '0.01', // [!code ++]
to: '0x000000000000000000000000000000000000dEaD', // [!code ++]
token: 'ousd', // [!code ++]
}) // [!code ++]
} // [!code ++]
type="button" // [!code ++]
> {/* [!code ++] */}
Send 0.01 OUSD {/* [!code ++] */}
{/* [!code ++] */}
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [react(), viem()],
})
```
:::
### Sign the message
:::code-group
```tsx [App.tsx]
import { accounts } from './tempo.config.js'
const message = 'I agree to the terms of app.example.' // [!code ++]
export function App() {
const { session } = accounts.useSession()
const address = session?.accessKey?.account
if (!address)
return (
accounts.dialog.signIn()} type="button">
Sign in with Tempo
)
return (
Tempo Account {address}
accounts.pay({
amount: '0.01',
to: '0x000000000000000000000000000000000000dEaD',
token: 'ousd',
})
}
type="button"
>
Send 0.01 OUSD
{ // [!code ++]
const signature = await accounts.signMessage({ message }) // [!code ++]
}} // [!code ++]
type="button" // [!code ++]
> {/* [!code ++] */}
Prove the account {/* [!code ++] */}
{/* [!code ++] */}
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [react(), viem()],
})
```
:::
### Send the signature
`session.fetch` sends the signature with the session's access token.
:::code-group
```tsx [App.tsx]
import { useState } from 'react' // [!code ++]
import { accounts } from './tempo.config.js'
const message = 'I agree to the terms of app.example.'
export function App() {
const { session } = accounts.useSession()
const [proven, setProven] = useState() // [!code ++]
const address = session?.accessKey?.account
if (!address)
return (
accounts.dialog.signIn()} type="button">
Sign in with Tempo
)
return (
Tempo Account {address}
accounts.pay({
amount: '0.01',
to: '0x000000000000000000000000000000000000dEaD',
token: 'ousd',
})
}
type="button"
>
Send 0.01 OUSD
{
const signature = await accounts.signMessage({ message })
const response = await accounts.session.fetch({ // [!code ++]
init: { // [!code ++]
body: JSON.stringify({ address, message, signature }), // [!code ++]
headers: { 'content-type': 'application/json' }, // [!code ++]
method: 'POST', // [!code ++]
}, // [!code ++]
url: '/api/message', // [!code ++]
}) // [!code ++]
const body = await response.json() // [!code ++]
setProven(body.address) // [!code ++]
}}
type="button"
>
Prove the account
{proven && The server verified {proven}.
} {/* [!code ++] */}
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [react(), viem()],
})
```
:::
### Create the instance of the server
Name the app's `clientId` , so the instance accepts only the app's access tokens.
```ts [api.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
const accounts = Accounts.create({
chain: 'testnet',
clientId: 'https://app.example',
plugins: [viem()],
})
```
:::warning
Another app's access token names that app's access keys. A server that accepts it accepts that app's signatures.
:::
### Verify the signature
`verifyMessage` verifies the access token, then the signature. An access key's signature counts only if the token names it for the address, on the instance's chain. The owner's signature also counts.
```ts [api.ts]
import { AccessToken, Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { Hono } from 'hono'
import { isAddress, isHex } from 'viem'
const accounts = Accounts.create({
chain: 'testnet',
clientId: 'https://app.example',
plugins: [viem()],
})
const app = new Hono()
app.post('/api/message', async (c) => {
const [, accessToken] = c.req.header('authorization')?.split(' ') ?? []
if (!accessToken) return c.json({ error: 'invalid_token' }, 401)
const { address, message, signature } = await c.req.json()
if (
!isAddress(address) ||
typeof message !== 'string' ||
!isHex(signature)
)
return c.json({ error: 'invalid_request' }, 400)
try {
// [!code hl:start]
const valid = await accounts.verifyMessage({
accessToken,
address,
message,
signature,
})
// [!code hl:end]
if (!valid) return c.json({ error: 'invalid_signature' }, 400)
} catch (error) {
if (error instanceof AccessToken.InvalidError)
return c.json({ error: 'invalid_token' }, 401)
throw error
}
// The access key of the app signed `message` for `address`.
return c.json({ address })
})
export default app
```
A signature verifies each time. If a message counts once, add a server challenge to it, and [spend the challenge](/docs/guides/account-proof/sign-challenges#spend-the-challenge).
::::
## Use cases
Each use case sets one option of `verifyMessage` or of the `viem` plugin, or verifies another kind of signature.
### Verify a DPoP token
If a [DPoP key](/docs/guides/api-authentication/bind-dpop-keys) binds the access token, pass the request's proof as `dpop` . `verifyMessage` refuses no repeated proof, so the API refuses one with `tokens.verifyAccessToken` , as [Bind DPoP keys](/docs/guides/api-authentication/bind-dpop-keys#refuse-a-repeated-proof) shows.
```ts [api.ts]
import { AccessToken, Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import { Hono } from 'hono'
import { isAddress, isHex } from 'viem'
const accounts = Accounts.create({
chain: 'testnet',
clientId: 'https://app.example',
plugins: [viem()],
})
const app = new Hono()
app.post('/api/message', async (c) => {
const [scheme, accessToken] = c.req.header('authorization')?.split(' ') ?? [] // [!code hl]
if (!accessToken) return c.json({ error: 'invalid_token' }, 401)
const { address, message, signature } = await c.req.json()
if (
!isAddress(address) ||
typeof message !== 'string' ||
!isHex(signature)
)
return c.json({ error: 'invalid_request' }, 400)
try {
const valid = await accounts.verifyMessage({
accessToken,
address,
// [!code hl:start]
dpop: {
method: c.req.method,
proof: c.req.header('dpop'),
scheme,
url: c.req.url,
},
// [!code hl:end]
message,
signature,
})
if (!valid) return c.json({ error: 'invalid_signature' }, 400)
} catch (error) {
if (error instanceof AccessToken.InvalidError)
return c.json({ error: 'invalid_token' }, 401)
throw error
}
return c.json({ address })
})
export default app
```
### Verify typed data
`accounts.signTypedData` signs typed data (EIP-712) with the access key. `accounts.verifyTypedData` verifies it with the same `accessToken` .
```ts [api.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
import type { Address, Hex } from 'viem'
const accounts = Accounts.create({
chain: 'testnet',
clientId: 'https://app.example',
plugins: [viem()],
})
export async function verify(options: {
accessToken: string
address: Address
signature: Hex
}) {
// [!code hl:start]
return await accounts.verifyTypedData({
accessToken: options.accessToken,
address: options.address,
domain: { name: 'app.example', version: '1' },
message: { terms: 'I agree to the terms of app.example.' },
primaryType: 'Agreement',
signature: options.signature,
types: { Agreement: [{ name: 'terms', type: 'string' }] },
})
// [!code hl:end]
}
```
### Verify a hash
`accounts.verifyHash` verifies a signature of a 32-byte hash, such as one that the app computed itself. An access key's signature counts as `verifyMessage` decides.
```ts [api.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
const accounts = Accounts.create({
chain: 'testnet',
clientId: 'https://app.example',
plugins: [viem()],
})
export async function verify(
options: Parameters[0],
) {
return await accounts.verifyHash(options) // [!code hl]
}
```
### Accept the tokens of several apps
The `accessTokens` option of the plugin takes the options of the access token's verifier, as the `tokens` plugin does. With `clientIds` , a server counts the access keys of each named app.
```ts [api.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
const accounts = Accounts.create({
chain: 'testnet',
clientId: 'https://app.example',
plugins: [
viem({
// [!code hl:start]
accessTokens: {
clientIds: ['https://app.example', 'https://admin.example'],
},
// [!code hl:end]
}),
],
})
```
## Next steps
# End app sessions \[An app signs the user out. A second call revokes the session's access key.]
## Overview
`accounts.signOut()` ends the app's [session](/docs/guides/user-session), and revokes its refresh token (RFC 7009). The user's Tempo ID session stays, so other apps stay signed in. The [access token](/docs/guides/api-authentication/authenticate-requests) and the [access key](/docs/guides/access-keys) outlive the sign-out, since APIs verify the token on their own, and the chain holds the access key\:
| Part of the session | After `signOut` |
| ------------------- | ------------------------------------------------------------------------------ |
| Session of the app | Empty at once. The saved session is deleted |
| Refresh token | Revoked at Tempo ID |
| Access token | Valid until it expires, at most 5 minutes later |
| Access key | Valid until its expiry, unless the app revokes it |
| Tempo ID session | Stays. The next sign-in asks for no email address |
The demo signs a user in and out of the app, and shows the session's status after each step.
## Walkthrough
The [`web`](https\://github.com/tempoxyz/accounts/tree/main/examples/web) example runs these steps in a React app.
::::steps
### Create the instance
The `react` plugin adds the `useSession` hook.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [react()],
})
```
### Render the status
`useSession` returns the session and its status, such as `pending` before the restore ends, and renders again at each change.
Outside React, `session.status` holds the same status, and its listener receives the new status and the previous one.
:::code-group
```tsx [App.tsx]
import { accounts } from './tempo.config.js'
export function App() {
const { session, status } = accounts.useSession() // [!code hl]
if (status === 'pending') return Checking the session…
// [!code hl]
if (!session)
return (
void accounts.dialog.signIn()} type="button">
Sign in with Tempo
)
return Signed in as {session.user.email}
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [react()],
})
```
:::
### Sign the user out
`signOut` empties the session at once, also when the revocation fails.
:::code-group
```tsx [App.tsx]
import { accounts } from './tempo.config.js'
export function App() {
const { session, status } = accounts.useSession()
if (status === 'pending') return Checking the session…
if (!session)
return (
void accounts.dialog.signIn()} type="button">
Sign in with Tempo
)
return Signed in as {session.user.email}
// [!code --]
return ( // [!code ++]
{/* [!code ++] */}
Signed in as {session.user.email}
{/* [!code ++] */}
void accounts.signOut()} type="button"> {/* [!code ++] */}
Sign out {/* [!code ++] */}
{/* [!code ++] */}
// [!code ++]
) // [!code ++]
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [react()],
})
```
:::
The instance saves a signed-out mark, so a reload restores no session until the next sign-in.
If Tempo ID does not answer the revocation, such as offline, `signOut` rejects with `server_error` and status 0, but the session is empty. The store keeps the refresh token for the next `signOut` to revoke.
:::warning
If the app deletes the saved session in place of `signOut` , the refresh token stays valid until the end of the app's [refresh token lifetime](https\://github.com/tempoxyz/id/blob/main/docs/access-tokens.md#refresh-token-lifetime).
:::
### Revoke the access key
A sign-out leaves the access key valid on the chain. To revoke it, call `dialog.revokeAccessKey` before `signOut` , in a click handler, since a popup opens only within the gesture. The account owner signs the revocation on Tempo ID's approval page, because the chain refuses keychain changes from an access key.
:::code-group
```tsx [SignOut.tsx]
import { accounts } from './tempo.config.js'
export function SignOut() {
async function signOut() {
const { session } = accounts.session.status.get()
if (session?.accessKey) await accounts.dialog.revokeAccessKey() // [!code hl]
await accounts.signOut()
}
return (
Sign out
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
// Each sign-in requests an access key that sends up to 100 OUSD for a day.
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
}),
chain: 'testnet',
plugins: [react()],
})
```
:::
It returns the revoking transaction's hash, or `null` for an access key revoked already. A Cancel throws `Accounts.RequestError` with `access_denied`, and the session stays.
With the `viem` plugin, `accessKey.revokeSync` revokes the session's own access key with no page, for any sign-in plugin. It sends the session's access token, and Tempo ID's cloud wallet signs as the owner.
The session then keeps the access key without its private key. A transaction before the sign-out thus throws `Accounts.AccessKeyRequiredError` , and on a page a transfer opens Tempo ID's payment page.
An account that only a passkey owns throws `Accounts.RequestError` with `webauthn_required`. Revoke its access key in the dialog.
::::
## Use cases
The use case sets the only option of `signOut` .
### Sign out of every app
`everywhere` also ends the user's Tempo ID session, which signs the user out of every app. Only a first-party app may set it, as [End all sessions](/docs/guides/sign-out/end-all-sessions) shows.
:::code-group
```tsx [SignOut.tsx]
import { accounts } from './tempo.config.js'
export function SignOut() {
return (
accounts.signOut({ everywhere: true })} // [!code hl]
type="button"
>
Sign out of every app
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
export const accounts = Accounts.create({
chain: 'testnet',
clientId: 'example-app',
})
```
:::
## Next steps
# End all sessions \[A first-party app ends the user's Tempo ID session, which signs the user out of every app.]
## Overview
The user's Tempo ID session in the browser signs the user in to every app, as single sign-on. `accounts.signOut({ everywhere: true })` ends the app's [session](/docs/guides/user-session) and that Tempo ID session.
Tempo ID revokes every app's tokens on it, and the next sign-in asks for the user again. Only a first-party app may do this, since it signs the user out of every app\:
| App | Call |
| ---------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| First-party app, which the Admin API registers | `accounts.signOut({ everywhere: true })` |
| App with post-logout redirect URIs | [RP-initiated logout](/docs/guides/sign-out/end-all-sessions#end-the-tempo-id-session-with-the-id-token) |
| Any other app | None. `everywhere` throws `Accounts.EverywhereNotAllowedError` |
The demo's client ID is this page's origin, so the instance refuses its sign-out of every app, and the demo signs out of the app only.
## Walkthrough
These steps change the sign-out of the [`web`](https\://github.com/tempoxyz/accounts/tree/main/examples/web) example for a first-party app.
::::steps
### Create the instance
Pass the first-party app's `clientId` . Tempo ID accepts the logout only from an origin of the app's registration.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
export const accounts = Accounts.create({
chain: 'testnet',
clientId: 'example-app',
})
```
### Sign the user out of every app
`everywhere` revokes the app's refresh token, then ends the Tempo ID session with `POST /v1/auth/logout`.
:::code-group
```tsx [SignOut.tsx]
import { accounts } from './tempo.config.js'
export function SignOut() {
async function signOut() {
await accounts.signOut({ everywhere: true }) // [!code hl]
}
return (
Sign out of every app
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
export const accounts = Accounts.create({
chain: 'testnet',
clientId: 'example-app',
})
```
:::
A Tempo ID session of the user in another browser stays.
### Handle the refusal
From any other app, `everywhere` throws `Accounts.EverywhereNotAllowedError` before any request. Sign out of the app in its place.
:::code-group
```tsx [SignOut.tsx]
import { Accounts } from 'accounts' // [!code ++]
import { accounts } from './tempo.config.js'
export function SignOut() {
async function signOut() {
await accounts.signOut({ everywhere: true }) // [!code --]
await accounts.signOut({ everywhere: true }).catch((error: unknown) => { // [!code ++]
if (!(error instanceof Accounts.EverywhereNotAllowedError)) throw error // [!code ++]
return accounts.signOut() // [!code ++]
}) // [!code ++]
}
return (
Sign out of every app
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
export const accounts = Accounts.create({
chain: 'testnet',
clientId: 'example-app',
})
```
:::
::::
## Use cases
Each use case ends the Tempo ID session where `everywhere` does not apply, beside `signOut` .
### End the Tempo ID session with the ID token
An app with registered post-logout redirect URIs uses OpenID Connect RP-Initiated Logout, which no action of the package runs. Read the `idToken` of the session for `id_token_hint` before `signOut` empties the session.
:::code-group
```tsx [SignOut.tsx]
import { accounts } from './tempo.config.js'
export function SignOut() {
async function signOut() {
const session = await accounts.session.get() // [!code hl]
const idToken = session?.idToken // [!code hl]
await accounts.signOut()
// [!code hl:start]
if (idToken) {
const url = new URL('/oauth2/end-session', accounts.config.url)
url.searchParams.set('id_token_hint', idToken)
url.searchParams.set('post_logout_redirect_uri', 'https://app.example/')
location.assign(url)
}
// [!code hl:end]
}
return (
Sign out of every app
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
export const accounts = Accounts.create({
chain: 'testnet',
clientId: 'example-app',
})
```
:::
Tempo ID ends the hinted session if the browser holds it, then redirects to `post_logout_redirect_uri`. Other apps receive 403 [`logout_not_permitted`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#logout_not_permitted). A refresh can omit the ID token, so a session can hold none.
### Sign out of a native app
With the `redirect` plugin and `open` , a native app signs in through the system browser, whose Tempo ID session `everywhere` does not end, since the logout sends the app's cookies. After `signOut` , the next `signIn` asks Tempo ID for a new login, so Tempo ID shows its sign-in page.
:::code-group
```tsx [SignOut.tsx]
import { Button } from 'react-native'
import { accounts } from './tempo.config.js'
export function SignOut() {
return accounts.signOut()} title="Sign out" /> // [!code hl]
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { expo } from 'accounts/expo'
export const accounts = Accounts.create({
chain: 'testnet',
// The client ID of the app's registration.
clientId: 'example-mobile',
plugins: [expo({ redirectUri: 'com.example.app:/callback' })],
})
```
:::
## Next steps
# End backend sessions \[A backend ends the session that it holds for a user, and refuses that session's cookie.]
## Overview
With the `backend` plugin, the server's store holds each [session](/docs/guides/user-session), and the browser holds only its ID, in an HttpOnly session cookie. The logout route of `accounts.handler` ends each part\:
| Part | After the logout route |
| ------------- | ------------------------------------------------------- |
| Refresh token | Revoked at Tempo ID |
| Session | Deleted from the store, with its tokens and access key |
| Cookie | Deleted. A request with the old cookie reads no session |
The user's Tempo ID session in the browser stays, as after an [app sign-out](/docs/guides/sign-out/end-app-sessions).
The demo signs a user in on this site's server, posts to the logout route, and then receives 401 from a route that needs the session.
## Walkthrough
The [`backend`](https\://github.com/tempoxyz/accounts/tree/main/examples/backend) example runs these steps.
::::steps
### Serve the logout route
`accounts.handler` of an instance with the `backend` plugin serves `POST /api/auth/logout` beside the sign-in routes.
:::code-group
```ts [server.ts]
import { Hono } from 'hono'
import { accounts } from './tempo.config.js'
const app = new Hono()
app.all('/api/*', (c) => accounts.handler.fetch(c.req.raw)) // [!code hl]
export default app
```
```ts [tempo.config.ts]
import { Accounts, Store } from 'accounts'
import { backend } from 'accounts/plugins'
export const accounts = Accounts.create({
chain: 'testnet',
clientId: process.env.APP_URL,
plugins: [backend({ store: Store.memory() })],
})
```
:::
:::note
`Store.memory` keeps the sessions in the process, so a restart loses them. In production, use a store that each replica shares, such as `Store.postgres` or `Store.redis` .
:::
### Post to the logout route
The route answers 204. It answers 403 to a request from another origin, since a cross-site form post also sends the cookie. If the revocation or the store fails, it answers 503, and still deletes the cookie.
```html
Sign out
```
### Refuse a request without a session
`session.get` returns `undefined` without a cookie, or for an ended session's cookie.
:::code-group
```ts [server.ts]
import { Hono } from 'hono'
import { accounts } from './tempo.config.js'
const app = new Hono()
app.all('/api/*', (c) => accounts.handler.fetch(c.req.raw))
app.get('/profile', async (c) => {
const session = await accounts.session.get(c.req.raw) // [!code hl]
if (session?.method !== 'tempo-id')
return c.json({ error: 'signed_out' }, 401) // [!code hl]
return c.json({ email: session.user.email })
})
export default app
```
```ts [tempo.config.ts]
import { Accounts, Store } from 'accounts'
import { backend } from 'accounts/plugins'
export const accounts = Accounts.create({
chain: 'testnet',
clientId: process.env.APP_URL,
plugins: [backend({ store: Store.memory() })],
})
```
:::
::::
## Use cases
Each use case ends a session with another route or member of the `backend` plugin, or sets one of its options.
### End a session in a route of the app
A backend with its own sign-in routes calls `backend.end` with its cookie's session ID, and deletes the cookie. With `revoke: false` , it deletes a session that Tempo ID ended already, with no request.
:::code-group
```ts [server.ts]
import { Hono } from 'hono'
import { deleteCookie, getCookie } from 'hono/cookie'
import { accounts } from './tempo.config.js'
const app = new Hono()
app.post('/auth/sign-out', async (c) => {
const id = getCookie(c, 'session')
if (id) await accounts.backend.end({ id }) // [!code hl]
deleteCookie(c, 'session')
return c.body(null, 204)
})
export default app
```
```ts [tempo.config.ts]
import { Accounts, Store } from 'accounts'
import { backend } from 'accounts/plugins'
export const accounts = Accounts.create({
chain: 'testnet',
clientId: process.env.APP_URL,
plugins: [backend({ store: Store.memory() })],
})
```
:::
### Disconnect the app
`backend.disconnect` ends the connection of the app and the session's user at Tempo ID. It then deletes the session without a revocation.
:::code-group
```ts [server.ts]
import { Hono } from 'hono'
import { deleteCookie, getCookie } from 'hono/cookie'
import { csrf } from 'hono/csrf'
import { accounts } from './tempo.config.js'
const app = new Hono()
// The browser sends the cookie with a form post of another site, so the route checks the origin.
app.use(csrf())
app.post('/auth/disconnect', async (c) => {
const id = getCookie(c, 'session')
if (id) await accounts.backend.disconnect({ id }) // [!code hl]
deleteCookie(c, 'session')
return c.body(null, 204)
})
export default app
```
```ts [tempo.config.ts]
import { Accounts, Store } from 'accounts'
import { backend } from 'accounts/plugins'
export const accounts = Accounts.create({
chain: 'testnet',
clientId: process.env.APP_URL,
plugins: [backend({ store: Store.memory() })],
})
```
:::
### End a session after a logout token
If a Tempo ID session ends, such as at a sign-out of every app, Tempo ID posts a logout token (OpenID Connect Back-Channel Logout) to each registered app. The back-channel logout route of `accounts.handler` verifies it, and ends each session of the token's Tempo ID session.
:::code-group
```ts [server.ts]
import { Hono } from 'hono'
import { csrf } from 'hono/csrf'
import { accounts } from './tempo.config.js'
const app = new Hono()
// Tempo ID posts the token with no Origin header, so the route comes before the CSRF middleware.
app.post('/api/auth/backchannel-logout', (c) => accounts.handler.fetch(c.req.raw)) // [!code hl]
app.use(csrf())
app.all('/api/*', (c) => accounts.handler.fetch(c.req.raw))
export default app
```
```ts [tempo.config.ts]
import { Accounts, Store } from 'accounts'
import { backend } from 'accounts/plugins'
export const accounts = Accounts.create({
chain: 'testnet',
clientId: process.env.APP_URL,
plugins: [backend({ store: Store.memory() })],
})
```
:::
Register the route's URL, such as `https://app.example/api/auth/backchannel-logout`, as the app's back-channel logout URI, with the session required. Tempo ID revoked the refresh tokens already, so the route ends each session without a revocation. A second revocation reads as a reuse, which revokes the user's other sessions at the app.
The route ends only the sessions that Tempo ID issued no later than the token. The `backend` plugin indexes each session by its Tempo ID session at the sign-in. The index keeps a session that fails to end, so the retry of the token ends it.
A session from a release before the index has no entry, so it ends at its next refresh. A sign-in of the same Tempo ID session that finishes after the token ends at once. The exception is a sign-in whose tokens Tempo ID issued after the token, such as a sign-in again after the app's disconnection.
The route answers a body above 64 KiB with 413, and stops reading it at the chunk that crosses 64 KiB.
### Verify a logout token in a route of the app
A backend with routes of its own calls `backend.logout` with the token of the form body. It throws `LogoutToken.InvalidError` for a token that does not verify.
:::code-group
```ts [server.ts]
import { LogoutToken } from 'accounts'
import { Hono } from 'hono'
import { accounts } from './tempo.config.js'
const app = new Hono()
app.post('/auth/logout-token', async (c) => {
const form = await c.req.formData()
// [!code hl:start]
const ended = await accounts.backend
.logout({ logoutToken: String(form.get('logout_token')) })
.catch((error: unknown) => {
if (error instanceof LogoutToken.InvalidError) return undefined
throw error
})
// [!code hl:end]
if (!ended) return c.body(null, 400)
return c.body(null, 200)
})
export default app
```
```ts [tempo.config.ts]
import { Accounts, Store } from 'accounts'
import { backend } from 'accounts/plugins'
export const accounts = Accounts.create({
chain: 'testnet',
clientId: process.env.APP_URL,
plugins: [backend({ store: Store.memory() })],
})
```
:::
### Reach Tempo ID at an internal address
`logoutToken` takes the options of the logout token's verifier. If the instance's `url` reaches Tempo ID at another address, its `issuer` names Tempo ID's public origin.
```ts [tempo.config.ts]
import { Accounts, Store } from 'accounts'
import { backend } from 'accounts/plugins'
export const accounts = Accounts.create({
chain: 'testnet',
clientId: process.env.APP_URL,
plugins: [
backend({
logoutToken: { issuer: 'https://id.tempo.xyz' }, // [!code hl]
store: Store.memory(),
}),
],
url: 'http://tempo-id.internal',
})
```
## Next steps
# Plugins \[A plugin adds a namespace of actions to the instance, and runs code at the instance's sign-in and sign-out.]
## Overview
Each sign-in method and each set of actions of the package is a plugin, such as `dialog` and `viem`. An app writes a plugin of its own with `Plugin.from` , as the built-in plugins do. Its actions share the instance's configuration and [session](/docs/guides/user-session), and its hooks run at the instance's sign-in and sign-out.
The plugin's `id` names its namespace on the instance, such as `accounts.analytics`. The instance's type holds the namespace and each action, inferred from the plugin, so an app declares no types for it.
The demo adds an `analytics` plugin. Its action tracks an event of the signed-in user, and its hooks track each sign-in and sign-out.
## Walkthrough
These steps add an `analytics` plugin to a React app.
::::steps
### Install the packages
:::code-group
```sh [npm]
npm install accounts react react-dom viem
```
```sh [pnpm]
pnpm add accounts react react-dom viem
```
```sh [bun]
bun add accounts react react-dom viem
```
:::
### Define the plugin
A function takes the plugin's options and returns the plugin, as each built-in plugin does. `id` names the namespace. `actions` runs once at `Accounts.create` , and returns the namespace.
Each action reads the instance through the `context` that `actions` receives. `track` attaches the instance's chain and the signed-in user's ID to each event.
```ts [analytics.ts]
import { Plugin } from 'accounts'
export function analytics(options: analytics.Options) {
const { send } = options
return Plugin.from({
// [!code hl:start]
actions: (context) => ({
track: (name: string) =>
send({
chainId: context.chain.get(),
name,
userId: context.session.get()?.user?.id,
}),
}),
id: 'analytics',
// [!code hl:end]
})
}
export declare namespace analytics {
type Event = {
chainId: number
name: string
userId?: string | undefined
}
type Options = {
send: (event: Event) => void
}
}
```
If an `id` names a member of every instance, such as `session`, or the `id` of another plugin, `Accounts.create` throws. A plugin with the `id` of a sign-in plugin, such as `dialog`, replaces the default `dialog` plugin.
### Track sign-ins and sign-outs
`afterSignIn` runs after each change that sets a session, with the session. `afterSignOut` runs after each sign-out. Both also run after a sign-in or a sign-out in another tab, or in another instance on a store with `connect`, such as `Store.memory` in React Native or Node.
The sign-in waits for each `afterSignIn` hook, so the hook sends the event without an `await`.
```ts [analytics.ts]
import { Plugin } from 'accounts'
export function analytics(options: analytics.Options) {
const { send } = options
return Plugin.from({
actions: (context) => ({
track: (name: string) =>
send({
chainId: context.chain.get(),
name,
userId: context.session.get()?.user?.id,
}),
}),
// [!code hl:start]
hooks: {
afterSignIn: (context, session) =>
send({
chainId: context.chain.get(),
name: 'signIn',
userId: session.user?.id,
}),
afterSignOut: (context) =>
send({ chainId: context.chain.get(), name: 'signOut' }),
},
// [!code hl:end]
id: 'analytics',
})
}
export declare namespace analytics {
type Event = {
chainId: number
name: string
userId?: string | undefined
}
type Options = {
send: (event: Event) => void
}
}
```
### Add the plugin to the instance
`send` posts each event to the app's API with [`navigator.sendBeacon`](https\://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon), which returns before the request completes.
:::code-group
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
import { analytics } from './analytics.js'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [
react(),
// [!code hl:start]
analytics({
send: (event) => {
navigator.sendBeacon('/api/events', JSON.stringify(event))
},
}),
// [!code hl:end]
],
})
```
```ts [analytics.ts]
import { Plugin } from 'accounts'
export function analytics(options: analytics.Options) {
const { send } = options
return Plugin.from({
actions: (context) => ({
track: (name: string) =>
send({
chainId: context.chain.get(),
name,
userId: context.session.get()?.user?.id,
}),
}),
hooks: {
afterSignIn: (context, session) =>
send({
chainId: context.chain.get(),
name: 'signIn',
userId: session.user?.id,
}),
afterSignOut: (context) =>
send({ chainId: context.chain.get(), name: 'signOut' }),
},
id: 'analytics',
})
}
export declare namespace analytics {
type Event = {
chainId: number
name: string
userId?: string | undefined
}
type Options = {
send: (event: Event) => void
}
}
```
:::
### Call the action
The instance holds the plugin's namespace under its `id`, so `accounts.analytics.track` sends an event.
:::code-group
```tsx [App.tsx]
import { accounts } from './tempo.config.js'
export function App() {
const { session } = accounts.useSession()
if (!session)
return (
accounts.dialog.signIn()} type="button">
Sign in
)
return (
// [!code hl:start]
accounts.analytics.track('checkout.start')}
type="button"
>
Check out
// [!code hl:end]
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
import { analytics } from './analytics.js'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [
react(),
analytics({
send: (event) => {
navigator.sendBeacon('/api/events', JSON.stringify(event))
},
}),
],
})
```
:::
::::
## Use cases
Each use case sets an option of `Plugin.from` , or passes plugins to `Accounts.create` .
### Run code at creation
`setup` runs once at `Accounts.create`, after the plugin's `actions`. This plugin subscribes to the instance's chain with `context.chain.subscribe` , and tracks each `switchChain`.
```ts [chains.ts]
import { Plugin } from 'accounts'
export function chains(options: chains.Options) {
const { send } = options
return Plugin.from({
id: 'chains',
// [!code hl:start]
setup: (context) => {
context.chain.subscribe((chainId, previous) => send({ chainId, previous }))
},
// [!code hl:end]
})
}
export declare namespace chains {
type Options = {
send: (event: { chainId: number; previous: number }) => void
}
}
```
### Add members to the instance
`extend` adds members to the instance itself, beside its namespaces. It receives the instance, so a member calls the instance's own members, such as `session.fetch` . If a member's name is a member of the instance already, `Accounts.create` throws.
:::code-group
```ts [api.ts]
import { Plugin } from 'accounts'
export function api(options: api.Options) {
const { url } = options
return Plugin.from({
// [!code hl:start]
extend: (instance) => ({
api: (path: string) =>
instance.session.fetch({ url: new URL(path, url).href }),
}),
// [!code hl:end]
id: 'api',
})
}
export declare namespace api {
type Options = {
url: string
}
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { api } from './api.js'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [api({ url: 'https://api.example' })],
})
const response = await accounts.api('/me')
```
:::
### Set options of the instance
`config` returns options of `Accounts.create`, such as the `redirectUri` of a platform. The options that `Accounts.create` receives win over them, and a later plugin's options win over an earlier plugin's.
```ts [platform.ts]
import { Plugin } from 'accounts'
export function platform(options: platform.Options) {
const { redirectUri } = options
return Plugin.from({
config: () => ({ redirectUri }), // [!code hl]
id: 'platform',
})
}
export declare namespace platform {
type Options = {
redirectUri: string
}
}
```
### Combine plugins in a preset
An entry of `plugins` can be a list of plugins, such as the list that a preset returns. `Plugin.Option` types each entry. `Accounts.create` flattens each list in order, and the instance's type holds the namespace of each plugin.
:::code-group
```ts [preset.ts]
import { Plugin } from 'accounts'
import { redirect, viem } from 'accounts/plugins'
export function preset(options: preset.Options) {
const { redirectUri } = options
return [
Plugin.from({ config: () => ({ redirectUri }), id: 'preset' }),
redirect(),
viem(),
] satisfies readonly Plugin.Option[]
}
export declare namespace preset {
type Options = {
redirectUri: string
}
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { preset } from './preset.js'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [preset({ redirectUri: 'https://app.example/callback' })], // [!code hl]
})
```
:::
### Add a plugin conditionally
A falsy entry of `plugins` adds nothing, so `enabled && analytics()` adds the plugin only while `enabled` holds.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { analytics } from './analytics.js'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [
// [!code hl:start]
import.meta.env.PROD &&
analytics({
send: (event) => {
navigator.sendBeacon('/api/events', JSON.stringify(event))
},
}),
// [!code hl:end]
],
})
```
### Leave out the default plugins
The instance of `accounts` adds the `dialog`, `funding`, and `mpp` plugins that `plugins` lacks. `accounts/lite` exports the same modules, and its `Accounts.create` adds none of them, so the bundle holds only the plugins that the app names.
```ts [tempo.config.ts]
// [!code hl:next]
import { Accounts } from 'accounts/lite'
import { dialog } from 'accounts/plugins'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [dialog()],
})
```
## Next steps
# Errors \[An app catches each refusal of Tempo ID, and branches on its reason.]
## Overview
Each call throws `Accounts.RequestError` when Tempo ID refuses a request. Its `reason` is the refusal's stable name, its `code` the OAuth error code, and its message the fault and the fix.
The demo reads the user of an [access token](/docs/guides/api-authentication/authenticate-requests) that Tempo ID did not issue, and shows the error. The read needs no sign-in, and changes nothing.
## Walkthrough
::::steps
### Create the instance
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
export const accounts = Accounts.create({ chain: 'testnet' })
```
### Catch the error
The handler throws again each error that is not an `Accounts.RequestError` , such as `Accounts.SignedOutError` without a session. It returns the message of each refusal that it does not handle.
:::code-group
```ts [main.ts]
import { Accounts } from 'accounts'
import { accounts } from './tempo.config.js'
export async function readConnection() {
try {
const { accessKeys } = await accounts.connection.get()
return `The app holds ${accessKeys.length} access keys.`
} catch (error) {
if (!(error instanceof Accounts.RequestError)) throw error // [!code hl]
return error.message // [!code hl]
}
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
export const accounts = Accounts.create({ chain: 'testnet' })
```
:::
### Branch on the reason
A message's wording may change, and a `reason` does not. `invalid_token` refuses an expired or revoked access token, or another app's. [Reasons](/docs/guides/errors#reasons) lists each reason.
:::code-group
```ts [main.ts]
import { Accounts } from 'accounts'
import { accounts } from './tempo.config.js'
export async function readConnection() {
try {
const { accessKeys } = await accounts.connection.get()
return `The app holds ${accessKeys.length} access keys.`
} catch (error) {
if (!(error instanceof Accounts.RequestError)) throw error
if (error.reason === 'invalid_token') return 'Sign in again.' // [!code ++]
return error.message
}
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
export const accounts = Accounts.create({ chain: 'testnet' })
```
:::
### Retry a temporary failure
A rate limit and a failed service have different reasons, and share the code `temporarily_unavailable`. A branch on the `code` handles both.
:::code-group
```ts [main.ts]
import { Accounts } from 'accounts'
import { accounts } from './tempo.config.js'
export async function readConnection() {
try {
const { accessKeys } = await accounts.connection.get()
return `The app holds ${accessKeys.length} access keys.`
} catch (error) {
if (!(error instanceof Accounts.RequestError)) throw error
if (error.reason === 'invalid_token') return 'Sign in again.'
if (error.code === 'temporarily_unavailable') return 'Try again later.' // [!code ++]
return error.message
}
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
export const accounts = Accounts.create({ chain: 'testnet' })
```
:::
::::
## Use cases
Each use case reads one property of `Accounts.RequestError` , or catches another error class of the package.
### Handle a refusal without a reason
Tempo ID's OAuth endpoints return no `reason` , so the app branches on the `code` . A refresh with a revoked or expired refresh token fails with `invalid_grant`.
`tokens.userInfo` sets the reason `invalid_token` itself, for each access token that Tempo ID refuses.
:::code-group
```ts [main.ts]
import { Accounts } from 'accounts'
import { accounts } from './tempo.config.js'
export async function refresh() {
try {
await accounts.session.refresh()
} catch (error) {
if (!(error instanceof Accounts.RequestError)) throw error
if (error.code === 'invalid_grant') console.log('Sign in again.') // [!code hl]
}
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
export const accounts = Accounts.create({ chain: 'testnet' })
```
:::
### Detect a refusal before a request
The package refuses some options, such as a past `expiry` , before any request. The error holds Tempo ID's reason, and `status` 0.
:::code-group
```ts [main.ts]
import { Accounts } from 'accounts'
import { accounts } from './tempo.config.js'
export async function signIn() {
try {
await accounts.dialog.signIn({
accessKey: { expiry: 1, limits: [{ limit: '100', token: 'ousd' }] },
})
} catch (error) {
if (!(error instanceof Accounts.RequestError)) throw error
console.log(error.reason, error.status) // 'expiry_passed', 0
}
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
export const accounts = Accounts.create({ chain: 'testnet' })
```
:::
### Show the field at fault
`field` names the request field at fault as a dotted path, such as the limit of an access key. A form shows the message beside that field.
```ts [main.ts]
import { Accounts } from 'accounts'
export function fieldError(error: Accounts.RequestError, name: string) {
return error.field === name ? error.message : undefined // [!code hl]
}
```
### Wait out a rate limit
`meta` holds the values that the refusal compared. For `rate_limited`, it holds the seconds to wait, if Tempo ID knows them.
```ts [main.ts]
import { Accounts } from 'accounts'
export function wait(error: Accounts.RequestError) {
if (error.reason !== 'rate_limited') return undefined
return Number(error.meta?.retryAfter ?? 60) // [!code hl]
}
```
### Link the explanation
`uri` holds the link to Tempo ID's description of the error, as the [Reasons](/docs/guides/errors#reasons) table shows. A support page or a log shows it beside the message.
```ts [main.ts]
import { Accounts } from 'accounts'
export function describe(error: Accounts.RequestError) {
if (!error.uri) return error.message
return `${error.message} See ${error.uri}.` // [!code hl]
}
```
### Restart a failed sign-in
A sign-in can fail after the user's code or passkey verified, such as when Tempo ID refuses the authorization. The error then has `signedIn` , and the instance empties its session.
The emailed code verified already, so the app requests a new one. Without `signedIn`, the session stays as it was.
:::code-group
```ts [main.ts]
import { Accounts } from 'accounts'
import { accounts } from './tempo.config.js'
export async function signIn(email: string, code: string) {
try {
await accounts.email.signIn({ code, email })
} catch (error) {
if (!(error instanceof Accounts.RequestError)) throw error
if (error.signedIn) await accounts.email.sendCode({ email }) // [!code hl]
return error.message
}
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { email } from 'accounts/plugins'
export const accounts = Accounts.create({
chain: 'testnet',
clientId: 'example-app',
plugins: [email()],
})
```
:::
### Ignore a closed dialog
A closed dialog is no refusal. `dialog.signIn` throws a `DOMException` named `AbortError` for it, and for a sign-in that a later one replaces. A closed passkey prompt is none either\: `passkey.signIn` , `passkey.register` , and `email.signIn` with `link` throw an `Error` named `AbortError` for it, since React Native has no `DOMException`. The app checks the name alone. An authenticator that already holds one of the user's passkeys refuses a new one, so `passkey.register` throws an `Error` named `InvalidStateError`, and the app offers a sign-in with that passkey instead.
If another sign-in or a sign-out completes first, it throws `Accounts.SupersededError` . The app ignores both.
In a browser without a connection, `dialog.signIn` opens no dialog, and throws `Accounts.RequestError` with `server_error` and status 0. The app shows its message.
:::code-group
```tsx [SignIn.tsx]
import { Accounts } from 'accounts'
import { accounts } from './tempo.config.js'
export function SignIn() {
async function signIn() {
try {
await accounts.dialog.signIn()
} catch (error) {
// [!code hl:start]
if (error instanceof Error && error.name === 'AbortError') return
if (error instanceof Accounts.SupersededError) return
// [!code hl:end]
throw error
}
}
return (
Sign in with Tempo
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
export const accounts = Accounts.create({ chain: 'testnet' })
```
:::
### Send only when signed in
A transaction without a session throws `Accounts.SignedOutError` . If a refused refresh token ended the session, its `cause` holds that refusal.
A transaction from a session without an access key throws `Accounts.AccessKeyRequiredError` . The app then signs the user in with an [access key](/docs/guides/access-keys/authorize-access-keys).
:::code-group
```ts [main.ts]
import { Accounts } from 'accounts'
import { parseUnits } from 'viem'
import { Addresses } from 'viem/tempo'
import { accounts } from './tempo.config.js'
export async function send() {
try {
await accounts.token.transferSync({
amount: parseUnits('1', 6),
to: '0x000000000000000000000000000000000000dEaD',
token: Addresses.ousd,
})
} catch (error) {
// [!code hl:start]
if (error instanceof Accounts.SignedOutError) return 'Sign in to send.'
if (error instanceof Accounts.AccessKeyRequiredError)
return 'Sign in with an access key to send.'
// [!code hl:end]
throw error
}
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [viem()],
})
```
:::
### Handle an ended retry
If a transaction fails for its access key, its limit, or its balance, the `viem` plugin shows a screen that resolves it, then sends again. If the user closes the screen, the call throws `Plugins.viem.RetryClosedError` .
If the sign-in for a new access key returns another account, the call throws `Plugins.viem.RetryAccountError` . The app matches both by name.
:::code-group
```ts [main.ts]
import { parseUnits } from 'viem'
import { Addresses } from 'viem/tempo'
import { accounts } from './tempo.config.js'
export async function send() {
try {
await accounts.token.transferSync({
amount: parseUnits('1', 6),
to: '0x000000000000000000000000000000000000dEaD',
token: Addresses.ousd,
})
} catch (error) {
// [!code hl:start]
const { name } = error as Error
if (name === 'Plugins.viem.RetryClosedError') return 'The transaction did not send.'
if (name === 'Plugins.viem.RetryAccountError') return 'Sign in with the same account.'
// [!code hl:end]
throw error
}
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [viem()],
})
```
:::
### Ignore a revoked access key
`accessKey.revokeSync` throws `Accounts.RevokedError` if the chain holds the access key revoked already. A sign-out ignores it, since the access key signs nothing.
:::code-group
```ts [main.ts]
import { Accounts } from 'accounts'
import { accounts } from './tempo.config.js'
export async function signOut() {
const { session } = accounts.session.status.get()
const accessKey = session?.accessKey?.keyAuthorization.keyId
try {
if (accessKey) await accounts.accessKey.revokeSync({ accessKey })
} catch (error) {
if (!(error instanceof Accounts.RevokedError)) throw error // [!code hl]
}
await accounts.signOut()
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [viem()],
})
```
:::
### Catch the errors of a guest session
A [guest session](/docs/guides/guest-checkout) holds no Tempo ID tokens. A call that reads Tempo ID as the user, such as `account.get`, throws `Accounts.GuestSessionError` . An MPP payment without a cap throws `mpp.MaxAmountRequiredError` or `mpp.MaxDepositRequiredError` , and a malformed `maxDeposit` `mpp.MaxDepositInvalidError` . Outside a page, a guest payment whose outcome Tempo ID does not confirm throws `Actions.guest.PendingError` , which names the checkout in `checkout`. The store keeps nothing of it, and a later `pay` of the same payment opens a new checkout, which can pay again. Confirm the outcome of the checkout before paying again.
:::code-group
```ts [main.ts]
import { Accounts } from 'accounts'
import { accounts } from './tempo.config.js'
export async function readAccount() {
try {
return await accounts.account.get()
} catch (error) {
// A guest session has no Tempo ID user, so the app reads its address instead.
if (error instanceof Accounts.GuestSessionError) return undefined // [!code hl]
throw error
}
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
export const accounts = Accounts.create({
chain: 'testnet',
guest: true,
})
```
:::
## Reasons
The table lists each `RequestError.Reason` . Each links Tempo ID's description, which names its `code` , `field` , and `meta` .
The error's `uri` holds the same link, as [Link the explanation](/docs/guides/errors#link-the-explanation) shows. Each call's TSDoc lists its reasons.
| Reason | Fault | Fix |
| ---------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| [`access_key_changing`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#access_key_changing) | Another request changes the same limit or the scopes. | Retry after it ends. |
| [`access_key_endpoint_failed`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#access_key_endpoint_failed) | An API's access key endpoint failed at the approval. | Approve again. |
| [`access_key_pending`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#access_key_pending) | The access key has an unregistered key authorization with other limits or scopes. | Request a new access key. |
| [`access_key_taken`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#access_key_taken) | Another app holds the access key for the Tempo Account. | Request a new access key. |
| [`allowance_redeemed`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#allowance_redeemed) | The API redeemed the connection's allowance for another access key. | Use the access key of `meta.address`. |
| [`already_decided`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#already_decided) | The user already approved or denied the device code. | Request a new code. |
| [`app_exists`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#app_exists) | Another OAuth app has the client ID. | Choose another client ID. |
| [`authorization_expired`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#authorization_expired) | The authorization request that a Tempo ID page continues is forged or expired. | Start the sign-in again. |
| [`backend_sign_in_not_permitted`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#backend_sign_in_not_permitted) | The app has no client secret or keys, or no backend sign-in. | Sign in through a redirect. |
| [`body_too_large`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#body_too_large) | The body exceeds 65,536 bytes, or a pushed request 8,192 bytes. | Send a smaller body. |
| [`challenge_not_permitted`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#challenge_not_permitted) | A headless request holds a challenge without the `tempo-id:sign` scope. | Send the challenge through a redirect. |
| [`config_conflict`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#config_conflict) | The chain's account configuration differs from Tempo ID's. | Read the account again. |
| [`configurable_accounts_disabled`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#configurable_accounts_disabled) | The deployment has no configurable accounts on the chain. | Select a chain of `meta.configured`. |
| [`connection_mismatch`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#connection_mismatch) | A redemption's `nonce` or public key does not match the prepared access key. | Send the newest `nonce` and its public key. |
| [`consent_required`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#consent_required) | A redirect requests an access key with `prompt=none`, which shows no approval page. | Remove `prompt=none`. |
| [`cross_site_request`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#cross_site_request) | A form, or a write without a body, came from another site. | Send JSON from an allowed origin. |
| [`duplicate_limit`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#duplicate_limit) | Two limits name one token. | Limit each token once. |
| [`duplicate_scope`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#duplicate_scope) | Two scopes name one call on one target. | Name each call once. |
| [`embed_not_permitted`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#embed_not_permitted) | A native or device app frames the embedded sign-in. | Sign in through a redirect. |
| [`employee_required`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#employee_required) | An employee app's request holds no active employee identity. | Send an admitted request's identity assertion. |
| [`empty_limits`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#empty_limits) | `limits` is empty. | Name a token. |
| [`empty_scopes`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#empty_scopes) | `scopes` is empty. | Name a call. |
| [`expiry_exceeds_maximum`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#expiry_exceeds_maximum) | A headless access key lasts longer than a year. | Use an earlier expiry. |
| [`expiry_passed`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#expiry_passed) | The expiry is in the past. | Use a future time, or a duration. |
| [`foreign_account`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#foreign_account) | The user holds no such Tempo Account in the app's realms. | Name one of the user's Tempo Accounts. |
| [`funding_unavailable`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#funding_unavailable) | The deployment sells no MACH. | Choose another deposit method. |
| [`google_unavailable`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#google_unavailable) | The deployment offers no Google sign-in. | Sign in with an emailed code or a passkey. |
| [`guest_selected`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#guest_selected) | The user selected Continue as guest at a device code of an instance with `guest`. | None\: `device.signIn` returns a guest session. |
| [`insufficient_balance`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#insufficient_balance) | The Tempo Account cannot pay the network fee to revoke or change an access key. | Add funds. |
| [`invalid_access_key_endpoint`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#invalid_access_key_endpoint) | An access key endpoint is not an `https` URL on its resource's origin. | Register such a URL. |
| [`invalid_app`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#invalid_app) | An OAuth app value is not valid. | Fix the value that the message names. |
| [`invalid_chain`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#invalid_chain) | The chain ID is 0. | Use a Tempo chain ID. |
| [`invalid_client`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#invalid_client) | The app is unknown or disabled, or its credentials are missing or wrong. | Send an enabled app's credentials. |
| [`invalid_client_attestation`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#invalid_client_attestation) | A native app's client attestation is missing, or does not verify. | Attest the instance key again. |
| [`invalid_client_metadata`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#invalid_client_metadata) | A dynamic client registration names a value that Tempo ID refuses. | Leave out the value that `field` names. |
| [`invalid_code`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#invalid_code) | The emailed code is wrong, expired, or used. | Request a new code. |
| [`invalid_dpop_proof`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#invalid_dpop_proof) | A DPoP proof is missing, invalid, or replayed. | Send a new proof, or sign in again. |
| [`invalid_expiry`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#invalid_expiry) | The expiry is 0, not a whole number of seconds, or in milliseconds. | Use a future time in whole seconds, or a duration. |
| [`invalid_field`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#invalid_field) | A request field is missing or malformed. | Fix the field that `field` names. |
| [`invalid_id_token_hint`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#invalid_id_token_hint) | A logout's hint is not an ID token that Tempo ID signed for the app. | Send the app's ID token. |
| [`invalid_origin`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#invalid_origin) | A headless request came from an origin that the app does not allow. | Call from a page on the app's origin. |
| [`invalid_period`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#invalid_period) | A limit's period is not a whole number of seconds. | Use whole seconds, a duration, or 0 for a one-time limit. |
| [`invalid_public_key`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#invalid_public_key) | The public key is not a valid point. | Send an uncompressed public key, or an address. |
| [`invalid_realm`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#invalid_realm) | A realm value is not valid. | Fix the value that the message names. |
| [`invalid_recipients`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#invalid_recipients) | A scope names the zero address, one address twice, or recipients on a call that takes none. | Name each recipient once. |
| [`invalid_redirect_uri`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#invalid_redirect_uri) | A dynamic client registration names no redirect URI, more than 10, or one that Tempo ID refuses. | Name a public `https` URI. |
| [`invalid_resource`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#invalid_resource) | A registered resource's value is not valid. | Fix the value that the message names. |
| [`invalid_scope`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#invalid_scope) | `scope` names an API scope that the API lacks or the app may not request. | Request only the scopes that the app may request. |
| [`invalid_target`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#invalid_target) | `resource` is unregistered, disabled, or outside the grant. | Name a resource of the grant. |
| [`invalid_token`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#invalid_token) | The access token is malformed, expired, revoked, or another app's. | Refresh the tokens, or sign in again. |
| [`limit_exceeds_maximum`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#limit_exceeds_maximum) | A headless access key's limit exceeds its token's ceiling. | Lower the limit. |
| [`localhost_not_permitted`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#localhost_not_permitted) | The deployment refuses a localhost client ID. | Use a registered client ID. |
| [`logout_not_permitted`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#logout_not_permitted) | The app is disabled, or not registered for logout. | Register the app's post-logout redirect URIs. |
| [`malformed_body`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#malformed_body) | The body is not valid JSON. | Send a JSON object. |
| [`missing_key`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#missing_key) | The request names no access key, or the zero address. | Send an address or a public key. |
| [`missing_permissions`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#missing_permissions) | The request leaves out `limits` or `scopes` . | Send both. |
| [`not_configurable`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#not_configurable) | The Tempo Account is not configurable yet. | Upgrade the account, then add the owner. |
| [`origin_required`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#origin_required) | A request without `Origin` names an app by its client ID alone. | Send it from the app's page. |
| [`owner_app_taken`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#owner_app_taken) | Another realm holds the server owner's app. | Give each realm its own app. |
| [`owner_exists`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#owner_exists) | The Tempo Account already holds the owner, or is already configurable. | Use the account as it is. |
| [`owner_unavailable`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#owner_unavailable) | The user's cloud wallet fails a check to join the Tempo Account. | Upgrade without `addOwner` . |
| [`passkey_limit`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#passkey_limit) | The user holds 10 passkeys, the maximum. | Sign in with one of them. |
| [`passkey_link_expired`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#passkey_link_expired) | The link to a wallet.tempo passkey expired after 5 minutes. | Send the code again without the link. |
| [`passkey_not_permitted`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#passkey_not_permitted) | No realm of the request holds passkeys whose relying party covers the page. | Sign in with an emailed code. |
| [`passkey_register_not_permitted`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#passkey_register_not_permitted) | No app at the page's origin holds the `tempo-id:sign` scope. | Register the passkey on Tempo ID's account page. |
| [`payment_declined`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#payment_declined) | The card issuer or the payment provider declined the payment. | Pay with another card. |
| [`payment_pending`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#payment_pending) | Another request sends the same payment, or the chain has not confirmed it. | Wait, then read the payment. |
| [`payment_reverted`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#payment_reverted) | The chain reverted the payment's transfer. | Pay with another token, or to another recipient. |
| [`post_logout_redirect_not_permitted`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#post_logout_redirect_not_permitted) | The URI is none of the app's post-logout redirect URIs. | Use a registered URI. |
| [`public_app`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#public_app) | The app has no client secret to rotate. | Name an app with a client secret. |
| [`pushed_authorization_required`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#pushed_authorization_required) | The app requires pushed requests, and the URL holds the access key. | Pass `par: true` to the flow's plugin. |
| [`quote_changed`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#quote_changed) | The payment costs more than the approval page showed. | Request the payment again. |
| [`rate_limited`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#rate_limited) | The request exceeded a rate limit. | Wait for `meta.retryAfter` seconds. |
| [`realm_exists`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#realm_exists) | A realm with the ID exists. | Choose another ID. |
| [`realm_in_use`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#realm_in_use) | An app names the realm. | Remove the realm from each app first. |
| [`recipient_not_permitted`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#recipient_not_permitted) | The token's transfer policy refuses the recipient. | Pay with another token, or to another recipient. |
| [`registrar_required`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#registrar_required) | The app may not register third-party apps. | Authenticate as a registrar. |
| [`rejected`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#rejected) | Tempo ID refused the authorization request, such as a third-party app's headless request. | Check the request against the app's registration. |
| [`relying_party_taken`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#relying_party_taken) | Another realm holds the passkeys' relying party. | Give each realm its own relying party. |
| [`resource_exists`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#resource_exists) | Another resource has the identifier. | Choose another identifier. |
| [`scope_without_limit`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#scope_without_limit) | A scope calls a token that no limit names. | Add a limit for the token. |
| [`session_changed`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#session_changed) | The signed-in session differs from the one that the approval page showed. | Reload the page. |
| [`session_required`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#session_required) | The request has no Tempo ID session, or one older than its `max_age`. | Sign the user in. |
| [`sign_not_permitted`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#sign_not_permitted) | The page may not sign as the cloud wallet. | Sign from a first-party app's page with `tempo-id:sign`. |
| [`sign_out_link_expired`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#sign_out_link_expired) | A security email's sign-out link is unknown, spent, or older than 7 days. | Sign in on a new browser, which sends a new link. |
| [`signing_key_in_use`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#signing_key_in_use) | A revocation names a signing key that signs tokens. | Send `ifSigning: "rotate"` with the revocation. |
| [`too_many_signing_keys`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#too_many_signing_keys) | 100 signing keys are live, or in their grace period. | Rotate again after the oldest grace period. |
| [`unexpected`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#unexpected) | Tempo ID failed unexpectedly. | Retry the request. |
| [`unknown_allowance`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#unknown_allowance) | The connection holds no unexpired allowance for the API. | Authorize the app for the API again. |
| [`unknown_app`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#unknown_app) | No registered OAuth app has the client ID. | Name a registered app. |
| [`unknown_code`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#unknown_code) | The device grant's user code is wrong or expired. | Check the code. |
| [`unknown_endpoint`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#unknown_endpoint) | No route matches the method and the path. | Check both against Tempo ID's OpenAPI document. |
| [`unknown_key`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#unknown_key) | The user holds no live access key with the address on the Tempo Account and the chain. | Name a live access key. |
| [`unknown_order`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#unknown_order) | No MACH order matches the ID and the order token. | Start a new purchase. |
| [`unknown_realm`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#unknown_realm) | No realm has the ID. | Name a realm of the deployment. |
| [`unknown_resource`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#unknown_resource) | No resource has the identifier. | Name a registered resource. |
| [`unknown_screening`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#unknown_screening) | The user has no screening of the address. | Name a screened address. |
| [`unknown_session`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#unknown_session) | The user has no session with the ID. | Read the sessions again. |
| [`unknown_signing_key`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#unknown_signing_key) | No unrevoked signing key has the ID. | Name a live signing key. |
| [`unknown_user`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#unknown_user) | No user has the ID. | Name a user of the deployment. |
| [`unsupported_call`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#unsupported_call) | A scope names a call that Tempo ID does not recognize. | Name a recognized call. |
| [`unsupported_token`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#unsupported_token) | The token is no supported Tempo token on the chain. | Use a supported token, such as OUSD. |
| [`upgrade_required`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#upgrade_required) | The access key's Tempo Account needs an upgrade first. | Upgrade the account, or authorize through a redirect. |
| [`upstream_unavailable`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#upstream_unavailable) | A service that Tempo ID depends on failed. | Retry later. |
| [`webauthn_rejected`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#webauthn_rejected) | A passkey ceremony's challenge is unknown, spent, or expired, or its response does not verify. | Start the passkey sign-in again. |
| [`webauthn_required`](https\://github.com/tempoxyz/id/blob/main/docs/errors.md#webauthn_required) | A request without a page names a Tempo Account that a passkey owns. | Pass `passkey: true` from a page, or authorize through a redirect. |
## Next steps
# Redirect (Web) \[An app signs a user in on Tempo ID's pages, and completes the sign-in on return.]
## Overview
The `redirect` plugin runs an OAuth authorization code flow with PKCE in the page's own window\: the browser leaves for Tempo ID's pages, and returns to the redirect URI with a code. It needs no registration.
Among the sign-in flows, choose it over the [dialog](/docs/guides/dialog) for a full-page sign-in with no frame or popup. To keep the session on a server, use the [backend](/docs/guides/backend) flow.
The demo leaves this page for Tempo ID's sign-in, returns through the site's root, and shows the user.
## Walkthrough
The steps build the demo's flow in a browser app.
::::steps
### Install the packages
:::code-group
```sh [npm]
npm install accounts react react-dom viem
```
```sh [pnpm]
pnpm add accounts react react-dom viem
```
```sh [bun]
bun add accounts react react-dom viem
```
:::
### Create the instance
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { redirect } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [react(), redirect()],
})
```
The page's origin is the client ID, and its root is the default redirect URI.
### Sign the user in
`redirect.signIn` leaves the page. On the return, the first render of `accounts.useSession` redeems the code, saves the [session](/docs/guides/user-session), and removes the callback's parameters from the address bar. Read the session before any routing that reads the URL.
:::code-group
```tsx [App.tsx]
import { accounts } from './tempo.config.js'
export function App() {
const { isPending, session } = accounts.useSession() // [!code hl]
// The sign-in completes, or the saved session loads.
if (isPending) return Loading…
// [!code hl:start]
if (!session)
return (
accounts.redirect.signIn()} type="button">
Sign in with Tempo
)
// [!code hl:end]
return Signed in as {session.user.email}
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { redirect } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [react(), redirect()],
})
```
:::
### Sign the user out
`signOut` ends the app's session. The browser keeps its Tempo ID session, so the next sign-in returns with no prompt.
:::code-group
```tsx [SignOut.tsx]
import { accounts } from './tempo.config.js'
export function SignOut() {
return (
accounts.signOut()} type="button">
Sign out
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { redirect } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [react(), redirect()],
})
```
:::
::::
## Use cases
Each use case sets one option of `redirect.signIn` , of the `redirect` plugin, or of the instance.
### Request an access key
`accessKey` requests an [access key](/docs/guides/access-keys) with the sign-in. The user approves its limits on Tempo ID's page, so they may exceed the [headless ceiling](https\://github.com/tempoxyz/id/blob/main/docs/permissions.md#headless-ceiling) of a sign-in with no page. Without it, the sign-in takes the instance's `accessKey` , if the instance sets one.
:::code-group
```tsx [SignIn.tsx]
import { accounts } from './tempo.config.js'
export function SignIn() {
return (
accounts.redirect.signIn({
// [!code hl:start]
// The access key sends up to 100 OUSD for a day.
accessKey: {
expiry: '1d',
limits: [{ limit: '100', token: 'ousd' }],
},
// [!code hl:end]
})
}
type="button"
>
Sign in with Tempo
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { redirect } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [react(), redirect()],
})
```
:::
### Bind a challenge
`challenge` has the user sign a server's message at the sign-in. On the return, the session's `challengeSignature` holds the signature, which the server checks, as [Sign challenges](/docs/guides/account-proof/sign-challenges) shows.
:::code-group
```tsx [SignIn.tsx]
import { accounts } from './tempo.config.js'
export function SignIn() {
async function signIn() {
// The server issues the message to sign.
const response = await fetch('/challenge', { method: 'POST' })
await accounts.redirect.signIn({ challenge: await response.text() }) // [!code hl]
}
return (
Sign in with Tempo
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { redirect } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [react(), redirect()],
})
```
:::
### Ask for funds
`funding` names the amount that the app needs in the user's Tempo Account. If the account holds less, Tempo ID's deposit page opens after the approval, before the return.
:::code-group
```tsx [SignIn.tsx]
import { accounts } from './tempo.config.js'
export function SignIn() {
return (
accounts.redirect.signIn({
funding: { amount: '10', currency: 'USD' }, // [!code hl]
})
}
type="button"
>
Sign in with Tempo
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { redirect } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [react(), redirect()],
})
```
:::
### Fill in the email
`loginHint` fills in the email field of Tempo ID's sign-in page, and the user can still change it. It defaults to the saved session's email, so an app passes it only for a session that ended, such as after a refused refresh.
:::code-group
```tsx [SignIn.tsx]
import { accounts } from './tempo.config.js'
export function SignIn() {
return (
accounts.redirect.signIn({
loginHint: 'alice@example.com', // [!code hl]
})
}
type="button"
>
Sign in with Tempo
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { redirect } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [react(), redirect()],
})
```
:::
### Sign in for an API
`resource` names a [registered resource](https\://github.com/tempoxyz/id/blob/main/docs/resources.md), such as an MCP server. Each access token then names it as its audience, so only that API accepts the token.
:::code-group
```tsx [SignIn.tsx]
import { accounts } from './tempo.config.js'
export function SignIn() {
return (
accounts.redirect.signIn({
resource: 'https://mcp.example.com/mcp', // [!code hl]
})
}
type="button"
>
Sign in with Tempo
)
}
```
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { redirect } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [react(), redirect()],
})
```
:::
### Push each request
`par: true` sends each request to Tempo ID first, so the URL holds only a reference to it, as [Pushed authorization requests](https\://github.com/tempoxyz/id/blob/main/docs/pushed-authorization-requests.md) describes. A pushed request names at most one resource.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { redirect } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [react(), redirect({ par: true })], // [!code hl]
})
```
### Return to another page
Tempo ID returns only to a redirect URI that matches one of the app's exactly. For another URI, it shows an error page.
| Client ID | Redirect URIs of the app |
| ----------------------------- | -------------------------------------------------------- |
| An `https` origin | The root, or the `redirect_uris` of its web app manifest |
| A localhost origin | Each path of the origin, on the same port |
| The client ID of an OAuth app | The redirect URIs of its registration |
To return to another page of an `https` origin, list it in the [web app manifest](https\://github.com/tempoxyz/id/blob/main/docs/apps.md#origin-client-id) that the origin's root links. The list replaces the root, so keep the root in it if the app uses it.
```json [manifest.webmanifest]
{
"redirect_uris": ["https://app.example/", "https://app.example/callback"]
}
```
Pass the same URI as `redirectUri` , and render `accounts.useSession` on that page.
```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { redirect } from 'accounts/plugins'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [react(), redirect()],
redirectUri: 'https://app.example/callback', // [!code hl]
})
```
## Next steps