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

chore: upgrade eslint and fix the warnings #6420

Merged
merged 7 commits into from
Feb 13, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,10 @@ module.exports = {
},
//ignore rules on destructured params
{selector: "variable", modifiers: ["destructured"], format: null},
{
selector: "import",
format: ["camelCase", "PascalCase"]
Copy link
Contributor Author

Choose a reason for hiding this comment

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

This will allow to import packages like below without warnings.

import EventEmitter from "node:events";

},
],
"@typescript-eslint/no-explicit-any": "error",
"@typescript-eslint/no-floating-promises": "error",
Expand Down Expand Up @@ -159,6 +163,7 @@ module.exports = {
"prettier/prettier": "error",
quotes: ["error", "double"],
semi: "off",
"import/namespace": "off",
Copy link
Contributor Author

Choose a reason for hiding this comment

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

https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/namespace.md

This rule is taking most of the linting time, 33% of the overall time.

This rule check each package usages at import time, but is not trivial to us as the non-existing methods can also be detected by unsafe-assignment rules.

import/namespace                              | 10715.327 |    33.2%

Copy link
Member

Choose a reason for hiding this comment

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

we should probably add a short comment in eslintrc to document it there as well

},
settings: {
"import/core-modules": [
Expand Down
12 changes: 6 additions & 6 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,18 +50,18 @@
"@dapplion/benchmark": "^0.2.4",
"@types/mocha": "^10.0.6",
"@types/node": "^20.6.5",
"@typescript-eslint/eslint-plugin": "6.7.2",
"@typescript-eslint/parser": "6.7.2",
"@typescript-eslint/eslint-plugin": "6.21.0",
"@typescript-eslint/parser": "6.21.0",
"@vitest/coverage-v8": "^1.2.1",
"@vitest/browser": "^1.2.1",
"crypto-browserify": "^3.12.0",
"dotenv": "^16.4.1",
"electron": "^26.2.2",
"eslint": "^8.50.0",
"eslint": "^8.56.0",
"eslint-import-resolver-typescript": "^3.6.1",
"eslint-plugin-import": "^2.28.1",
"eslint-plugin-prettier": "^5.0.0",
"eslint-plugin-vitest": "^0.3.20",
"eslint-plugin-import": "^2.29.1",
"eslint-plugin-prettier": "^5.1.3",
"eslint-plugin-vitest": "^0.3.22",
"https-browserify": "^1.0.0",
"jsdom": "^23.0.1",
"lerna": "^7.3.0",
Expand Down
4 changes: 2 additions & 2 deletions packages/api/src/utils/client/format.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import qs from "qs";
import {stringify as queryStringStringify} from "qs";

/**
* Ethereum Beacon API requires the query with format:
* - arrayFormat: repeat `topic=topic1&topic=topic2`
*/
export function stringifyQuery(query: unknown): string {
return qs.stringify(query, {arrayFormat: "repeat"});
return queryStringStringify(query, {arrayFormat: "repeat"});
}

/**
Expand Down
2 changes: 1 addition & 1 deletion packages/api/test/unit/client/httpClient.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {IncomingMessage} from "node:http";
import {describe, it, afterEach, expect} from "vitest";
import fastify, {RouteOptions} from "fastify";
import {RouteOptions, fastify} from "fastify";
import {ErrorAborted, TimeoutError, toBase64} from "@lodestar/utils";
import {HttpClient, HttpError} from "../../../src/utils/client/index.js";
import {HttpStatusCode} from "../../../src/utils/client/httpStatusCode.js";
Expand Down
2 changes: 1 addition & 1 deletion packages/api/test/utils/utils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {MockedObject, vi} from "vitest";
import qs from "qs";
import fastify, {FastifyInstance} from "fastify";
import {FastifyInstance, fastify} from "fastify";
import {mapValues} from "@lodestar/utils";
import {ServerApi} from "../../src/interfaces.js";

Expand Down
8 changes: 4 additions & 4 deletions packages/beacon-node/src/api/rest/base.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import qs from "qs";
import fastify, {FastifyInstance} from "fastify";
import fastifyCors from "@fastify/cors";
import {parse as parseQueryString} from "qs";
import {FastifyInstance, fastify} from "fastify";
import {fastifyCors} from "@fastify/cors";
import bearerAuthPlugin from "@fastify/bearer-auth";
import {RouteConfig} from "@lodestar/api/beacon/server";
import {ErrorAborted, Gauge, Histogram, Logger} from "@lodestar/utils";
Expand Down Expand Up @@ -48,7 +48,7 @@ export class RestApiServer {
logger: false,
ajv: {customOptions: {coerceTypes: "array"}},
querystringParser: (str) =>
qs.parse(str, {
parseQueryString(str, {
// Array as comma-separated values must be supported to be OpenAPI spec compliant
comma: true,
// Drop support for array query strings like `id[0]=1&id[1]=2&id[2]=3` as those are not required to
Expand Down
2 changes: 1 addition & 1 deletion packages/beacon-node/src/chain/emitter.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {EventEmitter} from "events";
import StrictEventEmitter from "strict-event-emitter-types";
import {StrictEventEmitter} from "strict-event-emitter-types";

import {routes} from "@lodestar/api";
import {phase0} from "@lodestar/types";
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {EventEmitter} from "events";
import StrictEventEmitter from "strict-event-emitter-types";
import {StrictEventEmitter} from "strict-event-emitter-types";
import {fetch} from "@lodestar/api";
import {ErrorAborted, Gauge, Histogram, TimeoutError, isValidHttpUrl, retry} from "@lodestar/utils";
import {IJson, RpcPayload} from "../interface.js";
Expand Down
4 changes: 1 addition & 3 deletions packages/beacon-node/src/eth1/provider/jwt.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import type {TAlgorithm} from "jwt-simple";
// TODO: fix jwt-simple types
import jwt from "jwt-simple";

const {encode, decode} = jwt;
import {encode, decode} from "jwt-simple";

/**
* jwt token has iat which is issued at unix timestamp, an optional exp for expiry,
Expand Down
13 changes: 13 additions & 0 deletions packages/beacon-node/src/monitoring/system.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import os from "node:os";
import path from "node:path";
// We want to keep `system` export as it's more readable and easier to understand
// eslint-disable-next-line import/no-named-as-default
nflaig marked this conversation as resolved.
Show resolved Hide resolved
import system from "systeminformation";
import {Logger} from "@lodestar/utils";

Expand Down Expand Up @@ -56,6 +58,8 @@ class System {
private async collectStaticData(): Promise<void> {
if (this.staticDataCollected) return;

// Usage of `system.cpu()` is more readable than `cpu()`
// eslint-disable-next-line import/no-named-as-default-member
const cpu = await system.cpu();
// Note: inside container this might be inaccurate as
// physicalCores in some cases is the count of logical CPU cores
Expand Down Expand Up @@ -85,6 +89,8 @@ class System {
}

private async collectMemoryData(): Promise<void> {
// Usage of `system.mem()` is more readable than `mem()`
// eslint-disable-next-line import/no-named-as-default-member
const memory = await system.mem();
this.memoryNodeBytesTotal = memory.total;
this.memoryNodeBytesFree = memory.free;
Expand All @@ -93,6 +99,8 @@ class System {
}

private async collectDiskData(): Promise<void> {
// Usage of `system.fsSize()` is more readable than `fsSize()`
// eslint-disable-next-line import/no-named-as-default-member
nazarhussain marked this conversation as resolved.
Show resolved Hide resolved
const fileSystems = await system.fsSize();
// get file system root, on windows this is the name of the hard disk partition
const rootFs = process.platform === "win32" ? process.cwd().split(path.sep)[0] : "/";
Expand All @@ -102,6 +110,8 @@ class System {
this.diskNodeBytesFree = fileSystem.available;

if (this.diskIOMeasurable) {
// Usage of `system.disksIO()` is more readable than `disksIO()`
// eslint-disable-next-line import/no-named-as-default-member
const disk = await system.disksIO();
if (disk != null && disk.rIO !== 0) {
// Note: rIO and wIO might not be available inside container
Expand All @@ -116,6 +126,9 @@ class System {

private async collectNetworkData(): Promise<void> {
// defaults to first external network interface

// Usage of `system.networkStats()` is more readable than `networkStats()`
// eslint-disable-next-line import/no-named-as-default-member
const [network] = await system.networkStats();
// Note: rx_bytes and tx_bytes will be inaccurate if process
// runs inside container as it only captures local network traffic
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import path from "node:path";
import worker_threads from "node:worker_threads";
import workerThreads from "node:worker_threads";
import {PeerScoreStatsDump} from "@chainsafe/libp2p-gossipsub/dist/src/score/peer-score.js";
import {PublishOpts} from "@chainsafe/libp2p-gossipsub/types";
import {ModuleThread, Thread, Worker, spawn} from "@chainsafe/threads";
Expand Down Expand Up @@ -78,14 +78,14 @@ export class WorkerNetworkCore implements INetworkCore {
wireEventsOnMainThread<NetworkEventData>(
NetworkWorkerThreadEventType.networkEvent,
modules.events,
modules.worker as unknown as worker_threads.Worker,
modules.worker as unknown as workerThreads.Worker,
modules.metrics,
networkEventDirection
);
wireEventsOnMainThread<ReqRespBridgeEventData>(
NetworkWorkerThreadEventType.reqRespBridgeEvents,
this.reqRespBridgeEventBus,
modules.worker as unknown as worker_threads.Worker,
modules.worker as unknown as workerThreads.Worker,
modules.metrics,
reqRespBridgeEventDirection
);
Expand Down
2 changes: 1 addition & 1 deletion packages/beacon-node/src/network/discv5/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import EventEmitter from "events";
import {PeerId} from "@libp2p/interface";
import StrictEventEmitter from "strict-event-emitter-types";
import {StrictEventEmitter} from "strict-event-emitter-types";
import {exportToProtobuf} from "@libp2p/peer-id-factory";
import {createPrivateKeyFromPeerId, ENR, ENRData, SignableENR} from "@chainsafe/enr";
import {spawn, Thread, Worker} from "@chainsafe/threads";
Expand Down
2 changes: 1 addition & 1 deletion packages/beacon-node/src/sync/range/range.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {EventEmitter} from "events";
import StrictEventEmitter from "strict-event-emitter-types";
import {StrictEventEmitter} from "strict-event-emitter-types";
import {computeStartSlotAtEpoch} from "@lodestar/state-transition";
import {BeaconConfig} from "@lodestar/config";
import {Epoch, phase0} from "@lodestar/types";
Expand Down
4 changes: 2 additions & 2 deletions packages/beacon-node/src/util/blobs.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import SHA256 from "@chainsafe/as-sha256";
import {digest as sha256Digest} from "@chainsafe/as-sha256";
import {Tree} from "@chainsafe/persistent-merkle-tree";
import {VERSIONED_HASH_VERSION_KZG, KZG_COMMITMENT_GINDEX0, ForkName} from "@lodestar/params";
import {deneb, ssz, allForks} from "@lodestar/types";
Expand All @@ -8,7 +8,7 @@ import {signedBlockToSignedHeader} from "@lodestar/state-transition";
type VersionHash = Uint8Array;

export function kzgCommitmentToVersionedHash(kzgCommitment: deneb.KZGCommitment): VersionHash {
const hash = SHA256.digest(kzgCommitment);
const hash = sha256Digest(kzgCommitment);
// Equivalent to `VERSIONED_HASH_VERSION_KZG + hash(kzg_commitment)[1:]`
hash[0] = VERSIONED_HASH_VERSION_KZG;
return hash;
Expand Down
2 changes: 1 addition & 1 deletion packages/beacon-node/src/util/clock.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import EventEmitter from "node:events";
import type StrictEventEmitter from "strict-event-emitter-types";
import type {StrictEventEmitter} from "strict-event-emitter-types";
import type {Epoch, Slot} from "@lodestar/types";
import {ChainForkConfig} from "@lodestar/config";
import {ErrorAborted} from "@lodestar/utils";
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import worker_threads from "node:worker_threads";
import workerThreads from "node:worker_threads";
import {spawn, Worker} from "@chainsafe/threads";

export type EchoWorker = {
Expand All @@ -8,7 +8,7 @@ export type EchoWorker = {

export async function getEchoWorker(): Promise<EchoWorker> {
const workerThreadjs = new Worker("./workerEcho.js");
const worker = workerThreadjs as unknown as worker_threads.Worker;
const worker = workerThreadjs as unknown as workerThreads.Worker;

// eslint-disable-next-line @typescript-eslint/no-explicit-any
await spawn<any>(workerThreadjs, {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import fastify from "fastify";
import {fastify} from "fastify";
import {afterAll, expect} from "vitest";
import {RemoteServiceError} from "../../../src/monitoring/service.js";
import {ProcessType} from "../../../src/monitoring/types.js";
Expand Down
4 changes: 2 additions & 2 deletions packages/beacon-node/test/utils/db.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import child_process from "node:child_process";
import childProcess from "node:child_process";
import {FilterOptions, LevelDbController} from "@lodestar/db";
import {ChainForkConfig} from "@lodestar/config";
import {BeaconDb} from "../../src/index.js";
Expand All @@ -8,7 +8,7 @@ export const TEMP_DB_LOCATION = ".tmpdb";

export async function startTmpBeaconDb(config: ChainForkConfig): Promise<BeaconDb> {
// Clean-up db first
child_process.execSync(`rm -rf ${TEMP_DB_LOCATION}`);
childProcess.execSync(`rm -rf ${TEMP_DB_LOCATION}`);

return new BeaconDb(config, await LevelDbController.create({name: TEMP_DB_LOCATION}, {logger: testLogger()}));
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import fastify from "fastify";
import {fastify} from "fastify";
import {fromHexString} from "@chainsafe/ssz";
import type {SecretKey} from "@chainsafe/bls/types";
import {EXTERNAL_SIGNER_BASE_PORT} from "./constants.js";
Expand Down
4 changes: 2 additions & 2 deletions packages/cli/test/utils/simulation/SimulationTracker.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import EventEmitter from "node:events";
import Debug from "debug";
import createDebug from "debug";
import {routes} from "@lodestar/api/beacon";
import {ChainForkConfig} from "@lodestar/config";
import {Epoch, Slot} from "@lodestar/types";
Expand All @@ -20,7 +20,7 @@ import {defaultAssertions} from "./assertions/defaults/index.js";
import {TableReporter} from "./TableReporter.js";
import {fetchBlock} from "./utils/network.js";

const debug = Debug("lodestar:sim:tracker");
const debug = createDebug("lodestar:sim:tracker");

interface SimulationTrackerInitOptions {
nodes: NodePair[];
Expand Down
8 changes: 4 additions & 4 deletions packages/light-client/test/utils/server.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import qs from "qs";
import fastify, {FastifyInstance} from "fastify";
import fastifyCors from "@fastify/cors";
import {parse as queryStringParse} from "qs";
import {FastifyInstance, fastify} from "fastify";
import {fastifyCors} from "@fastify/cors";
import {Api, ServerApi} from "@lodestar/api";
import {registerRoutes} from "@lodestar/api/beacon/server";
import {ChainForkConfig} from "@lodestar/config";
Expand All @@ -18,7 +18,7 @@ export async function startServer(
const server = fastify({
logger: false,
ajv: {customOptions: {coerceTypes: "array"}},
querystringParser: (str) => qs.parse(str, {comma: true, parseArrays: false}),
querystringParser: (str) => queryStringParse(str, {comma: true, parseArrays: false}),
});

registerRoutes(server, config, api, ["lightclient", "proof", "events"]);
Expand Down
2 changes: 2 additions & 0 deletions packages/logger/src/node.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import path from "node:path";
import DailyRotateFile from "winston-daily-rotate-file";
import TransportStream from "winston-transport";
// We want to keep `winston` export as it's more readable and easier to understand
// eslint-disable-next-line import/no-named-as-default-member
import winston from "winston";
import type {Logger as Winston} from "winston";
import {Logger, LogLevel, TimestampFormat} from "./interface.js";
Expand Down
6 changes: 3 additions & 3 deletions packages/logger/src/utils/format.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import winston from "winston";
// We want to keep `winston` export as it's more readable and easier to understand
// eslint-disable-next-line import/no-named-as-default-member
import winston, {format} from "winston";
import {LodestarError, isEmptyObject} from "@lodestar/utils";
import {LoggerOptions, TimestampFormatCode} from "../interface.js";
import {logCtxToJson, logCtxToString, LogData} from "./json.js";
import {formatEpochSlotTime} from "./timeFormat.js";

const {format} = winston;

type Format = ReturnType<typeof winston.format.combine>;

// TODO: Find a more typesafe way of enforce this properties
Expand Down
6 changes: 4 additions & 2 deletions packages/logger/src/winston.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import winston from "winston";
// We want to keep `winston` export as it's more readable and easier to understand
// eslint-disable-next-line import/no-named-as-default-member
import winston, {createLogger} from "winston";
import type {Logger as Winston} from "winston";
import {Logger, LoggerOptions, LogLevel, logLevelNum} from "./interface.js";
import {getFormat} from "./utils/format.js";
Expand Down Expand Up @@ -46,7 +48,7 @@ export class WinstonLogger implements Logger {
static createWinstonInstance(options: Partial<LoggerOptions> = {}, transports?: winston.transport[]): Winston {
const defaultMeta: DefaultMeta = {module: options?.module || ""};

return winston.createLogger({
return createLogger({
// Do not set level at the logger level. Always control by Transport, unless for testLogger
nazarhussain marked this conversation as resolved.
Show resolved Hide resolved
level: options.level,
defaultMeta,
Expand Down
4 changes: 2 additions & 2 deletions packages/logger/test/e2e/logger/workerLoggerHandler.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import worker_threads from "node:worker_threads";
import workerThreads from "node:worker_threads";
import {spawn, Worker} from "@chainsafe/threads";

export type LoggerWorker = {
Expand All @@ -12,7 +12,7 @@ export async function getLoggerWorker(opts: WorkerData): Promise<LoggerWorker> {
const workerThreadjs = new Worker("./workerLogger.js", {
workerData: opts,
});
const worker = workerThreadjs as unknown as worker_threads.Worker;
const worker = workerThreadjs as unknown as workerThreads.Worker;

// eslint-disable-next-line @typescript-eslint/no-explicit-any
await spawn<any>(workerThreadjs, {
Expand Down
2 changes: 1 addition & 1 deletion packages/prover/test/e2e/cli/cmds/start.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import childProcess from "node:child_process";
import {writeFile, mkdir} from "node:fs/promises";
import path from "node:path";
import {describe, it, expect, beforeAll, afterAll} from "vitest";
import Web3 from "web3";
import {Web3} from "web3";
import {runCliCommand, spawnCliCommand, stopChildProcess} from "@lodestar/test-utils";
import {sleep} from "@lodestar/utils";
import {ChainConfig, chainConfigToJson} from "@lodestar/config";
Expand Down
2 changes: 1 addition & 1 deletion packages/prover/test/e2e/web3_batch_request.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/* eslint-disable @typescript-eslint/naming-convention */
import {describe, it, expect, beforeAll} from "vitest";
import Web3 from "web3";
import {Web3} from "web3";
import {LCTransport} from "../../src/interfaces.js";
import {createVerifiedExecutionProvider} from "../../src/web3_provider.js";
import {rpcUrl, beaconUrl, config, waitForCapellaFork} from "../utils/e2e_env.js";
Expand Down
2 changes: 1 addition & 1 deletion packages/prover/test/e2e/web3_provider.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/* eslint-disable @typescript-eslint/naming-convention */
import {describe, it, expect, beforeAll} from "vitest";
import Web3 from "web3";
import {Web3} from "web3";
import {ethers} from "ethers";
import {LCTransport} from "../../src/interfaces.js";
import {createVerifiedExecutionProvider} from "../../src/web3_provider.js";
Expand Down
2 changes: 1 addition & 1 deletion packages/prover/test/unit/utils/assertion.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {describe, it, expect} from "vitest";
import {ethers} from "ethers";
import Web3 from "web3";
import {Web3} from "web3";
import {isSendProvider, isWeb3jsProvider, isEthersProvider} from "../../../src/utils/assertion.js";

describe("utils/assertion", () => {
Expand Down