Type error in catch clause (with TS feature) (#3072)

* Bump typescript to 4.4.0

* Type catch e clause

* Bump observable-fns

* Type lodestar error

* Skip readme checks
This commit is contained in:
Lion - dapplion
2021-09-09 21:44:57 +02:00
committed by GitHub
parent 6a0745e9db
commit d7a4379d93
58 changed files with 142 additions and 143 deletions

View File

@@ -39,5 +39,7 @@ jobs:
run: yarn coverage
- name: E2e tests
run: yarn test:e2e
- name: README check
run: yarn run check-readme
# Tool incompatible with current Typescript version
# See https://github.com/bbc/typescript-docs-verifier/issues/1
# - name: README check
# run: yarn run check-readme

View File

@@ -59,7 +59,7 @@
"typedoc-plugin-external-module-name": "^4.0.3",
"typedoc-plugin-internal-external": "^2.2.0",
"typedoc-plugin-markdown": "^2.4.1",
"typescript": "^4.2.0",
"typescript": "^4.4.0",
"typescript-docs-verifier": "^1.1.3"
},
"dependencies": {},

View File

@@ -93,7 +93,7 @@ export class HttpClient implements IHttpClient {
return await getBody(res);
} catch (e) {
if (isAbortedError(e)) {
if (isAbortedError(e as Error)) {
if (signalGlobal?.aborted) {
throw new ErrorAborted("REST client");
} else if (controller.signal.aborted) {

View File

@@ -29,7 +29,7 @@ export function getRoutes(config: IChainForkConfig, api: Api): ServerRoutes<Api,
const data = eventSerdes.toJson(event);
res.raw.write(serializeSSEEvent({event: event.type, data}));
} catch (e) {
reject(e);
reject(e as Error);
}
});

View File

@@ -69,7 +69,7 @@ describe("events", () => {
await sleep(5);
}
} catch (e) {
reject(e);
reject(e as Error);
}
});

View File

