Skip to content
LogoLogo

Mppx.create

Create a payment-aware fetch client

Choose a signing account

Create a server-only wallet.ts module, then import account wherever an example creates a local signing account.

wallet.ts
import { privateKeyToAccount } from 'viem/accounts'

export const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`)

Creates a client-side payment handler. Returns a payment handler with a fetch function that automatically handles 402 Payment Required responses. By default, also polyfills globalThis.fetch.

Credential-bearing retries use redirect: 'manual'. Redirect responses return without forwarding the Credential and leave payment acceptance pending, as with Fetch.from.

Usage

With payment hooks

Register hooks on the returned mppx instance to observe the payment flow.

Without polyfill

Set polyfill: false to get a scoped fetch without modifying the global:

Manual Credential handling

For full control over the payment flow:

Pass acceptPayment to override method selection for this one response:

Return type

type Mppx = {
  /** Creates a credential from a payment-required response. */
  createCredential: (
    response: Response,
    context?: Context,
    options?: {
      acceptPayment?: string | AcceptPayment.Entry[]
      orderChallenges?: OrderChallenges
      request?: RequestInit
    },
  ) => Promise<string>
  /** Payment-aware fetch function that automatically handles 402 responses. */
  fetch: Fetch
  /** The configured payment methods. */
  methods: readonly Method.Client[]
  /** Register a handler for any client payment event. */
  on(name: ClientEventName | '*', handler: ClientEventHandler): Unsubscribe
  /** Register a handler for received payment Challenges. */
  onChallengeReceived(handler: ChallengeReceivedHandler): Unsubscribe
  /** Register a handler for created Credentials. */
  onCredentialCreated(handler: CredentialCreatedHandler): Unsubscribe
  /** Register a handler for failed automatic payment handling. */
  onPaymentFailed(handler: PaymentFailedHandler): Unsubscribe
  /** Register a handler for payment retry responses. */
  onPaymentResponse(handler: PaymentResponseHandler): Unsubscribe
  /** Selects a payment without creating its Credential. */
  preparePayment: (
    response: Response,
    options?: {
      acceptPayment?: string | AcceptPayment.Entry[]
      orderChallenges?: OrderChallenges
      request?: RequestInit
    },
  ) => Promise<PreparedPayment>
  /** The original, unwrapped fetch — bypasses payment interception. */
  rawFetch: typeof globalThis.fetch
  /** The transport used. */
  transport: Transport
}

preparePayment

Selects and snapshots a supported Challenge without signing it. The returned object lets you inspect the terms, create the Credential later, and attach it through the correct Payment auth, x402, or MCP protocol. See Mppx.preparePayment.

rawFetch

The original fetch function, before payment interception. Use rawFetch when you need to make requests that bypass the 402 handler—for example, probing a 402 endpoint for websocket auth tokens or calling APIs that return 402 for non-payment reasons.

Payment hooks

Payment hooks are for logging, monitoring, tracing, and request-local context. Each registration returns an unsubscribe function.

HookRuns when
onChallengeReceivedA 402 Challenge is selected
onCredentialCreatedA Credential is created for the selected Challenge
onPaymentResponseThe retry after payment returns a successful response
onPaymentFailedChallenge parsing, Credential creation, or retry handling fails
on('*', handler)Any client payment event fires

onChallengeReceived runs before onChallenge. It can return a non-empty Credential string to override the default Credential flow. Other hooks are observers: thrown errors are ignored and don't change payment handling.

Parameters

acceptPaymentPolicy (optional)

  • Type: 'always' | 'same-origin' | 'never' | { origins: readonly string[] }
  • Default: 'same-origin' when polyfill is true in browsers, 'always' otherwise

Controls when mppx injects Accept-Payment on outgoing requests. Browser polyfills default to same-origin injection to avoid CORS preflight failures on APIs that don't support payment discovery.

Use { origins } for cross-origin paid APIs. Origin patterns support *. subdomain wildcards.

attestation (optional)

  • Type: Readonly<Record<string, Attestation.Signer>>

Request-attestation signers applied to the initial HTTP request and every automatic payment retry. Each attempt uses a fresh shared nonce and timestamp. Configure Web Bot Auth or Trusted Agent Protocol, or include both signers when a request needs both signatures.

import * as  from 'mppx/attestation/web-bot-auth'
import { ,  } from 'mppx/client'
import type {  } from 'viem'
 
declare const : 
declare const : CryptoKey
 
const  = .({
  : {
    : ..({
      : ,
      : ..!,
      : ..!,
    }),
  },
  : [({  })],
  : false,
})

fetch (optional)

  • Type: typeof globalThis.fetch
  • Default: globalThis.fetch

Custom fetch function to wrap.

methods

  • Type: readonly Method.Client[]

Array of payment methods to use.

onChallenge (optional)

  • Type: (challenge: Challenge, helpers: { createCredential: (context?) => Promise<string> }) => Promise<string | undefined>

Called when a 402 Challenge is received, before Credential creation. Return a Credential string to use it directly, or undefined to fall back to the default Credential flow.

orderChallenges (optional)

  • Type: (challenges: readonly Challenge[]) => readonly Challenge[]

Filters or reorders supported Challenges before Credential creation. It applies to automatic fetch handling and manual createCredential calls unless you pass a request-local override.

paymentPreferences (optional)

  • Type: AcceptPayment.Config<methods>

Configures which payment methods the client prefers when a server offers multiple options via Mppx.compose. Emits an Accept-Payment header on requests so the server can filter Challenges to the client's preferred methods.

Accepts a definition map or a callback that receives a typed key tree. Each key is a method/intent string (like 'tempo/charge'). Values are q-values from 0 to 1—higher means more preferred. Set to 0 to explicitly opt out.

With a plain definition map:

polyfill (optional)

  • Type: boolean
  • Default: true

Whether to polyfill globalThis.fetch with the payment-aware wrapper.

Manual Credential options

acceptPayment (optional)

  • Type: string | readonly AcceptPayment.Entry[]

Request-local method preference override for mppx.preparePayment(response, options) or mppx.createCredential(response, context, options). Use this when you manually fetch a 402 response and want to select from the returned Challenges without changing the client's default paymentPreferences.

orderChallenges (optional)

  • Type: (candidates: readonly ChallengeCandidate[]) => MaybePromise<readonly ChallengeCandidate[]>

Request-local Challenge filter or sort order for preparePayment and createCredential.

request (optional)

  • Type: RequestInit

Original request passed to Challenge extraction. Include this for transports that inspect both request and response, including MCP-over-HTTP.

createCredential.orderChallenges (optional)

  • Type: (challenges: readonly Challenge[]) => readonly Challenge[]

Request-local Challenge filter or ordering override for mppx.createCredential(response, context, options).

transport (optional)

  • Type: Transport
  • Default: Transport.http()

Transport to use for extracting Challenges and attaching Credentials.