All files / src/StakePool/DbSyncStakePoolProvider StakePoolBuilder.ts

80.4% Statements 119/148
58.92% Branches 33/56
94.44% Functions 17/18
85.5% Lines 118/138

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 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330                                    36x                   36x 36x                         36x                         36x 7x 7x   7x 7x       77x 77x 77x       77x 77x     77x       77x 77x 77x       77x 77x 77x       86x 86x   86x 86x 86x   86x       95x 95x       95x         95x 95x 95x         93x 93x 93x                 80x   80x                 80x 80x 80x 80x               33x 33x 33x           33x       36x 36x       36x       19x 19x             19x       1x 1x       1x 1x 1x       128x 128x 128x 128x 128x       46x 46x 46x 46x 33x 33x 33x   46x 31x 31x   46x 19x 19x   46x 33x 46x 44x   46x         89x 89x 89x 89x 89x 89x 17x 17x 17x 17x 13x 13x 13x 13x   17x 13x                         13x   17x 72x 9x 9x 9x 5x 5x 5x 5x   63x 19x 19x         19x   89x 89x 89x       4x 4x 4x 4x 4x                                                                                
/* eslint-disable sonarjs/no-nested-template-literals */
import {
  BlockfrostPoolMetricsModel,
  EpochModel,
  OrderByOptions,
  OwnerAddressModel,
  PoolAPY,
  PoolAPYModel,
  PoolDataModel,
  PoolMetricsModel,
  PoolRegistrationModel,
  PoolRetirementModel,
  PoolUpdateModel,
  QueryPoolsApyArgs,
  RelayModel,
  StakePoolStatsModel,
  SubQuery
} from './types';
import {
  Cardano,
  MultipleChoiceSearchFilter,
  ProviderError,
  ProviderFailure,
  QueryStakePoolsArgs,
  StakePoolStats
} from '@cardano-sdk/core';
import { Logger } from 'ts-log';
import { Pool, QueryResult } from 'pg';
import { findLastEpoch } from '../../util';
import {
  mapAddressOwner,
  mapBlockfrostPoolMetrics,
  mapEpoch,
  mapPoolAPY,
  mapPoolData,
  mapPoolMetrics,
  mapPoolRegistration,
  mapPoolRetirement,
  mapPoolStats,
  mapPoolUpdate,
  mapRelay
} from './mappers';
import Queries, {
  addSentenceToQuery,
  blockfrostQuery,
  buildOrQueryFromClauses,
  findPoolStats,
  getIdentifierFullJoinClause,
  getIdentifierWhereClause,
  getStatusWhereClause,
  poolsByPledgeMetSubqueries,
  withPagination,
  withSort
} from './queries';
 
export class StakePoolBuilder {
  #db: Pool;
  #logger: Logger;
  constructor(db: Pool, logger: Logger) {
    this.#db = db;
    this.#logger = logger;
  }
 
  public async queryRetirements(hashesIds: number[]) {
    this.#logger.debug('About to query pool retirements');
    const result: QueryResult<PoolRetirementModel> = await this.#db.query(Queries.findPoolsRetirements, [hashesIds]);
    return result.rows.length > 0 ? result.rows.map(mapPoolRetirement) : [];
  }
 
