Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. 🔥
TypeScript aiai-agentsai-crawlerai-scrapingai-searchcrawlerdata-extractionhtml-to-markdownllmmarkdownscraperscrapingweb-crawlerweb-dataweb-data-extractionweb-scraperweb-scrapingweb-searchwebscraping
refactor: remove generate payment header functionality and related references
AdemÃlson Tonato0f3355016216
diff --git a/apps/api/requests.http b/apps/api/requests.httpindex 6fd622268..b33e94055 100644--- a/apps/api/requests.http+++ b/apps/api/requests.http@@ -132,22 +132,8 @@ content-type: application/jsonGET {{baseUrl}}/v1/crawl/active HTTP/1.1Authorization: Bearer {{$dotenv TEST_API_KEY}}-### Generate Payment Header for Search with Wallet-# Generate a payment header for search with wallet-# Duration options: 1h, 1d, 1w-# @name generatePaymentHeaderSearch-POST {{baseUrl}}/v1/generate-payment-header HTTP/1.1-Authorization: Bearer {{$dotenv TEST_API_KEY}}-content-type: application/json--{- "privateKey": "0X-PRIVATE-KEY-PRIVATE-KEY",- "duration": "1h",- "resource": "x402/search"-}-### Search with Wallet-@paymentHeaderSearch = {{generatePaymentHeaderSearch.response.body.data.paymentHeader}}+@paymentHeaderSearch = 'EXAMPLE-PAYMENT-HEADER'# @name searchWithWalletPOST {{baseUrl}}/v1/x402/search HTTP/1.1Authorization: Bearer {{$dotenv TEST_API_KEY}}diff --git a/apps/api/src/controllers/auth.ts b/apps/api/src/controllers/auth.tsindex dcab29b28..0cc24d6f4 100644--- a/apps/api/src/controllers/auth.ts+++ b/apps/api/src/controllers/auth.ts@@ -91,7 +91,6 @@ const mockPreviewACUC: (team_id: string, is_extract: boolean) => AuthCreditUsageextractStatus: 500,extractAgentPreview: 1,scrapeAgentPreview: 5,- generatePaymentHeader: 2,},price_credits: 99999999,credits_used: 0,@@ -427,8 +426,6 @@ export async function supaAuthenticateUser(rateLimiter = getRateLimiter(RateLimiterMode.CrawlStatus, token);} else if (mode == RateLimiterMode.ExtractStatus) {rateLimiter = getRateLimiter(RateLimiterMode.ExtractStatus, token);- } else if (mode == RateLimiterMode.GeneratePaymentHeader) {- rateLimiter = getRateLimiter(RateLimiterMode.GeneratePaymentHeader, token);} else {rateLimiter = getRateLimiter(RateLimiterMode.Preview, token);}diff --git a/apps/api/src/controllers/v1/generate-payment-header.ts b/apps/api/src/controllers/v1/generate-payment-header.tsdeleted file mode 100644index 14e736d29..000000000--- a/apps/api/src/controllers/v1/generate-payment-header.ts+++ /dev/null@@ -1,205 +0,0 @@-import { Request, Response } from "express";-import crypto from 'crypto';-import { privateKeyToAccount } from 'viem/accounts';-import { getAddress } from 'viem';-import {- GeneratePaymentHeaderResponse,- GeneratePaymentHeaderRequest,- RequestWithAuth,-} from "./types";--interface PaymentRequirements {- scheme: string;- network: string;- maxAmountRequired: string;- resource: string;- description: string;- mimeType: string;- payTo: string;- maxTimeoutSeconds: number;- asset: string;- extra: {- name: string;- version: string;- };-}--// Generate a random nonce (32 bytes = 64 hex chars)-function generateNonce(): string {- return '0x' + crypto.randomBytes(32).toString('hex');-}--// Create the unsigned payment header-function createUnsignedPaymentHeader(account: any, paymentRequirements: PaymentRequirements, durationSeconds: number): any {- const now = Math.floor(Date.now() / 1000);- const validAfter = (now - 60).toString(); // 60 seconds before- const validBefore = (now + durationSeconds).toString();- const nonce = generateNonce();-- return {- x402Version: 1,- scheme: paymentRequirements.scheme,- network: paymentRequirements.network,- payload: {- signature: null,- authorization: {- from: account.address,- to: getAddress(paymentRequirements.payTo),- value: paymentRequirements.maxAmountRequired,- validAfter: validAfter,- validBefore: validBefore,- nonce: nonce- }- }- };-}--// Create EIP-712 typed data for signing-function createTypedData(paymentRequirements: PaymentRequirements, authorization: any): any {- return {- types: {- TransferWithAuthorization: [- { name: "from", type: "address" },- { name: "to", type: "address" },- { name: "value", type: "uint256" },- { name: "validAfter", type: "uint256" },- { name: "validBefore", type: "uint256" },- { name: "nonce", type: "bytes32" }- ]- },- primaryType: "TransferWithAuthorization",- domain: {- name: paymentRequirements.extra.name,- version: paymentRequirements.extra.version,- chainId: 84532, // Base Sepolia chain ID- verifyingContract: getAddress(paymentRequirements.asset)- },- message: {- from: authorization.from,- to: authorization.to,- value: authorization.value,- validAfter: authorization.validAfter,- validBefore: authorization.validBefore,- nonce: authorization.nonce- }- };-}--// Base64 encode the payment header-function encodePayment(paymentHeader: any): string {- const jsonString = JSON.stringify(paymentHeader);- return Buffer.from(jsonString).toString('base64');-}--export async function generatePaymentHeaderController(req: RequestWithAuth<{}, GeneratePaymentHeaderResponse, GeneratePaymentHeaderRequest>,- res: Response<GeneratePaymentHeaderResponse>) {- try {- const { privateKey, duration, resource }: GeneratePaymentHeaderRequest = req.body;-- if (!privateKey) {- return res.status(400).json({- success: false,- error: "Private key is required"- });- }-- if (!duration || !['1h', '1d', '1w'].includes(duration)) {- return res.status(400).json({- success: false,- error: "Duration must be one of: 1h, 1d, 1w"- });- }-- // Convert duration to seconds- const durationMap = {- '1h': 3600,- '1d': 86400,- '1w': 604800- };- const durationSeconds = durationMap[duration];-- // Payment requirements based on the Express server configuration- const getPaymentRequirements = (resource: string): PaymentRequirements => {- const baseRequirements = {- scheme: "exact",- network: "base-sepolia",- mimeType: "application/json",- payTo: process.env.X402_PAY_TO_ADDRESS || "0x0000000000000000000000000000000000000000",- maxTimeoutSeconds: durationSeconds,- asset: "0x036CbD53842c5426634e7929541eC2318f3dCF7e", // USDC on Base Sepolia- extra: {- name: "USDC",- version: "2"- }- };-- // Get the base URL from the request- const protocol = req.protocol || 'http';- const host = req.get('host') || 'localhost:3002';- const baseUrl = `${protocol}://${host}`;-- switch (resource) {- case 'x402/search':- default:- return {- ...baseRequirements,- maxAmountRequired: "10000", // $0.01 in USDC base units - matches X402_ENDPOINT_PRICE_USD ("20000" => $0.02)- resource: `${baseUrl}/v1/x402/search`,- description: "x402 search payment API",- };- }- };-- const PAYMENT_REQUIREMENTS = getPaymentRequirements(resource);-- // Create account from private key- const account = privateKeyToAccount(privateKey as `0x${string}`);-- // Create unsigned payment header- const unsignedHeader = createUnsignedPaymentHeader(account, PAYMENT_REQUIREMENTS, durationSeconds);-- // Create typed data for signing- const typedData = createTypedData(PAYMENT_REQUIREMENTS, unsignedHeader.payload.authorization);-- // Sign the typed data- const signature = await account.signTypedData(typedData);-- // Add signature to the header- const signedHeader = {- ...unsignedHeader,- payload: {- ...unsignedHeader.payload,- signature: signature- }- };-- // Encode the final payment header- const encodedHeader = encodePayment(signedHeader);-- // Return the payment header and additional info- res.json({- success: true,- data: {- paymentHeader: encodedHeader,- walletAddress: account.address,- duration: duration,- validUntil: new Date((Math.floor(Date.now() / 1000) + durationSeconds) * 1000).toISOString(),- notes: {- timeSensitive: `This payment header is time-sensitive (valid for ${duration})`,- walletRequirement: "Make sure your wallet has USDC on Base Sepolia",- paymentAmount: "10000 USDC (in base units = $0.01)", // 20000 USDC (in base units = $0.02)- generatedAt: new Date().toISOString(),- team_id: req.auth?.team_id || req.acuc?.team_id- }- }- });-- } catch (error) {- console.error('Error generating payment header:', error);- res.status(500).json({- success: false,- error: "Failed to generate payment header",- details: error instanceof Error ? error.message : "Unknown error"- });- }-}\ No newline at end of filediff --git a/apps/api/src/controllers/v1/types.ts b/apps/api/src/controllers/v1/types.tsindex 59268522b..5de6eb3c8 100644--- a/apps/api/src/controllers/v1/types.ts+++ b/apps/api/src/controllers/v1/types.ts@@ -1030,7 +1030,6 @@ export type AuthCreditUsageChunk = {extractStatus: number;extractAgentPreview?: number;scrapeAgentPreview?: number;- generatePaymentHeader?: number;};concurrency: number;flags: TeamFlags;@@ -1377,34 +1376,3 @@ export class TimeoutSignal extends Error {super("Operation timed out");}}--// Generate Payment Header Request-export const generatePaymentHeaderRequestSchema = z.object({- privateKey: z.string(),- duration: z.enum(['1h', '1d', '1w']),- resource: z.string().optional().default('protected-data'),-})--export type GeneratePaymentHeaderRequest = z.infer<typeof generatePaymentHeaderRequestSchema>;-export type GeneratePaymentHeaderRequestInput = z.input<typeof generatePaymentHeaderRequestSchema>;--export type GeneratePaymentData = {- paymentHeader: string;- walletAddress: string;- duration: string;- validUntil: string;- notes: {- timeSensitive: string;- walletRequirement: string;- paymentAmount: string;- generatedAt: string;- [key: string]: string;- }-}--export type GeneratePaymentHeaderResponse =- | ErrorResponse- | {- success: true;- data: GeneratePaymentData;- };\ No newline at end of filediff --git a/apps/api/src/routes/v1.ts b/apps/api/src/routes/v1.tsindex f1c4142d9..593197337 100644--- a/apps/api/src/routes/v1.ts+++ b/apps/api/src/routes/v1.ts@@ -37,7 +37,6 @@ import { deepResearchController } from "../controllers/v1/deep-research";import { deepResearchStatusController } from "../controllers/v1/deep-research-status";import { tokenUsageController } from "../controllers/v1/token-usage";import { ongoingCrawlsController } from "../controllers/v1/crawl-ongoing";-import { generatePaymentHeaderController } from "../controllers/v1/generate-payment-header";import { paymentMiddleware } from "x402-express";function checkCreditsMiddleware(@@ -366,12 +365,6 @@ v1Router.get(wrap(tokenUsageController),);-v1Router.post(- "/generate-payment-header",- authMiddleware(RateLimiterMode.GeneratePaymentHeader),- wrap(generatePaymentHeaderController),-);-v1Router.post("/x402/search",authMiddleware(RateLimiterMode.Search),diff --git a/apps/api/src/services/rate-limiter.ts b/apps/api/src/services/rate-limiter.tsindex cd4b22e2e..bcf423ac6 100644--- a/apps/api/src/services/rate-limiter.ts+++ b/apps/api/src/services/rate-limiter.ts@@ -33,7 +33,6 @@ const fallbackRateLimits: AuthCreditUsageChunk["rate_limits"] = {crawlStatus: 25000,extractAgentPreview: 10,scrapeAgentPreview: 10,- generatePaymentHeader: 2,};export function getRateLimiter(diff --git a/apps/api/src/types.ts b/apps/api/src/types.tsindex a23f5617b..c42720c1c 100644--- a/apps/api/src/types.ts+++ b/apps/api/src/types.ts@@ -162,7 +162,6 @@ export enum RateLimiterMode {Extract = "extract",ExtractStatus = "extractStatus",ExtractAgentPreview = "extractAgentPreview",- GeneratePaymentHeader = "generatePaymentHeader",}export type AuthResponse =