All files / src/Blockfrost BlockfrostService.ts

13.2% Statements 7/53
0% Branches 0/9
0% Functions 0/8
13.72% Lines 7/51

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132  35x 35x 35x 35x     35x 35x                             35x                                                                                                                                                                                                                        
import { AvailableNetworks } from '../Program/programs/blockfrostWorker';
import { BlockFrostAPI } from '@blockfrost/blockfrost-js';
import { BlockfrostCacheBuilder } from './builder';
import { Cardano, Provider } from '@cardano-sdk/core';
import { HttpService } from '../Http';
import { Logger } from 'ts-log';
import { Pool } from 'pg';
import { Router } from 'express';
import { setPoolMetric } from './queries';
 
type BlockfrostMetrics = Awaited<ReturnType<BlockFrostAPI['poolsById']>>;
 
export interface BlockfrostServiceConfig {
  blockfrostApiKey: string;
  cacheTtl: number;
  network: AvailableNetworks;
}
 
export interface BlockfrostServiceDependencies {
  db: Pool;
  logger: Logger;
}
 
export class BlockfrostService extends HttpService {
  #api: BlockFrostAPI;
  #builder: BlockfrostCacheBuilder;
  #cacheTtl: number;
  #db: Pool;
  #shuttingDown?: boolean;
 
  constructor(cfg: BlockfrostServiceConfig, deps: BlockfrostServiceDependencies) {
    const { blockfrostApiKey, cacheTtl, network } = cfg;
    const { db, logger } = deps;
    const provider: Provider = { healthCheck: () => Promise.resolve({ ok: false }) };
 
    super('blockfrost-cache', provider, Router(), __dirname, logger);
 
    this.#api = new BlockFrostAPI({ network, projectId: blockfrostApiKey });
    this.#builder = new BlockfrostCacheBuilder(db, this.logger);
    this.#cacheTtl = cacheTtl;
    this.#db = db;
 
    provider.healthCheck = async () => {
      try {
        await db.query('SELECT 1');
        await this.#api.pools();
      } catch (error) {
        this.logger.error(error);
 
        return { ok: false };
      }
 
      return { ok: true };
    };
  }
 
  protected initializeImpl() {
    return Promise.resolve();
  }
 
  protected startImpl() {
    return Promise.resolve();
  }
 
  protected shutdownImpl() {
    this.#shuttingDown = true;
 
    return Promise.resolve();
  }
 
  public async refreshCache() {
    const [pools, currentEpoch] = await Promise.all([
      this.#builder.getPools(this.#cacheTtl),
      this.#builder.getCurrentEpoch()
    ]);
 
    for (const { id, view } of pools) {
      Iif (this.#shuttingDown) return;
 
      this.logger.debug(`Going to fetch data from Blockfrost for pool ${view}`);
      const metrics = await this.#api.poolsById(view);
 
      const lastRetire = await this.#builder.getLastRetire(id);
      const firstUpdate = await this.#builder.getFirstUpdateAfterBlock(id, lastRetire ? lastRetire.block_no : 0);
      const status = firstUpdate
        ? firstUpdate.epoch_no <= currentEpoch
          ? Cardano.StakePoolStatus.Active
          : Cardano.StakePoolStatus.Activating
        : lastRetire!.retiring_epoch <= currentEpoch
        ? Cardano.StakePoolStatus.Retired
        : Cardano.StakePoolStatus.Retiring;
 
      this.logger.debug(`Going to write Blockfrost cache data for pool ${view}`);
      await this.writeCache(id, metrics, status);
    }
  }
 
  private async writeCache(id: string, metrics: BlockfrostMetrics, status: Cardano.StakePoolStatus) {
    const client = await this.#db.connect();
 
    try {
      await client.query('BEGIN');
 
      try {
        await client.query(setPoolMetric, [
          id,
          0,
          Date.now(),
          metrics.blocks_minted,
          metrics.live_delegators,
          metrics.active_stake,
          metrics.live_stake,
          metrics.live_pledge,
          metrics.live_saturation,
          metrics.reward_account,
          JSON.stringify([metrics.owners, metrics.registration.reverse(), metrics.retirement]),
          status
        ]);
 
        await client.query('COMMIT');
      } catch (error) {
        this.logger.error(error);
        await client.query('ROLLBACK');
      }
    } catch (error) {
      this.logger.error(error);
    }
 
    client.release();
  }
}