> **Can't find what you're looking for?** Use `search_docs` on the docs MCP server at `https://accounts.tempo.xyz/api/mcp` to find what you need.

# `Provider`

Creates an EIP-1193 provider with a pluggable adapter for managing accounts on Tempo.

The returned object implements [EIP-1193](https://eips.ethereum.org/EIPS/eip-1193) (`request`, `on`, `removeListener`, `emit`, ...) and exposes a few convenience helpers (`getAccount`, `getAccessKeyStatus`, `getClient`, `getMppxParameters`, `ready`, `store`, `chains`). See [Return Type](/docs/api/provider#return-type) for the full surface.

## Usage

```ts twoslash
import { Provider } from 'accounts'

const provider = Provider.create()
```

### Using JSON-RPC Methods

You can interact with accounts via the provider's `request` method.

```ts twoslash
// @noErrors
import { Provider } from 'accounts'

const provider = Provider.create()

const { accounts } = await provider.request({ // [!code focus]
  method: 'wallet_connect', // [!code focus]
}) // [!code focus]
```

### Using Viem Actions

If you prefer to use Viem actions over raw JSON-RPC calls, the provider exposes a `getClient` accessor.

```ts twoslash
// @noErrors
import { parseUnits } from 'viem'
import { tempoActions } from 'viem/tempo'
import { Provider } from 'accounts'

const provider = Provider.create()

const client = provider.getClient().extend(tempoActions()) // [!code focus]

const { receipt } = await client.token.transferSync({ // [!code focus]
  amount: parseUnits('100', 6), // [!code focus]
  to: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', // [!code focus]
  token: '0x20c0000000000000000000000000000000000001', // [!code focus]
}) // [!code focus]
```

### Access Key Status

Use `getAccessKeyStatus` to check whether the active account has a matching delegated key before starting a paid or delegated flow.

```ts twoslash
// @noErrors
import { Provider } from 'accounts'

const provider = Provider.create()

const status = await provider.getAccessKeyStatus({ // [!code focus]
  calls: [{ // [!code focus]
    to: '0x20c0000000000000000000000000000000000001', // [!code focus]
    data: '0xa9059cbb', // [!code focus]
  }], // [!code focus]
}) // [!code focus]

if (status === 'pending') {
  // The next matching transaction will publish the key authorization.
}
```

### Waiting for Stored State

The provider loads its stored state from [`storage`](/docs/api/provider#storage) in the background. `request` waits for it, but `getAccount` reads it synchronously and throws `Store.HydrationError` until it has loaded, so await `ready` first.

```ts twoslash
import { Provider } from 'accounts'

const provider = Provider.create()

await provider.ready() // [!code focus]
const account = provider.getAccount() // [!code focus]
```

## Parameters

### accessKey

* **Type:** `{ authorize?: Provider.create.AuthorizeAccessKey; keystores?: Keystore.Keystores }`
* **Optional**

Access-key configuration: `authorize` automatically authorizes an access key when no stored key satisfies a request; `keystores` is where key material lives.

#### accessKey.authorize

* **Type:** `Provider.create.AuthorizeAccessKeyParameters | (() => Provider.create.AuthorizeAccessKeyParameters | undefined)`
* **Optional**

Access-key parameters to authorize automatically when no stored key satisfies a request.

Applies to `wallet_connect` and transaction sends: the provider first checks stored access keys and reuses one that satisfies the request; if none does, `wallet_connect` includes `capabilities.authorizeAccessKey`, and sends authorize the key immediately beforehand when the requested scopes cover the transaction calls. Pass an object to use the same parameters for every request, or a function to compute them per request — return `undefined` to skip authorization for that request.

The optional `reuse` object is SDK-only. It is never sent to the wallet RPC. Use it to make reuse stricter than the default scope check.

Tempo Wallet-hosted approval pages require at least one `limits` entry and one `scopes` entry. Local adapters accept unbounded keys, but production apps should pass both so local and wallet-hosted flows use the same policy.

```ts
declare function authorize(): {
  /** Access key address. Alternative to `publicKey` when the caller already knows the derived address. */
  address?: Address | undefined
  /** Chain ID the key authorization is scoped to. Defaults to the active chain. */
  chainId?: bigint | undefined
  /** Unix timestamp (seconds) when the key expires. */
  expiry: number
  /** Key type of the external public key. Required when `publicKey` or `address` is provided. */
  keyType?: 'secp256k1' | 'p256' | 'webAuthn' | undefined
  /** TIP-20 spending limits. Optional `period` (seconds) makes the limit roll over each period. */
  limits?: { limit: bigint; period?: number; token: Address }[] | undefined
  /** Private key material to keep in SDK storage. It is not forwarded to wallets over JSON-RPC. */
  privateKey?: Hex | undefined
  /**
   * External public key to authorize. When provided, no key pair is generated —
   * the caller holds the signing material.
   */
  publicKey?: Hex | undefined
  /** Call scopes restricting which contracts/selectors this key can call. */
  scopes?:
    | { address: Address; recipients?: readonly Address[]; selector?: Hex | string }[]
    | undefined
  /** SDK-only reuse policy. Omitted before `wallet_connect` or `wallet_authorizeAccessKey` RPCs. */
  reuse?: {
    /** Minimum Unix timestamp (seconds) a stored key must be valid through. */
    minExpiry?: number | undefined
    /** Minimum spending limits a stored key must satisfy. */
    minLimits?: { limit: bigint; period?: number; token: Address }[] | undefined
  } | undefined
} | undefined
```

```ts twoslash
import { parseUnits } from 'viem'
import { Expiry, Provider } from 'accounts'

const provider = Provider.create({
  accessKey: { // [!code focus]
    authorize: { // [!code focus]
      expiry: Expiry.days(7), // [!code focus]
      limits: [{ // [!code focus]
        token: '0x20c0000000000000000000000000000000000001', // [!code focus]
        limit: parseUnits('500', 6), // [!code focus]
        period: 60 * 60 * 24, // rolling daily limit // [!code focus]
      }], // [!code focus]
      scopes: [{ // [!code focus]
        address: '0x20c0000000000000000000000000000000000001', // [!code focus]
        selector: 'transfer(address,uint256)', // [!code focus]
      }], // [!code focus]
      reuse: { // [!code focus]
        minExpiry: Expiry.hours(1), // [!code focus]
        minLimits: [{ // [!code focus]
          token: '0x20c0000000000000000000000000000000000001', // [!code focus]
          limit: parseUnits('50', 6), // [!code focus]
          period: 60 * 60 * 24, // [!code focus]
        }], // [!code focus]
      }, // [!code focus]
    }, // [!code focus]
  }, // [!code focus]
})
```

If `reuse` is omitted, the provider reuses any unexpired locally signable key whose scopes cover the requested scopes and transaction calls. Add `reuse.minExpiry` or `reuse.minLimits` when a stored key must also be valid long enough or have enough remaining policy capacity for your app's workflow.

You can also pre-derive the access key locally by passing `publicKey` or `address` with `keyType`. The wallet still authorizes that key during `wallet_connect`; the app keeps the signing material.

For `keyType: 'secp256k1'`, generate and store the private key in your app or backend, then pass either the derived `address` or the `publicKey` in `authorizeAccessKey`.

Alternatively, pass `privateKey` to let the SDK derive the access-key address and persist the private key through the configured [`storage`](/docs/api/provider#storage). `privateKey` material is not forwarded to wallets over JSON-RPC.

```ts twoslash
// @noErrors
import { Expiry, Provider } from 'accounts'

const provider = Provider.create({
  accessKey: { // [!code focus]
    authorize: { // [!code focus]
      expiry: Expiry.days(7), // [!code focus]
      keyType: 'p256', // [!code focus]
      publicKey: '0x1234', // [!code focus]
    }, // [!code focus]
  }, // [!code focus]
})
```

#### accessKey.keystores

* **Type:** `Keystore.Keystores`
* **Default:** `Keystore.defaults` — `{ p256: Keystore.webCryptoP256() }`

[Keystores](/docs/api/keystore) backing provider-generated access keys, one per key type.

```ts twoslash
import { Keystore, Provider } from 'accounts'

const provider = Provider.create({
  accessKey: { // [!code focus]
    keystores: { p256: Keystore.webCryptoP256({ extractable: true }) }, // [!code focus]
  }, // [!code focus]
})
```

### adapter

* **Type:** `Adapter`
* **Default:** `dialog()`

Adapter to use for account management.

```ts twoslash
import { Provider, webAuthn } from 'accounts'

const provider = Provider.create({
  adapter: webAuthn({ auth: '/auth' }), // [!code focus]
})
```

### auth

* **Type:** `string | { url?: string; challenge?: string; verify?: string; logout?: string; returnToken?: boolean }`
* **Optional**

Default Server Authentication configuration for `wallet_connect`. When set, every `wallet_connect` call orchestrates the SIWE round-trip against this endpoint unless the caller passes their own `capabilities.auth` (per-call override).

Designed to point at a service running [`Handler.webAuthn`](/docs/server/handler.webAuthn) from `accounts/server`.

Pass a base URL string (endpoints are derived as `${url}/challenge`, `${url}` for verify, and `${url}/logout`), or an object with explicit endpoints.

```ts twoslash
import { Provider } from 'accounts'

const provider = Provider.create({
  auth: '/api/auth', // [!code focus]
})
```

Or with explicit endpoints:

```ts twoslash
import { Provider } from 'accounts'

const provider = Provider.create({
  auth: { // [!code focus]
    challenge: '/api/auth/challenge', // [!code focus]
    verify: '/api/auth/verify', // [!code focus]
    logout: '/api/auth/logout', // [!code focus]
    returnToken: true, // [!code focus]
  }, // [!code focus]
})
```

### chains

* **Type:** `readonly [Chain, ...Chain[]]`
* **Default:** `[tempo, tempoModerato, tempoDevnet]`

Supported chains. The first chain is the default.

```ts twoslash
import { Provider } from 'accounts'
import { tempo } from 'viem/tempo/chains'

const provider = Provider.create({
  chains: [tempo], // [!code focus]
})
```

### feePayer

* **Type:** `string | false | { url: string; precedence?: 'fee-payer-first' | 'user-first' }`
* **Optional**

Fee payer configuration for interacting with a service running [`Handler.relay`](/docs/server/handler.relay) from `accounts/server`. Pass a URL string, an object with `url` and optional `precedence` to control whether the fee payer or the user pays first, or `false` to opt out.

```ts twoslash
import { Provider } from 'accounts'

const provider = Provider.create({
  feePayer: 'https://myapp.com/fee-payer', // [!code focus]
})
```

Or with precedence:

```ts twoslash
import { Provider } from 'accounts'

const provider = Provider.create({
  feePayer: { // [!code focus]
    url: 'https://myapp.com/fee-payer', // [!code focus]
    precedence: 'user-first', // [!code focus]
  }, // [!code focus]
})
```

### hydrationTimeout

* **Type:** `number`
* **Default:** `10_000`

Milliseconds to wait for stored state to load from [`storage`](/docs/api/provider#storage). When the load fails or takes longer than this, `ready` rejects with `Store.HydrationError`, and `request` rejects with an `RpcResponse.InternalError` whose `cause` is that `Store.HydrationError`.

```ts twoslash
import { Provider } from 'accounts'

const provider = Provider.create({
  hydrationTimeout: 30_000, // [!code focus]
})
```

### identity

* **Type:** `{ audience?: string; issuer: string }`
* **Optional**

Identity (verified email) token minting for local adapters. When a `wallet_connect` request asks for `identity.email` and the adapter returns no identity claims — local adapters have no wallet host to mint them — the provider mints the id token from this issuer's `/token` route (the `Handler.oidcProvider` shape) and attaches it to the connect result.

The issuer must trust body-supplied subjects (`Handler.oidcProvider` without `authenticate`), so this is for development deployments — for example, signing in to a local app with the `secp256k1` adapter and an auto-verified email.

* `audience` — the `aud` claim bound into minted tokens. Defaults to `location.origin`.
* `issuer` — the OIDC issuer whose `/token` route mints the id token.

```ts twoslash
import { Provider, secp256k1 } from 'accounts'

const provider = Provider.create({
  adapter: secp256k1(),
  identity: { issuer: 'http://localhost:8787/v1/auth/dev-oidc' }, // [!code focus]
})
```

### maxAccounts

* **Type:** `number`
* **Optional**

Maximum number of accounts to persist. Oldest accounts are evicted when exceeded (LRU).

```ts twoslash
import { Provider } from 'accounts'

const provider = Provider.create({
  maxAccounts: 5, // [!code focus]
})
```

### mpp

* **Type:** `boolean | Provider.mpp.Options`
* **Default:** `true`

Enable [Machine Payment Protocol](https://mpp.dev) (mppx) support. Enabled by default — pass an options object to configure, or `false` to disable.

When enabled, the provider replaces `globalThis.fetch` with a payment-aware `fetch` right away and loads mppx in the background. Requests sent before it finishes loading wait for it. With `polyfill: false` (or `mpp: false`), `fetch` is left alone and mppx is not loaded at all.

```ts twoslash
import { Provider } from 'accounts'

const provider = Provider.create({
  mpp: false, // [!code focus]
})
```

MPP session endpoints can use `deposit` or `maxDeposit` so the client opens and tops up a payment channel before sending vouchers.

Use `provider.getMppxParameters()` when composing an mppx client with `tempo({ account, ...provider.getMppxParameters() })`.

```ts twoslash
import { Provider } from 'accounts'

const provider = Provider.create({
  mpp: { // [!code focus]
    maxDeposit: '10', // [!code focus]
    mode: 'pull', // [!code focus]
  }, // [!code focus]
})
```

### persistCredentials

* **Type:** `boolean`
* **Default:** `true`

Whether to persist credentials and access keys to storage. When `false`, only account addresses are persisted (the user must re-authenticate on each session).

```ts twoslash
import { Provider } from 'accounts'

const provider = Provider.create({
  persistCredentials: false, // [!code focus]
})
```

### relay

* **Type:** `string`
* **Optional**

Base URL for a wallet relay endpoint. When set, every chain's transport defaults to `http("${relay}/${chainId}")` — a single endpoint that routes by chain ID via the path. Per-chain entries in `transports` override this on a chain-by-chain basis.

Designed to point at a service running [`Handler.relay`](/docs/server/handler.relay) from `accounts/server`.

Pass the base path here. The provider appends the active chain ID, so a base
path of `/relay` sends chain `33139` requests to `/relay/33139`.

```ts twoslash
import { Provider } from 'accounts'

const provider = Provider.create({
  relay: '/relay', // [!code focus]
  // tempo (33139) → http('/relay/33139')
  // tempoModerato → http('/relay/<id>')
})
```

### storage

* **Type:** `Storage`
* **Default:** `Storage.idb()` with a `Storage.memory()` fallback where IndexedDB is available, `Storage.memory()` otherwise

Storage adapter for persistence. The default uses IndexedDB in browsers (via `Storage.idb()`) and an in-memory map elsewhere, including React Native. When IndexedDB exists but fails, the default keeps state in memory for the session. A storage adapter you pass yourself has no fallback, so its failures reach `ready`, `request` and `getAccount`.

```ts twoslash
import { Provider, Storage } from 'accounts'

const provider = Provider.create({
  storage: Storage.memory(), // [!code focus]
})
```

### testnet

* **Type:** `boolean`
* **Default:** `false`

Use testnet. When `true`, the default chain will be the first testnet chain in `chains`.

```ts twoslash
import { Provider } from 'accounts'

const provider = Provider.create({
  testnet: true, // [!code focus]
})
```

### transports

* **Type:** `Record<number, Transport>`
* **Optional**

Per-chain transports keyed by chain ID. When omitted, defaults to `http()` for each chain (uses the chain's default RPC URL). Layered on top of `relay`, so explicit per-chain entries win over `relay`-derived defaults.

```ts twoslash
import { Provider } from 'accounts'
import { http } from 'viem'
import { tempo, tempoModerato } from 'viem/tempo/chains'

const provider = Provider.create({
  transports: { // [!code focus]
    [tempo.id]: http('/relay/' + tempo.id), // [!code focus]
    [tempoModerato.id]: http('/relay/' + tempoModerato.id), // [!code focus]
  }, // [!code focus]
})
```

## Return Type

The provider type is exported as `Provider` and is the intersection of [`ox.Provider.Provider`](https://oxlib.sh/Provider) (the EIP-1193 surface) and [`ox.Provider.Emitter`](https://oxlib.sh/Provider#emitter) plus a few extra accessors:

```ts
import type { Address, Hex, Provider as ox_Provider } from 'ox'
import type { tempo as mppx_tempo } from 'mppx/client'
import type { Chain, Client as ViemClient, Transport } from 'viem'
import type { JsonRpcAccount } from 'viem/accounts'
import type { tempo } from 'viem/tempo/chains'

export type Provider = ox_Provider.Provider & ox_Provider.Emitter & {
  /** Configured chains. */
  chains: readonly [Chain, ...Chain[]]
  /** Returns the active root account as a viem JSON-RPC account. */
  getAccount(): JsonRpcAccount
  /** Returns local or on-chain publication status for an access key. */
  getAccessKeyStatus(options?: {
    address?: Address | undefined
    accessKey?: Address | undefined
    calls?: readonly { to?: Address | undefined; data?: Hex | undefined }[] | undefined
    chainId?: number | undefined
  }): Promise<'missing' | 'pending' | 'published' | 'expired'>
  /** Returns a viem Client for the given (or current) chain ID. */
  getClient(options?: {
    chainId?: number | undefined
    feePayer?: string | undefined
  }): ViemClient<Transport, typeof tempo>
  /** Returns mppx Tempo client parameters backed by this provider. */
  getMppxParameters(): {
    getClient: NonNullable<mppx_tempo.Parameters['getClient']>
    resolveAccount: NonNullable<mppx_tempo.Parameters['resolveAccount']>
  }
  /** Resolves once the provider has loaded its stored state. */
  ready(): Promise<void>
  /** Reactive state store. */
  store: Store
}
```
