|
| 1 | +// Thin wrapper around @buidlrrr/rain-sdk. SDK is ESM-only; we use dynamic |
| 2 | +// import() to stay CJS-friendly. All methods return raw Rain SDK types; |
| 3 | +// the normalizer maps them into the Unified schema. |
| 4 | + |
| 5 | +import { rainErrorMapper } from './errors'; |
| 6 | +import { logger } from '../../utils/logger'; |
| 7 | + |
| 8 | +// ESM dynamic import (same pattern as Opinion adapter). |
| 9 | +type RainSdk = typeof import('@buidlrrr/rain-sdk'); |
| 10 | +type RainClient = InstanceType<RainSdk['Rain']>; |
| 11 | + |
| 12 | +let sdkPromise: Promise<RainSdk> | undefined; |
| 13 | +function loadSdk(): Promise<RainSdk> { |
| 14 | + if (!sdkPromise) sdkPromise = import('@buidlrrr/rain-sdk'); |
| 15 | + return sdkPromise; |
| 16 | +} |
| 17 | + |
| 18 | +export interface RainFetcherConfig { |
| 19 | + environment?: 'development' | 'stage' | 'production'; |
| 20 | + subgraphUrl?: string; |
| 21 | + subgraphApiKey?: string; |
| 22 | + rpcUrl?: string; |
| 23 | + wsRpcUrl?: string; |
| 24 | +} |
| 25 | + |
| 26 | +// Re-export raw SDK types as the fetcher's contract surface. |
| 27 | +export type RainRawMarket = Awaited<ReturnType<RainClient['getPublicMarkets']>>[number]; |
| 28 | +export type RainRawMarketDetails = Awaited<ReturnType<RainClient['getMarketDetails']>>; |
| 29 | +export type RainRawOptionPrice = Awaited<ReturnType<RainClient['getMarketPrices']>>[number]; |
| 30 | +export type RainRawPositions = Awaited<ReturnType<RainClient['getPositions']>>; |
| 31 | +export type RainRawBalance = Awaited<ReturnType<RainClient['getSmartAccountBalance']>>; |
| 32 | +export type RainRawPriceHistory = Awaited<ReturnType<RainClient['getPriceHistory']>>; |
| 33 | +export type RainRawTransactions = Awaited<ReturnType<RainClient['getTransactions']>>; |
| 34 | +export type RainRawMarketTransactions = Awaited<ReturnType<RainClient['getMarketTransactions']>>; |
| 35 | + |
| 36 | +// What the fetcher returns: a market plus its enriched details (when available). |
| 37 | +export interface RainMarketWithDetails { |
| 38 | + market: RainRawMarket; |
| 39 | + details?: RainRawMarketDetails; |
| 40 | +} |
| 41 | + |
| 42 | +const DETAIL_ENRICHMENT_LIMIT = 25; |
| 43 | +const DETAIL_PARALLEL_BATCH = 5; |
| 44 | + |
| 45 | +export class RainFetcher { |
| 46 | + private readonly config: RainFetcherConfig; |
| 47 | + private client?: RainClient; |
| 48 | + |
| 49 | + constructor(config: RainFetcherConfig) { |
| 50 | + this.config = config; |
| 51 | + } |
| 52 | + |
| 53 | + private async getClient(): Promise<RainClient> { |
| 54 | + if (!this.client) { |
| 55 | + const sdk = await loadSdk(); |
| 56 | + this.client = new sdk.Rain({ |
| 57 | + environment: this.config.environment ?? 'production', |
| 58 | + rpcUrl: this.config.rpcUrl, |
| 59 | + subgraphUrl: this.config.subgraphUrl, |
| 60 | + subgraphApiKey: this.config.subgraphApiKey, |
| 61 | + wsRpcUrl: this.config.wsRpcUrl, |
| 62 | + }); |
| 63 | + } |
| 64 | + return this.client; |
| 65 | + } |
| 66 | + |
| 67 | + /** |
| 68 | + * List markets. Enriches the first `DETAIL_ENRICHMENT_LIMIT` with on-chain |
| 69 | + * details (options + prices) in bounded-parallel batches. Beyond that, only |
| 70 | + * the basic list-view fields are populated. ponytail: N+1 enrichment is |
| 71 | + * fine for the typical 25-market view; switch to a multicall bundler if a |
| 72 | + * larger feed needs full options on every row. |
| 73 | + */ |
| 74 | + async fetchRawMarkets(params?: { |
| 75 | + limit?: number; |
| 76 | + offset?: number; |
| 77 | + sortBy?: 'Liquidity' | 'Volumn' | 'latest'; |
| 78 | + status?: string; |
| 79 | + }): Promise<RainMarketWithDetails[]> { |
| 80 | + try { |
| 81 | + const client = await this.getClient(); |
| 82 | + const markets = await client.getPublicMarkets({ |
| 83 | + limit: params?.limit, |
| 84 | + offset: params?.offset, |
| 85 | + sortBy: params?.sortBy ?? 'Liquidity', |
| 86 | + status: params?.status as any, |
| 87 | + }); |
| 88 | + |
| 89 | + const enrichUpTo = Math.min(markets.length, DETAIL_ENRICHMENT_LIMIT); |
| 90 | + const enriched: RainMarketWithDetails[] = []; |
| 91 | + |
| 92 | + const resolveId = (m: any): string | undefined => m?._id ?? m?.id; |
| 93 | + |
| 94 | + for (let i = 0; i < enrichUpTo; i += DETAIL_PARALLEL_BATCH) { |
| 95 | + const batch = markets.slice(i, i + DETAIL_PARALLEL_BATCH); |
| 96 | + const details = await Promise.all( |
| 97 | + batch.map((m) => { |
| 98 | + const mid = resolveId(m); |
| 99 | + return mid ? this.safeFetchDetails(client, mid) : Promise.resolve(undefined); |
| 100 | + }), |
| 101 | + ); |
| 102 | + batch.forEach((m, j) => enriched.push({ market: m, details: details[j] })); |
| 103 | + } |
| 104 | + |
| 105 | + for (let i = enrichUpTo; i < markets.length; i++) { |
| 106 | + enriched.push({ market: markets[i] }); |
| 107 | + } |
| 108 | + |
| 109 | + return enriched; |
| 110 | + } catch (error: any) { |
| 111 | + throw rainErrorMapper.mapError(error); |
| 112 | + } |
| 113 | + } |
| 114 | + |
| 115 | + async fetchRawMarket(marketId: string): Promise<RainMarketWithDetails | null> { |
| 116 | + try { |
| 117 | + const client = await this.getClient(); |
| 118 | + const details = await client.getMarketDetails(marketId); |
| 119 | + if (!details) return null; |
| 120 | + return { |
| 121 | + market: { |
| 122 | + id: details.id, |
| 123 | + title: details.title, |
| 124 | + totalVolume: '0', |
| 125 | + status: details.status, |
| 126 | + contractAddress: details.contractAddress, |
| 127 | + } as RainRawMarket, |
| 128 | + details, |
| 129 | + }; |
| 130 | + } catch (error: any) { |
| 131 | + throw rainErrorMapper.mapError(error); |
| 132 | + } |
| 133 | + } |
| 134 | + |
| 135 | + async fetchRawOHLCV(marketId: string, optionIndex: number, interval: string, limit?: number): Promise<RainRawPriceHistory | null> { |
| 136 | + if (!this.config.subgraphUrl) return null; |
| 137 | + try { |
| 138 | + const client = await this.getClient(); |
| 139 | + return await client.getPriceHistory({ |
| 140 | + marketId, |
| 141 | + optionIndex, |
| 142 | + interval: interval as any, |
| 143 | + limit, |
| 144 | + }); |
| 145 | + } catch (error: any) { |
| 146 | + throw rainErrorMapper.mapError(error); |
| 147 | + } |
| 148 | + } |
| 149 | + |
| 150 | + async fetchRawPositions(walletAddress: string): Promise<RainRawPositions> { |
| 151 | + try { |
| 152 | + const client = await this.getClient(); |
| 153 | + return await client.getPositions(walletAddress as `0x${string}`); |
| 154 | + } catch (error: any) { |
| 155 | + throw rainErrorMapper.mapError(error); |
| 156 | + } |
| 157 | + } |
| 158 | + |
| 159 | + async fetchRawBalance(walletAddress: string, tokenAddresses: string[]): Promise<RainRawBalance> { |
| 160 | + try { |
| 161 | + const client = await this.getClient(); |
| 162 | + return await client.getSmartAccountBalance({ |
| 163 | + address: walletAddress as `0x${string}`, |
| 164 | + tokenAddresses: tokenAddresses as `0x${string}`[], |
| 165 | + }); |
| 166 | + } catch (error: any) { |
| 167 | + throw rainErrorMapper.mapError(error); |
| 168 | + } |
| 169 | + } |
| 170 | + |
| 171 | + async fetchRawMarketTrades(marketAddress: string, limit?: number): Promise<RainRawMarketTransactions | null> { |
| 172 | + if (!this.config.subgraphUrl) return null; |
| 173 | + try { |
| 174 | + const client = await this.getClient(); |
| 175 | + return await client.getMarketTransactions({ |
| 176 | + marketAddress: marketAddress as `0x${string}`, |
| 177 | + first: limit, |
| 178 | + }); |
| 179 | + } catch (error: any) { |
| 180 | + throw rainErrorMapper.mapError(error); |
| 181 | + } |
| 182 | + } |
| 183 | + |
| 184 | + async fetchRawUserTrades(walletAddress: string, marketAddress?: string, limit?: number): Promise<RainRawTransactions | null> { |
| 185 | + if (!this.config.subgraphUrl) return null; |
| 186 | + try { |
| 187 | + const client = await this.getClient(); |
| 188 | + return await client.getTransactions({ |
| 189 | + address: walletAddress as `0x${string}`, |
| 190 | + first: limit, |
| 191 | + marketAddress: marketAddress as `0x${string}` | undefined, |
| 192 | + }); |
| 193 | + } catch (error: any) { |
| 194 | + throw rainErrorMapper.mapError(error); |
| 195 | + } |
| 196 | + } |
| 197 | + |
| 198 | + /** Expose the underlying SDK client for trade-tx builders in index.ts. */ |
| 199 | + async sdkClient(): Promise<RainClient> { |
| 200 | + return this.getClient(); |
| 201 | + } |
| 202 | + |
| 203 | + private async safeFetchDetails(client: RainClient, marketId: string): Promise<RainRawMarketDetails | undefined> { |
| 204 | + try { |
| 205 | + return await client.getMarketDetails(marketId); |
| 206 | + } catch (err) { |
| 207 | + logger.warn('RainFetcher: getMarketDetails failed', { marketId, error: String(err) }); |
| 208 | + return undefined; |
| 209 | + } |
| 210 | + } |
| 211 | + |
| 212 | + async close(): Promise<void> { |
| 213 | + if (this.client && typeof (this.client as any).destroyWebSocket === 'function') { |
| 214 | + try { |
| 215 | + await (this.client as any).destroyWebSocket(); |
| 216 | + } catch { /* ignore */ } |
| 217 | + } |
| 218 | + this.client = undefined; |
| 219 | + } |
| 220 | +} |
0 commit comments