From f0496b3e6114bc2327b6db2e42541f37fb9622c8 Mon Sep 17 00:00:00 2001 From: Tyler Date: Thu, 17 Oct 2024 19:39:50 -0400 Subject: [PATCH] i messed up --- src/clients/metadataService.ts | 3 +- src/components/BackButton.tsx | 2 +- src/components/Button.tsx | 6 +- src/components/Details.tsx | 6 +- src/components/DropdownMenu.tsx | 2 +- src/components/FormInput.tsx | 2 +- src/components/Input.tsx | 2 +- src/components/NavigationMenu.tsx | 4 +- src/components/Table.tsx | 27 ++--- src/components/TimeoutButton.tsx | 4 +- src/components/ValidatorIcons.tsx | 2 +- src/components/WithHovercard.tsx | 4 +- src/components/WithTooltip.tsx | 4 +- src/components/visx/TimeSeriesChart.tsx | 8 +- .../visx/XYChartTooltipWithBounds.tsx | 22 ++-- src/components/visx/getScaleBandwidth.ts | 2 +- src/constants/analytics.ts | 4 +- src/constants/cctp.ts | 18 +-- src/constants/indexer.ts | 2 +- src/constants/localization.ts | 3 +- src/constants/time.ts | 6 +- src/hooks/Orderbook/useOrderbookValues.ts | 2 +- src/hooks/tradingView/useBuySellMarks.ts | 4 +- src/hooks/tradingView/useChartLines.tsx | 23 ++-- .../useChartMarketAndResolution.ts | 4 +- src/hooks/tradingView/useOrderbookCandles.ts | 4 +- src/hooks/tradingView/useTradingView.ts | 4 +- .../tradingView/useTradingViewDatafeed.ts | 2 +- .../tradingView/useTradingViewLaunchable.ts | 6 +- src/hooks/tradingView/useTradingViewTheme.ts | 44 ++++--- src/hooks/useAccountBalance.ts | 4 +- src/hooks/useAccounts.tsx | 2 +- src/hooks/useAnalytics.ts | 4 +- src/hooks/useDydxClient.tsx | 6 +- src/hooks/useLaunchableMarkets.ts | 5 +- src/hooks/useLocalNotifications.tsx | 6 +- src/hooks/useMarketsData.ts | 4 +- src/hooks/useMatchingEvmNetwork.ts | 4 +- src/hooks/useNextClobPairId.ts | 2 +- src/hooks/useNotificationTypes.tsx | 14 +-- src/hooks/useNotifications.tsx | 5 +- src/hooks/usePotentialMarkets.tsx | 5 +- src/hooks/useStakingValidator.ts | 2 +- src/hooks/useSubaccount.tsx | 27 ++--- src/hooks/useTriggerOrdersFormInputs.ts | 8 +- src/hooks/useWalletConnection.ts | 2 +- src/layout/Footer/FooterDesktop.tsx | 2 +- src/layout/NotificationsToastArea/index.tsx | 2 +- src/lib/__test__/skip.spec.ts | 4 +- src/lib/abacus/dydxChainTransactions.ts | 14 +-- src/lib/abacus/index.ts | 4 +- src/lib/abacus/rest.ts | 4 +- src/lib/abacus/stateNotification.ts | 11 +- src/lib/compliance.ts | 6 +- src/lib/formatString.ts | 4 +- src/lib/localStorage.ts | 6 +- src/lib/numbers.ts | 2 +- src/lib/objectHelpers.ts | 4 + src/lib/orderbookHelpers.ts | 6 +- src/lib/orders.ts | 8 +- src/lib/positions.ts | 6 +- src/lib/skip.ts | 2 +- src/lib/statsig.ts | 2 +- src/lib/testFlags.ts | 4 +- src/lib/tradeData.ts | 6 +- src/lib/tradingView/dydxfeed/cache.ts | 4 +- .../tradingView/launchableMarketFeed/index.ts | 4 +- src/lib/txUtils.ts | 2 +- src/lib/typeUtils.ts | 4 +- src/lib/wagmi.ts | 7 +- src/pages/markets/Markets.tsx | 2 +- src/pages/markets/NewMarket.tsx | 2 +- .../portfolio/AccountDetailsAndHistory.tsx | 2 +- .../portfolio/AccountOverviewSection.tsx | 2 +- src/pages/portfolio/Overview.tsx | 3 +- src/pages/portfolio/PortfolioNavMobile.tsx | 4 +- src/pages/settings/Settings.tsx | 2 +- src/pages/settings/SettingsHeader.tsx | 2 +- src/pages/token/RewardsPage.tsx | 4 +- src/pages/vaults/VaultDepositWithdrawForm.tsx | 29 +++-- src/pages/vaults/VaultInfoSections.tsx | 10 +- src/pages/vaults/VaultPnlChart.tsx | 4 +- src/pages/vaults/VaultTransactions.tsx | 2 +- src/state/account.ts | 13 ++- src/state/accountSelectors.ts | 71 ++++++------ src/state/assets.ts | 6 +- src/state/localOrders.ts | 2 +- src/state/localOrdersSelectors.ts | 2 +- src/state/localization.ts | 2 +- src/state/localizationSelectors.ts | 2 +- src/state/migrations/1.ts | 2 +- src/state/migrations/__test__/1.test.ts | 10 +- src/state/perpetuals.ts | 20 ++-- src/state/perpetualsSelectors.ts | 30 +++-- src/styles/articleMixins.ts | 4 +- src/styles/formMixins.ts | 4 +- src/styles/layoutMixins.ts | 4 +- src/styles/popoverMixins.ts | 4 +- src/styles/tabMixins.ts | 4 +- src/styles/tableMixins.ts | 4 +- src/styles/tradeViewMixins.ts | 4 +- .../AccountInfo/AccountInfoConnectedState.tsx | 2 +- src/views/CanvasOrderbook/CanvasOrderbook.tsx | 2 +- src/views/MarketFilter.tsx | 2 +- src/views/MarketsDropdown.tsx | 2 +- src/views/PositionInfo.tsx | 59 +++++----- src/views/charts/DepthChart/Tooltip.tsx | 4 +- src/views/charts/DepthChart/index.tsx | 12 +- src/views/charts/FundingChart/index.tsx | 6 +- src/views/charts/LaunchableMarketChart.tsx | 2 +- src/views/charts/PnlChart.tsx | 8 +- src/views/charts/TradingRewardsChart.tsx | 10 +- src/views/charts/TradingView/TvChart.tsx | 2 +- .../dialogs/AdjustIsolatedMarginDialog.tsx | 2 +- .../dialogs/AdjustTargetLeverageDialog.tsx | 2 +- .../CancelAllOrdersConfirmationDialog.tsx | 2 +- .../dialogs/CancelPendingOrdersDialog.tsx | 2 +- .../CloseAllPositionsConfirmationDialog.tsx | 2 +- src/views/dialogs/ClosePositionDialog.tsx | 2 +- .../DetailsDialog/OrderDetailsDialog.tsx | 2 +- src/views/dialogs/GeoComplianceDialog.tsx | 2 +- src/views/dialogs/HelpDialog.tsx | 2 +- src/views/dialogs/ManageFundsDialog.tsx | 2 +- src/views/dialogs/OnboardingDialog.tsx | 4 +- .../dialogs/OnboardingDialog/GenerateKeys.tsx | 2 +- src/views/dialogs/SelectMarginModeDialog.tsx | 2 +- src/views/dialogs/StakeDialog.tsx | 2 +- src/views/dialogs/TradeDialog.tsx | 4 +- src/views/dialogs/TransferDialog.tsx | 2 +- src/views/dialogs/UnstakeDialog.tsx | 2 +- .../dialogs/VaultDepositWithdrawDialog.tsx | 2 +- .../AccountManagementForms/DepositForm.tsx | 6 +- .../DepositForm/DepositButtonAndReceipt.tsx | 8 +- .../AccountManagementForms/SlippageEditor.tsx | 4 +- .../TokenSelectMenu.tsx | 8 +- .../AccountManagementForms/WithdrawForm.tsx | 6 +- .../WithdrawForm/WithdrawButtonAndReceipt.tsx | 8 +- src/views/forms/AdjustIsolatedMarginForm.tsx | 2 +- src/views/forms/AdjustTargetLeverageForm.tsx | 2 +- .../forms/CancelAllOrdersInMarketForm.tsx | 7 +- src/views/forms/ClosePositionForm.tsx | 2 +- .../NewMarketForm/NewMarketPreviewStep.tsx | 6 +- .../NewMarketForm/NewMarketSelectionStep.tsx | 4 +- .../v7/NewMarketSelectionStep.tsx | 2 +- .../StakeForm/ValidatorDropdown.tsx | 4 +- .../UnstakeForm/UnstakeFormInputContents.tsx | 7 +- .../UnstakeFormPreviewContents.tsx | 7 +- .../forms/StakingForms/UnstakeForm/index.tsx | 3 +- .../StakingForms/shared/ValidatorName.tsx | 4 +- src/views/forms/TradeForm.tsx | 6 +- .../forms/TradeForm/AdvancedTradeOptions.tsx | 2 +- src/views/forms/TradeForm/PositionPreview.tsx | 6 +- .../forms/TradeForm/TradeFormInfoMessages.tsx | 2 +- .../forms/TradeForm/useTradeTypeOptions.tsx | 2 +- src/views/forms/TransferForm.tsx | 14 +-- .../TransferForm/TransferButtonAndReceipt.tsx | 4 +- src/views/forms/TriggersForm/TriggersForm.tsx | 6 +- src/views/menus/AccountMenu.tsx | 4 +- src/views/menus/NotificationsMenu.tsx | 8 +- src/views/menus/useGlobalCommands.tsx | 3 +- .../notifications/OrderCancelNotification.tsx | 2 +- .../notifications/OrderStatusNotification.tsx | 6 +- .../notifications/TradeNotification/index.tsx | 2 +- .../TransferStatusSteps.tsx | 12 +- .../TransferStatusNotification/index.tsx | 6 +- src/views/tables/FillsTable.tsx | 9 +- src/views/tables/OrdersTable.tsx | 5 +- src/views/tables/PositionsTable.tsx | 108 +++++++++--------- 168 files changed, 607 insertions(+), 541 deletions(-) diff --git a/src/clients/metadataService.ts b/src/clients/metadataService.ts index 30b027ac5..8c8b8a091 100644 --- a/src/clients/metadataService.ts +++ b/src/clients/metadataService.ts @@ -6,6 +6,7 @@ import { MetadataServicePricesResponse, } from '@/constants/assetMetadata'; +import { MapOf } from '@/lib/objectHelpers'; import { log } from '@/lib/telemetry'; /** @@ -37,7 +38,7 @@ class MetadataServiceClient { return fetch(`${this.host}/${endpoint}`).then((res) => res.json()); } - async getMarketmap(): Promise> { + async getMarketmap(): Promise> { return this._get(MetadataServicePath.MARKET_MAP); } diff --git a/src/components/BackButton.tsx b/src/components/BackButton.tsx index 524fc69bb..8b9693ed4 100644 --- a/src/components/BackButton.tsx +++ b/src/components/BackButton.tsx @@ -18,7 +18,7 @@ export const BackButton = ({ const navigation = globalThis.navigation; if (!navigation) { - globalThis.history?.back(); + globalThis.history.back(); // @ts-ignore } else if (navigation.canGoBack) { navigation.back(); diff --git a/src/components/Button.tsx b/src/components/Button.tsx index 888233af7..f5ae4f6ac 100644 --- a/src/components/Button.tsx +++ b/src/components/Button.tsx @@ -6,6 +6,8 @@ import { ButtonAction, ButtonShape, ButtonSize, ButtonState } from '@/constants/ import { LoadingDots } from '@/components/Loading/LoadingDots'; +import { MapOf } from '@/lib/objectHelpers'; + import { BaseButton, BaseButtonProps } from './BaseButton'; export type ButtonStateConfig = { @@ -27,7 +29,7 @@ type ElementProps = { type StyleProps = { action?: ButtonAction; - state: Record; + state: MapOf; className?: string; }; @@ -50,7 +52,7 @@ export const Button = forwardRef { - const state: Record = + const state: MapOf = typeof stateConfig === 'string' ? { [stateConfig]: true } : { diff --git a/src/components/Details.tsx b/src/components/Details.tsx index b3d2b1ea8..926b9e217 100644 --- a/src/components/Details.tsx +++ b/src/components/Details.tsx @@ -12,11 +12,13 @@ import { layoutMixins } from '@/styles/layoutMixins'; import { WithSeparators } from '@/components/Separator'; import { WithTooltip } from '@/components/WithTooltip'; +import { MapOf } from '@/lib/objectHelpers'; + export type DetailsItem = { // eslint-disable-next-line react/no-unused-prop-types key: string; tooltip?: TooltipStringKeys; - tooltipParams?: Record; + tooltipParams?: MapOf; label: string | JSX.Element; value?: Nullable | JSX.Element | undefined; // eslint-disable-next-line react/no-unused-prop-types @@ -210,7 +212,7 @@ const itemLayoutVariants = { justify-items: start; gap: 0.375rem; `, -} satisfies Record>; +} satisfies MapOf>; const $Details = styled.dl<{ layout: 'column' | 'row' | 'rowColumns' | 'grid' | 'stackColumn'; withSeparators: boolean; diff --git a/src/components/DropdownMenu.tsx b/src/components/DropdownMenu.tsx index a4174eb01..569ecff0c 100644 --- a/src/components/DropdownMenu.tsx +++ b/src/components/DropdownMenu.tsx @@ -79,7 +79,7 @@ export const DropdownMenu = forwardRefFn( <$Item disabled={!item.onSelect} $highlightColor={item.highlightColor} - onSelect={item?.onSelect} + onSelect={item.onSelect} > {item.icon} {item.label} diff --git a/src/components/FormInput.tsx b/src/components/FormInput.tsx index 14e7d872c..689c10f76 100644 --- a/src/components/FormInput.tsx +++ b/src/components/FormInput.tsx @@ -32,7 +32,7 @@ export const FormInput = forwardRef( <$FormInputContainer className={className} isValidationAttached={validationConfig?.attached}> <$InputContainer hasLabel={!!label} hasSlotRight={!!slotRight}> {label ? ( - <$WithLabel label={label} inputID={id} disabled={otherProps?.disabled}> + <$WithLabel label={label} inputID={id} disabled={otherProps.disabled}> ) : ( diff --git a/src/components/Input.tsx b/src/components/Input.tsx index 2ce6ef907..a00216178 100644 --- a/src/components/Input.tsx +++ b/src/components/Input.tsx @@ -175,7 +175,7 @@ export const Input = forwardRef( ? undefined : Number(newFormattedValue.replace(',', '.')); - onInput?.({ value: newValue, floatValue, formattedValue: newFormattedValue, ...e }); + onInput({ value: newValue, floatValue, formattedValue: newFormattedValue, ...e }); }} // Native disabled={disabled} diff --git a/src/components/NavigationMenu.tsx b/src/components/NavigationMenu.tsx index 717de69e3..742487a84 100644 --- a/src/components/NavigationMenu.tsx +++ b/src/components/NavigationMenu.tsx @@ -148,9 +148,9 @@ export const NavigationMenu = 0 ? 'menu' : orientation === 'vertical' ? 'vertical' : 'menu'} > - {item?.subitems?.map((subitem) => ( + {item.subitems?.map((subitem) => ( <$ListItem key={subitem.value} value={subitem.value} data-item={subitem.value}> - {subitem?.subitems ? ( + {subitem.subitems ? ( renderSubitems({ item: subitem, depth: depth + 1 }) ) : ( <$NavItem onSelect={onSelectItem} orientation={itemOrientation} {...subitem} /> diff --git a/src/components/Table.tsx b/src/components/Table.tsx index 21fc4ef57..f6cf65a5f 100644 --- a/src/components/Table.tsx +++ b/src/components/Table.tsx @@ -34,6 +34,7 @@ import breakpoints from '@/styles/breakpoints'; import { layoutMixins } from '@/styles/layoutMixins'; import { MustBigNumber } from '@/lib/numbers'; +import { MapOf } from '@/lib/objectHelpers'; import { testFlags } from '@/lib/testFlags'; import { Icon, IconName } from './Icon'; @@ -99,7 +100,7 @@ export type TableElementProps[]; data: Array; getRowKey: (rowData: TableRowData, rowIndex?: number) => Key; - getRowAttributes?: (rowData: TableRowData, rowIndex?: number) => Record; + getRowAttributes?: (rowData: TableRowData, rowIndex?: number) => MapOf; defaultSortDescriptor?: SortDescriptor; selectionMode?: 'multiple' | 'single'; selectionBehavior?: 'replace' | 'toggle'; @@ -215,10 +216,10 @@ export const Table = ({ const [sortDescriptor, setSortDescriptor] = useState(defaultSortDescriptor ?? {}); const items = useMemo(() => { - return sortDescriptor?.column - ? [...data].sort((a, b) => sortFn(a, b, sortDescriptor?.column, sortDescriptor?.direction)) + return sortDescriptor.column + ? [...data].sort((a, b) => sortFn(a, b, sortDescriptor.column, sortDescriptor.direction)) : data; - }, [data, sortDescriptor?.column, sortDescriptor?.direction, sortFn]); + }, [data, sortDescriptor.column, sortDescriptor.direction, sortFn]); const isEmpty = data.length === 0; const shouldPaginate = paginationBehavior === 'paginate' && data.length > Math.min(...PAGE_SIZES); @@ -299,7 +300,7 @@ export const Table = ({ {(columnKey) => ( {isTableRowData(item) && - columns.find((column) => column.columnKey === columnKey)?.renderCell?.(item)} + columns.find((column) => column.columnKey === columnKey)?.renderCell(item)} )} @@ -325,7 +326,7 @@ const TableRoot = (prop getRowAttributes?: ( rowData: TableRowData, rowIndex?: number - ) => Record>; + ) => MapOf>; onRowAction?: (key: Key) => void; children: TableStateProps['children']; numColumns: number; @@ -425,7 +426,7 @@ const TableRoot = (prop withOuterBorder={withOuterBorder} > {[...collection.body.childNodes].map((row) => - (row.value as CustomRowConfig)?.slotCustomRow ? ( + (row.value as CustomRowConfig).slotCustomRow ? ( (row.value as CustomRowConfig).slotCustomRow({ item: row, state, @@ -452,7 +453,7 @@ const TableRoot = (prop state={state} isActionable={ ((cell as GridNode).column?.value as ColumnDef) - ?.isActionable + .isActionable } /> ) @@ -568,7 +569,7 @@ const TableColumnHeader = ({ // data-focused={isFocusVisible || undefined} style={{ width: column.props?.width, - textAlign: (column?.value as any)?.align, + textAlign: (column.value as any)?.align, }} ref={ref} allowSorting={column.props?.allowsSorting ?? true} @@ -580,8 +581,8 @@ const TableColumnHeader = ({ (uiRefresh ? ( @@ -589,8 +590,8 @@ const TableColumnHeader = ({ <$SortArrow aria-hidden="true" sortDirection={ - state.sortDescriptor?.column === column.key - ? state.sortDescriptor?.direction ?? 'none' + state.sortDescriptor.column === column.key + ? state.sortDescriptor.direction ?? 'none' : 'none' } > diff --git a/src/components/TimeoutButton.tsx b/src/components/TimeoutButton.tsx index 8ffc0d270..9defe270f 100644 --- a/src/components/TimeoutButton.tsx +++ b/src/components/TimeoutButton.tsx @@ -43,8 +43,8 @@ export const TimeoutButton = ({ state={{ isDisabled: secondsLeft > 0 || - otherProps?.state === ButtonState.Disabled || - (otherProps?.state as ButtonStateConfig)?.isDisabled, + otherProps.state === ButtonState.Disabled || + (otherProps.state as ButtonStateConfig).isDisabled, }} > {secondsLeft diff --git a/src/components/ValidatorIcons.tsx b/src/components/ValidatorIcons.tsx index b38802b09..5cd3f9066 100644 --- a/src/components/ValidatorIcons.tsx +++ b/src/components/ValidatorIcons.tsx @@ -21,7 +21,7 @@ export const ValidatorIcons = ({ const validatorNames = validators.map((validator) => validator.description?.moniker).join(', '); return ( <$ValidatorIcons className={className}> - {validators?.length <= numToShow + {validators.length <= numToShow ? validators.map((validator) => ( <$ValidatorIcon key={validator.description?.moniker} diff --git a/src/components/WithHovercard.tsx b/src/components/WithHovercard.tsx index cd7db7f13..d10db22c6 100644 --- a/src/components/WithHovercard.tsx +++ b/src/components/WithHovercard.tsx @@ -10,9 +10,11 @@ import { useStringGetter } from '@/hooks/useStringGetter'; import { popoverMixins } from '@/styles/popoverMixins'; +import { MapOf } from '@/lib/objectHelpers'; + type ElementProps = { hovercard?: TooltipStringKeys; - stringParams?: Record; + stringParams?: MapOf; slotTrigger?: ReactNode; slotButton?: ReactNode; }; diff --git a/src/components/WithTooltip.tsx b/src/components/WithTooltip.tsx index 2f676b732..3c8e47878 100644 --- a/src/components/WithTooltip.tsx +++ b/src/components/WithTooltip.tsx @@ -16,11 +16,13 @@ import { popoverMixins } from '@/styles/popoverMixins'; import { Icon, IconName } from '@/components/Icon'; import { Link } from '@/components/Link'; +import { MapOf } from '@/lib/objectHelpers'; + type ElementProps = { tooltip?: TooltipStringKeys; tooltipString?: string; tooltipStringTitle?: string; - stringParams?: Record; + stringParams?: MapOf; withIcon?: boolean; children?: ReactNode; slotTooltip?: ReactNode; diff --git a/src/components/visx/TimeSeriesChart.tsx b/src/components/visx/TimeSeriesChart.tsx index ef5014a1f..243254d14 100644 --- a/src/components/visx/TimeSeriesChart.tsx +++ b/src/components/visx/TimeSeriesChart.tsx @@ -139,8 +139,8 @@ export const TimeSeriesChart = ({ // Chart data const { xAccessor, yAccessor } = series[0]; - const earliestDatum = data?.[0]; - const latestDatum = data?.[data.length - 1]; + const earliestDatum = data[0]; + const latestDatum = data[data.length - 1]; // Chart state const getClampedZoomDomain = useCallback( @@ -361,8 +361,8 @@ export const TimeSeriesChart = ({ colorAccessor={ childSeries.threshold ? () => 'transparent' : childSeries.colorAccessor } - onPointerMove={childSeries?.onPointerMove} - onPointerOut={childSeries?.onPointerOut} + onPointerMove={childSeries.onPointerMove} + onPointerOut={childSeries.onPointerOut} /> {(childSeries.glyphSize ?? childSeries.getGlyphSize) && ( diff --git a/src/components/visx/XYChartTooltipWithBounds.tsx b/src/components/visx/XYChartTooltipWithBounds.tsx index 3d39a5be2..add339749 100644 --- a/src/components/visx/XYChartTooltipWithBounds.tsx +++ b/src/components/visx/XYChartTooltipWithBounds.tsx @@ -132,14 +132,14 @@ const TooltipInner = ({ onTooltipContext?.(tooltipContext); }, [tooltipContext]); - const tooltipContent = tooltipContext?.tooltipOpen + const tooltipContent = tooltipContext.tooltipOpen ? renderTooltip({ ...tooltipContext, colorScale }) : null; - const showTooltip = tooltipContext?.tooltipOpen && tooltipContent != null; + const showTooltip = tooltipContext.tooltipOpen && tooltipContent != null; - let computedTooltipLeft = tooltipContext?.tooltipLeft ?? 0; - let computedTooltipTop = tooltipContext?.tooltipTop ?? 0; + let computedTooltipLeft = tooltipContext.tooltipLeft ?? 0; + let computedTooltipTop = tooltipContext.tooltipTop ?? 0; let crosshairLeft = computedTooltipLeft; let crosshairTop = computedTooltipTop; @@ -164,7 +164,7 @@ const TooltipInner = ({ [dataRegistry, xScaleBandwidth, yScaleBandwidth, xScale, yScale] ); - const nearestDatum = tooltipContext?.tooltipData?.nearestDatum; + const nearestDatum = tooltipContext.tooltipData?.nearestDatum; const nearestDatumKey = nearestDatum?.key ?? ''; if (showTooltip && nearestDatum) { @@ -185,7 +185,7 @@ const TooltipInner = ({ const size = Number(glyphStyle?.radius ?? 4); if (showSeriesGlyphs) { - Object.values(tooltipContext?.tooltipData?.datumByKey ?? {}).forEach( + Object.values(tooltipContext.tooltipData?.datumByKey ?? {}).forEach( ({ key, datum, index }) => { const color = colorScale?.(key) ?? theme?.htmlLabel?.color ?? '#222'; const { left, top } = getDatumLeftTop(key, datum); @@ -213,7 +213,7 @@ const TooltipInner = ({ const color = (nearestDatumKey && colorScale?.(nearestDatumKey)) ?? null ?? - theme?.gridStyles?.stroke ?? + theme?.gridStyles.stroke ?? theme?.htmlLabel?.color ?? '#222'; glyphProps.push({ @@ -249,7 +249,7 @@ const TooltipInner = ({ y1={margin.top} y2={margin.top + innerHeight} strokeWidth={1.5} - stroke={theme?.gridStyles?.stroke ?? theme?.htmlLabel?.color ?? '#222'} + stroke={theme?.gridStyles.stroke ?? theme?.htmlLabel?.color ?? '#222'} {...verticalCrosshairStyle} /> )} @@ -261,7 +261,7 @@ const TooltipInner = ({ y1={crosshairTop} y2={crosshairTop} strokeWidth={1.5} - stroke={theme?.gridStyles?.stroke ?? theme?.htmlLabel?.color ?? '#222'} + stroke={theme?.gridStyles.stroke ?? theme?.htmlLabel?.color ?? '#222'} {...horizontalCrosshairStyle} /> )} @@ -269,7 +269,7 @@ const TooltipInner = ({ {nearestDatum && renderXAxisLabel && ( - {renderXAxisLabel?.({ ...tooltipContext, colorScale })} + {renderXAxisLabel({ ...tooltipContext, colorScale })} )} @@ -281,7 +281,7 @@ const TooltipInner = ({ top={crosshairTop} > - {renderYAxisLabel?.({ ...tooltipContext, colorScale })} + {renderYAxisLabel({ ...tooltipContext, colorScale })} )} diff --git a/src/components/visx/getScaleBandwidth.ts b/src/components/visx/getScaleBandwidth.ts index ceabb0bbd..db27c9530 100644 --- a/src/components/visx/getScaleBandwidth.ts +++ b/src/components/visx/getScaleBandwidth.ts @@ -2,5 +2,5 @@ import { AxisScale } from '@visx/axis'; export function getScaleBandwidth(s?: Scale) { - return s && 'bandwidth' in s ? s?.bandwidth() ?? 0 : 0; + return s && 'bandwidth' in s ? s.bandwidth() ?? 0 : 0; } diff --git a/src/constants/analytics.ts b/src/constants/analytics.ts index 18be7e5a5..ad9744d8e 100644 --- a/src/constants/analytics.ts +++ b/src/constants/analytics.ts @@ -4,6 +4,8 @@ import { RecordOf, TagsOf, UnionOf, ofType, unionize } from 'unionize'; import { StatsigFlags } from '@/constants/statsig'; import { ConnectorType, WalletType } from '@/constants/wallets'; +import { MapOf } from '@/lib/objectHelpers'; + import type { AbacusApiStatus, HumanReadablePlaceOrderPayload } from './abacus'; import type { OnboardingState, OnboardingSteps } from './account'; import { DialogTypesTypes } from './dialogs'; @@ -231,7 +233,7 @@ export const AnalyticsEvents = unionize( TransferNotification: ofType<{ type: TransferNotificationTypes | undefined; toAmount: number | undefined; - timeSpent: Record | number | undefined; + timeSpent: MapOf | number | undefined; txHash: string; status: 'new' | 'success' | 'error'; triggeredAt: number | undefined; diff --git a/src/constants/cctp.ts b/src/constants/cctp.ts index 2669e20c8..72a489296 100644 --- a/src/constants/cctp.ts +++ b/src/constants/cctp.ts @@ -1,3 +1,5 @@ +import { MapOf } from '@/lib/objectHelpers'; + import cctpTokens from '../../public/configs/cctp.json'; import { TransferType, TransferTypeType } from './abacus'; @@ -33,10 +35,10 @@ export const getMapOfLowestFeeTokensByDenom = (type: NullableTransferType) => if (!acc[token.tokenAddress]) { acc[token.tokenAddress] = []; } - acc[token.tokenAddress].push(token); + acc[token.tokenAddress]!.push(token); return acc; }, - {} as Record + {} as MapOf ); const getMapOfChainsByChainId = (chains: CctpTokenInfo[]) => @@ -45,10 +47,10 @@ const getMapOfChainsByChainId = (chains: CctpTokenInfo[]) => if (!acc[token.chainId]) { acc[token.chainId] = []; } - acc[token.chainId].push(token); + acc[token.chainId]!.push(token); return acc; }, - {} as Record + {} as MapOf ); export const getMapOfLowestFeeTokensByChainId = (type: NullableTransferType) => @@ -62,10 +64,10 @@ export const cctpTokensByDenom = cctpTokens.reduce( if (!acc[token.tokenAddress]) { acc[token.tokenAddress] = []; } - acc[token.tokenAddress].push(token); + acc[token.tokenAddress]!.push(token); return acc; }, - {} as Record + {} as MapOf ); export const cctpTokensByChainId = cctpTokens.reduce( @@ -73,8 +75,8 @@ export const cctpTokensByChainId = cctpTokens.reduce( if (!acc[token.chainId]) { acc[token.chainId] = []; } - acc[token.chainId].push(token); + acc[token.chainId]!.push(token); return acc; }, - {} as Record + {} as MapOf ); diff --git a/src/constants/indexer.ts b/src/constants/indexer.ts index 5191381d8..a1b2251f6 100644 --- a/src/constants/indexer.ts +++ b/src/constants/indexer.ts @@ -23,5 +23,5 @@ export type PerpetualMarketResponse = { }; export type PerpetualMarketSparklineResponse = { - [key: string]: number[]; + [key: string]: number[] | undefined; }; diff --git a/src/constants/localization.ts b/src/constants/localization.ts index 0b24ab48c..4a2f2a555 100644 --- a/src/constants/localization.ts +++ b/src/constants/localization.ts @@ -15,6 +15,7 @@ import { StatsigConfigType } from '@/constants/statsig'; import { type LinksConfigs } from '@/hooks/useURLConfigs'; import formatString from '@/lib/formatString'; +import { MapOf } from '@/lib/objectHelpers'; export { TOOLTIP_STRING_KEYS } from '@dydxprotocol/v4-localization'; @@ -52,7 +53,7 @@ export type StringKey = keyof typeof STRING_KEYS; export type LocaleData = typeof EN_LOCALE_DATA; -export type StringGetterParams = Record; +export type StringGetterParams = MapOf; export type StringGetterProps = | { diff --git a/src/constants/time.ts b/src/constants/time.ts index 1ae9b7eb4..557d90c15 100644 --- a/src/constants/time.ts +++ b/src/constants/time.ts @@ -1,3 +1,5 @@ +import { MapOf } from '@/lib/objectHelpers'; + // Good Til Time Timescales export enum TimeUnitShort { Minutes = 'M', @@ -20,11 +22,11 @@ const smallTimeUnits = { decisecond: 100, centisecond: 10, millisecond: 1, -} satisfies Partial>; +} satisfies MapOf; const otherTimeUnits = { threeDays: 3 * timeUnits.day, -} satisfies Partial>; +} satisfies MapOf; export const allTimeUnits = { ...timeUnits, diff --git a/src/hooks/Orderbook/useOrderbookValues.ts b/src/hooks/Orderbook/useOrderbookValues.ts index 30a8eb5a9..811fc3388 100644 --- a/src/hooks/Orderbook/useOrderbookValues.ts +++ b/src/hooks/Orderbook/useOrderbookValues.ts @@ -94,7 +94,7 @@ export const useOrderbookValuesForDepthChart = () => { const highestAsk = asks[asks.length - 1]; const midMarketPrice = orderbook?.midPrice; - const spread = MustBigNumber(lowestAsk?.price ?? 0).minus(highestBid?.price ?? 0); + const spread = MustBigNumber(lowestAsk.price ?? 0).minus(highestBid.price ?? 0); const spreadPercent = orderbook?.spreadPercent; return { diff --git a/src/hooks/tradingView/useBuySellMarks.ts b/src/hooks/tradingView/useBuySellMarks.ts index fa9cc0ea4..b607a6573 100644 --- a/src/hooks/tradingView/useBuySellMarks.ts +++ b/src/hooks/tradingView/useBuySellMarks.ts @@ -37,10 +37,10 @@ export function useBuySellMarks({ tvWidget.onChartReady(() => { tvWidget.headerReady().then(() => { if (buySellMarksToggleOn) { - buySellMarksToggle?.classList?.add(TOGGLE_ACTIVE_CLASS_NAME); + buySellMarksToggle?.classList.add(TOGGLE_ACTIVE_CLASS_NAME); tvWidget.activeChart().refreshMarks(); } else { - buySellMarksToggle?.classList?.remove(TOGGLE_ACTIVE_CLASS_NAME); + buySellMarksToggle?.classList.remove(TOGGLE_ACTIVE_CLASS_NAME); tvWidget.activeChart().clearMarks(); } }); diff --git a/src/hooks/tradingView/useChartLines.tsx b/src/hooks/tradingView/useChartLines.tsx index bab55d394..eacb35f7b 100644 --- a/src/hooks/tradingView/useChartLines.tsx +++ b/src/hooks/tradingView/useChartLines.tsx @@ -34,6 +34,7 @@ import { getCurrentMarketId } from '@/state/perpetualsSelectors'; import abacusStateManager from '@/lib/abacus'; import { track } from '@/lib/analytics/analytics'; import { MustBigNumber } from '@/lib/numbers'; +import { MapOf } from '@/lib/objectHelpers'; import { cancelOrderAsync, canModifyOrderTypeFromChart, @@ -70,7 +71,7 @@ export const useChartLines = ({ const stringGetter = useStringGetter(); const dispatch = useAppDispatch(); - const chartLinesRef = useRef>({}); + const chartLinesRef = useRef>({}); const appTheme = useAppSelector(getAppTheme); const appColorMode = useAppSelector(getAppColorMode); @@ -195,9 +196,9 @@ export const useChartLines = ({ return; } - const entryPrice = currentMarketPositionData.entryPrice?.current; - const liquidationPrice = currentMarketPositionData.liquidationPrice?.current; - const size = currentMarketPositionData.size?.current; + const entryPrice = currentMarketPositionData.entryPrice.current; + const liquidationPrice = currentMarketPositionData.liquidationPrice.current; + const size = currentMarketPositionData.size.current; maybeDrawPositionLine({ key: entryLineKey, @@ -218,7 +219,9 @@ export const useChartLines = ({ // Cache for order modification that stores the new orders that are submitted but not yet placed const pendingOrderAdjustmentsRef = useRef<{ - [clientId: string]: { orderPayload: HumanReadablePlaceOrderPayload; oldOrderId: string }; + [clientId: string]: + | { orderPayload: HumanReadablePlaceOrderPayload; oldOrderId: string } + | undefined; }>({}); const removePendingOrderAdjustment = (clientId: string) => { @@ -338,7 +341,7 @@ export const useChartLines = ({ const orderString = trailingPercent ? `${orderLabel} ${trailingPercent}%` : orderLabel; const pendingReplacementOrder = Object.values(pendingOrderAdjustments).find( - (adjustment) => adjustment.oldOrderId === id + (adjustment) => adjustment?.oldOrderId === id ); const replacementOrderPlaced = !!currentMarketOrders.find( (o) => o.clientId === pendingReplacementOrder?.orderPayload.clientId @@ -413,8 +416,8 @@ export const useChartLines = ({ ]); const clearChartLines = useCallback(() => { - Object.values(chartLinesRef.current).forEach(({ line }) => { - line.remove(); + Object.values(chartLinesRef.current).forEach((line) => { + line?.line.remove(); }); chartLinesRef.current = {}; }, []); @@ -436,9 +439,9 @@ export const useChartLines = ({ if (isChartReady) { runOnChartReady(() => { if (orderLinesToggleOn) { - orderLineToggle?.classList?.add(TOGGLE_ACTIVE_CLASS_NAME); + orderLineToggle?.classList.add(TOGGLE_ACTIVE_CLASS_NAME); } else { - orderLineToggle?.classList?.remove(TOGGLE_ACTIVE_CLASS_NAME); + orderLineToggle?.classList.remove(TOGGLE_ACTIVE_CLASS_NAME); } }); } diff --git a/src/hooks/tradingView/useChartMarketAndResolution.ts b/src/hooks/tradingView/useChartMarketAndResolution.ts index 83d9c2ac7..1ee708d9f 100644 --- a/src/hooks/tradingView/useChartMarketAndResolution.ts +++ b/src/hooks/tradingView/useChartMarketAndResolution.ts @@ -36,7 +36,7 @@ export const useChartMarketAndResolution = ({ useAppSelector((s) => getSelectedResolutionForMarket(s, currentMarketId)) ?? DEFAULT_RESOLUTION; const chart = isWidgetReady ? tvWidget?.chart() : undefined; - const chartResolution = chart?.resolution?.(); + const chartResolution = chart?.resolution(); /** * @description Hook to handle changing markets - intentionally should avoid triggering on change of resolutions. @@ -68,7 +68,7 @@ export const useChartMarketAndResolution = ({ const setVisibleRangeForResolution = ({ resolution }: { resolution: ResolutionString }) => { // Different resolutions have different timeframes to display data efficiently. const defaultRange: number | undefined = isViewingUnlaunchedMarket - ? LAUNCHABLE_MARKET_RESOLUTION_CONFIGS[resolution]?.defaultRange + ? LAUNCHABLE_MARKET_RESOLUTION_CONFIGS[resolution].defaultRange : RESOLUTION_CHART_CONFIGS[resolution].defaultRange; if (defaultRange) { diff --git a/src/hooks/tradingView/useOrderbookCandles.ts b/src/hooks/tradingView/useOrderbookCandles.ts index e043337ee..44262a24c 100644 --- a/src/hooks/tradingView/useOrderbookCandles.ts +++ b/src/hooks/tradingView/useOrderbookCandles.ts @@ -27,9 +27,9 @@ export const useOrderbookCandles = ({ tvWidget.onChartReady(() => { tvWidget.headerReady().then(() => { if (orderbookCandlesToggleOn) { - orderbookCandlesToggle?.classList?.add(TOGGLE_ACTIVE_CLASS_NAME); + orderbookCandlesToggle?.classList.add(TOGGLE_ACTIVE_CLASS_NAME); } else { - orderbookCandlesToggle?.classList?.remove(TOGGLE_ACTIVE_CLASS_NAME); + orderbookCandlesToggle?.classList.remove(TOGGLE_ACTIVE_CLASS_NAME); } abacusStateManager.toggleOrderbookCandles(orderbookCandlesToggleOn); }); diff --git a/src/hooks/tradingView/useTradingView.ts b/src/hooks/tradingView/useTradingView.ts index 04b55617f..7da205162 100644 --- a/src/hooks/tradingView/useTradingView.ts +++ b/src/hooks/tradingView/useTradingView.ts @@ -187,8 +187,8 @@ export const useTradingView = ({ } }); - tvWidgetRef?.current?.subscribe('onAutoSaveNeeded', () => - tvWidgetRef?.current?.save((chartConfig: object) => { + tvWidgetRef.current?.subscribe('onAutoSaveNeeded', () => + tvWidgetRef.current?.save((chartConfig: object) => { dispatch(updateChartConfig(chartConfig)); }) ); diff --git a/src/hooks/tradingView/useTradingViewDatafeed.ts b/src/hooks/tradingView/useTradingViewDatafeed.ts index 04f43f593..06ca79180 100644 --- a/src/hooks/tradingView/useTradingViewDatafeed.ts +++ b/src/hooks/tradingView/useTradingViewDatafeed.ts @@ -219,7 +219,7 @@ export const useTradingViewDatafeed = ( // If there are not enough candles in the store, retrieve more from the API if (cachedBars.length < countBack) { - const earliestCachedBarTime = cachedBars?.[cachedBars.length - 1]?.time; + const earliestCachedBarTime = cachedBars[cachedBars.length - 1]?.time; fetchedCandles = await getCandlesForDatafeed({ marketId: symbolInfo.ticker!, diff --git a/src/hooks/tradingView/useTradingViewLaunchable.ts b/src/hooks/tradingView/useTradingViewLaunchable.ts index 30f7ec218..e969c3cf7 100644 --- a/src/hooks/tradingView/useTradingViewLaunchable.ts +++ b/src/hooks/tradingView/useTradingViewLaunchable.ts @@ -65,15 +65,15 @@ export const useTradingViewLaunchable = ({ symbol: marketId, saved_data: !isEmpty(savedTvChartConfig) ? savedTvChartConfig : undefined, auto_save_delay: 1, - disabled_features: [...(widgetOptions?.disabled_features ?? []), 'chart_scroll'], + disabled_features: [...(widgetOptions.disabled_features ?? []), 'chart_scroll'], }; const tvChartWidget = new Widget(options); tvWidgetRef.current = tvChartWidget; tvChartWidget.onChartReady(() => { - tvWidgetRef?.current?.subscribe('onAutoSaveNeeded', () => - tvWidgetRef?.current?.save((chartConfig: object) => { + tvWidgetRef.current?.subscribe('onAutoSaveNeeded', () => + tvWidgetRef.current?.save((chartConfig: object) => { dispatch(updateLaunchableMarketsChartConfig(chartConfig)); }) ); diff --git a/src/hooks/tradingView/useTradingViewTheme.ts b/src/hooks/tradingView/useTradingViewTheme.ts index 426f8ecd6..c298eabc2 100644 --- a/src/hooks/tradingView/useTradingViewTheme.ts +++ b/src/hooks/tradingView/useTradingViewTheme.ts @@ -8,6 +8,7 @@ import { AppColorMode, AppTheme } from '@/state/configs'; import { getAppColorMode, getAppTheme } from '@/state/configsSelectors'; import { assertNever } from '@/lib/assertNever'; +import { MapOf } from '@/lib/objectHelpers'; import { getChartLineColors, getWidgetOverrides } from '@/lib/tradingView/utils'; /** @@ -28,7 +29,7 @@ export const useTradingViewTheme = ({ tvWidget, isWidgetReady, }: { - chartLines?: Record; + chartLines?: MapOf; tvWidget: TvWidget | null; isWidgetReady?: boolean; }) => { @@ -37,25 +38,25 @@ export const useTradingViewTheme = ({ useEffect(() => { if (tvWidget && isWidgetReady) { - tvWidget.changeTheme?.(THEME_NAMES[appTheme]).then(() => { - const tvChartId = tvWidget?._id; + tvWidget.changeTheme(THEME_NAMES[appTheme]).then(() => { + const tvChartId = tvWidget._id; if (tvChartId) { - const frame = document?.getElementById(tvChartId); + const frame = document.getElementById(tvChartId); if (isIFrame(frame) && frame.contentWindow) { const innerHtml = frame.contentWindow.document.documentElement; switch (appTheme) { case AppTheme.Classic: - innerHtml?.classList.remove('theme-dark', 'theme-light'); + innerHtml.classList.remove('theme-dark', 'theme-light'); break; case AppTheme.Dark: - innerHtml?.classList.remove('theme-light'); - innerHtml?.classList.add('theme-dark'); + innerHtml.classList.remove('theme-light'); + innerHtml.classList.add('theme-dark'); break; case AppTheme.Light: - innerHtml?.classList.remove('theme-dark'); - innerHtml?.classList.add('theme-light'); + innerHtml.classList.remove('theme-dark'); + innerHtml.classList.add('theme-light'); break; default: assertNever(appTheme); @@ -66,17 +67,17 @@ export const useTradingViewTheme = ({ // eslint-disable-next-line @typescript-eslint/naming-convention const { overrides, studies_overrides } = getWidgetOverrides({ appTheme, appColorMode }); - tvWidget?.applyOverrides(overrides); - tvWidget?.applyStudiesOverrides(studies_overrides); + tvWidget.applyOverrides(overrides); + tvWidget.applyStudiesOverrides(studies_overrides); // Necessary to update existing indicators const volumeStudyId = tvWidget - ?.activeChart() - ?.getAllStudies() - ?.find((x) => x.name === 'Volume')?.id; + .activeChart() + .getAllStudies() + .find((x) => x.name === 'Volume')?.id; if (volumeStudyId) { - const volume = tvWidget?.activeChart()?.getStudyById(volumeStudyId); + const volume = tvWidget.activeChart().getStudyById(volumeStudyId); volume.applyOverrides({ 'volume.color.0': studies_overrides['volume.volume.color.0'], 'volume.color.1': studies_overrides['volume.volume.color.1'], @@ -85,15 +86,20 @@ export const useTradingViewTheme = ({ if (chartLines) { // Necessary to update existing chart lines - Object.values(chartLines).forEach(({ chartLineType, line }) => { + Object.values(chartLines).forEach((line) => { + if (line == null) { + return; + } const { maybeQuantityColor, borderColor, backgroundColor, textColor, textButtonColor } = - getChartLineColors({ chartLineType, appTheme, appColorMode }); + getChartLineColors({ chartLineType: line.chartLineType, appTheme, appColorMode }); if (maybeQuantityColor) { - line.setLineColor(maybeQuantityColor).setQuantityBackgroundColor(maybeQuantityColor); + line.line + .setLineColor(maybeQuantityColor) + .setQuantityBackgroundColor(maybeQuantityColor); } - line + line.line .setQuantityBorderColor(borderColor) .setBodyBackgroundColor(backgroundColor) .setBodyBorderColor(borderColor) diff --git a/src/hooks/useAccountBalance.ts b/src/hooks/useAccountBalance.ts index c555ba6db..134b7febe 100644 --- a/src/hooks/useAccountBalance.ts +++ b/src/hooks/useAccountBalance.ts @@ -237,7 +237,7 @@ export const useAccountBalance = ({ ? formatUnits(evmNativeBalance, evmNativeDecimals) : undefined : evmTokenBalance?.result !== undefined && evmTokenDecimals?.result !== undefined - ? formatUnits(evmTokenBalance?.result, evmTokenDecimals?.result) + ? formatUnits(evmTokenBalance.result, evmTokenDecimals.result) : undefined; // remove fee from usdc cosmos balance @@ -245,7 +245,7 @@ export const useAccountBalance = ({ ? Math.max(parseFloat(cosmosQuery.data) - COSMOS_GAS_RESERVE, 0) : undefined; - const solBalance = solanaQuery?.data?.data.formatted; + const solBalance = solanaQuery.data?.data.formatted; const balance = isCosmosChain ? cosmosBalance : isSolanaChain ? solBalance : evmBalance; diff --git a/src/hooks/useAccounts.tsx b/src/hooks/useAccounts.tsx index 3c98f0c24..20c07ae2a 100644 --- a/src/hooks/useAccounts.tsx +++ b/src/hooks/useAccounts.tsx @@ -209,7 +209,7 @@ const useAccountsContext = () => { if (!localDydxWallet) { dispatch(setOnboardingState(OnboardingState.WalletConnected)); - if (sourceAccount?.encryptedSignature && geo && !blockedGeo) { + if (sourceAccount.encryptedSignature && geo && !blockedGeo) { try { const signature = decryptSignature(sourceAccount.encryptedSignature); await setWalletFromSignature(signature); diff --git a/src/hooks/useAnalytics.ts b/src/hooks/useAnalytics.ts index 4b5a8cc22..71f68d207 100644 --- a/src/hooks/useAnalytics.ts +++ b/src/hooks/useAnalytics.ts @@ -232,8 +232,8 @@ export const useAnalytics = () => { if (selectedWallet) { track( AnalyticsEvents.ConnectWallet({ - walletType: selectedWallet?.name, - walletConnectorType: selectedWallet?.connectorType!, + walletType: selectedWallet.name, + walletConnectorType: selectedWallet.connectorType!, }) ); } else if (previousSelectedWallet) { diff --git a/src/hooks/useDydxClient.tsx b/src/hooks/useDydxClient.tsx index 1343f53f7..77737debd 100644 --- a/src/hooks/useDydxClient.tsx +++ b/src/hooks/useDydxClient.tsx @@ -81,9 +81,9 @@ const useDydxClientContext = () => { (async () => { if ( networkConfig?.chainId && - networkConfig?.indexerUrl && - networkConfig?.websocketUrl && - networkConfig?.validatorUrl + networkConfig.indexerUrl && + networkConfig.websocketUrl && + networkConfig.validatorUrl ) { try { const initializedClient = await CompositeClient.connect( diff --git a/src/hooks/useLaunchableMarkets.ts b/src/hooks/useLaunchableMarkets.ts index 9c15b788b..82fe1c3af 100644 --- a/src/hooks/useLaunchableMarkets.ts +++ b/src/hooks/useLaunchableMarkets.ts @@ -17,6 +17,7 @@ import { getMarketIds } from '@/state/perpetualsSelectors'; import metadataClient from '@/clients/metadataService'; import { getAssetFromMarketId } from '@/lib/assetUtils'; import { getTickSizeDecimalsFromPrice } from '@/lib/numbers'; +import { MapOf } from '@/lib/objectHelpers'; import { mapMetadataServiceCandles } from '@/lib/tradingView/utils'; export const useMetadataService = () => { @@ -42,7 +43,7 @@ export const useMetadataService = () => { combine: (results) => { const info = results[0].data; const prices = results[1].data; - const data: Record = {}; + const data: MapOf = {}; Object.keys(info ?? {}).forEach((key) => { if (info?.[key] && prices?.[key]) { @@ -90,7 +91,7 @@ export const useMetadataServiceAssetFromId = (marketId?: string) => { } const assetId = getAssetFromMarketId(marketId); - return metadataServiceData.data?.[assetId]; + return metadataServiceData.data[assetId]; }, [metadataServiceData.data, marketId]); return launchableAsset; diff --git a/src/hooks/useLocalNotifications.tsx b/src/hooks/useLocalNotifications.tsx index 04dbf3c80..b1aa7c2e1 100644 --- a/src/hooks/useLocalNotifications.tsx +++ b/src/hooks/useLocalNotifications.tsx @@ -50,7 +50,7 @@ const useLocalNotificationsContext = () => { // Ensure version matches, otherwise wipe useEffect(() => { if ( - allTransferNotifications?.version !== + allTransferNotifications.version !== LOCAL_STORAGE_VERSIONS[LocalStorageKey.TransferNotifications] ) { setAllTransferNotifications({ @@ -157,7 +157,7 @@ const useLocalNotificationsContext = () => { !isExchange && !hasErrors && (!currentStatus?.latestRouteStatusSummary || - currentStatus?.latestRouteStatusSummary === 'ongoing') + currentStatus.latestRouteStatusSummary === 'ongoing') ) { try { const skipParams = { @@ -178,7 +178,7 @@ const useLocalNotificationsContext = () => { }); if (status) { transferNotification.status = status; - if (status?.latestRouteStatusSummary === 'success') { + if (status.latestRouteStatusSummary === 'success') { track( AnalyticsEvents.TransferNotification({ triggeredAt, diff --git a/src/hooks/useMarketsData.ts b/src/hooks/useMarketsData.ts index e950d04d8..30ef1241d 100644 --- a/src/hooks/useMarketsData.ts +++ b/src/hooks/useMarketsData.ts @@ -116,14 +116,14 @@ export const useMarketsData = ( .filter(isTruthy) // temporary filterout TRUMPWIN until the backend is working .filter( - (m) => m.assetId !== 'TRUMPWIN' || featureFlags?.[StatsigFlags.ffShowPredictionMarketsUi] + (m) => m.assetId !== 'TRUMPWIN' || featureFlags[StatsigFlags.ffShowPredictionMarketsUi] ) .map((marketData): MarketData => { const sevenDaySparklineEntries = sevenDaysSparklineData?.[marketData.id]?.length ?? 0; const isNew = Boolean( sevenDaysSparklineData && sevenDaySparklineEntries < SEVEN_DAY_SPARKLINE_ENTRIES ); - const clobPairId = allPerpetualClobIds?.[marketData.id] ?? 0; + const clobPairId = allPerpetualClobIds[marketData.id] ?? 0; const { assetId, displayId, diff --git a/src/hooks/useMatchingEvmNetwork.ts b/src/hooks/useMatchingEvmNetwork.ts index e045811cb..3f96f0869 100644 --- a/src/hooks/useMatchingEvmNetwork.ts +++ b/src/hooks/useMatchingEvmNetwork.ts @@ -35,9 +35,9 @@ export const useMatchingEvmNetwork = ({ const matchNetwork = useCallback(async () => { if (!isMatchingNetwork) { if (sourceAccount.walletInfo?.connectorType === ConnectorType.Privy) { - await wallets?.[0].switchChain(Number(chainId)); + await wallets[0].switchChain(Number(chainId)); } else { - await switchChainAsync?.({ chainId: Number(chainId) }, { onError, onSuccess }); + await switchChainAsync({ chainId: Number(chainId) }, { onError, onSuccess }); } } }, [chainId, chain]); diff --git a/src/hooks/useNextClobPairId.ts b/src/hooks/useNextClobPairId.ts index 4a0c403b3..4a23aee3c 100644 --- a/src/hooks/useNextClobPairId.ts +++ b/src/hooks/useNextClobPairId.ts @@ -122,7 +122,7 @@ export const useNextClobPairId = () => { } if (markets && Object.values(markets).length > 0) { - const clobPairIds = Object.values(markets)?.map((perpetualMarket) => + const clobPairIds = Object.values(markets).map((perpetualMarket) => Number((perpetualMarket as PerpetualMarketResponse).clobPairId) ); diff --git a/src/hooks/useNotificationTypes.tsx b/src/hooks/useNotificationTypes.tsx index 50f86b67a..976e64c06 100644 --- a/src/hooks/useNotificationTypes.tsx +++ b/src/hooks/useNotificationTypes.tsx @@ -115,8 +115,8 @@ export const notificationTypes: NotificationTypeConfig[] = [ switch (abacusNotificationType) { case 'order': { - const order = ordersById[id]?.[0]; - const clientId: string | undefined = order?.clientId ?? undefined; + const order = ordersById[id][0]; + const clientId: string | undefined = order.clientId ?? undefined; const localOrderExists = clientId && localPlaceOrders.some((ordr) => ordr.clientId === clientId); @@ -250,7 +250,7 @@ export const notificationTypes: NotificationTypeConfig[] = [ }[transferType], }); - const toChainEta = status?.toChain?.chainData?.estimatedRouteDuration ?? 0; + const toChainEta = status?.toChain?.chainData.estimatedRouteDuration ?? 0; // TODO: remove typeguards once skip implements estimatedrouteduration // https://linear.app/dydx/issue/OTE-475/[web]-migration-followup-estimatedrouteduration const estimatedDuration = @@ -332,7 +332,7 @@ export const notificationTypes: NotificationTypeConfig[] = [ } if ( - featureFlags?.[StatsigFlags.ffShowPredictionMarketsUi] && + featureFlags[StatsigFlags.ffShowPredictionMarketsUi] && currentDate <= tradeUSElectionExpirationDate ) { trigger( @@ -355,7 +355,7 @@ export const notificationTypes: NotificationTypeConfig[] = [ ); } - if (featureFlags?.[StatsigFlags.ffEnableKeplr]) { + if (featureFlags[StatsigFlags.ffEnableKeplr]) { trigger( ReleaseUpdateNotificationIds.KeplrSupport, { @@ -503,7 +503,7 @@ export const notificationTypes: NotificationTypeConfig[] = [ useTrigger: ({ trigger }) => { const stringGetter = useStringGetter(); const dynamicConfigs = useAllStatsigDynamicConfigValues(); - const maticWindDownProposal = dynamicConfigs?.[StatsigDynamicConfigs.dcMaticProposalNotif]; + const maticWindDownProposal = dynamicConfigs[StatsigDynamicConfigs.dcMaticProposalNotif]; const { contractLossMechanismLearnMore } = useURLConfigs(); const MATICWindDownProposalExpirationDate = '2024-09-02T14:33:25.000Z'; @@ -804,7 +804,7 @@ export const notificationTypes: NotificationTypeConfig[] = [ const dynamicConfigs = useAllStatsigDynamicConfigValues(); const feedbackRequestWalletAddresses = - dynamicConfigs?.[StatsigDynamicConfigs.dcHighestVolumeUsers]; + dynamicConfigs[StatsigDynamicConfigs.dcHighestVolumeUsers]; useEffect(() => { if (dydxAddress && feedbackRequestWalletAddresses?.includes(dydxAddress) && getInTouch) { diff --git a/src/hooks/useNotifications.tsx b/src/hooks/useNotifications.tsx index f292a3598..9670671a3 100644 --- a/src/hooks/useNotifications.tsx +++ b/src/hooks/useNotifications.tsx @@ -25,6 +25,7 @@ import { import { track } from '@/lib/analytics/analytics'; import { isAbacusNotificationSingleSession } from '@/lib/notifications'; +import { MapOf } from '@/lib/objectHelpers'; import { renderSvgToDataUrl } from '@/lib/renderSvgToDataUrl'; import { useLocalStorage } from './useLocalStorage'; @@ -96,11 +97,11 @@ const useNotificationsContext = () => { // Display data const [notificationsDisplayData, setNotificationsDisplayData] = useState( - {} as Record + {} as MapOf ); const getDisplayData = useCallback( - (notification: Notification) => notificationsDisplayData[getKey(notification)], + (notification: Notification) => notificationsDisplayData[getKey(notification)]!, [getKey, notificationsDisplayData] ); diff --git a/src/hooks/usePotentialMarkets.tsx b/src/hooks/usePotentialMarkets.tsx index 2c51bafad..0b3fab616 100644 --- a/src/hooks/usePotentialMarkets.tsx +++ b/src/hooks/usePotentialMarkets.tsx @@ -4,6 +4,7 @@ import { STRING_KEYS } from '@/constants/localization'; import { LIQUIDITY_TIERS } from '@/constants/markets'; import type { NewMarketProposal } from '@/constants/potentialMarkets'; +import { MapOf } from '@/lib/objectHelpers'; import { log } from '@/lib/telemetry'; import { useStringGetter } from './useStringGetter'; @@ -32,9 +33,9 @@ const usePotentialMarketsContext = () => { try { fetch(POTENTIAL_MARKETS_FILE_PATH) .then((response) => response.json()) - .then((data: Record>) => { + .then((data: MapOf>) => { const newPotentialMarkets = Object.entries(data).map(([key, value]) => ({ - ...value, + ...value!, baseAsset: key, })); setPotentialMarkets(newPotentialMarkets); diff --git a/src/hooks/useStakingValidator.ts b/src/hooks/useStakingValidator.ts index 024c7f3b3..00963b346 100644 --- a/src/hooks/useStakingValidator.ts +++ b/src/hooks/useStakingValidator.ts @@ -34,7 +34,7 @@ export const useStakingValidator = () => { const [selectedValidator, setSelectedValidator] = useState(); - const validatorWhitelist = ENVIRONMENT_CONFIG_MAP[selectedNetwork].stakingValidators?.map( + const validatorWhitelist = ENVIRONMENT_CONFIG_MAP[selectedNetwork].stakingValidators.map( (delegation) => { return delegation.toLowerCase(); } diff --git a/src/hooks/useSubaccount.tsx b/src/hooks/useSubaccount.tsx index 9a76643f2..d2be03c4c 100644 --- a/src/hooks/useSubaccount.tsx +++ b/src/hooks/useSubaccount.tsx @@ -53,6 +53,7 @@ import { parseToPrimitives } from '@/lib/abacus/parseToPrimitives'; import { track } from '@/lib/analytics/analytics'; import { getValidErrorParamsFromParsingError } from '@/lib/errors'; import { isTruthy } from '@/lib/isTruthy'; +import { MapOf } from '@/lib/objectHelpers'; import { log } from '@/lib/telemetry'; import { hashFromTx } from '@/lib/txUtils'; @@ -158,11 +159,11 @@ const useSubaccountContext = ({ localDydxWallet }: { localDydxWallet?: LocalWall }) => { try { return await compositeClient?.validatorClient.post.send( - subaccountClient?.wallet, + subaccountClient.wallet, () => new Promise((resolve) => { const msg = - compositeClient?.validatorClient.post.composer.composeMsgWithdrawFromSubaccount( + compositeClient.validatorClient.post.composer.composeMsgWithdrawFromSubaccount( subaccountClient.address, subaccountClient.subaccountNumber, assetId, @@ -199,7 +200,7 @@ const useSubaccountContext = ({ localDydxWallet }: { localDydxWallet?: LocalWall subaccountClient.wallet, () => new Promise((resolve) => { - const msg = compositeClient?.sendTokenMessage( + const msg = compositeClient.sendTokenMessage( subaccountClient.wallet, amount.toString(), recipient @@ -208,7 +209,7 @@ const useSubaccountContext = ({ localDydxWallet }: { localDydxWallet?: LocalWall resolve([msg]); }), false, - compositeClient?.validatorClient?.post.defaultDydxGasPrice, + compositeClient.validatorClient.post.defaultDydxGasPrice, memo, Method.BroadcastTxCommit ); @@ -758,13 +759,13 @@ const useSubaccountContext = ({ localDydxWallet }: { localDydxWallet?: LocalWall if (!compositeClient) { throw new Error('client not initialized'); } - if (!subaccountClient?.wallet?.address) { + if (!subaccountClient?.wallet.address) { throw new Error('wallet not initialized'); } - const response = await compositeClient?.validatorClient.post.delegate( + const response = await compositeClient.validatorClient.post.delegate( subaccountClient, - subaccountClient.wallet?.address, + subaccountClient.wallet.address, validator, parseUnits(amount.toString(), chainTokenDecimals).toString() ); @@ -802,7 +803,7 @@ const useSubaccountContext = ({ localDydxWallet }: { localDydxWallet?: LocalWall ); const undelegate = useCallback( - async (amounts: Record) => { + async (amounts: MapOf) => { if (!compositeClient) { throw new Error('client not initialized'); } @@ -837,7 +838,7 @@ const useSubaccountContext = ({ localDydxWallet }: { localDydxWallet?: LocalWall ); const getUndelegateFee = useCallback( - async (amounts: Record) => { + async (amounts: MapOf) => { if (!compositeClient) { throw new Error('client not initialized'); } @@ -934,14 +935,14 @@ const useSubaccountContext = ({ localDydxWallet }: { localDydxWallet?: LocalWall if (!compositeClient) { throw new Error('client not initialized'); } - if (!subaccountClient?.wallet?.address) { + if (!subaccountClient?.wallet.address) { throw new Error('wallet not initialized'); } - if (affiliate === subaccountClient?.wallet?.address) { + if (affiliate === subaccountClient.wallet.address) { throw new Error('affiliate can not be the same as referree'); } try { - const response = await compositeClient?.validatorClient.post.registerAffiliate( + const response = await compositeClient.validatorClient.post.registerAffiliate( subaccountClient, affiliate ); @@ -1007,7 +1008,7 @@ const useSubaccountContext = ({ localDydxWallet }: { localDydxWallet?: LocalWall if (!compositeClient?.validatorClient) { throw new Error('client not initialized'); } - const result = await compositeClient?.validatorClient.get.getMegavaultOwnerShares(dydxAddress); + const result = await compositeClient.validatorClient.get.getMegavaultOwnerShares(dydxAddress); if (result == null) { return result; } diff --git a/src/hooks/useTriggerOrdersFormInputs.ts b/src/hooks/useTriggerOrdersFormInputs.ts index 19a64364f..777a111db 100644 --- a/src/hooks/useTriggerOrdersFormInputs.ts +++ b/src/hooks/useTriggerOrdersFormInputs.ts @@ -135,16 +135,16 @@ export const useTriggerOrdersFormInputs = ({ } if (stopLossOrder?.size && takeProfitOrder?.size) { - if (stopLossOrder?.size === takeProfitOrder?.size) { - setSize(stopLossOrder?.size); + if (stopLossOrder.size === takeProfitOrder.size) { + setSize(stopLossOrder.size); } else { setSize(null); setDifferingOrderSizes(true); } } else if (stopLossOrder?.size) { - setSize(stopLossOrder?.size); + setSize(stopLossOrder.size); } else if (takeProfitOrder?.size) { - setSize(takeProfitOrder?.size); + setSize(takeProfitOrder.size); } else { // Default to full position size for initial order creation setSize(positionSize); diff --git a/src/hooks/useWalletConnection.ts b/src/hooks/useWalletConnection.ts index dbb91f929..50a75067f 100644 --- a/src/hooks/useWalletConnection.ts +++ b/src/hooks/useWalletConnection.ts @@ -172,7 +172,7 @@ export const useWalletConnection = () => { // Currently the only usecase for this is piping in EIP specified error codes. // There's a nonzero chance of overlap so we should watch out for this code: error.code, - connectorType: wallet?.connectorType, + connectorType: wallet.connectorType, } ); } diff --git a/src/layout/Footer/FooterDesktop.tsx b/src/layout/Footer/FooterDesktop.tsx index 17c887589..981014246 100644 --- a/src/layout/Footer/FooterDesktop.tsx +++ b/src/layout/Footer/FooterDesktop.tsx @@ -83,7 +83,7 @@ export const FooterDesktop = () => { - {globalThis?.Intercom && ( + {globalThis.Intercom && ( <$FooterButton slotLeft={} size={ButtonSize.XSmall} diff --git a/src/layout/NotificationsToastArea/index.tsx b/src/layout/NotificationsToastArea/index.tsx index d942d8b31..72daae91c 100644 --- a/src/layout/NotificationsToastArea/index.tsx +++ b/src/layout/NotificationsToastArea/index.tsx @@ -53,7 +53,7 @@ export const NotificationsToastArea = ({ className }: StyleProps) => { displayData && notification.status < NotificationStatus.Unseen ) .slice(-MAX_NUM_TOASTS); - return groupBy(notificationMap, (notification) => notification.displayData?.groupKey); + return groupBy(notificationMap, (notification) => notification.displayData.groupKey); }, [notifications, getKey, getDisplayData]); if (isMenuOpen) return null; diff --git a/src/lib/__test__/skip.spec.ts b/src/lib/__test__/skip.spec.ts index 58bebe021..eebe4a1cb 100644 --- a/src/lib/__test__/skip.spec.ts +++ b/src/lib/__test__/skip.spec.ts @@ -28,7 +28,7 @@ const toChainPending = (chainId: string | undefined): SkipTransactionStatus => ( transactionId: undefined, }); -const chainIdsToNames: { [key: string]: TransferChainInfo } = { +const chainIdsToNames = { 1: { chainName: 'Ethereum', chainId: 'noop', @@ -69,7 +69,7 @@ const chainIdsToNames: { [key: string]: TransferChainInfo } = { equals: vi.fn(), hashCode: vi.fn(), }, -}; +} satisfies { [key: string]: TransferChainInfo }; let mockGetChainById: SpyInstance; diff --git a/src/lib/abacus/dydxChainTransactions.ts b/src/lib/abacus/dydxChainTransactions.ts index 163ed18d0..f5585fe5f 100644 --- a/src/lib/abacus/dydxChainTransactions.ts +++ b/src/lib/abacus/dydxChainTransactions.ts @@ -213,7 +213,7 @@ class DydxChainTransactions implements AbacusDYDXChainTransactionsProtocol { const subaccountClient = new SubaccountClient(this.localWallet, subaccountNumber); // Place order - const tx = await this.compositeClient?.placeOrder( + const tx = await this.compositeClient.placeOrder( subaccountClient, marketId, type as OrderType, @@ -234,7 +234,7 @@ class DydxChainTransactions implements AbacusDYDXChainTransactionsProtocol { ); // Handle stateful orders - if ((tx as IndexedTx)?.code !== 0) { + if ((tx as IndexedTx).code !== 0) { throw new StatefulOrderError('Stateful order has failed to commit.', tx); } @@ -268,7 +268,7 @@ class DydxChainTransactions implements AbacusDYDXChainTransactionsProtocol { params ?? {}; try { - const tx = await this.compositeClient?.cancelRawOrder( + const tx = await this.compositeClient.cancelRawOrder( new SubaccountClient(this.localWallet, subaccountNumber), parseInt(clientId, 10), orderFlags, @@ -339,11 +339,11 @@ class DydxChainTransactions implements AbacusDYDXChainTransactionsProtocol { if (!this.localWallet) { throw new Error('Missing compositeClient or localWallet'); } - const msg = compositeClient?.sendTokenMessage(this.localWallet, amount, recipient); + const msg = compositeClient.sendTokenMessage(this.localWallet, amount, recipient); resolve([msg]); }), - this.compositeClient?.validatorClient?.post.defaultDydxGasPrice + this.compositeClient.validatorClient.post.defaultDydxGasPrice ); const parsedTx = parseToPrimitives(tx); @@ -443,7 +443,7 @@ class DydxChainTransactions implements AbacusDYDXChainTransactionsProtocol { dd.info('withdrawToNobleIBC tx submitted', { tx, ibcMsg }); return JSON.stringify({ - txHash: hashFromTx(tx?.hash), + txHash: hashFromTx(tx.hash), }); } catch (error) { log('DydxChainTransactions/withdrawToNobleIBC', error); @@ -537,7 +537,7 @@ class DydxChainTransactions implements AbacusDYDXChainTransactionsProtocol { }): Promise { const address = this.localWallet?.address; try { - if (this.hdkey?.privateKey && this.hdkey?.publicKey) { + if (this.hdkey?.privateKey && this.hdkey.publicKey) { const { signedMessage, timestamp } = await signComplianceSignature( params.message, params.action, diff --git a/src/lib/abacus/index.ts b/src/lib/abacus/index.ts index a06c748f5..c7e4585cc 100644 --- a/src/lib/abacus/index.ts +++ b/src/lib/abacus/index.ts @@ -435,8 +435,8 @@ class AbacusStateManager { getCancelableOrderIds = (marketId: Nullable): string[] => this.stateManager .cancelAllOrdersPayload(marketId) - ?.payloads?.toArray() - ?.map((p) => p.orderId) ?? []; + ?.payloads.toArray() + .map((p) => p.orderId) ?? []; adjustIsolatedMarginOfPosition = ( callback: ( diff --git a/src/lib/abacus/rest.ts b/src/lib/abacus/rest.ts index 0e0a9e3c6..9bc32a6f5 100644 --- a/src/lib/abacus/rest.ts +++ b/src/lib/abacus/rest.ts @@ -3,6 +3,8 @@ import type { Nullable, kollections } from '@dydxprotocol/v4-abacus'; import type { AbacusRestProtocol } from '@/constants/abacus'; import { lastSuccessfulRestRequestByOrigin } from '@/constants/analytics'; +import { MapOf } from '../objectHelpers'; + type Headers = Nullable>; type FetchResponseCallback = (p0: Nullable, p1: number, p2: Nullable) => void; @@ -54,7 +56,7 @@ class AbacusRest implements AbacusRestProtocol { fetch(url, options) .then(async (response) => { const data = await response.text(); - const headersObj: Record = {}; + const headersObj: MapOf = {}; response.headers.forEach((value: string, key: string | number) => { headersObj[key] = value; }); diff --git a/src/lib/abacus/stateNotification.ts b/src/lib/abacus/stateNotification.ts index 41aeb426a..dbaaefcaf 100644 --- a/src/lib/abacus/stateNotification.ts +++ b/src/lib/abacus/stateNotification.ts @@ -43,6 +43,7 @@ import { updateNotifications } from '@/state/notifications'; import { setHistoricalFundings, setLiveTrades, setMarkets, setOrderbook } from '@/state/perpetuals'; import { isTruthy } from '../isTruthy'; +import { MapOf } from '../objectHelpers'; class AbacusStateNotifier implements AbacusStateNotificationProtocol { private store: RootStore | undefined; @@ -72,9 +73,9 @@ class AbacusStateNotifier implements AbacusStateNotificationProtocol { dispatch( setAssets( Object.fromEntries( - (updatedState?.assetIds()?.toArray() ?? []) + (updatedState.assetIds()?.toArray() ?? []) .map((assetId: string) => { - const assetData = updatedState?.asset(assetId); + const assetData = updatedState.asset(assetId); if (assetData == null) { return undefined; } @@ -88,13 +89,13 @@ class AbacusStateNotifier implements AbacusStateNotificationProtocol { if (changes.has(Changes.accountBalances)) { if (updatedState.account?.balances) { - const balances: Record = fromPairs( + const balances: MapOf = fromPairs( updatedState.account.balances.toArray().map(({ k, v }) => [k, v]) ); dispatch(setBalances(balances)); } if (updatedState.account?.stakingBalances) { - const stakingBalances: Record = fromPairs( + const stakingBalances: MapOf = fromPairs( updatedState.account.stakingBalances.toArray().map(({ k, v }) => [k, v]) ); dispatch(setStakingBalances(stakingBalances)); @@ -112,7 +113,7 @@ class AbacusStateNotifier implements AbacusStateNotificationProtocol { if (changes.has(Changes.tradingRewards)) { if (updatedState.account?.tradingRewards) { - dispatch(setTradingRewards(updatedState.account?.tradingRewards)); + dispatch(setTradingRewards(updatedState.account.tradingRewards)); } } diff --git a/src/lib/compliance.ts b/src/lib/compliance.ts index 1ba3fc6ab..139ef738e 100644 --- a/src/lib/compliance.ts +++ b/src/lib/compliance.ts @@ -21,7 +21,7 @@ export const signComplianceSignature = async ( status: string, hdkey: Hdkey ): Promise<{ signedMessage: string; timestamp: number }> => { - if (!hdkey?.privateKey || !hdkey?.publicKey) { + if (!hdkey.privateKey || !hdkey.publicKey) { throw new Error('Missing hdkey'); } @@ -50,8 +50,8 @@ export const signComplianceSignatureKeplr = async ( key: LocalStorageKey.KeplrCompliance, }); - const storedSignature = stored[signer]?.signature; - const storedPubKey = stored[signer]?.pubKey; + const storedSignature = stored[signer].signature; + const storedPubKey = stored[signer].pubKey; if (storedPubKey && storedSignature) { return { diff --git a/src/lib/formatString.ts b/src/lib/formatString.ts index 8eb86a04a..6c85bad81 100644 --- a/src/lib/formatString.ts +++ b/src/lib/formatString.ts @@ -1,9 +1,11 @@ // implemntation based on https://github.com/stefalda/react-localization/blob/master/src/LocalizedStrings.js import React from 'react'; +import { MapOf } from './objectHelpers'; + const PLACEHOLDER_REGEX = /(\{[\d|\w]+\})/; -export type StringGetterParams = Record; +export type StringGetterParams = MapOf; const formatString = ( str: string, diff --git a/src/lib/localStorage.ts b/src/lib/localStorage.ts index f6e7d28a2..9f8b5110e 100644 --- a/src/lib/localStorage.ts +++ b/src/lib/localStorage.ts @@ -10,7 +10,7 @@ export const setLocalStorage = ({ key, value }: { key: LocalStorageKey; v const serializedValue = JSON.stringify(value); - globalThis.localStorage?.setItem(key, serializedValue); + globalThis.localStorage.setItem(key, serializedValue); }; export const getLocalStorage = ({ @@ -23,7 +23,7 @@ export const getLocalStorage = ({ validateFn?: (value: Value) => boolean; }) => { try { - const unserializedValue = globalThis.localStorage?.getItem(key); + const unserializedValue = globalThis.localStorage.getItem(key); if (unserializedValue !== null) { const value = JSON.parse(unserializedValue) as Value; @@ -40,5 +40,5 @@ export const getLocalStorage = ({ }; const removeLocalStorage = ({ key }: { key: LocalStorageKey }) => { - globalThis.localStorage?.removeItem(key); + globalThis.localStorage.removeItem(key); }; diff --git a/src/lib/numbers.ts b/src/lib/numbers.ts index b4502a0ae..0a54c9df7 100644 --- a/src/lib/numbers.ts +++ b/src/lib/numbers.ts @@ -65,7 +65,7 @@ export const getSeparator = ({ }) => Intl.NumberFormat(browserLanguage) .formatToParts(1000.1) - .find?.((part) => part.type === separatorType)?.value; + .find((part) => part.type === separatorType)?.value; /** * Converts a byte array (representing an arbitrary-size signed integer) into a bigint. diff --git a/src/lib/objectHelpers.ts b/src/lib/objectHelpers.ts index b20b43130..77668f95a 100644 --- a/src/lib/objectHelpers.ts +++ b/src/lib/objectHelpers.ts @@ -10,3 +10,7 @@ export const objectKeys = (t: T) => Object.keys(t) as Array = Record; diff --git a/src/lib/orderbookHelpers.ts b/src/lib/orderbookHelpers.ts index a590b76f5..b4909d54f 100644 --- a/src/lib/orderbookHelpers.ts +++ b/src/lib/orderbookHelpers.ts @@ -1,6 +1,8 @@ // ------ Canvas helper methods ------ // import type { MarketOrderbook, Nullable, PerpetualMarketOrderbookLevel } from '@/constants/abacus'; +import { MapOf } from './objectHelpers'; + /** * @returns top left x,y and bottom x,y from array idx */ @@ -100,8 +102,8 @@ export const processOrderbookToCreateMap = ({ newOrderbook, }: { orderbookMap?: { - asks: Record; - bids: Record; + asks: MapOf; + bids: MapOf; }; newOrderbook: Nullable; }) => { diff --git a/src/lib/orders.ts b/src/lib/orders.ts index bfcb7ed40..1a2daa14f 100644 --- a/src/lib/orders.ts +++ b/src/lib/orders.ts @@ -22,6 +22,8 @@ import { IconName } from '@/components/Icon'; import { convertAbacusOrderSide } from '@/lib/abacus/conversions'; +import { MapOf } from './objectHelpers'; + export const getOrderStatusInfo = ({ status }: { status: string }) => { switch (status) { case AbacusOrderStatus.Open.rawValue: { @@ -135,11 +137,11 @@ export const getHydratedTradingData = < perpetualMarkets, }: { data: T; - assets: Record; - perpetualMarkets: Record; + assets: MapOf; + perpetualMarkets: MapOf; }): T & AddedProps => ({ ...data, - asset: assets[perpetualMarkets[data.marketId]?.assetId], + asset: assets[perpetualMarkets[data.marketId]?.assetId ?? ''], stepSizeDecimals: perpetualMarkets[data.marketId]?.configs?.stepSizeDecimals, tickSizeDecimals: perpetualMarkets[data.marketId]?.configs?.tickSizeDecimals, ...('side' in data && { orderSide: convertAbacusOrderSide(data.side) }), diff --git a/src/lib/positions.ts b/src/lib/positions.ts index 95d5be5cb..520223c0a 100644 --- a/src/lib/positions.ts +++ b/src/lib/positions.ts @@ -1,7 +1,7 @@ import { Nullable, SubaccountPosition, type Asset, type PerpetualMarket } from '@/constants/abacus'; import { TOKEN_DECIMALS, USD_DECIMALS } from '@/constants/numbers'; -import { safeAssign } from './objectHelpers'; +import { MapOf, safeAssign } from './objectHelpers'; type HydratedPositionData = SubaccountPosition & { asset?: Asset; @@ -16,8 +16,8 @@ export const getHydratedPositionData = ({ perpetualMarkets, }: { data: SubaccountPosition; - assets?: Record; - perpetualMarkets?: Record; + assets?: MapOf; + perpetualMarkets?: MapOf; }): HydratedPositionData => { return safeAssign({}, data, { asset: assets?.[data.assetId], diff --git a/src/lib/skip.ts b/src/lib/skip.ts index ef330f34a..61ebc11de 100644 --- a/src/lib/skip.ts +++ b/src/lib/skip.ts @@ -223,7 +223,7 @@ export const formSkipStatusResponse = ( routeStatus, toChain: toChainTxData?.transactionStatus, fromChain: fromChainTxData?.transactionStatus, - error: skipStatusResponse?.error?.message, + error: skipStatusResponse.error?.message, }; }; diff --git a/src/lib/statsig.ts b/src/lib/statsig.ts index a7625a868..ac663f7d6 100644 --- a/src/lib/statsig.ts +++ b/src/lib/statsig.ts @@ -65,7 +65,7 @@ export const getStatsigConfigAsync = async (): Promise => { })); const dynamicConfigValuesList = Object.values(StatsigDynamicConfigs).map((dcName) => ({ - [dcName]: client.getDynamicConfig(dcName)?.get('value'), + [dcName]: client.getDynamicConfig(dcName).get('value'), })); const statsigConfig = merge({}, ...gateValuesList, ...dynamicConfigValuesList); return statsigConfig; diff --git a/src/lib/testFlags.ts b/src/lib/testFlags.ts index 04d24ca95..dcb006f5d 100644 --- a/src/lib/testFlags.ts +++ b/src/lib/testFlags.ts @@ -1,7 +1,7 @@ import { isDev } from '@/constants/networks'; class TestFlags { - public queryParams: { [key: string]: string }; + public queryParams: { [key: string]: string | undefined }; constructor() { this.queryParams = {}; @@ -30,7 +30,7 @@ class TestFlags { return !!this.queryParams.displayinitializingmarkets; } - get addressOverride(): string { + get addressOverride(): string | undefined { return this.queryParams.address; } diff --git a/src/lib/tradeData.ts b/src/lib/tradeData.ts index 573c226f9..724923349 100644 --- a/src/lib/tradeData.ts +++ b/src/lib/tradeData.ts @@ -136,7 +136,7 @@ export const getTradeInputAlert = ({ } ); - return inputAlerts?.[0]; + return inputAlerts[0]; }; export const calculateCrossPositionMargin = ({ @@ -171,10 +171,10 @@ export const getPositionMargin = ({ position }: { position: SubaccountPosition } const margin = marginMode === AbacusMarginMode.Cross ? calculateCrossPositionMargin({ - notionalTotal: notionalTotal?.current, + notionalTotal: notionalTotal.current, adjustedImf: adjustedImf.current, }) - : equity?.current; + : equity.current; return margin; }; diff --git a/src/lib/tradingView/dydxfeed/cache.ts b/src/lib/tradingView/dydxfeed/cache.ts index 7ae365cfc..f89acfb30 100644 --- a/src/lib/tradingView/dydxfeed/cache.ts +++ b/src/lib/tradingView/dydxfeed/cache.ts @@ -4,6 +4,8 @@ import type { SubscribeBarsCallback, } from 'public/tradingview/charting_library'; +import { MapOf } from '@/lib/objectHelpers'; + export const lastBarsCache = new Map(); export const subscriptionsByChannelId: Map< string, @@ -11,6 +13,6 @@ export const subscriptionsByChannelId: Map< subscribeUID: string; resolution: ResolutionString; lastBar: Bar; - handlers: Record; + handlers: MapOf<{ id: string; callback: SubscribeBarsCallback }>; } > = new Map(); diff --git a/src/lib/tradingView/launchableMarketFeed/index.ts b/src/lib/tradingView/launchableMarketFeed/index.ts index d5032991e..40a3ece65 100644 --- a/src/lib/tradingView/launchableMarketFeed/index.ts +++ b/src/lib/tradingView/launchableMarketFeed/index.ts @@ -138,10 +138,10 @@ export const getLaunchableMarketDatafeed = ( }); const fetchedCandles: MetadataServiceCandlesResponse[string] | undefined = - candlesResponse?.[asset] ?? []; + candlesResponse[asset] ?? []; if (fetchedCandles) { - bars = [...(fetchedCandles?.map(mapMetadataServiceCandles) ?? [])]; + bars = [...(fetchedCandles.map(mapMetadataServiceCandles) ?? [])]; launchableMarketCandlesCache.set(cacheKey, bars); } } else { diff --git a/src/lib/txUtils.ts b/src/lib/txUtils.ts index 81413fbb8..c5a72da75 100644 --- a/src/lib/txUtils.ts +++ b/src/lib/txUtils.ts @@ -4,4 +4,4 @@ export const hashFromTx = (txHash: string | Uint8Array): string => `0x${Buffer.from(txHash).toString('hex')}`; export const getMintscanTxLink = (dydxChainId: DydxChainId, txHash: string): string => - `${LINKS_CONFIG_MAP[dydxChainId]?.mintscan?.replace('{tx_hash}', txHash.toString())}`; + `${LINKS_CONFIG_MAP[dydxChainId].mintscan.replace('{tx_hash}', txHash.toString())}`; diff --git a/src/lib/typeUtils.ts b/src/lib/typeUtils.ts index e37bb0a50..c46c8021b 100644 --- a/src/lib/typeUtils.ts +++ b/src/lib/typeUtils.ts @@ -1,7 +1,9 @@ import { EMPTY_OBJ } from '@/constants/objects'; +import { MapOf } from './objectHelpers'; + // preserves reference and empty object never churns -export function orEmptyRecord(obj: Record | null | undefined): Record { +export function orEmptyRecord(obj: MapOf | null | undefined): MapOf { return obj ?? (EMPTY_OBJ as any); } diff --git a/src/lib/wagmi.ts b/src/lib/wagmi.ts index f43f5c97f..f7e8ac362 100644 --- a/src/lib/wagmi.ts +++ b/src/lib/wagmi.ts @@ -1,7 +1,7 @@ // Custom connectors import type { PrivyClientConfig } from '@privy-io/react-auth'; import { createConfig } from '@privy-io/wagmi'; -import { fallback, FallbackTransport, http, Transport, type Chain } from 'viem'; +import { FallbackTransport, Transport, fallback, http, type Chain } from 'viem'; import { arbitrum, arbitrumGoerli, @@ -55,6 +55,7 @@ import { getMipdConnectorByRdns } from '@/hooks/useMipdInjectedWallets'; import { isTruthy } from './isTruthy'; import { getLocalStorage } from './localStorage'; import { validateAgainstAvailableEnvironments } from './network'; +import { MapOf } from './objectHelpers'; // Config @@ -144,12 +145,12 @@ export const RPCUrlsByChainId = [mainnet, ...WAGMI_SUPPORTED_CHAINS].reduce( ...chainIdToRpcMap, }; }, - {} as Record + {} as MapOf ); const RPCTransports = [mainnet, ...WAGMI_SUPPORTED_CHAINS].reduce( (transports, chain) => { - const rpcUrls = RPCUrlsByChainId[chain.id]; + const rpcUrls = RPCUrlsByChainId[chain.id]!; const rpcTransports = rpcUrls.map((rpcUrl) => http(rpcUrl)); const rpcTransportsWithDefault = [...rpcTransports, http()]; transports[chain.id] = fallback(rpcTransportsWithDefault); diff --git a/src/pages/markets/Markets.tsx b/src/pages/markets/Markets.tsx index 3aee4a7db..6669f9c58 100644 --- a/src/pages/markets/Markets.tsx +++ b/src/pages/markets/Markets.tsx @@ -35,7 +35,7 @@ const Markets = () => { useDocumentTitle(stringGetter({ key: STRING_KEYS.MARKETS })); const marketsPageBanner = useMemo(() => { - if (featureFlags?.[StatsigFlags.ffShowPredictionMarketsUi]) { + if (featureFlags[StatsigFlags.ffShowPredictionMarketsUi]) { return ( <$MarketsPageBanner to={`${AppRoute.Trade}/${PREDICTION_MARKET.TRUMPWIN}`}> 🇺🇸 {stringGetter({ key: STRING_KEYS.LEVERAGE_TRADE_US_ELECTION })} diff --git a/src/pages/markets/NewMarket.tsx b/src/pages/markets/NewMarket.tsx index f4a738a66..9f65d95c5 100644 --- a/src/pages/markets/NewMarket.tsx +++ b/src/pages/markets/NewMarket.tsx @@ -80,7 +80,7 @@ const NewMarket = () => { subtitle: stringGetter({ key: STRING_KEYS.ADD_MARKET_STEP_3_DESCRIPTION, params: { - REQUIRED_NUM_TOKENS: MustBigNumber(newMarketProposal?.initialDepositAmount) + REQUIRED_NUM_TOKENS: MustBigNumber(newMarketProposal.initialDepositAmount) .div(Number(`1e${chainTokenDecimals}`)) .toFixed(isMainnet ? 0 : chainTokenDecimals), NATIVE_TOKEN_DENOM: chainTokenLabel, diff --git a/src/pages/portfolio/AccountDetailsAndHistory.tsx b/src/pages/portfolio/AccountDetailsAndHistory.tsx index 0082adfe1..3b5ded563 100644 --- a/src/pages/portfolio/AccountDetailsAndHistory.tsx +++ b/src/pages/portfolio/AccountDetailsAndHistory.tsx @@ -60,7 +60,7 @@ const usePortfolioValues = ({ ); const earliestVisibleDatum = visibleData?.[0]; - const latestVisibleDatum = visibleData?.[(visibleData?.length ?? 1) - 1]; + const latestVisibleDatum = visibleData?.[(visibleData.length ?? 1) - 1]; const pnl = useMemo(() => { let pnlDiff; diff --git a/src/pages/portfolio/AccountOverviewSection.tsx b/src/pages/portfolio/AccountOverviewSection.tsx index a4ec74577..2b9946db4 100644 --- a/src/pages/portfolio/AccountOverviewSection.tsx +++ b/src/pages/portfolio/AccountOverviewSection.tsx @@ -52,7 +52,7 @@ export const MegavaultYieldTag = () => { ), diff --git a/src/pages/portfolio/Overview.tsx b/src/pages/portfolio/Overview.tsx index a95e534c4..92145e485 100644 --- a/src/pages/portfolio/Overview.tsx +++ b/src/pages/portfolio/Overview.tsx @@ -36,8 +36,7 @@ export const Overview = () => { const { dydxAddress } = useAccounts(); const dynamicConfigs = useAllStatsigDynamicConfigValues(); - const feedbackRequestWalletAddresses = - dynamicConfigs?.[StatsigDynamicConfigs.dcHighestVolumeUsers]; + const feedbackRequestWalletAddresses = dynamicConfigs[StatsigDynamicConfigs.dcHighestVolumeUsers]; const shouldShowTelegramInvite = dydxAddress && feedbackRequestWalletAddresses?.includes(dydxAddress); const affiliatesEnabled = useStatsigGateValue(StatsigFlags.ffEnableAffiliates); diff --git a/src/pages/portfolio/PortfolioNavMobile.tsx b/src/pages/portfolio/PortfolioNavMobile.tsx index 52f0b1661..8843081ba 100644 --- a/src/pages/portfolio/PortfolioNavMobile.tsx +++ b/src/pages/portfolio/PortfolioNavMobile.tsx @@ -78,10 +78,10 @@ export const PortfolioNavMobile = () => { <$MobilePortfolioHeader> value !== currentRoute?.value)} + items={portfolioRouteItems.filter(({ value }) => value !== currentRoute.value)} onValueChange={navigate} > - {currentRoute?.label} + {currentRoute.label} ); diff --git a/src/pages/settings/Settings.tsx b/src/pages/settings/Settings.tsx index 2fda0adaa..33def5e99 100644 --- a/src/pages/settings/Settings.tsx +++ b/src/pages/settings/Settings.tsx @@ -49,7 +49,7 @@ const SettingsPage = () => { label: stringGetter({ key: STRING_KEYS.NETWORK }), labelRight: selectedNetworkConfig && ( <> - {selectedNetworkConfig?.slotBefore} {selectedNetworkConfig?.label} + {selectedNetworkConfig.slotBefore} {selectedNetworkConfig.label} ), }, diff --git a/src/pages/settings/SettingsHeader.tsx b/src/pages/settings/SettingsHeader.tsx index 34725edfd..8855de5e7 100644 --- a/src/pages/settings/SettingsHeader.tsx +++ b/src/pages/settings/SettingsHeader.tsx @@ -42,7 +42,7 @@ export const SettingsHeader = ({ return ( <$SettingsHeader> -

{currentRoute?.label}

+

{currentRoute.label}

); }; diff --git a/src/pages/token/RewardsPage.tsx b/src/pages/token/RewardsPage.tsx index 93c3723cb..640030732 100644 --- a/src/pages/token/RewardsPage.tsx +++ b/src/pages/token/RewardsPage.tsx @@ -57,8 +57,8 @@ const RewardsPage = () => { const { totalRewards } = useAppSelector(getStakingRewards, shallowEqual) ?? {}; - const totalUsdcRewards = (totalRewards?.toArray() ?? [])?.reduce((total: number, reward) => { - if (reward?.denom === usdcDenom && reward.amount) { + const totalUsdcRewards = (totalRewards?.toArray() ?? []).reduce((total: number, reward) => { + if (reward.denom === usdcDenom && reward.amount) { return total + parseFloat(reward.amount); } return total; diff --git a/src/pages/vaults/VaultDepositWithdrawForm.tsx b/src/pages/vaults/VaultDepositWithdrawForm.tsx index db050ef9f..53d63ed82 100644 --- a/src/pages/vaults/VaultDepositWithdrawForm.tsx +++ b/src/pages/vaults/VaultDepositWithdrawForm.tsx @@ -108,7 +108,7 @@ export const VaultDepositWithdrawForm = ({ vaultBalance: userBalanceUpdated, marginUsage: marginUsageUpdated, withdrawableVaultBalance: userAvailableUpdated, - } = orEmptyObj(validationResponse?.summaryData); + } = orEmptyObj(validationResponse.summaryData); // save initial type to state if it is provided useEffect(() => { @@ -131,7 +131,7 @@ export const VaultDepositWithdrawForm = ({ const errors = useMemo( () => - validationResponse?.errors.toArray().map((error) => { + validationResponse.errors.toArray().map((error) => { const errorStrings: { long?: string | JSX.Element; short?: string } = runFn(() => { const longKey = error.resources.text?.stringKey; const shortKey = error.resources.title?.stringKey; @@ -160,7 +160,7 @@ export const VaultDepositWithdrawForm = ({ }); return safeAssign({}, error, errorStrings); }), - [slippagePercent, stringGetter, validationResponse?.errors, vaultsLearnMore] + [slippagePercent, stringGetter, validationResponse.errors, vaultsLearnMore] ); const onSubmitInputForm = () => { @@ -257,10 +257,7 @@ export const VaultDepositWithdrawForm = ({ }), }); } else if (operation === 'WITHDRAW') { - if ( - submissionData?.withdraw?.shares == null || - submissionData?.withdraw?.minAmount == null - ) { + if (submissionData?.withdraw?.shares == null || submissionData.withdraw.minAmount == null) { notify({ slotTitleLeft: <$SmallIcon iconName={IconName.OrderCanceled} $hasError />, title: stringGetter({ key: STRING_KEYS.MEGAVAULT_CANT_SUBMIT }), @@ -287,16 +284,16 @@ export const VaultDepositWithdrawForm = ({ const startTime = new Date().valueOf(); const result = await withdrawFromMegavault( - submissionData?.withdraw?.shares, - submissionData?.withdraw?.minAmount + submissionData.withdraw.shares, + submissionData.withdraw.minAmount ); const intermediateTime = new Date().valueOf(); await sleep(INDEXER_LAG_ALLOWANCE); const finalTime = new Date().valueOf(); - const events = (result as IndexedTx)?.events; + const events = (result as IndexedTx).events; const actualAmount = events - ?.find((e) => e.type === 'withdraw_from_megavault') + .find((e) => e.type === 'withdraw_from_megavault') ?.attributes.find((a) => a.key === 'redeemed_quote_quantums')?.value; const realAmountReceived = MustBigNumber(actualAmount).div(QUANTUM_MULTIPLIER).toNumber(); @@ -519,12 +516,12 @@ export const VaultDepositWithdrawForm = ({ }, }; - const errorsPreventingSubmit = errors?.filter((e) => e.type.name === 'error') ?? []; + const errorsPreventingSubmit = errors.filter((e) => e.type.name === 'error') ?? []; const hasInputErrors = validationResponse == null || errorsPreventingSubmit.length > 0; const renderedErrors = errors - ?.filter((e) => e.long != null) - ?.filter((e) => !isSubmitting || e.type.name !== 'error') // hide errors if submitting + .filter((e) => e.long != null) + .filter((e) => !isSubmitting || e.type.name !== 'error') // hide errors if submitting .map((alertMessage) => ( - {validationResponse?.summaryData.needSlippageAck && ( + {validationResponse.summaryData.needSlippageAck && ( dispatch(setVaultFormSlippageAck(checked))} @@ -681,7 +678,7 @@ export const VaultDepositWithdrawForm = ({ /> )} - {validationResponse?.summaryData.needTermsAck && ( + {validationResponse.summaryData.needTermsAck && ( dispatch(setVaultFormTermsAck(checked))} diff --git a/src/pages/vaults/VaultInfoSections.tsx b/src/pages/vaults/VaultInfoSections.tsx index 732309e7a..717e5d253 100644 --- a/src/pages/vaults/VaultInfoSections.tsx +++ b/src/pages/vaults/VaultInfoSections.tsx @@ -45,7 +45,7 @@ export const YourVaultDetailsCards = ({ className }: { className?: string }) => myVaultMetadata == null || myVaultMetadata.balanceUsdc === 0 ? ( ) : ( - + ), }, { @@ -54,14 +54,14 @@ export const YourVaultDetailsCards = ({ className }: { className?: string }) => tooltip: 'vault-all-time-pnl' as const, value: myVaultMetadata == null || - myVaultMetadata?.allTimeReturnUsdc == null || - myVaultMetadata?.allTimeReturnUsdc === 0 ? ( + myVaultMetadata.allTimeReturnUsdc == null || + myVaultMetadata.allTimeReturnUsdc === 0 ? ( ) : ( - <$ColoredReturn $sign={getNumberSign(myVaultMetadata?.allTimeReturnUsdc, 0.01)}> + <$ColoredReturn $sign={getNumberSign(myVaultMetadata.allTimeReturnUsdc, 0.01)}>
diff --git a/src/pages/vaults/VaultPnlChart.tsx b/src/pages/vaults/VaultPnlChart.tsx index 2fc12b804..9286d9155 100644 --- a/src/pages/vaults/VaultPnlChart.tsx +++ b/src/pages/vaults/VaultPnlChart.tsx @@ -121,9 +121,9 @@ export const VaultPnlChart = ({ className }: VaultPnlChartProps) => { : undefined; const pnlDiffPercent = atLeastTwoPoints ? (pnlDiff ?? 0) / relevantDataPoints[0] : undefined; - const xAccessorFunc = useCallback((datum: VaultPnlDatum) => datum?.date ?? 0, []); + const xAccessorFunc = useCallback((datum: VaultPnlDatum) => datum.date ?? 0, []); const yAccessorFunc = useCallback( - (datum: VaultPnlDatum) => (selectedChart === 'pnl' ? datum?.totalPnl ?? 0 : datum?.equity ?? 0), + (datum: VaultPnlDatum) => (selectedChart === 'pnl' ? datum.totalPnl ?? 0 : datum.equity ?? 0), [selectedChart] ); diff --git a/src/pages/vaults/VaultTransactions.tsx b/src/pages/vaults/VaultTransactions.tsx index 6a40d7c87..a50ef76e3 100644 --- a/src/pages/vaults/VaultTransactions.tsx +++ b/src/pages/vaults/VaultTransactions.tsx @@ -127,7 +127,7 @@ export const VaultTransactionsTable = ({ transactionHash ? ( {truncateAddress(transactionHash, '')} diff --git a/src/state/account.ts b/src/state/account.ts index a3b2e0681..f0485ec85 100644 --- a/src/state/account.ts +++ b/src/state/account.ts @@ -7,11 +7,11 @@ import { type Nullable, type StakingDelegation, type StakingRewards, - type SubAccountHistoricalPNLs, type Subaccount, type SubaccountFill, type SubaccountFills, type SubaccountFundingPayments, + type SubAccountHistoricalPNLs, type SubaccountOrder, type SubaccountTransfers, type TradingRewards, @@ -23,11 +23,12 @@ import { OnboardingGuard, OnboardingState } from '@/constants/account'; import { LocalStorageKey } from '@/constants/localStorage'; import { getLocalStorage } from '@/lib/localStorage'; +import { MapOf } from '@/lib/objectHelpers'; import { isOrderStatusClearable } from '@/lib/orders'; export type AccountState = { - balances?: Record; - stakingBalances?: Record; + balances?: MapOf; + stakingBalances?: MapOf; stakingDelegations?: StakingDelegation[]; unbondingDelegations?: UnbondingDelegation[]; stakingRewards?: StakingRewards; @@ -56,7 +57,7 @@ export type AccountState = { onboardingGuards: Record; onboardingState: OnboardingState; clearedOrderIds?: string[]; - unseenFillsCountPerMarket: Record; + unseenFillsCountPerMarket: MapOf; hasUnseenOrderUpdates: boolean; historicalPnlPeriod?: HistoricalPnlPeriods; @@ -228,10 +229,10 @@ export const accountSlice = createSlice({ viewedOrders: (state) => { state.hasUnseenOrderUpdates = false; }, - setBalances: (state, action: PayloadAction>) => { + setBalances: (state, action: PayloadAction>) => { state.balances = action.payload; }, - setStakingBalances: (state, action: PayloadAction>) => { + setStakingBalances: (state, action: PayloadAction>) => { state.stakingBalances = action.payload; }, setStakingDelegations: (state, action: PayloadAction) => { diff --git a/src/state/accountSelectors.ts b/src/state/accountSelectors.ts index 2a593f690..646d11839 100644 --- a/src/state/accountSelectors.ts +++ b/src/state/accountSelectors.ts @@ -68,7 +68,7 @@ export const getSubaccountBuyingPower = (state: RootState) => state.account.suba */ export const getSubaccountEquity = (state: RootState) => state.account.subaccount?.equity; -export const getSubaccountHistoricalPnl = (state: RootState) => state.account?.historicalPnl; +export const getSubaccountHistoricalPnl = (state: RootState) => state.account.historicalPnl; /** * @param state * @returns list of a subaccount's open positions. Each item in the list is an open position in a different market. @@ -135,9 +135,9 @@ export const getCurrentMarketIsolatedPositionLeverage = createAppSelector( [getCurrentMarketPositionData], (position) => { if ( - position?.childSubaccountNumber && + position.childSubaccountNumber && position.childSubaccountNumber >= NUM_PARENT_SUBACCOUNTS && - position.leverage?.current + position.leverage.current ) { return Math.abs(Number(position.leverage.current.toFixed(LEVERAGE_DECIMALS))); } @@ -176,14 +176,14 @@ export const getSubaccountUnclearedOrders = createAppSelector( */ export const getMarketOrders = createAppSelector( [getSubaccountUnclearedOrders], - (orders): { [marketId: string]: SubaccountOrder[] } => { + (orders): { [marketId: string]: SubaccountOrder[] | undefined } => { return (orders ?? []).reduce( (marketOrders, order) => { marketOrders[order.marketId] ??= []; - marketOrders[order.marketId].push(order); + marketOrders[order.marketId]!.push(order); return marketOrders; }, - {} as { [marketId: string]: SubaccountOrder[] } + {} as { [marketId: string]: SubaccountOrder[] | undefined } ); } ); @@ -268,15 +268,15 @@ export const getMarketSubaccountOpenOrders = createAppSelector( ( orders ): { - [marketId: string]: SubaccountOrder[]; + [marketId: string]: SubaccountOrder[] | undefined; } => { return (orders ?? []).reduce( (marketOrders, order) => { marketOrders[order.marketId] ??= []; - marketOrders[order.marketId].push(order); + marketOrders[order.marketId]!.push(order); return marketOrders; }, - {} as { [marketId: string]: SubaccountOrder[] } + {} as { [marketId: string]: SubaccountOrder[] | undefined } ); } ); @@ -298,7 +298,7 @@ export const getSubaccountConditionalOrders = () => positions?.forEach((position) => { const orderSideForConditionalOrder = - position?.side?.current === AbacusPositionSide.LONG + position.side.current === AbacusPositionSide.LONG ? AbacusOrderSide.Sell : AbacusOrderSide.Buy; @@ -386,7 +386,7 @@ export const getOrderDetails = () => * @param state * @returns list of fills for the currently connected subaccount */ -export const getSubaccountFills = (state: RootState) => state.account?.fills; +export const getSubaccountFills = (state: RootState) => state.account.fills; /** * @param state @@ -394,14 +394,14 @@ export const getSubaccountFills = (state: RootState) => state.account?.fills; */ export const getMarketFills = createAppSelector( [getSubaccountFills], - (fills): { [marketId: string]: SubaccountFill[] } => { + (fills): { [marketId: string]: SubaccountFill[] | undefined } => { return (fills ?? []).reduce( (marketFills, fill) => { marketFills[fill.marketId] ??= []; - marketFills[fill.marketId].push(fill); + marketFills[fill.marketId]!.push(fill); return marketFills; }, - {} as { [marketId: string]: SubaccountFill[] } + {} as { [marketId: string]: SubaccountFill[] | undefined } ); } ); @@ -432,7 +432,7 @@ export const getFillDetails = () => export const getCurrentMarketFills = createAppSelector( [getCurrentMarketId, getMarketFills], (currentMarketId, marketFills): SubaccountFill[] => - !currentMarketId ? [] : marketFills[currentMarketId] + !currentMarketId ? [] : marketFills[currentMarketId] ?? [] ); const getFillsForOrderId = createAppSelector( @@ -450,13 +450,13 @@ export const getAverageFillPriceForOrder = () => * @param state * @returns list of transfers for the currently connected subaccount */ -export const getSubaccountTransfers = (state: RootState) => state.account?.transfers; +export const getSubaccountTransfers = (state: RootState) => state.account.transfers; /** * @param state * @returns list of funding payments for the currently connected subaccount */ -export const getSubaccountFundingPayments = (state: RootState) => state.account?.fundingPayments; +export const getSubaccountFundingPayments = (state: RootState) => state.account.fundingPayments; /** * @param state @@ -464,14 +464,14 @@ export const getSubaccountFundingPayments = (state: RootState) => state.account? */ export const getMarketFundingPayments = createAppSelector( [getSubaccountFundingPayments], - (fundingPayments): { [marketId: string]: SubaccountFundingPayment[] } => { + (fundingPayments): { [marketId: string]: SubaccountFundingPayment[] | undefined } => { return (fundingPayments ?? []).reduce( (marketFundingPayments, fundingPayment) => { marketFundingPayments[fundingPayment.marketId] ??= []; - marketFundingPayments[fundingPayment.marketId].push(fundingPayment); + marketFundingPayments[fundingPayment.marketId]!.push(fundingPayment); return marketFundingPayments; }, - {} as { [marketId: string]: SubaccountFundingPayment[] } + {} as { [marketId: string]: SubaccountFundingPayment[] | undefined } ); } ); @@ -483,7 +483,7 @@ export const getMarketFundingPayments = createAppSelector( export const getCurrentMarketFundingPayments = createAppSelector( [getCurrentMarketId, getMarketFundingPayments], (currentMarketId, marketFundingPayments): SubaccountFundingPayment[] => - !currentMarketId ? [] : marketFundingPayments[currentMarketId] + !currentMarketId ? [] : marketFundingPayments[currentMarketId] ?? [] ); /** @@ -550,9 +550,9 @@ export const getCurrentMarketTradeInfoNumbers = createAppSelector( [getCurrentMarketOrders, getUnseenFillsCountForMarket, getCurrentMarketFundingPayments], (marketOrders, marketUnseenFillsCount, marketFundingPayments) => { return { - numOpenOrders: marketOrders?.filter((order) => isOpenOrderStatus(order.status)).length, + numOpenOrders: marketOrders.filter((order) => isOpenOrderStatus(order.status)).length, numUnseenFills: marketUnseenFillsCount, - numFundingPayments: marketFundingPayments?.length, + numFundingPayments: marketFundingPayments.length, }; } ); @@ -585,61 +585,58 @@ export const getHasUnseenOrderUpdates = (state: RootState) => state.account.hasU /** * @returns Fee tier id of the current user */ -export const getUserFeeTier = (state: RootState) => state.account?.wallet?.user?.feeTierId; +export const getUserFeeTier = (state: RootState) => state.account.wallet?.user?.feeTierId; /** * @returns user stats of the current user */ export const getUserStats = (state: RootState) => ({ - makerVolume30D: state.account?.wallet?.user?.makerVolume30D, - takerVolume30D: state.account?.wallet?.user?.takerVolume30D, + makerVolume30D: state.account.wallet?.user?.makerVolume30D, + takerVolume30D: state.account.wallet?.user?.takerVolume30D, }); /** * @returns user wallet balances */ -export const getBalances = (state: RootState) => state.account?.balances; +export const getBalances = (state: RootState) => state.account.balances; /** * @returns user wallet staking balances * */ -export const getStakingBalances = (state: RootState) => state.account?.stakingBalances; +export const getStakingBalances = (state: RootState) => state.account.stakingBalances; /** * @returns user wallet staking delegations * */ -export const getStakingDelegations = (state: RootState) => state.account?.stakingDelegations; +export const getStakingDelegations = (state: RootState) => state.account.stakingDelegations; /** * @returns user unbonding delegations * */ -export const getUnbondingDelegations = (state: RootState) => state.account?.unbondingDelegations; +export const getUnbondingDelegations = (state: RootState) => state.account.unbondingDelegations; /** * @returns user staking rewards * */ -export const getStakingRewards = (state: RootState) => state.account?.stakingRewards; +export const getStakingRewards = (state: RootState) => state.account.stakingRewards; /** * @returns account all time trading rewards */ -export const getTotalTradingRewards = (state: RootState) => state.account?.tradingRewards?.total; +export const getTotalTradingRewards = (state: RootState) => state.account.tradingRewards?.total; /** * @returns account trading rewards aggregated by period */ export const getHistoricalTradingRewards = (state: RootState) => - state.account?.tradingRewards?.filledHistory; + state.account.tradingRewards?.filledHistory; /** * @returns account historical trading rewards for the specified perid */ export const getTradingRewardsEventsForPeriod = () => createAppSelector( - [ - (state: RootState) => state.account?.tradingRewards?.rawHistory, - (s, period: string) => period, - ], + [(state: RootState) => state.account.tradingRewards?.rawHistory, (s, period: string) => period], (historicalTradingRewards, period) => historicalTradingRewards?.get(period)?.toArray() ); diff --git a/src/state/assets.ts b/src/state/assets.ts index c6e4a4e6b..4af579610 100644 --- a/src/state/assets.ts +++ b/src/state/assets.ts @@ -2,8 +2,10 @@ import { createSlice, type PayloadAction } from '@reduxjs/toolkit'; import { type Asset } from '@/constants/abacus'; +import { MapOf } from '@/lib/objectHelpers'; + export interface AssetsState { - assets?: Record; + assets?: MapOf; } const initialState: AssetsState = { @@ -14,7 +16,7 @@ export const assetsSlice = createSlice({ name: 'Assets', initialState, reducers: { - setAssets: (state: AssetsState, action: PayloadAction>) => ({ + setAssets: (state: AssetsState, action: PayloadAction>) => ({ ...state, assets: action.payload, }), diff --git a/src/state/localOrders.ts b/src/state/localOrders.ts index b686c5d39..a82b38712 100644 --- a/src/state/localOrders.ts +++ b/src/state/localOrders.ts @@ -76,7 +76,7 @@ export const localOrdersSlice = createSlice({ failedOrderClientIds: _.uniq([ ..._.intersection( localCloseAllPositions.submittedOrderClientIds, - canceledOrders.map((order) => order.clientId)?.filter(isTruthy) + canceledOrders.map((order) => order.clientId).filter(isTruthy) ), ...localCloseAllPositions.failedOrderClientIds, ]), diff --git a/src/state/localOrdersSelectors.ts b/src/state/localOrdersSelectors.ts index 0262dcac9..2ded4623d 100644 --- a/src/state/localOrdersSelectors.ts +++ b/src/state/localOrdersSelectors.ts @@ -7,7 +7,7 @@ import { createAppSelector } from './appTypes'; * @param state * @returns latestOrder of the currently connected subaccount throughout this session */ -export const getLatestOrder = (state: RootState) => state.localOrders?.latestOrder; +export const getLatestOrder = (state: RootState) => state.localOrders.latestOrder; /** * @returns the clientId of the latest order diff --git a/src/state/localization.ts b/src/state/localization.ts index 57c67f591..7860b75af 100644 --- a/src/state/localization.ts +++ b/src/state/localization.ts @@ -50,7 +50,7 @@ export const localizationSlice = createSlice({ AnalyticsEvents.SwitchedLanguageToEULanguage({ previousLocale, newLocale, - browserLanguage: globalThis.navigator?.language, + browserLanguage: globalThis.navigator.language, }) ); } diff --git a/src/state/localizationSelectors.ts b/src/state/localizationSelectors.ts index 9ae9c0781..16f57aa11 100644 --- a/src/state/localizationSelectors.ts +++ b/src/state/localizationSelectors.ts @@ -55,7 +55,7 @@ export const getStringGetterForLocaleData = ( } } - return formatString(formattedString, props?.params); + return formatString(formattedString, props.params); } return ''; diff --git a/src/state/migrations/1.ts b/src/state/migrations/1.ts index 84f4bf757..c34a70365 100644 --- a/src/state/migrations/1.ts +++ b/src/state/migrations/1.ts @@ -89,7 +89,7 @@ export function migration1(state: PersistedState): V1State { address: evmAddress, chain: WalletNetworkType.Evm, encryptedSignature: shouldCopyOverEvmSignature - ? evmDerivedAddresses?.[evmAddress]?.encryptedSignature + ? evmDerivedAddresses[evmAddress].encryptedSignature : undefined, walletInfo: selectedWallet, }, diff --git a/src/state/migrations/__test__/1.test.ts b/src/state/migrations/__test__/1.test.ts index 3bfb62aed..857cb77ef 100644 --- a/src/state/migrations/__test__/1.test.ts +++ b/src/state/migrations/__test__/1.test.ts @@ -40,7 +40,7 @@ describe('migration1', () => { localStorage.setItem('dydx.EvmAddress', JSON.stringify(MOCK_EVM_ADDRESS)); const newState = migration1(V0_STATE); expect(newState).toBeDefined(); - expect(newState.wallet.sourceAccount?.address).toBeUndefined(); + expect(newState.wallet.sourceAccount.address).toBeUndefined(); expect(newState.wallet.sourceAccount.walletInfo).toBeUndefined(); }); @@ -106,8 +106,8 @@ describe('migration1', () => { const newState = migration1(V0_STATE); expect(newState).toBeDefined(); - expect(newState.wallet.sourceAccount?.address).toBe(MOCK_EVM_ADDRESS); - expect(newState.wallet.sourceAccount?.encryptedSignature).toBe(MOCK_EVM_SIGNATURE); + expect(newState.wallet.sourceAccount.address).toBe(MOCK_EVM_ADDRESS); + expect(newState.wallet.sourceAccount.encryptedSignature).toBe(MOCK_EVM_SIGNATURE); }); it('should not migrate over saved encrypted v1 signatures', () => { @@ -123,7 +123,7 @@ describe('migration1', () => { const newState = migration1(V0_STATE); expect(newState).toBeDefined(); - expect(newState.wallet.sourceAccount?.address).toBe(MOCK_EVM_ADDRESS); - expect(newState.wallet.sourceAccount?.encryptedSignature).toBeUndefined(); + expect(newState.wallet.sourceAccount.address).toBe(MOCK_EVM_ADDRESS); + expect(newState.wallet.sourceAccount.encryptedSignature).toBeUndefined(); }); }); diff --git a/src/state/perpetuals.ts b/src/state/perpetuals.ts index 1f573d6b1..5b9ed81e6 100644 --- a/src/state/perpetuals.ts +++ b/src/state/perpetuals.ts @@ -13,28 +13,28 @@ import { LocalStorageKey } from '@/constants/localStorage'; import { DEFAULT_MARKETID, MarketFilters } from '@/constants/markets'; import { getLocalStorage } from '@/lib/localStorage'; -import { objectKeys } from '@/lib/objectHelpers'; +import { MapOf, objectKeys } from '@/lib/objectHelpers'; import { processOrderbookToCreateMap } from '@/lib/orderbookHelpers'; interface CandleDataByMarket { - data: Record; + data: MapOf; selectedResolution: string; } export interface PerpetualsState { currentMarketId?: string; - candles: Record; - liveTrades?: Record; - markets?: Record; - orderbooks?: Record; + candles: MapOf; + liveTrades?: MapOf; + markets?: MapOf; + orderbooks?: MapOf; orderbooksMap?: Record< string, { - asks: Record; - bids: Record; + asks: MapOf; + bids: MapOf; } >; - historicalFundings: Record; + historicalFundings: MapOf; marketFilter: MarketFilters; } @@ -100,7 +100,7 @@ export const perpetualsSlice = createSlice({ }), setMarkets: ( state: PerpetualsState, - action: PayloadAction<{ markets: Record; update?: boolean }> + action: PayloadAction<{ markets: MapOf; update?: boolean }> ) => ({ ...state, markets: action.payload.update diff --git a/src/state/perpetualsSelectors.ts b/src/state/perpetualsSelectors.ts index 0bcaa1107..6a00ad1e7 100644 --- a/src/state/perpetualsSelectors.ts +++ b/src/state/perpetualsSelectors.ts @@ -5,6 +5,7 @@ import { Candle, TradingViewChartBar } from '@/constants/candles'; import { EMPTY_ARR, EMPTY_OBJ } from '@/constants/objects'; import { calculateMarketMaxLeverage } from '@/lib/marketsHelpers'; +import { MapOf } from '@/lib/objectHelpers'; import { mapCandle } from '@/lib/tradingView/utils'; import { orEmptyObj } from '@/lib/typeUtils'; @@ -26,7 +27,7 @@ export const getCurrentMarketId = (state: RootState) => state.perpetuals.current */ export const getCurrentMarketDisplayId = (state: RootState) => { const currentMarketId = getCurrentMarketId(state) ?? ''; - return state.perpetuals?.markets?.[currentMarketId]?.displayId; + return state.perpetuals.markets?.[currentMarketId]?.displayId; }; /** @@ -34,7 +35,7 @@ export const getCurrentMarketDisplayId = (state: RootState) => { */ export const getCurrentMarketAssetId = (state: RootState) => { const currentMarketId = getCurrentMarketId(state) ?? ''; - return state.perpetuals?.markets?.[currentMarketId]?.assetId; + return state.perpetuals.markets?.[currentMarketId]?.assetId; }; /** @@ -59,16 +60,13 @@ export const getMarketIds = (state: RootState) => * @returns clobPairIds of all markets, mapped by marketId. */ export const getPerpetualMarketsClobIds = createAppSelector([getPerpetualMarkets], (markets) => { - return Object.entries(markets ?? {}).reduce( - (acc, [marketId, market]) => { - const clobPairId: Nullable = market?.configs?.clobPairId; - if (clobPairId !== undefined) { - acc[marketId] = Number(clobPairId); - } - return acc; - }, - {} as Record - ); + return Object.entries(markets ?? {}).reduce((acc, [marketId, market]) => { + const clobPairId: Nullable = market?.configs?.clobPairId; + if (clobPairId !== undefined) { + acc[marketId] = Number(clobPairId); + } + return acc; + }, {} as MapOf); }); /** @@ -139,7 +137,7 @@ export const getHistoricalFundings = (state: RootState) => state.perpetuals.hist export const getCurrentMarketHistoricalFundings = createAppSelector( [getHistoricalFundings, getCurrentMarketId], (historicalFundings, currentMarketId) => - currentMarketId ? historicalFundings?.[currentMarketId] ?? EMPTY_ARR : EMPTY_ARR + currentMarketId ? historicalFundings[currentMarketId] ?? EMPTY_ARR : EMPTY_ARR ); /** @@ -171,7 +169,7 @@ export const getPerpetualCandlesForMarket = ( state: RootState, marketId: string, resolution: string -): Candle[] => state.perpetuals.candles?.[marketId]?.data?.[resolution] ?? EMPTY_ARR; +): Candle[] => state.perpetuals.candles[marketId]?.data[resolution] ?? EMPTY_ARR; /** * @@ -194,7 +192,7 @@ export const getPerpetualBarsForPriceChart = (orderbookCandlesToggleOn: boolean) * @returns TvChart resolution for specified marketId */ export const getSelectedResolutionForMarket = (state: RootState, marketId: string) => - state.perpetuals.candles?.[marketId]?.selectedResolution; + state.perpetuals.candles[marketId]?.selectedResolution; /** * @returns Current market's next funding rate @@ -207,7 +205,7 @@ export const getCurrentMarketNextFundingRate = createAppSelector( export const getMarketIdToAssetMetadataMap = createAppSelector( [(state: RootState) => state.perpetuals.markets, (state: RootState) => state.assets.assets], (markets, assets) => { - const mapping = mapValues(markets ?? {}, (v) => assets?.[v.assetId]); + const mapping = mapValues(markets ?? {}, (v) => assets?.[v?.assetId ?? '']); return mapping; } ); diff --git a/src/styles/articleMixins.ts b/src/styles/articleMixins.ts index e32a6d13b..4db726bc7 100644 --- a/src/styles/articleMixins.ts +++ b/src/styles/articleMixins.ts @@ -1,5 +1,7 @@ import { css } from 'styled-components'; +import { MapOf } from '@/lib/objectHelpers'; + export const articleMixins = { article: css` padding: 2rem; @@ -42,4 +44,4 @@ export const articleMixins = { padding: 0.5rem 1rem; } `, -} satisfies Record>; +} satisfies MapOf>; diff --git a/src/styles/formMixins.ts b/src/styles/formMixins.ts index be4bf748d..a9014cefd 100644 --- a/src/styles/formMixins.ts +++ b/src/styles/formMixins.ts @@ -1,5 +1,7 @@ import { css } from 'styled-components'; +import { MapOf } from '@/lib/objectHelpers'; + import breakpoints from './breakpoints'; import { layoutMixins } from './layoutMixins'; @@ -191,4 +193,4 @@ export const formMixins = { --form-input-gap: 1rem; } `, -} satisfies Record>; +} satisfies MapOf>; diff --git a/src/styles/layoutMixins.ts b/src/styles/layoutMixins.ts index e4a81d515..25444418a 100644 --- a/src/styles/layoutMixins.ts +++ b/src/styles/layoutMixins.ts @@ -1,5 +1,7 @@ import { css, keyframes } from 'styled-components'; +import { MapOf } from '@/lib/objectHelpers'; + const withOuterBorder = css` box-shadow: 0 0 0 var(--border-width) var(--border-color); `; @@ -1022,4 +1024,4 @@ export const layoutMixins = { min-height: 100%; place-items: center; `, -} satisfies Record>; +} satisfies MapOf>; diff --git a/src/styles/popoverMixins.ts b/src/styles/popoverMixins.ts index e2e61a31e..465d1dfde 100644 --- a/src/styles/popoverMixins.ts +++ b/src/styles/popoverMixins.ts @@ -1,5 +1,7 @@ import { css, keyframes } from 'styled-components'; +import { MapOf } from '@/lib/objectHelpers'; + import { headerMixins } from './headerMixins'; import { layoutMixins } from './layoutMixins'; @@ -250,4 +252,4 @@ export const popoverMixins = { color: var(--item-checked-textColor, var(--trigger-textColor, inherit)); } `, -} satisfies Record>; +} satisfies MapOf>; diff --git a/src/styles/tabMixins.ts b/src/styles/tabMixins.ts index 001098da9..23dca9086 100644 --- a/src/styles/tabMixins.ts +++ b/src/styles/tabMixins.ts @@ -1,5 +1,7 @@ import { css } from 'styled-components'; +import { MapOf } from '@/lib/objectHelpers'; + import { layoutMixins } from './layoutMixins'; const tabTriggerStyle = css` @@ -43,4 +45,4 @@ export const tabMixins = { tabTriggerStyle, tabTriggerActiveUnderlineStyle, tabTriggerUnderlineStyle, -} satisfies Record>; +} satisfies MapOf>; diff --git a/src/styles/tableMixins.ts b/src/styles/tableMixins.ts index aa4767e4d..1e3fd669f 100644 --- a/src/styles/tableMixins.ts +++ b/src/styles/tableMixins.ts @@ -1,5 +1,7 @@ import { css } from 'styled-components'; +import { MapOf } from '@/lib/objectHelpers'; + import { layoutMixins } from './layoutMixins'; /** Use as a direct child of tableMixins.cellContent */ @@ -55,4 +57,4 @@ export const tableMixins = { } } `, -} satisfies Record>; +} satisfies MapOf>; diff --git a/src/styles/tradeViewMixins.ts b/src/styles/tradeViewMixins.ts index ed66d2b4e..15efb9fc8 100644 --- a/src/styles/tradeViewMixins.ts +++ b/src/styles/tradeViewMixins.ts @@ -1,5 +1,7 @@ import { css } from 'styled-components'; +import { MapOf } from '@/lib/objectHelpers'; + export const tradeViewMixins = { horizontalTable: css` --tableCell-padding: 0.25rem; @@ -29,4 +31,4 @@ export const tradeViewMixins = { --tableCell-padding: 0.5rem 1rem 0.5rem 1rem; } `, -} satisfies Record>; +} satisfies MapOf>; diff --git a/src/views/AccountInfo/AccountInfoConnectedState.tsx b/src/views/AccountInfo/AccountInfoConnectedState.tsx index 2b8a464f2..72f705d12 100644 --- a/src/views/AccountInfo/AccountInfoConnectedState.tsx +++ b/src/views/AccountInfo/AccountInfoConnectedState.tsx @@ -59,7 +59,7 @@ export const AccountInfoConnectedState = () => { const portfolioValue = subAccount?.equity; const isPostOrderBalanceNegative = - isNumber(availableBalance?.postOrder) && MustBigNumber(availableBalance?.postOrder).lt(0); + isNumber(availableBalance?.postOrder) && MustBigNumber(availableBalance.postOrder).lt(0); return ( <$ConnectedAccountInfoContainer> diff --git a/src/views/CanvasOrderbook/CanvasOrderbook.tsx b/src/views/CanvasOrderbook/CanvasOrderbook.tsx index d4ef82ce7..5a661dbef 100644 --- a/src/views/CanvasOrderbook/CanvasOrderbook.tsx +++ b/src/views/CanvasOrderbook/CanvasOrderbook.tsx @@ -183,7 +183,7 @@ export const CanvasOrderbook = forwardRef( key={idx} title={`${row.price}`} onClick={ - row?.price + row.price ? () => { onRowAction(row.price); } diff --git a/src/views/MarketFilter.tsx b/src/views/MarketFilter.tsx index 575875a9f..f877d7629 100644 --- a/src/views/MarketFilter.tsx +++ b/src/views/MarketFilter.tsx @@ -48,7 +48,7 @@ export const MarketFilter = ({ items={ Object.values(filters).map((value) => ({ label: stringGetter({ key: MARKET_FILTER_OPTIONS[value].label, fallback: value }), - slotAfter: MARKET_FILTER_OPTIONS[value]?.isNew && ( + slotAfter: MARKET_FILTER_OPTIONS[value].isNew && ( {stringGetter({ key: STRING_KEYS.NEW })} ), value, diff --git a/src/views/MarketsDropdown.tsx b/src/views/MarketsDropdown.tsx index 332c5d526..1c4c62811 100644 --- a/src/views/MarketsDropdown.tsx +++ b/src/views/MarketsDropdown.tsx @@ -159,7 +159,7 @@ const MarketsDropdownContent = ({ if ( !hasSeenElectionBannerTrumpWin && - featureFlags?.[StatsigFlags.ffShowPredictionMarketsUi] && + featureFlags[StatsigFlags.ffShowPredictionMarketsUi] && currentDate < new Date('2024-11-06T23:59:59') ) { return ( diff --git a/src/views/PositionInfo.tsx b/src/views/PositionInfo.tsx index 86a56b9b5..f9fcf9b80 100644 --- a/src/views/PositionInfo.tsx +++ b/src/views/PositionInfo.tsx @@ -29,6 +29,7 @@ import { getCurrentMarketConfig } from '@/state/perpetualsSelectors'; import abacusStateManager from '@/lib/abacus'; import { BIG_NUMBERS, isNumber, MustBigNumber } from '@/lib/numbers'; +import { MapOf } from '@/lib/objectHelpers'; import { hasPositionSideChanged } from '@/lib/tradeData'; import { PositionTile } from './PositionTile'; @@ -41,7 +42,7 @@ type PositionInfoItems = { // Label Properties label: string; tooltip?: TooltipStringKeys; - tooltipParams?: Record; + tooltipParams?: MapOf; // Output/DiffOutput Properties fractionDigits?: number | null; @@ -93,7 +94,7 @@ export const PositionInfo = ({ showNarrowVariation }: { showNarrowVariation?: bo type: OutputType.Fiat, label: STRING_KEYS.AVERAGE_OPEN, fractionDigits: tickSizeDecimals, - value: entryPrice?.current, + value: entryPrice.current, }, { key: 'average-close', @@ -117,21 +118,21 @@ export const PositionInfo = ({ showNarrowVariation }: { showNarrowVariation?: bo ]; const { current: currentSize, postOrder: postOrderSize } = size ?? {}; - const leverageBN = MustBigNumber(leverage?.current); - const newLeverageBN = MustBigNumber(leverage?.postOrder); - const maxLeverage = BIG_NUMBERS.ONE.div(MustBigNumber(adjustedImf?.postOrder)); + const leverageBN = MustBigNumber(leverage.current); + const newLeverageBN = MustBigNumber(leverage.postOrder); + const maxLeverage = BIG_NUMBERS.ONE.div(MustBigNumber(adjustedImf.postOrder)); const newPositionIsClosed = MustBigNumber(postOrderSize).isZero(); const hasNoPositionInMarket = MustBigNumber(currentSize).isZero(); const newLeverageIsInvalid = - !!leverage?.postOrder && (!newLeverageBN.isFinite() || newLeverageBN.gt(maxLeverage)); + !!leverage.postOrder && (!newLeverageBN.isFinite() || newLeverageBN.gt(maxLeverage)); const newLeverageIsLarger = - !leverage?.current || (leverage?.postOrder && newLeverageBN.gt(leverageBN)); + !leverage.current || (leverage.postOrder && newLeverageBN.gt(leverageBN)); let liquidationArrowSign = NumberSign.Neutral; - const newLiquidationPriceIsLarger = MustBigNumber(liquidationPrice?.postOrder).gt( - MustBigNumber(liquidationPrice?.current) + const newLiquidationPriceIsLarger = MustBigNumber(liquidationPrice.postOrder).gt( + MustBigNumber(liquidationPrice.current) ); const positionSideHasChanged = hasPositionSideChanged({ @@ -139,7 +140,7 @@ export const PositionInfo = ({ showNarrowVariation }: { showNarrowVariation?: bo postOrderSize, }).positionSideHasChanged; - if (leverage?.postOrder) { + if (leverage.postOrder) { if (newLeverageIsInvalid) { liquidationArrowSign = NumberSign.Negative; } else if (newPositionIsClosed) { @@ -147,13 +148,13 @@ export const PositionInfo = ({ showNarrowVariation }: { showNarrowVariation?: bo } else if (positionSideHasChanged) { liquidationArrowSign = NumberSign.Neutral; } else if ( - liquidationPrice?.current && MustBigNumber(currentSize).gt(0) + liquidationPrice.current && MustBigNumber(currentSize).gt(0) ? !newLiquidationPriceIsLarger : newLiquidationPriceIsLarger ) { liquidationArrowSign = NumberSign.Positive; } else if ( - !liquidationPrice?.current || + !liquidationPrice.current || (!newPositionIsClosed && MustBigNumber(currentSize).gt(0) ? newLiquidationPriceIsLarger : !newLiquidationPriceIsLarger) @@ -177,8 +178,8 @@ export const PositionInfo = ({ showNarrowVariation }: { showNarrowVariation?: bo : NumberSign.Neutral, useDiffOutput: true, showSign: ShowSign.None, - value: leverage?.current, - newValue: leverage?.postOrder, + value: leverage.current, + newValue: leverage.postOrder, withBaseFont: true, }, { @@ -193,8 +194,8 @@ export const PositionInfo = ({ showNarrowVariation }: { showNarrowVariation?: bo hasInvalidNewValue: Boolean(newLeverageIsInvalid), sign: liquidationArrowSign, useDiffOutput: true, - value: liquidationPrice?.current, - newValue: liquidationPrice?.postOrder, + value: liquidationPrice.current, + newValue: liquidationPrice.postOrder, withBaseFont: true, }, { @@ -202,13 +203,13 @@ export const PositionInfo = ({ showNarrowVariation }: { showNarrowVariation?: bo type: OutputType.Fiat, label: STRING_KEYS.UNREALIZED_PNL, tooltip: 'unrealized-pnl', - sign: MustBigNumber(unrealizedPnl?.current).gt(0) + sign: MustBigNumber(unrealizedPnl.current).gt(0) ? NumberSign.Positive - : MustBigNumber(unrealizedPnl?.current).lt(0) + : MustBigNumber(unrealizedPnl.current).lt(0) ? NumberSign.Negative : NumberSign.Neutral, - value: unrealizedPnl?.current, - percentValue: unrealizedPnlPercent?.current, + value: unrealizedPnl.current, + percentValue: unrealizedPnlPercent.current, withBaseFont: true, }, { @@ -216,12 +217,12 @@ export const PositionInfo = ({ showNarrowVariation }: { showNarrowVariation?: bo type: OutputType.Fiat, label: STRING_KEYS.REALIZED_PNL, tooltip: 'realized-pnl', - sign: MustBigNumber(realizedPnl?.current).gt(0) + sign: MustBigNumber(realizedPnl.current).gt(0) ? NumberSign.Positive - : MustBigNumber(realizedPnl?.current).lt(0) + : MustBigNumber(realizedPnl.current).lt(0) ? NumberSign.Negative : NumberSign.Neutral, - value: realizedPnl?.current ?? undefined, + value: realizedPnl.current ?? undefined, withBaseFont: true, }, ]; @@ -318,9 +319,9 @@ export const PositionInfo = ({ showNarrowVariation }: { showNarrowVariation?: bo <$MobilePositionInfo> <$DetachedSection>
datum?.price} - yAccessor={(datum: DepthChartDatum) => datum?.depth} + xAccessor={(datum: DepthChartDatum) => datum.price} + yAccessor={(datum: DepthChartDatum) => datum.depth} curve={curveStepAfter} lineProps={{ strokeWidth: 1.5 }} fillOpacity={0.2} @@ -268,8 +268,8 @@ export const DepthChart = ({ ] : [] } - xAccessor={(datum: DepthChartDatum) => datum?.price} - yAccessor={(datum: DepthChartDatum) => datum?.depth} + xAccessor={(datum: DepthChartDatum) => datum.price} + yAccessor={(datum: DepthChartDatum) => datum.depth} curve={curveStepAfter} lineProps={{ strokeWidth: 1.5 }} fillOpacity={0.2} @@ -299,8 +299,8 @@ export const DepthChart = ({ }, ]} strokeWidth={0.25} - xAccessor={(datum) => datum?.price} - yAccessor={(datum) => datum?.depth} + xAccessor={(datum) => datum.price} + yAccessor={(datum) => datum.depth} /> diff --git a/src/views/charts/FundingChart/index.tsx b/src/views/charts/FundingChart/index.tsx index c037fb165..4e4452da0 100644 --- a/src/views/charts/FundingChart/index.tsx +++ b/src/views/charts/FundingChart/index.tsx @@ -51,7 +51,7 @@ export const FundingChart = ({ selectedLocale }: ElementProps) => { // Chart data const data = useAppSelector(calculateFundingRateHistory, shallowEqual); - const latestDatum = data?.[data.length - 1]; + const latestDatum = data[data.length - 1]; // Chart state const [fundingRateView, setFundingRateView] = useState(FundingRateResolution.OneHour); @@ -82,8 +82,8 @@ export const FundingChart = ({ selectedLocale }: ElementProps) => { series={[ { dataKey: 'funding-rate', - xAccessor: (datum) => datum?.time, - yAccessor: (datum) => datum?.fundingRate, + xAccessor: (datum) => datum.time, + yAccessor: (datum) => datum.fundingRate, colorAccessor: () => 'var(--color-text-1)', getCurve: ({ zoom }) => (zoom > 12 ? curveMonotoneX : curveStepAfter), }, diff --git a/src/views/charts/LaunchableMarketChart.tsx b/src/views/charts/LaunchableMarketChart.tsx index b747061e2..d9bc596eb 100644 --- a/src/views/charts/LaunchableMarketChart.tsx +++ b/src/views/charts/LaunchableMarketChart.tsx @@ -128,7 +128,7 @@ export const LaunchableMarketChart = ({ ); const renderTooltip = (tooltipParam: RenderTooltipParams) => { - const datum = tooltipParam?.tooltipData?.nearestDatum?.datum; + const datum = tooltipParam.tooltipData?.nearestDatum?.datum; if (!datum) return
; return ( diff --git a/src/views/charts/PnlChart.tsx b/src/views/charts/PnlChart.tsx index 3690106a5..d32fe6a95 100644 --- a/src/views/charts/PnlChart.tsx +++ b/src/views/charts/PnlChart.tsx @@ -137,8 +137,8 @@ export const PnlChart = ({ const msForPeriod = useCallback( (period: HistoricalPnlPeriods, clampMax: Boolean = true) => { - const earliestCreatedAt = data?.[0]?.createdAt; - const latestCreatedAt = data?.[data.length - 1]?.createdAt; + const earliestCreatedAt = data[0]?.createdAt; + const latestCreatedAt = data[data.length - 1]?.createdAt; const maxPeriod = earliestCreatedAt && latestCreatedAt ? latestCreatedAt - earliestCreatedAt @@ -236,8 +236,8 @@ export const PnlChart = ({ [chartDotsBackground, isTablet] ); - const xAccessorFunc = useCallback((datum: PnlDatum) => datum?.createdAt, []); - const yAccessorFunc = useCallback((datum: PnlDatum) => datum?.equity, []); + const xAccessorFunc = useCallback((datum: PnlDatum) => datum.createdAt, []); + const yAccessorFunc = useCallback((datum: PnlDatum) => datum.equity, []); const series = useMemo( () => [ diff --git a/src/views/charts/TradingRewardsChart.tsx b/src/views/charts/TradingRewardsChart.tsx index ec9e4b4f8..2855eab40 100644 --- a/src/views/charts/TradingRewardsChart.tsx +++ b/src/views/charts/TradingRewardsChart.tsx @@ -108,8 +108,8 @@ export const TradingRewardsChart = ({ return []; }, [periodTradingRewards, canViewAccount]); - const oldestDataPointDate = rewardsData?.[0]?.date; - const newestDataPointDate = rewardsData?.[rewardsData.length - 1]?.date; + const oldestDataPointDate = rewardsData[0]?.date; + const newestDataPointDate = rewardsData[rewardsData.length - 1]?.date; const msForPeriod = useCallback( (period: TradingRewardsPeriod, clampMax: Boolean = true) => { @@ -186,8 +186,8 @@ export const TradingRewardsChart = ({ const onToggleInteract = () => setIsZooming(false); - const xAccessorFunc = useCallback((datum: TradingRewardsDatum) => datum?.date, []); - const yAccessorFunc = useCallback((datum: TradingRewardsDatum) => datum?.cumulativeAmount, []); + const xAccessorFunc = useCallback((datum: TradingRewardsDatum) => datum.date, []); + const yAccessorFunc = useCallback((datum: TradingRewardsDatum) => datum.cumulativeAmount, []); const series = useMemo( () => [ @@ -273,7 +273,7 @@ export const TradingRewardsChart = ({ {rewardsData.length > 0 && ( <$Value> {MustBigNumber( - tooltipContext?.tooltipData?.nearestDatum?.datum?.cumulativeAmount ?? + tooltipContext?.tooltipData?.nearestDatum?.datum.cumulativeAmount ?? totalTradingRewards ).toFixed(TOKEN_DECIMALS)} diff --git a/src/views/charts/TradingView/TvChart.tsx b/src/views/charts/TradingView/TvChart.tsx index 5ea0d6742..18063d171 100644 --- a/src/views/charts/TradingView/TvChart.tsx +++ b/src/views/charts/TradingView/TvChart.tsx @@ -132,7 +132,7 @@ export const TvChart = () => { // Only reset data if displayUnit has actually changed if (prevDisplayUnit !== displayUnit) { - const chart = tvWidget.activeChart?.(); + const chart = tvWidget.activeChart(); if (chart) { chart.resetData(); resetCache(); diff --git a/src/views/dialogs/AdjustIsolatedMarginDialog.tsx b/src/views/dialogs/AdjustIsolatedMarginDialog.tsx index 28446a758..b03385c50 100644 --- a/src/views/dialogs/AdjustIsolatedMarginDialog.tsx +++ b/src/views/dialogs/AdjustIsolatedMarginDialog.tsx @@ -22,7 +22,7 @@ export const AdjustIsolatedMarginDialog = ({ const stringGetter = useStringGetter(); const subaccountPosition = useAppSelector(getOpenPositionFromId(positionId), shallowEqual); - const onIsolatedMarginAdjustment = useCallback(() => setIsOpen?.(false), [setIsOpen]); + const onIsolatedMarginAdjustment = useCallback(() => setIsOpen(false), [setIsOpen]); return (
- setIsOpen?.(false)} /> + setIsOpen(false)} />
); diff --git a/src/views/dialogs/CancelAllOrdersConfirmationDialog.tsx b/src/views/dialogs/CancelAllOrdersConfirmationDialog.tsx index 4500b5c0e..3fbd157f4 100644 --- a/src/views/dialogs/CancelAllOrdersConfirmationDialog.tsx +++ b/src/views/dialogs/CancelAllOrdersConfirmationDialog.tsx @@ -44,7 +44,7 @@ export const CancelAllOrdersConfirmationDialog = ({ const onSubmit = useCallback(() => { cancelAllOrders(shouldCancelAllOrders ? undefined : marketIdOption); - setIsOpen?.(false); + setIsOpen(false); }, [cancelAllOrders, marketIdOption, setIsOpen, shouldCancelAllOrders]); return ( diff --git a/src/views/dialogs/CancelPendingOrdersDialog.tsx b/src/views/dialogs/CancelPendingOrdersDialog.tsx index f123b7f60..b0a4d303a 100644 --- a/src/views/dialogs/CancelPendingOrdersDialog.tsx +++ b/src/views/dialogs/CancelPendingOrdersDialog.tsx @@ -26,7 +26,7 @@ export const CancelPendingOrdersDialog = ({ [allPending, marketId] ); - const onSuccessfulCancel = useCallback(() => setIsOpen?.(false), [setIsOpen]); + const onSuccessfulCancel = useCallback(() => setIsOpen(false), [setIsOpen]); return ( { closeAllPositions(); - setIsOpen?.(false); + setIsOpen(false); }, [closeAllPositions, setIsOpen]); return ( diff --git a/src/views/dialogs/ClosePositionDialog.tsx b/src/views/dialogs/ClosePositionDialog.tsx index cfbccc14b..4828f795f 100644 --- a/src/views/dialogs/ClosePositionDialog.tsx +++ b/src/views/dialogs/ClosePositionDialog.tsx @@ -79,7 +79,7 @@ export const ClosePositionDialog = ({ setIsOpen }: DialogProps { - setIsOpen?.(isOpen); + setIsOpen(isOpen); if (!isOpen) abacusStateManager.clearClosePositionInputValues({ shouldFocusOnTradeInput: true }); }} diff --git a/src/views/dialogs/DetailsDialog/OrderDetailsDialog.tsx b/src/views/dialogs/DetailsDialog/OrderDetailsDialog.tsx index 2ab2c5a15..d49419fc4 100644 --- a/src/views/dialogs/DetailsDialog/OrderDetailsDialog.tsx +++ b/src/views/dialogs/DetailsDialog/OrderDetailsDialog.tsx @@ -211,7 +211,7 @@ export const OrderDetailsDialog = ({ const onClearClick = () => { dispatch(clearOrder(orderId)); - setIsOpen?.(false); + setIsOpen(false); }; const isShortTermOrder = orderFlags === OrderFlags.SHORT_TERM; diff --git a/src/views/dialogs/GeoComplianceDialog.tsx b/src/views/dialogs/GeoComplianceDialog.tsx index f76aab4b0..3a3a113bc 100644 --- a/src/views/dialogs/GeoComplianceDialog.tsx +++ b/src/views/dialogs/GeoComplianceDialog.tsx @@ -76,7 +76,7 @@ export const GeoComplianceDialog = ({ setIsOpen }: DialogProps) => { if (success) { - setIsOpen?.(false); + setIsOpen(false); } else { log('useWithdrawalInfo/getWithdrawalCapacityByDenom', new Error(parsingError?.message)); } diff --git a/src/views/dialogs/HelpDialog.tsx b/src/views/dialogs/HelpDialog.tsx index cece08833..2748f746e 100644 --- a/src/views/dialogs/HelpDialog.tsx +++ b/src/views/dialogs/HelpDialog.tsx @@ -51,7 +51,7 @@ export const HelpDialog = ({ setIsOpen }: DialogProps) => { }, slotBefore: , }, - globalThis?.Intercom && { + globalThis.Intercom && { value: 'live-chat', label: stringGetter({ key: STRING_KEYS.LIVE_CHAT }), description: stringGetter({ key: STRING_KEYS.LIVE_CHAT_DESCRIPTION }), diff --git a/src/views/dialogs/ManageFundsDialog.tsx b/src/views/dialogs/ManageFundsDialog.tsx index 9f50d4cc3..ae2a6a3e8 100644 --- a/src/views/dialogs/ManageFundsDialog.tsx +++ b/src/views/dialogs/ManageFundsDialog.tsx @@ -28,7 +28,7 @@ export const ManageFundsDialog = ({ const { type } = useAppSelector(getTransferInputs, shallowEqual) ?? {}; const currentType = type?.rawValue ?? selectedTransferType ?? TransferType.deposit.rawValue; - const closeDialog = () => setIsOpen?.(false); + const closeDialog = () => setIsOpen(false); const transferTypeConfig = { [TransferType.deposit.rawValue]: { diff --git a/src/views/dialogs/OnboardingDialog.tsx b/src/views/dialogs/OnboardingDialog.tsx index 158372408..494ac4816 100644 --- a/src/views/dialogs/OnboardingDialog.tsx +++ b/src/views/dialogs/OnboardingDialog.tsx @@ -42,11 +42,11 @@ export const OnboardingDialog = ({ setIsOpen }: DialogProps { - if (!currentOnboardingStep) setIsOpen?.(false); + if (!currentOnboardingStep) setIsOpen(false); }, [currentOnboardingStep, setIsOpen]); const setIsOpenFromDialog = (open: boolean) => { - setIsOpen?.(open); + setIsOpen(open); }; const onChooseWallet = (wallet: WalletInfo) => { diff --git a/src/views/dialogs/OnboardingDialog/GenerateKeys.tsx b/src/views/dialogs/OnboardingDialog/GenerateKeys.tsx index 7c2106471..f3e3ffd5b 100644 --- a/src/views/dialogs/OnboardingDialog/GenerateKeys.tsx +++ b/src/views/dialogs/OnboardingDialog/GenerateKeys.tsx @@ -62,7 +62,7 @@ export const GenerateKeys = ({ status, setStatus, onKeysDerived = () => {} }: El setError(undefined); try { - await matchNetwork?.(); + await matchNetwork(); return true; } catch (err) { const { message, walletErrorType, isErrorExpected } = parseWalletError({ diff --git a/src/views/dialogs/SelectMarginModeDialog.tsx b/src/views/dialogs/SelectMarginModeDialog.tsx index 1b29cb565..fce9700c2 100644 --- a/src/views/dialogs/SelectMarginModeDialog.tsx +++ b/src/views/dialogs/SelectMarginModeDialog.tsx @@ -11,7 +11,7 @@ export const SelectMarginModeDialog = ({ setIsOpen }: DialogProps - setIsOpen?.(false)} /> + setIsOpen(false)} /> ); }; diff --git a/src/views/dialogs/StakeDialog.tsx b/src/views/dialogs/StakeDialog.tsx index dcd6bc336..e1fdd9dce 100644 --- a/src/views/dialogs/StakeDialog.tsx +++ b/src/views/dialogs/StakeDialog.tsx @@ -29,7 +29,7 @@ export const StakeDialog = ({ setIsOpen }: DialogProps) => { const [currentStep, setCurrentStep] = useState(StakeFormSteps.EditInputs); - const closeDialog = () => setIsOpen?.(false); + const closeDialog = () => setIsOpen(false); const dialogProps: { [key in StakeFormSteps]: { diff --git a/src/views/dialogs/TradeDialog.tsx b/src/views/dialogs/TradeDialog.tsx index 1f47ee324..be56e83fb 100644 --- a/src/views/dialogs/TradeDialog.tsx +++ b/src/views/dialogs/TradeDialog.tsx @@ -25,13 +25,13 @@ export const TradeDialog = ({ isOpen, setIsOpen, slotTrigger }: DialogProps { setCurrentStep(MobilePlaceOrderSteps.EditOrder); - setIsOpen?.(false); + setIsOpen(false); }; return ( <$Dialog isOpen={isOpen} - setIsOpen={(open: boolean) => (open ? setIsOpen?.(true) : onCloseDialog())} + setIsOpen={(open: boolean) => (open ? setIsOpen(true) : onCloseDialog())} placement={isMobile ? DialogPlacement.FullScreen : DialogPlacement.Default} currentStep={currentStep} slotTrigger={slotTrigger} diff --git a/src/views/dialogs/TransferDialog.tsx b/src/views/dialogs/TransferDialog.tsx index af897e18e..26670b2c7 100644 --- a/src/views/dialogs/TransferDialog.tsx +++ b/src/views/dialogs/TransferDialog.tsx @@ -16,7 +16,7 @@ export const TransferDialog = ({ selectedAsset, setIsOpen }: DialogProps - setIsOpen?.(false)} /> + setIsOpen(false)} /> ); }; diff --git a/src/views/dialogs/UnstakeDialog.tsx b/src/views/dialogs/UnstakeDialog.tsx index e8fc9b319..332b5b289 100644 --- a/src/views/dialogs/UnstakeDialog.tsx +++ b/src/views/dialogs/UnstakeDialog.tsx @@ -24,7 +24,7 @@ export const UnstakeDialog = ({ setIsOpen }: DialogProps) => const { stakingValidators, currentDelegations } = useStakingValidator() ?? {}; const { chainTokenLabel } = useTokenConfigs(); - const closeDialog = () => setIsOpen?.(false); + const closeDialog = () => setIsOpen(false); const dialogProps: { [key in StakeFormSteps]: { diff --git a/src/views/dialogs/VaultDepositWithdrawDialog.tsx b/src/views/dialogs/VaultDepositWithdrawDialog.tsx index 6249c966f..999b54dcb 100644 --- a/src/views/dialogs/VaultDepositWithdrawDialog.tsx +++ b/src/views/dialogs/VaultDepositWithdrawDialog.tsx @@ -18,7 +18,7 @@ export const VaultDepositWithdrawDialog = ({ const stringGetter = useStringGetter(); const { isMobile, isTablet } = useBreakpoints(); - const closeDialog = useCallback(() => setIsOpen?.(false), [setIsOpen]); + const closeDialog = useCallback(() => setIsOpen(false), [setIsOpen]); useEffect(() => { if (!isTablet) { diff --git a/src/views/forms/AccountManagementForms/DepositForm.tsx b/src/views/forms/AccountManagementForms/DepositForm.tsx index eb10ed006..8e2874426 100644 --- a/src/views/forms/AccountManagementForms/DepositForm.tsx +++ b/src/views/forms/AccountManagementForms/DepositForm.tsx @@ -320,8 +320,8 @@ export const DepositForm = ({ onDeposit, onError }: DepositFormProps) => { if (!sourceToken?.address || !sourceToken.decimals) throw new Error('Missing source token address'); if (!requestPayload?.targetAddress) throw new Error('Missing target address'); - if (!requestPayload?.value) throw new Error('Missing transaction value'); - if (sourceToken?.address === NATIVE_TOKEN_ADDRESS) return; + if (!requestPayload.value) throw new Error('Missing transaction value'); + if (sourceToken.address === NATIVE_TOKEN_ADDRESS) return; const allowance = await publicClientWagmi.readContract({ address: sourceToken.address as EvmAddress, @@ -550,7 +550,7 @@ export const DepositForm = ({ onDeposit, onError }: DepositFormProps) => { if (!signerWagmi) { throw new Error('Missing signer'); } - if (!requestPayload?.targetAddress || !requestPayload?.data || !requestPayload?.value) { + if (!requestPayload?.targetAddress || !requestPayload.data || !requestPayload.value) { throw new Error('Missing request payload'); } await validateTokenApproval(); diff --git a/src/views/forms/AccountManagementForms/DepositForm/DepositButtonAndReceipt.tsx b/src/views/forms/AccountManagementForms/DepositForm/DepositButtonAndReceipt.tsx index 6c9a65db6..d71e020f3 100644 --- a/src/views/forms/AccountManagementForms/DepositForm/DepositButtonAndReceipt.tsx +++ b/src/views/forms/AccountManagementForms/DepositForm/DepositButtonAndReceipt.tsx @@ -141,7 +141,7 @@ export const DepositButtonAndReceipt = ({ ), tooltip: 'minimum-deposit-amount', @@ -158,7 +158,7 @@ export const DepositButtonAndReceipt = ({ tag={sourceToken?.symbol} /> = - + ), }, @@ -169,7 +169,7 @@ export const DepositButtonAndReceipt = ({ {stringGetter({ key: STRING_KEYS.GAS_FEE })} ), - value: , + value: , }, typeof summary?.bridgeFee === 'number' && { key: 'bridge-fees', @@ -178,7 +178,7 @@ export const DepositButtonAndReceipt = ({ {stringGetter({ key: STRING_KEYS.BRIDGE_FEE })} ), - value: , + value: , }, { key: 'equity', diff --git a/src/views/forms/AccountManagementForms/SlippageEditor.tsx b/src/views/forms/AccountManagementForms/SlippageEditor.tsx index 89faad274..7c3bc0782 100644 --- a/src/views/forms/AccountManagementForms/SlippageEditor.tsx +++ b/src/views/forms/AccountManagementForms/SlippageEditor.tsx @@ -50,9 +50,9 @@ export const SlippageEditor = ({ if (editorState === EditorState.Selecting) { // use setTimeout with a 0ms delay to focus asynchronously. - setTimeout(() => toggleGroupRef?.current?.focus(), 0); + setTimeout(() => toggleGroupRef.current?.focus(), 0); } else if (editorState === EditorState.Editing) { - inputRef?.current?.focus(); + inputRef.current?.focus(); } }, [editorState]); diff --git a/src/views/forms/AccountManagementForms/TokenSelectMenu.tsx b/src/views/forms/AccountManagementForms/TokenSelectMenu.tsx index 363831e22..34b3804e3 100644 --- a/src/views/forms/AccountManagementForms/TokenSelectMenu.tsx +++ b/src/views/forms/AccountManagementForms/TokenSelectMenu.tsx @@ -117,9 +117,9 @@ export const TokenSelectMenu = ({ selectedToken, onSelectToken, isExchange }: El label: stringGetter({ key: STRING_KEYS.SWAP }), value: selectedToken && ( <> - {type === TransferType.deposit ? selectedToken?.symbol : 'USDC'} + {type === TransferType.deposit ? selectedToken.symbol : 'USDC'} - {type === TransferType.deposit ? 'USDC' : selectedToken?.symbol} + {type === TransferType.deposit ? 'USDC' : selectedToken.symbol} ), }, @@ -130,8 +130,8 @@ export const TokenSelectMenu = ({ selectedToken, onSelectToken, isExchange }: El
{selectedToken ? ( <> - <$Img src={selectedToken?.iconUrl ?? undefined} alt="" /> {selectedToken?.name}{' '} - {selectedToken?.symbol} + <$Img src={selectedToken.iconUrl ?? undefined} alt="" /> {selectedToken.name}{' '} + {selectedToken.symbol} ) : ( stringGetter({ key: STRING_KEYS.SELECT_ASSET }) diff --git a/src/views/forms/AccountManagementForms/WithdrawForm.tsx b/src/views/forms/AccountManagementForms/WithdrawForm.tsx index a20f50606..1b3bc5d62 100644 --- a/src/views/forms/AccountManagementForms/WithdrawForm.tsx +++ b/src/views/forms/AccountManagementForms/WithdrawForm.tsx @@ -186,7 +186,7 @@ export const WithdrawForm = () => { const onSubmit = useCallback( async (e: FormEvent) => { - const notificationId = crypto?.randomUUID() ?? Date.now().toString(); + const notificationId = crypto.randomUUID() ?? Date.now().toString(); try { e.preventDefault(); @@ -206,13 +206,13 @@ export const WithdrawForm = () => { addresses: [toAddress, dydxAddress], }); - if (screenResults?.[dydxAddress]) { + if (screenResults[dydxAddress]) { setError( stringGetter({ key: STRING_KEYS.WALLET_RESTRICTED_WITHDRAWAL_TRANSFER_ORIGINATION_ERROR_MESSAGE, }) ); - } else if (screenResults?.[toAddress]) { + } else if (screenResults[toAddress]) { setError( stringGetter({ key: STRING_KEYS.WALLET_RESTRICTED_WITHDRAWAL_TRANSFER_DESTINATION_ERROR_MESSAGE, diff --git a/src/views/forms/AccountManagementForms/WithdrawForm/WithdrawButtonAndReceipt.tsx b/src/views/forms/AccountManagementForms/WithdrawForm/WithdrawButtonAndReceipt.tsx index a1033a316..22ae3e375 100644 --- a/src/views/forms/AccountManagementForms/WithdrawForm/WithdrawButtonAndReceipt.tsx +++ b/src/views/forms/AccountManagementForms/WithdrawForm/WithdrawButtonAndReceipt.tsx @@ -75,7 +75,7 @@ export const WithdrawButtonAndReceipt = ({ label: ( <$RowWithGap> {stringGetter({ key: STRING_KEYS.EXPECTED_AMOUNT_RECEIVED })} - {withdrawToken && {withdrawToken?.symbol}} + {withdrawToken && {withdrawToken.symbol}} ), value: ( @@ -102,7 +102,7 @@ export const WithdrawButtonAndReceipt = ({ label: ( {stringGetter({ key: STRING_KEYS.GAS_FEE })} ), - value: , + value: , }, typeof summary?.bridgeFee === 'number' && { key: 'bridge-fees', @@ -111,7 +111,7 @@ export const WithdrawButtonAndReceipt = ({ {stringGetter({ key: STRING_KEYS.BRIDGE_FEE })} ), - value: , + value: , }, !exchange && { key: 'slippage', @@ -154,7 +154,7 @@ export const WithdrawButtonAndReceipt = ({ newValue={leverage?.postOrder} sign={NumberSign.Negative} withDiff={Boolean( - leverage?.current && leverage?.postOrder && leverage.current !== leverage?.postOrder + leverage?.current && leverage.postOrder && leverage.current !== leverage.postOrder )} tw="[--diffOutput-valueWithDiff-fontSize:1em]" /> diff --git a/src/views/forms/AdjustIsolatedMarginForm.tsx b/src/views/forms/AdjustIsolatedMarginForm.tsx index 16d94911c..b012d640f 100644 --- a/src/views/forms/AdjustIsolatedMarginForm.tsx +++ b/src/views/forms/AdjustIsolatedMarginForm.tsx @@ -208,7 +208,7 @@ export const AdjustIsolatedMarginForm = ({ }; } - if (marginUsage?.postOrder && MustBigNumber(marginUsage?.postOrder).gte(1)) { + if (marginUsage?.postOrder && MustBigNumber(marginUsage.postOrder).gte(1)) { return { message: stringGetter({ key: STRING_KEYS.INVALID_NEW_ACCOUNT_MARGIN_USAGE }), type: AlertType.Error, diff --git a/src/views/forms/AdjustTargetLeverageForm.tsx b/src/views/forms/AdjustTargetLeverageForm.tsx index 9df2991c7..aa5b31edf 100644 --- a/src/views/forms/AdjustTargetLeverageForm.tsx +++ b/src/views/forms/AdjustTargetLeverageForm.tsx @@ -65,7 +65,7 @@ export const AdjustTargetLeverageForm = ({ field: TradeInputField.targetLeverage, }); - onSetTargetLeverage?.(leverage); + onSetTargetLeverage(leverage); }} > <$Description> diff --git a/src/views/forms/CancelAllOrdersInMarketForm.tsx b/src/views/forms/CancelAllOrdersInMarketForm.tsx index 47faf739e..f450ddadc 100644 --- a/src/views/forms/CancelAllOrdersInMarketForm.tsx +++ b/src/views/forms/CancelAllOrdersInMarketForm.tsx @@ -26,6 +26,7 @@ import { useAppSelector } from '@/state/appTypes'; import { getAssets } from '@/state/assetsSelectors'; import { MustBigNumber } from '@/lib/numbers'; +import { MapOf } from '@/lib/objectHelpers'; type CancelAllOrdersInMarketFormProps = { marketId: string; @@ -51,9 +52,9 @@ export const CancelAllOrdersInMarketForm = ({ const pendingPositionOrders = allPending[marketId] ?? EMPTY_ARR; const assetsData = useAppSelector(getAssets, shallowEqual); - const [cancellingStatus, setCancellingStatus] = useState>({}); + const [cancellingStatus, setCancellingStatus] = useState>({}); const isCancelling = useMemo( - () => Object.values(cancellingStatus).some((s) => s.type === 'pending'), + () => Object.values(cancellingStatus).some((s) => s?.type === 'pending'), [cancellingStatus] ); const { cancelOrder } = useSubaccount(); @@ -91,7 +92,7 @@ export const CancelAllOrdersInMarketForm = ({ return; } // if there are errors, user should be able to see the error notifications so we won't display inline. - if (allResults.every((r) => r.type === 'success' || r.type === 'error')) { + if (allResults.every((r) => r?.type === 'success' || r?.type === 'error')) { onCancelComplete(); } }, [cancellingStatus, onCancelComplete]); diff --git a/src/views/forms/ClosePositionForm.tsx b/src/views/forms/ClosePositionForm.tsx index 96d75e0e5..3856e949d 100644 --- a/src/views/forms/ClosePositionForm.tsx +++ b/src/views/forms/ClosePositionForm.tsx @@ -371,7 +371,7 @@ export const ClosePositionForm = ({ {'+ '} <$Icon - $hasError={nativeTokenBalance?.lt(initialDepositAmountBN)} + $hasError={nativeTokenBalance.lt(initialDepositAmountBN)} iconName={ - nativeTokenBalance?.gt(initialDepositAmountBN) + nativeTokenBalance.gt(initialDepositAmountBN) ? IconName.CheckCircle : IconName.CautionCircle } diff --git a/src/views/forms/NewMarketForm/NewMarketSelectionStep.tsx b/src/views/forms/NewMarketForm/NewMarketSelectionStep.tsx index 45010d5c2..ebe898b34 100644 --- a/src/views/forms/NewMarketForm/NewMarketSelectionStep.tsx +++ b/src/views/forms/NewMarketForm/NewMarketSelectionStep.tsx @@ -194,7 +194,7 @@ export const NewMarketSelectionStep = ({ > <$Header style={{ marginLeft: '1rem' }}> {label} - {Number(tier) === assetToAdd?.params.liquidityTier && ( + {Number(tier) === assetToAdd.params.liquidityTier && ( ✨ {stringGetter({ key: STRING_KEYS.RECOMMENDED })} @@ -259,7 +259,7 @@ export const NewMarketSelectionStep = ({ value: ( ), diff --git a/src/views/forms/NewMarketForm/v7/NewMarketSelectionStep.tsx b/src/views/forms/NewMarketForm/v7/NewMarketSelectionStep.tsx index 62e369799..1ce1cfa82 100644 --- a/src/views/forms/NewMarketForm/v7/NewMarketSelectionStep.tsx +++ b/src/views/forms/NewMarketForm/v7/NewMarketSelectionStep.tsx @@ -119,7 +119,7 @@ export const NewMarketSelectionStep = ({ group: 'markets', groupLabel: stringGetter({ key: STRING_KEYS.MARKETS }), items: - launchableMarkets.data?.map((launchableMarket) => ({ + launchableMarkets.data.map((launchableMarket) => ({ value: launchableMarket.id, label: getDisplayableTickerFromMarket(launchableMarket.id), tag: getDisplayableAssetFromBaseAsset(launchableMarket.asset), diff --git a/src/views/forms/StakingForms/StakeForm/ValidatorDropdown.tsx b/src/views/forms/StakingForms/StakeForm/ValidatorDropdown.tsx index c7ae16c80..35e689783 100644 --- a/src/views/forms/StakingForms/StakeForm/ValidatorDropdown.tsx +++ b/src/views/forms/StakingForms/StakeForm/ValidatorDropdown.tsx @@ -90,7 +90,7 @@ const ValidatorsDropdownContent = ({ commissionRate: MustBigNumber( formatUnits(BigInt(val.commission?.commissionRates?.rate ?? 0), commissionRateDecimals) ), - website: val.description?.website, + website: val.description.website, }); } return validators; @@ -162,7 +162,7 @@ export const ValidatorDropdown = memo( ); const slotTrigger = selectedValidator?.description?.website ? ( - + {output} ) : ( diff --git a/src/views/forms/StakingForms/UnstakeForm/UnstakeFormInputContents.tsx b/src/views/forms/StakingForms/UnstakeForm/UnstakeFormInputContents.tsx index 9c6986f3f..2007d4a4d 100644 --- a/src/views/forms/StakingForms/UnstakeForm/UnstakeFormInputContents.tsx +++ b/src/views/forms/StakingForms/UnstakeForm/UnstakeFormInputContents.tsx @@ -31,16 +31,17 @@ import { import { track } from '@/lib/analytics/analytics'; import { BigNumberish, MustBigNumber } from '@/lib/numbers'; +import { MapOf } from '@/lib/objectHelpers'; import { ValidatorName } from '../shared/ValidatorName'; type ElementProps = { - amounts: Record; + amounts: MapOf; detailItems: DetailsItem[]; fee?: BigNumberish; error?: StakeButtonAlert; isLoading: boolean; - setUnstakedAmounts: Dispatch>>; + setUnstakedAmounts: Dispatch>>; }; export const UnstakeFormInputContents = ({ @@ -180,7 +181,7 @@ export const UnstakeFormInputContents = ({ const balance = MustBigNumber(delegation.amount).toNumber(); return ( - + ; + amounts: MapOf; detailItems: DetailsItem[]; isLoading: boolean; setCurrentStep: Dispatch>; @@ -41,7 +42,7 @@ export const UnstakeFormPreviewContents = ({ MustBigNumber(amounts[delegation.validator]).gt(0) ) ?? []; const unstakingValidators = stakingValidators - ? delegationsToUnstake.map((delegation) => stakingValidators[delegation.validator]?.[0]) + ? delegationsToUnstake.map((delegation) => stakingValidators[delegation.validator][0]) : []; return ( @@ -49,7 +50,7 @@ export const UnstakeFormPreviewContents = ({ submitText={stringGetter({ key: STRING_KEYS.CONFIRM_UNSTAKE })} isLoading={isLoading} slotLeftHeading={stringGetter({ - key: unstakingValidators?.length === 1 ? STRING_KEYS.VALIDATOR : STRING_KEYS.VALIDATORS, + key: unstakingValidators.length === 1 ? STRING_KEYS.VALIDATOR : STRING_KEYS.VALIDATORS, })} slotRightHeading={stringGetter({ key: STRING_KEYS.AMOUNT_TO_UNSTAKE, diff --git a/src/views/forms/StakingForms/UnstakeForm/index.tsx b/src/views/forms/StakingForms/UnstakeForm/index.tsx index d3bee1b3e..c18fbafe0 100644 --- a/src/views/forms/StakingForms/UnstakeForm/index.tsx +++ b/src/views/forms/StakingForms/UnstakeForm/index.tsx @@ -32,6 +32,7 @@ import { StakeButtonAlert } from '@/views/forms/StakingForms/shared/StakeRewardB import { track } from '@/lib/analytics/analytics'; import { BigNumberish, MustBigNumber } from '@/lib/numbers'; +import { MapOf } from '@/lib/objectHelpers'; import { log } from '@/lib/telemetry'; import { hashFromTx } from '@/lib/txUtils'; @@ -63,7 +64,7 @@ export const UnstakeForm = ({ // Form states const [error, setError] = useState(); const [fee, setFee] = useState(); - const [amounts, setAmounts] = useState>({}); + const [amounts, setAmounts] = useState>({}); const [isLoading, setIsLoading] = useState(false); const isEachAmountValid = useMemo(() => { diff --git a/src/views/forms/StakingForms/shared/ValidatorName.tsx b/src/views/forms/StakingForms/shared/ValidatorName.tsx index d678cddaa..b3ea38e09 100644 --- a/src/views/forms/StakingForms/shared/ValidatorName.tsx +++ b/src/views/forms/StakingForms/shared/ValidatorName.tsx @@ -20,8 +20,8 @@ export const ValidatorName = ({ fallbackText={validator?.description?.moniker} /> {validator?.description?.website ? ( - - <$TruncatedText>{validator?.description?.moniker} + + <$TruncatedText>{validator.description.moniker} ) : ( <$TruncatedText>{validator?.description?.moniker} diff --git a/src/views/forms/TradeForm.tsx b/src/views/forms/TradeForm.tsx index 2f49e29c6..fb60abd0c 100644 --- a/src/views/forms/TradeForm.tsx +++ b/src/views/forms/TradeForm.tsx @@ -156,7 +156,7 @@ export const TradeForm = ({ } const shouldPromptUserToPlaceLimitOrderInner = ['MARKET_ORDER_ERROR_ORDERBOOK_SLIPPAGE'].some( - (errorCode) => inputAlertInner?.code === errorCode + (errorCode) => inputAlertInner.code === errorCode ); return { shortAlertContent: alertContentInner, @@ -323,11 +323,11 @@ export const TradeForm = ({ )} { const showReduceOnly = !!needsReduceOnly || !!reduceOnlyTooltip; const needsExecution = !!executionOptions || !!showPostOnly || !!showReduceOnly; - const hasTimeInForce = !!timeInForceOptions?.toArray()?.length; + const hasTimeInForce = !!timeInForceOptions?.toArray().length; const needsTimeRow = !!needsGoodUntil || hasTimeInForce; useEffect(() => { diff --git a/src/views/forms/TradeForm/PositionPreview.tsx b/src/views/forms/TradeForm/PositionPreview.tsx index d1d352d04..a70546c0c 100644 --- a/src/views/forms/TradeForm/PositionPreview.tsx +++ b/src/views/forms/TradeForm/PositionPreview.tsx @@ -42,9 +42,9 @@ export const PositionPreview = ({ showNarrowVariation }: ElementProps) => { }); if ( - featureFlags?.[StatsigFlags.ffShowPredictionMarketsUi] && + featureFlags[StatsigFlags.ffShowPredictionMarketsUi] && marketId === PREDICTION_MARKET.TRUMPWIN && !hasSeenTradeFormMessageTrumpWin ) { diff --git a/src/views/forms/TradeForm/useTradeTypeOptions.tsx b/src/views/forms/TradeForm/useTradeTypeOptions.tsx index 5c3936a50..0a4ab0eee 100644 --- a/src/views/forms/TradeForm/useTradeTypeOptions.tsx +++ b/src/views/forms/TradeForm/useTradeTypeOptions.tsx @@ -31,7 +31,7 @@ export const useTradeTypeOptions = (opts?: { showAssetIcon?: boolean; showAll?: const { typeOptions } = useAppSelector(getInputTradeOptions, shallowEqual) ?? {}; const allTradeTypeItems = useMemo((): Array> | undefined => { - const allItems = typeOptions?.toArray()?.map(({ type, stringKey }) => ({ + const allItems = typeOptions?.toArray().map(({ type, stringKey }) => ({ value: type as TradeTypes, label: stringGetter({ key: diff --git a/src/views/forms/TransferForm.tsx b/src/views/forms/TransferForm.tsx index 5a8c2a455..8291fc02d 100644 --- a/src/views/forms/TransferForm.tsx +++ b/src/views/forms/TransferForm.tsx @@ -160,13 +160,13 @@ export const TransferForm = ({ addresses: [recipientAddress!, dydxAddress!], }); - if (screenResults?.[dydxAddress!]) { + if (screenResults[dydxAddress!]) { setError( stringGetter({ key: STRING_KEYS.WALLET_RESTRICTED_WITHDRAWAL_TRANSFER_ORIGINATION_ERROR_MESSAGE, }) ); - } else if (screenResults?.[recipientAddress!]) { + } else if (screenResults[recipientAddress!]) { setError( stringGetter({ key: STRING_KEYS.WALLET_RESTRICTED_WITHDRAWAL_TRANSFER_DESTINATION_ERROR_MESSAGE, @@ -176,13 +176,13 @@ export const TransferForm = ({ const txResponse = await transfer( amountBN.toNumber(), recipientAddress!, - tokensConfigs[asset]?.denom, + tokensConfigs[asset].denom, memo ?? undefined ); if (txResponse?.code === 0) { // eslint-disable-next-line no-console - console.log('TransferForm > txReceipt > ', txResponse?.hash); + console.log('TransferForm > txReceipt > ', txResponse.hash); onDone?.(); } else { throw new Error(txResponse?.rawLog ?? 'Transaction did not commit.'); @@ -284,7 +284,7 @@ export const TransferForm = ({ key: 'amount', label: ( - {stringGetter({ key: STRING_KEYS.AVAILABLE })} {tokensConfigs[asset]?.name} + {stringGetter({ key: STRING_KEYS.AVAILABLE })} {tokensConfigs[asset].name} ), value: ( @@ -339,7 +339,7 @@ export const TransferForm = ({ <$Row> onChangeAddress(e.target?.value)} + onInput={(e: SyntheticInputEvent) => onChangeAddress(e.target.value)} label={ {stringGetter({ key: STRING_KEYS.DESTINATION })} @@ -419,7 +419,7 @@ export const TransferForm = ({ label={stringGetter({ key: STRING_KEYS.MEMO })} placeholder={stringGetter({ key: STRING_KEYS.REQUIRED_FOR_TRANSFERS_TO_CEX })} type={InputType.Text} - onInput={(e: SyntheticInputEvent) => onChangeMemo(e.target?.value || '')} + onInput={(e: SyntheticInputEvent) => onChangeMemo(e.target.value || '')} value={memo ?? undefined} slotRight={renderFormInputButton({ label: stringGetter({ key: STRING_KEYS.PASTE }), diff --git a/src/views/forms/TransferForm/TransferButtonAndReceipt.tsx b/src/views/forms/TransferForm/TransferButtonAndReceipt.tsx index 8d76e94d0..cc0e5cba2 100644 --- a/src/views/forms/TransferForm/TransferButtonAndReceipt.tsx +++ b/src/views/forms/TransferForm/TransferButtonAndReceipt.tsx @@ -66,7 +66,7 @@ export const TransferButtonAndReceipt = ({ key: 'fees', label: ( - {stringGetter({ key: STRING_KEYS.FEES })} {tokensConfigs[selectedAsset]?.name} + {stringGetter({ key: STRING_KEYS.FEES })} {tokensConfigs[selectedAsset].name} ), value: , @@ -76,7 +76,7 @@ export const TransferButtonAndReceipt = ({ label: ( {stringGetter({ key: STRING_KEYS.BALANCE })}{' '} - {tokensConfigs[selectedAsset]?.name} + {tokensConfigs[selectedAsset].name} ), value: ( diff --git a/src/views/forms/TriggersForm/TriggersForm.tsx b/src/views/forms/TriggersForm/TriggersForm.tsx index c9c6f2c95..d8b421d4e 100644 --- a/src/views/forms/TriggersForm/TriggersForm.tsx +++ b/src/views/forms/TriggersForm/TriggersForm.tsx @@ -124,7 +124,7 @@ export const TriggersForm = ({ symbol={symbol} existsLimitOrder={existsLimitOrder} size={inputSize} - positionSize={size?.current ? Math.abs(size?.current) : null} + positionSize={size?.current ? Math.abs(size.current) : null} differingOrderSizes={differingOrderSizes} multipleTakeProfitOrders={multipleTakeProfitOrders} multipleStopLossOrders={multipleStopLossOrders} @@ -135,7 +135,7 @@ export const TriggersForm = ({ {stringGetter({ key: STRING_KEYS.TRIGGERS_INFO_AUTOMATICALLY_CANCELED })}{' '} {stringGetter({ key: STRING_KEYS.TRIGGERS_INFO_CUSTOM_AMOUNT })}
- +