Skip to content

Commit

Permalink
Merge branch 'master' of https://github.com/gmx-io/gmx-interface
Browse files Browse the repository at this point in the history
  • Loading branch information
actions-user committed Sep 16, 2024
2 parents 9de69eb + 4d559e1 commit 57cbcad
Show file tree
Hide file tree
Showing 21 changed files with 845 additions and 249 deletions.
918 changes: 751 additions & 167 deletions src/abis/SyntheticsReader.json

Large diffs are not rendered by default.

3 changes: 1 addition & 2 deletions src/config/ab.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import mapValues from "lodash/mapValues";
import { AB_FLAG_STORAGE_KEY } from "./localStorage";

type Flag = "testAdjustRpcBatching" | "testPrebuiltMarkets";
type Flag = "testPrebuiltMarkets";

type AbFlag = {
enabled: boolean;
Expand All @@ -12,7 +12,6 @@ type AbStorage = {
};

const abFlagsConfig: Record<Flag, number> = {
testAdjustRpcBatching: 0.5,
testPrebuiltMarkets: 0.5,
};

Expand Down
6 changes: 3 additions & 3 deletions src/config/contracts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ const CONTRACTS = {
WithdrawalVault: "0x0628D46b5D145f183AdB6Ef1f2c97eD1C4701C55",
OrderVault: "0x31eF83a530Fde1B38EE9A18093A333D8Bbbc40D5",
ShiftVault: "0xfe99609C4AA83ff6816b64563Bdffd7fa68753Ab",
SyntheticsReader: "0x5Ca84c34a381434786738735265b9f3FD814b824",
SyntheticsReader: "0x23D4Da5C7C6902D4C86d551CaE60d5755820df9E",
SyntheticsRouter: "0x7452c558d45f8afC8c83dAe62C3f8A5BE19c71f6",

GlvReader: "0xd4f522c4339Ae0A90a156bd716715547e44Bed65",
Expand Down Expand Up @@ -250,7 +250,7 @@ const CONTRACTS = {
WithdrawalVault: "0xf5F30B10141E1F63FC11eD772931A8294a591996",
OrderVault: "0xD3D60D22d415aD43b7e64b510D86A30f19B1B12C",
ShiftVault: "0x7fC46CCb386e9bbBFB49A2639002734C3Ec52b39",
SyntheticsReader: "0xBAD04dDcc5CC284A86493aFA75D2BEb970C72216",
SyntheticsReader: "0x95861eecD91Cb30220598DdA68268E7c1F1A1386",
SyntheticsRouter: "0x820F5FfC5b525cD4d88Cd91aCf2c28F16530Cc68",

Multicall: "0xcA11bde05977b3631167028862bE2a173976CA11",
Expand Down Expand Up @@ -306,7 +306,7 @@ const CONTRACTS = {
WithdrawalVault: "0x74d49B6A630Bf519bDb6E4efc4354C420418A6A2",
OrderVault: "0x25D23e8E655727F2687CC808BB9589525A6F599B",
ShiftVault: "0x257D0EA0B040E2Cd1D456fB4C66d7814102aD346",
SyntheticsReader: "0xD52216D3A57F7eb1126498f00A4771553c737AE4",
SyntheticsReader: "0x538cFa1D253863e7550E444a388B12F511Ac4f50",
SyntheticsRouter: "0x5e7d61e4C52123ADF651961e4833aCc349b61491",
Timelock: ZeroAddress,

Expand Down
5 changes: 0 additions & 5 deletions src/config/dataStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,6 @@ export const ESTIMATED_GAS_FEE_PER_ORACLE_PRICE = hashString("ESTIMATED_GAS_FEE_
export const ESTIMATED_GAS_FEE_MULTIPLIER_FACTOR = hashString("ESTIMATED_GAS_FEE_MULTIPLIER_FACTOR");
export const MARKET_LIST_KEY = hashString("MARKET_LIST");
export const POSITION_LIST_KEY = hashString("POSITION_LIST");
export const ACCOUNT_POSITION_LIST_KEY = hashString("ACCOUNT_POSITION_LIST");
export const ORDER_LIST_KEY = hashString("ORDER_LIST");
export const ACCOUNT_ORDER_LIST_KEY = hashString("ACCOUNT_ORDER_LIST");
export const CLAIMABLE_FUNDING_AMOUNT = hashString("CLAIMABLE_FUNDING_AMOUNT");
Expand Down Expand Up @@ -274,10 +273,6 @@ export function accountOrderListKey(account: string) {
return hashData(["bytes32", "address"], [ACCOUNT_ORDER_LIST_KEY, account]);
}

export function accountPositionListKey(account: string) {
return hashData(["bytes32", "address"], [ACCOUNT_POSITION_LIST_KEY, account]);
}

export function minCollateralFactorKey(market: string) {
return hashData(["bytes32", "address"], [MIN_COLLATERAL_FACTOR_KEY, market]);
}
Expand Down
66 changes: 17 additions & 49 deletions src/domain/synthetics/positions/usePositions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { ethers } from "ethers";
import { useMemo } from "react";

import { getContract } from "config/contracts";
import { accountPositionListKey, hashedPositionKey } from "config/dataStore";
import { hashedPositionKey } from "config/dataStore";
import {
PendingPositionUpdate,
PositionDecreaseEvent,
Expand All @@ -18,7 +18,6 @@ import { TokensData } from "../tokens";
import { Position, PositionsData } from "./types";
import { getPositionKey, parsePositionKey } from "./utils";

import DataStore from "abis/DataStore.json";
import SyntheticsReader from "abis/SyntheticsReader.json";

const MAX_PENDING_UPDATE_AGE = 600 * 1000; // 10 minutes
Expand All @@ -39,43 +38,14 @@ export function usePositions(
): PositionsResult {
const { marketsInfoData, tokensData, account } = p;

const { data: existingPositionsKeysSet, error: existingPositionsKeysError } = useMulticall(
chainId,
"usePositions-keys",
{
key: account ? [account] : null,

refreshInterval: FREQUENT_MULTICALL_REFRESH_INTERVAL,
clearUnusedKeys: true,
keepPreviousData: true,

request: () => ({
dataStore: {
contractAddress: getContract(chainId, "DataStore"),
abi: DataStore.abi,
calls: {
keys: {
methodName: "getBytes32ValuesAt",
params: [accountPositionListKey(account!), 0, 1000],
},
},
},
}),
parseResponse: (res) => {
return new Set(res.data.dataStore.keys.returnValues as string[]);
},
}
);

const keysAndPrices = useKeysAndPricesParams({
marketsInfoData,
tokensData,
account,
existingPositionsKeysSet,
});

const { data: positionsData, error: positionsError } = useMulticall(chainId, "usePositionsData", {
key: keysAndPrices.contractPositionsKeys.length ? [keysAndPrices.contractPositionsKeys] : null,
key: account && keysAndPrices.marketsKeys.length ? [account, keysAndPrices.marketsKeys] : null,

refreshInterval: FREQUENT_MULTICALL_REFRESH_INTERVAL,
clearUnusedKeys: true,
Expand All @@ -91,10 +61,13 @@ export function usePositions(
params: [
getContract(chainId, "DataStore"),
getContract(chainId, "ReferralStorage"),
keysAndPrices!.contractPositionsKeys,
keysAndPrices!.marketsPrices,
account,
keysAndPrices.marketsKeys,
keysAndPrices.marketsPrices,
// uiFeeReceiver
ethers.ZeroAddress,
0,
1000,
],
},
},
Expand All @@ -103,7 +76,7 @@ export function usePositions(
parseResponse: (res) => {
const positions = res.data.reader.positions.returnValues;

return positions.reduce((positionsMap: PositionsData, positionInfo, i) => {
return positions.reduce((positionsMap: PositionsData, positionInfo) => {
const { position, fees } = positionInfo;
const { addresses, numbers, flags, data } = position;
const { account, market: marketAddress, collateralToken: collateralTokenAddress } = addresses;
Expand All @@ -114,7 +87,7 @@ export function usePositions(
}

const positionKey = getPositionKey(account, marketAddress, collateralTokenAddress, flags.isLong);
const contractPositionKey = keysAndPrices!.contractPositionsKeys[i];
const contractPositionKey = hashedPositionKey(account, marketAddress, collateralTokenAddress, flags.isLong);

positionsMap[positionKey] = {
key: positionKey,
Expand Down Expand Up @@ -147,23 +120,22 @@ export function usePositions(

return {
positionsData: optimisticPositionsData,
error: positionsError || existingPositionsKeysError,
error: positionsError,
};
}

function useKeysAndPricesParams(p: {
account: string | null | undefined;
marketsInfoData: MarketsData | undefined;
tokensData: TokensData | undefined;
existingPositionsKeysSet: Set<string> | undefined;
}) {
const { account, marketsInfoData, tokensData, existingPositionsKeysSet } = p;
const { account, marketsInfoData, tokensData } = p;

return useMemo(() => {
const values = {
allPositionsKeys: [] as string[],
contractPositionsKeys: [] as string[],
marketsPrices: [] as ContractMarketPrices[],
marketsKeys: [] as string[],
};

if (!account || !marketsInfoData || !tokensData) {
Expand All @@ -175,10 +147,13 @@ function useKeysAndPricesParams(p: {
for (const market of markets) {
const marketPrices = getContractMarketPrices(tokensData, market);

if (!marketPrices) {
if (!marketPrices || market.isSpotOnly) {
continue;
}

values.marketsKeys.push(market.marketTokenAddress);
values.marketsPrices.push(marketPrices);

const collaterals = market.isSameCollaterals
? [market.longTokenAddress]
: [market.longTokenAddress, market.shortTokenAddress];
Expand All @@ -187,19 +162,12 @@ function useKeysAndPricesParams(p: {
for (const isLong of [true, false]) {
const positionKey = getPositionKey(account, market.marketTokenAddress, collateralAddress, isLong);
values.allPositionsKeys.push(positionKey);

const contractPositionKey = hashedPositionKey(account, market.marketTokenAddress, collateralAddress, isLong);

if (existingPositionsKeysSet?.has(contractPositionKey)) {
values.contractPositionsKeys.push(contractPositionKey);
values.marketsPrices.push(marketPrices);
}
}
}
}

return values;
}, [account, existingPositionsKeysSet, marketsInfoData, tokensData]);
}, [account, marketsInfoData, tokensData]);
}

export function useOptimisticPositions(p: {
Expand Down
6 changes: 3 additions & 3 deletions src/lib/metrics/Metrics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ export class Metrics {
);
};

_sendError = async (error: unknown, errorSource: string) => {
pushError = async (error: unknown, errorSource: string) => {
const errorData = prepareErrorMetricData(error);

if (!errorData) {
Expand Down Expand Up @@ -204,15 +204,15 @@ export class Metrics {
const error = event.error;

if (error) {
this._sendError(error, "globalError");
this.pushError(error, "globalError");
}
};

handleUnhandledRejection = (event) => {
const error = event.reason;

if (error) {
this._sendError(error, "unhandledRejection");
this.pushError(error, "unhandledRejection");
}
};

Expand Down
16 changes: 8 additions & 8 deletions src/lib/metrics/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -412,7 +412,7 @@ export function sendOrderSubmittedMetric(metricId: OrderMetricId) {
const metricData = metrics.getCachedMetricData<OrderMetricData>(metricId);

if (!metricData) {
metrics._sendError("Order metric data not found", "sendOrderSubmittedMetric");
metrics.pushError("Order metric data not found", "sendOrderSubmittedMetric");
return;
}

Expand All @@ -427,7 +427,7 @@ export function sendTxnValidationErrorMetric(metricId: OrderMetricId) {
const metricData = metrics.getCachedMetricData<OrderMetricData>(metricId);

if (!metricData) {
metrics._sendError("Order metric data not found", "sendTxnValidationErrorMetric");
metrics.pushError("Order metric data not found", "sendTxnValidationErrorMetric");
return;
}

Expand All @@ -447,7 +447,7 @@ export function makeTxnSentMetricsHandler(metricId: OrderMetricId) {
const metricData = metrics.getCachedMetricData<OrderMetricData>(metricId);

if (!metricData) {
metrics._sendError("Order metric data not found", "makeTxnSentMetricsHandler");
metrics.pushError("Order metric data not found", "makeTxnSentMetricsHandler");
return;
}

Expand All @@ -469,7 +469,7 @@ export function makeTxnErrorMetricsHandler(metricId: OrderMetricId) {
const metricData = metrics.getCachedMetricData<OrderMetricData>(metricId);

if (!metricData) {
metrics._sendError("Order metric data not found", "makeTxnErrorMetricsHandler");
metrics.pushError("Order metric data not found", "makeTxnErrorMetricsHandler");
return;
}

Expand All @@ -494,7 +494,7 @@ export function sendPendingOrderTxnErrorMetric(metricId: OrderMetricId) {
const metricType = (metricData as OrderMetricData)?.metricType || "unknownOrder";

if (!metricData) {
metrics._sendError("Order metric data not found", "sendPendingOrderTxnErrorMetric");
metrics.pushError("Order metric data not found", "sendPendingOrderTxnErrorMetric");
return;
}

Expand All @@ -514,7 +514,7 @@ export function sendOrderCreatedMetric(metricId: OrderMetricId) {
const metricData = metrics.getCachedMetricData<OrderMetricData>(metricId);

if (!metricData) {
metrics._sendError("Order metric data not found", "sendOrderCreatedMetric");
metrics.pushError("Order metric data not found", "sendOrderCreatedMetric");
return;
}

Expand All @@ -530,7 +530,7 @@ export function sendOrderExecutedMetric(metricId: OrderMetricId) {
const metricData = metrics.getCachedMetricData<OrderMetricData>(metricId);

if (!metricData) {
metrics._sendError("Order metric data not found", "sendOrderExecutedMetric");
metrics.pushError("Order metric data not found", "sendOrderExecutedMetric");
return;
}

Expand All @@ -546,7 +546,7 @@ export function sendOrderCancelledMetric(metricId: OrderMetricId, eventData: Eve
const metricData = metrics.getCachedMetricData<OrderMetricData>(metricId);

if (!metricData) {
metrics._sendError("Order metric data not found", "sendOrderCancelledMetric");
metrics.pushError("Order metric data not found", "sendOrderCancelledMetric");
return;
}

Expand Down
9 changes: 5 additions & 4 deletions src/lib/multicall/Multicall.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,11 @@ import { sleep } from "lib/sleep";
import type { MulticallRequestConfig, MulticallResult } from "./types";

import CustomErrors from "abis/CustomErrors.json";
import { MulticallTimeoutEvent, MulticallErrorEvent } from "lib/metrics";
import { MulticallErrorEvent, MulticallTimeoutEvent } from "lib/metrics";
import { emitMetricEvent } from "lib/metrics/emitMetricEvent";
import { SlidingWindowFallbackSwitcher } from "lib/slidingWindowFallbackSwitcher";
import { getStaticOracleKeeperFetcher } from "lib/oracleKeeperFetcher";
import { serializeMulticallErrors } from "./utils";

export const MAX_TIMEOUT = 20000;

Expand Down Expand Up @@ -306,7 +307,7 @@ export class Multicall {
isFallback: true,
isAlchemy: true,
isInMainThread: !isWebWorker,
errorMessage: _viemError.message.slice(0, 150),
errorMessage: _viemError.message,
},
});

Expand All @@ -324,7 +325,7 @@ export class Multicall {
isAlchemy: isFallbackMode,
});

const result: any = await Promise.race([
const result = await Promise.race([
client.multicall({ contracts: encodedPayload as any }),
sleep(maxTimeout).then(() => Promise.reject(new Error("multicall timeout"))),
])
Expand Down Expand Up @@ -363,7 +364,7 @@ export class Multicall {
isFallback: false,
isAlchemy: isFallbackMode,
isInMainThread: !isWebWorker,
errorMessage: "multicall error",
errorMessage: serializeMulticallErrors(result.errors),
},
});

Expand Down
6 changes: 3 additions & 3 deletions src/lib/multicall/executeMulticall.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import entries from "lodash/entries";
import throttle from "lodash/throttle";
import values from "lodash/values";
import { stableHash } from "swr/_internal";
import { getAbFlags, getIsFlagEnabled } from "config/ab";
import { getAbFlags } from "config/ab";
import chunk from "lodash/chunk";

import { isDevelopment } from "config/env";
Expand Down Expand Up @@ -55,9 +55,9 @@ function executeChainsMulticalls() {
}

async function executeChainMulticall(chainId: number, calls: MulticallFetcherConfig[number]) {
const maxCallsPerBatch = getIsFlagEnabled("testAdjustRpcBatching") ? 250 : 500;
const MAX_CALLS_PER_BATCH = 500;

const callChunks = chunk(entries(calls), maxCallsPerBatch);
const callChunks = chunk(entries(calls), MAX_CALLS_PER_BATCH);
const batchedRequests = callChunks.map((chunk) => ({
requestConfig: getRequest(chunk),
callCount: chunk.length,
Expand Down
Loading

0 comments on commit 57cbcad

Please sign in to comment.