import { GammaSDK } from "@hk/polymarket";
import { type BaseConfig, getConfig } from "./config.js";
export type PolymarketApiConfig = Partial<BaseConfig>;
export interface OrderBookSummary {
market: string;
asset_id: string;
bids: Array<{ price: string; size: string }>;
asks: Array<{ price: string; size: string }>;
hash: string;
timestamp: string;
}
export class PolymarketAPI {
private gamma: GammaSDK;
private readonly cfg: BaseConfig;
constructor(config: PolymarketApiConfig = {}) {
this.cfg = getConfig(config);
this.gamma = new GammaSDK();
}
async getMarketBySlug(slug: string) {
return this.gamma.getMarketBySlug(slug);
}
async getEventBySlug(slug: string) {
return this.gamma.getEventBySlug(slug);
}
async listActiveMarkets(
limit = 20,
offset = 0,
order = "volume24hr",
ascending = false,
) {
return this.gamma.getActiveMarkets({
limit,
offset,
closed: false,
order,
ascending,
});
}
async searchMarkets(query: string, limit = 20) {
return this.gamma.search({ q: query, limit_per_type: limit });
}
async getMarketsByTag(tagId: string, limit = 20, closed = false) {
const parsedTagId = Number(tagId);
if (Number.isNaN(parsedTagId)) {
throw new Error("tag_id must be a number");
}
return this.gamma.getMarkets({ tag_id: parsedTagId, limit, closed });
}
async getAllTags() {
return this.gamma.getTags({});
}
async getOrderBook(tokenId: string): Promise<OrderBookSummary> {
const url = `${this.cfg.host}/book?token_id=${encodeURIComponent(tokenId)}`;
const res = await fetch(url);
if (!res.ok) {
throw new Error(
`Failed to fetch order book: ${res.status} ${res.statusText}`,
);
}
return (await res.json()) as OrderBookSummary;
}
}
export const api = new PolymarketAPI();