Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 16 additions & 2 deletions backend/src/controllers/gasStationController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { ApiResponse } from '../utils/response.js';

const sponsorSchema = z.object({
innerTxXdr: z.string().min(10),
turnstileToken: z.string().min(1).optional(),
});

export const gasStationController = {
Expand All @@ -18,11 +19,19 @@ export const gasStationController = {
}

const user = req.user!;
const countryCode =
(req.headers['cf-ipcountry'] as string | undefined) ||
(req.headers['x-vercel-ip-country'] as string | undefined) ||
(req.headers['x-country-code'] as string | undefined);

try {
const result = await gasStationService.sponsor({
studentId: user.id,
studentPublicKey: user.walletAddress || '',
innerTxXdr: parsed.data.innerTxXdr,
turnstileToken: parsed.data.turnstileToken,
clientIp: req.ip,
countryCode,
});
return res.status(200).json(ApiResponse.success('Transaction sponsored', result));
} catch (err) {
Expand All @@ -35,8 +44,13 @@ export const gasStationController = {

// Today's sponsorship usage for the authenticated student
getQuota: asyncHandler(async (req: Request, res: Response) => {
const usage = await getGasQuotaUsage(req.user!.id);
return res.status(200).json(ApiResponse.success('Gas quota retrieved', usage));
const [usage, dailyTransactions] = await Promise.all([
getGasQuotaUsage(req.user!.id),
gasStationService.getDailyTxCount(req.user!.id),
]);
return res
.status(200)
.json(ApiResponse.success('Gas quota retrieved', { ...usage, dailyTransactions }));
}),

// Verified course contracts eligible for sponsorship
Expand Down
70 changes: 68 additions & 2 deletions backend/src/routes/gasStation.routes.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,78 @@
import { Router } from 'express';
import { NextFunction, Request, Response, Router } from 'express';
import { authenticate } from '../auth/auth.middleware.js';
import { gasStationController } from '../controllers/gasStationController.js';
import { gasQuotaMiddleware } from '../middleware/gasQuotaMiddleware.js';
import { GasStationError, gasStationService } from '../services/gasStationService.js';
import { ApiResponse } from '../utils/response.js';

const router: ReturnType<typeof Router> = Router();

/**
* Early anti-drain guard on the gas station sponsor endpoint:
* - Enforces geofencing via proxy country headers (CF-IPCountry / X-Country-Code)
* - Rejects blacklisted linked wallets before quota or XDR work
* - Rejects students who have already exhausted their daily 50-tx cap
*/
const gasStationPolicyGuard = async (
req: Request,
res: Response,
next: NextFunction
): Promise<void> => {
const countryCode =
(req.headers['cf-ipcountry'] as string | undefined) ||
(req.headers['x-vercel-ip-country'] as string | undefined) ||
(req.headers['x-country-code'] as string | undefined);

try {
gasStationService.validateGeofence(countryCode);
} catch (err) {
if (err instanceof GasStationError) {
res.status(err.statusCode).json(ApiResponse.error(err.message));
return;
}
next(err);
return;
}

const user = req.user;
if (!user?.id) {
res.status(401).json(ApiResponse.error('Authentication required'));
return;
}

try {
if (user.walletAddress && (await gasStationService.isAddressBlacklisted(user.walletAddress))) {
res
.status(403)
.json(
ApiResponse.error('Address is temporarily blacklisted for 24 hours due to abusive activity')
);
return;
}

const txUsage = await gasStationService.getDailyTxCount(user.id);
if (txUsage.remaining <= 0) {
res
.status(429)
.json(ApiResponse.error(`Daily limit of ${txUsage.limit} sponsored transactions reached`));
return;
}
} catch {
res.status(503).json(ApiResponse.error('Gas sponsorship is temporarily unavailable'));
return;
}

next();
};

router.get('/contracts', gasStationController.getWhitelist);
router.get('/quota', authenticate, gasStationController.getQuota);
router.post('/sponsor', authenticate, gasQuotaMiddleware, gasStationController.sponsor);
router.post(
'/sponsor',
authenticate,
gasStationPolicyGuard,
gasQuotaMiddleware,
gasStationController.sponsor
);

export default router;
Loading
Loading