Skip to content

Trade and Claim history from squid #1638

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

Merged
merged 17 commits into from
Apr 24, 2025
Merged
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
208 changes: 29 additions & 179 deletions sdk/src/modules/trades/trades.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,18 @@
import merge from "lodash/merge";
import { Address, getAddress } from "viem";
import type { Address } from "viem";

import { getWrappedToken } from "configs/tokens";
import { GmxSdk } from "index";
import { MarketsInfoData } from "types/markets";
import { OrderType } from "types/orders";
import { Token, TokensData } from "types/tokens";
import { PositionTradeAction, RawTradeAction, SwapTradeAction, TradeAction, TradeActionType } from "types/tradeHistory";
import { TokensData } from "types/tokens";
import { PositionTradeAction, RawTradeAction, TradeAction, TradeActionType } from "types/tradeHistory";
import graphqlFetcher from "utils/graphqlFetcher";
import { getByKey } from "utils/objects";
import { isIncreaseOrderType, isLimitOrderType, isSwapOrderType, isTriggerDecreaseOrderType } from "utils/orders";
import { GraphQlFilters, buildFiltersBody } from "utils/subgraph";
import { getSwapPathOutputAddresses } from "utils/swap/swapStats";
import { parseContractPrice } from "utils/tokens";
import { createRawTradeActionTransformer } from "utils/tradeHistory";

import type { GmxSdk } from "../..";
import { Module } from "../base";