  public async queryRegistrations(hashesIds: number[]) {
    this.#logger.debug('About to query pool registrations');
    const result: QueryResult<PoolRegistrationModel> = await this.#db.query(Queries.findPoolsRegistrations, [
      hashesIds
    ]);
    return result.rows.length > 0 ? result.rows.map(mapPoolRegistration) : [];
  }
 
  public async queryPoolRelays(updatesIds: number[]) {
    this.#logger.debug('About to query pool relays');
    const result: QueryResult<RelayModel> = await this.#db.query(Queries.findPoolsRelays, [updatesIds]);
    return result.rows.length > 0 ? result.rows.map(mapRelay) : [];
  }
 
  public async queryPoolOwners(updatesIds: number[]) {
    this.#logger.debug('About to query pool owners');
    const result: QueryResult<OwnerAddressModel> = await this.#db.query(Queries.findPoolsOwners, [updatesIds]);
    return result.rows.length > 0 ? result.rows.map(mapAddressOwner) : [];
  }
 
  public async queryPoolAPY(hashesIds: number[], epochLength: number, options?: QueryPoolsApyArgs): Promise<PoolAPY[]> {
    this.#logger.debug('About to query pools APY');
    const defaultSort: OrderByOptions[] = [{ field: 'apy', order: 'desc' }];
 
    const sorted = withSort(Queries.findPoolAPY(epochLength, options?.apyEpochsBackLimit), options?.sort, defaultSort);
    const { query, args } = withPagination(sorted, [hashesIds], options?.pagination);
    const result = await this.#db.query<PoolAPYModel>(query, args);
 
    return result.rows.map(mapPoolAPY);
  }
 
  public async queryPoolData(updatesIds: number[], useBlockfrost: boolean, options?: QueryStakePoolsArgs) {
    this.#logger.debug('About to query pool data');
    const defaultSort: OrderByOptions[] = [
      { field: 'name', order: 'asc' },
      { field: 'pool_id', order: 'asc' }
    ];
    const sorted = withSort(
      useBlockfrost ? Queries.findBlockfrostPoolsData : Queries.findPoolsData,
      options?.sort,
      defaultSort
    );
    const { query, args } = withPagination(sorted, [updatesIds], options?.pagination);
    const result = await this.#db.query<PoolDataModel>(query, args);
    return result.rows.length > 0 ? result.rows.map(mapPoolData) : [];
  }
 
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  public async queryPoolHashes(query: string, params: any[] = []) {
    this.#logger.debug('About to query pool hashes');
    const result: QueryResult<PoolUpdateModel> = await this.#db.query(query, params);
    return result.rows.length > 0 ? result.rows.map(mapPoolUpdate) : [];
  }
 
  public async queryPoolMetrics(
    hashesIds: number[],
    totalStake: string | null,
    useBlockfrost: boolean,
    options?: QueryStakePoolsArgs
  ) {
    this.#logger.debug('About to query pool metrics');
 
    Iif (useBlockfrost) {
      const sorted = withSort(Queries.findBlockfrostPoolsMetrics, options?.sort, [
        { field: 'saturation', order: 'desc' }
      ]);
      const { query, args } = withPagination(sorted, [hashesIds], options?.pagination);
      const result = await this.#db.query<BlockfrostPoolMetricsModel>(query, args);
      return result.rows.map(mapBlockfrostPoolMetrics);
    }
 
    const sorted = withSort(Queries.findPoolsMetrics, options?.sort, [{ field: 'saturation', order: 'desc' }]);
    const { query, args } = withPagination(sorted, [hashesIds, totalStake], options?.pagination);
    const result = await this.#db.query<PoolMetricsModel>(query, args);
    return result.rows.length > 0 ? result.rows.map(mapPoolMetrics) : [];
  }
 
  public buildPoolsByIdentifierQuery(
    identifier: MultipleChoiceSearchFilter<
      Partial<Pick<Cardano.PoolParameters, 'id'> & Pick<Cardano.StakePoolMetadata, 'name' | 'ticker'>>
    >
  ) {
    const { where, params } = getIdentifierWhereClause(identifier);
    const whereClause = 'WHERE '.concat(where);
    const query = `
    ${Queries.IDENTIFIER_QUERY.SELECT_CLAUSE}
    ${Queries.IDENTIFIER_QUERY.JOIN_CLAUSE.POOL_UPDATE}
    ${Queries.IDENTIFIER_QUERY.JOIN_CLAUSE.OFFLINE_METADATA}
    ${whereClause}
    `;
    return { id: { isPrimary: true, name: 'pools_by_identifier' }, params, query };
  }
 
  public buildPoolsByStatusQuery(status: Cardano.StakePoolStatus[]) {
    const whereClause = getStatusWhereClause(status);
    const query = `
    ${Queries.STATUS_QUERY.SELECT_CLAUSE}
    WHERE ${whereClause}
    `;
    return { id: { isPrimary: true, name: 'pools_by_status' }, query };
  }
 
  public buildPoolsByPledgeMetQuery(pledgeMet: boolean) {
    const subQueries = [...poolsByPledgeMetSubqueries];
    subQueries.push({
      id: { isPrimary: true, name: 'pools_by_pledge_met' },
      query: `
    ${Queries.POOLS_WITH_PLEDGE_MET.SELECT_CLAUSE} 
    ${Queries.POOLS_WITH_PLEDGE_MET.JOIN_CLAUSE} 
    WHERE ${Queries.POOLS_WITH_PLEDGE_MET.WHERE_CLAUSE(pledgeMet)}`
    });
    return subQueries;
  }
 
  public async getLastEpoch() {
    this.#logger.debug('About to query last epoch');
    const result: QueryResult<EpochModel> = await this.#db.query({
      name: 'current_epoch',
      text: findLastEpoch
    });
    const lastEpoch = result.rows[0];
    Iif (!lastEpoch) throw new ProviderError(ProviderFailure.Unknown, null, "Couldn't find last epoch");
    return lastEpoch.no;
  }
 
  public async getLastEpochWithData() {
    this.#logger.debug('About to query last epoch with data');
    const result: QueryResult<EpochModel> = await this.#db.query(Queries.findLastEpochWithData);
    const lastEpoch = result.rows[0];
    Iif (!lastEpoch) throw new ProviderError(ProviderFailure.Unknown, null, "Couldn't find last epoch");
    return mapEpoch(lastEpoch);
  }
 
  public buildOrQuery(filters: QueryStakePoolsArgs['filters']) {
    const subQueries: SubQuery[] = [];
    const params = [];
    let query = Queries.findPools;
    if (filters?.identifier && filters.identifier.values.length > 0) {
      const { id: _id, query: _query, params: _params } = this.buildPoolsByIdentifierQuery(filters.identifier);
      subQueries.push({ id: _id, query: _query });
      params.push(..._params);
    }
    if (filters?.status) {
      const statusQuery = this.buildPoolsByStatusQuery(filters.status);
      subQueries.push(statusQuery);
    }
    if (filters?.pledgeMet !== undefined) {
      const pledgeMetQuery = this.buildPoolsByPledgeMetQuery(filters.pledgeMet);
      subQueries.push(...pledgeMetQuery);
    }
    if (filters?.status || filters?.pledgeMet !== undefined)
      subQueries.unshift({ id: { name: 'current_epoch' }, query: findLastEpoch });
    if (subQueries.length > 0) {
      query = subQueries.length > 1 ? buildOrQueryFromClauses(subQueries) : subQueries[0].query;
    }
    return { params, query };
  }
 
  // eslint-disable-next-line max-statements
  public buildAndQuery(filters: QueryStakePoolsArgs['filters']) {
    let query = Queries.findPools;
    let groupByClause = ' GROUP BY ph.id, pu.id ORDER BY ph.id DESC';
    const params = [];
    const whereClause = [];
    const containsIdentifierCondition = filters?.identifier && filters.identifier.values.length > 0;
    if (filters?.pledgeMet !== undefined) {
      const { WITH_CLAUSE, SELECT_CLAUSE, JOIN_CLAUSE, WHERE_CLAUSE } = Queries.POOLS_WITH_PLEDGE_MET;
      query = WITH_CLAUSE + SELECT_CLAUSE + JOIN_CLAUSE;
      whereClause.push(WHERE_CLAUSE(filters.pledgeMet));
      if (containsIdentifierCondition) {
        query = addSentenceToQuery(query, `${getIdentifierFullJoinClause()}`);
        const { where, params: identifierParams } = getIdentifierWhereClause(filters!.identifier!);
        whereClause.push(where);
        params.push(...identifierParams);
      }
      if (filters.status) {
        query = addSentenceToQuery(
          query,
          `
          LEFT JOIN pool_retire pr ON 
            pr.id = (
              SELECT id
              FROM pool_retire pr2
              WHERE pr2.hash_id = ph.id
              ORDER BY id desc 
              LIMIT 1
            )
          `
        );
        whereClause.push(getStatusWhereClause(filters.status, { activeEpoch: 'ph.active_epoch_no' }));
      }
      groupByClause = ' GROUP BY ph.id, ph.update_id ORDER BY ph.id DESC';
    } else if (filters?.status) {
      query = `${Queries.STATUS_QUERY.WITH_CLAUSE} ${Queries.STATUS_QUERY.SELECT_CLAUSE}`;
      whereClause.push(getStatusWhereClause(filters.status));
      if (containsIdentifierCondition) {
        query = addSentenceToQuery(query, Queries.IDENTIFIER_QUERY.JOIN_CLAUSE.OFFLINE_METADATA);
        const { where, params: identifierParams } = getIdentifierWhereClause(filters!.identifier!);
        whereClause.push(where);
        params.push(...identifierParams);
      }
    } else if (containsIdentifierCondition) {
      const { where, params: identifierParams } = getIdentifierWhereClause(filters!.identifier!);
      query = `
        ${Queries.IDENTIFIER_QUERY.SELECT_CLAUSE}
        ${getIdentifierFullJoinClause()}
        WHERE ${where}
        `;
      params.push(...identifierParams);
    }
    if (whereClause.length > 0) query = addSentenceToQuery(query, ` WHERE ${whereClause.join(' AND ')}`);
    query = addSentenceToQuery(query, groupByClause);
    return { params, query };
  }
 
  public async queryPoolStats(): Promise<StakePoolStats> {
    this.#logger.debug('About to get pool stats');
    const result: QueryResult<StakePoolStatsModel> = await this.#db.query(findPoolStats);
    const poolStats = result.rows[0];
    Iif (!poolStats) throw new ProviderError(ProviderFailure.Unknown, null, "Couldn't fetch pool stats");
    return mapPoolStats(poolStats);
  }
 
  public buildBlockfrostQuery(filters: QueryStakePoolsArgs['filters']): { params: string[]; query: string } {
    const query = blockfrostQuery.SELECT;
    let params: string[] = [];
 
    Iif (!filters) return { params, query };
 
    const { _condition, identifier, pledgeMet, status } = filters;
    const clauses: string[] = [query];
    const whereConditions: string[] = [];
 
    Iif (identifier || pledgeMet !== undefined) clauses.push(blockfrostQuery.identifierOrPledge.JOIN);
 
    Iif (identifier) {
      let where: string;
      ({ params, where } = getIdentifierWhereClause(filters!.identifier!));
 
      clauses.push(blockfrostQuery.identifier.JOIN);
      whereConditions.push(where);
    }
 
    Iif (pledgeMet !== undefined || status) clauses.push(blockfrostQuery.pledgeOrStatus.JOIN);
 
    Iif (pledgeMet !== undefined) whereConditions.push(blockfrostQuery.pledge.WHERE(pledgeMet));
 
    Iif (status) whereConditions.push(blockfrostQuery.status.WHERE(status));
 
    // this happens when an empty object is provided as filter parameter
    Iif (whereConditions.length === 0) return { params, query };
 
    return {
      params,
      query: `${clauses.join('')}
      WHERE
      ${whereConditions.join(` ${_condition === 'or' ? 'OR' : 'AND'}\n  `)}`
    };
  }
}