diff --git a/.eslintrc.js b/.eslintrc.js index afe380c5790..1f4ced38438 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -114,6 +114,10 @@ module.exports = { allowAny: true, }, ], + "@typescript-eslint/restrict-template-expressions": [ + "error", + {allowNumber: true, allowBoolean: true, allowNullish: true, allowNever: true, allowRegExp: true}, + ], "import/no-extraneous-dependencies": [ "error", { diff --git a/packages/api/test/utils/utils.ts b/packages/api/test/utils/utils.ts index ac160aa4520..793f8b2c61e 100644 --- a/packages/api/test/utils/utils.ts +++ b/packages/api/test/utils/utils.ts @@ -15,7 +15,7 @@ export function getTestServer(): {baseUrl: string; server: FastifyInstance} { server.addHook("onError", (request, reply, error, done) => { // eslint-disable-next-line no-console - console.log(`onError: ${error}`); + console.log(`onError: ${error.toString()}`); done(); }); diff --git a/packages/beacon-node/src/api/rest/base.ts b/packages/beacon-node/src/api/rest/base.ts index 7f7c03773a9..00da37d69ff 100644 --- a/packages/beacon-node/src/api/rest/base.ts +++ b/packages/beacon-node/src/api/rest/base.ts @@ -87,14 +87,14 @@ export class RestApiServer { // Note: Must be an async method so fastify can continue the release lifecycle. Otherwise we must call done() or the request stalls server.addHook("onRequest", async (req, _res) => { const {operationId} = req.routeConfig as RouteConfig; - this.logger.debug(`Req ${req.id} ${req.ip} ${operationId}`); + this.logger.debug(`Req ${req.id as string} ${req.ip} ${operationId}`); metrics?.requests.inc({operationId}); }); // Log after response server.addHook("onResponse", async (req, res) => { const {operationId} = req.routeConfig as RouteConfig; - this.logger.debug(`Res ${req.id} ${operationId} - ${res.raw.statusCode}`); + this.logger.debug(`Res ${req.id as string} ${operationId} - ${res.raw.statusCode}`); metrics?.responseTime.observe({operationId}, res.getResponseTime() / 1000); }); @@ -107,9 +107,9 @@ export class RestApiServer { const {operationId} = req.routeConfig as RouteConfig; if (err instanceof ApiError) { - this.logger.warn(`Req ${req.id} ${operationId} failed`, {reason: err.message}); + this.logger.warn(`Req ${req.id as string} ${operationId} failed`, {reason: err.message}); } else { - this.logger.error(`Req ${req.id} ${operationId} error`, {}, err); + this.logger.error(`Req ${req.id as string} ${operationId} error`, {}, err); } metrics?.errors.inc({operationId}); }); diff --git a/packages/beacon-node/src/chain/validation/blobsSidecar.ts b/packages/beacon-node/src/chain/validation/blobsSidecar.ts index bb46c384e50..952c7840cff 100644 --- a/packages/beacon-node/src/chain/validation/blobsSidecar.ts +++ b/packages/beacon-node/src/chain/validation/blobsSidecar.ts @@ -1,7 +1,7 @@ import bls from "@chainsafe/bls"; import {CoordType} from "@chainsafe/bls/types"; import {deneb, Root, ssz} from "@lodestar/types"; -import {bytesToBigInt} from "@lodestar/utils"; +import {bytesToBigInt, toHex} from "@lodestar/utils"; import {BYTES_PER_FIELD_ELEMENT, FIELD_ELEMENTS_PER_BLOB} from "@lodestar/params"; import {verifyKzgCommitmentsAgainstTransactions} from "@lodestar/state-transition"; import {BlobsSidecarError, BlobsSidecarErrorCode} from "../errors/blobsSidecarError.js"; @@ -83,7 +83,9 @@ export function validateBlobsSidecar( // assert beacon_block_root == blobs_sidecar.beacon_block_root if (!byteArrayEquals(beaconBlockRoot, blobsSidecar.beaconBlockRoot)) { throw new Error( - `beacon block root mismatch. Block root: ${beaconBlockRoot}, Blob root ${blobsSidecar.beaconBlockRoot}` + `beacon block root mismatch. Block root: ${toHex(beaconBlockRoot)}, Blob root ${toHex( + blobsSidecar.beaconBlockRoot + )}` ); } diff --git a/packages/beacon-node/src/network/reqresp/beaconBlocksMaybeBlobsByRange.ts b/packages/beacon-node/src/network/reqresp/beaconBlocksMaybeBlobsByRange.ts index 5cca52424e7..eaf2b46dce4 100644 --- a/packages/beacon-node/src/network/reqresp/beaconBlocksMaybeBlobsByRange.ts +++ b/packages/beacon-node/src/network/reqresp/beaconBlocksMaybeBlobsByRange.ts @@ -87,7 +87,8 @@ export async function beaconBlocksMaybeBlobsByRange( blobsSidecars.length } lastMatchedSlot=${lastMatchedSlot}, pending blobsSidecars slots=${blobsSidecars .slice(blobSideCarIndex) - .map((blb) => blb.beaconBlockSlot)}` + .map((blb) => blb.beaconBlockSlot) + .join(",")}` ); } return blockInputs; diff --git a/packages/beacon-node/src/sync/backfill/backfill.ts b/packages/beacon-node/src/sync/backfill/backfill.ts index d19594af62d..472bd6313cb 100644 --- a/packages/beacon-node/src/sync/backfill/backfill.ts +++ b/packages/beacon-node/src/sync/backfill/backfill.ts @@ -3,7 +3,7 @@ import {StrictEventEmitter} from "strict-event-emitter-types"; import {BeaconStateAllForks, blockToHeader} from "@lodestar/state-transition"; import {BeaconConfig, ChainForkConfig} from "@lodestar/config"; import {phase0, Root, Slot, allForks, ssz} from "@lodestar/types"; -import {ErrorAborted, Logger, sleep} from "@lodestar/utils"; +import {ErrorAborted, Logger, sleep, toHex} from "@lodestar/utils"; import {toHexString} from "@chainsafe/ssz"; import {SLOTS_PER_EPOCH} from "@lodestar/params"; @@ -528,7 +528,7 @@ export class BackfillSync extends (EventEmitter as {new (): BackfillSyncEmitter} ) // TODO: explode and stop the entire node throw new Error( - `InvalidWsCheckpoint root=${this.wsCheckpointHeader.root}, epoch=${ + `InvalidWsCheckpoint root=${toHex(this.wsCheckpointHeader.root)}, epoch=${ this.wsCheckpointHeader.slot / SLOTS_PER_EPOCH }, ${ wsDbCheckpointBlock @@ -590,9 +590,9 @@ export class BackfillSync extends (EventEmitter as {new (): BackfillSyncEmitter} } else { validSequence = false; this.logger.warn( - `Invalid backfill sequence: previous finalized or checkpoint block root=${ + `Invalid backfill sequence: previous finalized or checkpoint block root=${toHex( this.prevFinalizedCheckpointBlock.root - }, slot=${this.prevFinalizedCheckpointBlock.slot} ${ + )}, slot=${this.prevFinalizedCheckpointBlock.slot} ${ prevBackfillCpBlock ? "found at slot=" + prevBackfillCpBlock.message.slot : "not found" }, ignoring the sequence` ); @@ -644,7 +644,9 @@ export class BackfillSync extends (EventEmitter as {new (): BackfillSyncEmitter} if (cleanupSeqs.length > 0) { await this.db.backfilledRanges.batchDelete(cleanupSeqs.map((entry) => entry.key)); this.logger.debug( - `Cleaned up the old sequences between ${this.backfillStartFromSlot},${this.syncAnchor.lastBackSyncedBlock}`, + `Cleaned up the old sequences between ${this.backfillStartFromSlot},${toHex( + this.syncAnchor.lastBackSyncedBlock.root + )}`, {cleanupSeqs: JSON.stringify(cleanupSeqs)} ); } @@ -668,7 +670,9 @@ export class BackfillSync extends (EventEmitter as {new (): BackfillSyncEmitter} if (expectedSlot !== null && anchorBlock.message.slot !== expectedSlot) throw Error( - `Invalid slot of anchorBlock read from DB with root=${anchorBlockRoot}, expected=${expectedSlot}, actual=${anchorBlock.message.slot}` + `Invalid slot of anchorBlock read from DB with root=${toHex( + anchorBlockRoot + )}, expected=${expectedSlot}, actual=${anchorBlock.message.slot}` ); // If possible, read back till anchorBlock > this.prevFinalizedCheckpointBlock @@ -683,9 +687,9 @@ export class BackfillSync extends (EventEmitter as {new (): BackfillSyncEmitter} // Before moving anchorBlock back, we need check for prevFinalizedCheckpointBlock if (anchorBlock.message.slot < this.prevFinalizedCheckpointBlock.slot) { throw Error( - `Skipped a prevFinalizedCheckpointBlock with slot=${this.prevFinalizedCheckpointBlock}, root=${toHexString( + `Skipped a prevFinalizedCheckpointBlock with slot=${toHex( this.prevFinalizedCheckpointBlock.root - )}` + )}, root=${toHexString(this.prevFinalizedCheckpointBlock.root)}` ); } if (anchorBlock.message.slot === this.prevFinalizedCheckpointBlock.slot) { @@ -696,7 +700,7 @@ export class BackfillSync extends (EventEmitter as {new (): BackfillSyncEmitter} throw Error( `Invalid root for prevFinalizedCheckpointBlock at slot=${ this.prevFinalizedCheckpointBlock.slot - }, expected=${toHexString(this.prevFinalizedCheckpointBlock.root)}, found=${anchorBlockRoot}` + }, expected=${toHexString(this.prevFinalizedCheckpointBlock.root)}, found=${toHex(anchorBlockRoot)}` ); } diff --git a/packages/beacon-node/test/spec/utils/sszTestCaseParser.ts b/packages/beacon-node/test/spec/utils/sszTestCaseParser.ts index 704abc734cd..d4108a2eb01 100644 --- a/packages/beacon-node/test/spec/utils/sszTestCaseParser.ts +++ b/packages/beacon-node/test/spec/utils/sszTestCaseParser.ts @@ -47,7 +47,7 @@ export function parseSszValidTestcase(dirpath: string, metaFilename: string): Va const metaStr = fs.readFileSync(path.join(dirpath, metaFilename), "utf8"); const meta = jsyaml.load(metaStr) as {root: string}; if (typeof meta.root !== "string") { - throw Error(`meta.root not a string: ${meta.root}\n${fs}`); + throw Error(`meta.root not a string: ${meta.root}\n${metaStr}`); } // The serialized value is stored in serialized.ssz_snappy diff --git a/packages/beacon-node/test/unit/monitoring/remoteService.ts b/packages/beacon-node/test/unit/monitoring/remoteService.ts index 4acbb6f1439..e302118f319 100644 --- a/packages/beacon-node/test/unit/monitoring/remoteService.ts +++ b/packages/beacon-node/test/unit/monitoring/remoteService.ts @@ -6,7 +6,7 @@ import {BEACON_NODE_STATS_SCHEMA, ClientStatsSchema, SYSTEM_STATS_SCHEMA, VALIDA /* eslint-disable no-console */ -type ReceivedData = Record; +type ReceivedData = Record & {process: ProcessType}; export const remoteServiceRoutes = { success: "/success", diff --git a/packages/beacon-node/test/unit/network/fork.test.ts b/packages/beacon-node/test/unit/network/fork.test.ts index 4d807ddefdf..b920870189a 100644 --- a/packages/beacon-node/test/unit/network/fork.test.ts +++ b/packages/beacon-node/test/unit/network/fork.test.ts @@ -143,7 +143,7 @@ for (const testScenario of testScenarios) { it(` on epoch ${epoch} should return ${JSON.stringify({ currentFork, nextFork, - })}, getActiveForks: ${activeForks}`, () => { + })}, getActiveForks: ${activeForks.join(",")}`, () => { expect(getCurrentAndNextFork(forkConfig, epoch)).to.deep.equal({ currentFork: forks[currentFork as ForkName], nextFork: (nextFork && forks[nextFork as ForkName]) ?? undefined, diff --git a/packages/beacon-node/test/utils/node/validator.ts b/packages/beacon-node/test/utils/node/validator.ts index 9e0171db369..c574f905606 100644 --- a/packages/beacon-node/test/utils/node/validator.ts +++ b/packages/beacon-node/test/utils/node/validator.ts @@ -86,8 +86,8 @@ export async function getAndInitDevValidators({ } export function getApiFromServerHandlers(api: {[K in keyof Api]: ServerApi}): Api { - return mapValues(api, (module) => - mapValues(module, (api: APIServerHandler) => { + return mapValues(api, (apiModule) => + mapValues(apiModule, (api: APIServerHandler) => { return async (...args: any) => { let code: HttpStatusCode = HttpStatusCode.OK; try { @@ -110,7 +110,7 @@ export function getApiFromServerHandlers(api: {[K in keyof Api]: ServerApi for (const error of assertionErrors) { console.info( `├──── ${error.nodeId}: ${error.message} ${Object.entries(error.data ?? {}) - .map(([k, v]) => `${k}=${v}`) + .map(([k, v]) => `${k}=${v as string}`) .join(" ")}` ); } diff --git a/packages/config/src/chainConfig/json.ts b/packages/config/src/chainConfig/json.ts index eea00c7ad2f..4e61333cbde 100644 --- a/packages/config/src/chainConfig/json.ts +++ b/packages/config/src/chainConfig/json.ts @@ -52,7 +52,7 @@ export function serializeSpecValue(value: SpecValue, typeName: SpecValueTypeName switch (typeName) { case "number": if (typeof value !== "number") { - throw Error(`Invalid value ${value} expected number`); + throw Error(`Invalid value ${value.toString()} expected number`); } if (value === Infinity) { return MAX_UINT64_JSON; @@ -61,19 +61,19 @@ export function serializeSpecValue(value: SpecValue, typeName: SpecValueTypeName case "bigint": if (typeof value !== "bigint") { - throw Error(`Invalid value ${value} expected bigint`); + throw Error(`Invalid value ${value.toString()} expected bigint`); } return value.toString(10); case "bytes": if (!(value instanceof Uint8Array)) { - throw Error(`Invalid value ${value} expected Uint8Array`); + throw Error(`Invalid value ${value.toString()} expected Uint8Array`); } return toHexString(value); case "string": if (typeof value !== "string") { - throw Error(`Invalid value ${value} expected string`); + throw Error(`Invalid value ${value.toString()} expected string`); } return value; } @@ -81,7 +81,7 @@ export function serializeSpecValue(value: SpecValue, typeName: SpecValueTypeName export function deserializeSpecValue(valueStr: unknown, typeName: SpecValueTypeName, keyName: string): SpecValue { if (typeof valueStr !== "string") { - throw Error(`Invalid ${keyName} value ${valueStr} expected string`); + throw Error(`Invalid ${keyName} value ${valueStr as string} expected string`); } switch (typeName) { diff --git a/packages/logger/test/unit/logger.test.ts b/packages/logger/test/unit/logger.test.ts index 26caf910dd2..fb063b8e3a1 100644 --- a/packages/logger/test/unit/logger.test.ts +++ b/packages/logger/test/unit/logger.test.ts @@ -52,7 +52,9 @@ describe("shouldDeleteLogFile", function () { ]; for (const {logFile, maxFiles, result} of tcs) { - it(`should ${result ? "" : "not"} delete ${logFile}, maxFiles ${maxFiles}, today ${new Date()}`, () => { + it(`should ${ + result ? "" : "not" + } delete ${logFile}, maxFiles ${maxFiles}, today ${new Date().toUTCString()}`, () => { expect(shouldDeleteLogFile(prefix, extension, logFile, maxFiles)).to.be.equal(result); }); } diff --git a/packages/params/src/json.ts b/packages/params/src/json.ts index ffb041cbb63..8d475e680f4 100644 --- a/packages/params/src/json.ts +++ b/packages/params/src/json.ts @@ -45,7 +45,7 @@ export function presetFromJson(json: Record): Partial { // Temper the responses to make them invalid for (const tx of testCase.dependentRequests) { if (tx.payload.method === "eth_getCode") { - tx.response.result = `${tx.response.result}12`; + tx.response.result = `${tx.response.result as string}12`; } } diff --git a/packages/prover/test/unit/verified_requests/eth_estimateGas.test.ts b/packages/prover/test/unit/verified_requests/eth_estimateGas.test.ts index 5a3f4d5225a..b7ae3abc312 100644 --- a/packages/prover/test/unit/verified_requests/eth_estimateGas.test.ts +++ b/packages/prover/test/unit/verified_requests/eth_estimateGas.test.ts @@ -37,7 +37,7 @@ describe("verified_requests / eth_estimateGas", () => { // Temper the responses to make them invalid for (const tx of testCase.dependentRequests) { if (tx.payload.method === "eth_getCode") { - tx.response.result = `${tx.response.result}12`; + tx.response.result = `${tx.response.result as string}12`; } } diff --git a/packages/spec-test-util/src/downloadTests.ts b/packages/spec-test-util/src/downloadTests.ts index 59e727d78d5..d3da52c0306 100644 --- a/packages/spec-test-util/src/downloadTests.ts +++ b/packages/spec-test-util/src/downloadTests.ts @@ -77,7 +77,7 @@ export async function downloadGenericSpecTests( timeout: 30 * 60 * 1000, }); - const totalSize = headers["content-length"]; + const totalSize = headers["content-length"] as string; log(`Downloading ${url} - ${totalSize} bytes`); // extract tar into output directory diff --git a/packages/spec-test-util/src/sszGeneric.ts b/packages/spec-test-util/src/sszGeneric.ts index d62e4df4279..e9eee7df0ff 100644 --- a/packages/spec-test-util/src/sszGeneric.ts +++ b/packages/spec-test-util/src/sszGeneric.ts @@ -17,7 +17,7 @@ export function parseSszValidTestcase(dirpath: string, metaFilename: string): Va const metaStr = fs.readFileSync(path.join(dirpath, metaFilename), "utf8"); const meta = loadYaml(metaStr) as {root: string}; if (typeof meta.root !== "string") { - throw Error(`meta.root not a string: ${meta.root}\n${fs}`); + throw Error(`meta.root not a string: ${meta.root}\n${metaStr}`); } // The serialized value is stored in serialized.ssz_snappy diff --git a/packages/utils/src/assert.ts b/packages/utils/src/assert.ts index 7e5c5760345..aa86161cca4 100644 --- a/packages/utils/src/assert.ts +++ b/packages/utils/src/assert.ts @@ -16,6 +16,7 @@ export const assert = { */ equal(actual: T, expected: T, message?: string): void { if (!(actual === expected)) { + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions throw new AssertionError(`${message || "Expected values to be equal"}: ${actual} === ${expected}`); } },