Skip to content

Commit

Permalink
refactor: [LW-11802] enable strict null checks (#1536)
Browse files Browse the repository at this point in the history
* chore: enable strict null checks in tsconfig
* separate tags requiring co-signer and those which don't
* enable strict null checks
* update function return types to include nulls
* refactor(nami): remove src director from tsconfig exclusions
* refactor(core): make currentTimelineStep a required property of onboarding steps
* refactor(core): update deep partial types for governance actions
* add translation package to tsconfig references
  • Loading branch information
mchappell authored Dec 9, 2024
1 parent b3b1d06 commit 1435a4d
Show file tree
Hide file tree
Showing 137 changed files with 881 additions and 636 deletions.
1 change: 1 addition & 0 deletions apps/browser-extension-wallet/src/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"baseUrl": "../src",
"resolveJsonModule": true,
"noEmitOnError": false,
"strictNullChecks": false,
"paths": {
"@assets/*": ["assets/*"],
"@components/*": ["components/*"],
Expand Down
4 changes: 2 additions & 2 deletions apps/browser-extension-wallet/src/utils/format-number.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ export const formatLocaleNumber = (value: string, decimalPlaces: number = DEFAUL
* @param maxDecimals The maximum number of decimal places to include. Default is 0.
* @returns The formatted number string.
*/
export const formatNumberForDisplay = (value: string, maxDecimals = 0): string => {
export const formatNumberForDisplay = (value?: string, maxDecimals = 0): string => {
if (!value) return '0';
// Remove any character that is not a dot or a number
const parsedStringValue = value.replace(/[^\d.]/g, '');
Expand Down Expand Up @@ -137,7 +137,7 @@ export const handleFormattedValueChange = (
* @param decimals The desired decimal places (default = 2)
* @returns The formatted value with the desired decimals and the unit as a string
*/
export const compactNumberWithUnit = (value: number | string, decimals = DEFAULT_DECIMALS): string => {
export const compactNumberWithUnit = (value?: number | string, decimals = DEFAULT_DECIMALS): string => {
const bigNumberValue = value ? new BigNumber(value) : new BigNumber(0);

if (bigNumberValue.isNaN()) return formatLocaleNumber('0', decimals);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import { MAX_NFT_TICKER_LENGTH, MAX_TOKEN_TICKER_LENGTH } from '../../../constan

interface InputFieldActionParams {
id: string;
value: string;
value?: string;
maxDecimals?: number;
}

Expand Down Expand Up @@ -176,10 +176,10 @@ export const useSelectedCoins = ({
coinBalance,
spendableCoin?.toString(),
tokensUsed[cardanoCoin.id] || '0',
assetInputItem?.value || '0'
assetInputItem?.value ?? '0'
);
const fiatValue = Wallet.util.convertAdaToFiat({
ada: assetInputItem?.value || '0',
ada: assetInputItem?.value ?? '0',
fiat: prices?.cardano?.price
});
return {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ export const StakePoolInfo = ({
onClick?: () => void;
popupView: boolean;
}): React.ReactElement => {
const title = name || ticker || '-';
const subTitle: string | React.ReactElement = ticker || (
const title = name ?? ticker ?? '-';
const subTitle: string | React.ReactElement = ticker ?? (
<Ellipsis className={styles.id} text={id} beforeEllipsis={6} afterEllipsis={8} />
);

Expand Down
4 changes: 4 additions & 0 deletions apps/browser-extension-wallet/test/__mocks__/set-env-vars.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,7 @@ process.env.USE_POSTHOG_ANALYTICS = 'true';
process.env.USE_POSTHOG_ANALYTICS_FOR_OPTED_OUT = 'false';
process.env.POSTHOG_HOST = 'https://e.lw.iog.io';
process.env.POSTHOG_DEV_TOKEN = 'test-token';
process.env.MIN_NUMBER_OF_COSIGNERS = '2';
process.env.TWITTER_URL = 'TWITTER_URL';
process.env.YOUTUBE_URL = 'YOUTUBE_URL';
process.env.DISCORD_URL = 'DISCORD_URL';
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,14 @@ import isNil from 'lodash/isNil';
import cn from 'classnames';
import styles from './StakePoolMetricsBrowser.module.scss';

const formatNumericValue = (val: number | string, suffix: number | string): React.ReactElement => (
<>
{val ?? '-'} {!isNil(val) && <span className={styles.suffix}>{suffix}</span>}
</>
);
const formatNumericValue = ({ value, unit }: { value?: number | string; unit: number | string }): React.ReactNode =>
!isNil(value) ? (
<>
{value} <span className={styles.suffix}>{unit}</span>
</>
) : (
'-'
);

export interface StakePoolMetricsBrowserProps {
data: {
Expand All @@ -27,7 +30,7 @@ export const StakePoolMetricsBrowser = ({ data, popupView }: StakePoolMetricsBro
{t}
</div>
<div className={styles.statBody} data-testid={`${testId}-value`}>
{unit ? formatNumericValue(value, unit) : value}
{unit ? formatNumericValue({ value, unit }) : value}
</div>
</div>
))}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,9 @@ export const StakePoolNameBrowser = ({
isOversaturated,
translations
}: StakePoolNameBrowserProps): React.ReactElement => {
const title = name || ticker || '-';
const subTitle: string | React.ReactElement = ticker || (
<Ellipsis className={styles.id} text={id} beforeEllipsis={6} afterEllipsis={8} />
const title = name ?? ticker ?? '-';
const subTitle: string | React.ReactElement = ticker ?? (
<Ellipsis className={styles.id} text={id ?? ''} beforeEllipsis={6} afterEllipsis={8} />
);

return (
Expand All @@ -48,13 +48,15 @@ export const StakePoolNameBrowser = ({
<p className={styles.subTitle} data-testid="stake-pool-item-ticker">
{subTitle}
</p>
<StatusLogo
status={status}
isDelegated={isDelegated}
isOversaturated={isOversaturated}
className={styles.statusLogo}
translations={translations}
/>
{status && (
<StatusLogo
status={status}
isDelegated={!!isDelegated}
isOversaturated={isOversaturated}
className={styles.statusLogo}
translations={translations}
/>
)}
</div>
</div>
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,19 @@ import { StakePoolNameBrowser, StakePoolNameBrowserProps } from '../StakePoolNam
import '@testing-library/jest-dom';

describe('Testing StakePoolNameBrowser component', () => {
const name = 'name';
const ticker = 'ticker';
const props: StakePoolNameBrowserProps = {
name: 'name',
ticker: 'ticker',
name,
ticker,
isDelegated: true,
translations: { retiring: 'retiring', retired: 'retired', delegating: 'delegating', saturated: 'saturated' }
};
test('should display all stake pool metrics with icons', async () => {
const { findByText, findByTestId } = render(<StakePoolNameBrowser {...props} />);
const roiLabel = await findByTestId('stake-pool-item-logo');
const nameValue = await findByText(props.name);
const tickerValue = await findByText(props.ticker);
const nameValue = await findByText(name);
const tickerValue = await findByText(ticker);

expect(roiLabel).toBeVisible();
expect(nameValue).toBeVisible();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@ export const StatusLogo = ({
if (status === 'retired' || status === 'retiring') {
currentStatus = status;
}
const icon = statusIcons[currentStatus];
const description = statusInfo[currentStatus];
const icon = currentStatus ? statusIcons[currentStatus] : undefined;
const description = currentStatus ? statusInfo[currentStatus] : undefined;

return (
<>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import React from 'react';
import styles from './Voting.module.scss';
import { Button } from '@lace/common';
import CatalystLogo from '../../assets/images/catalyst-logo.png';
import Icon, { InfoCircleOutlined } from '@ant-design/icons';
import { InfoCircleOutlined } from '@ant-design/icons';
import { TranslationsFor } from '@wallet/util/types';

export interface CatalystConfirmationStepProps {
Expand Down Expand Up @@ -52,7 +52,7 @@ export const CatalystConfirmationStep = ({
<>
<div className={styles.fee}>
<p>
{translations.totalFee} <Icon component={InfoCircleOutlined} />
{translations.totalFee} <InfoCircleOutlined />
</p>
<b>{fee}</b>
</div>
Expand Down
12 changes: 6 additions & 6 deletions packages/cardano/src/ui/components/Voting/CatalystScanStep.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React, { useEffect, useRef } from 'react';
import { Button } from '@lace/common';
import Icon, { DownloadOutlined } from '@ant-design/icons';
import { DownloadOutlined } from '@ant-design/icons';
import QRCodeStyling from 'qr-code-styling';
import styles from './Voting.module.scss';
import { TranslationsFor } from '@wallet/util/types';
Expand All @@ -16,12 +16,12 @@ export const CatalystScanStep = ({
certificate,
translations
}: CatalystScanStepProps): React.ReactElement => {
const qrCodeRef = useRef(null);
const qrCode = useRef<QRCodeStyling>(null);
const qrCodeRef = useRef<HTMLDivElement | null>(null);
const qrCode = useRef<QRCodeStyling | null>(null);

useEffect(() => {
qrCode.current = new QRCodeStyling({ data: certificate, width: 240, height: 240 });
qrCode.current.append(qrCodeRef.current);
qrCode.current.append(qrCodeRef.current || undefined);
}, [certificate]);

return (
Expand All @@ -34,10 +34,10 @@ export const CatalystScanStep = ({
<div ref={qrCodeRef} />
<div>
<Button
onClick={() => qrCode.current.download({ name: 'certificate', extension: 'png' })}
onClick={() => qrCode.current?.download({ name: 'certificate', extension: 'png' })}
color="secondary"
>
<Icon component={DownloadOutlined} /> {translations.downloadButton}
<DownloadOutlined /> {translations.downloadButton}
</Button>
</div>
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ describe.skip('Testing build-transaction', () => {

expect(transaction).toBeDefined();
expect(minimumCoinQuantities).toBeDefined();
expect(minimumCoinQuantities.get(output).coinMissing).toBe(BigInt(0));
expect(minimumCoinQuantities.get(output)?.coinMissing).toBe(BigInt(0));
});

test('should validate and build a transaction successfully with coins missing', async () => {
Expand All @@ -39,7 +39,7 @@ describe.skip('Testing build-transaction', () => {

expect(transaction).toBeDefined();
expect(minimumCoinQuantities).toBeDefined();
expect(minimumCoinQuantities.get(output).coinMissing).toBeGreaterThan(BigInt(0));
expect(minimumCoinQuantities.get(output)?.coinMissing).toBeGreaterThan(BigInt(0));
});

test('should throw an error if tx initialization fails', async () => {
Expand Down
36 changes: 18 additions & 18 deletions packages/cardano/src/wallet/lib/__tests__/get-inputs-value.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ describe('Testing getTxInputsValueAndAddress function', () => {
signed$: of([])
}
}
} as ObservableWallet;
} as unknown as ObservableWallet;

const multiDelegationTransactionMock: Cardano.HydratedTx = {
inputSource: Cardano.InputSource.inputs,
Expand Down Expand Up @@ -194,11 +194,11 @@ describe('Testing getTxInputsValueAndAddress function', () => {
'addr_test1qrmavlv5c7za68rq6n6r0hrcqd604j9zsr6tycwtjf3lef0wc4p9nt0e0wwytcy30mxar65892w3k77e5g2uyhx29lhqjt267p'
);
// From matched output in mocked transaction
expect(inputs[0].value.coins.toString()).toBe('3000000');
expect(inputs[0].value?.coins.toString()).toBe('3000000');
expect(
inputs[0].value.assets
.get(Cardano.AssetId('6b8d07d69639e9413dd637a1a815a7323c69c86abbafb66dbfdb1aa7'))
.toString()
inputs[0].value?.assets
?.get(Cardano.AssetId('6b8d07d69639e9413dd637a1a815a7323c69c86abbafb66dbfdb1aa7'))
?.toString()
).toBe('30');
});
});
Expand All @@ -225,11 +225,11 @@ describe('Testing getTxInputsValueAndAddress function', () => {
'addr_test1qrmavlv5c7za68rq6n6r0hrcqd604j9zsr6tycwtjf3lef0wc4p9nt0e0wwytcy30mxar65892w3k77e5g2uyhx29lhqjt267p'
);
// From matched output in mocked transaction
expect(inputs[0].value.coins.toString()).toBe('3000000');
expect(inputs[0].value?.coins.toString()).toBe('3000000');
expect(
inputs[0].value.assets
.get(Cardano.AssetId('6b8d07d69639e9413dd637a1a815a7323c69c86abbafb66dbfdb1aa7'))
.toString()
inputs[0].value?.assets
?.get(Cardano.AssetId('6b8d07d69639e9413dd637a1a815a7323c69c86abbafb66dbfdb1aa7'))
?.toString()
).toBe('30');
});
});
Expand Down Expand Up @@ -261,7 +261,7 @@ describe('Testing getTxInputsValueAndAddress function', () => {
const inputs = await result;
expect(transactionsByHashes).toBeCalledTimes(1);
expect(inputs[0].address).toBe('address');
expect(inputs[0].value.coins.toString()).toBe('3000000');
expect(inputs[0].value?.coins.toString()).toBe('3000000');
});
});

Expand Down Expand Up @@ -329,11 +329,11 @@ describe('Testing getTxInputsValueAndAddress function', () => {
expect(inputs[0].address).toBe(
'addr_test1qrmavlv5c7za68rq6n6r0hrcqd604j9zsr6tycwtjf3lef0wc4p9nt0e0wwytcy30mxar65892w3k77e5g2uyhx29lhqjt267p'
);
expect(inputs[0].value.coins.toString()).toBe('3000000');
expect(inputs[0].value?.coins.toString()).toBe('3000000');
expect(
inputs[0].value.assets
.get(Cardano.AssetId('6b8d07d69639e9413dd637a1a815a7323c69c86abbafb66dbfdb1aa7'))
.toString()
inputs[0].value?.assets
?.get(Cardano.AssetId('6b8d07d69639e9413dd637a1a815a7323c69c86abbafb66dbfdb1aa7'))
?.toString()
).toBe('30');

// Assert the properties for the second input
Expand All @@ -342,12 +342,12 @@ describe('Testing getTxInputsValueAndAddress function', () => {
);

expect(
inputs[1].value.assets
.get(Cardano.AssetId('6b8d07d69639e9413dd637a1a815a7323c69c86abbafb66dbfdb1aa7'))
.toString()
inputs[1].value?.assets
?.get(Cardano.AssetId('6b8d07d69639e9413dd637a1a815a7323c69c86abbafb66dbfdb1aa7'))
?.toString()
).toBe('10');

expect(inputs[1].value.coins.toString()).toBe('100000');
expect(inputs[1].value?.coins.toString()).toBe('100000');

expect(inputs[2].address).toBe(
'addr_test1qrrx8s34r6m0w835qe9tj8mqa4ugkwhllw5l4hwpmhakpy8hukqufzmfnrvvr24tschssxw96z8dq9dz09xkg9eghtkqe07423'
Expand Down
2 changes: 1 addition & 1 deletion packages/cardano/src/wallet/lib/build-transaction-props.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ type OutputsMap = Map<string, CardanoOutput>;
type TokenBalanceMap = Map<Cardano.AssetId, bigint>;

export const convertAssetsToBigInt = (
assets: CardanoOutput['value']['assets'],
assets: Map<Cardano.AssetId, string>,
assetsInfo: Assets = new Map()
): TokenBalanceMap => {
const assetMap: TokenBalanceMap = new Map();
Expand Down
2 changes: 1 addition & 1 deletion packages/cardano/src/wallet/lib/build-transaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export const buildTransaction = async (
wallet: ObservableWallet
): Promise<InitializedCardanoTransaction> => {
const util = createWalletUtil(wallet);
const minimumCoinQuantities = await util.validateOutputs(txProps.outputs);
const minimumCoinQuantities = await util.validateOutputs(txProps.outputs || []);
const transaction = await wallet.initializeTx(txProps);

return { transaction, minimumCoinQuantities };
Expand Down
2 changes: 1 addition & 1 deletion packages/cardano/src/wallet/lib/get-inputs-value.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export const getTxInputsValueAndAddress = async (

for (const input of inputs) {
const output = await util.resolveInput(input);
resolvedInputs.push([{ address: output.address, ...input }, output]);
if (output) resolvedInputs.push([{ address: output.address, ...input }, output]);
}

return resolvedInputs.map((utxo) => {
Expand Down
Loading

0 comments on commit 1435a4d

Please sign in to comment.