All files / src/StakePool/TypeormStakePoolProvider util.ts

79.06% Statements 68/86
75% Branches 39/52
71.42% Functions 5/7
76.38% Lines 55/72

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                      42x 42x                   42x                                                         42x                               42x   42x   42x 62x   59x   59x     42x 49x     42x 62x   30x 30x 30x 30x   30x 11x 11x   30x 19x 19x 19x 40x 40x 40x     19x 19x 11x   9x   2x     19x 8x   8x           19x 19x   30x               30x           42x               42x                                                                                       42x     66x   42x 11x   10x   9x   9x 7x 5x   3x 7x 2x   1x    
/* eslint-disable complexity */
/* eslint-disable sonarjs/cognitive-complexity */
import {
  Cardano,
  FilterCondition,
  FuzzyOptions,
  QueryStakePoolsArgs,
  SortField,
  SortOrder,
  StakePoolSortOptions
} from '@cardano-sdk/core';
import { Percent } from '@cardano-sdk/util';
import { PoolRewardsEntity } from '@cardano-sdk/projection-typeorm';
import { RosComputeParams } from '../../PgBoss';
 
type StakePoolWhereClauseArgs = {
  name?: string[];
  id?: string[];
  ticker?: string[];
  status?: string[];
};
 
export const stakePoolSearchSelection = [
  'pool.id',
  'pool.status',
  'params.rewardAccount',
  'params.pledge',
  'params.cost',
  'params.margin',
  'params.relays',
  'params.owners',
  'params.vrf',
  'params.metadataUrl',
  'params.metadataHash',
  'metadata.name',
  'metadata.homepage',
  'metadata.ticker',
  'metadata.description',
  'metadata.ext',
  'metrics.mintedBlocks',
  'metrics.liveDelegators',
  'metrics.activeStake',
  'metrics.liveStake',
  'metrics.activeSize',
  'metrics.liveSize',
  'metrics.liveSaturation',
  'metrics.livePledge',
  'metrics.lastRos',
  'metrics.ros'
];
 
export const sortSelectionMap: { [key in SortField]: string } = {
  apy: 'metrics_ros',
  blocks: 'metrics_minted_blocks',
  cost: 'params_cost',
  lastRos: 'metrics_last_ros',
  liveStake: 'metrics_live_stake',
  // PERF: this may be source of performances issue due to its complexity.
  // In case of performances degradation we need to keep in mind this.
  margin: "(margin->>'numerator')::numeric / (margin->>'denominator')::numeric",
  name: 'lower(metadata.name)',
  pledge: 'params_pledge',
  ros: 'metrics_ros',
  saturation: 'metrics_live_saturation',
  ticker: 'metadata_ticker'
};
 
export const stakePoolSearchTotalCount = 'count(*) over () as total_count';
 
const defaultSortOption = { field: 'name', order: 'asc' } as const;
 
export const getSortOptions = (sortByScore: boolean, sort: StakePoolSortOptions = defaultSortOption) => {
  if (sortByScore) return { field: 'score', order: 'ASC' as const };
 
  const order = sort.order.toUpperCase() as Uppercase<SortOrder>;
 
  return { field: sortSelectionMap[sort.field], order };
};
 
export const getFilterCondition = (condition?: FilterCondition, defaultCondition: Uppercase<FilterCondition> = 'OR') =>
  condition ? (condition.toUpperCase() as Uppercase<FilterCondition>) : defaultCondition;
 
