-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbazaar.ts
More file actions
331 lines (294 loc) · 9.46 KB
/
bazaar.ts
File metadata and controls
331 lines (294 loc) · 9.46 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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
/**
* Facilitator with Discovery Extension Example
*
* Demonstrates how to create a facilitator with bazaar discovery extension that
* catalogs discovered x402 resources.
*/
import { base58 } from "@scure/base";
import { createKeyPairSignerFromBytes } from "@solana/kit";
import { x402Facilitator } from "@x402/core/facilitator";
import {
PaymentPayload,
PaymentRequirements,
SettleResponse,
VerifyResponse,
} from "@x402/core/types";
import { toFacilitatorEvmSigner } from "@x402/evm";
import { ExactEvmScheme } from "@x402/evm/exact/facilitator";
import { toFacilitatorSvmSigner } from "@x402/svm";
import { ExactSvmScheme } from "@x402/svm/exact/facilitator";
import { extractDiscoveryInfo, DiscoveryInfo } from "@x402/extensions/bazaar";
import dotenv from "dotenv";
import express from "express";
import { createWalletClient, http, publicActions } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { baseSepolia } from "viem/chains";
dotenv.config();
// Configuration
const PORT = process.env.PORT || "4022";
// Configuration - optional per network
const evmPrivateKey = process.env.EVM_PRIVATE_KEY as `0x${string}` | undefined;
const svmPrivateKey = process.env.SVM_PRIVATE_KEY as string | undefined;
// Validate at least one private key is provided
if (!evmPrivateKey && !svmPrivateKey) {
console.error(
"❌ At least one of EVM_PRIVATE_KEY or SVM_PRIVATE_KEY is required",
);
process.exit(1);
}
// Network configuration
const EVM_NETWORK = "eip155:84532"; // Base Sepolia
const SVM_NETWORK = "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1"; // Solana Devnet
// DiscoveredResource represents a discovered x402 resource for the bazaar catalog
interface DiscoveredResource {
resource: string;
description?: string;
mimeType?: string;
type: string;
x402Version: number;
accepts: PaymentRequirements[];
discoveryInfo?: DiscoveryInfo;
lastUpdated: string;
}
// BazaarCatalog stores discovered resources
class BazaarCatalog {
private resources: Map<string, DiscoveredResource> = new Map();
add(res: DiscoveredResource): void {
this.resources.set(res.resource, res);
}
getAll(): DiscoveredResource[] {
return Array.from(this.resources.values());
}
}
const bazaarCatalog = new BazaarCatalog();
// Initialize the x402 Facilitator with discovery hooks
const facilitator = new x402Facilitator()
.onBeforeVerify(async context => {
console.log("Before verify", context);
})
.onAfterVerify(async context => {
console.log("✅ Payment verified");
// Extract discovered resource from payment for bazaar catalog
try {
const discovered = extractDiscoveryInfo(
context.paymentPayload,
context.requirements,
true, // validate
);
if (discovered) {
console.log(` 📝 Discovered resource: ${discovered.resourceUrl}`);
console.log(` 📝 Description: ${discovered.description}`);
console.log(` 📝 MimeType: ${discovered.mimeType}`);
console.log(` 📝 Method: ${discovered.method}`);
console.log(` 📝 X402Version: ${discovered.x402Version}`);
bazaarCatalog.add({
resource: discovered.resourceUrl,
description: discovered.description,
mimeType: discovered.mimeType,
type: "http",
x402Version: discovered.x402Version,
accepts: [context.requirements],
discoveryInfo: discovered.discoveryInfo,
lastUpdated: new Date().toISOString(),
});
console.log(" ✅ Added to bazaar catalog");
}
} catch (err) {
console.log(` ⚠️ Failed to extract discovery info: ${err}`);
}
})
.onVerifyFailure(async context => {
console.log("Verify failure", context);
})
.onBeforeSettle(async context => {
console.log("Before settle", context);
})
.onAfterSettle(async context => {
console.log(`🎉 Payment settled: ${context.result.transaction}`);
})
.onSettleFailure(async context => {
console.log("Settle failure", context);
});
// Register EVM scheme if private key is provided
if (evmPrivateKey) {
const evmAccount = privateKeyToAccount(evmPrivateKey);
console.info(`EVM Facilitator account: ${evmAccount.address}`);
// Create a Viem client with both wallet and public capabilities
const viemClient = createWalletClient({
account: evmAccount,
chain: baseSepolia,
transport: http(),
}).extend(publicActions);
const evmSigner = toFacilitatorEvmSigner({
getCode: (args: { address: `0x${string}` }) => viemClient.getCode(args),
address: evmAccount.address,
readContract: (args: {
address: `0x${string}`;
abi: readonly unknown[];
functionName: string;
args?: readonly unknown[];
}) =>
viemClient.readContract({
...args,
args: args.args || [],
}),
verifyTypedData: (args: {
address: `0x${string}`;
domain: Record<string, unknown>;
types: Record<string, unknown>;
primaryType: string;
message: Record<string, unknown>;
signature: `0x${string}`;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
}) => viemClient.verifyTypedData(args as any),
writeContract: (args: {
address: `0x${string}`;
abi: readonly unknown[];
functionName: string;
args: readonly unknown[];
}) =>
viemClient.writeContract({
...args,
args: args.args || [],
}),
sendTransaction: (args: { to: `0x${string}`; data: `0x${string}` }) =>
viemClient.sendTransaction(args),
waitForTransactionReceipt: (args: { hash: `0x${string}` }) =>
viemClient.waitForTransactionReceipt(args),
});
facilitator.register(
EVM_NETWORK,
new ExactEvmScheme(evmSigner, { deployERC4337WithEIP6492: true }),
);
}
// Register SVM scheme if private key is provided
if (svmPrivateKey) {
const svmAccount = await createKeyPairSignerFromBytes(
base58.decode(svmPrivateKey),
);
console.info(`SVM Facilitator account: ${svmAccount.address}`);
const svmSigner = toFacilitatorSvmSigner(svmAccount);
facilitator.register(SVM_NETWORK, new ExactSvmScheme(svmSigner));
}
// Initialize Express app
const app = express();
app.use(express.json());
/**
* POST /verify
* Verify a payment against requirements
*
* Note: Payment tracking and bazaar discovery are handled by lifecycle hooks
*/
app.post("/verify", async (req, res) => {
try {
const { paymentPayload, paymentRequirements } = req.body as {
paymentPayload: PaymentPayload;
paymentRequirements: PaymentRequirements;
};
if (!paymentPayload || !paymentRequirements) {
return res.status(400).json({
error: "Missing paymentPayload or paymentRequirements",
});
}
// Hooks will automatically:
// - Track verified payment (onAfterVerify)
// - Extract and catalog discovery info (onAfterVerify)
const response: VerifyResponse = await facilitator.verify(
paymentPayload,
paymentRequirements,
);
res.json(response);
} catch (error) {
console.error("Verify error:", error);
res.status(500).json({
error: error instanceof Error ? error.message : "Unknown error",
});
}
});
/**
* POST /settle
* Settle a payment on-chain
*/
app.post("/settle", async (req, res) => {
try {
const { paymentPayload, paymentRequirements } = req.body;
if (!paymentPayload || !paymentRequirements) {
return res.status(400).json({
error: "Missing paymentPayload or paymentRequirements",
});
}
const response: SettleResponse = await facilitator.settle(
paymentPayload as PaymentPayload,
paymentRequirements as PaymentRequirements,
);
res.json(response);
} catch (error) {
console.error("Settle error:", error);
// Check if this was an abort from hook
if (
error instanceof Error &&
error.message.includes("Settlement aborted:")
) {
return res.json({
success: false,
errorReason: error.message.replace("Settlement aborted: ", ""),
network: req.body?.paymentPayload?.network || "unknown",
} as SettleResponse);
}
res.status(500).json({
error: error instanceof Error ? error.message : "Unknown error",
});
}
});
/**
* GET /supported
* Get supported payment kinds and extensions
*/
app.get("/supported", async (req, res) => {
try {
const response = facilitator.getSupported();
res.json(response);
} catch (error) {
console.error("Supported error:", error);
res.status(500).json({
error: error instanceof Error ? error.message : "Unknown error",
});
}
});
/**
* GET /discovery/resources
* List all discovered resources from bazaar
*/
app.get("/discovery/resources", async (req, res) => {
try {
const resources = bazaarCatalog.getAll();
res.json({
x402Version: 2,
items: resources,
pagination: {
limit: 100,
offset: 0,
total: resources.length,
},
});
} catch (error) {
console.error("Discovery error:", error);
res.status(500).json({
error: error instanceof Error ? error.message : "Unknown error",
});
}
});
/**
* GET /health
* Health check endpoint
*/
app.get("/health", (req, res) => {
res.json({ status: "ok" });
});
// Start the server
app.listen(parseInt(PORT), () => {
console.log(`🚀 Discovery Facilitator listening on http://localhost:${PORT}`);
console.log(` Supported networks: ${facilitator.getSupported().kinds.map(k => k.network).join(", ")}`);
console.log(` Discovery endpoint: GET /discovery/resources`);
console.log();
});