Skip to content
This repository has been archived by the owner on Jun 11, 2024. It is now read-only.

Commit

Permalink
♻️ Update chain to use eslint
Browse files Browse the repository at this point in the history
  • Loading branch information
shuse2 committed Apr 21, 2020
1 parent 4c40891 commit 63e228c
Show file tree
Hide file tree
Showing 41 changed files with 403 additions and 319 deletions.
1 change: 0 additions & 1 deletion .eslintrc.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ module.exports = {
rules: {
'arrow-body-style': 'off',
'dot-notation': 'off',
'@typescript-eslint/unbound-method': 'off',
'@typescript-eslint/no-magic-numbers': 'off',
'@typescript-eslint/unbound-method': 'off',
'@typescript-eslint/no-require-imports': 'off',
Expand Down
2 changes: 2 additions & 0 deletions elements/lisk-chain/.eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
dist-node
jest.config.js
7 changes: 7 additions & 0 deletions elements/lisk-chain/.eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
module.exports = {
extends: '../../.eslintrc.js',
parserOptions: {
project: './tsconfig.json',
tsconfigRootDir: __dirname,
},
};
14 changes: 9 additions & 5 deletions elements/lisk-chain/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@
"scripts": {
"clean": "./scripts/clean.sh",
"format": "prettier --write '**/*'",
"lint": "tslint --format verbose --project .",
"lint:fix": "npm run lint -- --fix",
"lint": "eslint . --ext .js,.ts",
"lint:fix": "eslint --fix --ext .js,.ts .",
"test": "jest",
"test:watch": "npm test -- --watch",
"prebuild": "rm -r dist-node/* || mkdir dist-node || true",
Expand All @@ -50,6 +50,13 @@
"@types/lodash.clonedeep": "4.5.6",
"@types/lodash.isequal": "4.5.5",
"@types/randomstring": "1.1.6",
"@typescript-eslint/eslint-plugin": "2.28.0",
"@typescript-eslint/parser": "2.28.0",
"eslint": "6.8.0",
"eslint-config-lisk-base": "1.2.2",
"eslint-config-prettier": "6.10.0",
"eslint-plugin-import": "2.20.1",
"eslint-plugin-jest": "23.8.2",
"faker": "4.1.0",
"jest": "25.1.0",
"jest-extended": "0.11.5",
Expand All @@ -61,9 +68,6 @@
"ts-jest": "25.2.1",
"ts-node": "8.6.2",
"tsconfig-paths": "3.9.0",
"tslint": "6.0.0",
"tslint-config-prettier": "1.18.0",
"tslint-immutable": "6.0.1",
"typescript": "3.8.3"
}
}
4 changes: 3 additions & 1 deletion elements/lisk-chain/src/account.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
*
* Removal or modification of this copyright notice is prohibited.
*/
// eslint-disable-next-line import/no-cycle
import { AccountJSON } from './types';

export const accountDefaultValues = {
Expand Down Expand Up @@ -109,6 +110,7 @@ export class Account {
unvoteHeight: unlock.unvoteHeight,
}))
: [];
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
this.totalVotesReceived = BigInt(accountInfo.totalVotesReceived ?? 0);
this.delegate = {
lastForgedHeight: accountInfo.delegate?.lastForgedHeight ?? 0,
Expand All @@ -126,7 +128,7 @@ export class Account {
optionalKeys: accountInfo.keys?.optionalKeys?.length
? [...accountInfo.keys.optionalKeys]
: [],
numberOfSignatures: accountInfo.keys?.numberOfSignatures || 0,
numberOfSignatures: accountInfo.keys?.numberOfSignatures ?? 0,
};

// TODO: Remove with https://github.com/LiskHQ/lisk-sdk/issues/5058
Expand Down
10 changes: 5 additions & 5 deletions elements/lisk-chain/src/block_reward.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,10 +117,10 @@ export const calculateSupply = (
}
}

// tslint:disable-next-line prefer-for-of no-let
// eslint-disable-next-line @typescript-eslint/prefer-for-of
for (let i = 0; i < rewards.length; i += 1) {
const reward = rewards[i];
supply = supply + BigInt(reward[0]) * BigInt(reward[1]);
supply += BigInt(reward[0]) * BigInt(reward[1]);
}

