( innerFetch: typeof globalThis.fetch, )
| 31 | * @returns A fetch-compatible function with x402 payment handling |
| 32 | */ |
| 33 | export function wrapFetchWithX402( |
| 34 | innerFetch: typeof globalThis.fetch, |
| 35 | ): typeof globalThis.fetch { |
| 36 | return async ( |
| 37 | input: RequestInfo | URL, |
| 38 | init?: RequestInit, |
| 39 | ): Promise<Response> => { |
| 40 | // Make the initial request |
| 41 | const response = await innerFetch(input, init) |
| 42 | |
| 43 | // If not a 402, pass through |
| 44 | if (response.status !== 402) { |
| 45 | return response |
| 46 | } |
| 47 | |
| 48 | // Check if x402 is enabled |
| 49 | if (!isX402Enabled()) { |
| 50 | logForDebugging('[x402] Received 402 but x402 payments are not enabled') |
| 51 | return response |
| 52 | } |
| 53 | |
| 54 | // Check for the x402 payment requirement header |
| 55 | const paymentRequiredHeader = response.headers.get( |
| 56 | X402_HEADERS.PAYMENT_REQUIRED, |
| 57 | ) |
| 58 | if (!paymentRequiredHeader) { |
| 59 | logForDebugging( |
| 60 | '[x402] Received 402 but no X-Payment-Required header present', |
| 61 | ) |
| 62 | return response |
| 63 | } |
| 64 | |
| 65 | logForDebugging(`[x402] Received 402 Payment Required, processing...`) |
| 66 | |
| 67 | // Handle the payment |
| 68 | const result = handlePaymentRequired( |
| 69 | paymentRequiredHeader, |
| 70 | getX402SessionSpentUSD(), |
| 71 | ) |
| 72 | |
| 73 | if (!result) { |
| 74 | logForDebugging('[x402] Payment handling failed, returning original 402') |
| 75 | return response |
| 76 | } |
| 77 | |
| 78 | // Retry with payment header |
| 79 | logForDebugging('[x402] Retrying request with payment header') |
| 80 | |
| 81 | const retryHeaders = new Headers(init?.headers) |
| 82 | retryHeaders.set(X402_HEADERS.PAYMENT, result.paymentHeader) |
| 83 | |
| 84 | const retryResponse = await innerFetch(input, { |
| 85 | ...init, |
| 86 | headers: retryHeaders, |
| 87 | }) |
| 88 | |
| 89 | if (retryResponse.status === 402) { |
| 90 | logForDebugging( |
no test coverage detected