Skip to content
LogoLogo

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:

GuideFee payerSent byThe app holds
Use Tempo APIThe sponsor of the app's Tempo API keyA page, through the app's relay routeA Tempo API key
Host fee payersAn account of the app's serverA page, through the app's relay routeA 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.

Send with no feeDemo
pnpx gitpick tempoxyz/accounts/tree/main/examples/sponsored-tempo-apiSource

Walkthrough

The sponsored-tempo-api example runs this flow.

Loading diagram...

Create a Tempo API key

In the Tempo Console, 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.

Install the packages

Add the relay route to the pageClient

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's access token, and every other request to the chain's RPC.

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' })], 
})

Serve the relay routeServer

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 shows.

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 transactionClient

The page sends as it does without a sponsor. The access key signs as the sender, and the receipt's feePayer names the account that paid the fee.

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<string>()
 
  return (
    <>
      <button
        onClick={async () => {
          const { receipt } = await accounts.token.transferSync({
            amount: parseUnits('1', 6),
            to: '0x000000000000000000000000000000000000dEaD',
            token: Addresses.ousd,
          })
          setFeePayer(receipt.feePayer) 
        }}
        type="button"
      >
        Send 1 OUSD
      </button>
      {feePayer && <p>Fee paid by {feePayer}</p>}
    </>
  )
}

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.

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!,
      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 })
      },
    }),
  ],
})
 
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, 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.

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' }, 
    }),
  ],
})
 
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'.

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' }, 
    }),
  ],
})

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.

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}` })), 
  ],
})

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 shows.

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', 
    }),
  ],
})
 
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.

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 }), 
  ],
})
 
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) => {
  // 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)
  return accounts.relay.fetch(c.req.raw)
})
 
export default app

Next steps