Skip to content

Commit

Permalink
fix: create optimized query to get current cycle signer weight percen…
Browse files Browse the repository at this point in the history
…tages (#70)
  • Loading branch information
rafaelcr authored Jan 17, 2025
1 parent 80a4c77 commit 8bcb54b
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 9 deletions.
18 changes: 14 additions & 4 deletions src/pg/pg-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -756,11 +756,21 @@ export class PgStore extends BasePgStore {
return dbRewardSetSigners;
}

async getCurrentCycleNumber() {
const result = await this.sql<{ cycle_number: number }[]>`
SELECT MAX(cycle_number) AS cycle_number FROM reward_set_signers
async getCurrentCycleSignersWeightPercentage() {
return await this.sql<{ signer_key: string; weight: number }[]>`
WITH current_cycle AS (
SELECT MAX(cycle_number) AS cycle_number
FROM reward_set_signers
),
total_weight AS (
SELECT SUM(signer_weight) AS total
FROM reward_set_signers
WHERE cycle_number = (SELECT cycle_number FROM current_cycle)
)
SELECT signer_key, ROUND((signer_weight::numeric / (SELECT total FROM total_weight)::numeric) * 100.0, 3)::float AS weight
FROM reward_set_signers
WHERE cycle_number = (SELECT cycle_number FROM current_cycle)
`;
return result[0]?.cycle_number;
}

async getSignerForCycle(cycleNumber: number, signerId: string) {
Expand Down
7 changes: 2 additions & 5 deletions src/prom-metrics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,13 +74,10 @@ export function configureSignerMetrics(db: PgStore) {
help: 'Signer weight percentage for the current cycle',
labelNames: ['signer'] as const,
async collect() {
const dbResults = await db.sqlTransaction(async sql => {
const cycle = await db.getCurrentCycleNumber();
return await db.getSignersForCycle({ sql, cycleNumber: cycle, limit: 60, offset: 0 });
});
const dbResults = await db.getCurrentCycleSignersWeightPercentage();
this.reset();
for (const row of dbResults) {
this.set({ signer: row.signer_key }, row.weight_percentage);
this.set({ signer: row.signer_key }, row.weight);
}
},
});
Expand Down

0 comments on commit 8bcb54b

Please sign in to comment.