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

Update block count in a week #891

Merged
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
1 change: 1 addition & 0 deletions cspell.json
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@
"rpcutil",
"rustup",
"Sablier",
"sepolia",
"setu",
"Shouldset",
"Sighash",
Expand Down
1 change: 1 addition & 0 deletions packages/contracts/scripts/shared/constants/networks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ export const Networks: Record<string, number> = {
mainnet: 1,
optimism: 10,
goerli: 5,
sepolia: 11155111,
};

export const FALLBACK_RPC = "https://eth.ubq.fi/v1/mainnet";
23 changes: 23 additions & 0 deletions packages/contracts/scripts/task/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Dollar task scripts

## BlocksInWeek

BlocksInWeek task provides a close approximate of number of blocks mined in one week.

Usage:

Ethereum mainnet:

```
npx tsx scripts/task/task.ts BlocksInWeek --network=mainnet
```

Sepolia:

Ethereum mainnet:

```
npx tsx scripts/task/task.ts BlocksInWeek --network=sepolia
```

Prerequisite: set ETHERSCAN_API_KEY in .env
51 changes: 51 additions & 0 deletions packages/contracts/scripts/task/dollar/blocks-in-week.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { OptionDefinition } from "command-line-args";

import { Networks, TaskFuncParam } from "../../shared";
import { EtherscanProvider } from "ethers";

export const optionDefinitions: OptionDefinition[] = [
{ name: "task", defaultOption: true },
{ name: "network", alias: "n", type: String },
];

const funcBlocksInAWeek = async (params: TaskFuncParam) => {
const { args, env } = params;
const { network } = args;

const chainId = Networks[network] ?? undefined;
if (!chainId) {
throw new Error(`Unsupported network: ${network} Please configure it out first`);
}

const provider = new EtherscanProvider(chainId, env.etherscanApiKey);

console.log(`Calculating number of blocks in the last week...`);
const secondsInAWeek = 604800; // 24 * 7 * 60 * 60 seconds is one week
const currentBlockNumber = await provider.getBlockNumber();
const currentBlockTimestamp = (await provider.getBlock(currentBlockNumber))?.timestamp;
const blockTimestampTwoBlocksAgo = (await provider.getBlock(currentBlockNumber - 2))?.timestamp;

if (currentBlockTimestamp && blockTimestampTwoBlocksAgo) {
const avgBlockTime = (currentBlockTimestamp - blockTimestampTwoBlocksAgo) / 2;
console.log(`Recent average block time: ${avgBlockTime} seconds`);

const oneWeekAgo = currentBlockTimestamp - secondsInAWeek;
const estimatedBlocksInAWeek = secondsInAWeek / avgBlockTime;
console.log(`Estimated blocks in a week best case ${estimatedBlocksInAWeek}`);

let estimatedBlockNumber = currentBlockNumber - estimatedBlocksInAWeek;
let estimatedBlockTimestamp = (await provider.getBlock(estimatedBlockNumber))?.timestamp;

if (estimatedBlockTimestamp) {
let deltaBlockTime = oneWeekAgo - estimatedBlockTimestamp;
estimatedBlockNumber += Math.trunc(deltaBlockTime / avgBlockTime);
estimatedBlockTimestamp = (await provider.getBlock(estimatedBlockNumber))?.timestamp || estimatedBlockTimestamp;
deltaBlockTime -= estimatedBlockTimestamp - oneWeekAgo;

console.log(`Produced ${estimatedBlocksInAWeek - deltaBlockTime / avgBlockTime} blocks, ${deltaBlockTime / avgBlockTime} worst than the best case`);
}
}

return "succeeded";
};
export default funcBlocksInAWeek;
7 changes: 6 additions & 1 deletion packages/contracts/scripts/task/manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,16 @@ import { OptionDefinition } from "command-line-args";

import { TaskFuncCallBack } from "../shared";

import PriceResetHandler, { optionDefinitions as priceResetOptions } from "./dollar/priceReset";
import PriceResetHandler, { optionDefinitions, optionDefinitions as priceResetOptions } from "./dollar/price-reset";
import BlocksInWeekHandler from "./dollar/blocks-in-week";

export const TASK_FUNCS: Record<string, { handler: TaskFuncCallBack; options: OptionDefinition[] }> = {
PriceReset: {
handler: PriceResetHandler,
options: priceResetOptions,
},
BlocksInWeek: {
handler: BlocksInWeekHandler,
options: optionDefinitions,
},
};
3 changes: 2 additions & 1 deletion packages/contracts/scripts/task/task.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ const main = async () => {
throw new Error("You MUST put the task name in command arguments at least");
}

const envPath = path.join(__dirname, "../.env");
const envPath = path.join(__dirname, "../../.env");
if (!fs.existsSync(envPath)) {
throw new Error("Env file not found");
}
Expand All @@ -26,6 +26,7 @@ const main = async () => {
let args;
try {
args = CommandLineArgs(commandLineParseOptions);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (error: any) {
console.error(`Argument parse failed!, error: ${error}`);
return;
Expand Down
4 changes: 2 additions & 2 deletions packages/contracts/src/dollar/libraries/LibStaking.sol
Original file line number Diff line number Diff line change
Expand Up @@ -267,8 +267,8 @@ library LibStaking {
// deposit new shares
LibChef.deposit(msg.sender, _sharesAmount, _id);
// calculate end locking period block number
// 1 week = 45361 blocks = 2371753*7/366
// n = (block + duration * 45361)
// 1 week = 49930 blocks
// n = (block number + duration * 49930)
stake.endBlock = block.number + _weeks * ss.blockCountInAWeek;
gitcoindev marked this conversation as resolved.
Show resolved Hide resolved

// should be done after masterchef withdraw
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ contract DiamondInit is Modifiers {
// staking
LibStaking.StakingData storage ls = LibStaking.stakingStorage();
ls.stakingDiscountMultiplier = uint256(0.001 ether); // 0.001
ls.blockCountInAWeek = 45361;
ls.blockCountInAWeek = 49930;

// reentrancy guard
_initReentrancyGuard();
Expand Down
2 changes: 1 addition & 1 deletion packages/contracts/test/diamond/facets/ChefFacet.t.sol
Original file line number Diff line number Diff line change
Expand Up @@ -311,7 +311,7 @@ contract DepositStateChefTest is DepositStateChef {

// advance the block number to staking time so the withdraw is possible
uint256 currentBlock = block.number;
blocks = bound(blocks, 45361, 2 ** 128 - 1);
blocks = bound(blocks, 49930, 2 ** 128 - 1);
assertEq(chefFacet.totalShares(), shares);

uint256 preBal = governanceToken.balanceOf(fourthAccount);
Expand Down
2 changes: 1 addition & 1 deletion packages/contracts/test/diamond/facets/StakingFacet.t.sol
Original file line number Diff line number Diff line change
Expand Up @@ -312,7 +312,7 @@ contract DepositStateTest is DepositStateStaking {

// advance the block number to staking time so the withdraw is possible
uint256 currentBlock = block.number;
blocks = bound(blocks, 45361, 2 ** 128 - 1);
blocks = bound(blocks, 49930, 2 ** 128 - 1);
assertEq(chefFacet.totalShares(), shares);

uint256 preBal = governanceToken.balanceOf(fourthAccount);
Expand Down
Loading