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

alchemy for large accounts #1278

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
4 changes: 4 additions & 0 deletions src/config/localStorage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,10 @@ export function getSubaccountConfigKey(chainId: number | undefined, account: str
return [chainId, account, "one-click-trading-config"];
}

export function getIsLargeAccountKey(account: string) {
return [account, "is-large-account"];
}

export function getSyntheticsReceiveMoneyTokenKey(
chainId: number,
marketName: string | undefined,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { getKeepLeverageKey } from "config/localStorage";
import { SettingsContextType, useSettings } from "context/SettingsContext/SettingsContextProvider";
import { UserReferralInfo, useUserReferralInfoRequest } from "domain/referrals";
import { PeriodAccountStats, useAccountStats, usePeriodAccountStats } from "domain/synthetics/accountStats";
import { useIsLargeAccountTracker } from "lib/rpc/bestRpcTracker";
import { useGasLimits, useGasPrice } from "domain/synthetics/fees";
import { RebateInfoItem, useRebatesInfoRequest } from "domain/synthetics/fees/useRebatesInfo";
import useUiFeeFactorRequest from "domain/synthetics/fees/utils/useUiFeeFactor";
Expand Down Expand Up @@ -81,6 +82,7 @@ export type SyntheticsState = {
lastWeekAccountStats?: PeriodAccountStats;
lastMonthAccountStats?: PeriodAccountStats;
accountStats?: AccountStats;
isLargeAccount?: boolean;
};
claims: {
accruedPositionPriceImpactFees: RebateInfoItem[];
Expand Down Expand Up @@ -187,6 +189,8 @@ export function SyntheticsStateContextProvider({

const timePerios = useMemo(() => getTimePeriodsInSeconds(), []);

const isLargeAccount = useIsLargeAccountTracker(walletAccount);

const { data: lastWeekAccountStats } = usePeriodAccountStats(chainId, {
account,
from: timePerios.week[0],
Expand Down Expand Up @@ -256,6 +260,7 @@ export function SyntheticsStateContextProvider({
lastWeekAccountStats,
lastMonthAccountStats,
accountStats,
isLargeAccount,
},
claims: { accruedPositionPriceImpactFees, claimablePositionPriceImpactFees },
leaderboard,
Expand Down Expand Up @@ -300,6 +305,7 @@ export function SyntheticsStateContextProvider({
positionSellerState,
positionEditorState,
confirmationBoxState,
isLargeAccount,
]);

latestState = state;
Expand Down
1 change: 1 addition & 0 deletions src/domain/synthetics/accountStats/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from "./useAccountStats";
export * from "./usePeriodAccountStats";
export * from "./usePnlSummaryData";
export * from "./useIsLargeAccount";
95 changes: 95 additions & 0 deletions src/domain/synthetics/accountStats/useAccountVolumeStats.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import { gql } from "@apollo/client";
import { getSubsquidGraphClient } from "lib/subgraph";
import { useMemo } from "react";
import useSWR from "swr";
import { subDays, format, eachDayOfInterval } from "date-fns";
import { toUtcDayStart } from "lib/dates";
import { CONFIG_UPDATE_INTERVAL } from "lib/timeConstants";
import { ARBITRUM, AVALANCHE } from "config/chains";

const LARGE_ACCOUNT_CHAINS = [ARBITRUM, AVALANCHE];

export function useAccountVolumeStats(params: { account?: string }) {
const { account } = params;

const now = new Date();
const date30dAgo = subDays(now, 30);
const last30dList = eachDayOfInterval({
start: date30dAgo,
end: now,
});

const { data, error, isLoading } = useSWR<{
totalVolume: bigint;
dailyVolume: { date: string; volume: bigint }[];
}>(account ? ["useAccountVolumeStats", account] : null, {
fetcher: async () => {
const chainPromises = LARGE_ACCOUNT_CHAINS.map(async (chainId) => {
const client = getSubsquidGraphClient(chainId);

const dailyQueries = last30dList.map((day, index) => {
const from = Math.floor(toUtcDayStart(day));
const to = Math.floor(toUtcDayStart(day) + 24 * 60 * 60);

return `
day${index}: periodAccountStats(
where: { id_eq: "${account}", from: ${from}, to: ${to} }
) {
volume
}
`;
});

const query = gql`
query AccountVolumeStats {
total: accountStats(where: { id_eq: "${account}" }) {
volume
}
${dailyQueries.join("\n")}
}
`;

const res = await client?.query({
query,
fetchPolicy: "no-cache",
});

const totalVolume = BigInt(res?.data?.total?.[0]?.volume ?? 0);

const dailyVolume = last30dList.map((day, index) => {
const volume = BigInt(res?.data[`day${index}`]?.[0]?.volume ?? 0);
return {
date: format(day, "yyyy-MM-dd"),
volume,
};
});

return {
totalVolume,
dailyVolume,
};
});

const chainResults = await Promise.all(chainPromises);

const totalVolume = chainResults.reduce((acc, result) => acc + result.totalVolume, 0n);

const dailyVolume = last30dList.map((day, index) => {
const volume = chainResults.reduce((acc, { dailyVolume }) => acc + dailyVolume[index].volume, 0n);

return {
date: format(day, "yyyy-MM-dd"),
volume,
};
});

return {
totalVolume,
dailyVolume,
};
},
refreshInterval: CONFIG_UPDATE_INTERVAL,
});

return useMemo(() => ({ data, error, isLoading }), [data, error, isLoading]);
}
30 changes: 30 additions & 0 deletions src/domain/synthetics/accountStats/useIsLargeAccount.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { useMemo } from "react";
import { USD_DECIMALS } from "config/factors";
import { expandDecimals } from "lib/numbers";

import { useAccountVolumeStats } from "./useAccountVolumeStats";

// Thresholds to recognise large accounts
const MAX_DAILY_VOLUME = expandDecimals(220_000n, USD_DECIMALS);
const AGG_14_DAYS_VOLUME = expandDecimals(1_200_000n, USD_DECIMALS);
const AGG_ALL_TIME_VOLUME = expandDecimals(3_500_000n, USD_DECIMALS);

export function useIsLargeAccount(account?: string) {
const { data, error, isLoading } = useAccountVolumeStats({ account });

const isLargeAccount = useMemo(() => {
if (!data || isLoading || error) return undefined;

const { totalVolume, dailyVolume } = data;

const maxDailyVolume = dailyVolume.reduce((max, day) => (day.volume > max ? day.volume : max), 0n);

const last14DaysVolume = dailyVolume.slice(-14).reduce((acc, day) => acc + day.volume, 0n);

return (
maxDailyVolume >= MAX_DAILY_VOLUME || last14DaysVolume >= AGG_14_DAYS_VOLUME || totalVolume >= AGG_ALL_TIME_VOLUME
);
}, [data, isLoading, error]);

return isLargeAccount;
}
2 changes: 2 additions & 0 deletions src/lib/metrics/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,7 @@ export type MulticallTimeoutEvent = {
isInMainThread: boolean;
requestType?: "initial" | "retry";
rpcProvider?: string;
isLargeAccount?: boolean;
errorMessage: string;
};
};
Expand All @@ -160,6 +161,7 @@ export type MulticallErrorEvent = {
isInMainThread: boolean;
rpcProvider?: string;
requestType?: "initial" | "retry";
isLargeAccount?: boolean;
errorMessage: string;
};
};
Expand Down
12 changes: 11 additions & 1 deletion src/lib/multicall/Multicall.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,12 @@ export class Multicall {
private abFlags: Record<string, boolean>
) {}

async call(providerUrls: MulticallProviderUrls, request: MulticallRequestConfig<any>, maxTimeout: number) {
async call(
providerUrls: MulticallProviderUrls,
request: MulticallRequestConfig<any>,
maxTimeout: number,
isLargeAccount: boolean
) {
const originalKeys: {
contractKey: string;
callKey: string;
Expand Down Expand Up @@ -208,6 +213,7 @@ export class Multicall {
isInMainThread: !isWebWorker,
requestType,
rpcProvider,
isLargeAccount,
},
});
};
Expand All @@ -227,6 +233,7 @@ export class Multicall {
data: {
requestType,
rpcProvider,
isLargeAccount,
},
});
};
Expand Down Expand Up @@ -332,6 +339,7 @@ export class Multicall {
rpcProvider: fallbackProviderName,
isInMainThread: !isWebWorker,
errorMessage: _viemError.message,
isLargeAccount,
},
});

Expand Down Expand Up @@ -375,6 +383,7 @@ export class Multicall {
isInMainThread: !isWebWorker,
requestType: "initial",
rpcProvider: rpcProviderName,
isLargeAccount,
errorMessage: _viemError.message.slice(0, 150),
},
});
Expand All @@ -398,6 +407,7 @@ export class Multicall {
requestType: "initial",
rpcProvider: rpcProviderName,
isInMainThread: !isWebWorker,
isLargeAccount,
errorMessage: serializeMulticallErrors(result.errors),
},
});
Expand Down
5 changes: 3 additions & 2 deletions src/lib/multicall/executeMulticallMainThread.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { MAX_TIMEOUT, Multicall } from "./Multicall";
import type { MulticallRequestConfig } from "./types";
import { getAbFlags } from "config/ab";
import { getBestRpcUrl } from "lib/rpc/bestRpcTracker";
import { getBestRpcUrl, getIsLargeAccount } from "lib/rpc/bestRpcTracker";
import { getFallbackRpcUrl } from "config/chains";

