Skip to content
LogoLogo

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.

The Machine Payments Protocol (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, and the close settles the channel and returns the rest.

The mpp plugin runs the session through mppx, MPP's TypeScript SDK. Open payment channels 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.

Pay with a sessionDemo
pnpx gitpick tempoxyz/accounts/tree/main/examples/mpp-sessionSource

Walkthrough

The mpp-session example runs these steps, and also pays over SSE and a WebSocket with the session manager's sse and ws.

Install the packages

The server serves its route with Hono.

Create the instanceClient

The mpp plugin adds MPP payments to the instance.

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

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 inClient

dialog.signIn opens Tempo ID's dialog over the page.

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>Signed in as {session.user.email}</p>
}

Start the payment sessionClient

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.

import type { mpp } from 'accounts/mpp'
import { useState } from 'react'
import { accounts } from './tempo.config.js'
 
export function Start() {
  const [manager, setManager] = useState<mpp.SessionManager>()
 
  // The manager opens no channel before its first request.
  if (manager) return <p>Session started</p>
 
  return (
    <button
      onClick={() => setManager(accounts.mpp.session({ maxDeposit: '0.05' }))}
      type="button"
    >
      Start a session
    </button>
  )
}

Pay each requestClient

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.

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<string>()
  // The total that the vouchers of the session pay, in base units.
  const [spent, setSpent] = useState(0n)
 
  return (
    <>
      <button
        onClick={async () => {
          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
      </button>
      <p>{fortune}</p>
      <p>Spent {formatUnits(spent, 6)} OUSD</p>
    </>
  )
}
 
export declare namespace Pay {
  type Props = {
    /** The manager of the session. */
    manager: mpp.SessionManager
  }
}

A request that needs a voucher above maxDeposit throws before any payment.

Close the payment sessionClient

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.

import type { mpp } from 'accounts/mpp'
import { useState } from 'react'
 
export function Close(props: Close.Props) {
  const { manager } = props
  const [hash, setHash] = useState<string>()
 
  return (
    <>
      <button
        onClick={async () => {
          const receipt = await manager.close() 
          setHash(receipt?.txHash)
        }}
        type="button"
      >
        Close the session
      </button>
      <p>{hash}</p>
    </>
  )
}
 
export declare namespace Close {
  type Props = {
    /** The manager of the session. */
    manager: mpp.SessionManager
  }
}

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 routeServer

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.

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.

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.

TopUp.tsx
import type { mpp } from 'accounts/mpp'
 
export function TopUp(props: TopUp.Props) {
  const { manager } = props
 
  return (
    <button onClick={() => manager.topUp('0.01')} type="button"> 
      Add 0.01 OUSD
    </button>
  )
}
 
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.

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

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.

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

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.

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

Next steps