All files / src/PgBoss stakePoolRewardsHandler.ts

17.09% Statements 20/117
0% Branches 0/14
0% Functions 0/11
18.09% Lines 19/105

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 24036x 36x 36x                 36x   36x 36x 36x 36x 36x     36x     36x                                             36x                                               36x                           36x                                                   36x                                                       36x                                                             36x                                                                     36x               36x                                                      
import { Between, DataSource, LessThanOrEqual } from 'typeorm';
import { Cardano, NetworkInfoProvider, epochSlotsCalcFactory } from '@cardano-sdk/core';
import {
  CurrentPoolMetricsEntity,
  PoolRegistrationEntity,
  PoolRetirementEntity,
  PoolRewardsEntity,
  STAKE_POOL_REWARDS,
  StakePoolEntity,
  StakePoolRewardsJob
} from '@cardano-sdk/projection-typeorm';
import { MissingProgramOption } from '../Program/errors';
import { RewardsComputeContext, WorkerHandlerFactory } from './types';
import { ServiceNames } from '../Program/programs/types';
import { accountActiveStake, poolDelegators, poolRewards } from './stakePoolRewardsQueries';
import { computeROS } from '../StakePool/TypeormStakePoolProvider/util';
import { missingProviderUrlOption } from '../Program/options/common';
import { networkInfoHttpProvider } from '@cardano-sdk/cardano-services-client';
 
/** The version of the algorithm to compute rewards. */
export const REWARDS_COMPUTE_VERSION = 1;
 
/** Gets from **db-sync** the _active stake_. */
const getPoolActiveStake = async (context: RewardsComputeContext) => {
  const { db, delegatorsIds, epochNo, ownersIds } = context;
 
  context.memberActiveStake = 0n;
  context.activeStake = 0n;
 
  for (const delegatorId of delegatorsIds!) {
    const { rows, rowCount } = await db.query<{ value: string }>({
      name: 'get_active_stake',
      text: accountActiveStake,
      values: [epochNo, delegatorId]
    });
 
    Iif (rowCount > 0) {
      const amount = BigInt(rows[0].value);
 
      context.activeStake += amount;
      Iif (!ownersIds!.includes(delegatorId)) context.memberActiveStake += amount;
    }
  }
};
 
/** Gets from **db-sync** the _delegators_ (`stake_address.id` arrays). */
const getPoolDelegators = async (context: RewardsComputeContext) => {
  context.delegatorsIds = [];
  context.membersIds = [];
  context.ownersIds = [];
 
  const { db, delegatorsIds, epochNo, membersIds, ownersIds, poolHashId, registration } = context;
  const { owners } = registration!;
  const { rows } = await db.query<{ addr_id: string; owner: boolean }>({
    name: 'get_delegators',
    text: poolDelegators,
    values: [epochNo, poolHashId, owners]
  });
 
  context.delegators = rows.length;
 
  for (const { addr_id, owner } of rows) {
    delegatorsIds.push(addr_id);
 
    if (owner) ownersIds.push(addr_id);
    else membersIds.push(addr_id);
  }
};
 
/** Gets from **db-sync** the `pool_hash.id`. */
const getPoolHashId = async (context: RewardsComputeContext) => {
  const { db, stakePool } = context;
  const result = await db.query<{ id: string }>({
    name: 'get_hash_id',
    text: 'SELECT id FROM pool_hash WHERE view = $1',
    values: [stakePool.id]
  });
 
  Iif (result.rowCount !== 1) throw new Error('Expected exactly 1 row');
 
  context.poolHashId = result.rows[0].id;
};
 
/** Gets from **db-sync** the _rewards_. */
const getPoolRewards = async (context: RewardsComputeContext) => {
  const { db, epochNo, poolHashId } = context;
  const result = await db.query<{ amount: string; type: string }>({
    name: 'get_rewards',
    text: poolRewards,
    values: [epochNo, poolHashId]
  });
 
  context.leaderRewards = 0n;
  context.memberRewards = 0n;
  context.rewards = 0n;
 
  for (const { amount, type } of result.rows) {
    const biAmount = BigInt(amount);
 
    Iif (type === 'leader') context.leaderRewards += biAmount;
    Iif (type === 'member') context.memberRewards += biAmount;
    context.rewards += biAmount;
  }
};
 
/**
 * Checks if the job for previous epoch already completed accessing the **pg-boss** `job` table.
 *
 * In case previous job is not yet completed, `throw`s an `Error`.
 */
const checkPreviousEpochCompleted = async (dataSource: DataSource, epochNo: Cardano.EpochNo) => {
  // Epoch no 0 doesn't need to wait for any jobs about previous epoch
  Iif (epochNo === 0) return;
 
  const queryRunner = dataSource.createQueryRunner();
 
  try {
    const subQuery = (table: 'archive' | 'job') =>
      `(SELECT COUNT(*) FROM pgboss.${table} WHERE name = $1 AND singletonkey = $2 AND state = $3)`;
    const result: { completed: string }[] = await queryRunner.query(
      `SELECT ${subQuery('archive')} + ${subQuery('job')} AS completed`,
      [STAKE_POOL_REWARDS, epochNo - 1, 'completed']
    );
 
    Iif (result[0]?.completed !== '1') throw new Error(`Previous epoch (${epochNo - 1}) rewards job not completed yet`);
  } finally {
    await queryRunner.release();
  }
};
 
