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 20, 2024
2 parents f4d693a + b0c672f commit e2a9845
Show file tree
Hide file tree
Showing 22 changed files with 644 additions and 223 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -909,7 +909,7 @@ export function GmSwapBoxDepositWithdrawal(p: GmSwapBoxProps) {
<div>
{submitState.tokensToApprove.map((address) => {
const token = getTokenData(allTokensData, address)!;
const market = getByKey(marketsInfoData, address);
const marketOrGlv = getByKey(glvAndMarketsInfoData, address);
let marketTokenData = address === marketToken?.address && getByKey(marketsInfoData, marketToken?.address);
return (
<div key={address}>
Expand All @@ -918,8 +918,8 @@ export function GmSwapBoxDepositWithdrawal(p: GmSwapBoxProps) {
tokenAddress={address}
tokenSymbol={
marketTokenData
? isGlvInfo(market)
? market.glvToken.contractSymbol
? isGlvInfo(marketOrGlv)
? marketOrGlv.glvToken.contractSymbol
: token.assetSymbol ?? token.symbol
: token.assetSymbol ?? token.symbol
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ export const useTokensToApprove = ({
}
}
} else if (operation === Operation.Withdrawal) {
addresses.push(marketToken.address);
addresses.push(glvToken ? glvToken.address : marketToken.address);
}

return uniq(addresses);
Expand All @@ -76,6 +76,7 @@ export const useTokensToApprove = ({
shortTokenAmount,
shortToken,
glvInfo,
glvToken,
isMarketTokenDeposit,
marketTokenAmount,
]
Expand Down Expand Up @@ -132,7 +133,7 @@ export const useTokensToApprove = ({
}
} else if (operation === Operation.Withdrawal) {
if (glvInfo && shouldApproveGlvToken) {
addresses.push(marketToken.address);
addresses.push(glvToken.address);
} else if (!glvInfo && shouldApproveMarketToken) {
addresses.push(marketToken.address);
}
Expand Down
4 changes: 2 additions & 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 = "testRpcWindowFallback" | "testPrebuiltMarkets";
type Flag = "testPrebuiltMarkets" | "testSmartRpcSwitching";

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

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

const flags: Flag[] = Object.keys(abFlagsConfig) as Flag[];
Expand Down
14 changes: 7 additions & 7 deletions src/config/chains.ts
Original file line number Diff line number Diff line change
Expand Up @@ -225,13 +225,17 @@ export const RPC_PROVIDERS = {
"https://bsc-dataseed4.binance.org",
],
[BSС_TESTNET]: ["https://data-seed-prebsc-1-s1.binance.org:8545/"],
[ARBITRUM]: ["https://arb1.arbitrum.io/rpc"],
[ARBITRUM]: ["https://arb1.arbitrum.io/rpc", "https://arbitrum-one-rpc.publicnode.com", "https://1rpc.io/arb"],
[ARBITRUM_GOERLI]: [
"https://goerli-rollup.arbitrum.io/rpc",
// "https://endpoints.omniatech.io/v1/arbitrum/goerli/public",
// "https://arbitrum-goerli.public.blastapi.io",
],
[AVALANCHE]: ["https://api.avax.network/ext/bc/C/rpc"],
[AVALANCHE]: [
"https://api.avax.network/ext/bc/C/rpc",
"https://avalanche-c-chain-rpc.publicnode.com",
"https://1rpc.io/avax/c",
],
[AVALANCHE_FUJI]: [
"https://avalanche-fuji-c-chain.publicnode.com",
"https://api.avax-test.network/ext/bc/C/rpc",
Expand Down Expand Up @@ -336,11 +340,7 @@ export function getChainName(chainId: number) {
return CHAIN_NAMES_MAP[chainId];
}

export function getRpcUrl(chainId: number): string | undefined {
return sample(RPC_PROVIDERS[chainId]);
}

export function getFallbackRpcUrl(chainId: number): string | undefined {
export function getFallbackRpcUrl(chainId: number): string {
return sample(FALLBACK_PROVIDERS[chainId]);
}

Expand Down
6 changes: 6 additions & 0 deletions src/config/localStorage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ export const DEBUG_MULTICALL_BATCHING_KEY = "debug-multicall-batching";

export const AB_FLAG_STORAGE_KEY = "ab-flags";

export const RPC_PROVIDER = "rpc-provider";

export const getSubgraphUrlKey = (chainId: number, subgraph: string) => `subgraphUrl:${chainId}:${subgraph}`;

export function getSyntheticsDepositIndexTokenKey(chainId: number) {
Expand Down Expand Up @@ -109,6 +111,10 @@ export function getExecutionFeeBufferBpsKey(chainId: number) {
return [chainId, EXECUTION_FEE_BUFFER_BPS_KEY];
}

export function getRpcProviderKey(chainId: number | string) {
return [chainId, RPC_PROVIDER];
}

// TODO: this was made on 07.06.2024, remove this in 6 months, because everyone would be migrated to new defaults by then
export function getHasOverriddenDefaultArb30ExecutionFeeBufferBpsKey(chainId: number) {
return [chainId, HAS_OVERRIDDEN_DEFAULT_ARB_30_EXECUTION_FEE_BUFFER_BPS_KEY];
Expand Down
14 changes: 7 additions & 7 deletions src/context/SubaccountContext/SubaccountContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,8 @@ import {
ARBITRUM,
AVALANCHE,
AVALANCHE_FUJI,
NETWORK_EXECUTION_TO_CREATE_FEE_FACTOR,
getRpcUrl,
getFallbackRpcUrl,
NETWORK_EXECUTION_TO_CREATE_FEE_FACTOR,
} from "config/chains";
import { getContract } from "config/contracts";
import {
Expand Down Expand Up @@ -40,6 +39,7 @@ import { Context, PropsWithChildren, useCallback, useEffect, useMemo, useState }
import { createContext, useContextSelector } from "use-context-selector";
import { clientToSigner } from "lib/wallets/useEthersSigner";
import { estimateOrderOraclePriceCount } from "domain/synthetics/fees/utils/estimateOraclePriceCount";
import { useBestRpcUrl } from "lib/rpc/bestRpcTracker";

export type Subaccount = ReturnType<typeof useSubaccount>;

Expand Down Expand Up @@ -302,13 +302,13 @@ function useSubaccountCustomSigners() {
const { chainId } = useChainId();
const privateKey = useSubaccountPrivateKey();

return useMemo(() => {
const publicRpc = getRpcUrl(chainId);
const fallbackRpc = getFallbackRpcUrl(chainId);
const primaryRpc = useBestRpcUrl(chainId);
const fallbackRpc = getFallbackRpcUrl(chainId);

return useMemo(() => {
const rpcUrls: string[] = [];

if (publicRpc) rpcUrls.push(publicRpc);
if (primaryRpc) rpcUrls.push(primaryRpc);
if (fallbackRpc) rpcUrls.push(fallbackRpc);

if (!rpcUrls.length || !privateKey) return undefined;
Expand All @@ -320,7 +320,7 @@ function useSubaccountCustomSigners() {

return new ethers.Wallet(privateKey, provider);
});
}, [chainId, privateKey]);
}, [chainId, privateKey, primaryRpc, fallbackRpc]);
}

export function useSubaccount(requiredBalance: bigint | null, requiredActions = 1) {
Expand Down
95 changes: 6 additions & 89 deletions src/domain/synthetics/markets/useMarkets.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,12 @@
import { useMemo } from "react";
import { ethers } from "ethers";

import { getContract } from "config/contracts";
import { isMarketEnabled } from "config/markets";
import { convertTokenAddress, getToken } from "config/tokens";
import { useMulticall } from "lib/multicall";
import { CONFIG_UPDATE_INTERVAL } from "lib/timeConstants";
import { getIsFlagEnabled } from "config/ab";

import { MarketsData } from "./types";
import { getMarketFullName } from "./utils";

import SyntheticsReader from "abis/SyntheticsReader.json";

import { MARKETS } from "config/markets";

export type MarketsResult = {
Expand All @@ -21,20 +15,15 @@ export type MarketsResult = {
error?: Error | undefined;
};

const MARKETS_COUNT = 100;

export function useMarkets(chainId: number): MarketsResult {
const staticMarketData = useMemo(() => {
const enabledMarkets = MARKETS[chainId];

if (!enabledMarkets) {
// eslint-disable-next-line no-console
console.warn(`Static markets data for chain ${chainId} not found`);
return useMemo(() => {
const markets = MARKETS[chainId];

return null;
if (!markets) {
throw new Error(`Static markets data for chain ${chainId} not found`);
}

return Object.values(enabledMarkets).reduce(
return Object.values(markets).reduce(
(acc: MarketsResult, enabledMarketConfig) => {
const market = enabledMarketConfig;

Expand Down Expand Up @@ -67,79 +56,7 @@ export function useMarkets(chainId: number): MarketsResult {

return acc;
},
{ marketsData: {}, marketsAddresses: [], error: undefined }
{ marketsData: {}, marketsAddresses: [] }
);
}, [chainId]);

const shouldUseStaticMarketKeys = staticMarketData && getIsFlagEnabled("testPrebuiltMarkets");

const freshData = useMarketsMulticall(chainId, { enabled: !shouldUseStaticMarketKeys });

return shouldUseStaticMarketKeys ? staticMarketData : freshData;
}

function useMarketsMulticall(chainId: number, { enabled = true } = {}): MarketsResult {
const { data, error } = useMulticall(chainId, "useMarketsData", {
key: enabled ? [] : null,

refreshInterval: CONFIG_UPDATE_INTERVAL,

request: () => ({
reader: {
contractAddress: getContract(chainId, "SyntheticsReader"),
abi: SyntheticsReader.abi,
calls: {
markets: {
methodName: "getMarkets",
params: [getContract(chainId, "DataStore"), 0, MARKETS_COUNT],
},
},
},
}),
parseResponse: (res) => {
return res.data.reader.markets.returnValues.reduce(
(acc: { marketsData: MarketsData; marketsAddresses: string[] }, marketValues) => {
if (!isMarketEnabled(chainId, marketValues.marketToken)) {
return acc;
}

try {
const indexToken = getToken(chainId, convertTokenAddress(chainId, marketValues.indexToken, "native"));
const longToken = getToken(chainId, marketValues.longToken);
const shortToken = getToken(chainId, marketValues.shortToken);

const isSameCollaterals = marketValues.longToken === marketValues.shortToken;
const isSpotOnly = marketValues.indexToken === ethers.ZeroAddress;

const name = getMarketFullName({ indexToken, longToken, shortToken, isSpotOnly });

acc.marketsData[marketValues.marketToken] = {
marketTokenAddress: marketValues.marketToken,
indexTokenAddress: marketValues.indexToken,
longTokenAddress: marketValues.longToken,
shortTokenAddress: marketValues.shortToken,
isSameCollaterals,
isSpotOnly,
name,
data: "",
};

acc.marketsAddresses.push(marketValues.marketToken);
} catch (e) {
// eslint-disable-next-line no-console
console.warn("unsupported market", e);
}

return acc;
},
{ marketsData: {}, marketsAddresses: [] }
);
},
});

return {
marketsData: data?.marketsData,
marketsAddresses: data?.marketsAddresses,
error,
};
}
4 changes: 2 additions & 2 deletions src/domain/synthetics/markets/useMarketsInfoRequest/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ export type MarketConfigMulticallRequestConfig = MulticallRequestConfig<{

export function useMarketsInfoRequest(chainId: number): MarketsInfoResult {
const { address: account } = useAccount();
const { marketsData, marketsAddresses, error: marketsError } = useMarkets(chainId);
const { marketsData, marketsAddresses } = useMarkets(chainId);
const { tokensData, pricesUpdatedAt, error: tokensDataError } = useTokensDataRequest(chainId);

const isDependenciesLoading = !marketsAddresses || !tokensData;
Expand Down Expand Up @@ -263,7 +263,7 @@ export function useMarketsInfoRequest(chainId: number): MarketsInfoResult {
return data as MarketsInfoData;
}, [marketsValues.data, marketsConfigs.data, marketsAddresses, marketsData, tokensData, chainId]);

const error = marketsError || tokensDataError || marketsValues.error || marketsConfigs.error;
const error = tokensDataError || marketsValues.error || marketsConfigs.error;

return {
marketsInfoData: isDependenciesLoading ? undefined : mergedData,
Expand Down
17 changes: 16 additions & 1 deletion src/lib/contracts/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,27 @@ import {
import { BASIS_POINTS_DIVISOR_BIGINT } from "config/factors";
import { BaseContract, Contract, Provider, Wallet } from "ethers";
import { bigMath } from "lib/bigmath";
import { emitMetricCounter } from "lib/metrics/emitMetricEvent";
import { withRetry } from "viem";

export async function getGasPrice(provider: Provider, chainId: number) {
let maxFeePerGas = MAX_FEE_PER_GAS_MAP[chainId];
const premium: bigint = GAS_PRICE_PREMIUM_MAP[chainId] || 0n;

const feeData = await provider.getFeeData();
const feeData = await withRetry(() => provider.getFeeData(), {
delay: 200,
retryCount: 2,
shouldRetry: ({ error }) => {
const isInvalidBlockError = error?.message?.includes("invalid value for value.hash");

if (isInvalidBlockError) {
emitMetricCounter({ event: "error.getFeeData.value.hash" });
}

return isInvalidBlockError;
},
});

const gasPrice = feeData.gasPrice;

if (maxFeePerGas) {
Expand Down
5 changes: 5 additions & 0 deletions src/lib/localStorage/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { useCallback } from "react";
import { useLocalStorage } from "react-use";
import { SHOW_DEBUG_VALUES_KEY } from "config/localStorage";

export function useLocalStorageByChainId<T>(
chainId: number,
Expand Down Expand Up @@ -51,3 +52,7 @@ export function useLocalStorageSerializeKey<T>(

return useLocalStorage<T>(key, initialValue, opts);
}

export function isDebugMode() {
return localStorage.getItem(JSON.stringify(SHOW_DEBUG_VALUES_KEY)) === "true";
}
Loading

0 comments on commit e2a9845

Please sign in to comment.