Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 10 additions & 8 deletions packages/brain/src/modules/apiClients/beaconchain/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,18 +48,20 @@ export interface TotalRewards {
inactivity: string;
}

export interface IdealRewards {
effective_balance: string;
head: string;
target: string;
source: string;
inclusion_delay: string;
inactivity: string;
}

export interface BeaconchainAttestationRewardsPostResponse {
execution_optimistic: boolean;
finalized: boolean;
data: {
ideal_rewards: {
effective_balance: string;
head: string;
target: string;
source: string;
inclusion_delay: string;
inactivity: string;
}[];
ideal_rewards: IdealRewards[];
total_rewards: TotalRewards[];
};
}
Expand Down
66 changes: 7 additions & 59 deletions packages/brain/src/modules/apiClients/postgres/index.ts
Original file line number Diff line number Diff line change
@@ -1,54 +1,8 @@
import postgres from "postgres";
import logger from "../../logger/index.js";
import { BlockProposalStatus, ValidatorPerformance } from "./types.js";
import { BlockProposalStatus, Columns, ValidatorPerformance, ValidatorPerformancePostgres } from "./types.js";
import { ConsensusClient, ExecutionClient } from "@stakingbrain/common";

// Postgres has a built in class for errors PostgresError. i.e:
// PostgresError: type "block_proposal_status" already exists
// at ErrorResponse (file:///app/node_modules/postgres/src/connection.js:788:26)
// at handle (file:///app/node_modules/postgres/src/connection.js:474:6)
// at Socket.data (file:///app/node_modules/postgres/src/connection.js:315:9)
// at Socket.emit (node:events:519:28)
// at addChunk (node:internal/streams/readable:559:12)
// at readableAddChunkPushByteMode (node:internal/streams/readable:510:3)
// at Readable.push (node:internal/streams/readable:390:5)
// at TCP.onStreamRead (node:internal/stream_base_commons:191:23) {
// severity_local: 'ERROR',
// severity: 'ERROR',
// code: '42710',
// where: `SQL statement "CREATE TYPE BLOCK_PROPOSAL_STATUS AS ENUM('Missed', 'Proposed', 'Unchosen')"\n` +
// 'PL/pgSQL function inline_code_block line 5 at SQL statement',
// file: 'typecmds.c',
// line: '1170',
// routine: 'DefineEnum'
// }

enum Columns {
validatorIndex = "validator_index",
epoch = "epoch",
executionClient = "execution_client",
consensusClient = "consensus_client",
slot = "slot",
liveness = "liveness",
blockProposalStatus = "block_proposal_status",
syncCommitteeRewards = "sync_comittee_rewards",
attestationsTotalRewards = "attestations_total_rewards",
error = "error"
}

interface ValidatorPerformancePostgres {
[Columns.validatorIndex]: number;
[Columns.epoch]: number;
[Columns.executionClient]: ExecutionClient;
[Columns.consensusClient]: ConsensusClient;
[Columns.slot]: number;
[Columns.liveness]: boolean;
[Columns.blockProposalStatus]: BlockProposalStatus;
[Columns.syncCommitteeRewards]: number;
[Columns.attestationsTotalRewards]: string;
[Columns.error]: string;
}

export class PostgresClient {
private readonly tableName = "validators_performance";
private readonly BLOCK_PROPOSAL_STATUS = "BLOCK_PROPOSAL_STATUS";
Expand Down Expand Up @@ -83,17 +37,7 @@ SELECT pg_total_relation_size('${this.tableName}');
}

