Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: fix l1 to l2 conversion issues #61

Merged
merged 1 commit into from
Dec 5, 2024
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
19 changes: 11 additions & 8 deletions packages/rewards-calculator/src/chain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
parseAbiItem,
} from "viem";
import { logger } from "./logger";
import { bigSum, fromBase58, withCache } from "./utils";
import { bigSum, fromBase58 } from "./utils";
import { Rewards } from "./reward";
import { Workers } from "./workers";
import { fordefiRequest } from "./fordefi/request";
Expand All @@ -31,8 +31,8 @@ function getNitroGenesisBlock(chainId: number) {
let lastKnowBlockPair: {l1Block: bigint, l2Block: bigint} | undefined = undefined

// ref https://github.com/OffchainLabs/arbitrum-sdk/blob/5ef44308d3c89fd956c9dfdc59b6776b88afd251/src/lib/utils/lib.ts#L90
export async function getFirstBlockForL1Block(targetL1Block: number | bigint | undefined): Promise<bigint> {
targetL1Block = targetL1Block == null ? await l1Client.getBlockNumber() : BigInt(targetL1Block)
export async function getFirstBlockForL1Block(targetL1Block: number | bigint): Promise<bigint> {
targetL1Block = BigInt(targetL1Block)

let start: bigint
if (lastKnowBlockPair == null || lastKnowBlockPair.l1Block > targetL1Block) {
Expand All @@ -48,7 +48,9 @@ export async function getFirstBlockForL1Block(targetL1Block: number | bigint | u
return lastKnowBlockPair.l2Block
}

let end = await publicClient.getBlockNumber()
// for some reason .getBlockNumber() returns inconsistent result to .getBlock(),
// so, since we use .getBlock() further down the code, we should use .getBlock() here as well
let end = await publicClient.getBlock().then(block => block.number)

let targetL2Block: bigint | undefined
while (start <= end) {
Expand Down Expand Up @@ -127,9 +129,9 @@ export async function getLatestDistributionBlock() {
return -1n
}

export const currentApy = withCache(_currentApy)
// export const currentApy = withCache(_currentApy)

async function _currentApy(l1BlockNumber: number | bigint) {
export async function currentApy(l1BlockNumber: number | bigint) {
assert (l1BlockNumber < 1000000000n, `${l1BlockNumber} should fit into number` )

const l2blockNumber = await getFirstBlockForL1Block(l1BlockNumber)
Expand Down Expand Up @@ -172,8 +174,9 @@ export async function bond(blockNumber?: bigint) {
return contracts.workerRegistration.read.bondAmount({ blockNumber });
}

export async function getBlockNumber() {
return Number(await l1Client.getBlockNumber());
export async function getL1BlockNumber() {
const block = await publicClient.getBlock();
return Number.parseInt((block as any).l1BlockNumber, 16);
}

export async function lastRewardedBlock() {
Expand Down
30 changes: 18 additions & 12 deletions packages/rewards-calculator/src/endpoints.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import express from "express";
import { epochStats } from "./reward";
import { config, l1Client } from "./config";
import { getBlockNumber, currentApy } from "./chain";
import { getL1BlockNumber, currentApy } from "./chain";
import { logger } from "./logger"

const app = express();
Expand Down Expand Up @@ -106,22 +106,28 @@ app.get("/rewards/:fromBlock/:toBlock", async (req, res) => {
await rewards(fromBlock, toBlock, res);
});

app.get("/currentApy/:atBlock", async (req, res) => {
const { atBlock } = req.params
let block
if (!isInteger(atBlock)) {
block = await getBlockNumber()
} else {
block = atBlock
app.get("/currentApy/:atBlock?", async (req, res) => {
try {
const { atBlock } = req.params
let block: number
if (!atBlock || !isInteger(atBlock)) {
block = await getL1BlockNumber()
block = block - 1
} else {
block = Number(atBlock)
}
logger.log(`Block: ${block}`)
const apy = await currentApy(block);
res.jsonp({ block, apy})
} catch (e: any) {
console.error(e);
res.status(500).send(e.message);
}
logger.log(`Block: ${block}`)
const apy = await currentApy(Number(block));
res.jsonp({ block, apy})
});


app.get("/rewards/:lastNBlocks", async (req, res) => {
const lastBlock = await getBlockNumber();
const lastBlock = await getL1BlockNumber();
const fromBlock = lastBlock - Number(req.params.lastNBlocks);
await rewards(fromBlock.toString(), lastBlock.toString(), res);
});
Expand Down
4 changes: 2 additions & 2 deletions packages/rewards-calculator/src/rewardBot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import {
canCommit,
commitRewards,
epochLength,
getBlockNumber,
getL1BlockNumber,
getFirstBlockForL1Block,
getLatestCommitment,
getRegistrations,
Expand Down Expand Up @@ -164,7 +164,7 @@ export class RewardBot {
);
}

const currentBlock = await getBlockNumber();
const currentBlock = await getL1BlockNumber();
const lastConfirmedBlock = currentBlock - config.epochConfirmationBlocks;
if (lastConfirmedBlock - _lastRewardedBlock < epochLen) {
return { fromBlock: 0, toBlock: 0, epochLen, chunkType: 'even' };
Expand Down
4 changes: 0 additions & 4 deletions packages/rewards-calculator/src/testRPC.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,5 @@ export async function currentApyTest(blockNumber?: number) {
console.log(`Approve Ranges: ${JSON.stringify(await approveRanges())}`)
console.log(`APY: ${await currentApy(21279057n)}`)
console.log(`APY: ${await currentApy(21279057)}`)
console.log(`APY: ${await currentApy(21279057n)}`)
console.log(`APY: ${await currentApy(21279057)}`)
console.log(`APY: ${await currentApy(21279057n)}`)
console.log(`APY: ${await currentApy(21279057)}`)
})().then(() => console.log('Done'))

9 changes: 3 additions & 6 deletions packages/rewards-calculator/src/workers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export class Workers {
private workers: Record<string, Worker> = {};
private bond = new Decimal(0);
private nextDistributionStartBlockNumber = 0n;

baseApr = new Decimal(0);
stakeFactor = new Decimal(0);
rAPR = new Decimal(0);
Expand Down Expand Up @@ -167,7 +167,7 @@ export class Workers {
const baseApr = await currentApy(
this.nextDistributionStartBlockNumber,
);
this.baseApr = new Decimal(baseApr.toString());
this.baseApr = bigIntToDecimal(baseApr);

this.stakeFactor = this.calculateStakeFactor();

Expand Down Expand Up @@ -309,10 +309,7 @@ export class Workers {
dayjs(this.clickhouseClient.from),
"second",
);
const apy = bigIntToDecimal(
await currentApy(this.nextDistributionStartBlockNumber),
);
return apy.mul(this.totalSupply()).mul(duration).div(YEAR).div(10_000);
return this.baseApr.mul(this.totalSupply()).mul(duration).div(YEAR).div(10_000);
}

private calculateStakeFactor() {
Expand Down
Loading