// eslint-disable-next-line max-statements
export const getWhereClauseAndArgs = (filters: QueryStakePoolsArgs['filters'], textFilter: boolean) => {
  if (!filters) return { args: {}, clause: '1=1' };
 
  let args: StakePoolWhereClauseArgs = {};
  const clauses: string[] = [];
  const identifierArgs: { [key: string]: unknown[] } = {};
  const condition = getFilterCondition(filters._condition, 'AND');
 
  if (filters.status?.length) {
    args = { ...args, status: filters.status };
    clauses.push('pool.status IN (:...status)');
  }
  if (!textFilter && filters.identifier && filters.identifier.values.length > 0) {
    const identifierClauses: string[] = [];
    const identifierCondition = getFilterCondition(filters.identifier?._condition, 'OR');
    for (const item of filters.identifier.values) {
      const key = item.id ? 'id' : item.name ? 'name' : 'ticker';
      const value = item[key]!.toLocaleLowerCase();
      identifierArgs[key] ? identifierArgs[key].push(value) : (identifierArgs[key] = [value]);
    }
 
    if ('id' in identifierArgs) identifierClauses.push('LOWER(pool.id) IN (:...id)');
    if ('name' in identifierArgs) {
      if (identifierArgs.name.length === 1) {
        // exact match first then regexp
        identifierClauses.push('(LOWER(metadata.name) IN (:...name) OR LOWER(metadata.name) ~* (:...name))');
      } else {
        identifierClauses.push('LOWER(metadata.name) IN (:...name)');
      }
    }
    if ('ticker' in identifierArgs) {
      if (identifierArgs.ticker.length === 1) {
        // exact match first then regexp
        identifierClauses.push('(LOWER(metadata.ticker) IN (:...ticker) OR LOWER(metadata.ticker) ~* (:...ticker))');
      } else E{
        identifierClauses.push('LOWER(metadata.ticker) IN (:...ticker)');
      }
    }
 
    const identifierFilters = identifierClauses.join(` ${identifierCondition} `);
    clauses.push(` (${identifierFilters}) `);
  }
  Iif (filters.pledgeMet !== undefined && filters.pledgeMet !== null) {
    if (filters.pledgeMet) {
      clauses.push('params.pledge<=metrics.live_pledge');
    } else {
      clauses.push('params.pledge>metrics.live_pledge');
    }
  }
 
  return {
    args: { ...args, ...identifierArgs },
    clause: clauses.join(` ${condition} `)
  };
};
 
const millisecondsPerYear = 1000 * 3600 * 24 * 365;
 
/**
 * Computes the annualized ROS for a give stake pool. If `epochs` is not specified, the life time ROS
 * of the stake pool is computed.
 *
 * @returns the ROS
 */
export const computeROS = async ({ dataSource, epochs, logger, stakePool: { id } }: RosComputeParams) => {
  let ros = Percent(0);
 
  logger.debug(`Going to fetch ${epochs || 'all'} epoch rewards for stake pool ${id}`);
 
  const result = await dataSource.getRepository(PoolRewardsEntity).find({
    order: { epochNo: 'DESC' },
    select: {
      activeStake: true,
      epochLength: true,
      epochNo: true,
      id: true,
      leaderRewards: true,
      memberActiveStake: true,
      memberRewards: true,
      pledge: true,
      rewards: true
    },
    where: { stakePool: { id } },
    ...(epochs ? { take: epochs } : undefined)
  });
 
  Iif (result.length > 0) {
    let period = 0;
    let returnInPeriod = 0;
 
    for (const epochRewards of result) {
      const { epochLength, memberActiveStake, memberRewards } = epochRewards;
 
      period += epochLength!;
      returnInPeriod += memberActiveStake === 0n ? 0 : Number(memberRewards) / Number(memberActiveStake);
    }
 
    ros = Percent((returnInPeriod * millisecondsPerYear) / period);
  }
 
  logger.debug(`Stake pool ${id} ROS: ${ros}`);
 
  // eslint-disable-next-line @typescript-eslint/no-shadow, @typescript-eslint/no-unused-vars
  return [ros, result.map(({ id, ...rest }) => rest) as Cardano.StakePoolEpochRewards[]] as const;
};
 
type NotUndefinedFilters = Exclude<QueryStakePoolsArgs['filters'], undefined>;
 
export const withTextFilter = (
  filters?: QueryStakePoolsArgs['filters']
): filters is NotUndefinedFilters & Required<Pick<NotUndefinedFilters, 'text'>> =>
  (filters && typeof filters.text === 'string' && filters.text !== '') as unknown as boolean;
 
export const validateFuzzyOptions = (arg: string) => {
  const options = JSON.parse(arg) as FuzzyOptions;
 
  if (typeof options !== 'object' || !options) throw new Error('must be an object');
 
  const { threshold, weights } = options;
 
  if (typeof threshold !== 'number') throw new Error('threshold must be a number');
  if (threshold < 0 || threshold > 1) throw new Error('expected 0 <= threshold <= 1');
  if (typeof weights !== 'object' || !weights) throw new Error('weights must be an object');
 
  for (const weight of ['description', 'homepage', 'name', 'poolId', 'ticker'] as const)
    if (typeof weights[weight] !== 'number' || weights[weight] < 0)
      throw new Error(`weights.${weight} must be a positive number`);
 
  return options;
};