|
| 1 | +import { |
| 2 | + type ERC20TokenAmount, |
| 3 | + type Money, |
| 4 | + moneySchema, |
| 5 | + type Network, |
| 6 | + SupportedEVMNetworks, |
| 7 | +} from "x402/types"; |
| 8 | +import { getAddress } from "../utils/address.js"; |
| 9 | +import { decodePayment } from "./encode.js"; |
| 10 | +import type { facilitator as facilitatorType } from "./facilitator.js"; |
| 11 | +import { |
| 12 | + type FacilitatorNetwork, |
| 13 | + networkToChainId, |
| 14 | + type RequestedPaymentPayload, |
| 15 | + type RequestedPaymentRequirements, |
| 16 | +} from "./schemas.js"; |
| 17 | +import { |
| 18 | + type PaymentArgs, |
| 19 | + type PaymentRequiredResult, |
| 20 | + x402Version, |
| 21 | +} from "./types.js"; |
| 22 | + |
| 23 | +type GetPaymentRequirementsResult = { |
| 24 | + status: 200; |
| 25 | + paymentRequirements: RequestedPaymentRequirements[]; |
| 26 | + selectedPaymentRequirements: RequestedPaymentRequirements; |
| 27 | + decodedPayment: RequestedPaymentPayload; |
| 28 | +}; |
| 29 | + |
| 30 | +/** |
| 31 | + * Decodes a payment request and returns the payment requirements, selected payment requirements, and decoded payment |
| 32 | + * @param args |
| 33 | + * @returns The payment requirements, selected payment requirements, and decoded payment |
| 34 | + */ |
| 35 | +export async function decodePaymentRequest( |
| 36 | + args: PaymentArgs, |
| 37 | +): Promise<GetPaymentRequirementsResult | PaymentRequiredResult> { |
| 38 | + const { |
| 39 | + price, |
| 40 | + network, |
| 41 | + facilitator, |
| 42 | + resourceUrl, |
| 43 | + routeConfig = {}, |
| 44 | + payTo, |
| 45 | + method, |
| 46 | + paymentData, |
| 47 | + } = args; |
| 48 | + const { |
| 49 | + description, |
| 50 | + mimeType, |
| 51 | + maxTimeoutSeconds, |
| 52 | + inputSchema, |
| 53 | + outputSchema, |
| 54 | + errorMessages, |
| 55 | + discoverable, |
| 56 | + } = routeConfig; |
| 57 | + const atomicAmountForAsset = await processPriceToAtomicAmount( |
| 58 | + price, |
| 59 | + network, |
| 60 | + facilitator, |
| 61 | + ); |
| 62 | + if ("error" in atomicAmountForAsset) { |
| 63 | + return { |
| 64 | + status: 402, |
| 65 | + responseHeaders: { "Content-Type": "application/json" }, |
| 66 | + responseBody: { |
| 67 | + x402Version, |
| 68 | + error: atomicAmountForAsset.error, |
| 69 | + accepts: [], |
| 70 | + }, |
| 71 | + }; |
| 72 | + } |
| 73 | + const { maxAmountRequired, asset } = atomicAmountForAsset; |
| 74 | + |
| 75 | + const paymentRequirements: RequestedPaymentRequirements[] = []; |
| 76 | + |
| 77 | + if ( |
| 78 | + SupportedEVMNetworks.includes(network as Network) || |
| 79 | + network.startsWith("eip155:") |
| 80 | + ) { |
| 81 | + paymentRequirements.push({ |
| 82 | + scheme: "exact", |
| 83 | + network, |
| 84 | + maxAmountRequired, |
| 85 | + resource: resourceUrl, |
| 86 | + description: description ?? "", |
| 87 | + mimeType: mimeType ?? "application/json", |
| 88 | + payTo: getAddress(payTo), |
| 89 | + maxTimeoutSeconds: maxTimeoutSeconds ?? 300, |
| 90 | + asset: getAddress(asset.address), |
| 91 | + // TODO: Rename outputSchema to requestStructure |
| 92 | + outputSchema: { |
| 93 | + input: { |
| 94 | + type: "http", |
| 95 | + method, |
| 96 | + discoverable: discoverable ?? true, |
| 97 | + ...inputSchema, |
| 98 | + }, |
| 99 | + output: outputSchema, |
| 100 | + }, |
| 101 | + extra: (asset as ERC20TokenAmount["asset"]).eip712, |
| 102 | + }); |
| 103 | + } else { |
| 104 | + return { |
| 105 | + status: 402, |
| 106 | + responseHeaders: { |
| 107 | + "Content-Type": "application/json", |
| 108 | + }, |
| 109 | + responseBody: { |
| 110 | + x402Version, |
| 111 | + error: `Unsupported network: ${network}`, |
| 112 | + accepts: paymentRequirements, |
| 113 | + }, |
| 114 | + }; |
| 115 | + } |
| 116 | + |
| 117 | + // Check for payment header |
| 118 | + if (!paymentData) { |
| 119 | + return { |
| 120 | + status: 402, |
| 121 | + responseHeaders: { |
| 122 | + "Content-Type": "application/json", |
| 123 | + }, |
| 124 | + responseBody: { |
| 125 | + x402Version, |
| 126 | + error: errorMessages?.paymentRequired || "X-PAYMENT header is required", |
| 127 | + accepts: paymentRequirements, |
| 128 | + }, |
| 129 | + }; |
| 130 | + } |
| 131 | + |
| 132 | + // Verify payment |
| 133 | + let decodedPayment: RequestedPaymentPayload; |
| 134 | + try { |
| 135 | + decodedPayment = decodePayment(paymentData); |
| 136 | + decodedPayment.x402Version = x402Version; |
| 137 | + } catch (error) { |
| 138 | + return { |
| 139 | + status: 402, |
| 140 | + responseHeaders: { |
| 141 | + "Content-Type": "application/json", |
| 142 | + }, |
| 143 | + responseBody: { |
| 144 | + x402Version, |
| 145 | + error: |
| 146 | + errorMessages?.invalidPayment || |
| 147 | + (error instanceof Error ? error.message : "Invalid payment"), |
| 148 | + accepts: paymentRequirements, |
| 149 | + }, |
| 150 | + }; |
| 151 | + } |
| 152 | + |
| 153 | + const selectedPaymentRequirements = paymentRequirements.find( |
| 154 | + (value) => |
| 155 | + value.scheme === decodedPayment.scheme && |
| 156 | + value.network === decodedPayment.network, |
| 157 | + ); |
| 158 | + if (!selectedPaymentRequirements) { |
| 159 | + return { |
| 160 | + status: 402, |
| 161 | + responseHeaders: { |
| 162 | + "Content-Type": "application/json", |
| 163 | + }, |
| 164 | + responseBody: { |
| 165 | + x402Version, |
| 166 | + error: |
| 167 | + errorMessages?.noMatchingRequirements || |
| 168 | + "Unable to find matching payment requirements", |
| 169 | + accepts: paymentRequirements, |
| 170 | + }, |
| 171 | + }; |
| 172 | + } |
| 173 | + |
| 174 | + return { |
| 175 | + status: 200, |
| 176 | + paymentRequirements, |
| 177 | + decodedPayment, |
| 178 | + selectedPaymentRequirements, |
| 179 | + }; |
| 180 | +} |
| 181 | + |
| 182 | +/** |
| 183 | + * Parses the amount from the given price |
| 184 | + * |
| 185 | + * @param price - The price to parse |
| 186 | + * @param network - The network to get the default asset for |
| 187 | + * @returns The parsed amount or an error message |
| 188 | + */ |
| 189 | +async function processPriceToAtomicAmount( |
| 190 | + price: Money | ERC20TokenAmount, |
| 191 | + network: FacilitatorNetwork, |
| 192 | + facilitator: ReturnType<typeof facilitatorType>, |
| 193 | +): Promise< |
| 194 | + | { maxAmountRequired: string; asset: ERC20TokenAmount["asset"] } |
| 195 | + | { error: string } |
| 196 | +> { |
| 197 | + // Handle USDC amount (string) or token amount (ERC20TokenAmount) |
| 198 | + let maxAmountRequired: string; |
| 199 | + let asset: ERC20TokenAmount["asset"]; |
| 200 | + |
| 201 | + if (typeof price === "string" || typeof price === "number") { |
| 202 | + // USDC amount in dollars |
| 203 | + const parsedAmount = moneySchema.safeParse(price); |
| 204 | + if (!parsedAmount.success) { |
| 205 | + return { |
| 206 | + error: `Invalid price (price: ${price}). Must be in the form "$3.10", 0.10, "0.001", ${parsedAmount.error}`, |
| 207 | + }; |
| 208 | + } |
| 209 | + const parsedUsdAmount = parsedAmount.data; |
| 210 | + const defaultAsset = await getDefaultAsset(network, facilitator); |
| 211 | + if (!defaultAsset) { |
| 212 | + return { |
| 213 | + error: `Unable to get default asset on ${network}. Please specify an asset in the payment requirements.`, |
| 214 | + }; |
| 215 | + } |
| 216 | + asset = defaultAsset; |
| 217 | + maxAmountRequired = (parsedUsdAmount * 10 ** asset.decimals).toString(); |
| 218 | + } else { |
| 219 | + // Token amount in atomic units |
| 220 | + maxAmountRequired = price.amount; |
| 221 | + asset = price.asset; |
| 222 | + } |
| 223 | + |
| 224 | + return { |
| 225 | + maxAmountRequired, |
| 226 | + asset, |
| 227 | + }; |
| 228 | +} |
| 229 | + |
| 230 | +async function getDefaultAsset( |
| 231 | + network: FacilitatorNetwork, |
| 232 | + facilitator: ReturnType<typeof facilitatorType>, |
| 233 | +): Promise<ERC20TokenAmount["asset"] | undefined> { |
| 234 | + const supportedAssets = await facilitator.supported(); |
| 235 | + const chainId = networkToChainId(network); |
| 236 | + const matchingAsset = supportedAssets.kinds.find( |
| 237 | + (supported) => supported.network === `eip155:${chainId}`, |
| 238 | + ); |
| 239 | + const assetConfig = matchingAsset?.extra |
| 240 | + ?.defaultAsset as ERC20TokenAmount["asset"]; |
| 241 | + return assetConfig; |
| 242 | +} |
0 commit comments