Compare commits

..
Author SHA1 Message Date
jaredvu 29a894e124 Merge branch 'main' into canvas-orderbook 2024-01-03 13:44:50 -08:00
jaredvu 4a4014d837 Merge remote-tracking branch 'origin/main' into canvas-orderbook 2023-12-06 10:09:10 -08:00
jaredvu 7c48058cd3 Animation attempt 2023-11-28 15:44:01 -08:00
jaredvu 2e51502abe Use 100% for canvas width 2023-11-27 14:58:45 -08:00
jaredvu def6874de9 useDrawOrderbookHistograms -> useDrawOrderbook 2023-11-27 13:26:26 -08:00
jaredvu e475a24732 Histogram side handling 2023-11-27 13:20:52 -08:00
jaredvu 01a1678edd Merge remote-tracking branch 'origin/main' into canvas-orderbook 2023-11-27 13:07:22 -08:00
jaredvu 8da8408a0a hard code height/width to avoid scaling issues 2023-11-27 10:18:35 -08:00
jaredvu 8bae419297 restore setting width from ref 2023-11-27 09:52:58 -08:00
jaredvu a54653242e Update drawnText color on theme change 2023-11-26 17:31:08 -08:00
jaredvu fad4284ed5 Add log for createLinearGradient 2023-11-26 17:00:06 -08:00
jaredvu 19a377a9e5 remove clientHeight from dep list 2023-11-26 15:02:38 -08:00
jaredvu ca9501e3cc Fix orderbook centering 2023-11-26 14:55:53 -08:00
jaredvu 1407c9a460 Orderbook Row: Handle locale change 2023-11-26 14:32:20 -08:00
jaredvu d96b07b394 Unset hoveredRow if unapplicable 2023-11-26 13:43:51 -08:00
jaredvu c76b71143b Add hoverCanvas. Optimize Clearing for canvas 2023-11-26 13:32:54 -08:00
jaredvu a2dfda3481 Consolidate draw methods, improve scrollListener 2023-11-25 14:20:56 -08:00
jaredvu e3462b6514 Create new Orderbook component rendered by canvas 2023-11-25 02:27:16 -08:00
27 changed files with 1750 additions and 4614 deletions
+4 -5
View File
@@ -41,7 +41,7 @@
"@cosmjs/tendermint-rpc": "^0.31.0",
"@dydxprotocol/v4-abacus": "^1.1.32",
"@dydxprotocol/v4-client-js": "^1.0.11",
"@dydxprotocol/v4-localization": "^1.1.6",
"@dydxprotocol/v4-localization": "^1.1.5",
"@ethersproject/providers": "^5.7.2",
"@js-joda/core": "^5.5.3",
"@radix-ui/react-accordion": "^1.1.2",
@@ -72,7 +72,6 @@
"@reduxjs/toolkit": "^1.9.5",
"@scure/bip32": "^1.3.0",
"@scure/bip39": "^1.2.0",
"@tanstack/react-query": "^5.17.9",
"@types/lodash": "^4.14.195",
"@types/styled-components": "^5.1.26",
"@visx/axis": "^3.1.0",
@@ -105,15 +104,15 @@
"react-aria": "^3.25.0",
"react-dom": "^18.2.0",
"react-number-format": "^5.2.2",
"react-query": "^3.39.3",
"react-redux": "^8.1.1",
"react-router-dom": "^6.14.0",
"react-stately": "^3.23.0",
"reselect": "^4.1.8",
"stream-browserify": "^3.0.0",
"styled-components": "^5.3.11",
"use-latest": "^1.2.1",
"viem": "^2.0.0",
"wagmi": "^2.0.3"
"viem": "^1.12.2",
"wagmi": "^1.4.12"
},
"devDependencies": {
"@babel/core": "^7.22.5",
+597 -4299
View File
File diff suppressed because it is too large Load Diff
+26 -26
View File
@@ -39,7 +39,7 @@
"environments": {
"dydxprotocol-dev": {
"name": "v4 Dev",
"ethereumChainId": "11155111",
"ethereumChainId": "5",
"dydxChainId": "dydxprotocol-testnet",
"chainName": "dYdX Chain",
"chainLogo": "/dydx-chain.png",
@@ -113,7 +113,7 @@
},
"dydxprotocol-dev-2": {
"name": "v4 Dev 2",
"ethereumChainId": "11155111",
"ethereumChainId": "5",
"dydxChainId": "dydxprotocol-testnet",
"chainName": "dYdX Chain",
"chainLogo": "/dydx-chain.png",
@@ -186,7 +186,7 @@
},
"dydxprotocol-dev-4": {
"name": "v4 Dev 4",
"ethereumChainId": "11155111",
"ethereumChainId": "5",
"dydxChainId": "dydxprotocol-testnet",
"chainName": "dYdX Chain",
"chainLogo": "/dydx-chain.png",
@@ -259,7 +259,7 @@
},
"dydxprotocol-dev-5": {
"name": "v4 Dev 5",
"ethereumChainId": "11155111",
"ethereumChainId": "5",
"dydxChainId": "dydxprotocol-testnet",
"chainName": "dYdX Chain",
"chainLogo": "/dydx-chain.png",
@@ -332,7 +332,7 @@
},
"dydxprotocol-staging": {
"name": "v4 Staging",
"ethereumChainId": "11155111",
"ethereumChainId": "5",
"dydxChainId": "dydxprotocol-testnet",
"chainName": "dYdX Chain",
"chainLogo": "/dydx-chain.png",
@@ -407,7 +407,7 @@
},
"dydxprotocol-staging-forced-update": {
"name": "v4 Staging Forced Update",
"ethereumChainId": "11155111",
"ethereumChainId": "5",
"dydxChainId": "dydxprotocol-testnet",
"chainName": "dYdX Chain",
"chainLogo": "/dydx-chain.png",
@@ -480,7 +480,7 @@
},
"dydxprotocol-staging-west": {
"name": "v4 Staging West",
"ethereumChainId": "11155111",
"ethereumChainId": "5",
"dydxChainId": "dydxprotocol-testnet",
"chainName": "dYdX Chain",
"chainLogo": "/dydx-chain.png",
@@ -555,7 +555,7 @@
},
"dydxprotocol-testnet": {
"name": "v4 Public Testnet",
"ethereumChainId": "11155111",
"ethereumChainId": "5",
"dydxChainId": "dydx-testnet-4",
"chainName": "dYdX Chain",
"chainLogo": "/dydx-chain.png",
@@ -579,8 +579,8 @@
"endpoints": {
"indexers": [
{
"api": "https://indexer.v4testnet.dydx.exchange",
"socket": "wss://indexer.v4testnet.dydx.exchange"
"api": "https://dydx-testnet.imperator.co",
"socket": "wss://dydx-testnet.imperator.co"
}
],
"validators": [
@@ -634,7 +634,7 @@
},
"dydxprotocol-testnet-dydx": {
"name": "v4 Public Testnet/dYdX",
"ethereumChainId": "11155111",
"ethereumChainId": "5",
"dydxChainId": "dydx-testnet-4",
"chainName": "dYdX Chain",
"chainLogo": "/dydx-chain.png",
@@ -710,7 +710,7 @@
},
"dydxprotocol-testnet-nodefleet": {
"name": "v4 Public Testnet/nodefleet",
"ethereumChainId": "11155111",
"ethereumChainId": "5",
"dydxChainId": "dydx-testnet-4",
"chainName": "dYdX Chain",
"chainLogo": "/dydx-chain.png",
@@ -734,8 +734,8 @@
"endpoints": {
"indexers": [
{
"api": "https://indexer.v4testnet.dydx.exchange",
"socket": "wss://indexer.v4testnet.dydx.exchange"
"api": "https://dydx-testnet.imperator.co",
"socket": "wss://dydx-testnet.imperator.co"
}
],
"validators": [
@@ -786,7 +786,7 @@
},
"dydxprotocol-testnet-kingnodes": {
"name": "v4 Public Testnet/KingNodes",
"ethereumChainId": "11155111",
"ethereumChainId": "5",
"dydxChainId": "dydx-testnet-4",
"chainName": "dYdX Chain",
"chainLogo": "/dydx-chain.png",
@@ -810,8 +810,8 @@
"endpoints": {
"indexers": [
{
"api": "https://indexer.v4testnet.dydx.exchange",
"socket": "wss://indexer.v4testnet.dydx.exchange"
"api": "https://dydx-testnet.imperator.co",
"socket": "wss://dydx-testnet.imperator.co"
}
],
"validators": [
@@ -862,7 +862,7 @@
},
"dydxprotocol-testnet-liquify": {
"name": "v4 Public Testnet/Liquify",
"ethereumChainId": "11155111",
"ethereumChainId": "5",
"dydxChainId": "dydx-testnet-4",
"chainName": "dYdX Chain",
"chainLogo": "/dydx-chain.png",
@@ -886,8 +886,8 @@
"endpoints": {
"indexers": [
{
"api": "https://indexer.v4testnet.dydx.exchange",
"socket": "wss://indexer.v4testnet.dydx.exchange"
"api": "https://dydx-testnet.imperator.co",
"socket": "wss://dydx-testnet.imperator.co"
}
],
"validators": [
@@ -938,7 +938,7 @@
},
"dydxprotocol-testnet-polkachu": {
"name": "v4 Public Testnet/Polkahcu",
"ethereumChainId": "11155111",
"ethereumChainId": "5",
"dydxChainId": "dydx-testnet-4",
"chainName": "dYdX Chain",
"chainLogo": "/dydx-chain.png",
@@ -962,8 +962,8 @@
"endpoints": {
"indexers": [
{
"api": "https://indexer.v4testnet.dydx.exchange",
"socket": "wss://indexer.v4testnet.dydx.exchange"
"api": "https://dydx-testnet.imperator.co",
"socket": "wss://dydx-testnet.imperator.co"
}
],
"validators": [
@@ -1005,7 +1005,7 @@
},
"dydxprotocol-testnet-bware": {
"name": "v4 Public Testnet/BWare",
"ethereumChainId": "11155111",
"ethereumChainId": "5",
"dydxChainId": "dydx-testnet-4",
"chainName": "dYdX Chain",
"chainLogo": "/dydx-chain.png",
@@ -1029,8 +1029,8 @@
"endpoints": {
"indexers": [
{
"api": "https://indexer.v4testnet.dydx.exchange",
"socket": "wss://indexer.v4testnet.dydx.exchange"
"api": "https://dydx-testnet.imperator.co",
"socket": "wss://dydx-testnet.imperator.co"
}
],
"validators": [
+3 -3
View File
@@ -1,8 +1,8 @@
import { lazy, Suspense } from 'react';
import { Navigate, Route, Routes } from 'react-router-dom';
import styled, { AnyStyledComponent, css } from 'styled-components';
import { WagmiProvider } from 'wagmi';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { WagmiConfig } from 'wagmi';
import { QueryClient, QueryClientProvider } from 'react-query';
import { GrazProvider } from 'graz';
import { AppRoute, DEFAULT_TRADE_ROUTE } from '@/constants/routes';
@@ -120,9 +120,9 @@ const wrapProvider = (Component: React.ComponentType<any>, props?: any) => {
};
const providers = [
wrapProvider(WagmiProvider, { config }),
wrapProvider(QueryClientProvider, { client: queryClient }),
wrapProvider(GrazProvider),
wrapProvider(WagmiConfig, { config }),
wrapProvider(LocaleProvider),
wrapProvider(RestrictionProvider),
wrapProvider(DydxProvider),
+16
View File
@@ -0,0 +1,16 @@
import { forwardRef } from 'react';
type StyleProps = {
className?: string;
};
type ElementProps = {
width: number | string;
height: number | string;
};
export const Canvas = forwardRef<HTMLCanvasElement, ElementProps & StyleProps>(
({ className, width, height }, canvasRef) => (
<canvas ref={canvasRef} className={className} width={width ?? 0} height={height ?? 0} />
)
);
+1
View File
@@ -118,6 +118,7 @@ export const Tabs = <TabItemsValue extends string>({
forceMount={forceMount}
$hide={forceMount && currentItem?.value !== value}
$withTransitions={withTransitions}
asChild={asChild}
>
{content}
</Styled.Content>
-5
View File
@@ -1,5 +0,0 @@
export enum QueryKeys {
ACCOUNT_BALANCE = 'ACCOUNT_BALANCE',
LAUNCH_INCENTIVES = 'LAUNCH_INCENTIVES',
TRANSACTION_STATUS = 'TRANSACTION_STATUS',
}
+2 -13
View File
@@ -52,7 +52,7 @@ type WalletConnectionTypeConfig = {
wagmiConnectorId?: string;
};
export const WALLET_CONNECTION_TYPES: Record<WalletConnectionType, WalletConnectionTypeConfig> = {
export const walletConnectionTypes: Record<WalletConnectionType, WalletConnectionTypeConfig> = {
[WalletConnectionType.CoinbaseWalletSdk]: {
name: 'Coinbase Wallet SDK',
wagmiConnectorId: 'coinbaseWallet',
@@ -110,7 +110,7 @@ export const WALLET_CONNECT_EXPLORER_RECOMMENDED_IDS = Object.values(
WALLET_CONNECT_EXPLORER_RECOMMENDED_WALLETS
);
export type WalletConfig = {
type WalletConfig = {
type: WalletType;
stringKey: string;
icon: string;
@@ -274,17 +274,6 @@ export type WalletConnection = {
provider?: ExternalProvider;
};
export type WalletConnectConfig = {
client: {
name: string;
description: string;
iconUrl: string;
};
v2: {
projectId: string;
};
};
// dYdX Chain wallets
export const COSMOS_DERIVATION_PATH = "m/44'/118'/0'/0/0";
+11
View File
@@ -0,0 +1,11 @@
import { useCalculateOrderbookData } from './useCalculateOrderbookData';
import { useCenterOrderbook } from './useCenterOrderbook';
import { useDrawOrderbook } from './useDrawOrderbook';
import { useSpreadRowScrollListener } from './useSpreadRowScrollListener';
export {
useCalculateOrderbookData,
useCenterOrderbook,
useDrawOrderbook,
useSpreadRowScrollListener,
};
@@ -0,0 +1,55 @@
import { useMemo } from 'react';
import { useSelector, shallowEqual } from 'react-redux';
import { OrderSide } from '@dydxprotocol/v4-client-js';
import { OrderbookLine } from '@/constants/abacus';
import { getCurrentMarketOrderbook } from '@/state/perpetualsSelectors';
import { getSubaccountOpenOrdersBySideAndPrice } from '@/state/accountSelectors';
import type { RowData } from '@/views/Orderbook/OrderbookRow';
import { MustBigNumber } from '@/lib/numbers';
export const useCalculateOrderbookData = ({ maxRowsPerSide }: { maxRowsPerSide: number }) => {
const orderbook = useSelector(getCurrentMarketOrderbook, shallowEqual);
const openOrdersBySideAndPrice =
useSelector(getSubaccountOpenOrdersBySideAndPrice, shallowEqual) || {};
return useMemo(() => {
const asks = (orderbook?.asks?.toArray() ?? [])
.map(
(row: OrderbookLine) =>
({
side: 'ask',
mine: openOrdersBySideAndPrice[OrderSide.SELL]?.[row.price]?.size,
...row,
} as RowData)
)
.slice(0, maxRowsPerSide);
const bids = (orderbook?.bids?.toArray() ?? [])
.map(
(row: OrderbookLine) =>
({
side: 'bid',
mine: openOrdersBySideAndPrice[OrderSide.BUY]?.[row.price]?.size,
...row,
} as RowData)
)
.slice(0, maxRowsPerSide);
const spread =
asks[0] && bids[0] ? MustBigNumber(asks[0]?.price ?? 0).minus(bids[0]?.price ?? 0) : null;
const spreadPercent = orderbook?.spreadPercent;
const histogramRange = Math.max(
Number(bids[bids.length - 1]?.depth),
Number(asks[asks.length - 1]?.depth)
);
return { asks, bids, spread, spreadPercent, histogramRange, hasOrderbook: !!orderbook };
}, [orderbook, openOrdersBySideAndPrice]);
};
+22
View File
@@ -0,0 +1,22 @@
import { type RefObject, useEffect } from 'react';
type ElementProps = {
marketId: string;
orderbookRef: RefObject<HTMLDivElement>;
};
/**
* @description Center Orderbook on load and market change
* Assumed that the two sides are the same height
*/
export const useCenterOrderbook = ({ marketId, orderbookRef }: ElementProps) => {
const orderbookEl = orderbookRef.current;
const { clientHeight, scrollHeight } = orderbookEl ?? {};
const shouldScroll = !!scrollHeight && !!clientHeight && scrollHeight > clientHeight;
useEffect(() => {
if (orderbookEl && shouldScroll) {
orderbookEl.scrollTo({ top: (scrollHeight - clientHeight) / 2 });
}
}, [shouldScroll, marketId]);
};
+380
View File
@@ -0,0 +1,380 @@
import { useCallback, useEffect, useMemo, useRef } from 'react';
import { useSelector } from 'react-redux';
import type { Nullable } from '@/constants/abacus';
import { SMALL_USD_DECIMALS, TOKEN_DECIMALS } from '@/constants/numbers';
import { useLocaleSeparators } from '@/hooks/useLocaleSeparators';
import { getAppTheme } from '@/state/configsSelectors';
import { ROW_HEIGHT, ROW_PADDING_RIGHT, type RowData } from '@/views/Orderbook/OrderbookRow';
import { MustBigNumber } from '@/lib/numbers';
import { log } from '@/lib/telemetry';
import { Colors } from '@/styles/colors';
type ElementProps = {
data: RowData[];
histogramRange: number;
hoveredRow?: number;
stepSizeDecimals: Nullable<number>;
tickSizeDecimals: Nullable<number>;
};
type StyleProps = {
histogramSide?: 'left' | 'right';
};
export const useDrawOrderbook = ({
data,
histogramRange,
stepSizeDecimals,
tickSizeDecimals,
histogramSide = 'right',
hoveredRow,
}: ElementProps & StyleProps) => {
const theme = useSelector(getAppTheme);
const canvasRef = useRef<HTMLCanvasElement>(null);
const hoverCanvasRef = useRef<HTMLCanvasElement>(null);
const canvas = canvasRef.current;
const hoverCanvas = hoverCanvasRef.current;
/**
* to === 'right' to === 'left'
* |===================| |===================|
* bar: a b c d
* a = 0
* b = depthBarWidth
* c = canvasWidth - depthBarWidth
* d = canvasWidth
*
*/
const getXYValues = ({
barWidth,
canvasWidth,
gradientMultiplier,
}: {
barWidth: number;
canvasWidth: number;
gradientMultiplier: number;
}) => {
const gradient = {
x1: Math.floor(histogramSide === 'left' ? barWidth : canvasWidth - barWidth),
x2: Math.floor(
histogramSide === 'left'
? 0 - (canvasWidth * gradientMultiplier - canvasWidth)
: canvasWidth * gradientMultiplier
),
};
const bar = {
x1: Math.floor(histogramSide === 'left' ? 0 : canvasWidth - barWidth),
x2: Math.floor(
histogramSide === 'left' ? Math.min(barWidth, canvasWidth - 2) : canvasWidth - 2
),
};
return {
bar,
gradient,
};
};
const getYFromIndex = (idx: number, type: 'text' | 'bar' | 'rect') => {
return (
idx * ROW_HEIGHT +
{
text: ROW_HEIGHT / 2, // center of the row
bar: 1, // 1px off the top and bottom so the histograms do not touch
rect: 0,
}[type]
);
};
// Get X value by column, colIdx starts at 0
const getXByColumn = ({ canvasWidth, colIdx }: { canvasWidth: number; colIdx: number }) => {
return Math.floor(((colIdx + 1) * canvasWidth) / 3);
};
const drawBars = ({
value,
canvasWidth,
ctx,
gradientMultiplier,
histogramAccentColor,
idx,
histogramSide,
}: {
value: Nullable<number>;
canvasWidth: number;
ctx: CanvasRenderingContext2D;
gradientMultiplier: number;
histogramAccentColor: string;
idx: number;
histogramSide: 'left' | 'right';
}) => {
const histogramBarWidth = canvasWidth - 2;
const barWidth = value ? (value / histogramRange) * histogramBarWidth : 0;
const { gradient, bar } = getXYValues({ barWidth, canvasWidth, gradientMultiplier });
let linearGradient;
try {
linearGradient = ctx.createLinearGradient(
gradient.x1,
ROW_HEIGHT / 2,
gradient.x2,
ROW_HEIGHT / 2
);
linearGradient.addColorStop(0, histogramAccentColor);
linearGradient.addColorStop(1, 'rgba(0, 0, 0, 0)');
ctx.fillStyle = linearGradient;
} catch (err) {
log('Orderbook/createLinearGradient', err, {
x1: gradient.x1,
y1: ROW_HEIGHT / 2,
x2: gradient.x2,
y2: ROW_HEIGHT / 2,
});
ctx.fillStyle = 'rgba(0, 0, 0, 0)';
}
ctx.beginPath();
ctx.roundRect
? ctx.roundRect?.(
bar.x1,
getYFromIndex(idx, 'bar'),
bar.x2,
ROW_HEIGHT - 2,
histogramSide === 'right' ? [2, 0, 0, 2] : [0, 2, 2, 0]
)
: ctx.rect(bar.x1, getYFromIndex(idx, 'bar'), bar.x2, ROW_HEIGHT - 2);
ctx.fill();
};
const { decimal: LOCALE_DECIMAL_SEPARATOR } = useLocaleSeparators();
const formatOptions = {
decimalSeparator: LOCALE_DECIMAL_SEPARATOR,
};
const drawText = useCallback(
({
ctx,
canvasWidth,
idx,
size,
price,
mine,
animationType,
}: {
ctx: CanvasRenderingContext2D;
canvasWidth: number;
idx: number;
size?: Nullable<number>;
price?: Nullable<number>;
mine?: Nullable<number>;
animationType?: 'remove' | 'add';
}) => {
const y = getYFromIndex(idx, 'text');
const rectY = getYFromIndex(idx, 'rect');
let startTime: number;
let textColor: string = Colors[theme].text2;
const animateColor = (timestamp: number) => {
if (!startTime) startTime = timestamp;
const animationTime = timestamp - startTime;
// Linear transition for demonstration purposes
textColor = animationType
? {
add: Colors[theme].green,
remove: Colors[theme].red,
}[animationType]
: Colors[theme].text2;
if (animationTime < 500) {
// Continue the animation for 500ms (adjust as needed)
requestAnimationFrame(animateColor);
} else {
textColor = Colors[theme].text2;
}
if (animationType) {
// TODO: Clear rect and redraw text
// ctx.clearRect(0, rectY, canvasWidth, rectY + ROW_HEIGHT);
}
};
requestAnimationFrame(animateColor);
// Size text
if (size) {
ctx.fillStyle = textColor;
ctx.fillText(
MustBigNumber(size).toFormat(stepSizeDecimals ?? TOKEN_DECIMALS, formatOptions),
getXByColumn({ canvasWidth, colIdx: 0 }) - ROW_PADDING_RIGHT,
y
);
}
// Price text
if (price) {
ctx.fillStyle = textColor;
ctx.fillText(
MustBigNumber(price).toFormat(tickSizeDecimals ?? SMALL_USD_DECIMALS, formatOptions),
getXByColumn({ canvasWidth, colIdx: 1 }) - ROW_PADDING_RIGHT,
y
);
}
// Mine text
if (mine) {
ctx.fillStyle = Colors[theme].text2;
ctx.fillText(
MustBigNumber(mine).toFormat(stepSizeDecimals ?? TOKEN_DECIMALS, formatOptions),
getXByColumn({ canvasWidth, colIdx: 2 }) - ROW_PADDING_RIGHT,
y
);
}
},
[theme, LOCALE_DECIMAL_SEPARATOR, tickSizeDecimals, stepSizeDecimals]
);
/**
* Scale canvas using device pixel ratio to unblur drawn text
* @returns adjusted canvas width used in coordinates for drawing
**/
const canvasWidth = useMemo(() => {
const devicePixelRatio = window.devicePixelRatio || 1;
if (!canvas || !hoverCanvas) return 300 / devicePixelRatio;
const ctx = canvas.getContext('2d');
const hoverCtx = hoverCanvas.getContext('2d');
const backingStoreRatio =
// @ts-ignore
ctx.webkitBackingStorePixelRatio ||
// @ts-ignore
ctx.mozBackingStorePixelRatio ||
// @ts-ignore
ctx.msBackingStorePixelRatio ||
// @ts-ignore
ctx.oBackingStorePixelRatio ||
// @ts-ignore
ctx.backingStorePixelRatio ||
1;
const ratio = devicePixelRatio / backingStoreRatio;
canvas.width = canvas.offsetWidth * ratio;
canvas.height = canvas.offsetHeight * ratio;
hoverCanvas.width = hoverCanvas.offsetWidth * ratio;
hoverCanvas.height = hoverCanvas.offsetHeight * ratio;
if (hoverCtx) {
hoverCtx.scale(ratio, ratio);
}
if (ctx) {
ctx.scale(ratio, ratio);
ctx.font = `12.5px Satoshi`;
ctx.textAlign = 'right';
ctx.textBaseline = 'middle';
ctx.imageSmoothingQuality = 'high';
}
return canvas.width / ratio;
}, [canvas, hoverCanvas]);
//Handle Row Hover
const lastHoveredRowRef = useRef<number>();
const lastHoveredRow = lastHoveredRowRef.current;
useEffect(() => {
const hoverCtx = hoverCanvas?.getContext('2d');
if (!!!hoverCtx) return;
if (hoveredRow !== lastHoveredRow) {
const y = getYFromIndex(lastHoveredRow ?? 0, 'rect');
hoverCtx.clearRect(0, y, canvasWidth, ROW_HEIGHT);
lastHoveredRowRef.current = hoveredRow;
}
if (hoveredRow !== undefined) {
hoverCtx.fillStyle = 'rgba(255, 255, 255, 0.02)';
hoverCtx.fillRect(0, hoveredRow * 20, canvasWidth, 20);
}
}, [lastHoveredRow, hoveredRow]);
// Row Removal Animation state
const previousDataRef = useRef<{
[key: string]: number;
}>(Object.fromEntries(data.map((row: RowData) => [row.price, row.size])));
//Update histograms and row contents on data change
useEffect(() => {
const ctx = canvas?.getContext('2d');
if (!canvas || !ctx) return;
// Clear canvas before redraw
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
// Draw histograms
data.forEach(({ depth, mine, price, size, side }, idx) => {
const histogramAccentColor =
side === 'bid' ? `hsla(159, 67%, 39%, 0.15)` : `hsla(360, 73%, 61%, 0.15)`;
// Depth Bar
drawBars({
value: depth,
canvasWidth,
ctx,
gradientMultiplier: 1.3,
histogramAccentColor,
idx,
histogramSide,
});
// Size Bar
drawBars({
value: size,
canvasWidth,
ctx,
gradientMultiplier: 5,
histogramAccentColor,
idx,
histogramSide,
});
const isNew = !previousDataRef.current[price];
const wasRemoved = previousDataRef.current[price] && !data.find((row) => row.price === price);
// Size, Price, Mine
drawText({
ctx,
canvasWidth,
idx,
size,
price,
mine,
animationType: isNew ? 'add' : wasRemoved ? 'remove' : undefined,
});
});
previousDataRef.current = Object.fromEntries(data.map((row: RowData) => [row.price, row.size]));
}, [
canvasWidth,
data,
drawText,
histogramRange,
stepSizeDecimals,
tickSizeDecimals,
histogramSide,
]);
return { canvasRef, hoverCanvasRef };
};
@@ -0,0 +1,39 @@
import { type RefObject, useEffect, useState, Dispatch } from 'react';
export const useSpreadRowScrollListener = ({
orderbookRef,
spreadRowRef,
}: {
orderbookRef: RefObject<HTMLDivElement>;
spreadRowRef: RefObject<HTMLDivElement>;
}) => {
const [displaySide, setDisplaySide] = useState<string>();
useEffect(() => {
const onScroll = () => {
if (spreadRowRef.current && orderbookRef.current) {
const { clientHeight } = orderbookRef.current;
const parent = orderbookRef.current.getBoundingClientRect();
const spread = spreadRowRef.current.getBoundingClientRect();
const spreadTop = spread.top - parent.top;
const spreadBottom = spread.bottom - parent.top;
if (spreadBottom > clientHeight) {
setDisplaySide('bottom');
} else if (spreadTop < 0) {
setDisplaySide('top');
} else {
setDisplaySide(undefined);
}
}
};
orderbookRef.current?.addEventListener('scroll', onScroll, false);
return () => {
orderbookRef.current?.removeEventListener('scroll', onScroll, false);
};
}, [orderbookRef.current, spreadRowRef.current]);
return displaySide;
};
+11 -27
View File
@@ -1,12 +1,11 @@
import { useCallback, useEffect } from 'react';
import { useCallback } from 'react';
import { shallowEqual, useSelector } from 'react-redux';
import { useBalance, useBlockNumber } from 'wagmi';
import { useBalance } from 'wagmi';
import { StargateClient } from '@cosmjs/stargate';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useQuery } from 'react-query';
import { formatUnits } from 'viem';
import { ENVIRONMENT_CONFIG_MAP } from '@/constants/networks';
import { QueryKeys } from '@/constants/queries';
import { EvmAddress } from '@/constants/wallets';
import { convertBech32Address } from '@/lib/addressUtils';
@@ -53,27 +52,15 @@ export const useAccountBalance = ({
const evmChainId = Number(ENVIRONMENT_CONFIG_MAP[selectedNetwork].ethereumChainId);
const stakingBalances = useSelector(getStakingBalances, shallowEqual);
const queryClient = useQueryClient();
const { data: blockNumber } = useBlockNumber({ watch: true });
const {
data: evmQuery,
status: evmBalanceStatus,
fetchStatus: evmBalanceFetchStatus,
queryKey,
} = useBalance({
query: {
enabled: Boolean(!isCosmosChain && addressOrDenom?.startsWith('0x')),
},
const evmQuery = useBalance({
enabled: Boolean(!isCosmosChain && addressOrDenom?.startsWith('0x')),
address: evmAddress,
chainId: typeof chainId === 'number' ? chainId : Number(evmChainId),
token:
addressOrDenom === CHAIN_DEFAULT_TOKEN_ADDRESS ? undefined : (addressOrDenom as EvmAddress),
watch: true,
});
useEffect(() => {
queryClient.invalidateQueries({ queryKey });
}, [blockNumber]);
const cosmosQueryFn = useCallback(async () => {
if (dydxAddress && bech32AddrPrefix && rpc && addressOrDenom) {
const address = convertBech32Address({
@@ -91,7 +78,7 @@ export const useAccountBalance = ({
const cosmosQuery = useQuery({
enabled: Boolean(isCosmosChain && dydxAddress && bech32AddrPrefix && rpc && addressOrDenom),
queryKey: [QueryKeys.ACCOUNT_BALANCE, chainId, addressOrDenom],
queryKey: `accountBalances_${chainId}_${addressOrDenom}`,
queryFn: cosmosQueryFn,
refetchOnWindowFocus: false,
refetchOnMount: false,
@@ -100,11 +87,8 @@ export const useAccountBalance = ({
staleTime: 10_000,
});
const balance = isCosmosChain
? cosmosQuery.data
: evmQuery
? formatUnits(evmQuery?.value, evmQuery?.decimals)
: undefined;
const { formatted: evmBalance } = evmQuery.data || {};
const balance = isCosmosChain ? cosmosQuery.data : evmBalance;
const nativeTokenCoinBalance = balances?.[chainTokenDenom];
const nativeTokenBalance = MustBigNumber(nativeTokenCoinBalance?.amount);
@@ -120,7 +104,7 @@ export const useAccountBalance = ({
nativeTokenBalance,
nativeStakingBalance,
usdcBalance,
queryStatus: isCosmosChain ? cosmosQuery.status : evmBalanceStatus,
isQueryFetching: isCosmosChain ? cosmosQuery.isFetching : evmBalanceFetchStatus === 'fetching',
queryStatus: isCosmosChain ? cosmosQuery.status : evmQuery.status,
isQueryFetching: isCosmosChain ? cosmosQuery.isFetching : evmQuery.fetchStatus === 'fetching',
};
};
+3
View File
@@ -39,6 +39,7 @@ const useAccountsContext = () => {
walletConnectionType,
selectWalletType,
selectedWalletType,
selectedWalletError,
evmAddress,
signerWagmi,
publicClientWagmi,
@@ -299,7 +300,9 @@ const useAccountsContext = () => {
walletConnectionType,
// Wallet selection
selectWalletType,
selectedWalletType,
selectedWalletError,
// Wallet connection (EVM)
evmAddress,
+13 -24
View File
@@ -1,9 +1,8 @@
import { createContext, useContext, useCallback, useEffect, useMemo } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useQuery } from 'react-query';
import { LOCAL_STORAGE_VERSIONS, LocalStorageKey } from '@/constants/localStorage';
import { type TransferNotifcation } from '@/constants/notifications';
import { QueryKeys } from '@/constants/queries';
import { useAccounts } from '@/hooks/useAccounts';
import { fetchSquidStatus, STATUS_ERROR_GRACE_PERIOD } from '@/lib/squid';
@@ -69,8 +68,8 @@ const useLocalNotificationsContext = () => {
[transferNotifications]
);
const { data: newTransferNotifications } = useQuery({
queryKey: [QueryKeys.TRANSACTION_STATUS],
useQuery({
queryKey: 'getTransactionStatus',
queryFn: async () => {
const processTransferNotifications = async (transferNotifications: TransferNotifcation[]) => {
const newTransferNotifications = await Promise.all(
@@ -85,11 +84,10 @@ const useLocalNotificationsContext = () => {
status: currentStatus,
} = transferNotification;
const hasErrors =
// @ts-ignore status.errors is not in the type definition but can be returned
// also error can some time come back as an empty object so we need to ignore for that
!!currentStatus?.errors ||
(currentStatus?.error && Object.keys(currentStatus.error).length !== 0);
// @ts-ignore status.errors is not in the type definition but can be returned
// also error can some time come back as an empty object so we need to ignore for that
const hasErrors = !!currentStatus?.errors ||
(currentStatus?.error && Object.keys(currentStatus.error).length !== 0);
if (
!hasErrors &&
@@ -97,14 +95,11 @@ const useLocalNotificationsContext = () => {
currentStatus?.squidTransactionStatus === 'ongoing')
) {
try {
const status = await fetchSquidStatus(
{
transactionId: txHash,
toChainId,
fromChainId,
},
isCctp
);
const status = await fetchSquidStatus({
transactionId: txHash,
toChainId,
fromChainId,
}, isCctp);
if (status) {
transferNotification.status = status;
@@ -126,18 +121,12 @@ const useLocalNotificationsContext = () => {
return newTransferNotifications;
};
const newTransferNotifications = await processTransferNotifications(transferNotifications);
return newTransferNotifications;
setTransferNotifications(newTransferNotifications);
},
refetchInterval: TRANSFER_STATUS_FETCH_INTERVAL,
});
useEffect(() => {
if (!newTransferNotifications) return;
setTransferNotifications(newTransferNotifications);
}, [newTransferNotifications]);
return {
transferNotifications,
addTransferNotification,
+6 -13
View File
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useMemo } from 'react';
import { UseSwitchChainReturnType, useAccount, useSwitchChain } from 'wagmi';
import { useNetwork, useSwitchNetwork } from 'wagmi';
export const useMatchingEvmNetwork = ({
chainId,
@@ -8,10 +8,10 @@ export const useMatchingEvmNetwork = ({
}: {
chainId?: string | number;
switchAutomatically?: boolean;
onError?: Parameters<UseSwitchChainReturnType['switchChainAsync']>[1]['onError'];
onError?: (error: Error) => void;
}) => {
const { chain } = useAccount();
const { switchChainAsync, isPending } = useSwitchChain();
const { chain } = useNetwork();
const { isLoading, switchNetworkAsync } = useSwitchNetwork({ onError });
// If chainId is not a number, we can assume it is a non EVM compatible chain
const isMatchingNetwork = useMemo(
@@ -21,14 +21,7 @@ export const useMatchingEvmNetwork = ({
const matchNetwork = useCallback(async () => {
if (!isMatchingNetwork) {
await switchChainAsync?.(
{
chainId: Number(chainId),
},
{
onError,
}
);
await switchNetworkAsync?.(Number(chainId));
}
}, [chainId, chain]);
@@ -41,6 +34,6 @@ export const useMatchingEvmNetwork = ({
return {
isMatchingNetwork,
matchNetwork,
isSwitchingNetwork: isPending,
isSwitchingNetwork: isLoading,
};
};
+10 -14
View File
@@ -104,13 +104,12 @@ export const useWalletConnection = () => {
[walletConnectConfig, walletType, walletConnectionType]
);
const { connectAsync: connectWagmi } = useConnectWagmi();
const { connectAsync: connectWagmi } = useConnectWagmi({ connector: wagmiConnector })
const { suggestAndConnect: connectGraz } = useConnectGraz();
const connectWallet = useCallback(
async ({ walletType }: { walletType: WalletType }) => {
const walletConnection = getWalletConnection({ walletType });
console.log({ walletConnection });
try {
if (!walletConnection) {
@@ -134,17 +133,13 @@ export const useWalletConnection = () => {
}
} else {
if (!isConnectedWagmi) {
const connector = resolveWagmiConnector({
walletType,
walletConnection,
walletConnectConfig,
await connectWagmi({
connector: resolveWagmiConnector({
walletType,
walletConnection,
walletConnectConfig,
}),
});
if (connector) {
await connectWagmi({
connector,
});
}
}
}
} catch (error) {
@@ -161,7 +156,7 @@ export const useWalletConnection = () => {
walletConnectionType: walletConnection.type,
};
},
[isConnectedGraz, signerGraz, isConnectedWagmi, signerWagmi, walletConnectConfig]
[isConnectedGraz, signerGraz, isConnectedWagmi, signerWagmi]
);
const disconnectWallet = useCallback(async () => {
@@ -209,9 +204,10 @@ export const useWalletConnection = () => {
})();
}, [selectedWalletType, signerWagmi, signerGraz]);
const selectWalletType = (walletType: WalletType | undefined) => {
const selectWalletType = async (walletType: WalletType | undefined) => {
if (selectedWalletType) {
setSelectedWalletType(undefined);
await new Promise(requestAnimationFrame);
}
setSelectedWalletType(walletType);
+118 -112
View File
@@ -1,6 +1,7 @@
import { createConfig, createConnector, http, usePublicClient } from 'wagmi';
import { createConfig, configureChains, mainnet, Chain, Connector, usePublicClient } from 'wagmi';
import { goerli } from 'wagmi/chains';
import {
type Chain,
arbitrum,
arbitrumGoerli,
avalanche,
@@ -25,33 +26,34 @@ import {
fantomTestnet,
celo,
celoAlfajores,
mainnet,
goerli,
sepolia,
} from 'wagmi/chains';
} from 'viem/chains';
import { coinbaseWallet, injected, metaMask, walletConnect } from 'wagmi/connectors';
import type { ExternalProvider } from '@ethersproject/providers';
import { alchemyProvider } from 'wagmi/providers/alchemy';
import { jsonRpcProvider } from 'wagmi/providers/jsonRpc';
import { publicProvider } from 'wagmi/providers/public';
import { CoinbaseWalletConnector } from 'wagmi/connectors/coinbaseWallet';
import { InjectedConnector } from 'wagmi/connectors/injected';
import { MetaMaskConnector } from 'wagmi/connectors/metaMask';
import { WalletConnectConnector } from 'wagmi/connectors/walletConnect';
import {
type WalletConnectConfig,
type WalletConnection,
WalletConnectionType,
WalletType,
WALLET_CONNECTION_TYPES,
type WalletType,
walletConnectionTypes,
wallets,
WALLET_CONNECT_EXPLORER_RECOMMENDED_IDS,
WalletConfig,
} from '@/constants/wallets';
import { isTruthy } from './isTruthy';
import { log } from './telemetry';
// Config
const WAGMI_SUPPORTED_CHAINS: Parameters<typeof createConfig>[0]['chains'] = [
export const WAGMI_SUPPORTED_CHAINS: Chain[] = [
mainnet,
goerli,
sepolia,
arbitrum,
arbitrumGoerli,
avalanche,
@@ -78,104 +80,118 @@ const WAGMI_SUPPORTED_CHAINS: Parameters<typeof createConfig>[0]['chains'] = [
celoAlfajores,
];
export const config = createConfig({
chains: WAGMI_SUPPORTED_CHAINS,
transports: Object.fromEntries(
Object.values(WAGMI_SUPPORTED_CHAINS).map(({ id }) => [id, http()])
),
});
const { chains, publicClient, webSocketPublicClient } = configureChains(
WAGMI_SUPPORTED_CHAINS,
[
import.meta.env.VITE_ALCHEMY_API_KEY &&
alchemyProvider({ apiKey: import.meta.env.VITE_ALCHEMY_API_KEY }),
jsonRpcProvider({
rpc: (chain) => ({ http: chain.rpcUrls.default.http[0] }),
}),
publicProvider(),
].filter(isTruthy)
);
const createdInjectedConnectorWithProvider = ({ provider }: { provider: ExternalProvider }) => {
console.log(provider);
return injected({
target() {
return {
id: 'windowProvider',
name: 'Injected',
provider,
};
},
const injectedConnectorOptions = {
chains,
options: {
name: 'Injected',
shimDisconnect: true,
});
shimChainChangedDisconnect: false,
},
};
const getConnector = ({
walletConnectionType,
walletConnectConfig,
}: {
walletConnectionType: WalletConnectionType;
walletConnectConfig: WalletConnectConfig;
}) => {
console.log(walletConnectionType);
switch (walletConnectionType) {
case WalletConnectionType.WalletConnect2:
return [
walletConnect(
getConnectorInfoForWc2({
walletConnectConfig,
})
),
];
case WalletConnectionType.CoinbaseWalletSdk:
return [
coinbaseWallet({
appName: 'dYdX',
appLogoUrl: walletConnectConfig.client.iconUrl,
reloadOnDisconnect: false,
darkMode: true,
}),
];
case WalletConnectionType.InjectedEip1193:
return injected({
target() {
return {
id: 'windowProvider',
name: 'Injected',
provider: window.ethereum,
};
},
shimDisconnect: true,
});
case WalletConnectionType.CosmosSigner:
default: {
return undefined;
}
}
type WalletConnectConfig = {
client: {
name: string;
description: string;
iconUrl: string;
};
v2: {
projectId: string;
};
};
const getConnectorInfoForWc2 = ({
walletConnectId,
walletConnectConfig,
}: {
walletConnectId?: string;
walletConnectConfig: WalletConnectConfig;
}) => {
const explorerRecommendedWalletIds = walletConnectId
? [walletConnectId]
: WALLET_CONNECT_EXPLORER_RECOMMENDED_IDS;
return {
projectId: walletConnectConfig.v2.projectId,
const getWalletconnect2ConnectorOptions = (
config: WalletConnectConfig
): ConstructorParameters<typeof WalletConnectConnector>[0] => ({
chains,
options: {
projectId: config.v2.projectId,
metadata: {
name: walletConnectConfig.client.name,
description: walletConnectConfig.client.description,
name: config.client.name,
description: config.client.description,
url: import.meta.env.VITE_BASE_URL,
icons: [walletConnectConfig.client.iconUrl],
icons: [config.client.iconUrl],
},
showQrModal: true,
qrModalOptions: {
themeMode: 'dark' as const,
themeVariables: {
'--wcm-accent-color': 'var(--color-accent)',
'--wcm-accent-color': '#5973fe',
'--wcm-font-family': 'var(--fontFamily-base)',
'--wcm-background-color': 'var(--color-accent)',
},
explorerRecommendedWalletIds,
explorerRecommendedWalletIds: WALLET_CONNECT_EXPLORER_RECOMMENDED_IDS,
},
};
},
});
const getConnectors = (walletConnectConfig: WalletConnectConfig) => [
new MetaMaskConnector({
chains,
options: {
shimDisconnect: true,
},
}),
new CoinbaseWalletConnector({
chains,
options: {
appName: 'dYdX',
reloadOnDisconnect: false,
},
}),
new WalletConnectConnector(getWalletconnect2ConnectorOptions(walletConnectConfig)),
new InjectedConnector(injectedConnectorOptions),
];
export const config = createConfig({
autoConnect: true,
// connectors,
publicClient,
webSocketPublicClient,
});
// Custom connectors
import type { ExternalProvider } from '@ethersproject/providers';
// Create a custom wagmi InjectedConnector using a specific injected EIP-1193 provider (instead of wagmi's default detection logic)
const createInjectedConnectorWithProvider = (provider: ExternalProvider) =>
new (class extends InjectedConnector {
getProvider = async () =>
provider as unknown as Awaited<ReturnType<InjectedConnector['getProvider']>>;
})(injectedConnectorOptions) as InjectedConnector;
const createWalletConnect2ConnectorWithId = (
walletconnectId: string,
walletConnectConfig: WalletConnectConfig
) => {
const walletconnect2ConnectorOptions = getWalletconnect2ConnectorOptions(walletConnectConfig);
return new WalletConnectConnector({
...walletconnect2ConnectorOptions,
options: {
...walletconnect2ConnectorOptions.options,
qrModalOptions: {
...walletconnect2ConnectorOptions.options.qrModalOptions,
explorerRecommendedWalletIds: [walletconnectId],
explorerExcludedWalletIds: 'ALL',
},
},
});
};
// Custom connector from wallet selection
export const resolveWagmiConnector = ({
walletType,
walletConnection,
@@ -186,23 +202,13 @@ export const resolveWagmiConnector = ({
walletConnectConfig: WalletConnectConfig;
}) => {
const walletConfig = wallets[walletType];
const walletConnectionConfig = walletConnectionTypes[walletConnection.type];
if (walletConnection.type === WalletConnectionType.InjectedEip1193 && walletConnection.provider) {
if (walletType === WalletType.MetaMask) {
return metaMask();
}
return createdInjectedConnectorWithProvider({ provider: walletConnection.provider });
} else if (
walletConnection.type === WalletConnectionType.WalletConnect2 &&
walletConfig.walletconnect2Id
) {
return walletConnect(
getConnectorInfoForWc2({
walletConnectId: walletConfig.walletconnect2Id,
walletConnectConfig,
})
);
} else {
return getConnector({ walletConnectionType: walletConnection.type, walletConnectConfig });
}
return walletConnection.type === WalletConnectionType.InjectedEip1193 && walletConnection.provider
? createInjectedConnectorWithProvider(walletConnection.provider)
: walletConnection.type === WalletConnectionType.WalletConnect2 && walletConfig.walletconnect2Id
? createWalletConnect2ConnectorWithId(walletConfig.walletconnect2Id, walletConnectConfig)
: getConnectors(walletConnectConfig).find(
({ id }: { id: string }) => id === walletConnectionConfig.wagmiConnectorId
);
};
+8 -16
View File
@@ -1,12 +1,11 @@
import { useEffect } from 'react';
import { useDispatch } from 'react-redux';
import { useQuery } from '@tanstack/react-query';
import { useQuery } from 'react-query';
import styled, { AnyStyledComponent } from 'styled-components';
import { STRING_KEYS } from '@/constants/localization';
import { ButtonAction } from '@/constants/buttons';
import { DialogTypes } from '@/constants/dialogs';
import { QueryKeys } from '@/constants/queries';
import breakpoints from '@/styles/breakpoints';
import { useAccounts, useBreakpoints, useStringGetter } from '@/hooks';
@@ -25,8 +24,6 @@ import { openDialog } from '@/state/dialogs';
import { log } from '@/lib/telemetry';
const SEASON_NUMBER = 2;
export const LaunchIncentivesPanel = () => {
const { isNotTablet } = useBreakpoints();
const dispatch = useDispatch();
@@ -69,24 +66,17 @@ const EstimatedRewards = () => {
const stringGetter = useStringGetter();
const { dydxAddress } = useAccounts();
const { data, isLoading, status, error } = useQuery({
const { data, isLoading } = useQuery({
enabled: !!dydxAddress,
queryKey: [QueryKeys.LAUNCH_INCENTIVES, dydxAddress, SEASON_NUMBER],
queryKey: `launch_incentives_rewards_${dydxAddress ?? ''}`,
queryFn: async () => {
if (!dydxAddress) return undefined;
const resp = await fetch(
`https://cloud.chaoslabs.co/query/api/dydx/points/${dydxAddress}?n=${SEASON_NUMBER}`
);
const resp = await fetch(`https://cloud.chaoslabs.co/query/api/dydx/points/${dydxAddress}`);
return (await resp.json())?.incentivePoints;
},
onError: (error: Error) => log('LaunchIncentives/fetchPoints', error),
});
useEffect(() => {
if (status === 'error') {
log('LaunchIncentives/fetchPoints', error);
}
}, [status]);
return (
<Styled.EstimatedRewardsCard>
<Styled.EstimatedRewardsCardContent>
@@ -95,7 +85,9 @@ const EstimatedRewards = () => {
<Styled.Season>
{stringGetter({
key: STRING_KEYS.LAUNCH_INCENTIVES_SEASON_NUM,
params: { SEASON_NUMBER },
params: {
SEASON_NUMBER: 1,
},
})}
</Styled.Season>
</div>
+4 -35
View File
@@ -1,6 +1,4 @@
import { useEffect, useState } from 'react';
import { useSelector } from 'react-redux';
import styled, { AnyStyledComponent } from 'styled-components';
import { useState } from 'react';
import { TradeLayouts } from '@/constants/layout';
import { STRING_KEYS } from '@/constants/localization';
@@ -9,11 +7,9 @@ import { useStringGetter } from '@/hooks';
import { Tabs } from '@/components/Tabs';
import { Orderbook, orderbookMixins, OrderbookScrollBehavior } from '@/views/tables/Orderbook';
import { Orderbook } from '@/views/Orderbook';
import { LiveTrades } from '@/views/tables/LiveTrades';
import { getCurrentMarketId } from '@/state/perpetualsSelectors';
enum Tab {
Orderbook = 'Orderbook',
Trades = 'Trades',
@@ -27,22 +23,13 @@ const HISTOGRAM_SIDES_BY_LAYOUT = {
export const VerticalPanel = ({ tradeLayout }: { tradeLayout: TradeLayouts }) => {
const stringGetter = useStringGetter();
const [value, setValue] = useState(Tab.Orderbook);
const [scrollBehavior, setScrollBehavior] = useState<OrderbookScrollBehavior>('snapToCenter');
const marketId = useSelector(getCurrentMarketId);
useEffect(() => {
setScrollBehavior('snapToCenter');
}, [marketId]);
return (
<Styled.Tabs
<Tabs
fullWidthTabs
value={value}
onValueChange={(value: Tab) => {
setScrollBehavior('snapToCenter');
setValue(value);
}}
items={[
@@ -50,6 +37,7 @@ export const VerticalPanel = ({ tradeLayout }: { tradeLayout: TradeLayouts }) =>
content: <Orderbook histogramSide={HISTOGRAM_SIDES_BY_LAYOUT[tradeLayout]} />,
label: stringGetter({ key: STRING_KEYS.ORDERBOOK_SHORT }),
value: Tab.Orderbook,
asChild: true,
},
{
content: <LiveTrades histogramSide={HISTOGRAM_SIDES_BY_LAYOUT[tradeLayout]} />,
@@ -57,26 +45,7 @@ export const VerticalPanel = ({ tradeLayout }: { tradeLayout: TradeLayouts }) =>
value: Tab.Trades,
},
]}
onWheel={() => setScrollBehavior('free')}
withTransitions={false}
isShowingOrderbook={value === Tab.Orderbook}
scrollBehavior={scrollBehavior}
// style={{
// scrollSnapType: {
// 'snapToCenter': 'y mandatory',
// 'free': 'none',
// 'snapToCenterUnlessHovered': 'none',
// }[scrollBehavior],
// }}
/>
);
};
const Styled: Record<string, AnyStyledComponent> = {};
Styled.Tabs = styled(Tabs)<{
isShowingOrderbook: boolean;
scrollBehavior: OrderbookScrollBehavior;
}>`
${orderbookMixins.scrollArea}
`;
+2 -2
View File
@@ -114,8 +114,8 @@ export const MarketDetails: React.FC = () => {
),
},
{
key: 'initial-margin-fraction',
label: stringGetter({ key: STRING_KEYS.INITIAL_MARGIN_FRACTION }),
key: 'base-initial-margin-fraction',
label: stringGetter({ key: STRING_KEYS.BASE_INITIAL_MARGIN_FRACTION }),
tooltip: 'initial-margin-fraction',
value: <Output useGrouping value={initialMarginFraction} type={OutputType.SmallPercent} />,
},
+317
View File
@@ -0,0 +1,317 @@
import { useCallback, useMemo, useRef, useState } from 'react';
import { shallowEqual, useDispatch, useSelector } from 'react-redux';
import styled, { css } from 'styled-components';
import { Nullable } from '@/constants/abacus';
import { STRING_KEYS } from '@/constants/localization';
import { useBreakpoints, useStringGetter } from '@/hooks';
import {
useCalculateOrderbookData,
useCenterOrderbook,
useDrawOrderbook,
useSpreadRowScrollListener,
} from '@/hooks/orderbook';
import { calculateCanViewAccount } from '@/state/accountCalculators';
import { getCurrentMarketAssetData } from '@/state/assetsSelectors';
import { getCurrentMarketConfig } from '@/state/perpetualsSelectors';
import { setTradeFormInputs } from '@/state/inputs';
import { getCurrentInput } from '@/state/inputsSelectors';
import { Canvas } from '@/components/Canvas';
import { LoadingSpace } from '@/components/Loading/LoadingSpinner';
import { Tag } from '@/components/Tag';
import { ROW_HEIGHT, Row, type RowData } from './Orderbook/OrderbookRow';
import { SpreadRow } from './Orderbook/SpreadRow';
import { Output, OutputType } from '@/components/Output';
const ORDERBOOK_MAX_ROWS_PER_SIDE = 35;
type ElementProps = {
maxRowsPerSide?: number;
layout?: 'vertical' | 'horizontal';
};
type StyleProps = {
hideHeader?: boolean;
histogramSide?: 'left' | 'right';
className?: string;
};
const getEmptyRow = (side: 'bid' | 'ask') => ({
side,
size: undefined,
price: undefined,
offset: 0,
depth: undefined,
});
export const Orderbook = ({
histogramSide,
maxRowsPerSide = ORDERBOOK_MAX_ROWS_PER_SIDE,
}: ElementProps & StyleProps) => {
const dispatch = useDispatch();
const stringGetter = useStringGetter();
const { isTablet } = useBreakpoints();
const showMineColumn = useSelector(calculateCanViewAccount) && !isTablet;
const currentInput = useSelector(getCurrentInput);
const { id = '' } = useSelector(getCurrentMarketAssetData, shallowEqual) ?? {};
const { stepSizeDecimals, tickSizeDecimals } =
useSelector(getCurrentMarketConfig, shallowEqual) ?? {};
const { asks, bids, spread, spreadPercent, histogramRange, hasOrderbook } =
useCalculateOrderbookData({
maxRowsPerSide,
});
const { askLevels, asksSlice, bidLevels, bidsSlice, numRows } = useMemo(() => {
const bidsSlice = bids.slice(0, maxRowsPerSide).reverse();
const asksSlice = asks.slice(0, maxRowsPerSide);
const numRows = maxRowsPerSide; // Math.max(bidsSlice.length, asksSlice.length);
if (asksSlice.length < numRows) {
const emptyRows = new Array(numRows - asksSlice.length).fill(getEmptyRow('ask'));
asksSlice.push(...emptyRows);
}
if (bidsSlice.length < numRows) {
const emptyRows = new Array(numRows - bidsSlice.length).fill(getEmptyRow('bid'));
bidsSlice.unshift(...emptyRows);
}
const askLevels = new Set(asksSlice.map(({ price }: { price: number }) => price));
const bidLevels = new Set(bidsSlice.map(({ price }: { price: number }) => price));
return { askLevels, asksSlice, bidLevels, bidsSlice, numRows };
}, [asks, bids]);
const orderbookRef = useRef<HTMLDivElement>(null);
useCenterOrderbook({ orderbookRef, marketId: id });
/**
* Display top or bottom spreadRow when center spreadRow is off screen
*/
const spreadRowRef = useRef<HTMLDivElement>(null);
const displaySide = useSpreadRowScrollListener({
orderbookRef,
spreadRowRef,
});
/**
* Row action and hover
*/
const onRowAction = useCallback(
(price: Nullable<number>) => {
if (currentInput === 'trade' && price) {
dispatch(setTradeFormInputs({ limitPriceInput: price?.toString() }));
}
},
[currentInput]
);
const [hoveredRow, setHoveredRow] = useState<{
idx: number;
side: 'bid' | 'ask';
}>();
const { canvasRef: asksCanvasRef, hoverCanvasRef: asksHoverRef } = useDrawOrderbook({
data: asksSlice.reverse(),
histogramRange,
stepSizeDecimals,
tickSizeDecimals,
hoveredRow: hoveredRow?.side === 'ask' ? hoveredRow.idx : undefined,
histogramSide,
});
const { canvasRef: bidsCanvasRef, hoverCanvasRef: bidsHoverRef } = useDrawOrderbook({
data: bidsSlice.reverse(),
histogramRange,
stepSizeDecimals,
tickSizeDecimals,
hoveredRow: hoveredRow?.side === 'bid' ? hoveredRow.idx : undefined,
histogramSide,
});
return (
<$OrderbookContainer>
<$OrderbookContent isLoading={!hasOrderbook}>
<$Header>
<span>
{stringGetter({ key: STRING_KEYS.SIZE })} {id && <Tag>{id}</Tag>}
</span>
<span>
{stringGetter({ key: STRING_KEYS.PRICE })} <Tag>USD</Tag>
</span>
<span>{showMineColumn && stringGetter({ key: STRING_KEYS.MINE })}</span>
</$Header>
{displaySide === 'top' && (
<$SpreadRow
side="top"
spread={spread}
spreadPercent={spreadPercent}
tickSizeDecimals={tickSizeDecimals}
/>
)}
<$OrderbookWrapper ref={orderbookRef}>
{!hasOrderbook ? (
<LoadingSpace id="orderbook" />
) : (
<>
<$OrderbookSideContainer
numRows={numRows}
side="ask"
onMouseLeave={() => setHoveredRow(undefined)}
>
<$OrderbookCanvas ref={asksCanvasRef} width="100%" height={numRows * ROW_HEIGHT} />
<$HoverCanvas ref={asksHoverRef} width="100%" height={numRows * ROW_HEIGHT} />
<$HoverRows>
{asksSlice.map((row: RowData, idx) =>
row.price ? (
<$Row
key={idx}
title={`${row.price}`}
onClick={() => onRowAction(row.price)}
onMouseOver={(e) => setHoveredRow({ idx, side: 'ask' })}
>
<span></span>
<span></span>
<span>
<Output
type={OutputType.Fiat}
value={row.price}
fractionDigits={tickSizeDecimals}
/>
</span>
</$Row>
) : (
<$Row key={idx} onMouseOver={(e) => setHoveredRow(undefined)} />
)
)}
</$HoverRows>
</$OrderbookSideContainer>
<SpreadRow
ref={spreadRowRef}
spread={spread}
spreadPercent={spreadPercent}
tickSizeDecimals={tickSizeDecimals}
/>
<$OrderbookSideContainer
numRows={numRows}
side="bid"
onMouseLeave={() => setHoveredRow(undefined)}
>
<$OrderbookCanvas ref={bidsCanvasRef} width="100%" height={numRows * ROW_HEIGHT} />
<$HoverCanvas ref={bidsHoverRef} width="100%" height={numRows * ROW_HEIGHT} />
<$HoverRows>
{bidsSlice.map((row: RowData, idx) =>
row.price ? (
<$Row
key={idx}
title={`${row.price}`}
onClick={() => onRowAction(row.price)}
onMouseOver={(e) => setHoveredRow({ idx, side: 'bid' })}
>
<span></span>
<span></span>
<span>
<Output
type={OutputType.Fiat}
value={row.price}
fractionDigits={tickSizeDecimals}
/>
</span>
</$Row>
) : (
<$Row key={idx} onMouseOver={(e) => setHoveredRow(undefined)} />
)
)}
</$HoverRows>
</$OrderbookSideContainer>
</>
)}
</$OrderbookWrapper>
{displaySide === 'bottom' && (
<$SpreadRow
side="bottom"
spread={spread}
spreadPercent={spreadPercent}
tickSizeDecimals={tickSizeDecimals}
/>
)}
</$OrderbookContent>
</$OrderbookContainer>
);
};
const $OrderbookContainer = styled.div`
display: flex;
flex: 1 1 0%;
flex-direction: column;
overflow: hidden;
`;
const $OrderbookContent = styled.div<{ isLoading?: boolean }>`
max-height: 100%;
display: flex;
flex-direction: column;
position: relative;
${({ isLoading }) => isLoading && 'flex: 1;'}
`;
const $Header = styled(Row)`
height: 2rem;
border-bottom: 1px solid var(--color-border);
color: var(--color-text-0);
`;
const $OrderbookWrapper = styled.div`
overflow-y: auto;
display: flex;
flex-direction: column;
flex: 1 1 0%;
`;
const $OrderbookSideContainer = styled.div<{ numRows: number; side: 'bid' | 'ask' }>`
${({ numRows }) => css`
min-height: calc(${numRows} * 1.25rem);
`}
${({ side }) => css`
--accent-color: ${side === 'bid' ? 'var(--color-positive)' : 'var(--color-negative)'};
`}
position: relative;
`;
const $OrderbookCanvas = styled(Canvas)`
width: 100%;
height: 100%;
position: absolute;
top: 0;
right: 0;
font-feature-settings: var(--fontFeature-monoNumbers);
`;
const $HoverCanvas = styled($OrderbookCanvas)``;
const $HoverRows = styled.div`
position: absolute;
width: 100%;
`;
const $Row = styled(Row)<{ onClick?: () => void }>`
${({ onClick }) => (onClick ? 'cursor: pointer;' : 'cursor: default;')}
`;
const $SpreadRow = styled(SpreadRow)`
position: absolute;
`;
+26
View File
@@ -0,0 +1,26 @@
import styled from 'styled-components';
import { OrderbookLine } from '@/constants/abacus';
export type RowData = OrderbookLine & { side: 'bid' | 'ask'; mine?: number };
export const ROW_HEIGHT = 20;
export const ROW_PADDING_RIGHT = 8;
export const Row = styled.div`
display: flex;
flex-shrink: 0;
align-items: center;
height: ${ROW_HEIGHT}px;
min-height: ${ROW_HEIGHT}px;
font: var(--font-mini-book);
position: relative;
padding-right: 0.5rem;
> span {
flex: 1 1 0%;
text-align: right;
padding-bottom: 2px;
}
`;
+61
View File
@@ -0,0 +1,61 @@
import { forwardRef } from 'react';
import styled, { css } from 'styled-components';
import BigNumber from 'bignumber.js';
import type { Nullable } from '@/constants/abacus';
import { STRING_KEYS } from '@/constants/localization';
import { useStringGetter } from '@/hooks';
import { Output, OutputType } from '@/components/Output';
import { WithTooltip } from '@/components/WithTooltip';
import { Row } from './OrderbookRow';
type StyleProps = {
side?: 'top' | 'bottom';
};
type ElementProps = {
spread: BigNumber | null;
spreadPercent: Nullable<number>;
tickSizeDecimals: Nullable<number>;
};
export const SpreadRow = forwardRef<HTMLDivElement, StyleProps & ElementProps>(
({ side, spread, spreadPercent, tickSizeDecimals }, ref) => {
const stringGetter = useStringGetter();
return (
<$SpreadRow ref={ref} side={side}>
<span>
<WithTooltip tooltip="spread">
{stringGetter({ key: STRING_KEYS.ORDERBOOK_SPREAD })}
</WithTooltip>
</span>
<span>
<Output type={OutputType.Number} value={spread} fractionDigits={tickSizeDecimals} />
</span>
<span>
<Output type={OutputType.Percent} value={spreadPercent} />
</span>
</$SpreadRow>
);
}
);
const $SpreadRow = styled(Row)<{ side?: 'top' | 'bottom' }>`
height: 2rem;
border-top: 1px solid var(--color-border);
border-bottom: 1px solid var(--color-border);
${({ side }) =>
side &&
{
top: css`
border-top: none;
`,
bottom: css`
border-bottom: none;
`,
}[side]}
`;
@@ -3,18 +3,19 @@ import styled, { AnyStyledComponent } from 'styled-components';
import { useDispatch } from 'react-redux';
import { AlertType } from '@/constants/alerts';
import { ButtonAction, ButtonSize } from '@/constants/buttons';
import { STRING_KEYS } from '@/constants/localization';
import { WalletType, wallets } from '@/constants/wallets';
import { useStringGetter, useURLConfigs } from '@/hooks';
import { useDisplayedWallets } from '@/hooks/useDisplayedWallets';
import { useWalletConnection } from '@/hooks/useWalletConnection';
import { ButtonAction, ButtonSize } from '@/constants/buttons';
import { AlertMessage } from '@/components/AlertMessage';
import { Button } from '@/components/Button';
import { Icon } from '@/components/Icon';
import { Link } from '@/components/Link';
import { useAccounts, useStringGetter, useURLConfigs } from '@/hooks';
import { useDisplayedWallets } from '@/hooks/useDisplayedWallets';
import { breakpoints } from '@/styles';
import { layoutMixins } from '@/styles/layoutMixins';
@@ -24,7 +25,7 @@ export const ChooseWallet = () => {
const displayedWallets = useDisplayedWallets();
const { selectWalletType, selectedWalletType, selectedWalletError } = useWalletConnection();
const { selectWalletType, selectedWalletType, selectedWalletError } = useAccounts();
return (
<>
@@ -86,7 +86,13 @@ export const GenerateKeys = ({
].includes(status);
const signTypedData = getSignTypedData(selectedNetwork);
const { signTypedDataAsync } = useSignTypedData();
const { signTypedDataAsync } = useSignTypedData({
...signTypedData,
domain: {
...signTypedData.domain,
chainId,
},
});
const staticEncryptionKey = import.meta.env.VITE_PK_ENCRYPTION_KEY;
@@ -97,13 +103,7 @@ export const GenerateKeys = ({
// 1. First signature
setStatus(EvmDerivedAccountStatus.Deriving);
const signature = await signTypedDataAsync({
...signTypedData,
domain: {
...signTypedData.domain,
chainId,
},
});
const signature = await signTypedDataAsync();
const { wallet: dydxWallet } = await getWalletFromEvmSignature({ signature });
// 2. Ensure signature is deterministic
@@ -121,13 +121,7 @@ export const GenerateKeys = ({
setStatus(EvmDerivedAccountStatus.EnsuringDeterminism);
// Second signature
const additionalSignature = await signTypedDataAsync({
...signTypedData,
domain: {
...signTypedData.domain,
chainId,
},
});
const additionalSignature = await signTypedDataAsync();
if (signature !== additionalSignature) {
throw new Error(