return supply;
Expand All @@ -131,7 +131,7 @@ export const getTotalFees = (
): { readonly totalFee: bigint; readonly totalMinFee: bigint } =>
blockInstance.transactions.reduce(
(prev, current) => {
const minFee = current.minFee;
const { minFee } = current;

return {
totalFee: prev.totalFee + current.fee,
Expand Down Expand Up @@ -165,7 +165,7 @@ export const applyFeeAndRewards = async (
generator.balance += givenFee > 0 ? givenFee : BigInt(0);
const totalFeeBurntStr = await stateStore.chain.get(CHAIN_STATE_BURNT_FEE);
// tslint:disable-next-line no-let
let totalFeeBurnt = BigInt(totalFeeBurntStr || 0);
let totalFeeBurnt = BigInt(totalFeeBurntStr ?? 0);
totalFeeBurnt += givenFee > 0 ? totalMinFee : BigInt(0);

// Update state store
Expand Down Expand Up @@ -194,7 +194,7 @@ export const undoFeeAndRewards = async (
generator.balance -= totalFee - totalMinFee;
const totalFeeBurntStr = await stateStore.chain.get(CHAIN_STATE_BURNT_FEE);
// tslint:disable-next-line no-let
let totalFeeBurnt = BigInt(totalFeeBurntStr || 0);
let totalFeeBurnt = BigInt(totalFeeBurntStr ?? 0);
totalFeeBurnt -= totalMinFee;

// Update state store
Expand Down
120 changes: 63 additions & 57 deletions elements/lisk-chain/src/chain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ const saveBlock = async (
blockJSON: BlockJSON,
tx: StorageTransaction,
): Promise<void> => {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (!tx) {
throw new Error('Block should only be saved in a database tx');
}
Expand All @@ -123,7 +124,7 @@ const saveBlock = async (
const applyConfirmedStep = async (
blockInstance: BlockInstance,
stateStore: StateStore,
) => {
): Promise<void> => {
if (blockInstance.transactions.length <= 0) {
return;
}
Expand Down Expand Up @@ -181,6 +182,7 @@ const undoConfirmedStep = async (
}
};

// eslint-disable-next-line new-cap
const debug = Debug('lisk:chain');

export class Chain {
Expand Down Expand Up @@ -248,10 +250,12 @@ export class Chain {
totalAmount,
};
this.blockReward = {
calculateMilestone: height =>
calculateMilestone: (height: number): number =>
calculateMilestone(height, this.blockRewardArgs),
calculateReward: height => calculateReward(height, this.blockRewardArgs),
calculateSupply: height => calculateSupply(height, this.blockRewardArgs),
calculateReward: (height: number): bigint =>
calculateReward(height, this.blockRewardArgs),
calculateSupply: (height: number): bigint =>
calculateSupply(height, this.blockRewardArgs),
};
this.constants = {
stateBlockSize,
Expand Down Expand Up @@ -325,7 +329,7 @@ export class Chain {
this.dataAccess.resetBlockHeaderCache();
}

public async newStateStore(skipLastHeights: number = 0): Promise<StateStore> {
public async newStateStore(skipLastHeights = 0): Promise<StateStore> {
const fromHeight = Math.max(
1,
this._lastBlock.height - this.constants.stateBlockSize - skipLastHeights,
Expand All @@ -337,6 +341,7 @@ export class Chain {
);

const lastBlockReward = this.blockReward.calculateReward(
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
lastBlockHeaders[0]?.height ?? 1,
);

Expand All @@ -347,34 +352,6 @@ export class Chain {
});
}

private async _cacheBlockHeaders(
storageLastBlock: BlockInstance,
): Promise<void> {
// Cache the block headers (size=DEFAULT_MAX_BLOCK_HEADER_CACHE)
const fromHeight = Math.max(
storageLastBlock.height - DEFAULT_MAX_BLOCK_HEADER_CACHE,
1,
);
const toHeight = storageLastBlock.height;

debug(
{ h: storageLastBlock.height, fromHeight, toHeight },
'Cache block headers during chain init',
);
const blockHeaders = await this.dataAccess.getBlockHeadersByHeightBetween(
fromHeight,
toHeight,
);
const sortedBlockHeaders = [...blockHeaders].sort(
(a: BlockHeader, b: BlockHeader) => a.height - b.height,
);

for (const blockHeader of sortedBlockHeaders) {
debug({ height: blockHeader.height }, 'Add block header to cache');
this.dataAccess.addBlockHeader(blockHeader);
}
}

public validateBlockHeader(block: BlockInstance, blockBytes: Buffer): void {
validatePreviousBlockProperty(block, this.genesisBlock);
validateSignature(block, blockBytes, this._networkIdentifier);
Expand All @@ -394,6 +371,7 @@ export class Chain {
validatePayload(block, this.constants.maxPayloadLength);

// Update id
// eslint-disable-next-line no-param-reassign
block.id = blocksUtils.getId(blockBytes);
}

Expand Down Expand Up @@ -426,7 +404,7 @@ export class Chain {
await this.blocksVerify.checkTransactions(blockInstance);
}

// tslint:disable-next-line prefer-function-over-method
// eslint-disable-next-line class-methods-use-this
public async apply(
blockInstance: BlockInstance,
stateStore: StateStore,
Expand All @@ -435,7 +413,7 @@ export class Chain {
await applyFeeAndRewards(blockInstance, stateStore);
}

// tslint:disable-next-line prefer-function-over-method
// eslint-disable-next-line class-methods-use-this
public async applyGenesis(
blockInstance: BlockInstance,
stateStore: StateStore,
Expand Down Expand Up @@ -475,7 +453,7 @@ export class Chain {
});
}

// tslint:disable-next-line prefer-function-over-method
// eslint-disable-next-line class-methods-use-this
public async undo(
blockInstance: BlockInstance,
stateStore: StateStore,
Expand All @@ -484,26 +462,6 @@ export class Chain {
await undoConfirmedStep(blockInstance, stateStore);
}

private async _deleteLastBlock(
lastBlock: BlockInstance,
tx?: StorageTransaction,
): Promise<BlockInstance> {
if (lastBlock.height === 1) {
throw new Error('Cannot delete genesis block');
}
const block = await this.dataAccess.getBlockByID(
lastBlock.previousBlockId as string,
);

if (!block) {
throw new Error('PreviousBlock is null');
}

await this.storage.entities.Block.delete({ id: lastBlock.id }, {}, tx);

return block;
}

public async remove(
block: BlockInstance,
stateStore: StateStore,
Expand Down Expand Up @@ -641,7 +599,7 @@ export class Chain {
}

// Temporally added because DPoS uses totalEarning to calculate the vote weight change
// tslint:disable-next-line prefer-function-over-method
// eslint-disable-next-line class-methods-use-this
public getTotalEarningAndBurnt(
blockInstance: BlockInstance,
): { readonly totalEarning: bigint; readonly totalBurnt: bigint } {
Expand All @@ -652,4 +610,52 @@ export class Chain {
totalBurnt: totalMinFee,
};
}

private async _cacheBlockHeaders(
storageLastBlock: BlockInstance,
): Promise<void> {
// Cache the block headers (size=DEFAULT_MAX_BLOCK_HEADER_CACHE)
const fromHeight = Math.max(
storageLastBlock.height - DEFAULT_MAX_BLOCK_HEADER_CACHE,
1,
);
const toHeight = storageLastBlock.height;

debug(
{ h: storageLastBlock.height, fromHeight, toHeight },
'Cache block headers during chain init',
);
const blockHeaders = await this.dataAccess.getBlockHeadersByHeightBetween(
fromHeight,
toHeight,
);
const sortedBlockHeaders = [...blockHeaders].sort(
(a: BlockHeader, b: BlockHeader) => a.height - b.height,
);

for (const blockHeader of sortedBlockHeaders) {
debug({ height: blockHeader.height }, 'Add block header to cache');
this.dataAccess.addBlockHeader(blockHeader);
}
}

private async _deleteLastBlock(
lastBlock: BlockInstance,
tx?: StorageTransaction,
): Promise<BlockInstance> {
if (lastBlock.height === 1) {
throw new Error('Cannot delete genesis block');
}
const block = await this.dataAccess.getBlockByID(
lastBlock.previousBlockId as string,
);

if (!block) {
throw new Error('PreviousBlock is null');
}

await this.storage.entities.Block.delete({ id: lastBlock.id }, {}, tx);

return block;
}
}
4 changes: 2 additions & 2 deletions elements/lisk-chain/src/data_access/cache/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,6 @@ export abstract class Base<T> {
return this.items[this.length - 1];
}

public abstract add(item: T): T[];

public empty(): T[] {
this._items = [];

Expand All @@ -64,4 +62,6 @@ export abstract class Base<T> {
public get needsRefill(): boolean {
return this._needsRefill;
}

public abstract add(item: T): T[];
}
6 changes: 4 additions & 2 deletions elements/lisk-chain/src/data_access/cache/block.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,13 @@ export class BlockCache extends Base<BlockHeader> {
if (this.items.length) {
assert(
blockHeader.height === this.last.height + 1,
`Block header with height ${this.last.height +
1} can only be added, instead received height ${blockHeader.height}`,
`Block header with height ${(
this.last.height + 1
).toString()} can only be added, instead received height ${blockHeader.height.toString()}`,
);
}

// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (this.first && blockHeader.height === this.last.height + 1) {
this.items.push(blockHeader);
} else {
Expand Down
Loading

0 comments on commit 63e228c

Please sign in to comment.