Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[CHORE]: Remove transaction inconsistencies and improve type safety #6137

Merged
merged 19 commits into from
Oct 10, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
lots of typescript improvements
  • Loading branch information
walmat committed Sep 23, 2024
commit 2a4c08ff60a99391f6fd5e960bbbfcb9da019db5
Original file line number Diff line number Diff line change
@@ -143,5 +143,4 @@ export const SearchInputButton = ({
</GestureHandlerButton>
</Animated.View>
);

};
48 changes: 36 additions & 12 deletions src/components/Divider.js → src/components/Divider.tsx
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

typescript conversion

Original file line number Diff line number Diff line change
@@ -3,10 +3,12 @@ import React from 'react';
import { magicMemo } from '../utils';
import styled from '@/styled-thing';
import { borders, position } from '@/styles';
import { View } from 'react-native';
import { ThemeContextProps, useTheme } from '@/theme';

export const DividerSize = 2;

const buildInsetFromProps = inset => {
const buildInsetFromProps = (inset: number | number[]): number[] => {
if (!inset) return [0, 0, 0, 0];
if (isNumber(inset)) return [inset, inset, inset, inset];

@@ -15,35 +17,41 @@ const buildInsetFromProps = inset => {
return [inset[0], rightInset, inset[2] || inset[0], !isNil(inset[3]) ? inset[3] : rightInset];
};

const horizontalBorderLineStyles = inset => `
const horizontalBorderLineStyles = (inset: number[]): string => `
${inset[3] ? borders.buildRadius('left', 2) : ''}
${inset[1] ? borders.buildRadius('right', 2) : ''}
left: ${inset[3]};
right: ${inset[1]};
`;

horizontalBorderLineStyles.object = inset => ({
horizontalBorderLineStyles.object = (inset: number[]): object => ({
...(inset[3] ? borders.buildRadiusAsObject('left', 2) : {}),
...(inset[1] ? borders.buildRadiusAsObject('right', 2) : {}),
left: inset[3],
right: inset[1],
});

const verticalBorderLineStyles = inset => `
const verticalBorderLineStyles = (inset: number[]): string => `
${inset[2] ? borders.buildRadius('bottom', 2) : ''}
${inset[0] ? borders.buildRadius('top', 2) : ''}
bottom: ${inset[2]};
top: ${inset[0]};
`;

verticalBorderLineStyles.object = inset => ({
verticalBorderLineStyles.object = (inset: number[]): object => ({
...(inset[2] ? borders.buildRadiusAsObject('bottom', 2) : {}),
...(inset[0] ? borders.buildRadiusAsObject('top', 2) : {}),
bottom: inset[2],
top: inset[0],
});

const BorderLine = styled.View(({ color, horizontal, inset }) => {
interface BorderLineProps {
color: string;
horizontal: boolean;
inset: number | number[];
}

const BorderLine = styled(View)(({ color, horizontal, inset }: BorderLineProps) => {
const insetFromProps = buildInsetFromProps(inset);
return {
...position.coverAsObject,
@@ -52,14 +60,30 @@ const BorderLine = styled.View(({ color, horizontal, inset }) => {
};
});

const Container = styled.View({
backgroundColor: ({ backgroundColor, theme: { colors } }) => backgroundColor || colors.white,
interface ContainerProps {
backgroundColor: string;
horizontal: boolean;
size: number;
theme: ThemeContextProps;
}

const Container = styled(View)(({ backgroundColor, theme: { colors } }: ContainerProps) => ({
backgroundColor: backgroundColor || colors.white,
flexShrink: 0,
height: ({ horizontal, size }) => (horizontal ? size : '100%'),
width: ({ horizontal, size }) => (horizontal ? '100%' : size),
});
height: ({ horizontal, size }: { horizontal: boolean; size: number }) => (horizontal ? size : '100%'),
width: ({ horizontal, size }: { horizontal: boolean; size: number }) => (horizontal ? '100%' : size),
}));

interface DividerProps {
backgroundColor?: string;
color?: string;
horizontal?: boolean;
inset?: number | number[];
size?: number;
[key: string]: any;
}

const Divider = ({ backgroundColor, color, horizontal = true, inset = [0, 0, 0, 19], size = DividerSize, ...props }) => {
const Divider = ({ backgroundColor, color, horizontal = true, inset = [0, 0, 0, 19], size = DividerSize, ...props }: DividerProps) => {
const { colors } = useTheme();
return (
<Container {...props} backgroundColor={backgroundColor} horizontal={horizontal} size={size}>
4 changes: 1 addition & 3 deletions src/components/cards/GasCard.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
// @ts-expect-error
import AnimateNumber from '@bankify/react-native-animate-number';
import { useIsFocused } from '@react-navigation/native';
import * as i18n from '@/languages';
@@ -60,8 +59,7 @@ export const GasCard = () => {
const isCurrentGweiLoaded = currentGwei && Number(currentGwei) > 0;

const renderGweiText = useCallback(
// @ts-expect-error passed to an untyped JS component
animatedNumber => {
(animatedNumber: number) => {
const priceText =
animatedNumber === 0
? isCurrentGweiLoaded
1 change: 0 additions & 1 deletion src/components/coin-row/CollectiblesSendRow.tsx
Original file line number Diff line number Diff line change
@@ -114,7 +114,6 @@ const CollectiblesSendRow = React.memo(
<Fragment>
{isFirstRow && (
<Centered height={dividerHeight}>
{/* @ts-expect-error JavaScript component */}
<Divider color={colors.rowDividerLight} />
</Centered>
)}
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
/* eslint-disable no-nested-ternary */
/* eslint-disable no-undef */
import AnimateNumber from '@bankify/react-native-animate-number';
import lang from 'i18n-js';
import { isEmpty, isNaN, isNil } from 'lodash';
import { isEmpty, isNaN, isNil, noop } from 'lodash';
import makeColorMoreChill from 'make-color-more-chill';
import { AnimatePresence, MotiView } from 'moti';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { InteractionManager, Keyboard } from 'react-native';
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { InteractionManager, Keyboard, View } from 'react-native';
import { Easing } from 'react-native-reanimated';
import { darkModeThemeColors } from '../../styles/colors';
import { ButtonPressAnimation } from '../animations';
@@ -29,9 +28,21 @@ import { ContextMenu } from '../context-menu';
import { EthCoinIcon } from '../coin-icon/EthCoinIcon';
import { ChainId } from '@/chains/types';
import { chainsGasSpeeds } from '@/chains';
import { ThemeContextProps, useTheme } from '@/theme';
import { OnPressMenuItemEventObject } from 'react-native-ios-context-menu';
import { ParsedAddressAsset } from '@/entities';

const { GAS_EMOJIS, GAS_ICONS, GasSpeedOrder, CUSTOM, URGENT, NORMAL, FAST, getGasLabel } = gasUtils;

type WithThemeProps = {
borderColor: string;
color: string;
theme: ThemeContextProps;
marginBottom: number;
marginTop: number;
horizontalPadding: number;
};

const CustomGasButton = styled(ButtonPressAnimation).attrs({
align: 'center',
alignItems: 'center',
@@ -40,7 +51,7 @@ const CustomGasButton = styled(ButtonPressAnimation).attrs({
justifyContent: 'center',
scaleTo: 0.8,
})({
borderColor: ({ borderColor, color, theme: { colors } }) => borderColor || color || colors.appleBlue,
borderColor: ({ borderColor, color, theme: { colors } }: WithThemeProps) => borderColor || color || colors.appleBlue,
borderRadius: 19,
borderWidth: 2,
...padding.object(android ? 2 : 3, 0),
@@ -69,7 +80,7 @@ const DoneCustomGas = styled(Text).attrs({
bottom: 0.5,
});

const ChainBadgeContainer = styled.View.attrs({
const ChainBadgeContainer = styled(View).attrs({
hapticType: 'impactHeavy',
scaleTo: 0.9,
})({
@@ -89,24 +100,24 @@ const Container = styled(Column).attrs({
alignItems: 'center',
hapticType: 'impactHeavy',
justifyContent: 'center',
})(({ marginBottom, marginTop, horizontalPadding }) => ({
})(({ marginBottom, marginTop, horizontalPadding }: WithThemeProps) => ({
...margin.object(marginTop, 0, marginBottom),
...padding.object(0, horizontalPadding),
width: '100%',
}));

const Label = styled(Text).attrs(({ size }) => ({
const Label = styled(Text).attrs(({ size }: { size: string }) => ({
lineHeight: 'normal',
size: size || 'lmedium',
}))(({ weight }) => fontWithWidth(weight || fonts.weight.semibold));
}))(({ weight }: { weight: string }) => fontWithWidth(weight || fonts.weight.semibold));

const GasSpeedPagerCentered = styled(Centered).attrs(() => ({
marginRight: 8,
}))({});

const TextContainer = styled(Column).attrs(() => ({}))({});

const TransactionTimeLabel = ({ formatter, isLongWait, theme }) => {
const TransactionTimeLabel = ({ formatter, isLongWait, theme }: { formatter: () => string; isLongWait: boolean; theme: string }) => {
const { colors } = useTheme();
let color = theme === 'dark' ? colors.alpha(darkModeThemeColors.blueGreyDark, 0.6) : colors.alpha(colors.blueGreyDark, 0.6);

@@ -121,7 +132,7 @@ const TransactionTimeLabel = ({ formatter, isLongWait, theme }) => {
);
};

const shouldRoundGasDisplay = chainId => {
const shouldRoundGasDisplay = (chainId: ChainId) => {
switch (chainId) {
case ChainId.bsc:
case ChainId.polygon:
@@ -131,14 +142,32 @@ const shouldRoundGasDisplay = chainId => {
}
};

type GasSpeedButtonProps = {
asset?: Partial<ParsedAddressAsset>;
chainId: ChainId;
horizontalPadding?: number;
fallbackColor?: string;
marginBottom?: number;
marginTop?: number;
speeds?: string[];
testID?: string;
theme?: string;
canGoBack?: boolean;
showGasOptions?: boolean;
validateGasParams?: React.RefObject<(callback?: () => void) => void>;
flashbotTransaction?: boolean;
crossChainServiceTime?: number;
loading?: boolean;
};

const GasSpeedButton = ({
asset,
chainId,
horizontalPadding = 19,
fallbackColor,
marginBottom = 20,
marginTop = 18,
speeds = null,
speeds = [],
testID,
theme = 'dark',
canGoBack = true,
@@ -147,7 +176,7 @@ const GasSpeedButton = ({
flashbotTransaction = false,
crossChainServiceTime,
loading = false,
}) => {
}: GasSpeedButtonProps) => {
const { colors } = useTheme();
const { navigate, goBack } = useNavigation();
const { nativeCurrencySymbol, nativeCurrency } = useAccountSettings();
@@ -159,7 +188,10 @@ const GasSpeedButton = ({
const { gasFeeParamsBySpeed, updateGasFeeOption, selectedGasFee, selectedGasFeeOption, currentBlockParams } = useGas();

const [gasPriceReady, setGasPriceReady] = useState(false);
const [shouldOpenCustomGasSheet, setShouldOpenCustomGasSheet] = useState({
const [shouldOpenCustomGasSheet, setShouldOpenCustomGasSheet] = useState<{
focusTo: string | null;
shouldOpen: boolean;
}>({
focusTo: null,
shouldOpen: false,
});
@@ -188,7 +220,7 @@ const GasSpeedButton = ({
);

const formatGasPrice = useCallback(
animatedValue => {
(animatedValue: string) => {
if (animatedValue === null || loading || isNaN(animatedValue)) {
return 0;
}
@@ -213,7 +245,7 @@ const GasSpeedButton = ({
[loading, gasPriceReady, isLegacyGasNetwork, nativeCurrencySymbol, nativeCurrency]
);

const openCustomOptionsRef = useRef();
const openCustomOptionsRef = useRef<any>();

const openCustomGasSheet = useCallback(() => {
if (gasIsNotReady) return;
@@ -222,14 +254,14 @@ const GasSpeedButton = ({
fallbackColor,
flashbotTransaction,
focusTo: shouldOpenCustomGasSheet.focusTo,
openCustomOptions: focusTo => openCustomOptionsRef.current(focusTo),
openCustomOptions: (focusTo: string) => openCustomOptionsRef?.current?.(focusTo),
speeds: speeds ?? GasSpeedOrder,
type: 'custom_gas',
});
}, [gasIsNotReady, navigate, asset, shouldOpenCustomGasSheet.focusTo, flashbotTransaction, speeds, fallbackColor]);

const openCustomOptions = useCallback(
focusTo => {
(focusTo: string) => {
if (ios) {
setShouldOpenCustomGasSheet({ focusTo, shouldOpen: true });
} else {
@@ -242,7 +274,7 @@ const GasSpeedButton = ({
openCustomOptionsRef.current = openCustomOptions;

const renderGasPriceText = useCallback(
animatedNumber => {
(animatedNumber: number) => {
const priceText = animatedNumber === 0 || loading ? lang.t('swap.loading') : animatedNumber;
return (
<Text
@@ -260,7 +292,7 @@ const GasSpeedButton = ({

// I'M SHITTY CODE BUT GOT THINGS DONE REFACTOR ME ASAP
const handlePressSpeedOption = useCallback(
selectedSpeed => {
(selectedSpeed: string) => {
if (selectedSpeed === CUSTOM) {
if (ios) {
InteractionManager.runAfterInteractions(() => {
@@ -294,7 +326,7 @@ const GasSpeedButton = ({
}

const estimatedTime = (selectedGasFee?.estimatedTime?.display || '').split(' ');
const [estimatedTimeValue = 0, estimatedTimeUnit = 'min'] = estimatedTime;
const [estimatedTimeValue = '0', estimatedTimeUnit = 'min'] = estimatedTime;
const time = parseFloat(estimatedTimeValue).toFixed(0);

const timeSymbol = estimatedTimeUnit === 'hr' ? '>' : '~';
@@ -329,14 +361,14 @@ const GasSpeedButton = ({
}, [chainId, crossChainServiceTime, inputCurrency, navigate, outputCurrency]);

const handlePressMenuItem = useCallback(
({ nativeEvent: { actionKey } }) => {
({ nativeEvent: { actionKey } }: OnPressMenuItemEventObject) => {
handlePressSpeedOption(actionKey);
},
[handlePressSpeedOption]
);

const handlePressActionSheet = useCallback(
buttonIndex => {
(buttonIndex: number) => {
switch (buttonIndex) {
case 0:
handlePressSpeedOption(NORMAL);
@@ -368,7 +400,8 @@ const GasSpeedButton = ({

const shouldRoundGwei = shouldRoundGasDisplay(chainId);
const gweiDisplay = !shouldRoundGwei
? gasFeeParamsBySpeed[gasOption]?.gasPrice?.display
? // @ts-expect-error - legacy gas params has `gasPrice`
gasFeeParamsBySpeed[gasOption]?.gasPrice?.display
: gasOption === 'custom' && selectedGasFeeOption !== 'custom'
? ''
: greaterThan(estimatedGwei, totalGwei)
@@ -411,9 +444,8 @@ const GasSpeedButton = ({
: colors.alpha(colors.blueGreyDark, 0.12)
}
dropdownEnabled={gasOptionsAvailable}
onPress={noop}
label={label}
showGasOptions={showGasOptions}
showPager
theme={theme}
/>
);
@@ -477,7 +509,7 @@ const GasSpeedButton = ({
// would make the expanded sheet come up with too much force
// instead calling it from `useEffect` makes it appear smoothly
useEffect(() => {
if (shouldOpenCustomGasSheet.shouldOpen && !prevShouldOpenCustomGasSheet.shouldOpen) {
if (shouldOpenCustomGasSheet.shouldOpen && !prevShouldOpenCustomGasSheet?.shouldOpen) {
openCustomGasSheet();
setShouldOpenCustomGasSheet({ focusTo: null, shouldOpen: false });
}
@@ -494,6 +526,7 @@ const GasSpeedButton = ({
<MotiView
animate={{ opacity: 1 }}
from={{ opacity: 0 }}
// @ts-expect-error - MotiTransitionProp is not assignable to TransitionConfig
transition={{
duration: 300,
easing: Easing.bezier(0.2, 0, 0, 1),
Loading