export type MarketFilterLongShortDirection = "long" | "short" | "swap" | "any";
Expand Down Expand Up @@ -102,15 +101,15 @@ export async function fetchTradeActions({
marketsInfoData: MarketsInfoData | undefined;
tokensData: TokensData | undefined;
}): Promise<TradeAction[]> {
const endpoint = sdk.config.subgraphUrl;
const endpoint = sdk.config.subsquidUrl;
const chainId = sdk.chainId;

if (!endpoint) {
return [];
}

const skip = pageIndex * pageSize;
const first = pageSize;
const offset = pageIndex * pageSize;
const limit = pageSize;

const nonSwapRelevantDefinedFiltersLowercased: MarketFilterLongShortItemData[] = marketsDirectionsFilter
.filter((filter) => filter.direction !== "swap" && filter.marketAddress !== "any")
Expand All @@ -137,57 +136,55 @@ export async function fetchTradeActions({
const hasSwapRelevantDefinedMarkets = swapRelevantDefinedMarketsLowercased.length > 0;

const filtersStr = buildFiltersBody({
and: [
AND: [
{
account: forAllAccounts ? undefined : account!.toLowerCase(),
transaction: {
timestamp_gte: fromTxTimestamp,
timestamp_lte: toTxTimestamp,
},
account_eq: forAllAccounts ? undefined : account,
timestamp_gte: fromTxTimestamp,
timestamp_lte: toTxTimestamp,
},
{
or: !hasPureDirectionFilters
OR: !hasPureDirectionFilters
? undefined
: pureDirectionFilters.map((filter) =>
filter.direction === "swap"
? {
orderType_in: [OrderType.LimitSwap, OrderType.MarketSwap],
}
: {
isLong: filter.direction === "long",
isLong_eq: filter.direction === "long",
orderType_not_in: [OrderType.LimitSwap, OrderType.MarketSwap],
}
),
},
{
or: [
OR: [
// For non-swap orders
{
and: !hasNonSwapRelevantDefinedMarkets
AND: !hasNonSwapRelevantDefinedMarkets
? undefined
: [
{
orderType_not_in: [OrderType.LimitSwap, OrderType.MarketSwap],
},
{
or: nonSwapRelevantDefinedFiltersLowercased.map((filter) => ({
marketAddress: filter.marketAddress === "any" ? undefined : filter.marketAddress,
isLong: filter.direction === "any" ? undefined : filter.direction === "long",
OR: nonSwapRelevantDefinedFiltersLowercased.map((filter) => ({
marketAddress_eq: filter.marketAddress === "any" ? undefined : filter.marketAddress,
isLong_eq: filter.direction === "any" ? undefined : filter.direction === "long",
// Collateral filtering is done outside of graphql on the client
})),
},
],
},
// For defined markets on swap orders
{
and: !hasSwapRelevantDefinedMarkets
AND: !hasSwapRelevantDefinedMarkets
? undefined
: [
{
orderType_in: [OrderType.LimitSwap, OrderType.MarketSwap],
},
{
or: [
OR: [
// Source token is not in swap path so we add it to the or filter
{
marketAddress_in: swapRelevantDefinedMarketsLowercased,
Expand All @@ -203,7 +200,7 @@ export async function fetchTradeActions({
],
},
{
or: orderEventCombinations?.map((combination) => {
OR: orderEventCombinations?.map((combination) => {
let sizeDeltaUsdCondition = {};

if (
Expand All @@ -219,8 +216,8 @@ export async function fetchTradeActions({

return merge(
{
eventName: combination.eventName,
orderType: combination.orderType,
eventName_eq: combination.eventName,
orderType_eq: combination.orderType,
},
sizeDeltaUsdCondition
);
Expand All @@ -229,7 +226,7 @@ export async function fetchTradeActions({
{
// We do not show create liquidation orders in the trade history, thus we filter it out
// ... && not (liquidation && orderCreated) === ... && (not liquidation || not orderCreated)
or: [{ orderType_not: OrderType.Liquidation }, { eventName_not: TradeActionType.OrderCreated }],
OR: [{ orderType_not_eq: OrderType.Liquidation }, { eventName_not_eq: TradeActionType.OrderCreated }],
},
],
});
Expand All @@ -238,10 +235,9 @@ export async function fetchTradeActions({

const query = `{
tradeActions(
skip: ${skip},
first: ${first},
orderBy: transaction__timestamp,
orderDirection: desc,
offset: ${offset},
limit: ${limit},
orderBy: transaction_timestamp_DESC,
${whereClause}
) {
id
Expand Down Expand Up @@ -281,6 +277,7 @@ export async function fetchTradeActions({

reason
reasonBytes
timestamp

transaction {
timestamp
Expand Down Expand Up @@ -376,150 +373,3 @@ export async function fetchTradeActions({

return tradeActions;
}

function createRawTradeActionTransformer(
marketsInfoData: MarketsInfoData,
wrappedToken: Token,
tokensData: TokensData
): (
value: RawTradeAction,
index: number,
array: RawTradeAction[]
) => SwapTradeAction | PositionTradeAction | undefined {
return (rawAction) => {
const orderType = Number(rawAction.orderType);

if (isSwapOrderType(orderType)) {
const initialCollateralTokenAddress = getAddress(rawAction.initialCollateralTokenAddress!);
const swapPath = rawAction.swapPath!.map((address) => getAddress(address));

const swapPathOutputAddresses = getSwapPathOutputAddresses({
marketsInfoData,
swapPath,
initialCollateralAddress: initialCollateralTokenAddress,
wrappedNativeTokenAddress: wrappedToken.address,
shouldUnwrapNativeToken: rawAction.shouldUnwrapNativeToken!,
isIncrease: false,
});

const initialCollateralToken = getByKey(tokensData, initialCollateralTokenAddress)!;
const targetCollateralToken = getByKey(tokensData, swapPathOutputAddresses.outTokenAddress)!;

if (!initialCollateralToken || !targetCollateralToken) {
return undefined;
}

const tradeAction: SwapTradeAction = {
id: rawAction.id,
eventName: rawAction.eventName,
account: rawAction.account,
swapPath,
orderType,
orderKey: rawAction.orderKey,
initialCollateralTokenAddress: rawAction.initialCollateralTokenAddress!,
initialCollateralDeltaAmount: bigNumberify(rawAction.initialCollateralDeltaAmount)!,
minOutputAmount: bigNumberify(rawAction.minOutputAmount)!,
executionAmountOut: rawAction.executionAmountOut ? bigNumberify(rawAction.executionAmountOut) : undefined,
shouldUnwrapNativeToken: rawAction.shouldUnwrapNativeToken!,
targetCollateralToken,
initialCollateralToken,
transaction: rawAction.transaction,
reason: rawAction.reason,
reasonBytes: rawAction.reasonBytes,
};

return tradeAction;
} else {
const marketAddress = getAddress(rawAction.marketAddress!);
const marketInfo = getByKey(marketsInfoData, marketAddress);
const indexToken = marketInfo?.indexToken;
const initialCollateralTokenAddress = getAddress(rawAction.initialCollateralTokenAddress!);
const swapPath = rawAction.swapPath!.map((address) => getAddress(address));
const swapPathOutputAddresses = getSwapPathOutputAddresses({
marketsInfoData,
swapPath,
initialCollateralAddress: initialCollateralTokenAddress,
wrappedNativeTokenAddress: wrappedToken.address,
shouldUnwrapNativeToken: rawAction.shouldUnwrapNativeToken!,
isIncrease: isIncreaseOrderType(rawAction.orderType),
});
const initialCollateralToken = getByKey(tokensData, initialCollateralTokenAddress);
const targetCollateralToken = getByKey(tokensData, swapPathOutputAddresses.outTokenAddress);

if (!marketInfo || !indexToken || !initialCollateralToken || !targetCollateralToken) {
return undefined;
}

const tradeAction: PositionTradeAction = {
id: rawAction.id,
eventName: rawAction.eventName,
account: rawAction.account,
marketAddress,
marketInfo,
indexToken,
swapPath,
initialCollateralTokenAddress,
initialCollateralToken,
targetCollateralToken,
initialCollateralDeltaAmount: bigNumberify(rawAction.initialCollateralDeltaAmount)!,
sizeDeltaUsd: bigNumberify(rawAction.sizeDeltaUsd)!,
triggerPrice: rawAction.triggerPrice
? parseContractPrice(bigNumberify(rawAction.triggerPrice)!, indexToken.decimals)
: undefined,
acceptablePrice: parseContractPrice(bigNumberify(rawAction.acceptablePrice)!, indexToken.decimals),
executionPrice: rawAction.executionPrice
? parseContractPrice(bigNumberify(rawAction.executionPrice)!, indexToken.decimals)
: undefined,
minOutputAmount: bigNumberify(rawAction.minOutputAmount)!,

collateralTokenPriceMax: rawAction.collateralTokenPriceMax
? parseContractPrice(bigNumberify(rawAction.collateralTokenPriceMax)!, initialCollateralToken.decimals)
: undefined,

collateralTokenPriceMin: rawAction.collateralTokenPriceMin
? parseContractPrice(bigNumberify(rawAction.collateralTokenPriceMin)!, initialCollateralToken.decimals)
: undefined,

indexTokenPriceMin: rawAction.indexTokenPriceMin
? parseContractPrice(BigInt(rawAction.indexTokenPriceMin), indexToken.decimals)
: undefined,
indexTokenPriceMax: rawAction.indexTokenPriceMax
? parseContractPrice(BigInt(rawAction.indexTokenPriceMax), indexToken.decimals)
: undefined,

orderType,
orderKey: rawAction.orderKey,
isLong: rawAction.isLong!,
pnlUsd: rawAction.pnlUsd ? BigInt(rawAction.pnlUsd) : undefined,
basePnlUsd: rawAction.basePnlUsd ? BigInt(rawAction.basePnlUsd) : undefined,

priceImpactDiffUsd: rawAction.priceImpactDiffUsd ? BigInt(rawAction.priceImpactDiffUsd) : undefined,
priceImpactUsd: rawAction.priceImpactUsd ? BigInt(rawAction.priceImpactUsd) : undefined,
positionFeeAmount: rawAction.positionFeeAmount ? BigInt(rawAction.positionFeeAmount) : undefined,
borrowingFeeAmount: rawAction.borrowingFeeAmount ? BigInt(rawAction.borrowingFeeAmount) : undefined,
fundingFeeAmount: rawAction.fundingFeeAmount ? BigInt(rawAction.fundingFeeAmount) : undefined,

reason: rawAction.reason,
reasonBytes: rawAction.reasonBytes,

transaction: rawAction.transaction,
shouldUnwrapNativeToken: rawAction.shouldUnwrapNativeToken!,
};

return tradeAction;
}
};
}

export function bigNumberify(n?: bigint | string | null | undefined) {
try {
if (n === undefined) throw new Error("n is undefined");
if (n === null) throw new Error("n is null");

return BigInt(n);
} catch (e) {
// eslint-disable-next-line no-console
console.error("bigNumberify error", e);
return undefined;
}
}
2 changes: 0 additions & 2 deletions sdk/src/types/sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@ export interface GmxSdkConfig {
rpcUrl: string;
/** GMX Subsquid URL */
subsquidUrl: string;
/** GMX Subgraph Synthetics Stats URL */
subgraphUrl: string;

/** Custom viem's public and private client */
publicClient?: PublicClient;
Expand Down
7 changes: 3 additions & 4 deletions sdk/src/types/tradeHistory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,8 @@ export type RawTradeAction = {
reason?: string;
reasonBytes?: BytesLike;

timestamp: number;
transaction: {
timestamp: number;
hash: string;
};
};
Expand Down Expand Up @@ -92,9 +92,8 @@ export type PositionTradeAction = {
reasonBytes?: string | Uint8Array;
shouldUnwrapNativeToken: boolean;
liquidationFeeAmount?: bigint;

timestamp: number;
transaction: {
timestamp: number;
hash: string;
};
};
Expand All @@ -117,8 +116,8 @@ export type SwapTradeAction = {
reason?: string;
reasonBytes?: string | Uint8Array;

timestamp: number;
transaction: {
timestamp: number;
hash: string;
};
};
Expand Down
4 changes: 0 additions & 4 deletions sdk/src/utils/__tests__/subgraph.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,6 @@ describe("buildFiltersBody", () => {
foo: "bar",
},
],
// @ts-expect-error
baz: "qux",
};

Expand All @@ -139,7 +138,6 @@ describe("buildFiltersBody", () => {
foo: "bar",
},
],
// @ts-expect-error
baz: "qux",
};

Expand All @@ -151,7 +149,6 @@ describe("buildFiltersBody", () => {
it("should throw not error if empty or is mixed with other filters", () => {
const input: GraphQlFilters = {
or: [],
// @ts-expect-error
baz: "qux",
};

Expand All @@ -163,7 +160,6 @@ describe("buildFiltersBody", () => {
it("should throw not error if empty and is mixed with other filters", () => {
const input: GraphQlFilters = {
and: [],
// @ts-expect-error
baz: "qux",
};

Expand Down
Loading