Skip to content

Commit

Permalink
fix: import namespaces
Browse files Browse the repository at this point in the history
  • Loading branch information
mo4islona committed Aug 1, 2024
1 parent 0dc900d commit 95ceeb7
Show file tree
Hide file tree
Showing 4 changed files with 78 additions and 81 deletions.
11 changes: 6 additions & 5 deletions packages/rewards-calculator/src/chain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
isAddressEqual,
parseAbiItem,
} from "viem";
import { Context, logger } from './logger';
import { Context } from './logger';
import { bigSum, fromBase58 } from "./utils";
import { Rewards } from "./reward";
import { Workers } from "./workers";
Expand Down Expand Up @@ -180,6 +180,7 @@ Worker reward: ${totalWorkerReward} SQD;\nStaker reward: ${totalStarkerReward} S
}

async function logIfSuccessfulDistribution(
ctx: Context,
txHash: Hex,
workers: Workers,
address: string,
Expand All @@ -206,7 +207,7 @@ async function logIfSuccessfulDistribution(
) {
workers.noteSuccessfulCommit(txHash);

await workers.printLogs({
await workers.printLogs(ctx,{
walletAddress: address,
index,
});
Expand Down Expand Up @@ -242,7 +243,7 @@ export async function commitRewards(

ctx.logger.info(`committed rewards ${tx}, logging successful distribution...`);

await logIfSuccessfulDistribution(tx, workers, address, index);
await logIfSuccessfulDistribution(ctx, tx, workers, address, index);

return tx;
}
Expand Down Expand Up @@ -339,7 +340,7 @@ export async function approveRewards(
else {
ctx.logger.info(`re-commited rewards ${tx}, logging successful distribution...`);

await logIfSuccessfulDistribution(tx, workers, address, index);
await logIfSuccessfulDistribution(ctx, tx, workers, address, index);
}

return;
Expand All @@ -359,7 +360,7 @@ export async function approveRewards(

ctx.logger.info(`approved rewards ${tx}, logging successful distribution...`);

await logIfSuccessfulDistribution(tx, workers, address, index);
await logIfSuccessfulDistribution(ctx, tx, workers, address, index);

return tx;
}
Expand Down
8 changes: 4 additions & 4 deletions packages/rewards-calculator/src/logger.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
import pino from 'pino';
import dayjs from 'dayjs';
import pinoms, { Level, prettyStream, Streams } from 'pino-multi-stream';
import pinoms from 'pino-multi-stream';

const shouldLog = () => process.env.VERBOSE === "true";
const prettyLog = process.env.DISABLE_PRETTY_PRINT === undefined && process.stdout.isTTY;
const logLevel = (process.env.LOG_LEVEL || 'debug') as Level;
const logLevel = (process.env.LOG_LEVEL || 'debug') as pinoms.Level;

export type CtxValue = Record<string, string | number>

const streams: Streams = [
const streams: pinoms.Streams = [
{

level: logLevel,
stream: prettyLog
? prettyStream({
? pinoms.prettyStream({
prettyPrint: {
messageKey: 'message',
singleLine: true,
Expand Down
2 changes: 1 addition & 1 deletion packages/rewards-calculator/src/reward.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,6 @@ export async function epochStats(
await workers.getLiveness();
await workers.getDTenure(fromBlock);
await workers.calculateRewards();
await workers.logStats();
await workers.logStats(ctx);
return workers;
}
138 changes: 67 additions & 71 deletions packages/rewards-calculator/src/workers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,29 +10,29 @@ import {
registeredWorkersCount,
storagePerWorkerInGb,
targetCapacity as getTargetCapacity,
} from "./chain";
} from './chain';
import {
bigIntToDecimal,
decimalSum,
decimalToBigInt,
formatSqd,
keysToFixed,
sum,
} from "./utils";
} from './utils';
import {
ClickhouseClient,
historicalLiveness,
livenessFactor,
} from "./clickhouseClient";
import { logger } from "./logger";
import { Worker } from "./worker";
import dayjs from "dayjs";
import { config } from "./config";
import { Rewards } from "./reward";
} from './clickhouseClient';
import { Context, logger } from './logger';
import { Worker } from './worker';
import dayjs from 'dayjs';
import { config } from './config';
import { Rewards } from './reward';

import Decimal from "decimal.js";
import Decimal from 'decimal.js';

Decimal.set({ precision: 28, minE: -9 });
Decimal.set({precision: 28, minE: -9});

const YEAR = 365 * 24 * 60 * 60;

Expand All @@ -44,10 +44,11 @@ export class Workers {
baseApr = new Decimal(0);
stakeFactor = new Decimal(0);
rAPR = new Decimal(0);
commitmentTxHash = "";
commitmentError = "";
commitmentTxHash = '';
commitmentError = '';

constructor(private clickhouseClient: ClickhouseClient) {}
constructor(private clickhouseClient: ClickhouseClient) {
}

public add(workerId: string) {
if (this.workers[workerId]) {
Expand Down Expand Up @@ -103,11 +104,11 @@ export class Workers {
this.nextDistributionStartBlockNumber,
);
this.parseMulticallResult(
"stake",
'stake',
this.mapMulticallResult(capedStakes, bigIntToDecimal),
);
this.parseMulticallResult(
"totalStake",
'totalStake',
this.mapMulticallResult(totalStakes, bigIntToDecimal),
);
}
Expand Down Expand Up @@ -147,10 +148,10 @@ export class Workers {
});
}

public async calculateRewards() {
async calculateRewards() {
const duration = dayjs(this.clickhouseClient.to).diff(
dayjs(this.clickhouseClient.from),
"second",
'second',
);
const baseApr = await currentApy(
this.count(),
Expand All @@ -166,15 +167,15 @@ export class Workers {
this.map((worker) => worker.getRewards(rMax));
}

public noteSuccessfulCommit(txHash: string) {
noteSuccessfulCommit(txHash: string) {
this.commitmentTxHash = txHash;
}

public noteFailedCommit(error: Error) {
noteFailedCommit(error: Error) {
this.commitmentError = error.toString();
}

public async printLogs({
async printLogs(ctx: Context, {
walletAddress,
index,
}: {
Expand All @@ -190,11 +191,11 @@ export class Workers {
);
const current_capacity = active_workers_count * storagePerWorker;

const stakeSum = decimalSum(this.map(({ stake }) => stake));
const stakeSum = decimalSum(this.map(({stake}) => stake));

const duration = dayjs(this.clickhouseClient.to).diff(
dayjs(this.clickhouseClient.from),
"second",
'second',
);

const total_reward = decimalSum(
Expand All @@ -205,41 +206,39 @@ export class Workers {
const botId = process.env.BOT_NAME || `bot-${index}`;
const isCommitSuccess = !this.commitmentError;

console.log(
JSON.stringify({
time: new Date(),
epoch_start: this.clickhouseClient.from,
epoch_end: this.clickhouseClient.to,
type: "rewards_report",
bot_id: botId,
bot_wallet: address,
is_commit_success: isCommitSuccess,
commit_tx_hash: this.commitmentTxHash ?? "",
commit_error_message: this.commitmentError ?? "",
target_capacity,
current_capacity,
active_workers_count,
base_apr: this.baseApr.toFixed(),
stake_factor: this.stakeFactor.toFixed(),
r_apr: this.rAPR.toFixed(),
total_reward: total_reward.toFixed(),
total_chunks_read: this.totalChunksRead(),
total_bytes_sent: this.totalBytesSent(),
total_requests: sum(this.map((w) => w.totalRequests)),
valid_requests: sum(this.map((w) => w.requestsProcessed)),
}),
);
ctx.logger.info({
time: new Date(),
epoch_start: this.clickhouseClient.from,
epoch_end: this.clickhouseClient.to,
type: 'rewards_report',
bot_id: botId,
bot_wallet: address,
is_commit_success: isCommitSuccess,
commit_tx_hash: this.commitmentTxHash ?? '',
commit_error_message: this.commitmentError ?? '',
target_capacity,
current_capacity,
active_workers_count,
base_apr: this.baseApr.toFixed(),
stake_factor: this.stakeFactor.toFixed(),
r_apr: this.rAPR.toFixed(),
total_reward: total_reward.toFixed(),
total_chunks_read: this.totalChunksRead(),
total_bytes_sent: this.totalBytesSent(),
total_requests: sum(this.map((w) => w.totalRequests)),
valid_requests: sum(this.map((w) => w.requestsProcessed)),
});

// If commit is not successful, don't print worker report
if (!isCommitSuccess) {
ctx.logger.warn('skipping worker report due to failed commit');
return;
}

this.map((worker) =>
console.log(
JSON.stringify({
ctx.logger.info({
time: new Date(),
type: "worker_report",
type: 'worker_report',
bot_id: botId,
bot_wallet: address,
worker_id: worker.peerId,
Expand All @@ -254,8 +253,7 @@ export class Workers {
chunks_read: worker.chunksRead,
requests: worker.totalRequests,
valid_requests: worker.requestsProcessed,
}),
),
})
);
}

Expand All @@ -272,31 +270,31 @@ export class Workers {
multicallResult: MulticallResult<S>[],
mapper: (v: S) => T,
): MulticallResult<T>[] {
return multicallResult.map(({ status, error, result }) =>
status === "success"
? { status, error, result: mapper(result) }
: { status, error, result },
return multicallResult.map(({status, error, result}) =>
status === 'success'
? {status, error, result: mapper(result)}
: {status, error, result},
);
}

private totalBytesSent() {
return sum(this.map(({ bytesSent }) => bytesSent));
return sum(this.map(({bytesSent}) => bytesSent));
}

private totalChunksRead() {
return sum(this.map(({ chunksRead }) => chunksRead));
return sum(this.map(({chunksRead}) => chunksRead));
}

private totalSupply() {
return this.bond
.mul(this.count())
.add(decimalSum(this.map(({ stake }) => stake)));
.add(decimalSum(this.map(({stake}) => stake)));
}

private async rUnlocked() {
const duration = dayjs(this.clickhouseClient.to).diff(
dayjs(this.clickhouseClient.from),
"second",
'second',
);
const apy = bigIntToDecimal(
await currentApy(this.count(), this.nextDistributionStartBlockNumber),
Expand All @@ -308,7 +306,7 @@ export class Workers {
return new Decimal(1);
}

public async logStats() {
public async logStats(ctx: Context) {
const stats = Object.fromEntries(
this.map((worker) => [
worker.peerId,
Expand All @@ -325,24 +323,22 @@ export class Workers {
);
const totalUnlocked = await this.rUnlocked();
const totalReward = decimalSum(
this.map(({ workerReward, stakerReward }) =>
this.map(({workerReward, stakerReward}) =>
workerReward.add(stakerReward),
),
);
logger.table(stats);
logger.log("Max unlocked:", formatSqd(totalUnlocked));
logger.log("Total reward:", formatSqd(totalReward));
this.logPercentageUnlocked(totalReward, totalUnlocked);
}

private logPercentageUnlocked(totalReward: Decimal, totalUnlocked: Decimal) {
if (!totalUnlocked) logger.log("Percentage unlocked 0 %");
else
logger.log('Max unlocked:', formatSqd(totalUnlocked));
logger.log('Total reward:', formatSqd(totalReward));
if (!totalUnlocked) {
logger.log('Percentage unlocked 0 %');
} else {
logger.log(
"Percentage of max unlocked",
'Percentage of max unlocked',
totalReward.mul(10000).div(totalUnlocked).div(100).toFixed(2),
"%",
'%',
);
}
}

public async rewards(): Promise<Rewards> {
Expand Down

0 comments on commit 95ceeb7

Please sign in to comment.