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.
Payment retries use redirect: 'manual' to keep Credentials from following redirects. A 3xx response returns to you and leaves payment acceptance pending. The initial request retains its configured redirect behavior.
Usage
import { } from 'accounts'
import { , } from 'mppx/client'
const = .({ : false }) // Avoid double 402 handling; mppx is configured below.
await .({ : 'wallet_connect' })
.({
: [({
: .({ : true }),
: .,
})],
})
const = await ('https://mpp.dev/api/ping/paid')
.(.)
200import { , } from 'mppx/client'
import { } from 'viem/accounts'
const = ('0x...')
.({
: [({ })],
})
const = await ('https://mpp.dev/api/ping/paid')
.(.)
200With cross-origin payments
In browsers, Fetch.polyfill defaults to same-origin Accept-Payment injection. Pass acceptPaymentPolicy when your paid API lives on another origin.
import { } from 'accounts'
import { , } from 'mppx/client'
const = .({ : false }) // Avoid double 402 handling; mppx is configured below.
await .({ : 'wallet_connect' })
.({
: {
: ['https://api.example.com'],
},
: [({
: .({ : true }),
: .,
})],
})import { , } from 'mppx/client'
import { } from 'viem/accounts'
const = ('0x...')
.({
: {
: ['https://api.example.com'],
},
: [({ })],
})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.
orderChallenges (optional)
- Type:
(challenges: readonly Challenge[]) => readonly Challenge[]
Filters or reorders supported Challenges before Credential creation.
transport (optional)
- Type:
Transport.AnyTransport - Default:
Transport.http()
Transport used to extract Challenges and attach Credentials.