/**
* Initializes the database by creating the required table if it does not exist.
* The table will have the following columns:
* - validator_index: The index of the validator.
* - epoch: The epoch number.
* - slot: The slot number.
* - liveness: The liveness status of the validator.
* - block_proposal_status: The status of the block proposal (missed, proposed, unchosen).
* - sync_comittee_rewards: The rewards received by the validator for participating in the sync committee.
* - attestations_rewards: The rewards received by the validator for participating in the attestations.
* - error: Any error message related to the validator's performance fetch.
* The primary key will be a combination of validator_index and epoch.
* Initializes the database by creating the required table if it does not exist with the required columns.
*/
public async initialize() {
// important: enum create types must be broken into separate conditional checks for each ENUM type before trying to create it.
Expand All @@ -106,7 +50,6 @@ SELECT pg_total_relation_size('${this.tableName}');
WHEN duplicate_object THEN NULL;
END $$;
`);

// Check and create EXECUTION_CLIENT ENUM type if not exists
await this.sql.unsafe(`
DO $$
Expand Down Expand Up @@ -139,6 +82,7 @@ CREATE TABLE IF NOT EXISTS ${this.tableName} (
${Columns.blockProposalStatus} ${this.BLOCK_PROPOSAL_STATUS},
${Columns.syncCommitteeRewards} BIGINT,
${Columns.attestationsTotalRewards} JSONB,
${Columns.attestationsIdealRewards} JSONB,
${Columns.error} JSONB NULL,
PRIMARY KEY (${Columns.validatorIndex}, ${Columns.epoch})
);
Expand Down Expand Up @@ -180,6 +124,7 @@ DO UPDATE SET
${Columns.blockProposalStatus} = EXCLUDED.${Columns.blockProposalStatus},
${Columns.syncCommitteeRewards} = EXCLUDED.${Columns.syncCommitteeRewards},
${Columns.attestationsTotalRewards} = EXCLUDED.${Columns.attestationsTotalRewards},
${Columns.attestationsIdealRewards} = EXCLUDED.${Columns.attestationsIdealRewards},
${Columns.error} = EXCLUDED.${Columns.error};
`;

Expand All @@ -194,6 +139,7 @@ DO UPDATE SET
data.blockProposalStatus ?? null,
data.syncCommitteeRewards ?? null,
data.attestationsTotalRewards ? JSON.stringify(data.attestationsTotalRewards) : null, // JSONB expects a string or null
data.attestationsIdealRewards ? JSON.stringify(data.attestationsIdealRewards) : null, // JSONB expects a string or null
data.error ? JSON.stringify(data.error) : null // JSONB expects a string or null
]);
}
Expand Down Expand Up @@ -222,6 +168,7 @@ WHERE ${Columns.validatorIndex} = ANY($1)
blockProposalStatus: row.block_proposal_status,
syncCommitteeRewards: row.sync_comittee_rewards,
attestationsTotalRewards: JSON.parse(row.attestations_total_rewards),
attestationsIdealRewards: JSON.parse(row.attestations_ideal_rewards),
error: JSON.parse(row.error)
}));
}
Expand Down Expand Up @@ -270,6 +217,7 @@ AND ${Columns.epoch} <= $3
blockProposalStatus: row.block_proposal_status,
syncCommitteeRewards: row.sync_comittee_rewards,
attestationsTotalRewards: JSON.parse(row.attestations_total_rewards),
attestationsIdealRewards: JSON.parse(row.attestations_ideal_rewards),
error: JSON.parse(row.error)
};

Expand Down
43 changes: 33 additions & 10 deletions packages/brain/src/modules/apiClients/postgres/types.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,34 @@
import { ConsensusClient, ExecutionClient } from "@stakingbrain/common";
import { IdealRewards, TotalRewards } from "../beaconchain/types.js";

export enum Columns {
validatorIndex = "validator_index",
epoch = "epoch",
executionClient = "execution_client",
consensusClient = "consensus_client",
slot = "slot",
liveness = "liveness",
blockProposalStatus = "block_proposal_status",
syncCommitteeRewards = "sync_comittee_rewards",
attestationsTotalRewards = "attestations_total_rewards",
attestationsIdealRewards = "attestations_ideal_rewards",
error = "error"
}

// Interface data write with Postgres client
export interface ValidatorPerformancePostgres {
[Columns.validatorIndex]: number;
[Columns.epoch]: number;
[Columns.executionClient]: ExecutionClient;
[Columns.consensusClient]: ConsensusClient;
[Columns.slot]: number;
[Columns.liveness]: boolean;
[Columns.blockProposalStatus]: BlockProposalStatus;
[Columns.syncCommitteeRewards]: number;
[Columns.attestationsTotalRewards]: string;
[Columns.attestationsIdealRewards]: string;
[Columns.error]: string;
}

export enum BlockProposalStatus {
Missed = "Missed",
Expand All @@ -7,22 +37,15 @@ export enum BlockProposalStatus {
Error = "Error"
}

export interface AttestationsTotalRewards {
validator_index: string;
head: string;
target: string;
source: string;
inclusion_delay: string;
inactivity: string;
}

// Interface data return from Postgres client
export interface ValidatorPerformance {
validatorIndex: number;
epoch: number;
executionClient: ExecutionClient;
consensusClient: ConsensusClient;
blockProposalStatus?: BlockProposalStatus;
attestationsTotalRewards?: AttestationsTotalRewards;
attestationsTotalRewards?: TotalRewards;
attestationsIdealRewards?: IdealRewards;
slot?: number;
liveness?: boolean;
syncCommitteeRewards?: number;
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { BeaconchainApi } from "../../apiClients/index.js";
import { IdealRewards, TotalRewards } from "../../apiClients/types.js";

/**
* Get attestations rewards for the validators:
* - Total rewards
* - Ideal reward last item from array of IdealRewards -> is the ideal reward maximum that could be achieved by the validator
*/
export async function getValidatorAttestationsRewards({
beaconchainApi,
epoch,
activeValidatorsIndexes
}: {
beaconchainApi: BeaconchainApi;
epoch: string;
activeValidatorsIndexes: string[];
}): Promise<{ totalRewards: TotalRewards[]; idealRewards: IdealRewards }> {
const attestationsRewards = (
await beaconchainApi.getAttestationsRewards({
epoch,
pubkeysOrIndexes: activeValidatorsIndexes
})
).data;

return {
totalRewards: attestationsRewards.total_rewards,
idealRewards: attestationsRewards.ideal_rewards[attestationsRewards.ideal_rewards.length - 1]
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
ValidatorPerformanceError,
ValidatorPerformanceErrorCode
} from "../../apiClients/postgres/types.js";
import { TotalRewards } from "../../apiClients/types.js";
import { IdealRewards, TotalRewards } from "../../apiClients/types.js";
import logger from "../../logger/index.js";
import { logPrefix } from "./logPrefix.js";
import { sendValidatorsPerformanceNotifications } from "./sendValidatorsPerformanceNotifications.js";
Expand All @@ -15,34 +15,28 @@ import { sendValidatorsPerformanceNotifications } from "./sendValidatorsPerforma
* Insert the performance data for the validators in the Postgres DB. On any error
* inserting the performance of a validator, the error will be logged and the process will continue
* with the next validator.
*
* @param postgresClient - Postgres client to interact with the DB.
* @param activeValidatorIndexes - Array of validator indexes.
* @param currentEpoch - The current epoch.
* @param validatorBlockStatusMap - Map with the block proposal status of each validator.
* @param validatorsAttestationsTotalRewards - Array of total rewards for the validators.
*/
export async function insertPerformanceDataAndSendNotification({
executionClient,
consensusClient,
sendNotification,
dappmanagerApi,
postgresClient,
activeValidatorsIndexes,
currentEpoch,
activeValidatorsIndexes,
validatorBlockStatusMap,
validatorsAttestationsTotalRewards,
executionClient,
consensusClient,
validatorAttestationsRewards,
error
}: {
executionClient: ExecutionClient;
consensusClient: ConsensusClient;
sendNotification: boolean;
dappmanagerApi: DappmanagerApi;
postgresClient: PostgresClient;
activeValidatorsIndexes: string[];
currentEpoch: number;
validatorBlockStatusMap: Map<string, BlockProposalStatus>;
validatorsAttestationsTotalRewards: TotalRewards[];
executionClient: ExecutionClient;
consensusClient: ConsensusClient;
activeValidatorsIndexes: string[];
validatorBlockStatusMap?: Map<string, BlockProposalStatus>;
validatorAttestationsRewards?: { totalRewards: TotalRewards[]; idealRewards: IdealRewards };
error?: ValidatorPerformanceError;
}): Promise<void> {
for (const validatorIndex of activeValidatorsIndexes) {
Expand All @@ -60,7 +54,7 @@ export async function insertPerformanceDataAndSendNotification({
continue;
}

const attestationsTotalRewards = validatorsAttestationsTotalRewards.find(
const attestationsTotalRewards = validatorAttestationsRewards?.totalRewards.find(
(attestationReward) => attestationReward.validator_index === validatorIndex
);
if (!attestationsTotalRewards) {
Expand All @@ -80,7 +74,7 @@ export async function insertPerformanceDataAndSendNotification({
continue;
}

const blockProposalStatus = validatorBlockStatusMap.get(validatorIndex);
const blockProposalStatus = validatorBlockStatusMap?.get(validatorIndex);
if (!blockProposalStatus) {
await insertDataNotThrow({
postgresClient,
Expand Down Expand Up @@ -115,7 +109,7 @@ export async function insertPerformanceDataAndSendNotification({
dappmanagerApi,
currentEpoch: currentEpoch.toString(),
validatorBlockStatusMap,
validatorsAttestationsTotalRewards,
validatorAttestationsRewards,
error
});
}
Expand Down
Loading