@mixrpay/merchant-sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,320 @@
1
+ // src/middleware/nextjs.ts
2
+ import { NextResponse } from "next/server";
3
+
4
+ // src/verify.ts
5
+ import { recoverTypedDataAddress } from "viem";
6
+
7
+ // src/utils.ts
8
+ var USDC_CONTRACTS = {
9
+ 8453: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
10
+ // Base Mainnet
11
+ 84532: "0x036CbD53842c5426634e7929541eC2318f3dCF7e"
12
+ // Base Sepolia
13
+ };
14
+ var DEFAULT_FACILITATOR = "https://x402.org/facilitator";
15
+ function getUSDCDomain(chainId) {
16
+ const verifyingContract = USDC_CONTRACTS[chainId];
17
+ if (!verifyingContract) {
18
+ throw new Error(`Unsupported chain ID: ${chainId}. Supported: ${Object.keys(USDC_CONTRACTS).join(", ")}`);
19
+ }
20
+ return {
21
+ name: "USD Coin",
22
+ version: "2",
23
+ chainId,
24
+ verifyingContract
25
+ };
26
+ }
27
+ var TRANSFER_WITH_AUTHORIZATION_TYPES = {
28
+ TransferWithAuthorization: [
29
+ { name: "from", type: "address" },
30
+ { name: "to", type: "address" },
31
+ { name: "value", type: "uint256" },
32
+ { name: "validAfter", type: "uint256" },
33
+ { name: "validBefore", type: "uint256" },
34
+ { name: "nonce", type: "bytes32" }
35
+ ]
36
+ };
37
+ function usdToMinor(usd) {
38
+ return BigInt(Math.round(usd * 1e6));
39
+ }
40
+ function minorToUsd(minor) {
41
+ return Number(minor) / 1e6;
42
+ }
43
+ function generateNonce() {
44
+ const bytes = new Uint8Array(32);
45
+ crypto.getRandomValues(bytes);
46
+ return `0x${Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("")}`;
47
+ }
48
+ function base64Decode(str) {
49
+ if (typeof Buffer !== "undefined") {
50
+ return Buffer.from(str, "base64").toString("utf-8");
51
+ }
52
+ return atob(str);
53
+ }
54
+
55
+ // src/verify.ts
56
+ async function verifyX402Payment(paymentHeader, options) {
57
+ try {
58
+ let decoded;
59
+ try {
60
+ const jsonStr = base64Decode(paymentHeader);
61
+ decoded = JSON.parse(jsonStr);
62
+ } catch (e) {
63
+ return { valid: false, error: "Invalid payment header encoding" };
64
+ }
65
+ if (!decoded.payload?.authorization || !decoded.payload?.signature) {
66
+ return { valid: false, error: "Missing authorization or signature in payment" };
67
+ }
68
+ const { authorization, signature } = decoded.payload;
69
+ const chainId = options.chainId || 8453;
70
+ const message = {
71
+ from: authorization.from,
72
+ to: authorization.to,
73
+ value: BigInt(authorization.value),
74
+ validAfter: BigInt(authorization.validAfter),
75
+ validBefore: BigInt(authorization.validBefore),
76
+ nonce: authorization.nonce
77
+ };
78
+ const domain = getUSDCDomain(chainId);
79
+ let signerAddress;
80
+ try {
81
+ signerAddress = await recoverTypedDataAddress({
82
+ domain,
83
+ types: TRANSFER_WITH_AUTHORIZATION_TYPES,
84
+ primaryType: "TransferWithAuthorization",
85
+ message,
86
+ signature
87
+ });
88
+ } catch (e) {
89
+ return { valid: false, error: "Failed to recover signer from signature" };
90
+ }
91
+ if (signerAddress.toLowerCase() !== authorization.from.toLowerCase()) {
92
+ return {
93
+ valid: false,
94
+ error: `Signature mismatch: expected ${authorization.from}, got ${signerAddress}`
95
+ };
96
+ }
97
+ const paymentAmount = BigInt(authorization.value);
98
+ if (paymentAmount < options.expectedAmount) {
99
+ return {
100
+ valid: false,
101
+ error: `Insufficient payment: expected ${options.expectedAmount}, got ${paymentAmount}`
102
+ };
103
+ }
104
+ if (authorization.to.toLowerCase() !== options.expectedRecipient.toLowerCase()) {
105
+ return {
106
+ valid: false,
107
+ error: `Wrong recipient: expected ${options.expectedRecipient}, got ${authorization.to}`
108
+ };
109
+ }
110
+ const now = Math.floor(Date.now() / 1e3);
111
+ if (Number(authorization.validBefore) < now) {
112
+ return { valid: false, error: "Payment authorization has expired" };
113
+ }
114
+ if (Number(authorization.validAfter) > now) {
115
+ return { valid: false, error: "Payment authorization is not yet valid" };
116
+ }
117
+ let txHash;
118
+ let settledAt;
119
+ if (!options.skipSettlement) {
120
+ const facilitatorUrl = options.facilitator || DEFAULT_FACILITATOR;
121
+ try {
122
+ const settlementResponse = await fetch(`${facilitatorUrl}/settle`, {
123
+ method: "POST",
124
+ headers: { "Content-Type": "application/json" },
125
+ body: JSON.stringify({
126
+ authorization,
127
+ signature,
128
+ chainId
129
+ })
130
+ });
131
+ if (!settlementResponse.ok) {
132
+ const errorBody = await settlementResponse.text();
133
+ let errorMessage = "Settlement failed";
134
+ try {
135
+ const errorJson = JSON.parse(errorBody);
136
+ errorMessage = errorJson.message || errorJson.error || errorMessage;
137
+ } catch {
138
+ errorMessage = errorBody || errorMessage;
139
+ }
140
+ return { valid: false, error: `Settlement failed: ${errorMessage}` };
141
+ }
142
+ const settlement = await settlementResponse.json();
143
+ txHash = settlement.txHash || settlement.tx_hash;
144
+ settledAt = /* @__PURE__ */ new Date();
145
+ } catch (e) {
146
+ return {
147
+ valid: false,
148
+ error: `Settlement request failed: ${e.message}`
149
+ };
150
+ }
151
+ }
152
+ return {
153
+ valid: true,
154
+ payer: authorization.from,
155
+ amount: minorToUsd(paymentAmount),
156
+ amountMinor: paymentAmount,
157
+ txHash,
158
+ settledAt: settledAt || /* @__PURE__ */ new Date(),
159
+ nonce: authorization.nonce
160
+ };
161
+ } catch (error) {
162
+ return {
163
+ valid: false,
164
+ error: `Verification error: ${error.message}`
165
+ };
166
+ }
167
+ }
168
+
169
+ // src/receipt-fetcher.ts
170
+ var DEFAULT_MIXRPAY_API_URL = process.env.MIXRPAY_BASE_URL || "http://localhost:3000";
171
+ async function fetchPaymentReceipt(params) {
172
+ const apiUrl = params.apiUrl || DEFAULT_MIXRPAY_API_URL;
173
+ const endpoint = `${apiUrl}/api/v1/receipts`;
174
+ try {
175
+ const response = await fetch(endpoint, {
176
+ method: "POST",
177
+ headers: {
178
+ "Content-Type": "application/json"
179
+ },
180
+ body: JSON.stringify({
181
+ tx_hash: params.txHash,
182
+ payer: params.payer,
183
+ recipient: params.recipient,
184
+ amount: params.amount.toString(),
185
+ chain_id: params.chainId
186
+ })
187
+ });
188
+ if (!response.ok) {
189
+ console.warn(`[x402] Receipt fetch failed: ${response.status} ${response.statusText}`);
190
+ return null;
191
+ }
192
+ const data = await response.json();
193
+ return data.receipt || null;
194
+ } catch (error) {
195
+ console.warn("[x402] Receipt fetch error:", error.message);
196
+ return null;
197
+ }
198
+ }
199
+
200
+ // src/middleware/nextjs.ts
201
+ function withX402(config, handler) {
202
+ return async (req) => {
203
+ try {
204
+ const recipient = config.recipient || process.env.MIXRPAY_MERCHANT_ADDRESS;
205
+ if (!recipient) {
206
+ console.error("[x402] No recipient address configured");
207
+ return NextResponse.json(
208
+ { error: "Payment configuration error" },
209
+ { status: 500 }
210
+ );
211
+ }
212
+ const price = config.getPrice ? await config.getPrice(req) : config.price;
213
+ const priceMinor = usdToMinor(price);
214
+ const chainId = config.chainId || 8453;
215
+ const facilitator = config.facilitator || DEFAULT_FACILITATOR;
216
+ const paymentHeader = req.headers.get("x-payment");
217
+ if (!paymentHeader) {
218
+ const nonce = generateNonce();
219
+ const expiresAt = Math.floor(Date.now() / 1e3) + 300;
220
+ const paymentRequired = {
221
+ recipient,
222
+ amount: priceMinor.toString(),
223
+ currency: "USDC",
224
+ chainId,
225
+ facilitator,
226
+ nonce,
227
+ expiresAt,
228
+ description: config.description
229
+ };
230
+ return NextResponse.json(
231
+ { error: "Payment required", payment: paymentRequired },
232
+ {
233
+ status: 402,
234
+ headers: {
235
+ "X-Payment-Required": JSON.stringify(paymentRequired),
236
+ "WWW-Authenticate": `X-402 ${Buffer.from(JSON.stringify(paymentRequired)).toString("base64")}`
237
+ }
238
+ }
239
+ );
240
+ }
241
+ const result = await verifyX402Payment(paymentHeader, {
242
+ expectedAmount: priceMinor,
243
+ expectedRecipient: recipient,
244
+ chainId,
245
+ facilitator,
246
+ skipSettlement: config.testMode
247
+ });
248
+ if (!result.valid) {
249
+ return NextResponse.json(
250
+ { error: "Invalid payment", reason: result.error },
251
+ { status: 402 }
252
+ );
253
+ }
254
+ const receiptMode = config.receiptMode || "webhook";
255
+ if ((receiptMode === "jwt" || receiptMode === "both") && result.txHash && result.payer) {
256
+ try {
257
+ const receipt = await fetchPaymentReceipt({
258
+ txHash: result.txHash,
259
+ payer: result.payer,
260
+ recipient,
261
+ amount: priceMinor,
262
+ chainId,
263
+ apiUrl: config.mixrpayApiUrl
264
+ });
265
+ if (receipt) {
266
+ result.receipt = receipt;
267
+ }
268
+ } catch (receiptError) {
269
+ console.warn("[x402] Failed to fetch JWT receipt:", receiptError);
270
+ }
271
+ }
272
+ if (config.onPayment) {
273
+ await config.onPayment(result, req);
274
+ }
275
+ const response = await handler(req, result);
276
+ if (result.txHash) {
277
+ response.headers.set("X-Payment-TxHash", result.txHash);
278
+ }
279
+ if (result.receipt) {
280
+ response.headers.set("X-Payment-Receipt", result.receipt);
281
+ }
282
+ return response;
283
+ } catch (error) {
284
+ console.error("[x402] Handler error:", error);
285
+ return NextResponse.json(
286
+ { error: "Payment processing error" },
287
+ { status: 500 }
288
+ );
289
+ }
290
+ };
291
+ }
292
+ function createPaymentRequired(options) {
293
+ const priceMinor = usdToMinor(options.amount);
294
+ const nonce = generateNonce();
295
+ const expiresAt = Math.floor(Date.now() / 1e3) + 300;
296
+ const paymentRequired = {
297
+ recipient: options.recipient,
298
+ amount: priceMinor.toString(),
299
+ currency: "USDC",
300
+ chainId: options.chainId || 8453,
301
+ facilitator: options.facilitator || DEFAULT_FACILITATOR,
302
+ nonce,
303
+ expiresAt,
304
+ description: options.description
305
+ };
306
+ return NextResponse.json(
307
+ { error: "Payment required", payment: paymentRequired },
308
+ {
309
+ status: 402,
310
+ headers: {
311
+ "X-Payment-Required": JSON.stringify(paymentRequired)
312
+ }
313
+ }
314
+ );
315
+ }
316
+ export {
317
+ createPaymentRequired,
318
+ withX402
319
+ };
320
+ //# sourceMappingURL=nextjs.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/middleware/nextjs.ts","../../src/verify.ts","../../src/utils.ts","../../src/receipt-fetcher.ts"],"sourcesContent":["/**\n * MixrPay Merchant SDK - Next.js Integration\n * \n * Add x402 payment requirement to Next.js API routes.\n * \n * @example\n * ```typescript\n * // app/api/query/route.ts\n * import { withX402 } from '@mixrpay/merchant-sdk/nextjs';\n * \n * async function handler(req: NextRequest, payment: X402PaymentResult) {\n * // This handler only runs after payment is verified\n * return NextResponse.json({ \n * result: 'success', \n * payer: payment.payer,\n * amount: payment.amount,\n * });\n * }\n * \n * export const POST = withX402({ price: 0.05 }, handler);\n * \n * // With JWT receipts\n * export const POST = withX402({ price: 0.10, receiptMode: 'jwt' }, handler);\n * ```\n */\n\nimport type { NextRequest } from 'next/server';\nimport { NextResponse } from 'next/server';\nimport { verifyX402Payment } from '../verify';\nimport { usdToMinor, generateNonce, DEFAULT_FACILITATOR } from '../utils';\nimport { fetchPaymentReceipt } from '../receipt-fetcher';\nimport type { X402Options, X402PaymentResult, X402PaymentRequired, PriceContext, ReceiptMode } from '../types';\n\nexport interface X402Config {\n /** Price in USD (e.g., 0.05 for 5 cents) */\n price: number;\n /** Your merchant wallet address to receive payments */\n recipient?: string;\n /** Chain ID (default: 8453 for Base) */\n chainId?: number;\n /** Facilitator URL */\n facilitator?: string;\n /** Description of what the payment is for */\n description?: string;\n /** Skip payment verification (for testing) */\n testMode?: boolean;\n /** Custom function to determine price dynamically */\n getPrice?: (req: NextRequest) => number | Promise<number>;\n /** Called after successful payment */\n onPayment?: (payment: X402PaymentResult, req: NextRequest) => void | Promise<void>;\n /**\n * Receipt mode for payment verification responses.\n * - 'jwt': Set X-Payment-Receipt header with JWT (no webhook)\n * - 'webhook': Send webhook only (default, backwards compatible)\n * - 'both': Set JWT header AND send webhook\n */\n receiptMode?: ReceiptMode;\n /** MixrPay API URL for fetching JWT receipts (default: production) */\n mixrpayApiUrl?: string;\n}\n\ntype X402Handler = (req: NextRequest, payment: X402PaymentResult) => Promise<NextResponse> | NextResponse;\n\n/**\n * Wrap a Next.js API route handler with x402 payment requirement.\n * \n * @param config - x402 configuration\n * @param handler - The handler to wrap (receives req and payment result)\n * @returns Wrapped handler function\n */\nexport function withX402(config: X402Config, handler: X402Handler) {\n return async (req: NextRequest): Promise<NextResponse> => {\n try {\n // Get recipient address\n const recipient = config.recipient || process.env.MIXRPAY_MERCHANT_ADDRESS;\n if (!recipient) {\n console.error('[x402] No recipient address configured');\n return NextResponse.json(\n { error: 'Payment configuration error' },\n { status: 500 }\n );\n }\n\n // Determine price\n const price = config.getPrice \n ? await config.getPrice(req)\n : config.price;\n \n const priceMinor = usdToMinor(price);\n const chainId = config.chainId || 8453;\n const facilitator = config.facilitator || DEFAULT_FACILITATOR;\n\n // Check for X-PAYMENT header\n const paymentHeader = req.headers.get('x-payment');\n\n if (!paymentHeader) {\n // Return 402 with payment requirements\n const nonce = generateNonce();\n const expiresAt = Math.floor(Date.now() / 1000) + 300;\n\n const paymentRequired: X402PaymentRequired = {\n recipient,\n amount: priceMinor.toString(),\n currency: 'USDC',\n chainId,\n facilitator,\n nonce,\n expiresAt,\n description: config.description,\n };\n\n return NextResponse.json(\n { error: 'Payment required', payment: paymentRequired },\n { \n status: 402,\n headers: {\n 'X-Payment-Required': JSON.stringify(paymentRequired),\n 'WWW-Authenticate': `X-402 ${Buffer.from(JSON.stringify(paymentRequired)).toString('base64')}`,\n },\n }\n );\n }\n\n // Verify the payment\n const result = await verifyX402Payment(paymentHeader, {\n expectedAmount: priceMinor,\n expectedRecipient: recipient,\n chainId,\n facilitator,\n skipSettlement: config.testMode,\n });\n\n if (!result.valid) {\n return NextResponse.json(\n { error: 'Invalid payment', reason: result.error },\n { status: 402 }\n );\n }\n\n // Handle receipt mode\n const receiptMode = config.receiptMode || 'webhook';\n \n if ((receiptMode === 'jwt' || receiptMode === 'both') && result.txHash && result.payer) {\n try {\n const receipt = await fetchPaymentReceipt({\n txHash: result.txHash,\n payer: result.payer,\n recipient,\n amount: priceMinor,\n chainId,\n apiUrl: config.mixrpayApiUrl,\n });\n \n if (receipt) {\n result.receipt = receipt;\n }\n } catch (receiptError) {\n console.warn('[x402] Failed to fetch JWT receipt:', receiptError);\n // Continue without receipt - payment was still successful\n }\n }\n\n // Call onPayment callback\n if (config.onPayment) {\n await config.onPayment(result, req);\n }\n\n // Call the handler with payment result\n const response = await handler(req, result);\n\n // Add tx hash to response headers\n if (result.txHash) {\n response.headers.set('X-Payment-TxHash', result.txHash);\n }\n\n // Add receipt to response headers\n if (result.receipt) {\n response.headers.set('X-Payment-Receipt', result.receipt);\n }\n\n return response;\n } catch (error) {\n console.error('[x402] Handler error:', error);\n return NextResponse.json(\n { error: 'Payment processing error' },\n { status: 500 }\n );\n }\n };\n}\n\n/**\n * Create a x402 payment requirements response.\n * Useful for building custom payment flows.\n */\nexport function createPaymentRequired(options: {\n recipient: string;\n amount: number;\n chainId?: number;\n facilitator?: string;\n description?: string;\n}): NextResponse {\n const priceMinor = usdToMinor(options.amount);\n const nonce = generateNonce();\n const expiresAt = Math.floor(Date.now() / 1000) + 300;\n\n const paymentRequired: X402PaymentRequired = {\n recipient: options.recipient,\n amount: priceMinor.toString(),\n currency: 'USDC',\n chainId: options.chainId || 8453,\n facilitator: options.facilitator || DEFAULT_FACILITATOR,\n nonce,\n expiresAt,\n description: options.description,\n };\n\n return NextResponse.json(\n { error: 'Payment required', payment: paymentRequired },\n { \n status: 402,\n headers: {\n 'X-Payment-Required': JSON.stringify(paymentRequired),\n },\n }\n );\n}\n\nexport type { X402PaymentResult };\n\n","/**\n * MixrPay Merchant SDK - Payment Verification\n */\n\nimport { recoverTypedDataAddress } from 'viem';\nimport type { \n X402PaymentResult, \n X402PaymentPayload, \n VerifyOptions,\n TransferWithAuthorizationMessage,\n} from './types';\nimport { \n getUSDCDomain, \n TRANSFER_WITH_AUTHORIZATION_TYPES, \n base64Decode,\n minorToUsd,\n DEFAULT_FACILITATOR,\n} from './utils';\n\n// =============================================================================\n// Payment Verification\n// =============================================================================\n\n/**\n * Verify an X-PAYMENT header and optionally settle the payment.\n * \n * @param paymentHeader - The X-PAYMENT header value (base64 encoded JSON)\n * @param options - Verification options\n * @returns Payment verification result\n * \n * @example\n * ```typescript\n * const result = await verifyX402Payment(req.headers['x-payment'], {\n * expectedAmount: 50000n, // 0.05 USDC\n * expectedRecipient: '0x...',\n * });\n * \n * if (result.valid) {\n * console.log(`Payment from ${result.payer}: $${result.amount}`);\n * }\n * ```\n */\nexport async function verifyX402Payment(\n paymentHeader: string,\n options: VerifyOptions\n): Promise<X402PaymentResult> {\n try {\n // 1. Decode the X-PAYMENT header\n let decoded: X402PaymentPayload;\n try {\n const jsonStr = base64Decode(paymentHeader);\n decoded = JSON.parse(jsonStr);\n } catch (e) {\n return { valid: false, error: 'Invalid payment header encoding' };\n }\n\n // 2. Validate payload structure\n if (!decoded.payload?.authorization || !decoded.payload?.signature) {\n return { valid: false, error: 'Missing authorization or signature in payment' };\n }\n\n const { authorization, signature } = decoded.payload;\n const chainId = options.chainId || 8453;\n\n // 3. Build EIP-712 message for verification\n const message: TransferWithAuthorizationMessage = {\n from: authorization.from as `0x${string}`,\n to: authorization.to as `0x${string}`,\n value: BigInt(authorization.value),\n validAfter: BigInt(authorization.validAfter),\n validBefore: BigInt(authorization.validBefore),\n nonce: authorization.nonce as `0x${string}`,\n };\n\n // 4. Recover signer address\n const domain = getUSDCDomain(chainId);\n let signerAddress: string;\n \n try {\n signerAddress = await recoverTypedDataAddress({\n domain,\n types: TRANSFER_WITH_AUTHORIZATION_TYPES,\n primaryType: 'TransferWithAuthorization',\n message,\n signature: signature as `0x${string}`,\n });\n } catch (e) {\n return { valid: false, error: 'Failed to recover signer from signature' };\n }\n\n // 5. Verify signer matches the 'from' address\n if (signerAddress.toLowerCase() !== authorization.from.toLowerCase()) {\n return { \n valid: false, \n error: `Signature mismatch: expected ${authorization.from}, got ${signerAddress}` \n };\n }\n\n // 6. Verify payment amount\n const paymentAmount = BigInt(authorization.value);\n if (paymentAmount < options.expectedAmount) {\n return { \n valid: false, \n error: `Insufficient payment: expected ${options.expectedAmount}, got ${paymentAmount}` \n };\n }\n\n // 7. Verify recipient\n if (authorization.to.toLowerCase() !== options.expectedRecipient.toLowerCase()) {\n return { \n valid: false, \n error: `Wrong recipient: expected ${options.expectedRecipient}, got ${authorization.to}` \n };\n }\n\n // 8. Check expiration\n const now = Math.floor(Date.now() / 1000);\n if (Number(authorization.validBefore) < now) {\n return { valid: false, error: 'Payment authorization has expired' };\n }\n\n // 9. Check validAfter\n if (Number(authorization.validAfter) > now) {\n return { valid: false, error: 'Payment authorization is not yet valid' };\n }\n\n // 10. Submit to facilitator for settlement (unless skipped)\n let txHash: string | undefined;\n let settledAt: Date | undefined;\n\n if (!options.skipSettlement) {\n const facilitatorUrl = options.facilitator || DEFAULT_FACILITATOR;\n \n try {\n const settlementResponse = await fetch(`${facilitatorUrl}/settle`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ \n authorization, \n signature,\n chainId,\n }),\n });\n\n if (!settlementResponse.ok) {\n const errorBody = await settlementResponse.text();\n let errorMessage = 'Settlement failed';\n try {\n const errorJson = JSON.parse(errorBody);\n errorMessage = errorJson.message || errorJson.error || errorMessage;\n } catch {\n errorMessage = errorBody || errorMessage;\n }\n return { valid: false, error: `Settlement failed: ${errorMessage}` };\n }\n\n const settlement = await settlementResponse.json() as { txHash?: string; tx_hash?: string };\n txHash = settlement.txHash || settlement.tx_hash;\n settledAt = new Date();\n } catch (e) {\n return { \n valid: false, \n error: `Settlement request failed: ${(e as Error).message}` \n };\n }\n }\n\n // Success!\n return {\n valid: true,\n payer: authorization.from,\n amount: minorToUsd(paymentAmount),\n amountMinor: paymentAmount,\n txHash,\n settledAt: settledAt || new Date(),\n nonce: authorization.nonce,\n };\n\n } catch (error) {\n return { \n valid: false, \n error: `Verification error: ${(error as Error).message}` \n };\n }\n}\n\n/**\n * Parse and validate an X-PAYMENT header without settlement.\n * Useful for checking if a payment is structurally valid before processing.\n */\nexport async function parseX402Payment(\n paymentHeader: string,\n chainId: number = 8453\n): Promise<{\n valid: boolean;\n error?: string;\n payer?: string;\n recipient?: string;\n amount?: number;\n amountMinor?: bigint;\n expiresAt?: Date;\n}> {\n try {\n const jsonStr = base64Decode(paymentHeader);\n const decoded: X402PaymentPayload = JSON.parse(jsonStr);\n\n if (!decoded.payload?.authorization) {\n return { valid: false, error: 'Missing authorization in payment' };\n }\n\n const { authorization, signature } = decoded.payload;\n\n // Verify signature\n const domain = getUSDCDomain(chainId);\n const message: TransferWithAuthorizationMessage = {\n from: authorization.from as `0x${string}`,\n to: authorization.to as `0x${string}`,\n value: BigInt(authorization.value),\n validAfter: BigInt(authorization.validAfter),\n validBefore: BigInt(authorization.validBefore),\n nonce: authorization.nonce as `0x${string}`,\n };\n\n const signerAddress = await recoverTypedDataAddress({\n domain,\n types: TRANSFER_WITH_AUTHORIZATION_TYPES,\n primaryType: 'TransferWithAuthorization',\n message,\n signature: signature as `0x${string}`,\n });\n\n if (signerAddress.toLowerCase() !== authorization.from.toLowerCase()) {\n return { valid: false, error: 'Signature mismatch' };\n }\n\n const amountMinor = BigInt(authorization.value);\n \n return {\n valid: true,\n payer: authorization.from,\n recipient: authorization.to,\n amount: minorToUsd(amountMinor),\n amountMinor,\n expiresAt: new Date(Number(authorization.validBefore) * 1000),\n };\n } catch (error) {\n return { valid: false, error: `Parse error: ${(error as Error).message}` };\n }\n}\n\n","/**\n * MixrPay Merchant SDK - Utilities\n */\n\nimport type { EIP712Domain } from './types';\n\n// =============================================================================\n// USDC Constants by Chain\n// =============================================================================\n\nexport const USDC_CONTRACTS: Record<number, `0x${string}`> = {\n 8453: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913', // Base Mainnet\n 84532: '0x036CbD53842c5426634e7929541eC2318f3dCF7e', // Base Sepolia\n};\n\nexport const DEFAULT_FACILITATOR = 'https://x402.org/facilitator';\n\n// =============================================================================\n// EIP-712 Domain\n// =============================================================================\n\nexport function getUSDCDomain(chainId: number): EIP712Domain {\n const verifyingContract = USDC_CONTRACTS[chainId];\n if (!verifyingContract) {\n throw new Error(`Unsupported chain ID: ${chainId}. Supported: ${Object.keys(USDC_CONTRACTS).join(', ')}`);\n }\n\n return {\n name: 'USD Coin',\n version: '2',\n chainId,\n verifyingContract,\n };\n}\n\n// EIP-712 types for TransferWithAuthorization\nexport const TRANSFER_WITH_AUTHORIZATION_TYPES = {\n TransferWithAuthorization: [\n { name: 'from', type: 'address' },\n { name: 'to', type: 'address' },\n { name: 'value', type: 'uint256' },\n { name: 'validAfter', type: 'uint256' },\n { name: 'validBefore', type: 'uint256' },\n { name: 'nonce', type: 'bytes32' },\n ],\n} as const;\n\n// =============================================================================\n// Utility Functions\n// =============================================================================\n\n/**\n * Convert USD dollars to USDC minor units (6 decimals)\n */\nexport function usdToMinor(usd: number): bigint {\n return BigInt(Math.round(usd * 1_000_000));\n}\n\n/**\n * Convert USDC minor units to USD dollars\n */\nexport function minorToUsd(minor: bigint): number {\n return Number(minor) / 1_000_000;\n}\n\n/**\n * Generate a random nonce for x402 payments\n */\nexport function generateNonce(): `0x${string}` {\n const bytes = new Uint8Array(32);\n crypto.getRandomValues(bytes);\n return `0x${Array.from(bytes).map(b => b.toString(16).padStart(2, '0')).join('')}` as `0x${string}`;\n}\n\n/**\n * Check if an address is valid\n */\nexport function isValidAddress(address: string): address is `0x${string}` {\n return /^0x[a-fA-F0-9]{40}$/.test(address);\n}\n\n/**\n * Normalize an address to lowercase checksum format\n */\nexport function normalizeAddress(address: string): `0x${string}` {\n if (!isValidAddress(address)) {\n throw new Error(`Invalid address: ${address}`);\n }\n return address.toLowerCase() as `0x${string}`;\n}\n\n/**\n * Safe base64 decode that works in both Node.js and browsers\n */\nexport function base64Decode(str: string): string {\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(str, 'base64').toString('utf-8');\n }\n return atob(str);\n}\n\n/**\n * Safe base64 encode that works in both Node.js and browsers\n */\nexport function base64Encode(str: string): string {\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(str, 'utf-8').toString('base64');\n }\n return btoa(str);\n}\n\n","/**\n * MixrPay Merchant SDK - Receipt Fetcher\n * \n * Internal utility to fetch JWT receipts from MixrPay API after settlement.\n * Used by x402 middleware to get receipts for the X-Payment-Receipt header.\n */\n\n// =============================================================================\n// Constants\n// =============================================================================\n\nconst DEFAULT_MIXRPAY_API_URL = process.env.MIXRPAY_BASE_URL || 'http://localhost:3000';\n\n// =============================================================================\n// Types\n// =============================================================================\n\nexport interface FetchReceiptParams {\n /** Settlement transaction hash */\n txHash: string;\n /** Payer address */\n payer: string;\n /** Recipient address */\n recipient: string;\n /** Amount in USDC minor units */\n amount: bigint;\n /** Chain ID */\n chainId: number;\n /** Custom MixrPay API URL (optional) */\n apiUrl?: string;\n}\n\ninterface ReceiptResponse {\n receipt: string;\n expiresAt: string;\n}\n\n// =============================================================================\n// Receipt Fetching\n// =============================================================================\n\n/**\n * Fetch a JWT payment receipt from MixrPay API.\n * \n * This is called by the x402 middleware after successful payment verification\n * when receiptMode is 'jwt' or 'both'.\n * \n * @param params - Receipt request parameters\n * @returns JWT receipt string, or null if not available\n */\nexport async function fetchPaymentReceipt(params: FetchReceiptParams): Promise<string | null> {\n const apiUrl = params.apiUrl || DEFAULT_MIXRPAY_API_URL;\n const endpoint = `${apiUrl}/api/v1/receipts`;\n\n try {\n const response = await fetch(endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n tx_hash: params.txHash,\n payer: params.payer,\n recipient: params.recipient,\n amount: params.amount.toString(),\n chain_id: params.chainId,\n }),\n });\n\n if (!response.ok) {\n // Log but don't throw - receipt is optional\n console.warn(`[x402] Receipt fetch failed: ${response.status} ${response.statusText}`);\n return null;\n }\n\n const data = await response.json() as ReceiptResponse;\n return data.receipt || null;\n } catch (error) {\n // Log but don't throw - payment was successful, receipt is optional\n console.warn('[x402] Receipt fetch error:', (error as Error).message);\n return null;\n }\n}\n\n/**\n * Generate a local receipt for testing purposes.\n * \n * WARNING: This generates an unsigned receipt that will NOT verify.\n * Use only for local development and testing.\n * \n * @param params - Receipt parameters\n * @returns Mock JWT-like string (not cryptographically signed)\n */\nexport function generateMockReceipt(params: FetchReceiptParams): string {\n const header = {\n alg: 'none',\n typ: 'JWT',\n };\n\n const payload = {\n paymentId: `mock_${Date.now()}`,\n amount: params.amount.toString(),\n amountUsd: Number(params.amount) / 1_000_000,\n payer: params.payer,\n recipient: params.recipient,\n chainId: params.chainId,\n txHash: params.txHash,\n settledAt: new Date().toISOString(),\n iat: Math.floor(Date.now() / 1000),\n exp: Math.floor(Date.now() / 1000) + 3600,\n _mock: true,\n };\n\n const base64Header = Buffer.from(JSON.stringify(header)).toString('base64url');\n const base64Payload = Buffer.from(JSON.stringify(payload)).toString('base64url');\n\n // Mock signature (not cryptographically valid)\n return `${base64Header}.${base64Payload}.mock_signature_for_testing_only`;\n}\n\n"],"mappings":";AA2BA,SAAS,oBAAoB;;;ACvB7B,SAAS,+BAA+B;;;ACMjC,IAAM,iBAAgD;AAAA,EAC3D,MAAM;AAAA;AAAA,EACN,OAAO;AAAA;AACT;AAEO,IAAM,sBAAsB;AAM5B,SAAS,cAAc,SAA+B;AAC3D,QAAM,oBAAoB,eAAe,OAAO;AAChD,MAAI,CAAC,mBAAmB;AACtB,UAAM,IAAI,MAAM,yBAAyB,OAAO,gBAAgB,OAAO,KAAK,cAAc,EAAE,KAAK,IAAI,CAAC,EAAE;AAAA,EAC1G;AAEA,SAAO;AAAA,IACL,MAAM;AAAA,IACN,SAAS;AAAA,IACT;AAAA,IACA;AAAA,EACF;AACF;AAGO,IAAM,oCAAoC;AAAA,EAC/C,2BAA2B;AAAA,IACzB,EAAE,MAAM,QAAQ,MAAM,UAAU;AAAA,IAChC,EAAE,MAAM,MAAM,MAAM,UAAU;AAAA,IAC9B,EAAE,MAAM,SAAS,MAAM,UAAU;AAAA,IACjC,EAAE,MAAM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T,SAAS,OAAO;AACd,cAAQ,MAAM,yBAAyB,KAAK;AAC5C,aAAO,aAAa;AAAA,QAClB,EAAE,OAAO,2BAA2B;AAAA,QACpC,EAAE,QAAQ,IAAI;AAAA,MAChB;AAAA,IACF;AAAA,EACF;AACF;AAMO,SAAS,sBAAsB,SAMrB;AACf,QAAM,aAAa,WAAW,QAAQ,MAAM;AAC5C,QAAM,QAAQ,cAAc;AAC5B,QAAM,YAAY,KAAK,MAAM,KAAK,IAAI,IAAI,GAAI,IAAI;AAElD,QAAM,kBAAuC;AAAA,IAC3C,WAAW,QAAQ;AAAA,IACnB,QAAQ,WAAW,SAAS;AAAA,IAC5B,UAAU;AAAA,IACV,SAAS,QAAQ,WAAW;AAAA,IAC5B,aAAa,QAAQ,eAAe;AAAA,IACpC;AAAA,IACA;AAAA,IACA,aAAa,QAAQ;AAAA,EACvB;AAEA,SAAO,aAAa;AAAA,IAClB,EAAE,OAAO,oBAAoB,SAAS,gBAAgB;AAAA,IACtD;AAAA,MACE,QAAQ;AAAA,MACR,SAAS;AAAA,QACP,sBAAsB,KAAK,UAAU,eAAe;AAAA,MACtD;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
@@ -0,0 +1,166 @@
1
+ /**
2
+ * MixrPay Merchant SDK - Type definitions
3
+ */
4
+ interface X402Options {
5
+ /** Price in USD (e.g., 0.05 for 5 cents) */
6
+ price: number;
7
+ /** Your merchant wallet address to receive payments */
8
+ recipient?: string;
9
+ /** Chain ID (default: 8453 for Base) */
10
+ chainId?: number;
11
+ /** Facilitator URL for payment settlement */
12
+ facilitator?: string;
13
+ /** Description of what the payment is for */
14
+ description?: string;
15
+ /** Custom function to determine price dynamically */
16
+ getPrice?: (context: PriceContext) => number | Promise<number>;
17
+ /** Called after successful payment verification */
18
+ onPayment?: (payment: X402PaymentResult) => void | Promise<void>;
19
+ /** Skip payment for certain requests (return true to skip) */
20
+ skip?: (context: SkipContext) => boolean | Promise<boolean>;
21
+ /** Allow test payments (for development) */
22
+ testMode?: boolean;
23
+ /**
24
+ * Receipt mode for payment verification responses.
25
+ * - 'jwt': Set X-Payment-Receipt header with JWT (no webhook)
26
+ * - 'webhook': Send webhook only (default, backwards compatible)
27
+ * - 'both': Set JWT header AND send webhook
28
+ */
29
+ receiptMode?: ReceiptMode;
30
+ /** MixrPay API URL for fetching JWT receipts (default: production) */
31
+ mixrpayApiUrl?: string;
32
+ }
33
+ interface PriceContext {
34
+ /** Request path */
35
+ path: string;
36
+ /** Request method */
37
+ method: string;
38
+ /** Request headers */
39
+ headers: Record<string, string | string[] | undefined>;
40
+ /** Request body (if parsed) */
41
+ body?: unknown;
42
+ }
43
+ type SkipContext = PriceContext;
44
+ interface X402PaymentResult {
45
+ /** Whether the payment is valid */
46
+ valid: boolean;
47
+ /** Error message if invalid */
48
+ error?: string;
49
+ /** Address that paid (if valid) */
50
+ payer?: string;
51
+ /** Amount in USDC (major units, e.g., 0.05) */
52
+ amount?: number;
53
+ /** Amount in USDC minor units (e.g., 50000) */
54
+ amountMinor?: bigint;
55
+ /** Settlement transaction hash */
56
+ txHash?: string;
57
+ /** When the payment was settled */
58
+ settledAt?: Date;
59
+ /** The nonce used for this payment */
60
+ nonce?: string;
61
+ /** JWT payment receipt (when receiptMode is 'jwt' or 'both') */
62
+ receipt?: string;
63
+ }
64
+ interface X402PaymentRequired {
65
+ /** Recipient wallet address */
66
+ recipient: string;
67
+ /** Amount in USDC minor units (6 decimals) as string */
68
+ amount: string;
69
+ /** Currency code */
70
+ currency: string;
71
+ /** Chain ID */
72
+ chainId: number;
73
+ /** Facilitator URL */
74
+ facilitator: string;
75
+ /** Unique nonce for this payment request */
76
+ nonce: string;
77
+ /** Unix timestamp when payment requirements expire */
78
+ expiresAt: number;
79
+ /** Description of the payment */
80
+ description?: string;
81
+ }
82
+ interface X402PaymentPayload {
83
+ x402Version: number;
84
+ scheme: 'exact';
85
+ network: 'base' | 'base-sepolia';
86
+ payload: {
87
+ signature: string;
88
+ authorization: {
89
+ from: string;
90
+ to: string;
91
+ value: string;
92
+ validAfter: string;
93
+ validBefore: string;
94
+ nonce: string;
95
+ };
96
+ };
97
+ }
98
+ interface EIP712Domain {
99
+ name: string;
100
+ version: string;
101
+ chainId: number;
102
+ verifyingContract: `0x${string}`;
103
+ }
104
+ interface TransferWithAuthorizationMessage {
105
+ from: `0x${string}`;
106
+ to: `0x${string}`;
107
+ value: bigint;
108
+ validAfter: bigint;
109
+ validBefore: bigint;
110
+ nonce: `0x${string}`;
111
+ }
112
+ interface VerifyOptions {
113
+ /** Expected amount in USDC minor units */
114
+ expectedAmount: bigint;
115
+ /** Expected recipient address */
116
+ expectedRecipient: string;
117
+ /** Chain ID (default: 8453 for Base) */
118
+ chainId?: number;
119
+ /** Facilitator URL */
120
+ facilitator?: string;
121
+ /** Skip on-chain settlement (for testing) */
122
+ skipSettlement?: boolean;
123
+ }
124
+ /**
125
+ * Verified payment receipt from MixrPay.
126
+ */
127
+ interface PaymentReceipt {
128
+ /** Unique payment ID */
129
+ paymentId: string;
130
+ /** Amount in USDC minor units (6 decimals) as string */
131
+ amount: string;
132
+ /** Amount in USD */
133
+ amountUsd: number;
134
+ /** Payer wallet address */
135
+ payer: string;
136
+ /** Recipient wallet address */
137
+ recipient: string;
138
+ /** Blockchain chain ID */
139
+ chainId: number;
140
+ /** Settlement transaction hash */
141
+ txHash: string;
142
+ /** When the payment was settled (ISO string) */
143
+ settledAt: string;
144
+ /** When the receipt was issued */
145
+ issuedAt?: Date;
146
+ /** When the receipt expires */
147
+ expiresAt?: Date;
148
+ }
149
+ /**
150
+ * Options for verifying a payment receipt.
151
+ */
152
+ interface VerifyReceiptOptions {
153
+ /** Custom JWKS URL (default: MixrPay production JWKS) */
154
+ jwksUrl?: string;
155
+ /** Expected issuer (for additional validation) */
156
+ issuer?: string;
157
+ }
158
+ /**
159
+ * Receipt mode for x402 middleware.
160
+ * - 'jwt': Only generate JWT receipt (no webhook)
161
+ * - 'webhook': Only send webhook (default, backwards compatible)
162
+ * - 'both': Generate JWT receipt AND send webhook
163
+ */
164
+ type ReceiptMode = 'jwt' | 'webhook' | 'both';
165
+
166
+ export type { EIP712Domain as E, PaymentReceipt as P, ReceiptMode as R, SkipContext as S, TransferWithAuthorizationMessage as T, VerifyOptions as V, X402PaymentResult as X, VerifyReceiptOptions as a, X402Options as b, X402PaymentRequired as c, X402PaymentPayload as d, PriceContext as e };