export async function executeMulticallMainThread(chainId: number, request: MulticallRequestConfig<any>) {
Expand All @@ -10,6 +10,7 @@ export async function executeMulticallMainThread(chainId: number, request: Multi
primary: getBestRpcUrl(chainId),
secondary: getFallbackRpcUrl(chainId),
};
const isLargeAccount = getIsLargeAccount();

return multicall?.call(providerUrls, request, MAX_TIMEOUT);
return multicall?.call(providerUrls, request, MAX_TIMEOUT, isLargeAccount);
}
3 changes: 2 additions & 1 deletion src/lib/multicall/executeMulticallWorker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { executeMulticallMainThread } from "./executeMulticallMainThread";
import type { MulticallRequestConfig, MulticallResult } from "./types";
import { MetricEventParams, MulticallTimeoutEvent } from "lib/metrics";
import { getAbFlags } from "config/ab";
import { getBestRpcUrl } from "lib/rpc/bestRpcTracker";
import { getBestRpcUrl, getIsLargeAccount } from "lib/rpc/bestRpcTracker";
import { getFallbackRpcUrl } from "config/chains";

const executorWorker: Worker = new Worker(new URL("./multicall.worker", import.meta.url), { type: "module" });
Expand Down Expand Up @@ -86,6 +86,7 @@ export async function executeMulticallWorker(
providerUrls,
request,
abFlags: getAbFlags(),
isLargeAccount: getIsLargeAccount(),
PRODUCTION_PREVIEW_KEY: localStorage.getItem(PRODUCTION_PREVIEW_KEY),
});

Expand Down
9 changes: 5 additions & 4 deletions src/lib/multicall/multicall.worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,22 +12,23 @@ async function executeMulticall(
chainId: number,
providerUrls: MulticallProviderUrls,
request: MulticallRequestConfig<any>,
abFlags: Record<string, boolean>
abFlags: Record<string, boolean>,
isLargeAccount: boolean
) {
const multicall = await Multicall.getInstance(chainId, abFlags);

return multicall?.call(providerUrls, request, MAX_TIMEOUT);
return multicall?.call(providerUrls, request, MAX_TIMEOUT, isLargeAccount);
}

self.addEventListener("message", run);

async function run(event) {
const { PRODUCTION_PREVIEW_KEY, chainId, providerUrls, request, id, abFlags } = event.data;
const { PRODUCTION_PREVIEW_KEY, chainId, providerUrls, request, id, abFlags, isLargeAccount } = event.data;
// @ts-ignore
self.PRODUCTION_PREVIEW_KEY = PRODUCTION_PREVIEW_KEY;

try {
const result = await executeMulticall(chainId, providerUrls, request, abFlags);
const result = await executeMulticall(chainId, providerUrls, request, abFlags, isLargeAccount);

postMessage({
id,
Expand Down
Loading