Skip to content
Open
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
5 changes: 3 additions & 2 deletions packages/api/src/beacon/routes/beacon/pool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import {toForkName} from "../../../utils/fork.js";
import {fromHeaders} from "../../../utils/headers.js";
import {Endpoint, RouteDefinitions, Schema} from "../../../utils/index.js";
import {MetaHeader, VersionCodec, VersionMeta} from "../../../utils/metadata.js";
import {bigintToNumber} from "@lodestar/utils";

const SingleAttestationListTypePhase0 = ArrayOf(ssz.phase0.Attestation);
const SingleAttestationListTypeElectra = ArrayOf(ssz.electra.SingleAttestation);
Expand Down Expand Up @@ -399,7 +400,7 @@ export function getDefinitions(config: ChainForkConfig): RouteDefinitions<Endpoi
method: "POST",
req: {
writeReqJson: ({attesterSlashing}) => {
const fork = config.getForkName(Number(attesterSlashing.attestation1.data.slot));
const fork = config.getForkName(bigintToNumber(attesterSlashing.attestation1.data.slot));
return {
body: isForkPostElectra(fork)
? ssz.electra.AttesterSlashing.toJson(attesterSlashing)
Expand All @@ -416,7 +417,7 @@ export function getDefinitions(config: ChainForkConfig): RouteDefinitions<Endpoi
};
},
writeReqSsz: ({attesterSlashing}) => {
const fork = config.getForkName(Number(attesterSlashing.attestation1.data.slot));
const fork = config.getForkName(bigintToNumber(attesterSlashing.attestation1.data.slot));
return {
body: isForkPostElectra(fork)
? ssz.electra.AttesterSlashing.serialize(attesterSlashing as electra.AttesterSlashing)
Expand Down
5 changes: 3 additions & 2 deletions packages/api/src/beacon/routes/events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {EmptyMeta, EmptyResponseCodec, EmptyResponseData} from "../../utils/code
import {getPostAltairForkTypes, getPostBellatrixForkTypes} from "../../utils/fork.js";
import {Endpoint, RouteDefinitions, Schema} from "../../utils/index.js";
import {VersionType} from "../../utils/metadata.js";
import {bigintToNumber} from "@lodestar/utils";

const stringType = new StringType();
export const blobSidecarSSE = new ContainerType(
Expand Down Expand Up @@ -273,11 +274,11 @@ export function getTypeByEvent(config: ChainForkConfig): {[K in EventType]: Type
[EventType.proposerSlashing]: ssz.phase0.ProposerSlashing,
[EventType.attesterSlashing]: {
toJson: (attesterSlashing) => {
const fork = config.getForkName(Number(attesterSlashing.attestation1.data.slot));
const fork = config.getForkName(bigintToNumber(attesterSlashing.attestation1.data.slot));
return sszTypesFor(fork).AttesterSlashing.toJson(attesterSlashing);
},
fromJson: (attesterSlashing) => {
const fork = config.getForkName(Number((attesterSlashing as AttesterSlashing).attestation1.data.slot));
const fork = config.getForkName(bigintToNumber((attesterSlashing as AttesterSlashing).attestation1.data.slot));
return sszTypesFor(fork).AttesterSlashing.fromJson(attesterSlashing);
},
},
Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/keymanager/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -691,7 +691,7 @@ function parseGasLimit(gasLimitInput: string | number): number {
if ((typeof gasLimitInput !== "string" && typeof gasLimitInput !== "number") || `${gasLimitInput}`.trim() === "") {
throw Error("Not valid Gas Limit");
}
const gasLimit = Number(gasLimitInput);
const gasLimit = typeof gasLimitInput === "string" ? parseInt(gasLimitInput, 10) : gasLimitInput;
if (Number.isNaN(gasLimit) || gasLimit === 0) {
throw Error(`Gas Limit is not valid gasLimit=${gasLimit}`);
}
Expand Down
4 changes: 3 additions & 1 deletion packages/beacon-node/src/api/impl/beacon/pool/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ import {validateApiVoluntaryExit} from "../../../../chain/validation/voluntaryEx
import {validateGossipFnRetryUnknownRoot} from "../../../../network/processor/gossipHandlers.js";
import {ApiError, FailureList, IndexedError} from "../../errors.js";
import {ApiModules} from "../../types.js";
import {bigintToNumber} from "@lodestar/utils"


export function getBeaconPoolApi({
chain,
Expand Down Expand Up @@ -180,7 +182,7 @@ export function getBeaconPoolApi({

async submitPoolAttesterSlashingsV2({attesterSlashing}) {
await validateApiAttesterSlashing(chain, attesterSlashing);
const fork = chain.config.getForkName(Number(attesterSlashing.attestation1.data.slot));
const fork = chain.config.getForkName(bigintToNumber(attesterSlashing.attestation1.data.slot));
chain.opPool.insertAttesterSlashing(fork, attesterSlashing);
await network.publishAttesterSlashing(attesterSlashing);
},
Expand Down
2 changes: 1 addition & 1 deletion packages/beacon-node/src/api/impl/beacon/state/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ export function getStateValidatorIndex(
return {valid: false, code: 400, reason: "Invalid pubkey hex encoding"};
}
} else {
id = Number(id);
id = parseInt(id, 10);
}
}

Expand Down
10 changes: 5 additions & 5 deletions packages/beacon-node/src/api/impl/validator/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,8 @@ import {
} from "@lodestar/types";
import {
TimeoutError,
bigintToNumber,
defer,
formatWeiToEth,
fromHex,
prettyWeiToEth,
resolveOrRacePromises,
Expand Down Expand Up @@ -455,8 +455,8 @@ export function getValidatorApi(

metrics?.blockProductionSuccess.inc({source});
metrics?.blockProductionNumAggregated.observe({source}, block.body.attestations.length);
metrics?.blockProductionConsensusBlockValue.observe({source}, Number(formatWeiToEth(consensusBlockValue)));
metrics?.blockProductionExecutionPayloadValue.observe({source}, Number(formatWeiToEth(executionPayloadValue)));
metrics?.blockProductionConsensusBlockValue.observe({source}, bigintToNumber(consensusBlockValue));
metrics?.blockProductionExecutionPayloadValue.observe({source}, bigintToNumber(executionPayloadValue));
logger.verbose("Produced blinded block", {
slot,
executionPayloadValue,
Expand Down Expand Up @@ -512,8 +512,8 @@ export function getValidatorApi(

metrics?.blockProductionSuccess.inc({source});
metrics?.blockProductionNumAggregated.observe({source}, block.body.attestations.length);
metrics?.blockProductionConsensusBlockValue.observe({source}, Number(formatWeiToEth(consensusBlockValue)));
metrics?.blockProductionExecutionPayloadValue.observe({source}, Number(formatWeiToEth(executionPayloadValue)));
metrics?.blockProductionConsensusBlockValue.observe({source}, bigintToNumber(consensusBlockValue));
metrics?.blockProductionExecutionPayloadValue.observe({source}, bigintToNumber(executionPayloadValue));

const blockRoot = toRootHex(config.getForkTypes(slot).BeaconBlock.hashTreeRoot(block));
logger.verbose("Produced execution block", {
Expand Down
3 changes: 2 additions & 1 deletion packages/beacon-node/src/chain/chain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ import {InMemoryCheckpointStateCache} from "./stateCache/inMemoryCheckpointsCach
import {PersistentCheckpointStateCache} from "./stateCache/persistentCheckpointsCache.js";
import {CheckpointStateCache} from "./stateCache/types.js";
import {ValidatorMonitor} from "./validatorMonitor.js";
import {bigintToNumber} from "@lodestar/utils"

/**
* The maximum number of cached produced results to keep in memory.
Expand Down Expand Up @@ -421,7 +422,7 @@ export class BeaconChain implements IBeaconChain {
const anchorStateFork = this.config.getForkName(anchorState.slot);
if (isForkPostElectra(anchorStateFork)) {
const {eth1DepositIndex, depositRequestsStartIndex} = anchorState as BeaconStateElectra;
if (eth1DepositIndex === Number(depositRequestsStartIndex)) {
if (eth1DepositIndex === bigintToNumber(depositRequestsStartIndex)) {
this.eth1.stopPollingEth1Data();
}
}
Expand Down
4 changes: 2 additions & 2 deletions packages/beacon-node/src/chain/prepareNextSlot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
isExecutionStateType,
} from "@lodestar/state-transition";
import {Slot} from "@lodestar/types";
import {Logger, fromHex, isErrorAborted, sleep} from "@lodestar/utils";
import {Logger, bigintToNumber, fromHex, isErrorAborted, sleep} from "@lodestar/utils";
import {GENESIS_SLOT, ZERO_HASH_HEX} from "../constants/constants.js";
import {BuilderStatus} from "../execution/builder/http.js";
import {Metrics} from "../metrics/index.js";
Expand Down Expand Up @@ -266,7 +266,7 @@ export class PrepareNextSlotScheduler {

if (
finalizedState !== undefined &&
finalizedState.eth1DepositIndex === Number((finalizedState as BeaconStateElectra).depositRequestsStartIndex)
finalizedState.eth1DepositIndex === bigintToNumber((finalizedState as BeaconStateElectra).depositRequestsStartIndex)
) {
// Signal eth1 to stop polling eth1Data
this.chain.eth1.stopPollingEth1Data();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -857,7 +857,7 @@ function fromCacheKey(key: CacheKey): CheckpointHex {
const [rootHex, epoch] = key.split("_");
return {
rootHex,
epoch: Number(epoch),
epoch: parseInt(epoch),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

It's a good practice to always specify the radix for parseInt. Since epoch is a decimal number string, you should specify radix 10 to ensure correct parsing and avoid potential issues.

    epoch: parseInt(epoch, 10),

};
}

Expand Down
10 changes: 5 additions & 5 deletions packages/beacon-node/src/eth1/eth1MergeBlockTracker.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {ChainConfig} from "@lodestar/config";
import {RootHex} from "@lodestar/types";
import {Logger, pruneSetToMax, toRootHex} from "@lodestar/utils";
import {bigintToNumber, Logger, pruneSetToMax, toRootHex} from "@lodestar/utils";
import {ZERO_HASH_HEX} from "../constants/index.js";
import {Metrics} from "../metrics/index.js";
import {enumToIndexMap} from "../util/enum.js";
Expand Down Expand Up @@ -75,8 +75,8 @@ export class Eth1MergeBlockTracker {
// Only run metrics if necessary
if (metrics) {
// TTD can't be dynamically changed during execution, register metric once
metrics.eth1.eth1MergeTTD.set(Number(scaledTTD as bigint));
metrics.eth1.eth1MergeTDFactor.set(Number(this.safeTDFactor as bigint));
metrics.eth1.eth1MergeTTD.set(bigintToNumber(scaledTTD as bigint));
metrics.eth1.eth1MergeTDFactor.set(bigintToNumber(this.safeTDFactor as bigint));

metrics.eth1.eth1MergeStatus.addCollect(() => {
// Set merge ttd, merge status and merge block status
Expand All @@ -85,7 +85,7 @@ export class Eth1MergeBlockTracker {
if (this.latestEth1Block !== null) {
// Set latestBlock stats
metrics.eth1.eth1LatestBlockNumber.set(this.latestEth1Block.number);
metrics.eth1.eth1LatestBlockTD.set(Number(this.latestEth1Block.totalDifficulty / this.safeTDFactor));
metrics.eth1.eth1LatestBlockTD.set(bigintToNumber(this.latestEth1Block.totalDifficulty / this.safeTDFactor));
metrics.eth1.eth1LatestBlockTimestamp.set(this.latestEth1Block.timestamp);
}
});
Expand Down Expand Up @@ -121,7 +121,7 @@ export class Eth1MergeBlockTracker {
return {
ttdHit: false,
tdFactor: this.safeTDFactor,
tdDiffScaled: Number((tdDiff / this.safeTDFactor) as bigint),
tdDiffScaled: bigintToNumber((tdDiff / this.safeTDFactor) as bigint),
ttd: this.config.TERMINAL_TOTAL_DIFFICULTY,
td: this.latestEth1Block.totalDifficulty,
timestamp: this.latestEth1Block.timestamp,
Expand Down
4 changes: 2 additions & 2 deletions packages/beacon-node/src/eth1/utils/eth1Vote.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import {ChainForkConfig} from "@lodestar/config";
import {EPOCHS_PER_ETH1_VOTING_PERIOD, SLOTS_PER_EPOCH, isForkPostElectra} from "@lodestar/params";
import {BeaconStateAllForks, BeaconStateElectra, computeTimeAtSlot} from "@lodestar/state-transition";
import {RootHex, phase0} from "@lodestar/types";
import {toRootHex} from "@lodestar/utils";
import { bigintToNumber, toRootHex} from "@lodestar/utils";

export type Eth1DataGetter = ({
timestampRange,
Expand All @@ -18,7 +18,7 @@ export async function getEth1VotesToConsider(
const fork = config.getForkName(state.slot);
if (isForkPostElectra(fork)) {
const {eth1DepositIndex, depositRequestsStartIndex} = state as BeaconStateElectra;
if (eth1DepositIndex === Number(depositRequestsStartIndex)) {
if (eth1DepositIndex === bigintToNumber(depositRequestsStartIndex)) {
return state.eth1DataVotes.getAllReadonly();
}
}
Expand Down
2 changes: 1 addition & 1 deletion packages/beacon-node/src/execution/engine/mock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -414,7 +414,7 @@ export class ExecutionEngineMockBackend implements JsonRpcBackend {
): EngineApiRpcReturnTypes["engine_getPayloadV5"] {
// 1. Given the payloadId client software MUST return the most recent version of the payload that is available in
// the corresponding build process at the time of receiving the call.
const payloadIdNbr = Number(payloadId);
const payloadIdNbr = parseInt(payloadId, 10);
const payload = this.preparingPayloads.get(payloadIdNbr);

// 2. The call MUST return -38001: Unknown payload error if the build process identified by the payloadId does not
Expand Down
6 changes: 3 additions & 3 deletions packages/beacon-node/src/network/network.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import {
fulu,
phase0,
} from "@lodestar/types";
import {prettyPrintIndices, sleep} from "@lodestar/utils";
import {bigintToNumber, prettyPrintIndices, sleep} from "@lodestar/utils";
import {BlockInputSource} from "../chain/blocks/blockInput/types.js";
import {ChainEvent, IBeaconChain} from "../chain/index.js";
import {computeSubnetForDataColumnSidecar} from "../chain/validation/dataColumnSidecar.js";
Expand Down Expand Up @@ -427,7 +427,7 @@ export class Network implements INetwork {
}

async publishProposerSlashing(proposerSlashing: phase0.ProposerSlashing): Promise<number> {
const epoch = computeEpochAtSlot(Number(proposerSlashing.signedHeader1.message.slot as bigint));
const epoch = computeEpochAtSlot(bigintToNumber(proposerSlashing.signedHeader1.message.slot as bigint));
const boundary = this.config.getForkBoundaryAtEpoch(epoch);

return this.publishGossip<GossipType.proposer_slashing>(
Expand All @@ -437,7 +437,7 @@ export class Network implements INetwork {
}

async publishAttesterSlashing(attesterSlashing: AttesterSlashing): Promise<number> {
const epoch = computeEpochAtSlot(Number(attesterSlashing.attestation1.data.slot as bigint));
const epoch = computeEpochAtSlot(bigintToNumber(attesterSlashing.attestation1.data.slot as bigint));
const boundary = this.config.getForkBoundaryAtEpoch(epoch);

return this.publishGossip<GossipType.attester_slashing>(
Expand Down
12 changes: 6 additions & 6 deletions packages/beacon-node/test/spec/presets/light_client/sync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {isForkPostAltair} from "@lodestar/params";
import {InputType} from "@lodestar/spec-test-util";
import {computeSyncPeriodAtSlot} from "@lodestar/state-transition";
import {RootHex, Slot, altair, phase0, ssz, sszTypesFor} from "@lodestar/types";
import {fromHex, toHex} from "@lodestar/utils";
import {bigintToNumber, fromHex, toHex} from "@lodestar/utils";
import {testLogger} from "../../../utils/logger.js";
import {TestRunnerFn} from "../../utils/types.js";

Expand Down Expand Up @@ -98,7 +98,7 @@ export const sync: TestRunnerFn<SyncTestCase, void> = (fork) => {

function assertHeader(actualHeader: phase0.BeaconBlockHeader, expectedHeader: CheckHeader, msg: string): void {
expect(toHeaderSummary(actualHeader)).deep.equals(
{root: expectedHeader.beacon_root, slot: Number(expectedHeader.slot as bigint)},
{root: expectedHeader.beacon_root, slot: bigintToNumber(expectedHeader.slot as bigint)},
msg
);
}
Expand All @@ -119,15 +119,15 @@ export const sync: TestRunnerFn<SyncTestCase, void> = (fork) => {
for (const [i, step] of testcase.steps.entries()) {
try {
if (isProcessUpdateStep(step)) {
const currentSlot = Number(step.process_update.current_slot as bigint);
const currentSlot = bigintToNumber(step.process_update.current_slot as bigint);
logger.debug(`Step ${i}/${stepsLen} process_update`, renderSlot(currentSlot));

const updateBytes = testcase.updates.get(step.process_update.update);
if (!updateBytes) {
throw Error(`update ${step.process_update.update} not found`);
}

const headerSlot = Number(step.process_update.checks.optimistic_header.slot);
const headerSlot = bigintToNumber(step.process_update.checks.optimistic_header.slot);
const update = config.getPostAltairForkTypes(headerSlot).LightClientUpdate.deserialize(updateBytes);

logger.debug(`LightclientUpdateSummary: ${JSON.stringify(toLightClientUpdateSummary(update))}`);
Expand All @@ -138,7 +138,7 @@ export const sync: TestRunnerFn<SyncTestCase, void> = (fork) => {

// force_update step
else if (isForceUpdateStep(step)) {
const currentSlot = Number(step.force_update.current_slot as bigint);
const currentSlot = bigintToNumber(step.force_update.current_slot as bigint);
logger.debug(`Step ${i}/${stepsLen} force_update`, renderSlot(currentSlot));

// Simulate force_update()
Expand Down Expand Up @@ -201,7 +201,7 @@ function pickConfigForkEpochs(config: Partial<ChainConfig>): Partial<ChainConfig
if (typeof value === "bigint" && value > BigInt(Number.MAX_SAFE_INTEGER)) {
configOnlyFork[key] = Infinity;
} else {
configOnlyFork[key] = Number(value);
configOnlyFork[key] = typeof value === "bigint" ? bigintToNumber(value) : Number(value);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import {isForkPostAltair} from "@lodestar/params";
import {InputType} from "@lodestar/spec-test-util";
import {LightClientUpdate, altair, ssz, sszTypesFor} from "@lodestar/types";
import {TestRunnerFn} from "../../utils/types.js";
import {bigintToNumber} from "@lodestar/utils";


// https://github.com/ethereum/consensus-specs/blob/da3f5af919be4abb5a6db5a80b235deb8b4b5cba/tests/formats/light_client/update_ranking.md
type UpdateRankingTestCase = {
Expand All @@ -19,7 +21,7 @@ export const updateRanking: TestRunnerFn<UpdateRankingTestCase, void> = (fork) =
return {
testFunction: (testcase) => {
// Parse update files
const updatesCount = Number(testcase.meta.updates_count as bigint);
const updatesCount = bigintToNumber(testcase.meta.updates_count as bigint);
const updates: LightClientUpdate[] = [];

for (let i = 0; i < updatesCount; i++) {
Expand Down
10 changes: 5 additions & 5 deletions packages/beacon-node/test/unit/execution/engine/types.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@ describe("execution / engine / types", () => {

// Assert 1-byte request_type prefix is set correctly
expect(serialized.length).toBe(3);
expect(Number(serialized[0].substring(0, 2))).toBe(DEPOSIT_REQUEST_TYPE);
expect(Number(serialized[1].substring(0, 2))).toBe(WITHDRAWAL_REQUEST_TYPE);
expect(Number(serialized[2].substring(0, 2))).toBe(CONSOLIDATION_REQUEST_TYPE);
expect(parseInt(serialized[0].substring(0, 2), 16)).toBe(DEPOSIT_REQUEST_TYPE);
expect(parseInt(serialized[1].substring(0, 2), 16)).toBe(WITHDRAWAL_REQUEST_TYPE);
expect(parseInt(serialized[2].substring(0, 2), 16)).toBe(CONSOLIDATION_REQUEST_TYPE);

// Assert execution requests can be deserialized
expect(ssz.electra.DepositRequests.deserialize(fromHex(serialized[0].slice(2)))).toEqual(
Expand All @@ -44,8 +44,8 @@ describe("execution / engine / types", () => {

// Assert withdrawals are omitted
expect(serialized.length).toBe(2);
expect(Number(serialized[0].substring(0, 2))).toBe(DEPOSIT_REQUEST_TYPE);
expect(Number(serialized[1].substring(0, 2))).toBe(CONSOLIDATION_REQUEST_TYPE);
expect(parseInt(serialized[0].substring(0, 2), 16)).toBe(DEPOSIT_REQUEST_TYPE);
expect(parseInt(serialized[1].substring(0, 2), 16)).toBe(CONSOLIDATION_REQUEST_TYPE);

// Assert execution requests can be deserialized
expect(ssz.electra.DepositRequests.deserialize(fromHex(serialized[0].slice(2)))).toEqual(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ describe("monitoring / service", () => {
});

it("should properly handle errors if remote service is unreachable", async () => {
const differentPort = Number(remoteServiceUrl.port) - 1;
const differentPort = parseInt(remoteServiceUrl.port, 10) - 1;
const endpoint = `http://127.0.0.1:${differentPort}/`;
service = new MonitoringService("beacon", {endpoint}, {register, logger});

Expand Down
Loading
Loading