-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathx402.ts
More file actions
205 lines (180 loc) · 6.32 KB
/
Copy pathx402.ts
File metadata and controls
205 lines (180 loc) · 6.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
/**
* Copyright 2026 Circle Internet Group, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
import { BatchFacilitatorClient } from "@circle-fin/x402-batching/server";
import { createClient } from "@supabase/supabase-js";
import { NextRequest, NextResponse } from "next/server";
// Arc Testnet contract addresses (from @circle-fin/x402-batching SDK)
const ARC_TESTNET_NETWORK = "eip155:5042002";
const ARC_TESTNET_USDC = "0x3600000000000000000000000000000000000000";
const ARC_TESTNET_GATEWAY_WALLET = "0x0077777d7EBA4688BDeF3E311b846F25870A19B9";
export const sellerAddress = process.env.SELLER_ADDRESS as `0x${string}`;
export const facilitator = new BatchFacilitatorClient();
export const supabase = createClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.SUPABASE_SERVICE_ROLE_KEY!,
);
interface PaymentPayload {
x402Version: number;
resource?: { url: string; description: string; mimeType: string };
accepted?: Record<string, unknown>;
payload: Record<string, unknown>;
extensions?: Record<string, unknown>;
}
/**
* `payTo` defaults to the platform seller (Circle's original behaviour), but
* TaskMesh overrides it per task so the bounty settles to the WORKER that
* actually did the job. That's what makes this a marketplace rather than a
* single-seller shop.
*/
export function buildPaymentRequirements(
price: string,
payTo: `0x${string}` = sellerAddress,
) {
// Parse dollar amount to USDC atomic units (6 decimals)
const amount = Math.round(parseFloat(price.replace("$", "")) * 1_000_000);
return {
scheme: "exact" as const,
network: ARC_TESTNET_NETWORK,
asset: ARC_TESTNET_USDC,
amount: amount.toString(),
payTo,
// 30 days. Circle Gateway rejects shorter authorization windows with
// `authorization_validity_too_short` — both the SDK default and this repo's
// original value (345600 / 4 days) fail verification. 7 days passes verify
// but still fails settle. Do not lower this.
maxTimeoutSeconds: 2592000,
extra: {
name: "GatewayWalletBatched",
version: "1",
verifyingContract: ARC_TESTNET_GATEWAY_WALLET,
},
};
}
/**
* Wraps a Next.js route handler with Circle Gateway payment verification.
*
* Follows fred-mvp's approach: manually constructs payment requirements with
* the Gateway batching `extra` field and calls BatchFacilitatorClient directly.
*/
export function withGateway(
handler: (req: NextRequest) => Promise<NextResponse>,
price: string,
endpoint: string,
) {
const requirements = buildPaymentRequirements(price);
return async (req: NextRequest) => {
const paymentSignature = req.headers.get("payment-signature");
// No payment — return 402 with Gateway batching payment requirements
if (!paymentSignature) {
console.log(`[x402] 402 Payment Required: ${endpoint}`);
const paymentRequired = {
x402Version: 2,
resource: {
url: endpoint,
description: `Paid resource (${price} USDC)`,
mimeType: "application/json",
},
accepts: [requirements],
};
return new NextResponse(JSON.stringify({}), {
status: 402,
headers: {
"Content-Type": "application/json",
"PAYMENT-REQUIRED": Buffer.from(
JSON.stringify(paymentRequired),
).toString("base64"),
},
});
}
// Payment present — verify and settle via Circle Gateway
try {
const paymentPayload: PaymentPayload = JSON.parse(
Buffer.from(paymentSignature, "base64").toString("utf-8"),
);
const verifyResult = await facilitator.verify(
paymentPayload,
requirements,
);
if (!verifyResult.isValid) {
return NextResponse.json(
{
error: "Payment verification failed",
reason: verifyResult.invalidReason,
},
{ status: 402 },
);
}
const settleResult = await facilitator.settle(
paymentPayload,
requirements,
);
if (!settleResult.success) {
console.error(
`[x402] Settlement failed for ${endpoint}: ${settleResult.errorReason}`,
);
return NextResponse.json(
{
error: "Payment settlement failed",
reason: settleResult.errorReason,
},
{ status: 402 },
);
}
// Record payment event in Supabase
const amountUsdc = (
Number(requirements.amount) / 1e6
).toString();
const payer = settleResult.payer ?? verifyResult.payer ?? "unknown";
const { error } = await supabase.from("payment_events").insert({
endpoint,
payer,
amount_usdc: amountUsdc,
network: requirements.network,
gateway_tx: settleResult.transaction ?? null,
raw: { requirements, settleResult },
});
if (error) {
console.error("Failed to record payment event:", error.message);
}
console.log(
`[x402] Payment settled: ${endpoint} — ${amountUsdc} USDC from ${payer}`,
);
// Call the actual route handler
const response = await handler(req);
// Forward settlement info to the client
const settleResponseHeader = Buffer.from(
JSON.stringify({
success: true,
transaction: settleResult.transaction,
network: requirements.network,
payer,
}),
).toString("base64");
response.headers.set("PAYMENT-RESPONSE", settleResponseHeader);
return response;
} catch (error) {
const message =
error instanceof Error ? error.message : String(error);
console.error("[x402] Payment processing error:", message);
return NextResponse.json(
{ error: "Payment processing error", message },
{ status: 500 },
);
}
};
}