Fetch.polyfill
Install a global payment-aware fetch
Choose a signing account
Create a server-only wallet.ts module, then import account wherever an example creates a local signing account.
import { privateKeyToAccount } from 'viem/accounts'
export const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`)Replaces globalThis.fetch with a payment-aware wrapper that handles 402 Payment Required responses.
Usage
With cross-origin payments
In browsers, Fetch.polyfill defaults to same-origin Accept-Payment injection. Pass acceptPaymentPolicy when your paid API lives on another origin.
Return type
type ReturnType = voidParameters
acceptPayment (optional)
- Type:
AcceptPayment.Resolved<methods>
Resolved Accept-Payment header and preference data.
acceptPaymentPolicy (optional)
- Type:
'always' | 'same-origin' | 'never' | { origins: readonly string[] } - Default:
'same-origin'in browsers,'always'otherwise
Controls when Accept-Payment is injected.
eventDispatcher (optional)
- Type:
ClientEventDispatcher<methods>
Advanced shared event dispatcher. challenge.received handlers run before onChallenge; the first non-empty Credential string skips onChallenge.
fetch (optional)
- Type:
typeof globalThis.fetch - Default:
globalThis.fetch
Custom fetch function to wrap.
methods
- Type:
readonly Method.AnyClient[]
Array of payment methods to use for 402 responses.
onChallenge (optional)
- Type:
(challenge, helpers) => Promise<string | undefined>
Called after a 402 Challenge is selected and before the wrapper retries the request.