Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

feat(bonsai-ui): migrate position action cell and triggers dialog, delete some old stuff #1465

Merged
merged 6 commits into from
Jan 27, 2025
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/abacus-ts/calculators/helpers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { PositionUniqueId } from '../types/summaryTypes';

export function getPositionUniqueId(marketId: string, subaccountNumber: number): PositionUniqueId {
return `${marketId}-${subaccountNumber}` as PositionUniqueId;
}
29 changes: 27 additions & 2 deletions src/abacus-ts/calculators/orders.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@ import { HeightResponse } from '@dydxprotocol/v4-client-js';
import { mapValues, maxBy, orderBy } from 'lodash';

import { NUM_PARENT_SUBACCOUNTS } from '@/constants/account';
import { IndexerBestEffortOpenedStatus, IndexerOrderStatus } from '@/types/indexer/indexerApiGen';
import {
IndexerBestEffortOpenedStatus,
IndexerOrderStatus,
IndexerOrderType,
} from '@/types/indexer/indexerApiGen';
import { IndexerCompositeOrderObject } from '@/types/indexer/indexerManual';

import { assertNever } from '@/lib/assertNever';
Expand All @@ -13,6 +17,7 @@ import { MaybeBigNumber, MustBigNumber } from '@/lib/numbers';
import { mergeObjects } from '../lib/mergeObjects';
import { OrdersData } from '../types/rawTypes';
import { OrderStatus, SubaccountOrder } from '../types/summaryTypes';
import { getPositionUniqueId } from './helpers';

