market.cache.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import { Connection, PublicKey } from '@solana/web3.js';
  2. import { getMinimalMarketV3, logger, MINIMAL_MARKET_STATE_LAYOUT_V3, MinimalMarketLayoutV3 } from '../helpers';
  3. import { MAINNET_PROGRAM_ID, MARKET_STATE_LAYOUT_V3, Token } from '@raydium-io/raydium-sdk';
  4. export class MarketCache {
  5. private readonly keys: Map<string, MinimalMarketLayoutV3> = new Map<string, MinimalMarketLayoutV3>();
  6. constructor(private readonly connection: Connection) {}
  7. async init(config: { quoteToken: Token }) {
  8. logger.debug({}, `Fetching all existing ${config.quoteToken.symbol} markets...`);
  9. const accounts = await this.connection.getProgramAccounts(MAINNET_PROGRAM_ID.OPENBOOK_MARKET, {
  10. commitment: this.connection.commitment,
  11. dataSlice: {
  12. offset: MARKET_STATE_LAYOUT_V3.offsetOf('eventQueue'),
  13. length: MINIMAL_MARKET_STATE_LAYOUT_V3.span,
  14. },
  15. filters: [
  16. { dataSize: MARKET_STATE_LAYOUT_V3.span },
  17. {
  18. memcmp: {
  19. offset: MARKET_STATE_LAYOUT_V3.offsetOf('quoteMint'),
  20. bytes: config.quoteToken.mint.toBase58(),
  21. },
  22. },
  23. ],
  24. });
  25. for (const account of accounts) {
  26. const market = MINIMAL_MARKET_STATE_LAYOUT_V3.decode(account.account.data);
  27. this.keys.set(account.pubkey.toString(), market);
  28. }
  29. logger.debug({}, `Cached ${this.keys.size} markets`);
  30. }
  31. public save(marketId: string, keys: MinimalMarketLayoutV3) {
  32. if (!this.keys.has(marketId)) {
  33. logger.trace({}, `Caching new market: ${marketId}`);
  34. this.keys.set(marketId, keys);
  35. }
  36. }
  37. public async get(marketId: string): Promise<MinimalMarketLayoutV3> {
  38. if (this.keys.has(marketId)) {
  39. return this.keys.get(marketId)!;
  40. }
  41. logger.trace({}, `Fetching new market keys for ${marketId}`);
  42. const market = await this.fetch(marketId);
  43. this.keys.set(marketId, market);
  44. return market;
  45. }
  46. private fetch(marketId: string): Promise<MinimalMarketLayoutV3> {
  47. return getMinimalMarketV3(this.connection, new PublicKey(marketId), this.connection.commitment);
  48. }
  49. }