import type { PublicKey } from "@solana/web3.js"; import { Decimal } from "decimal.js"; import type { Graph } from "ngraph.graph"; import createGraph from "ngraph.graph"; import ngraph from "ngraph.path"; import invariant from "tiny-invariant"; export interface Price { quote: string; base: string; price: Decimal; } export interface TokenInfo { address: string; symbol: string; decimals: number; } export interface PriceProvider { prices(): Promise>; } export interface TokenProvider { tokens(): Promise>; } function _pairSymbol( base: string, quote: string ): { pair: string; reversePair: string; } { return { pair: base.toUpperCase() + "-" + quote.toUpperCase(), reversePair: quote.toUpperCase() + "-" + base.toUpperCase(), }; } export class ExchangeRate { readonly priceProviders: PriceProvider[]; readonly tokenProviders: TokenProvider[]; readonly graph: Graph; private _rates: Map; private _symbolTokenMapping: Map; private _addressTokenMapping: Map; constructor(priceProvider: PriceProvider, tokenProvider: TokenProvider) { this.graph = createGraph(); this.priceProviders = []; this.tokenProviders = []; this._rates = new Map(); this._symbolTokenMapping = new Map(); this._addressTokenMapping = new Map(); this.priceProviders.push(priceProvider); this.tokenProviders.push(tokenProvider); } async load(): Promise { for (const provider of this.tokenProviders) { const tokens = await provider.tokens(); tokens.forEach((v) => { this._symbolTokenMapping.set(v.symbol.toUpperCase(), v); this._addressTokenMapping.set(v.address, v); }); } for (const provider of this.priceProviders) { const prices = await provider.prices(); for (const p of prices) { const base = p.base.toUpperCase(); const quote = p.quote.toUpperCase(); this.graph.addNode(base); this.graph.addNode(quote); this.graph.addLink(base, quote, p.price); const { pair } = _pairSymbol(base, quote); this._rates.set(pair, p.price); } } return this; } addPriceProvider(provider: PriceProvider): ExchangeRate { this.priceProviders.push(provider); return this; } addTokenProvider(provider: TokenProvider): ExchangeRate { this.tokenProviders.push(provider); return this; } tokenInfo(key: string | PublicKey): TokenInfo | undefined { return typeof key !== "string" ? this._addressTokenMapping.get(key.toBase58()) : this._symbolTokenMapping.get(key.toUpperCase()); } price( base: string | PublicKey, quote: string | PublicKey ): Decimal | undefined { const quoteSymbol = typeof quote !== "string" ? this.tokenInfo(quote)?.symbol : quote.toUpperCase(); const baseSymbol = typeof base !== "string" ? this.tokenInfo(base)?.symbol : base.toUpperCase(); if (quoteSymbol === undefined || baseSymbol === undefined) { return undefined; } if (baseSymbol === undefined || quoteSymbol === undefined) { return undefined; } return this._price(baseSymbol, quoteSymbol); } swap( base: string | PublicKey, quote: string | PublicKey, amount: Decimal ): Decimal | undefined { const baseToken = this.tokenInfo(base); const quoteToken = this.tokenInfo(quote); if (baseToken === undefined || quoteToken === undefined) { return undefined; } if (baseToken.symbol === quoteToken.symbol) { return amount; } const price = this.price(baseToken.symbol, quoteToken.symbol); if (price === undefined) { return undefined; } return amount.mul(price); } lamportsSwap( base: string | PublicKey, quote: string | PublicKey, lamports: Decimal ): Decimal | undefined { const baseToken = this.tokenInfo(base); const quoteToken = this.tokenInfo(quote); if (quoteToken === undefined || baseToken === undefined) { return undefined; } if (baseToken.symbol === quoteToken.symbol) { return lamports; } const input = lamports.div(new Decimal(10).pow(baseToken.decimals)); return this.swap(baseToken.symbol, quoteToken.symbol, input)?.mul( new Decimal(10).pow(quoteToken.decimals) ); } toLamports(token: string | PublicKey, amount: Decimal): Decimal | undefined { const tokenInfo = this.tokenInfo(token); if (tokenInfo === undefined) { return undefined; } return amount .mul(new Decimal(10).pow(tokenInfo.decimals)) .toDecimalPlaces(0); } toAmount(token: string | PublicKey, amount: Decimal): Decimal | undefined { const tokenInfo = this.tokenInfo(token); if (tokenInfo === undefined) { return undefined; } return amount .div(new Decimal(10).pow(tokenInfo.decimals)) .toDecimalPlaces(tokenInfo.decimals); } private _price(base: string, quote: string): Decimal | undefined { let price = this._directPrice(base.toUpperCase(), quote.toUpperCase()); if (price === undefined) { price = this._pathPrice(base.toUpperCase(), quote.toUpperCase()); } return price; } private _directPrice(base: string, quote: string): Decimal | undefined { const { pair, reversePair } = _pairSymbol(base.toUpperCase(), quote); if (this._rates.has(pair)) { return this._rates.get(pair); } else if (this._rates.has(reversePair)) { const price = this._rates.get(reversePair); invariant(price !== undefined); return new Decimal(1).div(price); } else { return undefined; } } private _pathPrice(base: string, quote: string): Decimal | undefined { if ( !this.graph.hasNode(base.toUpperCase()) || !this.graph.hasNode(quote.toUpperCase()) ) { return undefined; } const path = ngraph .nba(this.graph) .find(quote.toUpperCase(), base.toUpperCase()); if (path.length <= 1) { return undefined; } let price = new Decimal(1); for (let i = 0; i < path.length - 1; i++) { const base = path[i]?.id.toString(); const quote = path[i + 1]?.id.toString(); invariant( base !== undefined && quote !== undefined, "base of quote is undefined" ); const tempPrice = this._directPrice(base, quote); invariant( tempPrice !== undefined, `[${base}-${quote}] temp price is undefined` ); price = price.mul(tempPrice); } return price; } }