export function calculateOpenOrders(orders: SubaccountOrder[]) {
return orders.filter(
Expand Down Expand Up @@ -50,8 +55,9 @@ function calculateSubaccountOrder(
marginMode: base.subaccountNumber >= NUM_PARENT_SUBACCOUNTS ? 'ISOLATED' : 'CROSS',
subaccountNumber: base.subaccountNumber,
id: base.id,
positionUniqueId: getPositionUniqueId(base.ticker, base.subaccountNumber),
clientId: base.clientId,
type: base.type,
type: getOrderType(base.type, base.clientMetadata),
side: base.side,
timeInForce: base.timeInForce,
clobPairId: MaybeBigNumber(base.clobPairId)?.toNumber(),
Expand All @@ -72,6 +78,25 @@ function calculateSubaccountOrder(
return order;
}

function getOrderType(
type: IndexerOrderType,
clientMetadata: string | undefined
): IndexerOrderType {
if (clientMetadata === '1') {
switch (type) {
case IndexerOrderType.LIMIT:
return IndexerOrderType.MARKET;
case IndexerOrderType.STOPLIMIT:
return IndexerOrderType.STOPMARKET;
case IndexerOrderType.TAKEPROFIT:
return IndexerOrderType.TAKEPROFITMARKET;
default:
return type;
}
}
return type;
}

export function getSimpleOrderStatus(status: OrderStatus) {
switch (status) {
case OrderStatus.Open:
Expand Down
3 changes: 2 additions & 1 deletion src/abacus-ts/calculators/subaccount.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import {
SubaccountSummaryCore,
SubaccountSummaryDerived,
} from '../types/summaryTypes';
import { getPositionUniqueId } from './helpers';
import { getMarketEffectiveInitialMarginForMarket } from './markets';

export function calculateParentSubaccountPositions(
Expand Down Expand Up @@ -216,7 +217,7 @@ function calculateDerivedPositionCore(
const value = signedSize.times(oracle);

return {
uniqueId: `${position.market}-${position.subaccountNumber}`,
uniqueId: getPositionUniqueId(position.market, position.subaccountNumber),
assetId: getAssetFromMarketId(position.market),
marginMode,
unsignedSize,
Expand Down
4 changes: 4 additions & 0 deletions src/abacus-ts/ontology.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ import {
selectRawValidatorHeightDataLoading,
} from './selectors/base';
import {
createSelectMarketSummaryById,
selectAllMarketSummaries,
selectAllMarketSummariesLoading,
selectCurrentMarketInfo,
Expand Down Expand Up @@ -111,6 +112,9 @@ export const BonsaiHelpers = {
assets: {
createSelectAssetInfo,
},
markets: {
createSelectMarketSummaryById,
},
forms: {
deposit: {
createSelectParentSubaccountSummary: createSelectParentSubaccountSummaryDeposit,
Expand Down
11 changes: 11 additions & 0 deletions src/abacus-ts/selectors/summary.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,3 +66,14 @@ export const selectCurrentMarketAssetInfo = createAppSelector(
return assets[currentMarketInfo.assetId];
}
);

export const createSelectMarketSummaryById = () =>
createAppSelector(
[selectAllMarketSummaries, (_s, marketId: string | undefined) => marketId],
(allSummaries, marketId) => {
if (marketId == null) {
return undefined;
}
return allSummaries?.[marketId];
}
);
5 changes: 4 additions & 1 deletion src/abacus-ts/types/summaryTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,10 @@ export type SubaccountPositionBase = ConvertStringToBigNumber<

export type MarginMode = 'ISOLATED' | 'CROSS';

export type PositionUniqueId = string & { ___brand: 'POSITION_UNIQUE_ID' };

export type SubaccountPositionDerivedCore = {
uniqueId: string;
uniqueId: PositionUniqueId;
assetId: string;
marginMode: MarginMode;

Expand Down Expand Up @@ -133,6 +135,7 @@ export type SubaccountOrder = {
subaccountNumber: number;
id: string;
clientId: string | undefined;
positionUniqueId: PositionUniqueId; // market + subaccount, can map to a unique position if/when it exists
type: IndexerOrderType;
side: IndexerOrderSide;
status: OrderStatus | undefined;
Expand Down
6 changes: 3 additions & 3 deletions src/constants/dialogs.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import { ReactNode } from 'react';

import { PositionUniqueId } from '@/abacus-ts/types/summaryTypes';
import { TagsOf, UnionOf, ofType, unionize } from 'unionize';

import { IndexerPositionSide } from '@/types/indexer/indexerApiGen';

import { BigNumberish } from '@/lib/numbers';

import { Nullable, SubaccountOrder, SubaccountPosition } from './abacus';
import { Nullable, SubaccountPosition } from './abacus';
import { IAffiliateStats } from './affiliates';
import { DydxChainAsset } from './wallets';

Expand Down Expand Up @@ -76,10 +77,9 @@ export type TradeDialogProps = {
slotTrigger?: React.ReactNode;
};
export type TriggersDialogProps = {
positionUniqueId: PositionUniqueId;
marketId: string;
assetId: string;
stopLossOrders: SubaccountOrder[];
takeProfitOrders: SubaccountOrder[];
navigateToMarketOrders: (market: string) => void;
};
export type TransferDialogProps = { selectedAsset?: DydxChainAsset };
Expand Down
3 changes: 3 additions & 0 deletions src/constants/markets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ export type MarketData = {
// Displayable Market id (e.g. 'ETH-USD' or 'BUFFI-USD')
displayId: Nullable<string>;

// Displayable asset id so just 'ETH' or 'BUFFI
displayableAsset: Nullable<string>;

clobPairId: string;
effectiveInitialMarginFraction: Nullable<number>;
logo: string;
Expand Down
37 changes: 20 additions & 17 deletions src/hooks/useTriggerOrdersFormInputs.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { useEffect, useState } from 'react';

import { SubaccountOrder } from '@/abacus-ts/types/summaryTypes';
import { shallowEqual, useDispatch } from 'react-redux';

import { AbacusOrderType, SubaccountOrder, TriggerOrdersInputField } from '@/constants/abacus';
import { AbacusOrderType, TriggerOrdersInputField } from '@/constants/abacus';

import { useAppSelector } from '@/state/appTypes';
import { setTriggerFormInputs } from '@/state/inputs';
Expand All @@ -11,7 +12,7 @@ import { getTriggerOrdersInputErrors } from '@/state/inputsSelectors';
import abacusStateManager from '@/lib/abacus';
import { isTruthy } from '@/lib/isTruthy';
import { MustBigNumber } from '@/lib/numbers';
import { isLimitOrderType } from '@/lib/orders';
import { isLimitOrderTypeNew } from '@/lib/orders';

export const useTriggerOrdersFormInputs = ({
marketId,
Expand Down Expand Up @@ -50,22 +51,23 @@ export const useTriggerOrdersFormInputs = ({
},
{
field: TriggerOrdersInputField.stopLossOrderSize,
value: stopLossOrder.size,
value: stopLossOrder.size.toNumber(),
hasFormInput: false,
},
{
field: TriggerOrdersInputField.stopLossOrderType,
value: stopLossOrder.type.rawValue,
// DANGER - only safe because they happen to match, manually verified
value: stopLossOrder.type,
tyleroooo marked this conversation as resolved.
Show resolved Hide resolved
hasFormInput: false,
},
{
field: TriggerOrdersInputField.stopLossPrice,
value: stopLossOrder.triggerPrice,
value: stopLossOrder.triggerPrice?.toNumber(),
hasFormInput: true,
},
isLimitOrderType(stopLossOrder.type) && {
isLimitOrderTypeNew(stopLossOrder.type) && {
field: TriggerOrdersInputField.stopLossLimitPrice,
value: stopLossOrder.price,
value: stopLossOrder.price.toNumber(),
hasFormInput: true,
},
]
Expand Down Expand Up @@ -97,22 +99,23 @@ export const useTriggerOrdersFormInputs = ({
},
{
field: TriggerOrdersInputField.takeProfitOrderSize,
value: takeProfitOrder.size,
value: takeProfitOrder.size.toNumber(),
hasFormInput: false,
},
{
field: TriggerOrdersInputField.takeProfitOrderType,
value: takeProfitOrder.type.rawValue,
// DANGER - only safe because they happen to match, manually verified
value: takeProfitOrder.type,
hasFormInput: false,
},
{
field: TriggerOrdersInputField.takeProfitPrice,
value: takeProfitOrder.triggerPrice,
value: takeProfitOrder.triggerPrice?.toNumber(),
hasFormInput: true,
},
isLimitOrderType(takeProfitOrder.type) && {
isLimitOrderTypeNew(takeProfitOrder.type) && {
field: TriggerOrdersInputField.takeProfitLimitPrice,
value: takeProfitOrder.price,
value: takeProfitOrder.price.toNumber(),
hasFormInput: true,
},
]
Expand All @@ -136,15 +139,15 @@ export const useTriggerOrdersFormInputs = ({

if (stopLossOrder?.size && takeProfitOrder?.size) {
if (stopLossOrder.size === takeProfitOrder.size) {
setSize(stopLossOrder.size);
setSize(stopLossOrder.size.toNumber());
} else {
setSize(null);
setDifferingOrderSizes(true);
}
} else if (stopLossOrder?.size) {
setSize(stopLossOrder.size);
setSize(stopLossOrder.size.toNumber());
} else if (takeProfitOrder?.size) {
setSize(takeProfitOrder.size);
setSize(takeProfitOrder.size.toNumber());
} else {
// Default to full position size for initial order creation
setSize(positionSize);
Expand Down Expand Up @@ -172,7 +175,7 @@ export const useTriggerOrdersFormInputs = ({
inputSize,
// Boolean to signify whether the limit box should be checked on initial render of the triggers order form
existsLimitOrder:
!!(stopLossOrder && isLimitOrderType(stopLossOrder.type)) ||
!!(takeProfitOrder && isLimitOrderType(takeProfitOrder.type)),
!!(stopLossOrder && isLimitOrderTypeNew(stopLossOrder.type)) ||
!!(takeProfitOrder && isLimitOrderTypeNew(takeProfitOrder.type)),
};
};
15 changes: 0 additions & 15 deletions src/lib/abacus/stateNotification.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ import {
setChildSubaccount,
setCompliance,
setFills,
setFundingPayments,
setHistoricalPnl,
setRestrictionType,
setStakingBalances,
Expand Down Expand Up @@ -188,20 +187,6 @@ class AbacusStateNotifier implements AbacusStateNotificationProtocol {
}
}

if (changes.has(Changes.fundingPayments)) {
const fundingPayments =
updatedState.subaccountFundingPayments(subaccountId)?.toArray() ?? [];

if (isChildSubaccount) {
childSubaccountUpdate[subaccountId] = {
...childSubaccountUpdate[subaccountId],
fundingPayments,
};
} else {
dispatch(setFundingPayments(fundingPayments));
}
}

if (changes.has(Changes.transfers)) {
const transfers = updatedState.subaccountTransfers(subaccountId)?.toArray() ?? [];

Expand Down
10 changes: 9 additions & 1 deletion src/lib/marketsHelpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@ import { AssetData, PerpetualMarketSummary } from '@/abacus-ts/types/summaryType

import { ISOLATED_LIQUIDITY_TIER_INFO, MarketData } from '@/constants/markets';

import { getDisplayableTickerFromMarket, getMarketIdFromAsset } from './assetUtils';
import {
getDisplayableAssetFromTicker,
getDisplayableTickerFromMarket,
getMarketIdFromAsset,
} from './assetUtils';
import { BIG_NUMBERS, MustBigNumber } from './numbers';
import { safeAssign } from './objectHelpers';

Expand All @@ -28,6 +32,7 @@ export function getMarketDataFromPerpetualMarketSummary(
ticker: id,
assetId,
displayableTicker: displayId,
displayableAsset,
clobPairId,
effectiveInitialMarginFraction,
logo,
Expand All @@ -54,6 +59,7 @@ export function getMarketDataFromPerpetualMarketSummary(
id,
assetId,
displayId,
displayableAsset,
clobPairId,
effectiveInitialMarginFraction,
logo,
Expand Down Expand Up @@ -94,11 +100,13 @@ export function getMarketDataFromAsset(asset: AssetData, favoritedMarkets: strin

const ticker = getMarketIdFromAsset(assetId);
const displayId = getDisplayableTickerFromMarket(ticker);
const displayableAsset = getDisplayableAssetFromTicker(ticker);

return safeAssign({}, {
id: ticker,
assetId,
displayId,
displayableAsset,
clobPairId: '-1',
effectiveInitialMarginFraction: ISOLATED_LIQUIDITY_TIER_INFO.initialMarginFraction,
logo,
Expand Down
Loading
Loading