Skip to content

Commit

Permalink
vault fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
tyleroooo committed Oct 4, 2024
1 parent df7f9df commit 7ffa73d
Show file tree
Hide file tree
Showing 14 changed files with 70 additions and 43 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@
"@datadog/browser-logs": "^5.23.3",
"@dydxprotocol/v4-abacus": "1.12.18",
"@dydxprotocol/v4-client-js": "1.10.0",
"@dydxprotocol/v4-localization": "^1.1.215",
"@dydxprotocol/v4-localization": "^1.1.216",
"@dydxprotocol/v4-proto": "^7.0.0-dev.0",
"@emotion/is-prop-valid": "^1.3.0",
"@ethersproject/providers": "^5.7.2",
Expand Down
8 changes: 4 additions & 4 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

33 changes: 16 additions & 17 deletions src/components/Output.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -404,31 +404,30 @@ export const Output = ({
case OutputType.Percent:
case OutputType.SmallPercent:
case OutputType.Multiple: {
const formattedNumber = formatNumberOutput(value, type, {
decimalSeparator,
groupSeparator,
selectedLocale,
useGrouping,
fractionDigits,
minimumFractionDigits,
roundingMode,
showSign: ShowSign.None,
});

const renderedNumber = <NumberValue value={formattedNumber} withSubscript={withSubscript} />;

const hasValue = value !== null && value !== undefined;
const isNegative = MustBigNumber(value).isNegative();
const isPositive = MustBigNumber(value).isPositive() && !MustBigNumber(value).isZero();
const containsNonZeroNumber = /[1-9]/.test(formattedNumber);
const isNegative = MustBigNumber(value).isNegative() && containsNonZeroNumber;
const isPositive = MustBigNumber(value).isPositive() && containsNonZeroNumber;

const sign: string | undefined = {
[ShowSign.Both]: isNegative ? UNICODE.MINUS : isPositive ? UNICODE.PLUS : undefined,
[ShowSign.Negative]: isNegative ? UNICODE.MINUS : undefined,
[ShowSign.None]: undefined,
}[showSign];

const renderedNumber = (
<NumberValue
value={formatNumberOutput(value, type, {
decimalSeparator,
groupSeparator,
selectedLocale,
useGrouping,
fractionDigits,
minimumFractionDigits,
roundingMode,
showSign: ShowSign.None,
})}
withSubscript={withSubscript}
/>
);
return (
<$Number
key={value?.toString()}
Expand Down
2 changes: 2 additions & 0 deletions src/components/ToggleGroup.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -98,4 +98,6 @@ const $Root = styled(Root)<{ overflow: 'scroll' | 'wrap' }>`

const $Label = styled.div`
${layoutMixins.textTruncate}
// don't truncate 2 characters
min-width: 1rem;
`;
2 changes: 1 addition & 1 deletion src/lib/do.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ type NonNullableArray<T extends readonly any[]> = {
[K in keyof T]: NonNullable<T[K]>;
};

export function runIf<Args extends any[], T>(
export function mapIfPresent<Args extends any[], T>(
...args: [...Args, (...args: NonNullableArray<Args>) => T]
): T | undefined {
if ([...args].some((f) => f == null)) {
Expand Down
8 changes: 4 additions & 4 deletions src/pages/portfolio/AccountOverviewSection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import { getSubaccount } from '@/state/accountSelectors';
import { useAppSelector } from '@/state/appTypes';

import { track } from '@/lib/analytics/analytics';
import { runIf } from '@/lib/do';
import { mapIfPresent } from '@/lib/do';
import { isTruthy } from '@/lib/isTruthy';
import { testFlags } from '@/lib/testFlags';
import { orEmptyObj } from '@/lib/typeUtils';
Expand Down Expand Up @@ -60,7 +60,7 @@ export const AccountOverviewSection = () => {

const { equity, freeCollateral } = orEmptyObj(useAppSelector(getSubaccount, shallowEqual));
const { balanceUsdc: vaultBalance } = orEmptyObj(useLoadedVaultAccount().data);
const totalValue = runIf(equity?.current, (e) => e + (vaultBalance ?? 0));
const totalValue = mapIfPresent(equity?.current, (e) => e + (vaultBalance ?? 0));

const handleViewVault = useCallback(() => {
track(AnalyticsEvents.ClickViewVaultFromOverview());
Expand All @@ -81,8 +81,8 @@ export const AccountOverviewSection = () => {
},
{
id: 'open-positions',
label: stringGetter({ key: STRING_KEYS.OPEN_POSITIONS }),
amount: runIf(equity?.current, freeCollateral?.current, (e, f) => e - f),
label: stringGetter({ key: STRING_KEYS.POSITION_MARGIN }),
amount: mapIfPresent(equity?.current, freeCollateral?.current, (e, f) => e - f),
color: ColorToken.Green2,
},
(showVaults || (vaultBalance ?? 0) > 0.01) && {
Expand Down
2 changes: 1 addition & 1 deletion src/pages/portfolio/History.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export const History = () => {
},
enableVaults && {
value: HistoryRoute.VaultTransfers,
label: <h3>{stringGetter({ key: STRING_KEYS.MEGAVAULT_TRANSFERS })}</h3>,
label: <h3>{stringGetter({ key: STRING_KEYS.VAULT_TRANSFERS })}</h3>,
href: HistoryRoute.VaultTransfers,
tag: 'USDC',
},
Expand Down
2 changes: 1 addition & 1 deletion src/pages/portfolio/PortfolioNavMobile.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ export const PortfolioNavMobile = () => {
},
enableVaults && {
value: `${AppRoute.Portfolio}/${PortfolioRoute.History}/${HistoryRoute.VaultTransfers}`,
label: stringGetter({ key: STRING_KEYS.MEGAVAULT_TRANSFERS }),
label: stringGetter({ key: STRING_KEYS.VAULT_TRANSFERS }),
description: stringGetter({ key: STRING_KEYS.MEGAVAULT_TRANSFERS_DESCRIPTION }),
},
// TODO: TRCL-1693 - re-enable when Payments are ready
Expand Down
30 changes: 26 additions & 4 deletions src/pages/vaults/VaultDepositWithdrawForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,10 @@ import {
import { track } from '@/lib/analytics/analytics';
import { dd } from '@/lib/analytics/datadog';
import { assertNever } from '@/lib/assertNever';
import { runFn } from '@/lib/do';
import { MustBigNumber } from '@/lib/numbers';
import { mapIfPresent, runFn } from '@/lib/do';
import { MustBigNumber, getNumberSign } from '@/lib/numbers';
import { safeAssign } from '@/lib/objectHelpers';
import { sleep } from '@/lib/timeUtils';
import { orEmptyObj } from '@/lib/typeUtils';

// errors we don't want to show aggressive visual cues about, just disable submit
Expand All @@ -69,7 +70,7 @@ type VaultDepositWithdrawFormProps = {
onSuccess?: () => void;
};

const INDEXER_LAG_ALLOWANCE = timeUnits.second * 2;
const INDEXER_LAG_ALLOWANCE = timeUnits.second * 2.5;

const $SmallIcon = styled(Icon)<{ $hasError?: boolean }>`
${({ $hasError }) => ($hasError ? 'color: var(--color-error);' : 'color: var(--color-success);')}
Expand Down Expand Up @@ -206,6 +207,7 @@ export const VaultDepositWithdrawForm = ({
}

await depositToMegavault(cachedAmount);
await sleep(INDEXER_LAG_ALLOWANCE);

track(
AnalyticsEvents.SuccessfulVaultOperation({
Expand Down Expand Up @@ -261,6 +263,7 @@ export const VaultDepositWithdrawForm = ({
submissionData?.withdraw?.shares,
submissionData?.withdraw?.minAmount
);
await sleep(INDEXER_LAG_ALLOWANCE);

const events = (result as IndexedTx)?.events;
const actualAmount = events
Expand Down Expand Up @@ -328,7 +331,6 @@ export const VaultDepositWithdrawForm = ({
console.error('Error submitting megavault transaction', e);
} finally {
forceRefreshVaultAccount();
setTimeout(() => forceRefreshVaultAccount(), INDEXER_LAG_ALLOWANCE);
forceRefreshVault();
setIsSubmitting(false);
}
Expand All @@ -347,6 +349,13 @@ export const VaultDepositWithdrawForm = ({
type={OutputType.Fiat}
value={freeCollateral?.current}
newValue={freeCollateralUpdated}
sign={getNumberSign(
mapIfPresent(
freeCollateralUpdated,
freeCollateral?.current,
(updated, cur) => updated - cur
)
)}
withDiff={
MustBigNumber(amount).gt(0) &&
freeCollateralUpdated != null &&
Expand All @@ -359,6 +368,9 @@ export const VaultDepositWithdrawForm = ({
type={OutputType.Fiat}
value={userBalance}
newValue={userBalanceUpdated}
sign={getNumberSign(
mapIfPresent(userBalanceUpdated, userBalance ?? 0.0, (updated, cur) => updated - cur)
)}
withDiff={
MustBigNumber(amount).gt(0) &&
userBalanceUpdated != null &&
Expand All @@ -371,6 +383,13 @@ export const VaultDepositWithdrawForm = ({
type={OutputType.Fiat}
value={userAvailableBalance}
newValue={userAvailableUpdated}
sign={getNumberSign(
mapIfPresent(
userAvailableUpdated,
userAvailableBalance ?? 0.0,
(updated, cur) => updated - cur
)
)}
withDiff={
MustBigNumber(amount).gt(0) &&
userAvailableUpdated != null &&
Expand All @@ -383,6 +402,9 @@ export const VaultDepositWithdrawForm = ({
type={OutputType.Percent}
value={marginUsage?.current}
newValue={marginUsageUpdated}
sign={getNumberSign(
mapIfPresent(marginUsage?.current, marginUsageUpdated, (updated, cur) => updated - cur)
)}
withDiff={
MustBigNumber(amount).gt(0) &&
marginUsageUpdated != null &&
Expand Down
2 changes: 1 addition & 1 deletion src/pages/vaults/VaultInfoSections.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ export const VaultPositionsSection = ({ className }: { className?: string }) =>
return (
<div className={className}>
<div tw="row mb-1 gap-0.5 text-color-text-2 font-large-medium">
{stringGetter({ key: STRING_KEYS.OPEN_POSITIONS })}{' '}
{stringGetter({ key: STRING_KEYS.POSITIONS })}{' '}
<Tag size={TagSize.Medium} type={TagType.Number}>
{numPositions}
</Tag>
Expand Down
4 changes: 2 additions & 2 deletions src/pages/vaults/VaultLockedSharesTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import { Button } from '@/components/Button';
import { Output, OutputType } from '@/components/Output';
import { ColumnDef, Table } from '@/components/Table';

import { runIf } from '@/lib/do';
import { mapIfPresent } from '@/lib/do';

export const VaultLockedSharesCard = ({ className }: { className?: string }) => {
const stringGetter = useStringGetter();
Expand Down Expand Up @@ -75,7 +75,7 @@ const VaultLockedSharesTable = ({
getCellValue: (row) => row.unlockBlockHeight,
label: stringGetter({ key: STRING_KEYS.AVAILABLE }),
renderCell: ({ unlockBlockHeight }) => {
const estimatedUnlockMs = runIf(
const estimatedUnlockMs = mapIfPresent(
unlockBlockHeight,
height,
(unblock, actual) => new Date().valueOf() + (unblock - actual) * 1000
Expand Down
14 changes: 9 additions & 5 deletions src/pages/vaults/VaultPnlChart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ export const VaultPnlChart = ({ className }: VaultPnlChartProps) => {
}, []);

const chartDotsBackground = useAppSelector(getChartDotBackground);
const { isMobile } = useBreakpoints();
const { isMobile, isDesktopSmall } = useBreakpoints();

const onVisibleDataChange = useCallback((inRangeData: VaultPnlDatum[]) => {
setVisibleTimeRange(
Expand Down Expand Up @@ -201,7 +201,11 @@ export const VaultPnlChart = ({ className }: VaultPnlChartProps) => {
<div tw="flexColumn pl-1 pr-1">
<div tw="text-color-text-0 font-small-book">
{hoveredTime != null ? (
<Output value={hoveredTime} type={OutputType.Date} />
<Output
value={hoveredTime}
type={OutputType.DateTime}
dateOptions={{ format: 'medium' }}
/>
) : (
<Output value={new Date().valueOf()} type={OutputType.Date} />
)}
Expand Down Expand Up @@ -232,16 +236,16 @@ export const VaultPnlChart = ({ className }: VaultPnlChartProps) => {
series={series}
yAxisOrientation="right"
margin={{
left: 0,
left: isDesktopSmall ? 20 : 0,
right: isMobile ? 20 : 60,
top: 24,
bottom: 32,
}}
padding={{
left: 0.01,
right: 0.01,
top: 0.05,
bottom: 0,
top: 0.1,
bottom: 0.1,
}}
tickFormatY={tickFormatY}
onVisibleDataChange={onVisibleDataChange}
Expand Down
2 changes: 1 addition & 1 deletion src/pages/vaults/VaultPositionsTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import { orEmptyRecord } from '@/lib/typeUtils';

type VaultTableRow = VaultPosition;

const VAULT_PAGE_SIZE = 50 as const;
const VAULT_PAGE_SIZE = 20 as const;
export const VaultPositionsTable = ({ className }: { className?: string }) => {
const stringGetter = useStringGetter();
const navigate = useNavigate();
Expand Down
2 changes: 1 addition & 1 deletion src/views/ExportHistoryDropdown.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -358,7 +358,7 @@ export const ExportHistoryDropdown = (props: ExportHistoryDropdownProps) => {
testFlags.enableVaults && {
label: (
<Checkbox
label={stringGetter({ key: STRING_KEYS.MEGAVAULT_TRANSFERS })}
label={stringGetter({ key: STRING_KEYS.VAULT_TRANSFERS })}
checked={checkedVaultTransfers}
disabled={isEmpty(allVaultTransfers)}
onCheckedChange={() => {
Expand Down

0 comments on commit 7ffa73d

Please sign in to comment.