openraas
Version:
Open Robot-as-a-Service Protocol - A comprehensive TypeScript library for building and consuming RaaS applications with X402 payment support on Solana
47 lines (46 loc) • 1.72 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.PaymentMiddleware = void 0;
const x402_1 = require("../core/x402");
class PaymentMiddleware {
constructor(receiverAddress, mint, pricePerRequest // BigInt string
) {
this.receiverAddress = receiverAddress;
this.mint = mint;
this.pricePerRequest = pricePerRequest;
}
async handle(ctx) {
const { req, send, next } = ctx;
// Check for X-PAYMENT header or payload property
const paymentPayload = req.headers?.['x-payment'] || req.payment;
if (!paymentPayload) {
// 402 Payment Required
const request = x402_1.X402Payment.createRequest(this.receiverAddress, this.pricePerRequest, this.mint);
send({
status: 'payment_required',
paymentRequest: request,
});
return;
}
try {
const publicKey = x402_1.X402Payment.verifyPayment(paymentPayload);
// In a real app, we would also:
// 1. Check if the payment is on-chain (or valid off-chain channel)
// 2. Check nonce replay
// 3. Check amount >= pricePerRequest
if (BigInt(paymentPayload.request.amount) < BigInt(this.pricePerRequest)) {
throw new Error('Insufficient payment amount');
}
// Attach user info
req.user = { publicKey };
await next();
}
catch (err) {
send({
status: 'error',
error: `Payment verification failed: ${err.message}`,
});
}
}
}
exports.PaymentMiddleware = PaymentMiddleware;