|
| 1 | +import { |
| 2 | + PaymentPayload, |
| 3 | + PaymentRequirements, |
| 4 | + SettleResponse, |
| 5 | + VerifyResponse, |
| 6 | +} from './x402-types'; |
| 7 | +import { toJsonSafe } from './toJsonSafe'; |
| 8 | +import logger, { logMetric } from '../../logger'; |
| 9 | +import { env } from '../../env'; |
| 10 | +import { generateCdpJwt } from './facilitatorService'; |
| 11 | + |
| 12 | +const DEFAULT_FACILITATOR_URL = |
| 13 | + env.COINBASE_FACILITATOR_BASE_URL || 'https://api.cdp.coinbase.com'; |
| 14 | +const facilitatorTimeout = env.FACILITATOR_REQUEST_TIMEOUT || 20000; |
| 15 | + |
| 16 | +type FacilitatorMethod = 'verify' | 'settle'; |
| 17 | + |
| 18 | +async function fetchWithTimeout( |
| 19 | + url: string, |
| 20 | + options: RequestInit, |
| 21 | + timeoutMs: number, |
| 22 | + method: FacilitatorMethod |
| 23 | +): Promise<Response> { |
| 24 | + const abortController = new AbortController(); |
| 25 | + const timeoutId = setTimeout(() => { |
| 26 | + abortController.abort(); |
| 27 | + logger.warn( |
| 28 | + `Coinbase facilitator ${method} request timed out after ${timeoutMs}ms` |
| 29 | + ); |
| 30 | + }, Number(timeoutMs)); |
| 31 | + |
| 32 | + try { |
| 33 | + const res = await fetch(url, { |
| 34 | + ...options, |
| 35 | + signal: abortController.signal, |
| 36 | + }); |
| 37 | + clearTimeout(timeoutId); |
| 38 | + return res; |
| 39 | + } catch (error) { |
| 40 | + clearTimeout(timeoutId); |
| 41 | + logMetric('coinbase_facilitator_failure', 1, { |
| 42 | + method, |
| 43 | + error: error instanceof Error ? error.message : 'unknown', |
| 44 | + }); |
| 45 | + throw error; |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +/** |
| 50 | + * Executes a facilitator request directly to Coinbase's facilitator API |
| 51 | + * |
| 52 | + * @param method - The facilitator method to call ('verify' or 'settle') |
| 53 | + * @param payload - The payment payload |
| 54 | + * @param paymentRequirements - The payment requirements |
| 55 | + * @returns A promise that resolves to the facilitator response |
| 56 | + * @throws Error if the request fails |
| 57 | + */ |
| 58 | +export async function coinbaseFacilitator< |
| 59 | + T extends VerifyResponse | SettleResponse, |
| 60 | +>( |
| 61 | + method: FacilitatorMethod, |
| 62 | + payload: PaymentPayload, |
| 63 | + paymentRequirements: PaymentRequirements |
| 64 | +): Promise<T> { |
| 65 | + if (!env.CDP_API_KEY_ID || !env.CDP_API_KEY_SECRET) { |
| 66 | + throw new Error( |
| 67 | + 'CDP_API_KEY_ID and CDP_API_KEY_SECRET must be set to use Coinbase facilitator' |
| 68 | + ); |
| 69 | + } |
| 70 | + |
| 71 | + logMetric('coinbase_facilitator_attempt', 1, { |
| 72 | + method, |
| 73 | + }); |
| 74 | + |
| 75 | + const url = DEFAULT_FACILITATOR_URL; |
| 76 | + const requestPath = `/platform/v2/x402/${method}`; |
| 77 | + const jwt = await generateCdpJwt({ |
| 78 | + requestMethod: 'POST', |
| 79 | + requestPath, |
| 80 | + requestHost: 'api.cdp.coinbase.com', |
| 81 | + }); |
| 82 | + |
| 83 | + const headers: Record<string, string> = { |
| 84 | + 'Content-Type': 'application/json', |
| 85 | + Authorization: `Bearer ${jwt}`, |
| 86 | + }; |
| 87 | + |
| 88 | + const requestBody = { |
| 89 | + x402Version: 1, |
| 90 | + paymentPayload: toJsonSafe(payload), |
| 91 | + paymentRequirements: toJsonSafe(paymentRequirements), |
| 92 | + }; |
| 93 | + |
| 94 | + const res = await fetchWithTimeout( |
| 95 | + `${url}${requestPath}`, |
| 96 | + { |
| 97 | + method: 'POST', |
| 98 | + headers, |
| 99 | + body: JSON.stringify(requestBody), |
| 100 | + }, |
| 101 | + facilitatorTimeout, |
| 102 | + method |
| 103 | + ); |
| 104 | + |
| 105 | + if (!res.ok) { |
| 106 | + const errorText = await res.text().catch(() => 'Unknown error'); |
| 107 | + logger.error(`Coinbase facilitator ${method} failed`, { |
| 108 | + method, |
| 109 | + status: res.status, |
| 110 | + error: errorText, |
| 111 | + }); |
| 112 | + logMetric('coinbase_facilitator_failure', 1, { |
| 113 | + method, |
| 114 | + status: res.status, |
| 115 | + }); |
| 116 | + throw new Error( |
| 117 | + `Coinbase facilitator ${method} failed: ${res.status} ${errorText}` |
| 118 | + ); |
| 119 | + } |
| 120 | + |
| 121 | + const data = await res.json(); |
| 122 | + logger.info(`Coinbase facilitator ${method} succeeded`, { |
| 123 | + method, |
| 124 | + }); |
| 125 | + logMetric('coinbase_facilitator_success', 1, { |
| 126 | + method, |
| 127 | + }); |
| 128 | + |
| 129 | + return data as T; |
| 130 | +} |
0 commit comments