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 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's access key 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 example runs these steps in a React app.
Create the instance
Add the viem plugin. The client uses the chain and the RPC of the instance. Use another Tempo ID or chain changes them.
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
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.
import { accounts } from './tempo.config.js'
export function App() {
const { session } = accounts.useSession()
if (!session)
return (
<button onClick={() => accounts.dialog.signIn()} type="button">
Sign in with Tempo
</button>
)
return (
<p>
Tempo Account {accounts.viem.account.address} on {accounts.viem.chain.name}
</p>
)
}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 action sends 1 OUSD, and the access key signs it. The sync form waits for the receipt.
import { parseUnits } from 'viem'
import { Addresses } from 'viem/tempo'
import { accounts } from './tempo.config.js'
export function Send() {
return (
<button
onClick={async () => {
const { receipt } = await accounts.viem.token.transferSync({
amount: parseUnits('1', 6),
to: '0x000000000000000000000000000000000000dEaD',
token: Addresses.ousd,
})
console.log(receipt.transactionHash)
}}
type="button"
>
Send 1 OUSD
</button>
)
}import { Send } from './Send.js'
import { accounts } from './tempo.config.js'
export function App() {
const { session } = accounts.useSession()
if (!session)
return (
<button onClick={() => accounts.dialog.signIn()} type="button">
Sign in with Tempo
</button>
)
return (
<main>
<p>
Tempo Account {accounts.viem.account.address} on{' '}
{accounts.viem.chain.name}
</p>
<Send />
</main>
)
}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, public, and wallet 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 sends several calls in one transaction, which the access key signs once. Each Tempo action of Viem builds one call.
import { parseUnits } from 'viem'
import { Actions, Addresses } from 'viem/tempo'
import { accounts } from './tempo.config.js'
export function SendBoth() {
return (
<button
onClick={async () => {
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,
}),
],
})
console.log(receipt.transactionHash)
}}
type="button"
>
Send 3 OUSD
</button>
)
}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.
import { parseUnits } from 'viem'
import { Actions, Addresses } from 'viem/tempo'
import { accounts } from './tempo.config.js'
export function Send() {
return (
<button
onClick={async () => {
const { receipt } = await Actions.token.transferSync(accounts.viem, {
amount: parseUnits('1', 6),
to: '0x000000000000000000000000000000000000dEaD',
token: Addresses.ousd,
})
console.log(receipt.transactionHash)
}}
type="button"
>
Send 1 OUSD
</button>
)
}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.
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 (
<button
onClick={async () => {
const mainnet = accounts.viem({ chainId: tempo.id })
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
</button>
)
}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.
import { parseUnits } from 'viem'
import { Addresses } from 'viem/tempo'
import { accounts } from './tempo.config.js'
export function Send() {
return (
<button
onClick={async () => {
try {
await accounts.token.transferSync({
amount: parseUnits('1', 6),
to: '0x000000000000000000000000000000000000dEaD',
token: Addresses.ousd,
})
} catch (error) {
if ((error as Error).name !== 'Plugins.viem.RetryClosedError')
throw error
console.log('The transaction did not send.')
}
}}
type="button"
>
Send 1 OUSD
</button>
)
}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.
import { parseUnits } from 'viem'
import { Addresses } from 'viem/tempo'
import { accounts } from './tempo.config.js'
export function Send() {
return (
<button
onClick={async () => {
const client = accounts.viem({ retry: false })
const { receipt } = await client.token.transferSync({
amount: parseUnits('1', 6),
to: '0x000000000000000000000000000000000000dEaD',
token: Addresses.ousd,
})
console.log(receipt.transactionHash)
}}
type="button"
>
Send 1 OUSD
</button>
)
}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 } })],
})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.
import { parseUnits } from 'viem'
import { Addresses } from 'viem/tempo'
import { accounts } from './tempo.config.js'
export function Send() {
return (
<button
onClick={async () => {
// The call stops its wait on a screen after two minutes.
const client = accounts.viem({
retry: { signal: AbortSignal.timeout(120_000) },
})
const { receipt } = await client.token.transferSync({
amount: parseUnits('1', 6),
to: '0x000000000000000000000000000000000000dEaD',
token: Addresses.ousd,
})
console.log(receipt.transactionHash)
}}
type="button"
>
Send 1 OUSD
</button>
)
}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 serves the route.
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' })],
})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.
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: { credentials: 'include', url: 'https://api.example.com/relay' },
}),
],
})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.
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}`) })),
],
})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 first transaction.
import { accounts } from './tempo.config.js'
const message = 'Hello from Tempo ID'
export function Sign() {
return (
<button
onClick={async () => {
const signature = await accounts.signMessage({ message })
const valid = await accounts.verifyMessage({
accessToken: await accounts.session.accessToken(),
address: accounts.viem.account.address,
message,
signature,
})
console.log(valid)
}}
type="button"
>
Sign a message
</button>
)
}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 names the access key that signed. Without an access token, it returns false, and an access token that does not verify throws AccessToken.InvalidError.
Sign typed data
Viem's signTypedData and its verification follow the same rules for EIP-712 typed data.
import { accounts } from './tempo.config.js'
export function Sign() {
return (
<button
onClick={async () => {
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
const signature = await accounts.signTypedData(typedData)
const valid = await accounts.verifyTypedData({
...typedData,
accessToken: await accounts.session.accessToken(),
address: accounts.viem.account.address,
signature,
})
console.log(valid)
}}
type="button"
>
Sign a note
</button>
)
}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()],
})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 shows.
import { Accounts } from 'accounts'
import { viem } from 'accounts/plugins'
export const accounts = Accounts.create({
chain: 'testnet',
clientId: 'https://app.example',
plugins: [
viem({
accessTokens: {
clientIds: ['https://app.example', 'https://admin.example'],
},
}),
],
})Check the registration
Viem's 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.
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 (
<button
onClick={async () => {
const metadata = await accounts.accessKey.getMetadata({
accessKey: keyAuthorization.keyId,
account,
})
const registered =
!metadata.isRevoked &&
isAddressEqual(metadata.address, keyAuthorization.keyId)
console.log(registered)
}}
type="button"
>
Check the access key
</button>
)
}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.
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({
amount: parseUnits('1', 6),
to: '0x000000000000000000000000000000000000dEaD',
token: Addresses.ousd,
})
return c.json({ hash: receipt.transactionHash })
})
export default appUse 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.
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',
})