Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(x402): port x402-research as a native Solana x402 service

nirholas506cf74c77ed
diff --git a/api/_lib/service-catalog/services/index.js b/api/_lib/service-catalog/services/index.js
index 5f3d57034..e057accbd 100644
--- a/api/_lib/service-catalog/services/index.js
+++ b/api/_lib/service-catalog/services/index.js
@@ -80,6 +80,9 @@ import carbonNow from './carbon-now.js';
import carbonBestWindow from './carbon-best-window.js';
import domainsCheck from './domains-check.js';
import domainsBulk from './domains-bulk.js';
+import researchSearch from './research-search.js';
+import researchPaper from './research-paper.js';
+import researchBibliography from './research-bibliography.js';
export const PAID_SERVICES = Object.freeze([
modelCheck,
@@ -149,4 +152,7 @@ export const PAID_SERVICES = Object.freeze([
carbonBestWindow,
domainsCheck,
domainsBulk,
+ researchSearch,
+ researchPaper,
+ researchBibliography,
]);
diff --git a/api/_lib/service-catalog/services/research-bibliography.js b/api/_lib/service-catalog/services/research-bibliography.js
new file mode 100644
index 000000000..ada9cb92a
--- /dev/null
+++ b/api/_lib/service-catalog/services/research-bibliography.js
@@ -0,0 +1,41 @@
+// Service-catalog descriptor: see news-pulse.js for the contract notes.
+// Do not re-add a hand-written mirror for this route in api/wk.js.
+
+export default {
+ slug: 'research-bibliography',
+ title: 'Bibliography Formatter',
+ category: 'live-data',
+ useCase: 'three.ws Bibliography: $0.005 USDC per call returns formatted BibTeX and APA 7 entries for up to 25 DOIs in one request.',
+ path: '/api/x402/research-bibliography',
+ method: 'POST',
+ free: false,
+ status: 'live',
+ priceAtomics: '5000',
+ acceptsBuilder: 'standard',
+ serviceName: 'three.ws Research',
+ tags: ['research', 'academic', 'live-data', 'citations', 'bibliography'],
+ description: 'three.ws Bibliography: pay $0.005 USDC per call to get formatted BibTeX and/or APA 7 citation entries for up to 25 DOIs in one request, sourced live from Crossref.',
+ input: { dois: ['10.1038/nature14539'], format: 'both' },
+ inputSchema: {
+ type: 'object',
+ required: ['dois'],
+ properties: {
+ dois: { type: 'array', items: { type: 'string' }, minItems: 1, maxItems: 25, description: 'DOIs to format, 1 to 25 per call.' },
+ format: { type: 'string', enum: ['bibtex', 'apa', 'both'], default: 'both', description: 'Citation format to return.' },
+ },
+ },
+ outputExample: {
+ format: 'both',
+ count: 1,
+ entries: [
+ {
+ doi: '10.1038/nature14539',
+ status: 'ok',
+ bibtex: '@article{...}',
+ apa: 'LeCun, Y., Bengio, Y., & Hinton, G. (2015). Deep learning. Nature, 521(7553), 436-444. https://doi.org/10.1038/nature14539',
+ },
+ ],
+ retrievedAt: '2026-10-14T00:00:00Z',
+ },
+ storefronts: ['x402scan'],
+};
diff --git a/api/_lib/service-catalog/services/research-paper.js b/api/_lib/service-catalog/services/research-paper.js
new file mode 100644
index 000000000..c0959bbd8
--- /dev/null
+++ b/api/_lib/service-catalog/services/research-paper.js
@@ -0,0 +1,38 @@
+// Service-catalog descriptor: see news-pulse.js for the contract notes.
+// Do not re-add a hand-written mirror for this route in api/wk.js.
+
+export default {
+ slug: 'research-paper',
+ title: 'Paper Detail & Citation Graph',
+ category: 'live-data',
+ useCase: 'three.ws Paper Detail: $0.003 USDC per call returns metadata, abstract, TL;DR, and a two-sided citation graph for a DOI, arXiv id, or Semantic Scholar id.',
+ path: '/api/x402/research-paper',
+ method: 'GET',
+ free: false,
+ status: 'live',
+ priceAtomics: '3000',
+ acceptsBuilder: 'standard',
+ serviceName: 'three.ws Research',
+ tags: ['research', 'academic', 'live-data', 'citations'],
+ description: 'three.ws Paper Detail: pay $0.003 USDC per call for a single paper\'s full metadata (title, abstract, TL;DR, year, venue, authors, fields of study, open-access PDF link) plus a two-sided citation graph (top citations and references) from Semantic Scholar, keyed by DOI, arXiv id, or Semantic Scholar id. Falls back to Crossref metadata (marked partial, no citation graph) when Semantic Scholar is unreachable for a DOI.',
+ input: { id: '10.48550/arXiv.1706.03762' },
+ inputSchema: {
+ type: 'object',
+ required: ['id'],
+ properties: {
+ id: { type: 'string', description: 'A DOI, arXiv id (e.g. "1706.03762"), or Semantic Scholar paper id.' },
+ },
+ },
+ outputExample: {
+ id: '1706.03762',
+ resolvedAs: 'ARXIV:1706.03762',
+ title: 'Attention Is All You Need',
+ abstract: 'The dominant sequence transduction models...',
+ year: 2017,
+ venue: 'NeurIPS',
+ authors: ['Ashish Vaswani', 'Noam Shazeer'],
+ citationGraph: { citationCount: 142000, referenceCount: 45, topCitations: [], references: [] },
+ source: 'semantic-scholar',
+ },
+ storefronts: ['x402scan'],
+};
diff --git a/api/_lib/service-catalog/services/research-search.js b/api/_lib/service-catalog/services/research-search.js
new file mode 100644
index 000000000..5a407666c
--- /dev/null
+++ b/api/_lib/service-catalog/services/research-search.js
@@ -0,0 +1,48 @@
+// Service-catalog descriptor: see news-pulse.js for the contract notes.
+// Do not re-add a hand-written mirror for this route in api/wk.js.
+
+export default {
+ slug: 'research-search',
+ title: 'Scholarly Search',
+ category: 'live-data',
+ useCase: 'three.ws Scholarly Search: $0.002 USDC per call returns a ranked, de-duplicated merge of arXiv, Crossref, and Semantic Scholar hits for a query, with authors, venue, DOI, abstract, and citation count.',
+ path: '/api/x402/research-search',
+ method: 'GET',
+ free: true,
+ status: 'live',
+ priceAtomics: '2000',
+ acceptsBuilder: 'standard',
+ serviceName: 'three.ws Research',
+ tags: ['research', 'academic', 'live-data', 'arxiv', 'crossref'],
+ description: 'three.ws Scholarly Search: live public-data endpoint, no API key anywhere in the chain. Pay $0.002 USDC (or use the free daily per-IP quota) to query arXiv, Crossref, and Semantic Scholar in parallel and get a merged, de-duplicated ranking of papers with authors, year, venue, DOI, arXiv id, abstract, and citation count. A source failing or rate-limiting is reported per-source rather than failing the whole call.',
+ input: { q: 'transformer attention mechanism', limit: 10 },
+ inputSchema: {
+ type: 'object',
+ required: ['q'],
+ properties: {
+ q: { type: 'string', description: 'Search query.' },
+ limit: { type: 'integer', minimum: 1, maximum: 25, default: 10, description: 'Max papers to return.' },
+ },
+ },
+ outputExample: {
+ query: 'transformer attention mechanism',
+ count: 2,
+ papers: [
+ {
+ title: 'Attention Is All You Need',
+ authors: ['Ashish Vaswani', 'Noam Shazeer'],
+ year: 2017,
+ venue: 'NeurIPS',
+ doi: null,
+ arxivId: '1706.03762',
+ url: 'https://arxiv.org/abs/1706.03762',
+ abstract: 'The dominant sequence transduction models...',
+ citationCount: 142000,
+ source: 'semantic-scholar',
+ },
+ ],
+ sources: { arxiv: 'ok', crossref: 'ok', semanticScholar: 'ok' },
+ retrievedAt: '2026-10-14T00:00:00Z',
+ },
+ storefronts: ['x402scan'],
+};
diff --git a/api/_lib/x402-services/research.js b/api/_lib/x402-services/research.js
new file mode 100644
index 000000000..5b5515dcc
--- /dev/null
+++ b/api/_lib/x402-services/research.js
@@ -0,0 +1,286 @@
+// Live, keyless scholarly search and citation data from three sources:
+// - arXiv (Atom XML)
+// - Crossref (JSON)
+// - Semantic Scholar (JSON)
+// Each upstream call has a timeout and degrades gracefully: a failing or
+// rate-limited source is reported in the `sources` block instead of
+// failing the whole request.
+
+const THREE_WS_UA = 'three.ws/1.0 (+https://three.ws; [email protected])';
+const TIMEOUT_MS = 12_000;
+
+async function getJson(url, headers = {}) {
+ const res = await fetch(url, {
+ headers: { 'user-agent': THREE_WS_UA, accept: 'application/json', ...headers },
+ signal: AbortSignal.timeout(TIMEOUT_MS),
+ });
+ if (!res.ok) throw new Error(`HTTP ${res.status} from ${new URL(url).host}`);
+ return res.json();
+}
+
+async function getText(url, headers = {}) {
+ const res = await fetch(url, {
+ headers: { 'user-agent': THREE_WS_UA, ...headers },
+ signal: AbortSignal.timeout(TIMEOUT_MS),
+ });
+ if (!res.ok) throw new Error(`HTTP ${res.status} from ${new URL(url).host}`);
+ return res.text();
+}
+
+function decodeXml(s) {
+ return s
+ .replace(/&lt;/g, '<')
+ .replace(/&gt;/g, '>')
+ .replace(/&quot;/g, '"')
+ .replace(/&#39;|&apos;/g, "'")
+ .replace(/&amp;/g, '&')
+ .replace(/\s+/g, ' ')
+ .trim();
+}
+
+function xmlTag(block, tag) {
+ const m = block.match(new RegExp(`<${tag}[^>]*>([\\s\\S]*?)</${tag}>`));
+ return m ? decodeXml(m[1]) : null;
+}
+
+function normTitle(t) {
+ return t.toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim();
+}
+
+async function searchArxiv(q, limit) {
+ const url = `https://export.arxiv.org/api/query?search_query=all:${encodeURIComponent(q)}&start=0&max_results=${limit}&sortBy=relevance`;
+ const xml = await getText(url);
+ const entries = xml.match(/<entry>[\s\S]*?<\/entry>/g) ?? [];
+ return entries.map((e) => {
+ const idUrl = xmlTag(e, 'id') ?? '';
+ const arxivId = idUrl.replace(/^.*\/abs\//, '').replace(/v\d+$/, '') || null;
+ const published = xmlTag(e, 'published');
+ const authors = (e.match(/<author>[\s\S]*?<\/author>/g) ?? [])
+ .map((a) => xmlTag(a, 'name'))
+ .filter(Boolean);
+ return {
+ title: xmlTag(e, 'title') ?? '(untitled)',
+ authors,
+ year: published ? Number(published.slice(0, 4)) : null,
+ venue: 'arXiv',
+ doi: xmlTag(e, 'arxiv:doi'),
+ arxivId,
+ url: idUrl || null,
+ abstract: xmlTag(e, 'summary'),
+ citationCount: null,
+ source: 'arxiv',
+ };
+ });
+}
+
+async function searchCrossref(q, limit) {
+ const url = `https://api.crossref.org/works?query=${encodeURIComponent(q)}&rows=${limit}&select=DOI,title,author,issued,container-title,is-referenced-by-count,URL,abstract`;
+ const data = await getJson(url);
+ return (data.message?.items ?? []).map((it) => {
+ const issued = it.issued?.['date-parts']?.[0]?.[0];
+ return {
+ title: Array.isArray(it.title) ? it.title[0] ?? '(untitled)' : '(untitled)',
+ authors: (it.author ?? []).map((a) => [a.given, a.family].filter(Boolean).join(' ')),
+ year: typeof issued === 'number' ? issued : null,
+ venue: Array.isArray(it['container-title']) ? it['container-title'][0] ?? null : null,
+ doi: it.DOI ?? null,
+ arxivId: null,
+ url: it.URL ?? (it.DOI ? `https://doi.org/${it.DOI}` : null),
+ abstract: typeof it.abstract === 'string' ? decodeXml(it.abstract.replace(/<[^>]+>/g, ' ')) : null,
+ citationCount: it['is-referenced-by-count'] ?? null,
+ source: 'crossref',
+ };
+ });
+}
+
+const S2_FIELDS = 'title,year,venue,authors,externalIds,citationCount,abstract,url';
+
+async function searchS2(q, limit) {
+ const url = `https://api.semanticscholar.org/graph/v1/paper/search?query=${encodeURIComponent(q)}&limit=${limit}&fields=${S2_FIELDS}`;
+ const data = await getJson(url);
+ return (data.data ?? []).map((p) => ({
+ title: p.title ?? '(untitled)',
+ authors: (p.authors ?? []).map((a) => a.name).filter(Boolean),
+ year: p.year ?? null,
+ venue: p.venue || null,
+ doi: p.externalIds?.DOI ?? null,
+ arxivId: p.externalIds?.ArXiv ?? null,
+ url: p.url ?? null,
+ abstract: p.abstract ?? null,
+ citationCount: p.citationCount ?? null,
+ source: 'semantic-scholar',
+ }));
+}
+
+export async function search(q, limit) {
+ const per = Math.min(Math.max(limit, 1), 25);
+ const jobs = [
+ ['arxiv', searchArxiv(q, per)],
+ ['crossref', searchCrossref(q, per)],
+ ['semanticScholar', searchS2(q, per)],
+ ];
+ const sources = {};
+ const collected = [];
+ const settled = await Promise.allSettled(jobs.map(([, p]) => p));
+ settled.forEach((r, i) => {
+ const name = jobs[i][0];
+ if (r.status === 'fulfilled') {
+ sources[name] = 'ok';
+ collected.push(...r.value);
+ } else {
+ const msg = String(r.reason?.message ?? r.reason);
+ sources[name] = /429/.test(msg) ? 'rate-limited' : `error: ${msg}`;
+ }
+ });
+ if (Object.values(sources).every((s) => s !== 'ok')) {
+ const err = new Error(`All upstream sources failed: ${JSON.stringify(sources)}. Try again shortly.`);
+ err.status = 502;
+ err.code = 'all_sources_failed';
+ throw err;
+ }
+
+ const byKey = new Map();
+ for (const p of collected) {
+ const key = p.doi?.toLowerCase() ?? `t:${normTitle(p.title)}`;
+ const prev = byKey.get(key);
+ if (!prev) {
+ byKey.set(key, { ...p });
+ } else {
+ prev.citationCount = prev.citationCount ?? p.citationCount;
+ prev.abstract = prev.abstract ?? p.abstract;
+ prev.doi = prev.doi ?? p.doi;
+ prev.arxivId = prev.arxivId ?? p.arxivId;
+ prev.venue = prev.venue ?? p.venue;
+ }
+ }
+ const papers = [...byKey.values()]
+ .sort((a, b) => (b.citationCount ?? 0) - (a.citationCount ?? 0) || (b.year ?? 0) - (a.year ?? 0))
+ .slice(0, per);
+
+ return { query: q, count: papers.length, papers, sources, retrievedAt: new Date().toISOString() };
+}
+
+function s2IdFor(id) {
+ if (/^10\.\d{4,9}\//.test(id)) return `DOI:${id}`;
+ if (/^arxiv:/i.test(id)) return `ARXIV:${id.slice(6)}`;
+ if (/^\d{4}\.\d{4,5}(v\d+)?$/.test(id)) return `ARXIV:${id.replace(/v\d+$/, '')}`;
+ return id;
+}
+
+export async function paperDetail(id) {
+ const fields =
+ 'title,abstract,year,venue,publicationDate,authors,externalIds,citationCount,' +
+ 'referenceCount,influentialCitationCount,fieldsOfStudy,tldr,openAccessPdf,' +
+ 'citations.title,citations.year,citations.externalIds,citations.citationCount,' +
+ 'references.title,references.year,references.externalIds,references.citationCount';
+
+ try {
+ const p = await getJson(`https://api.semanticscholar.org/graph/v1/paper/${encodeURIComponent(s2IdFor(id))}?fields=${fields}`);
+ const slim = (arr) =>
+ (arr ?? []).slice(0, 25).map((c) => ({
+ title: c.title ?? null,
+ year: c.year ?? null,
+ doi: c.externalIds?.DOI ?? null,
+ arxivId: c.externalIds?.ArXiv ?? null,
+ citationCount: c.citationCount ?? null,
+ }));
+ return {
+ id,
+ resolvedAs: s2IdFor(id),
+ title: p.title ?? null,
+ abstract: p.abstract ?? p.tldr?.text ?? null,
+ tldr: p.tldr?.text ?? null,
+ year: p.year ?? null,
+ venue: p.venue || null,
+ publicationDate: p.publicationDate ?? null,
+ authors: (p.authors ?? []).map((a) => a.name).filter(Boolean),
+ externalIds: p.externalIds ?? {},
+ fieldsOfStudy: p.fieldsOfStudy ?? [],
+ openAccessPdf: p.openAccessPdf?.url ?? null,
+ citationGraph: {
+ citationCount: p.citationCount ?? null,
+ referenceCount: p.referenceCount ?? null,
+ influentialCitationCount: p.influentialCitationCount ?? null,
+ topCitations: slim(p.citations),
+ references: slim(p.references),
+ },
+ source: 'semantic-scholar',
+ retrievedAt: new Date().toISOString(),
+ };
+ } catch (err) {
+ if (/^10\.\d{4,9}\//.test(id)) {
+ const data = await getJson(`https://api.crossref.org/works/${encodeURIComponent(id)}`);
+ const m = data.message ?? {};
+ return {
+ id,
+ resolvedAs: `DOI:${id}`,
+ title: Array.isArray(m.title) ? m.title[0] ?? null : null,
+ abstract: typeof m.abstract === 'string' ? decodeXml(m.abstract.replace(/<[^>]+>/g, ' ')) : null,
+ year: m.issued?.['date-parts']?.[0]?.[0] ?? null,
+ venue: Array.isArray(m['container-title']) ? m['container-title'][0] ?? null : null,
+ authors: (m.author ?? []).map((a) => [a.given, a.family].filter(Boolean).join(' ')),
+ externalIds: { DOI: id },
+ citationGraph: {
+ citationCount: m['is-referenced-by-count'] ?? null,
+ referenceCount: m['reference-count'] ?? null,
+ note: 'Citation lists unavailable (Semantic Scholar unreachable); counts from Crossref.',
+ },
+ source: 'crossref',
+ partial: true,
+ upstreamError: String(err.message),
+ retrievedAt: new Date().toISOString(),
+ };
+ }
+ throw err;
+ }
+}
+
+function apaAuthors(authors) {
+ const fmt = (a) => {
+ const initials = (a.given ?? '')
+ .split(/[\s-]+/)
+ .filter(Boolean)
+ .map((n) => `${n[0].toUpperCase()}.`)
+ .join(' ');
+ return initials ? `${a.family}, ${initials}` : a.family ?? '';
+ };
+ const names = authors.map(fmt).filter(Boolean);
+ if (names.length === 0) return '';
+ if (names.length === 1) return names[0];
+ if (names.length <= 20) return `${names.slice(0, -1).join(', ')}, & ${names.at(-1)}`;
+ return `${names.slice(0, 19).join(', ')}, ... ${names.at(-1)}`;
+}
+
+function apaEntry(m, doi) {
+ const year = m.issued?.['date-parts']?.[0]?.[0] ?? 'n.d.';
+ const title = Array.isArray(m.title) ? m.title[0] ?? '' : '';
+ const journal = Array.isArray(m['container-title']) ? m['container-title'][0] ?? '' : '';
+ const vol = m.volume ? `${m.volume}` : '';
+ const issue = m.issue ? `(${m.issue})` : '';
+ const pages = m.page ? `, ${m.page}` : '';
+ const authors = apaAuthors(m.author ?? []);
+ const journalPart = journal ? ` ${journal}${vol || issue ? `, ${vol}${issue}` : ''}${pages}.` : '';
+ return `${authors ? `${authors} ` : ''}(${year}). ${title}.${journalPart} https://doi.org/${doi}`;
+}
+
+export async function bibliography(dois, format) {
+ const unique = [...new Set(dois.map((d) => String(d).trim()).filter(Boolean))].slice(0, 25);
+ const entries = await Promise.all(
+ unique.map(async (doi) => {
+ try {
+ const entry = { doi, status: 'ok' };
+ if (format !== 'apa') {
+ entry.bibtex = (await getText(`https://api.crossref.org/works/${encodeURIComponent(doi)}/transform/application/x-bibtex`)).trim();
+ }
+ if (format !== 'bibtex') {
+ const data = await getJson(`https://api.crossref.org/works/${encodeURIComponent(doi)}`);
+ entry.apa = apaEntry(data.message ?? {}, doi);
+ }
+ return entry;
+ } catch (err) {
+ return { doi, status: 'error', error: String(err.message) };
+ }
+ }),
+ );
+ return { format, count: entries.length, entries, retrievedAt: new Date().toISOString() };
+}
diff --git a/api/x402/research-bibliography.js b/api/x402/research-bibliography.js
new file mode 100644
index 000000000..0fc97099d
--- /dev/null
+++ b/api/x402/research-bibliography.js
@@ -0,0 +1,68 @@
+// POST /api/x402/research-bibliography body: {"dois":[...],"format":"both"}
+//
+// Bibliography Formatter: $0.005 USDC per call, always paid. Formatted
+// BibTeX and/or APA 7 entries for up to 25 DOIs, sourced live from Crossref.
+
+import { readBody } from '../_lib/http.js';
+import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';
+import { buildBazaarSchema } from '../_lib/x402-spec.js';
+import { installAccessControl } from '../_lib/x402/access-control.js';
+import { withService } from '../_lib/x402/bazaar-helpers.js';
+import { priceFor } from '../_lib/x402-prices.js';
+import { bibliography } from '../_lib/x402-services/research.js';
+import listing from '../_lib/service-catalog/services/research-bibliography.js';
+
+const ROUTE = '/api/x402/research-bibliography';
+const DESCRIPTION = listing.description;
+
+export const INPUT_SCHEMA = { $schema: 'https://json-schema.org/draft/2020-12/schema', ...listing.inputSchema };
+export const OUTPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ required: ['format', 'count', 'entries'],
+ properties: { format: { type: 'string' }, count: { type: 'integer' }, entries: { type: 'array' } },
+};
+
+export const BAZAAR = {
+ description: DESCRIPTION,
+ useCases: ['citation formatting', 'literature review', 'paper writing tools'],
+ input: { type: 'body', example: listing.input, schema: INPUT_SCHEMA },
+ output: { type: 'json', example: listing.outputExample },
+ schema: buildBazaarSchema({ method: 'POST', bodySchema: INPUT_SCHEMA, outputSchema: OUTPUT_SCHEMA }),
+};
+
+async function readJsonBody(req) {
+ const chunk = await readBody(req, 200_000);
+ return JSON.parse((chunk ? chunk.toString('utf8') : '') || '{}');
+}
+
+export default paidEndpoint({
+ route: ROUTE,
+ method: 'POST',
+ priceAtomics: priceFor('research-bibliography', '5000'), // $0.005 USDC
+ networks: ['solana', 'base'],
+ description: DESCRIPTION,
+ bazaar: BAZAAR,
+ service: withService({ serviceName: listing.serviceName, tags: listing.tags }),
+ accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),
+ async handler({ req }) {
+ let body;
+ try {
+ body = await readJsonBody(req);
+ } catch {
+ const err = new Error('request body must be valid JSON');
+ err.status = 400;
+ err.code = 'invalid_json';
+ throw err;
+ }
+ const dois = body?.dois;
+ if (!Array.isArray(dois) || dois.length === 0) {
+ const err = new Error('body must be {"dois": [...]} with 1-25 entries');
+ err.status = 400;
+ err.code = 'invalid_dois';
+ throw err;
+ }
+ const format = ['bibtex', 'apa', 'both'].includes(body?.format) ? body.format : 'both';
+ return bibliography(dois, format);
+ },
+});
diff --git a/api/x402/research-paper.js b/api/x402/research-paper.js
new file mode 100644
index 000000000..49192797a
--- /dev/null
+++ b/api/x402/research-paper.js
@@ -0,0 +1,49 @@
+// GET /api/x402/research-paper?id=10.48550/arXiv.1706.03762
+//
+// Paper Detail & Citation Graph: $0.003 USDC per call, always paid (the
+// free quota lives on research-search). Semantic Scholar primary, Crossref
+// fallback for DOIs.
+
+import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';
+import { buildBazaarSchema } from '../_lib/x402-spec.js';
+import { installAccessControl } from '../_lib/x402/access-control.js';
+import { withService } from '../_lib/x402/bazaar-helpers.js';
+import { priceFor } from '../_lib/x402-prices.js';
+import { paperDetail } from '../_lib/x402-services/research.js';
+import listing from '../_lib/service-catalog/services/research-paper.js';
+
+const ROUTE = '/api/x402/research-paper';
+const DESCRIPTION = listing.description;
+
+export const INPUT_SCHEMA = { $schema: 'https://json-schema.org/draft/2020-12/schema', ...listing.inputSchema };
+export const OUTPUT_SCHEMA = { $schema: 'https://json-schema.org/draft/2020-12/schema', type: 'object', required: ['id'], properties: { id: { type: 'string' } } };
+
+export const BAZAAR = {
+ description: DESCRIPTION,
+ useCases: ['literature review', 'citation graph traversal', 'research agents'],
+ input: { type: 'query', example: listing.input, schema: INPUT_SCHEMA },
+ output: { type: 'json', example: listing.outputExample },
+ schema: buildBazaarSchema({ method: 'GET', queryParamsSchema: INPUT_SCHEMA, outputSchema: OUTPUT_SCHEMA }),
+};
+
+export default paidEndpoint({
+ route: ROUTE,
+ method: 'GET',
+ priceAtomics: priceFor('research-paper', '3000'), // $0.003 USDC
+ networks: ['solana', 'base'],
+ description: DESCRIPTION,
+ bazaar: BAZAAR,
+ service: withService({ serviceName: listing.serviceName, tags: listing.tags }),
+ accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),
+ async handler({ req }) {
+ const params = new URL(req.url, 'http://x').searchParams;
+ const id = String(params.get('id') || '').trim();
+ if (!id) {
+ const err = new Error('query param "id" is required');
+ err.status = 400;
+ err.code = 'missing_id';
+ throw err;
+ }
+ return paperDetail(id);
+ },
+});
diff --git a/api/x402/research-search.js b/api/x402/research-search.js
new file mode 100644
index 000000000..b27ea6f22
--- /dev/null
+++ b/api/x402/research-search.js
@@ -0,0 +1,96 @@
+// GET /api/x402/research-search?q=transformer+attention&limit=10
+//
+// Scholarly Search: $0.002 USDC per call (free daily per-IP quota runs
+// first). Live merge of arXiv, Crossref, and Semantic Scholar. No API key.
+
+import { cors, method, error, json, wrap } from '../_lib/http.js';
+import { clientIp, limits } from '../_lib/rate-limit.js';
+import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';
+import { buildBazaarSchema } from '../_lib/x402-spec.js';
+import { installAccessControl } from '../_lib/x402/access-control.js';
+import { withService } from '../_lib/x402/bazaar-helpers.js';
+import { priceFor } from '../_lib/x402-prices.js';
+import { search } from '../_lib/x402-services/research.js';
+import listing from '../_lib/service-catalog/services/research-search.js';
+
+const ROUTE = '/api/x402/research-search';
+const DESCRIPTION = listing.description;
+
+export const INPUT_SCHEMA = { $schema: 'https://json-schema.org/draft/2020-12/schema', ...listing.inputSchema };
+export const OUTPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ required: ['query', 'count', 'papers', 'sources'],
+ properties: {
+ query: { type: 'string' },
+ count: { type: 'integer' },
+ papers: { type: 'array' },
+ sources: { type: 'object' },
+ tier: { type: 'string', enum: ['free', 'paid'] },
+ free_remaining_today: { type: 'integer' },
+ },
+};
+
+export const BAZAAR = {
+ description: DESCRIPTION,
+ useCases: ['literature review', 'citation lookup', 'research agents'],
+ input: { type: 'query', example: listing.input, schema: INPUT_SCHEMA },
+ output: { type: 'json', example: listing.outputExample },
+ schema: buildBazaarSchema({ method: 'GET', queryParamsSchema: INPUT_SCHEMA, outputSchema: OUTPUT_SCHEMA }),
+};
+
+function parseParams(req) {
+ const params = new URL(req.url, 'http://x').searchParams;
+ const q = String(params.get('q') || '').trim();
+ const limitRaw = Number(params.get('limit') || '10');
+ const limit = Number.isFinite(limitRaw) ? limitRaw : 10;
+ return { q, limit };
+}
+
+let _paid = null;
+function paidHandler() {
+ if (_paid) return _paid;
+ _paid = paidEndpoint({
+ route: ROUTE,
+ method: 'GET',
+ priceAtomics: priceFor('research-search', '2000'), // $0.002 USDC
+ networks: ['solana', 'base'],
+ description: DESCRIPTION,
+ bazaar: BAZAAR,
+ service: withService({ serviceName: listing.serviceName, tags: listing.tags }),
+ accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),
+ async handler({ req }) {
+ const { q, limit } = parseParams(req);
+ if (!q) {
+ const err = new Error('query param "q" is required');
+ err.status = 400;
+ err.code = 'missing_query';
+ throw err;
+ }
+ const data = await search(q, limit);
+ return { ...data, tier: 'paid' };
+ },
+ });
+ return _paid;
+}
+
+export default wrap(async function handler(req, res) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const paymentPresent = Boolean(req.headers['x-payment'] || req.headers['payment-signature']);
+ if (paymentPresent) return paidHandler()(req, res);
+
+ const rl = await limits.researchFreeIp(clientIp(req));
+ if (!rl.success) return paidHandler()(req, res);
+
+ const { q, limit } = parseParams(req);
+ if (!q) return error(res, 400, 'missing_query', 'query param "q" is required');
+
+ try {
+ const data = await search(q, limit);
+ return json(res, 200, { ...data, tier: 'free', free_remaining_today: Math.max(0, rl.remaining) }, { 'cache-control': 'no-store' });
+ } catch (e) {
+ return error(res, e.status || 502, e.code || 'provider_error', e.message);
+ }
+});