@@ -81,7 +81,7 @@ async function run(): Promise<void> {
}
}
run().catch((e) => {
run().catch((e: Error) => {
console.error(e);
process.exit(1);
});

View File

@@ -175,7 +175,7 @@ const fromEpoch = process.env.FROM_EPOCH !== undefined ? parseInt(process.env.FR
const network = process.env.NETWORK;
if (!network) throw Error("Must define process.env.NETWORK");
analyzeEpochs(network, fromEpoch).catch((e) => {
analyzeEpochs(network, fromEpoch).catch((e: Error) => {
// eslint-disable-next-line no-console
console.error(e);
process.exit(1);

View File

@@ -2,7 +2,7 @@ import {init} from "@chainsafe/bls";
// blst-native initialization is syncronous
// Initialize bls here instead of in before() so it's available inside describe() blocks
init("blst-native").catch((e) => {
init("blst-native").catch((e: Error) => {
// eslint-disable-next-line no-console
console.error(e);
process.exit(1);

View File

@@ -90,13 +90,7 @@ BE UNTIL AT LEAST TWO YEARS AFTER THE PHASE 0 MAINNET LAUNCH.
console.log(`Initiating voluntary exit for validator ${publicKey}`);
let secretKey;
try {
secretKey = await validatorDirManager.decryptValidator(publicKey, {force});
} catch (error) {
throw new YargsError(error);
}
const secretKey = await validatorDirManager.decryptValidator(publicKey, {force});
if (!secretKey) throw new YargsError("No validator keystores found");
console.log(`Decrypted keystore for validator ${publicKey}`);
@@ -111,10 +105,6 @@ BE UNTIL AT LEAST TWO YEARS AFTER THE PHASE 0 MAINNET LAUNCH.
graffiti: args.graffiti,
});
try {
await validatorClient.voluntaryExit(publicKey, args.exitEpoch);
} catch (error) {
throw new Error(error);
}
await validatorClient.voluntaryExit(publicKey, args.exitEpoch);
},
};

View File

@@ -12,7 +12,7 @@ export function getDefaultGraffiti(): string {
return `${lodestarPackageName}-${version}`;
} catch (e) {
// eslint-disable-next-line no-console
console.error("Error guessing lodestar version", e);
console.error("Error guessing lodestar version", e as Error);
return lodestarPackageName;
}
}

View File

@@ -28,7 +28,7 @@ export class Clock implements IClock {
start(signal: AbortSignal): void {
for (const fn of this.fns) {
this.runAtMostEvery(signal, fn).catch((e) => {
this.runAtMostEvery(signal, fn).catch((e: Error) => {
if (this.onError) this.onError(e);
});
}

View File

@@ -2,7 +2,7 @@ import {init} from "@chainsafe/bls";
// blst-native initialization is syncronous
// Initialize bls here instead of in before() so it's available inside describe() blocks
init("blst-native").catch((e) => {
init("blst-native").catch((e: Error) => {
// eslint-disable-next-line no-console
console.error(e);
process.exit(1);

View File

@@ -71,7 +71,7 @@ async function runAltairChainSimulator(): Promise<void> {
}
}
runAltairChainSimulator().catch((e) => {
runAltairChainSimulator().catch((e: Error) => {
console.error(e);
process.exit(1);
});

View File

@@ -87,7 +87,7 @@
"snappyjs": "^0.6.0",
"stream-to-it": "^0.2.0",
"strict-event-emitter-types": "^2.0.0",
"threads": "^1.6.3",
"threads": "^1.6.5",
"varint": "^5.0.0",
"wtfnode": "^0.8.4"
},

View File

@@ -60,11 +60,11 @@ export function getBeaconPoolApi({
chain.attestationPool.add(attestation),
]);
} catch (e) {
errors.push(e);
errors.push(e as Error);
logger.error(
`Error on submitPoolAttestations [${i}]`,
{slot: attestation.data.slot, index: attestation.data.index},
e
e as Error
);
if (e instanceof AttestationError && e.action === GossipAction.REJECT) {
const archivedPath = chain.persistInvalidSszObject(
@@ -148,11 +148,11 @@ export function getBeaconPoolApi({
})
);
} catch (e) {
errors.push(e);
errors.push(e as Error);
logger.error(
`Error on submitPoolSyncCommitteeSignatures [${i}]`,
{slot: signature.slot, validatorIndex: signature.validatorIndex},
e
e as Error
);
if (e instanceof SyncCommitteeError && e.action === GossipAction.REJECT) {
const archivedPath = chain.persistInvalidSszObject(

View File

@@ -369,14 +369,14 @@ export function getValidatorApi({
return; // Ok to submit the same aggregate twice
}
errors.push(e);
errors.push(e as Error);
logger.error(
`Error on publishAggregateAndProofs [${i}]`,
{
slot: signedAggregateAndProof.message.aggregate.data.slot,
index: signedAggregateAndProof.message.aggregate.data.index,
},
e
e as Error
);
if (e instanceof AttestationError && e.action === GossipAction.REJECT) {
const archivedPath = chain.persistInvalidSszObject(
@@ -417,14 +417,14 @@ export function getValidatorApi({
chain.syncContributionAndProofPool.add(contributionAndProof.message);
await network.gossip.publishContributionAndProof(contributionAndProof);
} catch (e) {
errors.push(e);
errors.push(e as Error);
logger.error(
`Error on publishContributionAndProofs [${i}]`,
{
slot: contributionAndProof.message.contribution.slot,
subCommitteeIndex: contributionAndProof.message.contribution.subCommitteeIndex,
},
e
e as Error
);
if (e instanceof SyncCommitteeError && e.action === GossipAction.REJECT) {
const archivedPath = chain.persistInvalidSszObject(

View File

@@ -117,7 +117,7 @@ export class RestApi {
const address = await this.server.listen(this.opts.port, this.opts.host);
this.logger.info("Started REST api server", {address, namespaces: this.opts.api});
} catch (e) {
this.logger.error("Error starting REST api server", {host: this.opts.host, port: this.opts.port}, e);
this.logger.error("Error starting REST api server", {host: this.opts.host, port: this.opts.port}, e as Error);
throw e;
}
}

View File

@@ -82,7 +82,7 @@ export class Archiver {
this.chain.forkChoice.prune(finalized.root);
this.logger.verbose("Finish processing finalized checkpoint", {epoch: finalizedEpoch});
} catch (e) {
this.logger.error("Error processing finalized checkpoint", {epoch: finalized.epoch}, e);
this.logger.error("Error processing finalized checkpoint", {epoch: finalized.epoch}, e as Error);
}
};
}

View File

@@ -66,7 +66,12 @@ export async function processBlockJob(modules: BlockProcessorModules, job: IBloc
await processBlock(modules, job);
} catch (e) {
// above functions only throw BlockError
modules.emitter.emit(ChainEvent.errorBlock, e);
if (e instanceof BlockError) {
modules.emitter.emit(ChainEvent.errorBlock, e);
} else {
// TODO: Hanlde non-BlockError(s)
modules.emitter.emit(ChainEvent.errorBlock, e as BlockError);
}
}
}
@@ -140,8 +145,9 @@ export async function processChainSegmentJob(modules: BlockProcessorModules, job
// error.
default:
throw new ChainSegmentError({
job: e.job,
...e.type,
// TODO: Stop using jobs in errors
job: (e as ChainSegmentError).job,
...(e as BlockError).type,
importedBlocks: 0,
});
}

View File

@@ -328,10 +328,10 @@ export class BlsMultiThreadWorkerPool implements IBlsVerifier {
if (batchSigsSuccess > 0) this.metrics?.blsThreadPool.batchSigsSuccess.inc(batchSigsSuccess);
} catch (e) {
// Worker communications should never reject
if (!this.signal.aborted) this.logger.error("BlsMultiThreadWorkerPool error", {}, e);
if (!this.signal.aborted) this.logger.error("BlsMultiThreadWorkerPool error", {}, e as Error);
// Reject all
for (const job of jobs) {
job.reject(e);
job.reject(e as Error);
}
}
@@ -379,7 +379,7 @@ export class BlsMultiThreadWorkerPool implements IBlsVerifier {
for (const [id, worker] of this.workers.entries()) {
// NOTE: 'threads' has not yet updated types, and NodeJS complains with
// [DEP0132] DeprecationWarning: Passing a callback to worker.terminate() is deprecated. It returns a Promise instead.
((worker.worker.terminate() as unknown) as Promise<void>).catch((e) => {
((worker.worker.terminate() as unknown) as Promise<void>).catch((e: Error) => {
if (e) this.logger.error("Error terminating worker", {id}, e);
});
}

View File

@@ -34,7 +34,7 @@ function wrapHandler<
await handler(...args);
emitter.emit(event, ...((args as unknown) as ListenerType<Callback>));
} catch (e) {
logger.error("Error handling event", {event}, e);
logger.error("Error handling event", {event}, e as Error);
}
};
}
@@ -197,12 +197,12 @@ export async function onForkChoiceFinalized(this: BeaconChain, cp: phase0.Checkp
state as TreeBacked<altair.BeaconState>
);
} catch (e) {
this.logger.error("Error lightclientUpdater.onFinalized", {epoch: cp.epoch}, e);
this.logger.error("Error lightclientUpdater.onFinalized", {epoch: cp.epoch}, e as Error);
}
try {
await this.lightClientIniter.onFinalized(cp);
} catch (e) {
this.logger.error("Error LightClientIniter.onFinalized", {epoch: cp.epoch}, e);
this.logger.error("Error LightClientIniter.onFinalized", {epoch: cp.epoch}, e as Error);
}
}
}
@@ -259,7 +259,7 @@ export async function onBlock(
this.metrics?.registerAttestationInBlock(indexedAttestation, block.message);
} catch (e) {
this.logger.error("Error processing attestation from block", {slot: block.message.slot}, e);
this.logger.error("Error processing attestation from block", {slot: block.message.slot}, e as Error);
}
}
}
@@ -293,7 +293,7 @@ export async function onBlock(
postState as TreeBacked<altair.BeaconState>
);
} catch (e) {
this.logger.error("Error lightclientUpdater.onHead", {slot: block.message.slot}, e);
this.logger.error("Error lightclientUpdater.onHead", {slot: block.message.slot}, e as Error);
}
}
}

View File

@@ -63,7 +63,7 @@ export async function validateGossipAggregateAndProof(
const targetState = await chain.regen
.getCheckpointState(attTarget, RegenCaller.validateGossipAggregateAndProof)
.catch((e) => {
.catch((e: Error) => {
throw new AttestationError(GossipAction.REJECT, {
code: AttestationErrorCode.MISSING_ATTESTATION_TARGET_STATE,
error: e as Error,

View File

@@ -87,7 +87,7 @@ export async function validateGossipAttestation(
const attestationTargetState = await chain.regen
.getCheckpointState(attTarget, RegenCaller.validateGossipAttestation)
.catch((e) => {
.catch((e: Error) => {
throw new AttestationError(GossipAction.REJECT, {
code: AttestationErrorCode.MISSING_ATTESTATION_TARGET_STATE,
error: e as Error,

View File

@@ -63,7 +63,7 @@ export class Eth1ForBlockProduction implements IEth1ForBlockProduction {
this.logger.warn("No depositContractDeployBlock provided");
}
this.runAutoUpdate().catch((e) => {
this.runAutoUpdate().catch((e: Error) => {
if (!(e instanceof ErrorAborted)) {
this.logger.error("Error on eth1 loop", {}, e);
}
@@ -133,7 +133,7 @@ export class Eth1ForBlockProduction implements IEth1ForBlockProduction {
this.logger.debug("Eth1 provider rate limited", {}, e);
await sleep(RATE_LIMITED_WAIT_MS, this.signal);
} else {
this.logger.error("Error updating eth1 chain cache", {}, e);
this.logger.error("Error updating eth1 chain cache", {}, e as Error);
await sleep(MIN_WAIT_ON_ERORR_MS, this.signal);
}
}

View File

@@ -74,7 +74,7 @@ export class JsonRpcHttpClient {
try {
return await this.fetchJsonOneUrl(url, json, opts);
} catch (e) {
if (this.opts.shouldNotFallback?.(e)) {
if (this.opts.shouldNotFallback?.(e as Error)) {
throw e;
}
@@ -148,7 +148,7 @@ function parseJson<T>(json: string): T {
try {
return JSON.parse(json) as T;
} catch (e) {
throw new ErrorParseJson(json, e);
throw new ErrorParseJson(json, e as Error);
}
}

View File

@@ -43,7 +43,7 @@ export class HttpMetricsServer implements IMetricsServer {
try {
await this.terminator.terminate();
} catch (e) {
this.logger.warn("Failed to stop metrics server", e);
this.logger.warn("Failed to stop metrics server", {}, e as Error);
}
}

View File

@@ -83,7 +83,7 @@ export function getGossipHandlers(modules: ValidatorFnsModules): GossipHandlers
try {
chain.receiveBlock(signedBlock);
} catch (e) {
logger.error("Error receiving block", {}, e);
logger.error("Error receiving block", {}, e as Error);
}
} catch (e) {
if (
@@ -183,7 +183,7 @@ export function getGossipHandlers(modules: ValidatorFnsModules): GossipHandlers
try {
chain.attestationPool.add(attestation);
} catch (e) {
logger.error("Error adding attestation to pool", {subnet}, e);
logger.error("Error adding attestation to pool", {subnet}, e as Error);
}
},
@@ -192,7 +192,7 @@ export function getGossipHandlers(modules: ValidatorFnsModules): GossipHandlers
// Handler
db.voluntaryExit.add(voluntaryExit).catch((e) => {
db.voluntaryExit.add(voluntaryExit).catch((e: Error) => {
logger.error("Error adding attesterSlashing to pool", {}, e);
});
},
@@ -202,7 +202,7 @@ export function getGossipHandlers(modules: ValidatorFnsModules): GossipHandlers
// Handler
db.proposerSlashing.add(proposerSlashing).catch((e) => {
db.proposerSlashing.add(proposerSlashing).catch((e: Error) => {
logger.error("Error adding attesterSlashing to pool", {}, e);
});
},
@@ -212,7 +212,7 @@ export function getGossipHandlers(modules: ValidatorFnsModules): GossipHandlers
// Handler
db.attesterSlashing.add(attesterSlashing).catch((e) => {
db.attesterSlashing.add(attesterSlashing).catch((e: Error) => {
logger.error("Error adding attesterSlashing to pool", {}, e);
});
},
@@ -237,7 +237,7 @@ export function getGossipHandlers(modules: ValidatorFnsModules): GossipHandlers
try {
chain.syncContributionAndProofPool.add(contributionAndProof.message);
} catch (e) {
logger.error("Error adding to contributionAndProof pool", {}, e);
logger.error("Error adding to contributionAndProof pool", {}, e as Error);
}
},
@@ -262,7 +262,7 @@ export function getGossipHandlers(modules: ValidatorFnsModules): GossipHandlers
try {
chain.syncCommitteeMessagePool.add(subnet, syncCommittee, indexInSubCommittee);
} catch (e) {
logger.error("Error adding to syncCommittee pool", {subnet}, e);
logger.error("Error adding to syncCommittee pool", {subnet}, e as Error);
}
},
};

View File

@@ -96,7 +96,7 @@ function getGossipValidatorFn<K extends GossipType>(
metrics?.gossipValidationAccept.inc({topic: type}, 1);
} catch (e) {
if (!(e instanceof GossipActionError)) {
logger.error(`Gossip validation ${type} threw a non-GossipActionError`, {}, e);
logger.error(`Gossip validation ${type} threw a non-GossipActionError`, {}, e as Error);
throw new GossipValidationError(ERR_TOPIC_VALIDATOR_IGNORE, (e as Error).message);
}

View File

@@ -274,7 +274,7 @@ export class Network implements INetwork {
}
}
} catch (e) {
this.logger.error("Error on BeaconGossipHandler.onEpoch", {epoch}, e);
this.logger.error("Error on BeaconGossipHandler.onEpoch", {epoch}, e as Error);
}
};

View File

@@ -124,7 +124,7 @@ export class PeerDiscovery {
}
}
} catch (e) {
this.logger.debug("Error deserializing ENR", {nodeId: enr.nodeId}, e);
this.logger.debug("Error deserializing ENR", {nodeId: enr.nodeId}, e as Error);
}
}
@@ -164,7 +164,7 @@ export class PeerDiscovery {
// Note: `libp2p.dial()` is what libp2p.connectionManager autoDial calls
// Note: You must listen to the connected events to listen for a successful conn upgrade
this.libp2p.dial(peer).catch((e) => {
this.libp2p.dial(peer).catch((e: Error) => {
this.logger.debug("Error dialing discovered peer", {peer: prettyPrintPeerId(peer)}, e);
});
}

View File

@@ -185,7 +185,7 @@ export class PeerManager {
return this.onStatus(peer, request.body);
}
} catch (e) {
this.logger.error("Error onRequest handler", {}, e);
this.logger.error("Error onRequest handler", {}, e as Error);
}
};
@@ -238,7 +238,7 @@ export class PeerManager {
if (e instanceof IrrelevantPeerError) {
this.logger.debug("Irrelevant peer", {peer: prettyPrintPeerId(peer), reason: e.getMetadata()});
} else {
this.logger.error("Unexpected error in assertPeerRelevance", {peer: prettyPrintPeerId(peer)}, e);
this.logger.error("Unexpected error in assertPeerRelevance", {peer: prettyPrintPeerId(peer)}, e as Error);
}
void this.goodbyeAndDisconnect(peer, GoodByeReasonCode.IRRELEVANT_NETWORK);
@@ -282,7 +282,7 @@ export class PeerManager {
const localStatus = this.chain.getStatus();
await Promise.all(peers.map(async (peer) => this.requestStatus(peer, localStatus)));
} catch (e) {
this.logger.verbose("Error requesting new status to peers", {}, e);
this.logger.verbose("Error requesting new status to peers", {}, e as Error);
}
}
@@ -324,7 +324,7 @@ export class PeerManager {
if (discv5Queries.length > 0 && !this.opts.disablePeerDiscovery) {
// It's a promise due to crypto lib calls only
this.discovery.discoverSubnetPeers(discv5Queries).catch((e) => {
this.discovery.discoverSubnetPeers(discv5Queries).catch((e: Error) => {
this.logger.error("Error on discoverSubnetPeers", {}, e);
});
}
@@ -333,7 +333,7 @@ export class PeerManager {
try {
this.discovery.discoverPeers(peersToConnect);
} catch (e) {
this.logger.error("Error on discoverPeers", {}, e);
this.logger.error("Error on discoverPeers", {}, e as Error);
}
}
@@ -419,7 +419,7 @@ export class PeerManager {
try {
await this.libp2p.hangUp(peer);
} catch (e) {
this.logger.warn("Unclean disconnect", {peer: prettyPrintPeerId(peer)}, e);
this.logger.warn("Unclean disconnect", {peer: prettyPrintPeerId(peer)}, e as Error);
}
}
@@ -428,7 +428,7 @@ export class PeerManager {
this.metrics?.peerGoodbyeSent.inc({reason: GOODBYE_KNOWN_CODES[goodbye.toString()] || ""});
await this.reqResp.goodbye(peer, BigInt(goodbye));
} catch (e) {
this.logger.verbose("Failed to send goodbye", {peer: prettyPrintPeerId(peer)}, e);
this.logger.verbose("Failed to send goodbye", {peer: prettyPrintPeerId(peer)}, e as Error);
} finally {
void this.disconnect(peer);
}

View File

@@ -97,7 +97,7 @@ export async function sendRequest<T extends ResponseBody | ResponseBody[]>(
},
DIAL_TIMEOUT,
signal
).catch((e) => {
).catch((e: Error) => {
if (e instanceof TimeoutError) {
throw new RequestInternalError({code: RequestErrorCode.DIAL_TIMEOUT});
} else {
@@ -141,7 +141,7 @@ export async function sendRequest<T extends ResponseBody | ResponseBody[]>(
collectResponses(method, maxResponses)
),
maxTotalResponseTimeout(maxResponses, options)
).catch((e) => {
).catch((e: Error) => {
// No need to close the stream here, the outter finally {} block will
if (e instanceof TimeoutError) {
throw new RequestInternalError({code: RequestErrorCode.RESPONSE_TIMEOUT});

View File

@@ -140,7 +140,7 @@ export class AttnetsService implements IAttnetsService {
try {
this.unsubscribeExpiredCommitteeSubnets(slot);
} catch (e) {
this.logger.error("Error on AttnetsService.onSlot", {slot}, e);
this.logger.error("Error on AttnetsService.onSlot", {slot}, e as Error);
}
};
@@ -153,7 +153,7 @@ export class AttnetsService implements IAttnetsService {
this.unsubscribeExpiredRandomSubnets(slot);
this.pruneExpiredKnownValidators(slot);
} catch (e) {
this.logger.error("Error on AttnetsService.onEpoch", {epoch}, e);
this.logger.error("Error on AttnetsService.onEpoch", {epoch}, e as Error);
}
};

View File

@@ -98,7 +98,7 @@ export class SyncnetsService implements ISubnetsService {
// Unsubscribe to a committee subnet from subscriptionsCommittee.
this.unsubscribeSubnets(this.subscriptionsCommittee.getExpired(slot));
} catch (e) {
this.logger.error("Error on SyncnetsService.onEpoch", {epoch}, e);
this.logger.error("Error on SyncnetsService.onEpoch", {epoch}, e as Error);
}
};

View File

@@ -104,7 +104,7 @@ export async function runNodeNotifier({
if (e instanceof ErrorAborted) {
return; // Ok
} else {
logger.error("Node notifier error", {}, e);
logger.error("Node notifier error", {}, e as Error);
}
}
}

View File

@@ -269,7 +269,7 @@ export class SyncChain {
}
this.status = SyncChainStatus.Error;
this.logger.verbose("SyncChain Error", {id: this.logId}, e);
this.logger.verbose("SyncChain Error", {id: this.logId}, e as Error);
// A batch could not be processed after max retry limit. It's likely that all peers
// in this chain are sending invalid batches repeatedly so are either malicious or faulty.
@@ -303,7 +303,7 @@ export class SyncChain {
this.requestBatches(this.peerset.keys());
} catch (e) {
// bubble the error up to the main async iterable loop
this.batchProcessor.end(e);
this.batchProcessor.end(e as Error);
}
}
@@ -397,7 +397,7 @@ export class SyncChain {
this.triggerBatchDownloader();
} catch (e) {
// bubble the error up to the main async iterable loop
this.batchProcessor.end(e);
this.batchProcessor.end(e as Error);
}
// Pre-emptively request more blocks from peers whilst we process current blocks

View File

@@ -215,7 +215,7 @@ export class BeaconSync implements IBeaconSync {
this.chain.receiveBlock(block);
this.logger.verbose("Found UnknownBlockRoot", {parentRootHex});
} catch (e) {
this.logger.verbose("Error fetching UnknownBlockRoot", {parentRootHex}, e);
this.logger.verbose("Error fetching UnknownBlockRoot", {parentRootHex}, e as Error);
} finally {
this.processingRoots.delete(parentRootHex);
}

View File

@@ -19,7 +19,7 @@ export async function fetchUnknownBlockRoot(
return blocks[0];
}
} catch (e) {
logger.debug("Error fetching UnknownBlockRoot", {i, parentRootHex}, e);
logger.debug("Error fetching UnknownBlockRoot", {i, parentRootHex}, e as Error);
}
}

View File

@@ -93,7 +93,7 @@ export class JobItemQueue<Args extends any[], R> {
await sleep(0);
}
} catch (e) {
job.reject(e);
job.reject(e as Error);
}
this.runningJobs = Math.max(0, this.runningJobs - 1);

View File

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

View File

@@ -153,7 +153,7 @@ describe("network", function () {
for (let i = 0; i < msgCount; i++) {
const voluntaryExit = ssz.phase0.SignedVoluntaryExit.defaultValue();
voluntaryExit.message.epoch = i;
netA.gossip.publishVoluntaryExit(voluntaryExit).catch((e) => {
netA.gossip.publishVoluntaryExit(voluntaryExit).catch((e: Error) => {
logger.error("Error on publishVoluntaryExit", {}, e);
});
}

View File

@@ -7,7 +7,7 @@ if (process.env.LODESTAR_PRESET === undefined) {
// blst-native initialization is syncronous
// Initialize bls here instead of in before() so it's available inside describe() blocks
init("blst-native").catch((e) => {
init("blst-native").catch((e: Error) => {
// eslint-disable-next-line no-console
console.error(e);
process.exit(1);

View File

@@ -100,7 +100,7 @@ async function runWorker(): Promise<void> {
await Promise.all(validators.map((validator) => validator.start()));
}
runWorker().catch((e) => {
runWorker().catch((e: Error) => {
console.error("Worker error", e);
process.exit(1);
});

View File

@@ -8,7 +8,7 @@ export function expectThrowsLodestarError(fn: () => void, expectedErr: LodestarE
const json = JSON.stringify(value, null, 2);
throw Error(`Expected fn to throw but returned value: \n\n\t${json}`);
} catch (e) {
expectLodestarError(e, expectedErr);
expectLodestarError(e as LodestarError<any>, expectedErr);
}
}
@@ -22,9 +22,9 @@ export async function expectRejectedWithLodestarError(
throw Error(`Expected promise to reject but returned value: \n\n\t${json}`);
} catch (e) {
if (typeof expectedErr === "string") {
expectLodestarErrorCode(e, expectedErr);
expectLodestarErrorCode(e as LodestarError<any>, expectedErr);
} else {
expectLodestarError(e, expectedErr);
expectLodestarError(e as LodestarError<any>, expectedErr);
}
}
}

View File

@@ -10,7 +10,7 @@ downloadTests(
specTestsRepoUrl: SPEC_TEST_REPO_URL,
},
console.log
).catch((e) => {
).catch((e: Error) => {
console.error(e);
process.exit(1);
});

View File

@@ -5,6 +5,6 @@ export const mochaHooks: RootHookObject = {
beforeAll: (done) => {
init("blst-native")
.then(() => done())
.catch((e) => done(e));
.catch((e: Error) => done(e));
},
};

View File

@@ -32,7 +32,7 @@ async function downloadTestsCli(): Promise<void> {
await downloadTests({specVersion, outputDir, testsToDownload}, console.log);
}
downloadTestsCli().catch((e) => {
downloadTestsCli().catch((e: Error) => {
console.error(e);
process.exit(1);
});

View File

@@ -40,7 +40,7 @@ export class AttestationService {
await Promise.all(
Array.from(dutiesByCommitteeIndex.entries()).map(async ([committeeIndex, duties]) => {
if (duties.length === 0) return;
await this.publishAttestationsAndAggregates(slot, committeeIndex, duties, signal).catch((e) => {
await this.publishAttestationsAndAggregates(slot, committeeIndex, duties, signal).catch((e: Error) => {
this.logger.error("Error on attestations routine", {slot, committeeIndex}, e);
});
})
@@ -83,7 +83,7 @@ export class AttestationService {
const logCtx = {slot, index: committeeIndex};
// Produce one attestation data per slot and committeeIndex
const attestationRes = await this.api.validator.produceAttestationData(committeeIndex, slot).catch((e) => {
const attestationRes = await this.api.validator.produceAttestationData(committeeIndex, slot).catch((e: Error) => {
throw extendError(e, "Error producing attestation");
});
const attestation = attestationRes.data;
@@ -101,7 +101,7 @@ export class AttestationService {
signedAttestations.push(await this.validatorStore.signAttestation(duty, attestation, currentEpoch));
this.logger.debug("Signed attestation", logCtxValidator);
} catch (e) {
this.logger.error("Error signing attestation", logCtxValidator, e);
this.logger.error("Error signing attestation", logCtxValidator, e as Error);
}
}
@@ -110,7 +110,7 @@ export class AttestationService {
await this.api.beacon.submitPoolAttestations(signedAttestations);
this.logger.info("Published attestations", {...logCtx, count: signedAttestations.length});
} catch (e) {
this.logger.error("Error publishing attestations", logCtx, e);
this.logger.error("Error publishing attestations", logCtx, e as Error);
}
}
@@ -141,7 +141,7 @@ export class AttestationService {
this.logger.verbose("Aggregating attestations", logCtx);
const aggregate = await this.api.validator
.getAggregatedAttestation(ssz.phase0.AttestationData.hashTreeRoot(attestation), attestation.slot)
.catch((e) => {
.catch((e: Error) => {
throw extendError(e, "Error producing aggregateAndProofs");
});
@@ -158,7 +158,7 @@ export class AttestationService {
this.logger.debug("Signed aggregateAndProofs", logCtxValidator);
}
} catch (e) {
this.logger.error("Error signing aggregateAndProofs", logCtxValidator, e);
this.logger.error("Error signing aggregateAndProofs", logCtxValidator, e as Error);
}
}
@@ -167,7 +167,7 @@ export class AttestationService {
await this.api.validator.publishAggregateAndProofs(signedAggregateAndProofs);
this.logger.info("Published aggregateAndProofs", {...logCtx, count: signedAggregateAndProofs.length});
} catch (e) {
this.logger.error("Error publishing aggregateAndProofs", logCtx, e);
this.logger.error("Error publishing aggregateAndProofs", logCtx, e as Error);
}
}
}

View File

@@ -53,7 +53,7 @@ export class AttestationDutiesService {
private runDutiesTasks = async (epoch: Epoch): Promise<void> => {
await Promise.all([
// Run pollBeaconAttesters immediately for all known local indices
this.pollBeaconAttesters(epoch, this.indicesService.getAllLocalIndices()).catch((e) => {
this.pollBeaconAttesters(epoch, this.indicesService.getAllLocalIndices()).catch((e: Error) => {
this.logger.error("Error on poll attesters", {epoch}, e);
}),
@@ -61,7 +61,7 @@ export class AttestationDutiesService {
this.indicesService
.pollValidatorIndices()
.then((newIndices) => this.pollBeaconAttesters(epoch, newIndices))
.catch((e) => {
.catch((e: Error) => {
this.logger.error("Error on poll indices and attesters", {epoch}, e);
}),
]);
@@ -90,7 +90,7 @@ export class AttestationDutiesService {
for (const epoch of [currentEpoch, nextEpoch]) {
// Download the duties and update the duties for the current and next epoch.
await this.pollBeaconAttestersForEpoch(epoch, indexArr).catch((e) => {
await this.pollBeaconAttestersForEpoch(epoch, indexArr).catch((e: Error) => {
this.logger.error("Failed to download attester duties", {epoch}, e);
});
}
@@ -124,7 +124,7 @@ export class AttestationDutiesService {
// If there are any subscriptions, push them out to the beacon node.
if (beaconCommitteeSubscriptions.length > 0) {
// TODO: Should log or throw?
await this.api.validator.prepareBeaconCommitteeSubnet(beaconCommitteeSubscriptions).catch((e) => {
await this.api.validator.prepareBeaconCommitteeSubnet(beaconCommitteeSubscriptions).catch((e: Error) => {
throw extendError(e, "Failed to subscribe to beacon committee subnets");
});
}
@@ -140,7 +140,7 @@ export class AttestationDutiesService {
}
// TODO: Implement dependentRoot logic
const attesterDuties = await this.api.validator.getAttesterDuties(epoch, indexArr).catch((e) => {
const attesterDuties = await this.api.validator.getAttesterDuties(epoch, indexArr).catch((e: Error) => {
throw extendError(e, "Failed to obtain attester duty");
});
const dependentRoot = attesterDuties.dependentRoot;

View File

@@ -39,7 +39,7 @@ export class BlockProposingService {
this.logger.warn("Multiple block proposers", {slot, count: proposers.length});
}
Promise.all(proposers.map((pubkey) => this.createAndPublishBlock(pubkey, slot))).catch((e) => {
Promise.all(proposers.map((pubkey) => this.createAndPublishBlock(pubkey, slot))).catch((e: Error) => {
this.logger.error("Error on block duties", {slot}, e);
});
};
@@ -55,18 +55,18 @@ export class BlockProposingService {
const graffiti = this.graffiti || "";
this.logger.debug("Producing block", logCtx);
const block = await this.produceBlock(slot, randaoReveal, graffiti).catch((e) => {
const block = await this.produceBlock(slot, randaoReveal, graffiti).catch((e: Error) => {
throw extendError(e, "Failed to produce block");
});
this.logger.debug("Produced block", logCtx);
const signedBlock = await this.validatorStore.signBlock(pubkey, block.data, slot);
await this.api.beacon.publishBlock(signedBlock).catch((e) => {
await this.api.beacon.publishBlock(signedBlock).catch((e: Error) => {
throw extendError(e, "Failed to publish block");
});
this.logger.info("Published block", {...logCtx, graffiti});
} catch (e) {
this.logger.error("Error proposing block", logCtx, e);
this.logger.error("Error proposing block", logCtx, e as Error);
}
}

View File

@@ -70,7 +70,7 @@ export class BlockDutiesService {
await this.pollBeaconProposersAndNotify(slot);
}
} catch (e) {
this.logger.error("Error on pollBeaconProposers", {}, e);
this.logger.error("Error on pollBeaconProposers", {}, e as Error);
} finally {
this.pruneOldDuties(computeEpochAtSlot(slot));
}
@@ -135,7 +135,7 @@ export class BlockDutiesService {
return;
}
const proposerDuties = await this.api.validator.getProposerDuties(epoch).catch((e) => {
const proposerDuties = await this.api.validator.getProposerDuties(epoch).catch((e: Error) => {
throw extendError(e, "Error on getProposerDuties");
});
const dependentRoot = proposerDuties.dependentRoot;

View File

@@ -64,13 +64,13 @@ export class SyncCommitteeService {
if (duties.length === 0) return;
// Then download, sign and publish a `SignedAggregateAndProof` for each
// validator that is elected to aggregate for this `slot` and `subcommitteeIndex`.
await this.produceAndPublishAggregates(slot, subcommitteeIndex, beaconBlockRoot, duties).catch((e) => {
await this.produceAndPublishAggregates(slot, subcommitteeIndex, beaconBlockRoot, duties).catch((e: Error) => {
this.logger.error("Error on SyncCommitteeContribution", {slot, index: subcommitteeIndex}, e);
});
})
);
} catch (e) {
this.logger.error("Error on runSyncCommitteeTasks", {slot}, e);
this.logger.error("Error on runSyncCommitteeTasks", {slot}, e as Error);
}
};
@@ -94,7 +94,7 @@ export class SyncCommitteeService {
let blockRoot = this.chainHeaderTracker.getCurrentChainHead(slot);
if (blockRoot === null) {
const blockRootData = await this.api.beacon.getBlockRoot("head").catch((e) => {
const blockRootData = await this.api.beacon.getBlockRoot("head").catch((e: Error) => {
throw extendError(e, "Error producing SyncCommitteeMessage");
});
blockRoot = blockRootData.data;
@@ -110,7 +110,7 @@ export class SyncCommitteeService {
);
this.logger.debug("Signed SyncCommitteeMessage", logCtxValidator);
} catch (e) {
this.logger.error("Error signing SyncCommitteeMessage", logCtxValidator, e);
this.logger.error("Error signing SyncCommitteeMessage", logCtxValidator, e as Error);
}
}
@@ -119,7 +119,7 @@ export class SyncCommitteeService {
await this.api.beacon.submitPoolSyncCommitteeSignatures(signatures);
this.logger.info("Published SyncCommitteeMessage", {...logCtx, count: signatures.length});
} catch (e) {
this.logger.error("Error publishing SyncCommitteeMessage", logCtx, e);
this.logger.error("Error publishing SyncCommitteeMessage", logCtx, e as Error);
}
}
@@ -152,7 +152,7 @@ export class SyncCommitteeService {
this.logger.verbose("Producing SyncCommitteeContribution", logCtx);
const contribution = await this.api.validator
.produceSyncCommitteeContribution(slot, subcommitteeIndex, beaconBlockRoot)
.catch((e) => {
.catch((e: Error) => {
throw extendError(e, "Error producing SyncCommitteeContribution");
});
@@ -169,7 +169,7 @@ export class SyncCommitteeService {
this.logger.debug("Signed SyncCommitteeContribution", logCtxValidator);
}
} catch (e) {
this.logger.error("Error signing SyncCommitteeContribution", logCtxValidator, e);
this.logger.error("Error signing SyncCommitteeContribution", logCtxValidator, e as Error);
}
}
@@ -178,7 +178,7 @@ export class SyncCommitteeService {
await this.api.validator.publishContributionAndProofs(signedContributions);
this.logger.info("Published SyncCommitteeContribution", {...logCtx, count: signedContributions.length});
} catch (e) {
this.logger.error("Error publishing SyncCommitteeContribution", logCtx, e);
this.logger.error("Error publishing SyncCommitteeContribution", logCtx, e as Error);
}
}
}

View File

@@ -93,7 +93,7 @@ export class SyncCommitteeDutiesService {
await Promise.all([
// Run pollSyncCommittees immediately for all known local indices
this.pollSyncCommittees(currentEpoch, this.indicesService.getAllLocalIndices()).catch((e) => {
this.pollSyncCommittees(currentEpoch, this.indicesService.getAllLocalIndices()).catch((e: Error) => {
this.logger.error("Error on poll SyncDuties", {epoch: currentEpoch}, e);
}),
@@ -101,7 +101,7 @@ export class SyncCommitteeDutiesService {
this.indicesService
.pollValidatorIndices()
.then((newIndices) => this.pollSyncCommittees(currentEpoch, newIndices))
.catch((e) => {
.catch((e: Error) => {
this.logger.error("Error on poll indices and SyncDuties", {epoch: currentEpoch}, e);
}),
]);
@@ -129,7 +129,7 @@ export class SyncCommitteeDutiesService {
const nextPeriodEpoch = currentEpoch + EPOCHS_PER_SYNC_COMMITTEE_PERIOD;
for (const epoch of [currentEpoch, nextPeriodEpoch]) {
// Download the duties and update the duties for the current and next period.
await this.pollSyncCommitteesForEpoch(epoch, indexArr).catch((e) => {
await this.pollSyncCommitteesForEpoch(epoch, indexArr).catch((e: Error) => {
this.logger.error("Failed to download SyncDuties", {epoch}, e);
});
}
@@ -167,7 +167,7 @@ export class SyncCommitteeDutiesService {
// If there are any subscriptions, push them out to the beacon node.
if (syncCommitteeSubscriptions.length > 0) {
// TODO: Should log or throw?
await this.api.validator.prepareSyncCommitteeSubnets(syncCommitteeSubscriptions).catch((e) => {
await this.api.validator.prepareSyncCommitteeSubnets(syncCommitteeSubscriptions).catch((e: Error) => {
throw extendError(e, "Failed to subscribe to sync committee subnets");
});
}
@@ -182,7 +182,7 @@ export class SyncCommitteeDutiesService {
return;
}
const syncDuties = await this.api.validator.getSyncCommitteeDuties(epoch, indexArr).catch((e) => {
const syncDuties = await this.api.validator.getSyncCommitteeDuties(epoch, indexArr).catch((e: Error) => {
throw extendError(e, "Failed to obtain SyncDuties");
});
const dependentRoot = syncDuties.dependentRoot;

View File

@@ -34,7 +34,7 @@ export class Clock implements IClock {
start(signal: AbortSignal): void {
for (const {timeItem, fn} of this.fns) {
this.runAtMostEvery(timeItem, signal, fn).catch((e) => {
this.runAtMostEvery(timeItem, signal, fn).catch((e: Error) => {
if (!isAbortedError(e)) {
this.logger.error("runAtMostEvery", {}, e);
}
@@ -68,7 +68,7 @@ export class Clock implements IClock {
let slotOrEpoch = timeItem === TimeItem.Slot ? slot : computeEpochAtSlot(slot);
while (!signal.aborted) {
// Must catch fn() to ensure `sleep()` is awaited both for resolve and reject
await fn(slotOrEpoch, signal).catch((e) => this.logger.error("Error on runEvery fn", {}, e));
await fn(slotOrEpoch, signal).catch((e: Error) => this.logger.error("Error on runEvery fn", {}, e));
try {
await sleep(this.timeUntilNext(timeItem), signal);
@@ -117,7 +117,7 @@ export function getCurrentSlotAround(config: IChainForkConfig, genesisTime: Numb
// function useEventStream() {
// this.stream = this.events.getEventStream([BeaconEventType.BLOCK, BeaconEventType.HEAD, BeaconEventType.CHAIN_REORG]);
// pipeToEmitter(this.stream, this).catch((e) => {
// pipeToEmitter(this.stream, this).catch((e: Error) => {
// this.logger.error("Error on stream pipe", {}, e);
// });

View File

@@ -11,7 +11,7 @@ downloadGenericSpecTests(
testsToDownload: TESTS_TO_DOWNLOAD,
},
console.log
).catch((e) => {
).catch((e: Error) => {
console.error(e);
process.exit(1);
});

View File

@@ -2,7 +2,7 @@ import {init} from "@chainsafe/bls";
// blst-native initialization is syncronous
// Initialize bls here instead of in before() so it's available inside describe() blocks
init("blst-native").catch((e) => {
init("blst-native").catch((e: Error) => {
// eslint-disable-next-line no-console
console.error(e);
process.exit(1);

View File

@@ -12,6 +12,7 @@
"strictFunctionTypes": true,
"strictBindCallApply": true,
"strictPropertyInitialization": true,
"useUnknownInCatchVariables": true,
"noImplicitAny": true,
"noImplicitThis": true,
"noImplicitReturns": true,

View File

@@ -8328,10 +8328,10 @@ object.values@^1.1.3:
define-properties "^1.1.3"
es-abstract "^1.18.2"
observable-fns@^0.5.1:
version "0.5.1"
resolved "https://registry.yarnpkg.com/observable-fns/-/observable-fns-0.5.1.tgz#9b56478690dd0fa8603e3a7e7d2975d88bca0904"
integrity sha512-wf7g4Jpo1Wt2KIqZKLGeiuLOEMqpaOZ5gJn7DmSdqXgTdxRwSdBhWegQQpPteQ2gZvzCKqNNpwb853wcpA0j7A==
observable-fns@^0.6.1:
version "0.6.1"
resolved "https://registry.yarnpkg.com/observable-fns/-/observable-fns-0.6.1.tgz#636eae4fdd1132e88c0faf38d33658cc79d87e37"
integrity sha512-9gRK4+sRWzeN6AOewNBTLXir7Zl/i3GB6Yl26gK4flxz8BXVpD3kt8amREmWNb0mxYOGDotvE5a4N+PtGGKdkg==
once@^1.3.0, once@^1.3.1, once@^1.4.0:
version "1.4.0"
@@ -10379,15 +10379,15 @@ text-table@^0.2.0:
resolved "https://registry.yarnpkg.com/text-table/-/text-table-0.2.0.tgz#7f5ee823ae805207c00af2df4a84ec3fcfa570b4"
integrity sha1-f17oI66AUgfACvLfSoTsP8+lcLQ=
threads@^1.6.3:
version "1.6.4"
resolved "https://registry.yarnpkg.com/threads/-/threads-1.6.4.tgz#cf8ad992d6014b492f20cf3566048475a3045192"
integrity sha512-A+9MQFAUha9W8MjIPmrvETy98qVmZFr5Unox9D95y7kvz3fBpGiFS7JOZs07B2KvTHoRNI5MrGudRVeCmv4Alw==
threads@^1.6.5:
version "1.6.5"
resolved "https://registry.yarnpkg.com/threads/-/threads-1.6.5.tgz#5cee7f139e3e147c5a64f0134844ee92469932a5"
integrity sha512-yL1NN4qZ25crW8wDoGn7TqbENJ69w3zCEjIGXpbqmQ4I+QHrG8+DLaZVKoX74OQUXWCI2lbbrUxDxAbr1xjDGQ==
dependencies:
callsites "^3.1.0"
debug "^4.2.0"
is-observable "^2.1.0"
observable-fns "^0.5.1"
observable-fns "^0.6.1"
optionalDependencies:
tiny-worker ">= 2"
@@ -10753,10 +10753,10 @@ typescript@3.8.3:
resolved "https://registry.yarnpkg.com/typescript/-/typescript-3.8.3.tgz#409eb8544ea0335711205869ec458ab109ee1061"
integrity sha512-MYlEfn5VrLNsgudQTVJeNaQFUAI7DkhnOjdpAp4T+ku1TfQClewlbSuTVHiA+8skNBgaf02TL/kLOvig4y3G8w==
typescript@^4.2.0:
version "4.2.4"
resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.2.4.tgz#8610b59747de028fda898a8aef0e103f156d0961"
integrity sha512-V+evlYHZnQkaz8TRBuxTA92yZBPotr5H+WhQ7bD3hZUndx5tGOa1fuCgeSjxAzM1RiN5IzvadIXTVefuuwZCRg==
typescript@^4.4.0:
version "4.4.2"
resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.4.2.tgz#6d618640d430e3569a1dfb44f7d7e600ced3ee86"
integrity sha512-gzP+t5W4hdy4c+68bfcv0t400HVJMMd2+H9B7gae1nQlBzCqvrXX+6GL/b3GAgyTH966pzrZ70/fRjwAtZksSQ==
uglify-js@^3.1.4:
version "3.13.4"