Skip to content
LogoLogo

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

Send a paymentDemo
pnpx gitpick tempoxyz/accounts/tree/main/examples/webSource

Walkthrough

The web example runs these steps.

Install the packages

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.

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 Tempo Account. If the Tempo Account holds less than funding, Tempo ID's deposit page opens after the user approves the limit.

import { accounts } from './tempo.config.js'
 
export function App() {
  const { session } = accounts.useSession()
 
  if (!session)
    return (
      <button
        onClick={() =>
          accounts.dialog.signIn({
            funding: { amount: '10', token: 'OUSD' }, 
          })
        }
        type="button"
      >
        Sign in with Tempo
      </button>
    )
 
  return <p>Signed in as {session.user.email}</p>
}

Send the payment

accounts.pay resolves with transaction once the chain includes the transfer. The app renders Pay for a signed-in user.

import { useState } from 'react'
import { accounts } from './tempo.config.js'
 
export function Pay() {
  const [transaction, setTransaction] = useState<string>()
 
  return (
    <>
      <button
        onClick={async () => {
          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',
          })
          setTransaction(transaction)
        }}
        type="button"
      >
        Pay 1 OUSD
      </button>
      {transaction && <p>Paid in {transaction}.</p>}
    </>
  )
}

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 userThe error
Selects RejectAn Accounts.RequestError with the code access_denied
Closes the dialogA 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.

import { accounts } from './tempo.config.js'
 
export function PayOrder() {
  return (
    <button
      onClick={() =>
        accounts.pay({
          amount: '5',
          memo: 'order-123', 
          to: '0x1f9090aaE28b8a3dCeaDf281B0F12828e676c326',
          token: 'ousd',
        })
      }
      type="button"
    >
      Pay 5 OUSD
    </button>
  )
}

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.

import { accounts } from './tempo.config.js'
 
export function PayPlan() {
  return (
    <button
      onClick={() =>
        accounts.pay({
          amount: '50',
          note: 'Pro plan, November', 
          to: '0x1f9090aaE28b8a3dCeaDf281B0F12828e676c326',
          token: 'ousd',
        })
      }
      type="button"
    >
      Pay 50 OUSD
    </button>
  )
}

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 serves the route.

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

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.

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

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.

import { accounts } from './tempo.config.js'
 
export function PayInPopup() {
  return (
    <button
      // The popup opens within the click, before any other `await`.
      onClick={() =>
        accounts.pay({
          amount: '50',
          mode: 'popup', 
          to: '0x000000000000000000000000000000000000dEaD',
          token: 'ousd',
        })
      }
      type="button"
    >
      Pay 50 OUSD
    </button>
  )
}

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.

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 (
    <button
      onClick={() =>
        accounts.pay({
          account,
          chainId: 4217,
          amount: '1',
          to: '0x000000000000000000000000000000000000dEaD',
          token: 'usdc.e',
        })
      }
      type="button"
    >
      Pay 1 USDC.e
    </button>
  )
}

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

import { accounts } from './tempo.config.js'
 
export function PayAndSignIn() {
  return (
    <button
      onClick={async () => {
        const { address, auth, authError, transaction } = await accounts.pay({
          amount: '1',
          to: '0x000000000000000000000000000000000000dEaD',
          token: 'ousd',
        })
        // 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
    </button>
  )
}
RouteReceivesReturns
Challenge{ chainId }{ message }, or { id, message }
Verify{ address, id, message, signature }, without id for a challenge without oneAny 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.

import { accounts } from './tempo.config.js'
 
export function PayWithTimeout() {
  return (
    <button
      onClick={() =>
        accounts.pay({
          amount: '50',
          // The dialog closes after two minutes without an answer.
          signal: AbortSignal.timeout(120_000), 
          to: '0x000000000000000000000000000000000000dEaD',
          token: 'ousd',
        })
      }
      type="button"
    >
      Pay 50 OUSD
    </button>
  )
}

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

import { parseUnits } from 'viem'
import { Addresses } from 'viem/tempo'
import { accounts } from './tempo.config.js'
 
export function Send() {
  return (
    <button
      onClick={() =>
        accounts.token.transferSync({
          amount: parseUnits('1', 6),
          to: '0x000000000000000000000000000000000000dEaD',
          token: Addresses.ousd,
        })
      }
      type="button"
    >
      Send 1 OUSD
    </button>
  )
}

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

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, 
    to: '0x000000000000000000000000000000000000dEaD',
    token: 'ousd',
  })
  return c.json({ transaction })
})
 
export default app

Next steps