Skip to content

Commit

Permalink
Remove unnecessary return await (#5117)
Browse files Browse the repository at this point in the history
* Add eslint rule to disallow unnecessary return await

* Fix unnecessary return await statements
  • Loading branch information
nflaig authored Feb 13, 2023
1 parent 93ae89e commit 4cec93e
Show file tree
Hide file tree
Showing 33 changed files with 57 additions and 59 deletions.
1 change: 1 addition & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@ module.exports = {
"no-consecutive-blank-lines": 0,
"no-console": "error",
"no-var": "error",
"no-return-await": "error",
"object-curly-spacing": ["error", "never"],
"object-literal-sort-keys": 0,
"no-prototype-builtins": 0,
Expand Down
6 changes: 3 additions & 3 deletions packages/api/src/utils/client/httpClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,15 +149,15 @@ export class HttpClient implements IHttpClient {
}

async json<T>(opts: FetchOpts): Promise<{status: HttpStatusCode; body: T}> {
return await this.requestWithBodyWithRetries<T>(opts, (res) => res.json() as Promise<T>);
return this.requestWithBodyWithRetries<T>(opts, (res) => res.json() as Promise<T>);
}

async request(opts: FetchOpts): Promise<{status: HttpStatusCode; body: void}> {
return await this.requestWithBodyWithRetries<void>(opts, async () => undefined);
return this.requestWithBodyWithRetries<void>(opts, async () => undefined);
}

async arrayBuffer(opts: FetchOpts): Promise<{status: HttpStatusCode; body: ArrayBuffer}> {
return await this.requestWithBodyWithRetries<ArrayBuffer>(opts, (res) => res.arrayBuffer());
return this.requestWithBodyWithRetries<ArrayBuffer>(opts, (res) => res.arrayBuffer());
}

private async requestWithBodyWithRetries<T>(
Expand Down
2 changes: 1 addition & 1 deletion packages/beacon-node/src/api/impl/beacon/blocks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ export function getBeaconBlockApi({
} else {
signedBlock = await executionBuilder.submitBlindedBlock(signedBlindedBlock);
}
return await this.publishBlock(signedBlock);
return this.publishBlock(signedBlock);
},

async publishBlock(signedBlock) {
Expand Down
4 changes: 2 additions & 2 deletions packages/beacon-node/src/api/impl/beacon/blocks/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,15 +71,15 @@ async function resolveBlockIdOrNull(
if (blockId.startsWith("0x")) {
const blockHash = fromHexString(blockId);
blockSummary = forkChoice.getBlock(blockHash);
getBlockByBlockArchive = async () => await db.blockArchive.getByRoot(blockHash);
getBlockByBlockArchive = async () => db.blockArchive.getByRoot(blockHash);
} else {
// block id must be slot
const blockSlot = parseInt(blockId, 10);
if (isNaN(blockSlot) && isNaN(blockSlot - 0)) {
throw new ValidationError(`Invalid block id '${blockId}'`, "blockId");
}
blockSummary = forkChoice.getCanonicalBlockAtSlot(blockSlot);
getBlockByBlockArchive = async () => await db.blockArchive.get(blockSlot);
getBlockByBlockArchive = async () => db.blockArchive.get(blockSlot);
}

if (blockSummary) {
Expand Down
2 changes: 1 addition & 1 deletion packages/beacon-node/src/api/impl/beacon/state/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export function getBeaconStateApi({
async function getState(
stateId: routes.beacon.StateId
): Promise<{state: BeaconStateAllForks; executionOptimistic: boolean}> {
return await resolveStateId(config, chain, db, stateId);
return resolveStateId(config, chain, db, stateId);
}

return {
Expand Down
6 changes: 3 additions & 3 deletions packages/beacon-node/src/api/impl/beacon/state/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,19 +56,19 @@ async function resolveStateIdOrNull(
): Promise<{state: BeaconStateAllForks | null; executionOptimistic: boolean}> {
stateId = String(stateId).toLowerCase();
if (stateId === "head" || stateId === "genesis" || stateId === "finalized" || stateId === "justified") {
return await stateByName(db, chain.stateCache, chain.forkChoice, stateId);
return stateByName(db, chain.stateCache, chain.forkChoice, stateId);
}

if (stateId.startsWith("0x")) {
return await stateByRoot(db, chain.stateCache, chain.forkChoice, stateId);
return stateByRoot(db, chain.stateCache, chain.forkChoice, stateId);
}

// state id must be slot
const slot = parseInt(stateId, 10);
if (isNaN(slot) && isNaN(slot - 0)) {
throw new ValidationError(`Invalid state id '${stateId}'`, "stateId");
}
return await stateBySlot(config, db, chain.stateCache, chain.forkChoice, slot, opts);
return stateBySlot(config, db, chain.stateCache, chain.forkChoice, slot, opts);
}

/**
Expand Down
2 changes: 1 addition & 1 deletion packages/beacon-node/src/chain/bls/multithread/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,7 @@ export class BlsMultiThreadWorkerPool implements IBlsVerifier {
throw this.workers[0].status.error;
}

return await new Promise<boolean>((resolve, reject) => {
return new Promise<boolean>((resolve, reject) => {
const job = {resolve, reject, addedTimeMs: Date.now(), workReq};

// Append batchable sets to `bufferedJobs`, starting a timeout to push them into `jobs`.
Expand Down
8 changes: 4 additions & 4 deletions packages/beacon-node/src/chain/chain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -338,7 +338,7 @@ export class BeaconChain implements IBeaconChain {
const currentEpochStartSlot = computeStartSlotAtEpoch(this.clock.currentEpoch);
const head = this.forkChoice.getHead();
const bestSlot = currentEpochStartSlot > head.slot ? currentEpochStartSlot : head.slot;
return await this.regen.getBlockSlotState(head.blockRoot, bestSlot, RegenCaller.getDuties);
return this.regen.getBlockSlotState(head.blockRoot, bestSlot, RegenCaller.getDuties);
}

async getCanonicalBlockAtSlot(slot: Slot): Promise<allForks.SignedBeaconBlock | null> {
Expand All @@ -350,7 +350,7 @@ export class BeaconChain implements IBeaconChain {
if (!block) {
return null;
}
return await this.db.block.get(fromHexString(block.blockRoot));
return this.db.block.get(fromHexString(block.blockRoot));
}

produceBlock(blockAttributes: BlockAttributes): Promise<{block: allForks.BeaconBlock; blockValue: Wei}> {
Expand Down Expand Up @@ -436,11 +436,11 @@ export class BeaconChain implements IBeaconChain {
}

async processBlock(block: BlockInput, opts?: ImportBlockOpts): Promise<void> {
return await this.blockProcessor.processBlocksJob([block], opts);
return this.blockProcessor.processBlocksJob([block], opts);
}

async processChainSegment(blocks: BlockInput[], opts?: ImportBlockOpts): Promise<void> {
return await this.blockProcessor.processBlocksJob(blocks, opts);
return this.blockProcessor.processBlocksJob(blocks, opts);
}

getStatus(): phase0.Status {
Expand Down
10 changes: 5 additions & 5 deletions packages/beacon-node/src/chain/regen/regen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,19 +60,19 @@ export class StateRegenerator implements IStateRegenerator {
// We may have the checkpoint state with parent root inside the checkpoint state cache
// through gossip validation.
if (parentEpoch < blockEpoch) {
return await this.getCheckpointState({root: block.parentRoot, epoch: blockEpoch}, rCaller);
return this.getCheckpointState({root: block.parentRoot, epoch: blockEpoch}, rCaller);
}

// Otherwise, get the state normally.
return await this.getState(parentBlock.stateRoot, rCaller);
return this.getState(parentBlock.stateRoot, rCaller);
}

/**
* Get state after block `cp.root` dialed forward to first slot of `cp.epoch`
*/
async getCheckpointState(cp: phase0.Checkpoint, rCaller: RegenCaller): Promise<CachedBeaconStateAllForks> {
const checkpointStartSlot = computeStartSlotAtEpoch(cp.epoch);
return await this.getBlockSlotState(toHexString(cp.root), checkpointStartSlot, rCaller);
return this.getBlockSlotState(toHexString(cp.root), checkpointStartSlot, rCaller);
}

/**
Expand Down Expand Up @@ -100,14 +100,14 @@ export class StateRegenerator implements IStateRegenerator {
// If a checkpoint state exists with the given checkpoint root, it either is in requested epoch
// or needs to have empty slots processed until the requested epoch
if (latestCheckpointStateCtx) {
return await processSlotsByCheckpoint(this.modules, latestCheckpointStateCtx, slot);
return processSlotsByCheckpoint(this.modules, latestCheckpointStateCtx, slot);
}

// Otherwise, use the fork choice to get the stateRoot from block at the checkpoint root
// regenerate that state,
// then process empty slots until the requested epoch
const blockStateCtx = await this.getState(block.stateRoot, rCaller);
return await processSlotsByCheckpoint(this.modules, blockStateCtx, slot);
return processSlotsByCheckpoint(this.modules, blockStateCtx, slot);
}

/**
Expand Down
4 changes: 2 additions & 2 deletions packages/beacon-node/src/db/repositories/blockArchive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ export class BlockArchiveRepository extends Repository<Slot, allForks.SignedBeac

async getByRoot(root: Root): Promise<allForks.SignedBeaconBlock | null> {
const slot = await this.getSlotByRoot(root);
return slot !== null ? await this.get(slot) : null;
return slot !== null ? this.get(slot) : null;
}

async getBinaryEntryByRoot(root: Root): Promise<IKeyValue<Slot, Buffer> | null> {
Expand All @@ -130,7 +130,7 @@ export class BlockArchiveRepository extends Repository<Slot, allForks.SignedBeac

async getByParentRoot(root: Root): Promise<allForks.SignedBeaconBlock | null> {
const slot = await this.getSlotByParentRoot(root);
return slot !== null ? await this.get(slot) : null;
return slot !== null ? this.get(slot) : null;
}

async getSlotByRoot(root: Root): Promise<Slot | null> {
Expand Down
2 changes: 1 addition & 1 deletion packages/beacon-node/src/eth1/eth1DataCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export class Eth1DataCache {
}

async get({timestampRange}: {timestampRange: {gte: number; lte: number}}): Promise<phase0.Eth1DataOrdered[]> {
return await this.db.eth1Data.values(timestampRange);
return this.db.eth1Data.values(timestampRange);
}

async add(eth1Datas: (phase0.Eth1DataOrdered & {timestamp: number})[]): Promise<void> {
Expand Down
2 changes: 1 addition & 1 deletion packages/beacon-node/src/eth1/eth1DepositDataTracker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ export class Eth1DepositDataTracker {

// Eth1 data may change due to the vote included in this block
const newEth1Data = becomesNewEth1Data(state, eth1DataVoteView) ? eth1DataVoteView : state.eth1Data;
return await getDeposits(state, newEth1Data, this.depositsCache.get.bind(this.depositsCache));
return getDeposits(state, newEth1Data, this.depositsCache.get.bind(this.depositsCache));
}

/**
Expand Down
2 changes: 1 addition & 1 deletion packages/beacon-node/src/eth1/eth1DepositsCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ export class Eth1DepositsCache {
lastProcessedDepositBlockNumber: number | null
): Promise<(phase0.Eth1Data & Eth1Block)[]> {
const highestBlock = blocks[blocks.length - 1]?.blockNumber;
return await getEth1DataForBlocks(
return getEth1DataForBlocks(
blocks,
this.db.depositEvent.valuesStream({lte: highestBlock, reverse: true}),
await this.db.depositDataRoot.getDepositRootTree(),
Expand Down
6 changes: 3 additions & 3 deletions packages/beacon-node/src/eth1/provider/eth1Provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ export class Eth1Provider implements IEth1Provider {
async getBlockByNumber(blockNumber: number | "latest"): Promise<EthJsonRpcBlockRaw | null> {
const method = "eth_getBlockByNumber";
const blockNumberHex = typeof blockNumber === "string" ? blockNumber : numToQuantity(blockNumber);
return await this.rpc.fetch<IEthJsonRpcReturnTypes[typeof method]>(
return this.rpc.fetch<IEthJsonRpcReturnTypes[typeof method]>(
// false = include only transaction roots, not full objects
{method, params: [blockNumberHex, false]},
getBlockByNumberOpts
Expand All @@ -113,7 +113,7 @@ export class Eth1Provider implements IEth1Provider {

async getBlockByHash(blockHashHex: string): Promise<EthJsonRpcBlockRaw | null> {
const method = "eth_getBlockByHash";
return await this.rpc.fetch<IEthJsonRpcReturnTypes[typeof method]>(
return this.rpc.fetch<IEthJsonRpcReturnTypes[typeof method]>(
// false = include only transaction roots, not full objects
{method, params: [blockHashHex, false]},
getBlockByHashOpts
Expand All @@ -131,7 +131,7 @@ export class Eth1Provider implements IEth1Provider {

async getCode(address: string): Promise<string> {
const method = "eth_getCode";
return await this.rpc.fetch<IEthJsonRpcReturnTypes[typeof method]>({method, params: [address, "latest"]});
return this.rpc.fetch<IEthJsonRpcReturnTypes[typeof method]>({method, params: [address, "latest"]});
}

async getLogs(options: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ export class JsonRpcHttpClient implements IJsonRpcHttpClient {
if (attempt > 1) {
this.opts?.metrics?.retryCount.inc({routeId});
}
return await this.fetchJson({jsonrpc: "2.0", id: this.id++, ...payload}, opts);
return this.fetchJson({jsonrpc: "2.0", id: this.id++, ...payload}, opts);
},
{
retries: opts?.retryAttempts ?? this.opts?.retryAttempts ?? 1,
Expand Down
5 changes: 1 addition & 4 deletions packages/beacon-node/src/execution/engine/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -337,10 +337,7 @@ export class ExecutionEngineHttp implements IExecutionEngine {
transitionConfiguration: TransitionConfigurationV1
): Promise<TransitionConfigurationV1> {
const method = "engine_exchangeTransitionConfigurationV1";
return await this.rpc.fetchWithRetries<
EngineApiRpcReturnTypes[typeof method],
EngineApiRpcParamTypes[typeof method]
>(
return this.rpc.fetchWithRetries<EngineApiRpcReturnTypes[typeof method], EngineApiRpcParamTypes[typeof method]>(
{
method,
params: [transitionConfiguration],
Expand Down
2 changes: 1 addition & 1 deletion packages/beacon-node/src/network/discv5/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ export class Discv5Worker extends (EventEmitter as {new (): StrictEventEmitter<E

async metrics(): Promise<string> {
if (this.status.status === "started") {
return await this.status.workerApi.metrics();
return this.status.workerApi.metrics();
} else {
return "";
}
Expand Down
4 changes: 2 additions & 2 deletions packages/beacon-node/src/network/gossip/gossipsub.ts
Original file line number Diff line number Diff line change
Expand Up @@ -209,15 +209,15 @@ export class Eth2Gossipsub extends GossipSub {

async publishBeaconAggregateAndProof(aggregateAndProof: phase0.SignedAggregateAndProof): Promise<number> {
const fork = this.config.getForkName(aggregateAndProof.message.aggregate.data.slot);
return await this.publishObject<GossipType.beacon_aggregate_and_proof>(
return this.publishObject<GossipType.beacon_aggregate_and_proof>(
{type: GossipType.beacon_aggregate_and_proof, fork},
aggregateAndProof
);
}

async publishBeaconAttestation(attestation: phase0.Attestation, subnet: number): Promise<number> {
const fork = this.config.getForkName(attestation.data.slot);
return await this.publishObject<GossipType.beacon_attestation>(
return this.publishObject<GossipType.beacon_attestation>(
{type: GossipType.beacon_attestation, fork, subnet},
attestation
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export function createValidatorFnsByType(
jobQueues,
(jobQueue): GossipValidatorFn => {
return async function gossipValidatorFnWithQueue(topic, gossipMsg, propagationSource, seenTimestampSec) {
return await jobQueue.push(topic, gossipMsg, propagationSource, seenTimestampSec);
return jobQueue.push(topic, gossipMsg, propagationSource, seenTimestampSec);
};
}
);
Expand Down
2 changes: 1 addition & 1 deletion packages/beacon-node/src/network/network.ts
Original file line number Diff line number Diff line change
Expand Up @@ -303,7 +303,7 @@ export class Network implements INetwork {
}

async getEnr(): Promise<SignableENR | undefined> {
return await this.peerManager["discovery"]?.discv5.enr();
return this.peerManager["discovery"]?.discv5.enr();
}

getConnectionsByPeer(): Map<string, Connection[]> {
Expand Down
2 changes: 1 addition & 1 deletion packages/beacon-node/src/sync/range/range.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ export class RangeSync extends (EventEmitter as {new (): RangeSyncEmitter}) {

/** Convenience method for `SyncChain` */
private downloadBeaconBlocksByRange: SyncChainFns["downloadBeaconBlocksByRange"] = async (peerId, request) => {
return await this.network.beaconBlocksMaybeBlobsByRange(peerId, request);
return this.network.beaconBlocksMaybeBlobsByRange(peerId, request);
};

/** Convenience method for `SyncChain` */
Expand Down
2 changes: 1 addition & 1 deletion packages/beacon-node/test/utils/node/beacon.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ export async function getDevBeaconNode(
}

const beaconConfig = createIBeaconConfig(config, anchorState.genesisValidatorsRoot);
return await BeaconNode.init({
return BeaconNode.init({
opts: options as IBeaconNodeOptions,
config: beaconConfig,
db,
Expand Down
2 changes: 1 addition & 1 deletion packages/beacon-node/test/utils/runEl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ async function waitForELOffline(ENGINE_PORT: string): Promise<void> {
}

async function isPortInUse(port: number): Promise<boolean> {
return await new Promise<boolean>((resolve, reject) => {
return new Promise<boolean>((resolve, reject) => {
const server = net.createServer();
server.once("error", function (err) {
if (((err as unknown) as {code: string}).code === "EADDRINUSE") {
Expand Down
4 changes: 2 additions & 2 deletions packages/cli/src/cmds/beacon/initBeaconState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,15 +114,15 @@ export async function initBeaconState(

// See if we can sync state using checkpoint sync args or else start from genesis
if (args.checkpointState) {
return await readWSState(
return readWSState(
lastDbState,
{checkpointState: args.checkpointState, wssCheckpoint: args.wssCheckpoint},
chainForkConfig,
db,
logger
);
} else if (args.checkpointSyncUrl) {
return await fetchWSStateFromBeaconApi(
return fetchWSStateFromBeaconApi(
lastDbState,
{checkpointSyncUrl: args.checkpointSyncUrl, wssCheckpoint: args.wssCheckpoint},
chainForkConfig,
Expand Down
8 changes: 4 additions & 4 deletions packages/cli/src/config/peerId.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@ async function createFromParts(multihash: Uint8Array, privKey?: Uint8Array, pubK
if (privKey != null) {
const key = await unmarshalPrivateKey(privKey);

return await createFromPrivKey(key);
return createFromPrivKey(key);
} else if (pubKey != null) {
const key = unmarshalPublicKey(pubKey);

return await createFromPubKey(key);
return createFromPubKey(key);
}

return peerIdFromBytes(multihash);
Expand All @@ -37,7 +37,7 @@ export function exportToJSON(peerId: PeerId, excludePrivateKey?: boolean): PeerI
}

export async function createFromJSON(obj: PeerIdJSON): Promise<PeerId> {
return await createFromParts(
return createFromParts(
uint8ArrayFromString(obj.id, "base58btc"),
obj.privKey != null ? uint8ArrayFromString(obj.privKey, "base64pad") : undefined,
obj.pubKey != null ? uint8ArrayFromString(obj.pubKey, "base64pad") : undefined
Expand All @@ -49,5 +49,5 @@ export function writePeerId(filepath: string, peerId: PeerId): void {
}

export async function readPeerId(filepath: string): Promise<PeerId> {
return await createFromJSON(readFile(filepath));
return createFromJSON(readFile(filepath));
}
2 changes: 1 addition & 1 deletion packages/cli/src/util/file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ export async function downloadOrLoadFile(pathOrUrl: string): Promise<Uint8Array>
const res = await got.get(pathOrUrl, {encoding: "binary"});
return res.rawBody;
} else {
return await fs.promises.readFile(pathOrUrl);
return fs.promises.readFile(pathOrUrl);
}
}

Expand Down
Loading

0 comments on commit 4cec93e

Please sign in to comment.