/**
 * Checks if a given pool needs to compute the rewards in a given epoch based on its status in that epoch.
 *
 * It also adds the `registration` to the `context`.
 *
 * @param context the computation context
 * @returns `true` if the pool has rewards to compute, `false` otherwise
 */
const hasRewardsInEpoch = async (context: RewardsComputeContext) => {
  const { dataSource, epochNo, lastSlot, stakePool } = context;
  const { id } = stakePool;
  const registration = await dataSource.getRepository(PoolRegistrationEntity).findOne({
    order: { blockSlot: 'DESC' },
    where: { blockSlot: LessThanOrEqual(lastSlot), stakePool: { id } }
  });
 
  Iif (!registration) return false;
 
  const retirements = await dataSource.getRepository(PoolRetirementEntity).count({
    where: {
      blockSlot: Between(registration.blockSlot!, lastSlot),
      retireAtEpoch: LessThanOrEqual(epochNo),
      stakePool: { id }
    }
  });
 
  Iif (retirements !== 0) return false;
 
  context.registration = registration;
 
  return true;
};
 
/**
 * Computes the rewards for a given stake pool in a given epoch; stores it into the DB
 * and updates ROS and lastROS for the stake pool in its metrics.
 *
 * @param context the computation context
 */
const epochRewards = async (context: RewardsComputeContext) => {
  const { dataSource, epochNo, idx, lastRosEpochs, logger, stakePool, totalStakePools } = context;
  const { id } = stakePool;
 
  Iif (await hasRewardsInEpoch(context)) {
    logger.info(`Going to compute rewards for stake pool ${id} on epoch ${epochNo} (${idx}/${totalStakePools})`);
 
    await getPoolHashId(context);
    await getPoolDelegators(context);
    await getPoolRewards(context);
    await getPoolActiveStake(context);
 
    const { registration } = context;
 
    context.pledge = registration!.pledge!;
    context.version = REWARDS_COMPUTE_VERSION;
 
    logger.debug(`Going to upsert epoch rewards for stake pool ${id}`);
 
    await dataSource.getRepository(PoolRewardsEntity).upsert(context, ['epochNo', 'stakePoolId']);
 
    logger.debug(`Epoch rewards for stake pool ${id} saved`);
  }
 
  const [ros] = await computeROS(context);
  const [lastRos] = await computeROS({ ...context, epochs: lastRosEpochs });
 
  logger.debug(`Going to refresh ROS metrics for stake pool ${id}`);
 
  await dataSource.getRepository(CurrentPoolMetricsEntity).upsert({ lastRos, ros, stakePool: { id } }, ['stakePoolId']);
 
  logger.debug(`ROS metrics for stake pool ${id} saved`);
};
 
/** Gets the last slot of the epoch. */
const getLastSlot = async (provider: NetworkInfoProvider, epochNo: Cardano.EpochNo) => {
  const epochSlotsCalc = epochSlotsCalcFactory(provider);
  const { firstSlot, lastSlot } = await epochSlotsCalc(epochNo);
 
  return { epochLength: (lastSlot - firstSlot + 1) * 1000, lastSlot };
};
 
/** Creates a `stakePoolRewardsHandler`. */
export const stakePoolRewardsHandlerFactory: WorkerHandlerFactory = (options) => {
  const { dataSource, db, lastRosEpochs, logger, networkInfoProviderUrl } = options;
 
  // Introduced following code repetition as the correct form is source of a circular-deps:check failure.
  // Solving it would require an invasive refactoring action, probably better to defer it.
  // if (!lastRosEpochs) throw new MissingProgramOption(STAKE_POOL_REWARDS, Descriptions.LastRosEpochs);
  Iif (!lastRosEpochs)
    throw new MissingProgramOption(STAKE_POOL_REWARDS, 'Number of epochs over which lastRos is computed');
  Iif (!networkInfoProviderUrl) throw missingProviderUrlOption(STAKE_POOL_REWARDS, ServiceNames.NetworkInfo);
 
  const provider = networkInfoHttpProvider({ baseUrl: networkInfoProviderUrl, logger });
 
  return async (data: StakePoolRewardsJob) => {
    const { epochNo } = data;
 
    logger.info(`Starting stake pools rewards job for epoch ${epochNo}`);
 
    await checkPreviousEpochCompleted(dataSource, epochNo);
 
    const { epochLength, lastSlot } = await getLastSlot(provider, epochNo);
    const stakePools = await dataSource.getRepository(StakePoolEntity).find();
    const totalStakePools = stakePools.length;
    const context = { dataSource, db, epochLength, epochNo, lastRosEpochs, lastSlot, logger, totalStakePools };
 
    for (const [idx, stakePool] of stakePools.entries()) await epochRewards({ ...context, idx, stakePool });
  };
};