Skip to content

Commit

Permalink
wip: new eslint rules and fix/ignore errors (#1721)
Browse files Browse the repository at this point in the history
* wip: new eslint rules and fix/ignore errors

* chore: syncpack format

* chore: prettier format

* dirs

* lint

* lint, handleChange callback

* lint, simplify AddressViewComponent

* chore: ignore nested ternaries

* feat: enable non-null assertions and ignore existing errors

---------

Co-authored-by: turbocrime <[email protected]>
  • Loading branch information
vacekj and turbocrime authored Aug 27, 2024
1 parent c11230c commit 87da2a6
Show file tree
Hide file tree
Showing 82 changed files with 551 additions and 297 deletions.
2 changes: 1 addition & 1 deletion apps/minifront/src/components/ibc/ibc-in/assets-table.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export const AssetsTable = () => {

// User has not connected their wallet yet
if (!address || !selectedChain) {
return <></>;
return;
}

if (isLoading) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export const CosmosWalletConnector = () => {
const { username, address, status, message } = useChainConnector();

if (!selectedChain) {
return <></>;
return;
}

return (
Expand Down
7 changes: 4 additions & 3 deletions apps/minifront/src/components/ibc/ibc-in/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,16 +108,16 @@ interface UseCosmosChainBalancesRes {
}

const getIconFromAsset = (asset: Asset): string | undefined => {
// Image default is "" and thus cannot do nullish-coalescing
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing -- Image default is "" and thus cannot do nullish-coalescing
const logoUri = asset.logo_URIs?.svg || asset.logo_URIs?.png;
if (logoUri) {
return logoUri;
}

if (asset.images?.length) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- TODO: justify non-null assertion
const first = asset.images[0]!;
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing -- Image default is "" and thus cannot do nullish-coalescing
return first.svg || first.svg;
}
return undefined;
Expand All @@ -131,6 +131,7 @@ const generatePenumbraIbcDenoms = async (chains: Chain[]): Promise<string[]> =>
const ibcStr = `transfer/${c.counterpartyChannelId}/upenumbra`;
const encoder = new TextEncoder();
const encodedString = encoder.encode(ibcStr);

const hash = await sha256HashStr(encodedString);
ibcAddrs.push(`ibc/${hash.toUpperCase()}`);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export const IbcInRequest = () => {

// User is not ready to issue request
if (!address || !selectedChain || !data?.length) {
return <></>;
return;
}

return (
Expand Down
2 changes: 1 addition & 1 deletion apps/minifront/src/components/ibc/ibc-in/interchain-ui.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export const InterchainUi = () => {
return <div>Error trying to load registry!</div>;
}
if (!data) {
return <></>;
return;
}
if (!data.ibcConnections.length) {
return <div>No known IBC connections available for {data.chainId}</div>;
Expand Down
3 changes: 1 addition & 2 deletions apps/minifront/src/components/shared/selectors/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,6 @@ export const useSyncSelectedBalance = ({
onChange(matchedValue);
}
}
// we only want to run this on new balances from ZQuery, so don't include `value` as dependency
// eslint-disable-next-line react-hooks/exhaustive-deps
// eslint-disable-next-line react-hooks/exhaustive-deps -- we only want to run this on new balances from ZQuery, so don't include `value` as dependency
}, [balances]);
};
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { LineWave } from 'react-loader-spinner';
import resolveConfig from 'tailwindcss/resolveConfig';
import tailwindConfig from '@repo/tailwind-config';

// eslint-disable-next-line
// eslint-disable-next-line -- TODO: explain
const lightGrey: string = (resolveConfig(tailwindConfig).theme.colors as any)['light-grey'].DEFAULT;

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ const getStateLabel = (state: ValidatorState_ValidatorStateEnum) =>

export const ValidatorStateLabel = ({ state }: { state: ValidatorState_ValidatorStateEnum }) => {
if (state === ValidatorState_ValidatorStateEnum.ACTIVE) {
return <></>;
return;
}

const { label, color } = getStateLabel(state);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ export const assembleAuctionBatch = (
a => a.addressIndex.equals(firstFoundAddressIndex),
batchLimit,
);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- TODO: justify
return { auctions: filteredBySeqAndAddressIndexAuctions, source: firstFoundAddressIndex! };
};

Expand Down
2 changes: 2 additions & 0 deletions apps/minifront/src/components/swap/duration-slider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ export const DurationSlider = () => {
const { duration, setDuration } = useStoreShallow(durationSliderSelector);

const handleChange = (newValue: number[]) => {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- TODO: justify non-null assertion
const value = newValue[0]!; // We don't use multiple values in the slider
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- TODO: justify non-null assertion
const option = DURATION_OPTIONS[value]!;

setDuration(option);
Expand Down
1 change: 1 addition & 0 deletions apps/minifront/src/components/tx-details/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ export const TxDetailsErrorBoundary = () => {
export const TxDetails = () => {
const { hash } = useParams<{ hash: string }>();

// eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- TODO: justify
const txInfo = useTransactionInfo(undefined, hash!);

if (
Expand Down
14 changes: 12 additions & 2 deletions apps/minifront/src/components/tx-details/tx-viewer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,11 @@ export const TxViewer = ({ txInfo }: { txInfo?: TransactionInfo }) => {
// use React-Query to invoke custom hooks that call async translators.
const { data: receiverView } = useQuery(
['receiverView', txInfo, option],
() => fetchReceiverView(txInfo!),
() =>
fetchReceiverView(
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- TODO: justify
txInfo!,
),
{
enabled: option === TxDetailsTab.RECEIVER && !!txInfo,
},
Expand Down Expand Up @@ -80,7 +84,13 @@ export const TxViewer = ({ txInfo }: { txInfo?: TransactionInfo }) => {
</div>
{option === TxDetailsTab.PRIVATE && txInfo && (
<>
<TransactionViewComponent txv={txInfo.view!} metadataFetcher={getMetadata} />
<TransactionViewComponent
txv={
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- TODO: justify
txInfo.view!
}
metadataFetcher={getMetadata}
/>
<div className='mt-8'>
<div className='text-xl font-bold'>Raw JSON</div>
<JsonViewer jsonObj={txInfo.toJson({ typeRegistry }) as Jsonified<TransactionInfo>} />
Expand Down
1 change: 1 addition & 0 deletions apps/minifront/src/fetchers/balances/by-asset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export const groupByAsset = (acc: ValueView[], curr: BalancesResponse): ValueVie
throw new Error('No amount in value view');
}

// eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- TODO: justify
const grouping = acc.find(v => hasMatchingAssetId(v, curr.balanceView!));

if (grouping) {
Expand Down
8 changes: 4 additions & 4 deletions apps/minifront/src/fetchers/page-path.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,17 @@ export const usePagePath = <T extends PagePath>() => {

export const matchPagePath = (str: string): PagePath => {
/** @todo: Remove next line after we switch to v2 layout */
str = str.replace('/v2', '');
const strFixed = str.replace('/v2', '');
const pathValues = Object.values(PagePath);

if (pathValues.includes(str as PagePath)) {
return str as PagePath;
if (pathValues.includes(strFixed as PagePath)) {
return strFixed as PagePath;
}

for (const pathValue of pathValues) {
if (pathValue.includes(':')) {
const regex = new RegExp('^' + pathValue.replace(/:(\w+)/g, '([^/]+)') + '$');
const match = str.match(regex);
const match = strFixed.match(regex);
if (match) {
return pathValue as PagePath;
}
Expand Down
1 change: 1 addition & 0 deletions apps/minifront/src/state/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ const build = async (
case 'buildProgress':
break;
case 'complete':
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- TODO: justify
return status.value.transaction!;
default:
console.warn(`unknown ${buildFn.name} status`, status);
Expand Down
1 change: 1 addition & 0 deletions apps/minifront/src/state/ibc-in/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,7 @@ const getExplorerPage = (txHash: string, chainId?: string) => {
return undefined;
}

// eslint-disable-next-line no-template-curly-in-string -- Intended template string
return txPage.replace('${txHash}', txHash);
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export const parseRevisionNumberFromChainId = (chainId: string): bigint => {
return 0n;
}

// eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- TODO: justify non-null assertion
const numStr = chainId.split('-').pop()!;
return BigInt(numStr);
};
Expand Down
1 change: 1 addition & 0 deletions apps/minifront/src/state/ibc-out.ts
Original file line number Diff line number Diff line change
Expand Up @@ -291,6 +291,7 @@ export const filterBalancesPerChain = (
}
return chain?.channelId === match.channel;
})
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- TODO: justify
.map(m => m.penumbraAssetId!);

const assetIdsToCheck = [...assetsWithMatchingChannel];
Expand Down
1 change: 1 addition & 0 deletions apps/minifront/src/state/staking/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -395,6 +395,7 @@ const assembleUndelegateRequest = ({
}: StakingSlice) => {
const delegation = delegationsByAccount
.get(account)
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- TODO: justify
?.find(delegation => isDelegationTokenForValidator(delegation, validatorInfo!));
if (!delegation) {
throw new Error('Tried to assemble undelegate request from account with no delegation tokens');
Expand Down
1 change: 1 addition & 0 deletions apps/minifront/src/state/swap/instant-swap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,7 @@ const calculatePriceImpact = (swapExec?: SwapExecution): number | undefined => {
// Get the price in the best execution trace
const inputAssetId = getAssetIdFromValue(swapExec.input);
const outputAssetId = getAssetIdFromValue(swapExec.output);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- TODO: justify non-null assertion
const bestTrace = swapExec.traces[0]!;
const bestInputAmount = getMatchingAmount(bestTrace.value, inputAssetId);
const bestOutputAmount = getMatchingAmount(bestTrace.value, outputAssetId);
Expand Down
2 changes: 1 addition & 1 deletion apps/node-status/src/components/node-info.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export const NodeInfo = () => {
status: { nodeInfo },
} = useLoaderData() as IndexLoaderResponse;
if (!nodeInfo) {
return <></>;
return;
}

return (
Expand Down
2 changes: 1 addition & 1 deletion apps/node-status/src/components/sync-info.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export const SyncInfo = () => {
latestAppHash,
} = useLoaderData() as IndexLoaderResponse;
if (!syncInfo) {
return <></>;
return;
}

const { date, time } = getFormattedTime(syncInfo);
Expand Down
2 changes: 1 addition & 1 deletion apps/node-status/src/components/validator-info.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export const ValidatorInfo = () => {
status: { validatorInfo },
} = useLoaderData() as IndexLoaderResponse;
if (!validatorInfo) {
return <></>;
return;
}

return (
Expand Down
88 changes: 50 additions & 38 deletions eslint.config.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
// @ts-check

import { createRequire } from 'node:module';

// @ts-expect-error https://github.com/eslint-community/eslint-plugin-eslint-comments/issues/214
import ESLintPluginESLintCommentsConfigs from '@eslint-community/eslint-plugin-eslint-comments/configs';
import { fixupPluginRules } from '@eslint/compat';
import eslint from '@eslint/js';
import * as import_ from 'eslint-plugin-import';
Expand Down Expand Up @@ -31,9 +32,17 @@ const storybookPluginConfigs = tseslint.config(
},
);

// The plugin is not currently exported from the root, so we have to get the plugin from the config.
// https://github.com/eslint-community/eslint-plugin-eslint-comments/issues/215
const ESLintPluginESLintComments =
ESLintPluginESLintCommentsConfigs.recommended.plugins['@eslint-community/eslint-comments'];

export default tseslint.config(
// completely ignored files
{ name: 'custom:ignores', ignores: ['vitest.workspace.ts', 'dist', 'node_modules'] },
{
name: 'custom:ignores',
ignores: ['vitest.workspace.ts', 'dist', 'node_modules', 'vite-env.d.ts'],
},

// base javascript config
eslint.configs.recommended,
Expand All @@ -47,6 +56,16 @@ export default tseslint.config(
languageOptions: { parser: tseslint.parser, parserOptions: { project: true } },
},

{
name: 'custom:eslint-comments',
plugins: {
'@eslint-community/eslint-comments': ESLintPluginESLintComments,
},
rules: {
'@eslint-community/eslint-comments/require-description': ['error', { ignore: [] }],
},
},

// tailwind config
{
name: 'custom:tailwindcss-config',
Expand Down Expand Up @@ -74,18 +93,15 @@ export default tseslint.config(
rules: {
...react.configs.recommended.rules,
...react_hooks.configs.recommended.rules,
'react-hooks/exhaustive-deps': 'warn',
'react-hooks/exhaustive-deps': 'error',
'react-hooks/rules-of-hooks': 'error',
},
},
{
name: 'custom:react-wishlist-improvements',
rules: {
// this plugin was formerly included, but was never actually applied.
'react/jsx-no-useless-fragment': [
'error',
{
allowExpressions: true,
},
],
'react-refresh/only-export-components': 'off',

//'react/jsx-no-literals': 'warn',
//'react/jsx-no-useless-fragment': 'warn',
},
},

Expand Down Expand Up @@ -177,39 +193,33 @@ export default tseslint.config(
name: 'custom:typescript-wishlist-improvements',
files: ['**/*.@(ts|tsx)'],
rules: {
// enabled by tseslint strictTypeChecked. large diff
'@typescript-eslint/no-non-null-assertion': 'off',
'@typescript-eslint/no-non-null-assertion': 'error',

//'@typescript-eslint/no-redeclare': 'error',
//'@typescript-eslint/no-shadow': 'error',
//'@typescript-eslint/restrict-template-expressions': ['error', { allowNumber: true }],
// '@typescript-eslint/no-redeclare': 'error',
// '@typescript-eslint/no-shadow': 'error',
// '@typescript-eslint/restrict-template-expressions': ['error', { allowNumber: true }],
},
},

{
name: 'custom:eslint-wishlist-improvements',
rules: {
//'array-callback-return': 'warn',
//'class-methods-use-this': 'warn',
//'consistent-return': 'warn',
//'consistent-this': 'error',
//'func-name-matching': 'warn',
//'no-await-in-loop': 'warn',
//'no-bitwise': 'warn',
//'no-console': 'warn',
//'no-continue': 'warn',
//'no-nested-ternary': 'warn',
//'no-param-reassign': 'error',
//'no-plusplus': 'error',
//'no-promise-executor-return': ['error', { allowVoid: true }],
//'no-restricted-globals': [ 'error', { message: 'Use `globalThis` instead.', name: 'global' }, { message: 'Use `globalThis` instead.', name: 'self' }, ],
//'no-self-assign': ['error', { props: true }],
//'no-template-curly-in-string': 'warn',
//'no-unreachable-loop': 'warn',
//'no-warning-comments': 'warn',
//'prefer-regex-literals': ['error', { disallowRedundantWrapping: true }],
//'spaced-comment': 'warn',
//complexity: 'warn',
'no-bitwise': 'error',
'no-console': ['error', { allow: ['warn', 'error', 'debug'] }],
'no-nested-ternary': 'warn',
'no-param-reassign': 'error',
'no-promise-executor-return': ['error', { allowVoid: true }],
'no-restricted-globals': [
'error',
{ message: 'Use `globalThis` instead.', name: 'global' },
{ message: 'Use `globalThis` instead.', name: 'self' },
],
'no-self-assign': ['error', { props: true }],
'no-template-curly-in-string': 'warn',
'no-unreachable-loop': 'warn',
'no-warning-comments': 'off',
'prefer-regex-literals': ['error', { disallowRedundantWrapping: true }],
'spaced-comment': ['error', 'always', { markers: ['/'] }],
},
},

Expand All @@ -233,10 +243,12 @@ export default tseslint.config(
'**/*.story.@(ts|tsx|js|jsx|mjs|cjs)',
],
rules: {
'no-console': 'off',
'@typescript-eslint/no-empty-function': 'off',
'@typescript-eslint/no-non-null-assertion': 'off',
'@typescript-eslint/prefer-promise-reject-errors': 'off',
'react/display-name': 'off',
'@eslint-community/eslint-comments/require-description': 'off',
},
},

Expand Down
Loading

0 comments on commit 87da2a6

Please sign in to comment.