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: add rule @typescript-eslint/restrict-template-expressions #5562

Merged
merged 2 commits into from
May 29, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -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",
{
Expand Down
2 changes: 1 addition & 1 deletion packages/api/test/utils/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});

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
Expand Up @@ -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);
});

Expand All @@ -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});
});
Expand Down
6 changes: 4 additions & 2 deletions packages/beacon-node/src/chain/validation/blobsSidecar.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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
)}`
);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
22 changes: 13 additions & 9 deletions packages/beacon-node/src/sync/backfill/backfill.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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`
);
Expand Down Expand Up @@ -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)}
);
}
Expand All @@ -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
Expand All @@ -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) {
Expand All @@ -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)}`
);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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}`);
Copy link
Member

Choose a reason for hiding this comment

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

👀

}

// The serialized value is stored in serialized.ssz_snappy
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ function validateRequestData(data: ReceivedData): void {
validateClientStats(data, SYSTEM_STATS_SCHEMA);
break;
default:
throw new Error(`Invalid process type "${data.process}"`);
throw new Error(`Invalid process type "${data.process as string}"`);
}
}

Expand Down
2 changes: 1 addition & 1 deletion packages/beacon-node/test/unit/network/fork.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
6 changes: 3 additions & 3 deletions packages/beacon-node/test/utils/node/validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,8 @@ export async function getAndInitDevValidators({
}

export function getApiFromServerHandlers(api: {[K in keyof Api]: ServerApi<Api[K]>}): 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 {
Expand All @@ -110,7 +110,7 @@ export function getApiFromServerHandlers(api: {[K in keyof Api]: ServerApi<Api[K
error: {
code: code ?? HttpStatusCode.INTERNAL_SERVER_ERROR,
message: (err as Error).message,
operationId: `${module}.${api.name}`,
operationId: api.name,
},
};
}
Expand Down
4 changes: 2 additions & 2 deletions packages/cli/test/sim/deneb.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/* eslint-disable @typescript-eslint/naming-convention */
import path from "node:path";
import {activePreset} from "@lodestar/params";
import {toHexString} from "@lodestar/utils";
import {toHex, toHexString} from "@lodestar/utils";
import {ApiError} from "@lodestar/api";
import {nodeAssertion} from "../utils/simulation/assertions/nodeAssertion.js";
import {CLIQUE_SEALING_PERIOD, SIM_TESTS_SECONDS_PER_SLOT} from "../utils/simulation/constants.js";
Expand Down Expand Up @@ -89,7 +89,7 @@ const checkpointSync = await env.createNodePair({
id: "checkpoint-sync-node",
cl: {
type: CLClient.Lodestar,
options: {clientOptions: {wssCheckpoint: `${headForCheckpointSync.root}:${headForCheckpointSync.epoch}`}},
options: {clientOptions: {wssCheckpoint: `${toHex(headForCheckpointSync.root)}:${headForCheckpointSync.epoch}`}},
},
el: ELClient.Geth,
keysCount: 0,
Expand Down
4 changes: 2 additions & 2 deletions packages/cli/test/sim/multi_fork.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/* eslint-disable @typescript-eslint/naming-convention */
import path from "node:path";
import {sleep, toHexString} from "@lodestar/utils";
import {sleep, toHex, toHexString} from "@lodestar/utils";
import {ApiError} from "@lodestar/api";
import {CLIQUE_SEALING_PERIOD, SIM_TESTS_SECONDS_PER_SLOT} from "../utils/simulation/constants.js";
import {AssertionMatch, CLClient, ELClient} from "../utils/simulation/interfaces.js";
Expand Down Expand Up @@ -116,7 +116,7 @@ const checkpointSync = await env.createNodePair({
id: "checkpoint-sync-node",
cl: {
type: CLClient.Lodestar,
options: {clientOptions: {wssCheckpoint: `${headForCheckpointSync.root}:${headForCheckpointSync.epoch}`}},
options: {clientOptions: {wssCheckpoint: `${toHex(headForCheckpointSync.root)}:${headForCheckpointSync.epoch}`}},
},
el: ELClient.Geth,
keysCount: 0,
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/test/utils/simulation/TableReporter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ export class TableReporter extends SimulationReporter<typeof defaultAssertions>
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(" ")}`
);
}
Expand Down
10 changes: 5 additions & 5 deletions packages/config/src/chainConfig/json.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -61,27 +61,27 @@ 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;
}
}

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) {
Expand Down
4 changes: 3 additions & 1 deletion packages/logger/test/unit/logger.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
}
Expand Down
2 changes: 1 addition & 1 deletion packages/params/src/json.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ export function presetFromJson(json: Record<string, unknown>): Partial<BeaconPre
*/
function deserializePresetValue(valueStr: unknown, keyName: string): number {
if (typeof valueStr !== "string") {
throw Error(`Invalid ${keyName} value ${valueStr} expected string`);
throw Error(`Invalid ${keyName} value ${valueStr as string} expected string`);
}

const value = parseInt(valueStr, 10);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ describe("verified_requests / eth_call", () => {
// 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`;
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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`;
}
}

Expand Down
2 changes: 1 addition & 1 deletion packages/spec-test-util/src/downloadTests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ export async function downloadGenericSpecTests<TestNames extends string>(
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
Expand Down
2 changes: 1 addition & 1 deletion packages/spec-test-util/src/sszGeneric.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions packages/utils/src/assert.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ export const assert = {
*/
equal<T>(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}`);
}
},
Expand Down