deps: migrate to biomejs from eslint (#7108)

* Replace eslint with biomejs

* Update the inclusion of word

* Fix the formatting

* Update the lint task to do all checks

* Update biome rules from eslint config

* Replace eslint with biomejs

* Update the inclusion of word

* Fix the formatting

* Update the lint task to do all checks

* Update biome rules from eslint config

* Fix all lint issues

* Fix formatting

* Add extension recomendation for vscode

* Enable recommended rules

* Enable rule noUselessSwitchCase

* Enable rule noUselessConstructor

* Fix the types

* Fix unit tests

* Enforce import extensions

* Update the cli command

* Enforce useConsistentMemberAccessibility

* Update rules

* Fix rules

* Upgrade biomejs to latest version

* Update the rules

* Update and format the config file

* Fix types break during merge

* Fix unused check

* Add comment for explicit-return-type

* Remove eslint file

* Add _e objects for empty catch blocks

* Update formatter config

* Fix formatting
This commit is contained in:
Nazar Hussain
2024-10-10 18:43:36 +02:00
committed by GitHub
parent 489accbc90
commit 5c359f92dc
453 changed files with 904 additions and 1861 deletions

9
.editorconfig Normal file
View File

@@ -0,0 +1,9 @@
# top-most EditorConfig file
root = true
# Unix-style newlines with a newline ending every file
[*]
end_of_line = lf
insert_final_newline = true
indent_style = space
indent_size = 2

View File

@@ -1,275 +0,0 @@
module.exports = {
root: true,
env: {
browser: true,
es6: true,
node: true,
// Performance tests still use mocha
mocha: true,
},
globals: {
BigInt: true,
},
parser: "@typescript-eslint/parser",
parserOptions: {
ecmaVersion: 10,
project: "./tsconfig.json",
sourceType: "module",
},
ignorePatterns: [
"webEsmBundle.browser.test.ts"
],
plugins: ["@typescript-eslint", "eslint-plugin-import", "@chainsafe/eslint-plugin-node", "prettier"],
extends: [
"eslint:recommended",
"plugin:@typescript-eslint/recommended",
"plugin:import/errors",
"plugin:import/typescript",
"plugin:import/warnings",
],
rules: {
"@chainsafe/node/file-extension-in-import": ["error", "always", {esm: true}],
"@chainsafe/node/no-deprecated-api": "error",
"@typescript-eslint/await-thenable": "error",
"@typescript-eslint/ban-ts-comment": "error",
"@typescript-eslint/explicit-function-return-type": ["error", {allowExpressions: true}],
"@typescript-eslint/explicit-member-accessibility": ["error", {accessibility: "no-public"}],
"@typescript-eslint/func-call-spacing": "error",
// TODO after upgrading es-lint, member-ordering is now leading to lint errors. Set to warning now and fix in another PR
"@typescript-eslint/member-ordering": "off",
"@typescript-eslint/naming-convention": [
"error",
{selector: "default", format: ["camelCase"]},
{
selector: ["classProperty", "objectLiteralProperty", "classMethod", "parameter"],
format: ["camelCase"],
leadingUnderscore: "allow",
},
//variable must be in camel or upper case
{selector: "variable", format: ["camelCase", "UPPER_CASE"], leadingUnderscore: "allow"},
//classes and types must be in PascalCase
{selector: ["typeLike", "enum"], format: ["PascalCase"]},
{selector: "enumMember", format: null},
//ignore rule for quoted stuff
{
selector: [
"classProperty",
"objectLiteralProperty",
"typeProperty",
"classMethod",
"objectLiteralMethod",
"typeMethod",
"accessor",
"enumMember",
],
format: null,
modifiers: ["requiresQuotes"],
},
//ignore rules on destructured params
{selector: "variable", modifiers: ["destructured"], format: null},
{
selector: "import",
format: ["camelCase", "PascalCase"],
},
],
"@typescript-eslint/no-explicit-any": "error",
"@typescript-eslint/no-floating-promises": "error",
"@typescript-eslint/no-non-null-assertion": "error",
"@typescript-eslint/no-require-imports": "error",
// We usually type-cast these standard types because the concerned function accepts any type
// and we want to TS detect error if original variable type changes
"@typescript-eslint/no-unnecessary-type-assertion": ["error", {typesToIgnore: ["string", "bigint", "number"]}],
"@typescript-eslint/no-unsafe-assignment": "error",
"@typescript-eslint/no-unsafe-call": "error",
"@typescript-eslint/no-unsafe-member-access": "error",
"@typescript-eslint/no-unsafe-return": "error",
"@typescript-eslint/no-unused-expressions": "error",
"@typescript-eslint/no-unused-vars": ["error", {varsIgnorePattern: "^_", argsIgnorePattern: "^_"}],
"@typescript-eslint/no-use-before-define": "off",
"@typescript-eslint/restrict-template-expressions": [
"error",
{allowNumber: true, allowBoolean: true, allowNullish: true, allowNever: true, allowRegExp: true},
],
"@typescript-eslint/return-await": "error",
"@typescript-eslint/semi": "error",
"@typescript-eslint/strict-boolean-expressions": [
"error",
{allowNullableBoolean: true, allowNullableString: true, allowAny: true},
],
"@typescript-eslint/type-annotation-spacing": "error",
"constructor-super": "off",
"func-call-spacing": "off",
// Force to add names to all functions to ease CPU profiling
"func-names": ["error", "always"],
"import/namespace": "off",
//if --fix is run it messes imports like /lib/presets/minimal & /lib/presets/mainnet
"import/no-duplicates": "off",
"import/no-extraneous-dependencies": [
"error",
{
devDependencies: false,
optionalDependencies: false,
peerDependencies: false,
},
],
"import/no-relative-packages": "error",
// TEMP Disabled while eslint-plugin-import support ESM (Typescript does support it) https://github.com/import-js/eslint-plugin-import/issues/2170
"import/no-unresolved": "off",
"import/order": [
"error",
{
groups: ["builtin", "external", "internal", "parent", "sibling", "index"],
pathGroups: [
{pattern: "@lodestar/**", group: "internal"},
// We want mocks to be imported before any internal code
{pattern: "**/mocks/**", group: "internal"},
],
pathGroupsExcludedImportTypes: ["builtin"],
},
],
//doesnt work, it reports false errors
"new-parens": "error",
"no-bitwise": "off",
"no-caller": "error",
"no-cond-assign": "error",
"no-consecutive-blank-lines": 0,
"no-console": "error",
"no-loss-of-precision": "error",
"no-prototype-builtins": 0,
"no-restricted-globals": [
"error",
{
name: "fetch",
message: "Please use 'fetch' from '@lodestar/api' instead.",
},
],
"no-restricted-imports": [
"error",
{
patterns: ["../lib/*", "@chainsafe/*/lib/*"],
paths: [
...restrictNodeModuleImports(
"child_process",
"crypto",
"fs",
"http",
"net",
"os",
"path",
"stream",
"util",
"url",
"worker_threads"
),
],
},
],
"no-restricted-syntax": ["error", ...restrictImportDestructuring("node:fs", "node:os", "node:path")],
// superseded by @typescript-eslint/return-await, must be disabled as it can report incorrect errors
"no-return-await": "off",
"no-var": "error",
"object-curly-spacing": ["error", "never"],
"object-literal-sort-keys": 0,
"prefer-const": "error",
"prettier/prettier": "error",
quotes: ["error", "double"],
semi: "off",
},
settings: {
"import/core-modules": [
"node:child_process",
"node:crypto",
"node:fs",
"node:http",
"node:net",
"node:os",
"node:path",
"node:stream",
"node:util",
"node:url",
],
"import/resolver": {
typescript: {
project: "packages/*/tsconfig.json",
},
},
},
overrides: [
{
files: [
"**/*.config.js",
"**/*.config.mjs",
"**/*.config.cjs",
"**/*.config.ts",
"scripts/vitest/**/*.ts",
"scripts/vite/**/*.ts",
],
rules: {
"@typescript-eslint/naming-convention": "off",
// Allow require in CJS modules
"@typescript-eslint/no-require-imports": "off",
// Allow require in CJS modules
"@typescript-eslint/no-var-requires": "off",
// Allow importing packages from dev dependencies
"import/no-extraneous-dependencies": "off",
// Allow importing and mixing different configurations
"import/no-relative-packages": "off",
},
},
{
files: ["**/test/**/*.ts"],
rules: {
"@typescript-eslint/no-explicit-any": "off",
"func-names": "off",
"import/no-extraneous-dependencies": "off",
// Turned off as it floods log with warnings. Underlying issue is not critical so switching off is acceptable
"import/no-named-as-default-member": "off",
},
},
{
files: ["**/perf/**/*.ts"],
rules: {
// A lot of benchmarks just need to execute expressions without using the result
"@typescript-eslint/no-unused-expressions": "off",
},
},
{
files: ["**/test/**/*.test.ts"],
plugins: ["vitest"],
extends: ["plugin:vitest/recommended"],
rules: {
"vitest/consistent-test-it": ["error", {fn: "it", withinDescribe: "it"}],
// We use a lot dynamic assertions so tests may not have usage of expect
"vitest/expect-expect": "off",
"vitest/no-disabled-tests": "warn",
"vitest/no-focused-tests": "error",
"vitest/prefer-called-with": "error",
"vitest/prefer-spy-on": "error",
// Our usage contains dynamic test title, this rule enforce static string value
"vitest/valid-title": "off",
},
},
{
files: ["**/types/**/*.ts"],
rules: {
"@typescript-eslint/naming-convention": [
"off",
{selector: "interface", prefix: ["I"]},
{selector: "interface", format: ["PascalCase"], prefix: ["I"]},
],
},
},
],
};
function restrictNodeModuleImports(...modules) {
return modules.map((module) => ({name: module, message: `Please use 'node:${module}' instead.`}));
}
function restrictImportDestructuring(...modules) {
return modules.map((module) => ({
selector: `ImportDeclaration[source.value='${module}'] ImportSpecifier`,
message: `Importing from '${module}' using destructuring is restricted.`,
}));
}

View File

@@ -64,9 +64,6 @@ jobs:
- name: Assert ESM module exports
run: node scripts/assert_exports.mjs
- name: Assert eslintrc rules sorted
run: scripts/assert_eslintrc_sorted.mjs
type-checks:
name: Type Checks
needs: build

5
.vscode/extensions.json vendored Normal file
View File

@@ -0,0 +1,5 @@
{
"recommendations": [
"biomejs.biome"
]
}

View File

@@ -26,7 +26,6 @@ EIPs
EL
ENR
ENRs
ESLint
ETH
Edgington
Erigon

View File

@@ -31,7 +31,7 @@ To run tests:
- :test_tube: Run `yarn test:spec` for spec tests.
- :test_tube: Run `yarn test` to run all tests.
- :test_tube: Run `yarn check-types` to check TypeScript types.
- :test_tube: Run `yarn lint` to run the linter (ESLint).
- :test_tube: Run `yarn lint` to run the linter.
Note that to run `test:e2e`, first ensure that the environment is correctly setup by running the `run_e2e_env.sh` script. This script requires a running docker engine.

376
biome.jsonc Normal file
View File

@@ -0,0 +1,376 @@
{
"$schema": "https://biomejs.dev/schemas/1.9.3/schema.json",
"vcs": {
"clientKind": "git",
"enabled": true,
"useIgnoreFile": true
},
"files": {
"include": ["packages/*/src/**/*.ts", "packages/*/test/**/*.ts"]
},
"formatter": {
"enabled": true,
"formatWithErrors": true,
"useEditorconfig": true,
"lineWidth": 120,
"attributePosition": "auto",
"bracketSpacing": false,
"ignore": ["**/lib", "**/.nyc_output", "./packages/*/spec-tests", "**/node_modules", "./packages/*/node_modules/**"]
},
"organizeImports": {
"enabled": false
},
"linter": {
"enabled": true,
"rules": {
"recommended": true,
"complexity": {
"noForEach": "off",
"noStaticOnlyClass": "off",
"noThisInStatic": "off",
"noUselessEmptyExport": "off",
"noUselessTypeConstraint": "error",
"useArrowFunction": "off",
"useFlatMap": "off",
"useLiteralKeys": "off",
"useOptionalChain": "off",
"useRegexLiterals": "off",
"noBannedTypes": "error",
"noUselessThisAlias": "error"
},
"correctness": {
"noInvalidConstructorSuper": "off",
"noInvalidUseBeforeDeclaration": "off",
"noPrecisionLoss": "error",
"noUnusedVariables": "error",
"noVoidTypeReturn": "off",
"useYield": "off",
"useImportExtensions": {
"level": "error",
"options": {
"suggestedExtensions": {
"ts": {
"module": "js",
"component": "jsx"
}
}
}
},
"useArrayLiterals": "error",
"noUndeclaredDependencies": "off", // TODO: Need to see why this rule is not detecting monorepo packages
"noUndeclaredVariables": "error"
},
"performance": {
"noAccumulatingSpread": "off",
"noDelete": "off"
},
"style": {
"noCommaOperator": "off",
"noInferrableTypes": "off",
"noNonNullAssertion": "error",
"noParameterAssign": "off",
"noRestrictedGlobals": {
"level": "error",
"options": {
"deniedGlobals": ["fetch"]
}
},
"noUnusedTemplateLiteral": "off",
"noUselessElse": "off",
"noVar": "error",
"useConst": "error",
"useEnumInitializers": "off",
"useExponentiationOperator": "off",
"useExportType": "off",
"useImportType": "off",
"useLiteralEnumMembers": "off",
"useNamingConvention": {
"level": "error",
"options": {
"strictCase": false,
"conventions": [
{
"selector": {
"kind": "any"
},
"formats": ["camelCase"]
},
{
"selector": {
"kind": "classProperty"
},
"formats": ["camelCase"]
},
{
"selector": {
"kind": "objectLiteralProperty"
},
"formats": ["camelCase"]
},
{
"selector": {
"kind": "classMethod"
},
"formats": ["camelCase"]
},
{
"selector": {
"kind": "functionParameter"
},
"formats": ["camelCase"]
},
{
"selector": {
"kind": "variable"
},
"formats": ["camelCase", "CONSTANT_CASE"]
},
{
"selector": {
"kind": "typeLike"
},
"formats": ["PascalCase"]
},
{
"selector": {
"kind": "enum"
},
"formats": ["PascalCase"]
},
{
"selector": {
"kind": "enumMember"
},
"formats": ["PascalCase", "camelCase", "CONSTANT_CASE"]
},
{
"selector": {
"kind": "classProperty"
},
"formats": ["PascalCase", "camelCase", "CONSTANT_CASE"]
},
{
"selector": {
"kind": "typeProperty"
},
"formats": ["PascalCase", "camelCase", "CONSTANT_CASE"]
},
{
"selector": {
"kind": "classMember"
},
"formats": ["PascalCase", "camelCase", "CONSTANT_CASE"]
},
{
"selector": {
"kind": "objectLiteralMethod"
},
"formats": ["PascalCase", "camelCase", "CONSTANT_CASE"]
},
{
"selector": {
"kind": "typeMethod"
},
"formats": ["PascalCase", "camelCase", "CONSTANT_CASE"]
},
{
"selector": {
"kind": "variable"
},
"formats": ["PascalCase", "camelCase", "CONSTANT_CASE"]
},
{
"selector": {
"kind": "importAlias"
},
"formats": ["PascalCase", "camelCase"]
},
{
"selector": {
"kind": "importNamespace"
},
"formats": ["PascalCase", "camelCase"]
}
]
}
},
"useNumberNamespace": "off",
"useSingleVarDeclarator": "off",
"useTemplate": "off",
"noNamespace": "error",
"useAsConstAssertion": "error"
},
"suspicious": {
"noAssignInExpressions": "error",
"noAsyncPromiseExecutor": "off",
"noConfusingVoidType": "off",
"noConsoleLog": "error",
"noDoubleEquals": "off",
"noDuplicateTestHooks": "off",
"noExplicitAny": "error",
"noExportsInTest": "off",
"noFallthroughSwitchClause": "off",
"noGlobalIsFinite": "off",
"noGlobalIsNan": "off",
"noImplicitAnyLet": "off",
"noPrototypeBuiltins": "off",
"noRedundantUseStrict": "off",
"noShadowRestrictedNames": "off",
"useDefaultSwitchClauseLast": "off",
"useGetterReturn": "off",
"noExtraNonNullAssertion": "error",
"noMisleadingInstantiator": "error",
"noUnsafeDeclarationMerging": "error",
"noEmptyBlockStatements": "off" // There is a lot of empty code blocks, should be enabled and clean up separately.
},
"nursery": {
"useConsistentMemberAccessibility": {
"level": "error",
"options": {
"accessibility": "noPublic"
}
},
"noCommonJs": "error",
"noRestrictedImports": {
"level": "error",
"options": {
"paths": {
"child_process": "Please use node:child_process instead.",
"crypto": "Please use node:crypto instead.",
"fs": "Please use node:fs instead.",
"http": "Please use node:https instead.",
"net": "Please use node:net instead.",
"os": "Please use node:os instead.",
"path": "Please use node:path instead.",
"stream": "Please use node:stream instead.",
"util": "Please use node:util instead.",
"url": "Please use node:url instead.",
"worker_threads": "Please use node:worker_threads instead."
}
}
},
"noDuplicateElseIf": "error",
"noUselessEscapeInRegex": "error",
"noIrregularWhitespace": "error",
"noOctalEscape": "error",
// Need to enable this rule with exception to anonymous functions
"useExplicitFunctionReturnType": "off"
}
}
},
"javascript": {
"formatter": {
"jsxQuoteStyle": "double",
"quoteProperties": "asNeeded",
"trailingCommas": "es5",
"semicolons": "always",
"arrowParentheses": "always",
"bracketSpacing": false,
"bracketSameLine": false,
"quoteStyle": "double",
"attributePosition": "auto",
"enabled": true
},
"linter": {
"enabled": true
},
"globals": ["BigInt"]
},
"overrides": [
{
"include": ["packages/**/test/perf/**/*.test.ts", "packages/state-transition/test/utils/beforeValueMocha.ts"],
"javascript": {
// These are used by mocha
"globals": ["describe", "it", "before", "after"]
}
},
{
"include": ["packages/cli/src/", "packages/test-utils/src", "packages/flare/src"],
"linter": {
"rules": {
"suspicious": {
"noConsoleLog": "off"
}
}
}
},
{
"include": [
"**/*.config.js",
"**/*.config.mjs",
"**/*.config.cjs",
"**/*.config.ts",
"scripts/vitest/**/*.ts",
"scripts/vite/**/*.ts",
"**/types/**/*.ts",
"packages/api/src/beacon/routes/*.ts",
"packages/api/src/**/routes.ts",
"packages/api/src/utils/server/handler.ts",
"packages/api/test/unit/client/urlFormat.test.ts",
"packages/beacon-node/src/api/impl/config/constants.ts",
"packages/beacon-node/src/eth1/provider/eth1Provider.ts",
""
],
"linter": {
"rules": {
"style": {
"useNamingConvention": {
"level": "off",
"options": {
"strictCase": false
}
}
}
}
}
},
{
"include": [
"**/test/**/*.ts",
"packages/*/test/**/*.js",
"packages/api/src/utils/**/*.ts",
"packages/beacon-node/src/db/repositories/checkpointState.ts",
"packages/spec-test-util/src/single.ts"
],
"linter": {
"rules": {
"suspicious": {
"noExplicitAny": "off"
}
}
}
},
{
"include": ["packages/beacon-node/test/e2e/eth1/jsonRpcHttpClient.test.ts"],
"linter": {
"rules": {
"correctness": {
"noUnusedVariables": "off"
}
}
}
},
{
"include": ["**/test/**/*.ts", "packages/*/test/**/*.js"],
"linter": {
"rules": {
"suspicious": {
"noConsoleLog": "off"
}
}
}
},
{
"include": ["**/perf/**/*.ts"],
"linter": {
"rules": {}
}
},
{
"include": ["**/test/**/*.test.ts"],
"linter": {
"rules": {}
}
}
]
}

View File

@@ -15,8 +15,8 @@
"build:bundle": "lerna run build:bundle",
"build:watch": "lerna exec --parallel -- 'yarn run build:watch'",
"build:ifchanged": "lerna exec -- ../../scripts/build_if_changed.sh",
"lint": "eslint --report-unused-disable-directives --color --ext .ts packages/*/src packages/*/test",
"lint:fix": "yarn lint --fix",
"lint": "biome check",
"lint:fix": "yarn lint --write",
"lint-dashboards": "node scripts/lint-grafana-dashboards.mjs ./dashboards",
"check-build": "lerna run check-build",
"check-bundle": "lerna run check-bundle",
@@ -48,22 +48,15 @@
},
"devDependencies": {
"@actions/core": "^1.10.1",
"@chainsafe/eslint-plugin-node": "^11.2.3",
"@dapplion/benchmark": "^0.2.4",
"@biomejs/biome": "^1.9.3",
"@types/mocha": "^10.0.6",
"@types/node": "^20.12.8",
"@typescript-eslint/eslint-plugin": "^7.2.0",
"@typescript-eslint/parser": "^7.2.0",
"@vitest/browser": "^2.0.4",
"@vitest/coverage-v8": "^2.0.4",
"crypto-browserify": "^3.12.0",
"dotenv": "^16.4.5",
"electron": "^26.2.2",
"eslint": "^8.57.0",
"eslint-import-resolver-typescript": "^3.6.1",
"eslint-plugin-import": "^2.29.1",
"eslint-plugin-prettier": "^5.1.3",
"eslint-plugin-vitest": "^0.3.26",
"https-browserify": "^1.0.0",
"jsdom": "^23.0.1",
"lerna": "^7.3.0",

View File

@@ -63,8 +63,8 @@
"build:release": "yarn clean && yarn run build",
"check-build": "node -e \"(async function() { await import('./lib/index.js') })()\"",
"check-types": "tsc",
"lint": "eslint --color --ext .ts src/ test/",
"lint:fix": "yarn run lint --fix",
"lint": "biome check src/ test/",
"lint:fix": "yarn run lint --write",
"test": "yarn test:unit",
"test:unit": "vitest --run --dir test/unit/",
"check-readme": "typescript-docs-verifier"

View File

@@ -16,10 +16,15 @@ export function getClient(config: ChainForkConfig, baseUrl: string): ApiClient {
const eventSerdes = getEventSerdes(config);
return {
eventstream: async ({topics, signal, onEvent, onError, onClose}) => {
eventstream: async ({
topics,
signal,
onEvent,
onError,
onClose,
}): Promise<ApiResponse<Endpoints["eventstream"]>> => {
const query = stringifyQuery({topics});
const url = `${urlJoin(baseUrl, definitions.eventstream.url)}?${query}`;
// eslint-disable-next-line @typescript-eslint/naming-convention
const EventSource = await getEventSource();
const eventSource = new EventSource(url);
@@ -40,7 +45,7 @@ export function getClient(config: ChainForkConfig, baseUrl: string): ApiClient {
// EventSource will try to reconnect always on all errors
// `eventSource.onerror` events are informative but don't indicate the EventSource closed
// The only way to abort the connection from the client is via eventSource.close()
eventSource.onerror = function onerror(err) {
eventSource.onerror = function onerror(err): void {
const errEs = err as unknown as EventSourceError;
// Ignore noisy errors due to beacon node being offline

View File

@@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/naming-convention */
import {ContainerType, ListCompositeType, ValueOf} from "@chainsafe/ssz";
import {ChainForkConfig} from "@lodestar/config";
import {
@@ -225,7 +224,7 @@ export type Endpoints = {
>;
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
const blockIdOnlyReq: RequestCodec<Endpoint<"GET", {blockId: BlockId}, {params: {block_id: string}}, any, any>> = {
writeReq: ({blockId}) => ({params: {block_id: blockId.toString()}}),
parseReq: ({params}) => ({blockId: params.block_id}),

View File

@@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/naming-convention */
import {ValueOf} from "@chainsafe/ssz";
import {ChainForkConfig} from "@lodestar/config";
import {isForkPostElectra} from "@lodestar/params";

View File

@@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/naming-convention */
import {ContainerType, ValueOf} from "@chainsafe/ssz";
import {ChainForkConfig} from "@lodestar/config";
import {Epoch, ssz} from "@lodestar/types";

View File

@@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/naming-convention */
import {ContainerType, ValueOf} from "@chainsafe/ssz";
import {ChainForkConfig} from "@lodestar/config";
import {MAX_VALIDATORS_PER_COMMITTEE} from "@lodestar/params";
@@ -269,7 +268,7 @@ export type Endpoints = {
>;
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
const stateIdOnlyReq: RequestCodec<Endpoint<"GET", {stateId: StateId}, {params: {state_id: string}}, any, any>> = {
writeReq: ({stateId}) => ({params: {state_id: stateId.toString()}}),
parseReq: ({params}) => ({stateId: params.state_id}),

View File

@@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/naming-convention */
import {ContainerType, ValueOf} from "@chainsafe/ssz";
import {ChainForkConfig} from "@lodestar/config";
import {ssz} from "@lodestar/types";

View File

@@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/naming-convention */
import {ContainerType, Type, ValueOf} from "@chainsafe/ssz";
import {ChainForkConfig} from "@lodestar/config";
import {ssz, StringType, BeaconState} from "@lodestar/types";

View File

@@ -188,7 +188,6 @@ export type TypeJson<T> = {
};
export function getTypeByEvent(config: ChainForkConfig): {[K in EventType]: TypeJson<EventData[K]>} {
// eslint-disable-next-line @typescript-eslint/naming-convention
const WithVersion = <T>(getType: (fork: ForkName) => TypeJson<T>): TypeJson<{data: T; version: ForkName}> => {
return {
toJson: ({data, version}) => ({
@@ -289,7 +288,6 @@ export function getTypeByEvent(config: ChainForkConfig): {[K in EventType]: Type
};
}
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
export function getEventSerdes(config: ChainForkConfig) {
const typeByEvent = getTypeByEvent(config);

View File

@@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/naming-convention */
import {ListCompositeType, ValueOf} from "@chainsafe/ssz";
import {
LightClientBootstrap,

View File

@@ -21,7 +21,7 @@ export type SyncChainDebugState = {
status: string;
startEpoch: number;
peers: number;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
batches: any[];
};

View File

@@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/naming-convention */
import {ContainerType, ValueOf} from "@chainsafe/ssz";
import {ChainForkConfig} from "@lodestar/config";
import {ssz, stringType} from "@lodestar/types";

View File

@@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/naming-convention */
import {CompactMultiProof, ProofType} from "@chainsafe/persistent-merkle-tree";
import {ByteListType, ContainerType} from "@chainsafe/ssz";
import {fromHex, toHex} from "@lodestar/utils";

View File

@@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/naming-convention */
import {ContainerType, Type, ValueOf} from "@chainsafe/ssz";
import {ChainForkConfig} from "@lodestar/config";
import {isForkBlobs, isForkPostElectra} from "@lodestar/params";

View File

@@ -25,7 +25,7 @@ export function registerRoutes(
// Enforces that we are declaring routes for every routeId in `Endpoints`
[K in keyof Endpoints]: () => {
// The Endpoints are enforced in each getRoutes return type
// eslint-disable-next-line @typescript-eslint/no-explicit-any
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
[K2 in keyof Endpoints[K]]: FastifyRoute<any>;
};
} = {

View File

@@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/naming-convention */
import {
ssz,
bellatrix,

View File

@@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/naming-convention */
import {ContainerType, ValueOf} from "@chainsafe/ssz";
import {ChainForkConfig} from "@lodestar/config";
import {Epoch, phase0, ssz, stringType} from "@lodestar/types";

View File

@@ -1,6 +1,5 @@
// This function switches between the native web implementation and a nodejs implemnetation
export async function getEventSource(): Promise<typeof EventSource> {
// eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
if (globalThis.EventSource) {
return EventSource;
} else {

View File

@@ -6,7 +6,7 @@
async function wrappedFetch(url: string | URL, init?: RequestInit): Promise<Response> {
try {
// This function wraps global `fetch` which should only be directly called here
// eslint-disable-next-line no-restricted-globals
// biome-ignore lint/style/noRestrictedGlobals: <explanation>
return await fetch(url, init);
} catch (e) {
throw new FetchError(url, e);

View File

@@ -198,8 +198,7 @@ export class HttpClient implements IHttpClient {
this.logger?.debug("Requesting fallback URL", {routeId, baseUrl: printableUrl, score: this.urlsScore[i]});
}
// eslint-disable-next-line @typescript-eslint/naming-convention
const i_ = i; // Keep local copy of i variable to index urlScore after requestMethod() resolves
const i_ = i; // Keep local copy of i variable to index urlScore after requestWithBody() resolves
const urlInit = this.urlsInits[i];
if (urlInit === undefined) {

View File

@@ -26,13 +26,15 @@ export class ApiResponse<E extends Endpoint> extends Response {
wireFormat(): WireFormat | null {
if (this._wireFormat === undefined) {
if (this.definition.resp.isEmpty) {
return (this._wireFormat = null);
this._wireFormat = null;
return this._wireFormat;
}
const contentType = this.headers.get(HttpHeader.ContentType);
if (contentType === null) {
if (this.status === HttpStatusCode.NO_CONTENT) {
return (this._wireFormat = null);
this._wireFormat = null;
return this._wireFormat;
} else {
throw Error("Content-Type header is required in response");
}
@@ -198,7 +200,7 @@ export class ApiResponse<E extends Endpoint> extends Response {
} else {
return errBody;
}
} catch (e) {
} catch (_e) {
return errBody || this.statusText;
}
}

View File

@@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/naming-convention */
import {ArrayType, ListBasicType, ListCompositeType, Type, isBasicType, isCompositeType} from "@chainsafe/ssz";
import {ForkName} from "@lodestar/params";
import {objectToExpectedCase} from "@lodestar/utils";
@@ -20,11 +19,8 @@ export type EmptyRequest = Record<never, never>;
export type EmptyResponseData = void;
export type EmptyMeta = void;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type AnyEndpoint = Endpoint<any, any, any, any, any>;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type EmptyRequestEndpoint = Endpoint<any, EmptyArgs, EmptyRequest, any, any>;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type EmptyResponseEndpoint = Endpoint<any, any, any, EmptyResponseData, EmptyMeta>;
/** Shortcut for routes that have no params, query */

View File

@@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/naming-convention */
import {ContainerType, ValueOf} from "@chainsafe/ssz";
import {ForkName} from "@lodestar/params";
import {StringType, ssz, stringType} from "@lodestar/types";

View File

@@ -104,7 +104,7 @@ export function fromGraffitiHex(hex?: string): string | undefined {
}
try {
return new TextDecoder("utf8").decode(fromHex(hex));
} catch {
} catch (_e) {
// allow malformed graffiti hex string
return hex;
}

View File

@@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/naming-convention */
import type * as fastify from "fastify";
import {HttpHeader, MediaType, SUPPORTED_MEDIA_TYPES, parseAcceptHeader, parseContentTypeHeader} from "../headers.js";
import {

View File

@@ -12,10 +12,9 @@ type ApplicationResponseObject<E extends Endpoint> = {
: {data: E["return"] | (E["return"] extends undefined ? undefined : Uint8Array)}) &
(E["meta"] extends EmptyMeta ? {meta?: never} : {meta: E["meta"]});
export type ApplicationResponse<E extends Endpoint> =
HasOnlyOptionalProps<ApplicationResponseObject<E>> extends true
? ApplicationResponseObject<E> | void
: ApplicationResponseObject<E>;
export type ApplicationResponse<E extends Endpoint> = HasOnlyOptionalProps<ApplicationResponseObject<E>> extends true
? ApplicationResponseObject<E> | void
: ApplicationResponseObject<E>;
export type ApiContext = {
/**

View File

@@ -1,7 +1,5 @@
import {compileRouteUrlFormatter} from "../../src/utils/urlFormat.js";
/* eslint-disable no-console */
describe("route parse", () => {
it.skip("Benchmark compileRouteUrlFormatter", () => {
const path = "/eth/v1/validator/:name/attester/:epoch";

View File

@@ -8,7 +8,6 @@ import {testData} from "../testData/beacon.js";
describe("beacon / beacon", () => {
runGenericServerTest<Endpoints>(
// eslint-disable-next-line @typescript-eslint/naming-convention
createChainForkConfig({...defaultChainConfig, ALTAIR_FORK_EPOCH: 1, BELLATRIX_FORK_EPOCH: 2}),
getClient,
getRoutes,

View File

@@ -6,8 +6,6 @@ import {getRoutes} from "../../../../src/beacon/server/config.js";
import {runGenericServerTest} from "../../../utils/genericServerTest.js";
import {testData} from "../testData/config.js";
/* eslint-disable @typescript-eslint/naming-convention */
describe("beacon / config", () => {
runGenericServerTest<Endpoints>(config, getClient, getRoutes, testData);

View File

@@ -18,7 +18,6 @@ import {testData as validatorTestData} from "./testData/validator.js";
// Global variable __dirname no longer available in ES6 modules.
// Solutions: https://stackoverflow.com/questions/46745014/alternative-for-dirname-in-node-js-when-using-es6-modules
// eslint-disable-next-line @typescript-eslint/naming-convention
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const version = "v3.0.0-alpha.6";
@@ -28,7 +27,6 @@ const openApiFile: OpenApiFile = {
version: RegExp(version),
};
// eslint-disable-next-line @typescript-eslint/naming-convention
const config = createChainForkConfig({...defaultChainConfig, ALTAIR_FORK_EPOCH: 1, BELLATRIX_FORK_EPOCH: 2});
const definitions = {

View File

@@ -5,8 +5,6 @@ import {GenericServerTestCases} from "../../../utils/genericServerTest.js";
const abortController = new AbortController();
/* eslint-disable @typescript-eslint/naming-convention */
export const testData: GenericServerTestCases<Endpoints> = {
eventstream: {
args: {topics: [EventType.head, EventType.chainReorg], signal: abortController.signal, onEvent: () => {}},

View File

@@ -10,7 +10,6 @@ describe("builder", () => {
runGenericServerTest<Endpoints>(
createChainForkConfig({
...defaultChainConfig,
/* eslint-disable @typescript-eslint/naming-convention */
ALTAIR_FORK_EPOCH: 0,
BELLATRIX_FORK_EPOCH: 0,
DENEB_FORK_EPOCH: 0,

View File

@@ -10,7 +10,6 @@ import {testData} from "./testData.js";
// Global variable __dirname no longer available in ES6 modules.
// Solutions: https://stackoverflow.com/questions/46745014/alternative-for-dirname-in-node-js-when-using-es6-modules
// eslint-disable-next-line @typescript-eslint/naming-convention
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const version = "v0.2.0";
@@ -23,7 +22,6 @@ const openApiFile: OpenApiFile = {
};
const definitions = getDefinitions(
// eslint-disable-next-line @typescript-eslint/naming-convention
createChainForkConfig({...defaultChainConfig, ALTAIR_FORK_EPOCH: 0, BELLATRIX_FORK_EPOCH: 0})
);

View File

@@ -92,7 +92,6 @@ describe("FetchError", function () {
const afterHook = afterHooks.pop();
if (afterHook)
await afterHook().catch((e: Error) => {
// eslint-disable-next-line no-console
console.error("Error in afterEach hook", e);
});
}

View File

@@ -81,7 +81,6 @@ describe("httpClient fallback", () => {
fetchStub.mockClear();
// eslint-disable-next-line no-console
if (DEBUG_LOGS) console.log("completed assertions step", step);
}

View File

@@ -7,8 +7,6 @@ import {
urlToTokens,
} from "../../../src/utils/urlFormat.js";
/* eslint-disable @typescript-eslint/naming-convention */
describe("utils / urlFormat", () => {
const testCases: {
urlTemplate: string;

View File

@@ -9,7 +9,6 @@ import {testData} from "./testData.js";
// Global variable __dirname no longer available in ES6 modules.
// Solutions: https://stackoverflow.com/questions/46745014/alternative-for-dirname-in-node-js-when-using-es6-modules
// eslint-disable-next-line @typescript-eslint/naming-convention
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const version = "v1.1.0";

View File

@@ -127,7 +127,7 @@ export function runTestCheckAgainstSpec<Es extends Record<string, Endpoint>>(
expect(reqSsz.body).toBeInstanceOf(Uint8Array);
expect(reqCodec.onlySupport).not.toBe(WireFormat.json);
} catch {
} catch (_e) {
throw Error("Must support ssz request body");
}
}
@@ -167,7 +167,7 @@ export function runTestCheckAgainstSpec<Es extends Record<string, Endpoint>>(
expect(sszBytes).toBeInstanceOf(Uint8Array);
expect(routeDef.resp.onlySupport).not.toBe(WireFormat.json);
} catch {
} catch (_e) {
throw Error("Must support ssz response body");
}
}
@@ -183,7 +183,6 @@ function validateSchema(schema: Parameters<typeof ajv.compile>[0], json: unknown
try {
validate = ajv.compile(schema);
} catch (e) {
// eslint-disable-next-line no-console
console.error(JSON.stringify(schema, null, 2));
(e as Error).message = `${id} schema - ${(e as Error).message}`;
throw e;

View File

@@ -105,7 +105,6 @@ export function parseOpenApiSpec(openApiJson: OpenApiJson): Map<OperationId, Rou
try {
preprocessSchema(responseOkSchema);
} catch (e) {
// eslint-disable-next-line no-console
console.log(responseOkSchema);
throw e;
}

View File

@@ -14,7 +14,6 @@ export function getTestServer(): {server: FastifyInstance; start: () => Promise<
addSszContentTypeParser(server);
server.addHook("onError", (_request, _reply, error, done) => {
// eslint-disable-next-line no-console
console.log(`onError: ${error.toString()}`);
done();
});

View File

@@ -75,8 +75,8 @@
"build:release": "yarn clean && yarn run build",
"check-build": "node -e \"(async function() { await import('./lib/index.js') })()\"",
"check-types": "tsc",
"lint": "eslint --color --ext .ts src/ test/",
"lint:fix": "yarn run lint --fix",
"lint": "biome check src/ test/",
"lint:fix": "yarn run lint --write",
"test": "yarn test:unit && yarn test:e2e",
"test:unit:minimal": "LODESTAR_PRESET=minimal vitest --run --dir test/unit/",
"test:unit:mainnet": "LODESTAR_PRESET=mainnet vitest --run --dir test/unit-mainnet",

View File

@@ -224,15 +224,17 @@ export function getBeaconBlockApi({
() => network.publishBeaconBlock(signedBlock) as Promise<unknown>,
() =>
// there is no rush to persist block since we published it to gossip anyway
chain.processBlock(blockForImport, {...opts, eagerPersistBlock: false}).catch((e) => {
if (e instanceof BlockError && e.type.code === BlockErrorCode.PARENT_UNKNOWN) {
network.events.emit(NetworkEvent.unknownBlockParent, {
blockInput: blockForImport,
peer: IDENTITY_PEER_ID,
});
}
throw e;
}),
chain
.processBlock(blockForImport, {...opts, eagerPersistBlock: false})
.catch((e) => {
if (e instanceof BlockError && e.type.code === BlockErrorCode.PARENT_UNKNOWN) {
network.events.emit(NetworkEvent.unknownBlockParent, {
blockInput: blockForImport,
peer: IDENTITY_PEER_ID,
});
}
throw e;
}),
];
await promiseAllMaybeAsync(publishPromises);
};
@@ -258,7 +260,7 @@ export function getBeaconBlockApi({
chain.logger.debug("Reconstructing signedBlockOrContents", {slot, blockRoot, source});
const contents = executionPayload
? chain.producedContentsCache.get(toRootHex(executionPayload.blockHash)) ?? null
? (chain.producedContentsCache.get(toRootHex(executionPayload.blockHash)) ?? null)
: null;
const signedBlockOrContents = reconstructFullBlockOrContents(signedBlindedBlock, {executionPayload, contents});

View File

@@ -94,7 +94,6 @@ export function getBeaconPoolApi({
signedAttestations.map(async (attestation, i) => {
try {
const fork = chain.config.getForkName(chain.clock.currentSlot);
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
const validateFn = () => validateApiAttestation(fork, chain, {attestation, serializedData: null});
const {slot, beaconBlockRoot} = attestation.data;
// when a validator is configured with multiple beacon node urls, this attestation data may come from another beacon node

View File

@@ -134,7 +134,7 @@ export function getStateValidatorIndex(
if (id.startsWith("0x")) {
try {
id = fromHex(id);
} catch (e) {
} catch (_e) {
return {valid: false, code: 400, reason: "Invalid pubkey hex encoding"};
}
} else {

View File

@@ -41,8 +41,6 @@ import {
FULL_EXIT_REQUEST_AMOUNT,
} from "@lodestar/params";
/* eslint-disable @typescript-eslint/naming-convention */
/**
* Hand-picked list of constants declared in consensus-spec .md files.
* This list is asserted to be up-to-date with the test `test/e2e/api/impl/config.test.ts`

View File

@@ -10,11 +10,10 @@ export function getEventsApi({
const onAbortFns: (() => void)[] = [];
for (const topic of topics) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
const handler = (data: any): void => {
// TODO: What happens if this handler throws? Does it break the other chain.emitter listeners?
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
onEvent({type: topic, message: data});
};

View File

@@ -44,6 +44,7 @@ function getPeerState(status: StreamStatus): routes.node.PeerState {
case "closing":
return "disconnecting";
case "closed":
return "disconnected";
default:
return "disconnected";
}

View File

@@ -1147,7 +1147,6 @@ export function getValidatorApi(
signedAggregateAndProofs.map(async (signedAggregateAndProof, i) => {
try {
// TODO: Validate in batch
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
const validateFn = () => validateApiAggregateAndProof(fork, chain, signedAggregateAndProof);
const {slot, beaconBlockRoot} = signedAggregateAndProof.message.aggregate.data;
// when a validator is configured with multiple beacon node urls, this attestation may come from another beacon node

View File

@@ -93,7 +93,7 @@ export class HttpActiveSocketsTracker {
await waitFor(() => this.sockets.size === 0, {
timeout: GRACEFUL_TERMINATION_TIMEOUT,
});
} catch {
} catch (_e) {
// Ignore timeout error
} finally {
for (const socket of this.sockets) {

View File

@@ -41,15 +41,13 @@ async function getAsset(name: string): Promise<Buffer | undefined> {
const path = await import("node:path");
const fs = await import("node:fs/promises");
const url = await import("node:url");
// eslint-disable-next-line @typescript-eslint/naming-convention
const __dirname = path.dirname(url.fileURLToPath(import.meta.url));
return await fs.readFile(path.join(__dirname, "../../../../../assets/", name));
} catch (e) {
} catch (_e) {
return undefined;
}
}
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
export async function getFavicon() {
const content = await getAsset("round-icon.ico");
if (!content) {
@@ -67,7 +65,6 @@ export async function getFavicon() {
];
}
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
export async function getLogo() {
const content = await getAsset("lodestar_icon_text_white.png");
if (!content) {

View File

@@ -83,7 +83,6 @@ async function maybeValidateBlobs(
return {dataAvailabilityStatus: DataAvailabilityStatus.Available, availableBlockInput: blockInput};
}
// eslint-disable-next-line no-fallthrough
case BlockInputType.dataPromise: {
// run full validation
const {block} = blockInput;
@@ -136,7 +135,7 @@ async function raceWithCutoff<T>(
try {
await Promise.race([availabilityPromise, cutoffTimeout]);
} catch (e) {
} catch (_e) {
// throw unavailable so that the unknownblock/blobs can be triggered to pull the block
throw new BlockError(block, {code: BlockErrorCode.DATA_UNAVAILABLE});
}

View File

@@ -3,9 +3,8 @@ import path from "node:path";
import {spawn, Worker} from "@chainsafe/threads";
// `threads` library creates self global variable which breaks `timeout-abort-controller` https://github.com/jacobheun/timeout-abort-controller/issues/9
// Don't add an eslint disable here as a reminder that this has to be fixed eventually
// eslint-disable-next-line
// @ts-ignore
// eslint-disable-next-line
// biome-ignore lint/suspicious/noGlobalAssign: <explanation>
self = undefined;
import {PublicKey} from "@chainsafe/blst";
import {Logger} from "@lodestar/utils";

View File

@@ -6,7 +6,7 @@ try {
} else {
defaultPoolSize = (await import("node:os")).availableParallelism();
}
} catch (e) {
} catch (_e) {
defaultPoolSize = 8;
}

View File

@@ -75,7 +75,7 @@ function verifyManySignatureSets(workReqArr: BlsWorkReq[]): BlsWorkResult {
// Re-verify all sigs
nonBatchableSets.push(...batchableChunk);
}
} catch (e) {
} catch (_e) {
// TODO: Ignore this error expecting that the same error will happen when re-verifying the set individually
// It's not ideal but '@chainsafe/blst' may throw errors on some conditions
batchRetries++;

View File

@@ -1,4 +1,4 @@
import {EventEmitter} from "events";
import {EventEmitter} from "node:events";
import {StrictEventEmitter} from "strict-event-emitter-types";
import {routes} from "@lodestar/api";

View File

@@ -132,7 +132,7 @@ export async function initStateFromEth1({
* Restore the latest beacon state from db
*/
export async function initStateFromDb(
config: ChainForkConfig,
_config: ChainForkConfig,
db: IBeaconDb,
logger: Logger
): Promise<BeaconStateAllForks> {

View File

@@ -5,7 +5,8 @@ import {BlobsBundle} from "../../execution/index.js";
* Optionally sanity-check that the KZG commitments match the versioned hashes in the transactions
* https://github.com/ethereum/consensus-specs/blob/11a037fd9227e29ee809c9397b09f8cc3383a8c0/specs/eip4844/validator.md#blob-kzg-commitments
*/
export function validateBlobsAndKzgCommitments(payload: ExecutionPayload, blobsBundle: BlobsBundle): void {
export function validateBlobsAndKzgCommitments(_payload: ExecutionPayload, blobsBundle: BlobsBundle): void {
// sanity-check that the KZG commitments match the blobs (as produced by the execution engine)
if (blobsBundle.blobs.length !== blobsBundle.commitments.length) {
throw Error(

View File

@@ -36,9 +36,9 @@ const defaultAttestationsReward = {head: 0, target: 0, source: 0, inclusionDelay
const defaultAttestationsPenalty = {target: 0, source: 0};
export async function computeAttestationsRewards(
epoch: Epoch,
_epoch: Epoch,
state: CachedBeaconStateAllForks,
config: BeaconConfig,
_config: BeaconConfig,
validatorIds?: (ValidatorIndex | string)[]
): Promise<AttestationsRewards> {
const fork = state.config.getForkName(state.slot);

View File

@@ -6,7 +6,7 @@ import {
createAggregateSignatureSetFromComponents,
} from "@lodestar/state-transition";
import {toRootHex} from "@lodestar/utils";
import {IBeaconChain} from "..";
import {IBeaconChain} from "../index.js";
import {AttestationError, AttestationErrorCode, GossipAction} from "../errors/index.js";
import {RegenCaller} from "../regen/index.js";
import {getSelectionProofSignatureSet, getAggregateAndProofSignatureSet} from "./signatureSets/index.js";

View File

@@ -4,7 +4,7 @@ import {
assertValidAttesterSlashing,
getAttesterSlashingSignatureSets,
} from "@lodestar/state-transition";
import {IBeaconChain} from "..";
import {IBeaconChain} from "../index.js";
import {AttesterSlashingError, AttesterSlashingErrorCode, GossipAction} from "../errors/index.js";
export async function validateApiAttesterSlashing(

View File

@@ -4,7 +4,7 @@ import {
getBlsToExecutionChangeSignatureSet,
CachedBeaconStateCapella,
} from "@lodestar/state-transition";
import {IBeaconChain} from "..";
import {IBeaconChain} from "../index.js";
import {BlsToExecutionChangeError, BlsToExecutionChangeErrorCode, GossipAction} from "../errors/index.js";
export async function validateApiBlsToExecutionChange(

View File

@@ -1,6 +1,6 @@
import {phase0} from "@lodestar/types";
import {assertValidProposerSlashing, getProposerSlashingSignatureSets} from "@lodestar/state-transition";
import {IBeaconChain} from "..";
import {IBeaconChain} from "../index.js";
import {ProposerSlashingError, ProposerSlashingErrorCode, GossipAction} from "../errors/index.js";
export async function validateApiProposerSlashing(

View File

@@ -1,6 +1,6 @@
import {phase0} from "@lodestar/types";
import {isValidVoluntaryExit, getVoluntaryExitSignatureSet} from "@lodestar/state-transition";
import {IBeaconChain} from "..";
import {IBeaconChain} from "../index.js";
import {VoluntaryExitError, VoluntaryExitErrorCode, GossipAction} from "../errors/index.js";
import {RegenCaller} from "../regen/index.js";

View File

@@ -23,8 +23,7 @@ export class BackfilledRanges extends Repository<Slot, Slot> {
return bytesToInt(super.decodeKey(data) as unknown as Uint8Array, "be");
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
getId(value: Slot): number {
getId(_value: Slot): number {
throw new Error("Cannot get the db key from slot");
}
}

View File

@@ -11,7 +11,6 @@ import {Bucket, getBucketNameByValue} from "../buckets.js";
export class CheckpointStateRepository extends Repository<Uint8Array, BeaconStateAllForks> {
constructor(config: ChainForkConfig, db: Db) {
// Pick some type but won't be used. Casted to any because no type can match `BeaconStateAllForks`
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-explicit-any
const type = ssz.phase0.BeaconState as any;
const bucket = Bucket.allForks_checkpointState;
super(config, db, bucket, type, getBucketNameByValue(bucket));

View File

@@ -21,8 +21,7 @@ export class DepositDataRootRepository extends Repository<number, Root> {
}
// depositDataRoots stored by depositData index
// eslint-disable-next-line @typescript-eslint/no-unused-vars
getId(value: Root): number {
getId(_value: Root): number {
throw new Error("Unable to create depositIndex from root");
}

View File

@@ -14,8 +14,7 @@ export class Eth1DataRepository extends Repository<number, phase0.Eth1DataOrdere
return bytesToInt(super.decodeKey(data) as unknown as Uint8Array, "be");
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
getId(value: phase0.Eth1Data): number {
getId(_value: phase0.Eth1Data): number {
throw new Error("Unable to create timestamp from block hash");
}

View File

@@ -10,7 +10,7 @@ import {getRootIndexKey, storeRootIndex} from "./stateArchiveIndex.js";
export class StateArchiveRepository extends Repository<Slot, BeaconStateAllForks> {
constructor(config: ChainForkConfig, db: Db) {
// Pick some type but won't be used. Casted to any because no type can match `BeaconStateAllForks`
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-explicit-any
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
const type = ssz.phase0.BeaconState as any;
const bucket = Bucket.allForks_stateArchive;
super(config, db, bucket, type, getBucketNameByValue(bucket));

View File

@@ -10,7 +10,7 @@ export class PreGenesisStateLastProcessedBlock {
private readonly db: Db;
private readonly key: Uint8Array;
constructor(config: ChainForkConfig, db: Db) {
constructor(_config: ChainForkConfig, db: Db) {
this.db = db;
this.type = ssz.UintNum64;
this.bucket = Bucket.phase0_preGenesisStateLastProcessedBlock;

View File

@@ -167,7 +167,6 @@ export class Eth1MergeBlockTracker {
this.status = {code: StatusCode.SEARCHING};
this.logger.info("Starting search for terminal POW block", {
// eslint-disable-next-line @typescript-eslint/naming-convention
TERMINAL_TOTAL_DIFFICULTY: this.config.TERMINAL_TOTAL_DIFFICULTY,
});
@@ -268,7 +267,6 @@ export class Eth1MergeBlockTracker {
// this class can start eagerly looking for the merge block when not necessary, startPollingMergeBlock() should
// only be called when there is certainty that a mergeBlock search is necessary.
// eslint-disable-next-line no-constant-condition
while (true) {
if (block.totalDifficulty < this.config.TERMINAL_TOTAL_DIFFICULTY) {
// TTD not reached yet

View File

@@ -21,8 +21,6 @@ import {
} from "./jsonRpcHttpClient.js";
import {isJsonRpcTruncatedError, quantityToNum, numToQuantity, dataToBytes} from "./utils.js";
/* eslint-disable @typescript-eslint/naming-convention */
/**
* Binds return types to Ethereum JSON RPC methods
*/

View File

@@ -1,4 +1,4 @@
import {EventEmitter} from "events";
import {EventEmitter} from "node:events";
import {StrictEventEmitter} from "strict-event-emitter-types";
import {fetch} from "@lodestar/api";
import {ErrorAborted, Gauge, Histogram, TimeoutError, isValidHttpUrl, retry} from "@lodestar/utils";

View File

@@ -2,7 +2,6 @@ import type {TAlgorithm} from "jwt-simple";
// TODO: fix jwt-simple types
import jwt from "jwt-simple";
// eslint-disable-next-line import/no-named-as-default-member
const {encode, decode} = jwt;
/**

View File

@@ -18,6 +18,7 @@ export function initializeExecutionBuilder(
): IExecutionBuilder {
switch (opts.mode) {
case "http":
return new ExecutionBuilderHttp(opts, config, metrics, logger);
default:
return new ExecutionBuilderHttp(opts, config, metrics, logger);
}

View File

@@ -437,7 +437,7 @@ export class ExecutionEngineHttp implements IExecutionEngine {
this.payloadIdCache.prune();
}
async getPayloadBodiesByHash(fork: ForkName, blockHashes: RootHex[]): Promise<(ExecutionPayloadBody | null)[]> {
async getPayloadBodiesByHash(_fork: ForkName, blockHashes: RootHex[]): Promise<(ExecutionPayloadBody | null)[]> {
const method = "engine_getPayloadBodiesByHashV1";
assertReqSizeLimit(blockHashes.length, 32);
const response = await this.rpc.fetchWithRetries<
@@ -448,7 +448,7 @@ export class ExecutionEngineHttp implements IExecutionEngine {
}
async getPayloadBodiesByRange(
fork: ForkName,
_fork: ForkName,
startBlockNumber: number,
blockCount: number
): Promise<(ExecutionPayloadBody | null)[]> {

View File

@@ -55,6 +55,8 @@ export function initializeExecutionEngine(
return getExecutionEngineFromBackend(new ExecutionEngineMockBackend(opts), modules);
case "http":
return getExecutionEngineHttp(opts, modules);
default:
return getExecutionEngineHttp(opts, modules);
}

View File

@@ -85,7 +85,6 @@ export class ExecutionEngineMockBackend implements JsonRpcBackend {
});
this.handlers = {
/* eslint-disable @typescript-eslint/naming-convention */
engine_newPayloadV1: this.notifyNewPayload.bind(this),
engine_newPayloadV2: this.notifyNewPayload.bind(this),
engine_newPayloadV3: this.notifyNewPayload.bind(this),

View File

@@ -19,8 +19,6 @@ import {
import {ExecutionPayloadStatus, BlobsBundle, PayloadAttributes, VersionedHashes} from "./interface.js";
import {WithdrawalV1} from "./payloadIdCache.js";
/* eslint-disable @typescript-eslint/naming-convention */
export type EngineApiRpcParamTypes = {
/**
* 1. Object - Instance of ExecutionPayload

View File

@@ -12,7 +12,7 @@ import {isQueueErrorAborted} from "../../util/queue/errors.js";
import {ExecutionPayloadStatus, ExecutionEngineState} from "./interface.js";
export type JsonRpcBackend = {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
readonly handlers: Record<string, (...args: any[]) => any>;
};
@@ -27,8 +27,7 @@ export class ExecutionEngineMockJsonRpcClient implements IJsonRpcHttpClient {
if (handler === undefined) {
throw Error(`Unknown method ${payload.method}`);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
return handler(...(payload.params as any[])) as R;
}, payload);
}

View File

@@ -11,7 +11,6 @@ export type BeaconMetrics = ReturnType<typeof createBeaconMetrics>;
* https://github.com/ethereum/beacon-metrics/ and
* https://hackmd.io/D5FmoeFZScim_squBFl8oA
*/
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
export function createBeaconMetrics(register: RegistryMetricCreator) {
return {
// From https://github.com/ethereum/beacon-metrics/blob/master/metrics.md

View File

@@ -25,7 +25,6 @@ export type LodestarMetrics = ReturnType<typeof createLodestarMetrics>;
/**
* Extra Lodestar custom metrics
*/
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
export function createLodestarMetrics(
register: RegistryMetricCreator,
metadata?: LodestarMetadata,

View File

@@ -229,7 +229,7 @@ export class MonitoringService {
}
return url;
} catch {
} catch (_e) {
throw new Error(`Monitoring endpoint must be a valid URL: ${endpoint}`);
}
}

View File

@@ -3,7 +3,6 @@
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
import system from "systeminformation";
import {Logger} from "@lodestar/utils";

View File

@@ -5,7 +5,6 @@ import {SubnetSource} from "../subnets/attnetsService.js";
export type NetworkCoreMetrics = ReturnType<typeof createNetworkCoreMetrics>;
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
export function createNetworkCoreMetrics(register: RegistryMetricCreator) {
return {
register,
@@ -254,7 +253,6 @@ export function createNetworkCoreMetrics(register: RegistryMetricCreator) {
export type NetworkCoreWorkerMetrics = ReturnType<typeof getNetworkCoreWorkerMetrics>;
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
export function getNetworkCoreWorkerMetrics(register: RegistryMetricCreator) {
return {
reqRespBridgeRespCallerPending: register.gauge({

View File

@@ -149,7 +149,7 @@ export class NetworkCore implements INetworkCore {
// Bind discv5's ENR to local metadata
// resolve circular dependency by setting `discv5` variable after the peer manager is instantiated
// eslint-disable-next-line prefer-const
// biome-ignore lint/style/useConst: <explanation>
let discv5: Discv5Worker | undefined;
const onMetadataSetValue = function onMetadataSetValue(key: string, value: Uint8Array): void {
discv5?.setEnrValue(key, value).catch((e) => logger.error("error on setEnrValue", {key}, e));

View File

@@ -28,7 +28,6 @@ import {
// Cloned data from instantiation
const workerData = worker.workerData as NetworkWorkerData;
const parentPort = worker.parentPort;
// eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
if (!workerData) throw Error("workerData must be defined");
if (!parentPort) throw Error("parentPort must be defined");

View File

@@ -136,7 +136,7 @@ export class WorkerNetworkCore implements INetworkCore {
resourceLimits: {maxYoungGenerationSizeMb: opts.maxYoungGenerationSizeMb},
} as ConstructorParameters<typeof Worker>[1]);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
const networkThreadApi = (await spawn<any>(worker, {
// A Lodestar Node may do very expensive task at start blocking the event loop and causing
// the initialization to timeout. The number below is big enough to almost disable the timeout

View File

@@ -90,7 +90,7 @@ export type NetworkWorkerData = {
*/
export type NetworkWorkerApi = INetworkCorePublic & {
// To satisfy the constraint of `ModuleThread` type
// eslint-disable-next-line @typescript-eslint/no-explicit-any
// biome-ignore lint/suspicious/noExplicitAny:
[string: string]: (...args: any[]) => Promise<any> | any;
// Async method through worker boundary
reportPeer(peer: PeerIdStr, action: PeerAction, actionName: string): Promise<void>;

View File

@@ -1,4 +1,4 @@
import EventEmitter from "events";
import EventEmitter from "node:events";
import {PeerId, Secp256k1PeerId} from "@libp2p/interface";
import {StrictEventEmitter} from "strict-event-emitter-types";
import {exportToProtobuf} from "@libp2p/peer-id-factory";

View File

@@ -22,7 +22,6 @@ import {enrRelevance, ENRRelevance} from "./utils.js";
// Cloned data from instatiation
const workerData = worker.workerData as Discv5WorkerData;
// eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
if (!workerData) throw Error("workerData must be defined");
const logger = getNodeLogger(workerData.loggerOpts);

View File

@@ -1,4 +1,4 @@
import {EventEmitter} from "events";
import {EventEmitter} from "node:events";
import {PeerId, TopicValidatorResult} from "@libp2p/interface";
import {phase0, RootHex} from "@lodestar/types";
import {BlockInput, NullBlockInput} from "../chain/blocks/types.js";

View File

@@ -86,7 +86,6 @@ export function getCurrentAndNextFork(
}
return {
// eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
currentFork: forks[currentForkIdx] || forks[0],
nextFork: hasNextFork ? forks[nextForkIdx] : undefined,
};

Some files were not shown because too many files have changed in this diff Show More