Pay MPP charges
Pay the 402 charge of an MPP endpoint with the access key of the session.
Overview
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. A charge is a one-time payment by one transfer. accounts.fetch pays each charge with the session's access key, with no prompt.
The demo signs a user in for an access key that spends up to 1 OUSD for a day, then fetches a route of this site that charges 0.01 OUSD, and shows the content and the receipt.
Walkthrough
The mpp-charge example runs these steps. Its server charges with mppx, MPP's TypeScript SDK.
Install the packages
The mpp plugin pays through mppx, a peer dependency. Every instance holds the plugin, so an app passes mpp() only to set its options.
Create the instance
The access key's limit caps the sum of the charges. The mpp plugin adds accounts.fetch, which works the same in a CLI, with the session of the device plugin.
The plugin pays on the chain and the transport of the viem plugin, or of Tempo's own RPC without one. For a local node, Use another Tempo ID or chain sets both.
import { Accounts } from 'accounts'
import { mpp } from 'accounts/mpp'
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: [mpp(), react()],
})Sign the user in
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: '1', token: 'OUSD' },
})
}
type="button"
>
Sign in with Tempo
</button>
)
return <p>Signed in as {session.user.email}</p>
}import { Accounts } from 'accounts'
import { mpp } from 'accounts/mpp'
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: [mpp(), react()],
})Fetch the paid content
accounts.fetch is fetch that pays each 402 charge: the access key signs the charge's transfer, and the endpoint broadcasts it. A response header holds the receipt. The app renders Fortune for a signed-in user.
import { Receipt } from 'mppx'
import { useState } from 'react'
import { accounts } from './tempo.config.js'
export function Fortune() {
const [paid, setPaid] = useState<{ fortune: string; hash: string }>()
return (
<>
<button
onClick={async () => {
const response = await accounts.fetch(
'https://api.example.com/fortune',
)
const { fortune } = (await response.json()) as { fortune: string }
// The hash of the transaction that paid the charge.
const { reference } = Receipt.fromResponse(response)
setPaid({ fortune, hash: reference })
}}
type="button"
>
Fetch a fortune
</button>
{paid && (
<p>
{paid.fortune} Paid in {paid.hash}.
</p>
)}
</>
)
}import { Accounts } from 'accounts'
import { mpp } from 'accounts/mpp'
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: [mpp(), react()],
})On a page, if the balance does not cover a charge, Tempo ID's deposit page opens, and the request sends again after the deposit. A spent limit opens the sign-in for a new access key in the same way. If the user closes the screen, the request rejects with Plugins.viem.RetryClosedError.
On a page, Tempo ID's payment page also pays a charge that no access key pays, such as one above the access key's whole limit, in mppx's push mode. The user approves the transfer there, and a Reject rejects with Accounts.RequestError and the code access_denied.
The payment page sends one transfer, so a charge of zero or with splits still needs the access key. A backend and mcp show no screen, so such a charge rejects with mpp.LimitError, or with Accounts.AccessKeyRequiredError without an access key. In a CLI, a device code opens the deposit page after its approval, as Send above the limit or the balance shows.
Use cases
Each use case sets one option of the mpp plugin, or of the payer that accounts.mpp returns for one call.
Cap each charge
maxAmount caps one charge. A larger charge rejects with mpp.MaxAmountError before the access key signs.
import { accounts } from './tempo.config.js'
export function Fortune() {
return (
<button
onClick={async () => {
const response = await accounts
.mpp({ maxAmount: '0.05' })
.fetch('https://api.example.com/fortune')
console.log(await response.json())
}}
type="button"
>
Fetch a fortune
</button>
)
}import { Accounts } from 'accounts'
import { mpp } from 'accounts/mpp'
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: [mpp(), react()],
})mpp({ maxAmount: '0.05' }) sets it for the instance. On a page, Tempo ID's payment page pays a charge above the access key's whole limit, as Fetch the paid content describes. Elsewhere, such a charge rejects with mpp.LimitError. So does a charge that a concurrent charge of the same access key left above the limit, such as in a Worker that pays a user's requests in parallel.
Turn off the deposit page
retry names the failures that show a screen of Tempo ID, then pay again. With balance: false, a charge that the balance does not cover rejects as it is, with no deposit page.
import { Accounts } from 'accounts'
import { mpp } from 'accounts/mpp'
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: [mpp({ retry: { balance: false } }), react()],
})Pay from a backend
With the backend plugin, a server holds the session, and accounts.mpp({ session }) pays with its access key.
import { Accounts, Store } from 'accounts'
import { mpp } from 'accounts/mpp'
import { backend } from 'accounts/plugins'
import { Hono } from 'hono'
const accounts = Accounts.create({
accessKey: () => ({
expiry: '1d',
limits: [{ limit: '1', token: 'ousd' }],
}),
chain: 'testnet',
clientId: process.env.APP_URL,
plugins: [backend({ store: Store.memory() }), mpp()],
})
const app = new Hono()
// The sign-in routes of the `backend` plugin.
app.all('/api/*', (c) => accounts.handler.fetch(c.req.raw))
app.get('/fortune', async (c) => {
const session = await accounts.session.get(c.req.raw)
if (session?.method !== 'tempo-id') return c.body(null, 401)
const response = await accounts
.mpp({ session })
.fetch('https://api.example.com/fortune')
return c.json(await response.json())
})
export default appA backend shows no screen, so a refused charge rejects with its error.
A 402 response whose every Tempo charge names another chain than the access key's rejects with mpp.ChainError before the access key signs, on a page as on a backend.
Prove who pays
An endpoint that verifies Tempo ID with mppx's mppx/extensions/identity/tempo reads who the user is, and refuses a payment from an account that the user did not grant to the app. identity.scope names the origins that receive the session's access token and ID token.
import { accounts } from './tempo.config.js'
export function Fortune() {
return (
<button
onClick={async () => {
// The request carries the session's identity to the endpoint.
const response = await accounts.fetch('https://api.example.com/fortune')
console.log(await response.json())
}}
type="button"
>
Fetch a fortune
</button>
)
}import { Accounts } from 'accounts'
import { mpp } from 'accounts/mpp'
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: [
mpp({ identity: { scope: ['https://api.example.com'] } }),
react(),
],
})The endpoint takes the payment credential in Payment-Authorization with mppx's requiresAuth: true, so the paid request carries both. An endpoint without it takes the credential in Authorization, so its paid request carries no identity.
For a DPoP token, each request carries a new proof of the instance's dpop key. A Bearer token, such as one that the store saved before the app set its dpop key, goes with the Bearer scheme and no proof.
The ID token carries the user's email address when the sign-in requests the email scope. The payer sends it only until it expires, after 10 hours, unless a refresh returns a new one. A payer of a fixed session sends no identity.
Attribute each payment
clientId names the app. Each charge's transfer memo then carries its fingerprint, so an endpoint attributes the payment to the app.
import { Accounts } from 'accounts'
import { mpp } from 'accounts/mpp'
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: [mpp({ clientId: 'example.com' }), react()],
})Swap into the charged token
autoSwap swaps another stablecoin into the charged token on Tempo's exchange, if the Tempo Account holds too little of it. The access key's limits must cover the token that the swap sells.
import { Accounts } from 'accounts'
import { mpp } from 'accounts/mpp'
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: [
// A charge in OUSD sells pathUSD for the OUSD that the account lacks.
mpp({ autoSwap: { fallback: false, tokenIn: [Addresses.pathUsd] } }),
react(),
],
})Broadcast each charge
mode: 'push' has the app broadcast each charge's transaction, in place of the endpoint. The credential then names the transaction's hash.
import { Accounts } from 'accounts'
import { mpp } from 'accounts/mpp'
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: [mpp({ mode: 'push' }), react()],
})Refuse subscription offers
orderChallenges filters and sorts the offers of a 402 response before the access key signs. The payer pays the first offer that it returns, and pays none for an empty array.
import { Accounts } from 'accounts'
import { mpp } from 'accounts/mpp'
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: [
mpp({
orderChallenges: (candidates) =>
candidates.filter((candidate) => candidate.challenge.intent === 'charge'),
}),
react(),
],
})