Skip to content

Commit

Permalink
initialize variables
Browse files Browse the repository at this point in the history
  • Loading branch information
pablomendezroyo committed Sep 23, 2024
1 parent 40bd2bb commit 48fc37e
Show file tree
Hide file tree
Showing 6 changed files with 40 additions and 48 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,24 +16,22 @@ import { logPrefix } from "./logPrefix.js";
*/
export async function getActiveValidatorsLoadedInBrain({
beaconchainApi,
brainDb,
activeValidatorsIndexes
brainDb
}: {
beaconchainApi: BeaconchainApi;
brainDb: BrainDataBase;
activeValidatorsIndexes: string[];
}): Promise<void> {
}): Promise<string[]> {
const validatorIndexes = await getValidatorIndexesAndSaveInDb({ beaconchainApi, brainDb });
if (validatorIndexes.length === 0) return;
(
if (validatorIndexes.length === 0) return [];
return (
await beaconchainApi.postStateValidators({
body: {
ids: validatorIndexes,
statuses: validatorIndexes.map(() => ValidatorStatus.ACTIVE_ONGOING)
},
stateId: "finalized"
})
).data.forEach((validator) => activeValidatorsIndexes.push(validator.index));
).data.map((validator) => validator.index.toString());
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,22 @@ import { TotalRewards } from "../../apiClients/types.js";
*
* @param {BeaconchainApi} beaconchainApi - Beaconchain API client.
* @param {string} epoch - The epoch to get the rewards.
* @param {string[]} validatorIndexes - Array of validator indexes.
* @param {string[]} activeValidatorsIndexes - Array of active validator indexes.
* @returns {TotalRewards[]} - Array of total rewards for the validators.
*/
export async function getAttestationsTotalRewards({
beaconchainApi,
epoch,
validatorIndexes,
totalRewards
activeValidatorsIndexes
}: {
beaconchainApi: BeaconchainApi;
epoch: string;
validatorIndexes: string[];
totalRewards: TotalRewards[];
}): Promise<void> {
(
activeValidatorsIndexes: string[];
}): Promise<TotalRewards[]> {
return (
await beaconchainApi.getAttestationsRewards({
epoch,
pubkeysOrIndexes: validatorIndexes
pubkeysOrIndexes: activeValidatorsIndexes
})
).data.total_rewards.forEach((reward) => totalRewards.push(reward));
).data.total_rewards;
}
22 changes: 10 additions & 12 deletions packages/brain/src/modules/cron/trackValidatorsPerformance/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,16 +52,16 @@ export async function trackValidatorsPerformance({
const epochFinalized = await beaconchainApi.getEpochHeader({ blockId: "finalized" });
let errorGettingValidatorData: Error | undefined;
let newEpochFinalized = epochFinalized;
const activeValidatorsIndexes: string[] = [];
const validatorsAttestationsTotalRewards: TotalRewards[] = [];
const validatorBlockStatusMap: Map<string, BlockProposalStatus> = new Map();
let activeValidatorsIndexes: string[] = [];
let validatorsAttestationsTotalRewards: TotalRewards[] = [];
let validatorBlockStatusMap: Map<string, BlockProposalStatus> = new Map();

while (epochFinalized === newEpochFinalized) {
try {
logger.debug(`${logPrefix}Epoch finalized: ${epochFinalized}`);

// active validators indexes
await getActiveValidatorsLoadedInBrain({ beaconchainApi, brainDb, activeValidatorsIndexes });
activeValidatorsIndexes = await getActiveValidatorsLoadedInBrain({ beaconchainApi, brainDb });
if (activeValidatorsIndexes.length === 0) {
logger.info(`${logPrefix}No active validators found`);
return;
Expand All @@ -72,19 +72,17 @@ export async function trackValidatorsPerformance({
await checkNodeHealth({ beaconchainApi });

// get block attestations rewards
await getAttestationsTotalRewards({
validatorsAttestationsTotalRewards = await getAttestationsTotalRewards({
beaconchainApi,
epoch: epochFinalized.toString(),
validatorIndexes: activeValidatorsIndexes,
totalRewards: validatorsAttestationsTotalRewards
activeValidatorsIndexes
});

// get block proposal status
await setBlockProposalStatusMap({
validatorBlockStatusMap = await setBlockProposalStatusMap({
beaconchainApi,
epoch: epochFinalized.toString(),
validatorIndexes: activeValidatorsIndexes,
validatorBlockStatusMap
activeValidatorsIndexes
});

// update error to undefined if no error occurred in last iteration and break the loop
Expand Down Expand Up @@ -119,9 +117,9 @@ export async function trackValidatorsPerformance({
// insert performance data or each validator
await insertPerformanceDataNotThrow({
postgresClient,
validatorIndexes: activeValidatorsIndexes,
activeValidatorsIndexes,
epochFinalized,
validatorBlockStatus: validatorBlockStatusMap,
validatorBlockStatusMap,
validatorsAttestationsTotalRewards,
error: errorGettingValidatorData,
executionClient,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,31 +11,31 @@ import { logPrefix } from "./logPrefix.js";
* with the next validator.
*
* @param postgresClient - Postgres client to interact with the DB.
* @param validatorIndexes - Array of validator indexes.
* @param activeValidatorIndexes - Array of validator indexes.
* @param epochFinalized - The epoch finalized.
* @param validatorBlockStatus - Map with the block proposal status of each validator.
* @param validatorBlockStatusMap - Map with the block proposal status of each validator.
* @param validatorsAttestationsTotalRewards - Array of total rewards for the validators.
*/
export async function insertPerformanceDataNotThrow({
postgresClient,
validatorIndexes,
activeValidatorsIndexes,
epochFinalized,
validatorBlockStatus,
validatorBlockStatusMap,
validatorsAttestationsTotalRewards,
executionClient,
consensusClient,
error
}: {
postgresClient: PostgresClient;
validatorIndexes: string[];
activeValidatorsIndexes: string[];
epochFinalized: number;
validatorBlockStatus: Map<string, BlockProposalStatus>;
validatorBlockStatusMap: Map<string, BlockProposalStatus>;
validatorsAttestationsTotalRewards: TotalRewards[];
executionClient: ExecutionClient;
consensusClient: ConsensusClient;
error?: Error;
}): Promise<void> {
for (const validatorIndex of validatorIndexes) {
for (const validatorIndex of activeValidatorsIndexes) {
//const liveness = validatorsLiveness.find((liveness) => liveness.index === validatorIndex)?.is_live;
const attestationsTotalRewards = validatorsAttestationsTotalRewards.find(
(attestationReward) => attestationReward.validator_index === validatorIndex
Expand All @@ -46,7 +46,7 @@ export async function insertPerformanceDataNotThrow({
continue;
}

const blockProposalStatus = validatorBlockStatus.get(validatorIndex);
const blockProposalStatus = validatorBlockStatusMap.get(validatorIndex);
if (!blockProposalStatus) {
logger.error(
`${logPrefix}Missing block proposal data for validator ${validatorIndex}, block: ${blockProposalStatus}`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,27 +8,27 @@ import { logPrefix } from "./logPrefix.js";
*
* @param {BeaconchainApi} beaconchainApi - Beaconchain API client.
* @param {string} epoch - The epoch to get the block proposal duties.
* @param {string[]} validatorIndexes - Array of validator indexes.
* @param {string[]} activeValidatorIndexes - Array of validator indexes.
*/
export async function setBlockProposalStatusMap({
beaconchainApi,
epoch,
validatorIndexes,
validatorBlockStatusMap
activeValidatorsIndexes
}: {
beaconchainApi: BeaconchainApi;
epoch: string;
validatorIndexes: string[];
validatorBlockStatusMap: Map<string, BlockProposalStatus>;
}): Promise<void> {
activeValidatorsIndexes: string[];
}): Promise<Map<string, BlockProposalStatus>> {
// Initialize the map with the block proposal status of each validator.
const validatorBlockStatusMap = new Map<string, BlockProposalStatus>();
// Get the block proposal duties for the given epoch. Which validators
// are supposed to propose a block in which slot?
const blockProposalsResponse = await beaconchainApi.getProposerDuties({
epoch
});

// Utilize a Set for quick lookup. We assume that the validator indexes are unique.
const validatorIndexesSet = new Set(validatorIndexes);
const validatorIndexesSet = new Set(activeValidatorsIndexes);

// Initialize all validator's status to Unchosen.
validatorIndexesSet.forEach((validatorIndex) => {
Expand Down Expand Up @@ -64,4 +64,5 @@ export async function setBlockProposalStatusMap({
}
}
}
return validatorBlockStatusMap;
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type { ValidatorPerformance } from "../apiClients/postgres/types.js";
/**
* Calculates the attestation success rate for a given validator. The attestation success rate is the percentage of successful attestations
* Being the total attestation opportunities the number of epochs between the first and last epoch in the data set of a specific validator.
* And the total successful attestations the number of epochs where the validator successfully attested: head target and source must be > 0.
* And the total successful attestations the number of epochs where the validator successfully attested: source must be >= 0.
*
* @param validatorData the data of the validator from the postgres database
* @param startEpoch the start epoch of the data set
Expand All @@ -23,10 +23,7 @@ export function calculateAttestationSuccessRate({

// Calculate the total successful attestations
const totalSuccessfulAttestations = validatorData.filter(
(data) =>
parseInt(data.attestationsTotalRewards.head) > 0 &&
parseInt(data.attestationsTotalRewards.target) > 0 &&
parseInt(data.attestationsTotalRewards.source) > 0
(data) => parseInt(data.attestationsTotalRewards.source) >= 0
).length;

return (totalSuccessfulAttestations / totalAttestationOpportunities) * 100;
Expand Down

0 comments on commit 48fc37e

Please sign in to comment.