@gmx-io/sdk 0.0.1-alpha-1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (237) hide show
  1. package/LICENSE +40 -0
  2. package/README.md +79 -0
  3. package/build/abis/CustomErrors.json +3254 -0
  4. package/build/abis/DataStore.json +1440 -0
  5. package/build/abis/ERC721.json +442 -0
  6. package/build/abis/EventEmitter.json +2065 -0
  7. package/build/abis/ExchangeRouter.json +1598 -0
  8. package/build/abis/GMT.json +522 -0
  9. package/build/abis/GlpManager.json +592 -0
  10. package/build/abis/GlvReader.json +1425 -0
  11. package/build/abis/GlvRouter.json +613 -0
  12. package/build/abis/GmxMigrator.json +657 -0
  13. package/build/abis/GovToken.json +1121 -0
  14. package/build/abis/MintableBaseToken.json +696 -0
  15. package/build/abis/Multicall.json +333 -0
  16. package/build/abis/OrderBook.json +1997 -0
  17. package/build/abis/OrderBookReader.json +111 -0
  18. package/build/abis/OrderExecutor.json +122 -0
  19. package/build/abis/PositionManager.json +1165 -0
  20. package/build/abis/PositionRouter.json +2030 -0
  21. package/build/abis/Reader.json +355 -0
  22. package/build/abis/ReaderV2.json +630 -0
  23. package/build/abis/ReferralStorage.json +507 -0
  24. package/build/abis/RewardReader.json +86 -0
  25. package/build/abis/RewardRouter.json +769 -0
  26. package/build/abis/RewardTracker.json +918 -0
  27. package/build/abis/Router-v2.json +605 -0
  28. package/build/abis/Router.json +605 -0
  29. package/build/abis/SubaccountRouter.json +648 -0
  30. package/build/abis/SyntheticsReader.json +4577 -0
  31. package/build/abis/SyntheticsRouter.json +77 -0
  32. package/build/abis/Timelock.json +1737 -0
  33. package/build/abis/Token.json +345 -0
  34. package/build/abis/Treasury.json +411 -0
  35. package/build/abis/UniPool.json +89 -0
  36. package/build/abis/UniswapV2.json +1 -0
  37. package/build/abis/Vault.json +3220 -0
  38. package/build/abis/VaultReader.json +87 -0
  39. package/build/abis/VaultV2.json +3019 -0
  40. package/build/abis/VaultV2b.json +3220 -0
  41. package/build/abis/Vester.json +1031 -0
  42. package/build/abis/WETH.json +320 -0
  43. package/build/abis/YieldFarm.json +599 -0
  44. package/build/abis/YieldToken.json +560 -0
  45. package/build/prebuilt/hashedMarketConfigKeys.json +3658 -0
  46. package/build/prebuilt/hashedMarketValuesKeys.json +1103 -0
  47. package/build/prebuilt/index.ts +28 -0
  48. package/build/src/abis/CustomErrors.json +3254 -0
  49. package/build/src/abis/DataStore.json +1440 -0
  50. package/build/src/abis/ERC721.json +442 -0
  51. package/build/src/abis/EventEmitter.json +2065 -0
  52. package/build/src/abis/ExchangeRouter.json +1598 -0
  53. package/build/src/abis/GMT.json +522 -0
  54. package/build/src/abis/GlpManager.json +591 -0
  55. package/build/src/abis/GlvReader.json +1424 -0
  56. package/build/src/abis/GlvRouter.json +612 -0
  57. package/build/src/abis/GmxMigrator.json +657 -0
  58. package/build/src/abis/GovToken.json +1121 -0
  59. package/build/src/abis/MintableBaseToken.json +696 -0
  60. package/build/src/abis/Multicall.json +333 -0
  61. package/build/src/abis/OrderBook.json +1997 -0
  62. package/build/src/abis/OrderBookReader.json +111 -0
  63. package/build/src/abis/OrderExecutor.json +122 -0
  64. package/build/src/abis/PositionManager.json +1165 -0
  65. package/build/src/abis/PositionRouter.json +2030 -0
  66. package/build/src/abis/Reader.json +355 -0
  67. package/build/src/abis/ReaderV2.json +630 -0
  68. package/build/src/abis/ReferralStorage.json +507 -0
  69. package/build/src/abis/RewardReader.json +86 -0
  70. package/build/src/abis/RewardRouter.json +769 -0
  71. package/build/src/abis/RewardTracker.json +918 -0
  72. package/build/src/abis/Router-v2.json +605 -0
  73. package/build/src/abis/Router.json +605 -0
  74. package/build/src/abis/SubaccountRouter.json +648 -0
  75. package/build/src/abis/SyntheticsReader.json +4577 -0
  76. package/build/src/abis/SyntheticsRouter.json +77 -0
  77. package/build/src/abis/Timelock.json +1737 -0
  78. package/build/src/abis/Token.json +345 -0
  79. package/build/src/abis/Treasury.json +411 -0
  80. package/build/src/abis/UniPool.json +89 -0
  81. package/build/src/abis/UniswapV2.json +1 -0
  82. package/build/src/abis/Vault.json +3220 -0
  83. package/build/src/abis/VaultReader.json +87 -0
  84. package/build/src/abis/VaultV2.json +3019 -0
  85. package/build/src/abis/VaultV2b.json +3220 -0
  86. package/build/src/abis/Vester.json +1031 -0
  87. package/build/src/abis/WETH.json +320 -0
  88. package/build/src/abis/YieldFarm.json +599 -0
  89. package/build/src/abis/YieldToken.json +560 -0
  90. package/build/src/configs/batch.d.ts +6 -0
  91. package/build/src/configs/batch.js +51 -0
  92. package/build/src/configs/chains.d.ts +37 -0
  93. package/build/src/configs/chains.js +90 -0
  94. package/build/src/configs/contracts.d.ts +2 -0
  95. package/build/src/configs/contracts.js +218 -0
  96. package/build/src/configs/dataStore.d.ts +149 -0
  97. package/build/src/configs/dataStore.js +276 -0
  98. package/build/src/configs/factors.d.ts +20 -0
  99. package/build/src/configs/factors.js +21 -0
  100. package/build/src/configs/markets.d.ts +8 -0
  101. package/build/src/configs/markets.js +528 -0
  102. package/build/src/configs/subgraph.d.ts +3 -0
  103. package/build/src/configs/subgraph.js +3 -0
  104. package/build/src/configs/tokens.d.ts +89 -0
  105. package/build/src/configs/tokens.js +1269 -0
  106. package/build/src/index.d.ts +44 -0
  107. package/build/src/index.js +245 -0
  108. package/build/src/modules/accounts/accounts.d.ts +5 -0
  109. package/build/src/modules/accounts/accounts.js +36 -0
  110. package/build/src/modules/accounts/accounts.spec.d.ts +1 -0
  111. package/build/src/modules/accounts/accounts.spec.js +7 -0
  112. package/build/src/modules/base.d.ts +9 -0
  113. package/build/src/modules/base.js +15 -0
  114. package/build/src/modules/markets/index.d.ts +26 -0
  115. package/build/src/modules/markets/index.js +339 -0
  116. package/build/src/modules/markets/markets.spec.d.ts +1 -0
  117. package/build/src/modules/markets/markets.spec.js +38 -0
  118. package/build/src/modules/markets/query-builders.d.ts +40 -0
  119. package/build/src/modules/markets/query-builders.js +379 -0
  120. package/build/src/modules/markets/types.d.ts +42 -0
  121. package/build/src/modules/markets/types.js +1 -0
  122. package/build/src/modules/oracle.d.ts +31 -0
  123. package/build/src/modules/oracle.js +53 -0
  124. package/build/src/modules/orders/orders.d.ts +60 -0
  125. package/build/src/modules/orders/orders.js +270 -0
  126. package/build/src/modules/orders/orders.spec.d.ts +1 -0
  127. package/build/src/modules/orders/orders.spec.js +16 -0
  128. package/build/src/modules/orders/transactions/cancelOrdersTxn.d.ts +6 -0
  129. package/build/src/modules/orders/transactions/cancelOrdersTxn.js +15 -0
  130. package/build/src/modules/orders/transactions/createDecreaseOrderTxn.d.ts +32 -0
  131. package/build/src/modules/orders/transactions/createDecreaseOrderTxn.js +98 -0
  132. package/build/src/modules/orders/transactions/createIncreaseOrderTxn.d.ts +77 -0
  133. package/build/src/modules/orders/transactions/createIncreaseOrderTxn.js +164 -0
  134. package/build/src/modules/orders/transactions/createSwapOrderTxn.d.ts +16 -0
  135. package/build/src/modules/orders/transactions/createSwapOrderTxn.js +97 -0
  136. package/build/src/modules/orders/transactions/createWrapOrUnwrapTxn.d.ts +6 -0
  137. package/build/src/modules/orders/transactions/createWrapOrUnwrapTxn.js +13 -0
  138. package/build/src/modules/orders/transactions/updateOrderTxn.d.ts +23 -0
  139. package/build/src/modules/orders/transactions/updateOrderTxn.js +44 -0
  140. package/build/src/modules/orders/utils.d.ts +248 -0
  141. package/build/src/modules/orders/utils.js +151 -0
  142. package/build/src/modules/positions/positions.d.ts +48 -0
  143. package/build/src/modules/positions/positions.js +563 -0
  144. package/build/src/modules/positions/positions.spec.d.ts +1 -0
  145. package/build/src/modules/positions/positions.spec.js +25 -0
  146. package/build/src/modules/tokens/tokens.d.ts +26 -0
  147. package/build/src/modules/tokens/tokens.js +132 -0
  148. package/build/src/modules/tokens/tokens.spec.d.ts +1 -0
  149. package/build/src/modules/tokens/tokens.spec.js +19 -0
  150. package/build/src/modules/trades/trades.d.ts +48 -0
  151. package/build/src/modules/trades/trades.js +390 -0
  152. package/build/src/modules/trades/trades.spec.d.ts +1 -0
  153. package/build/src/modules/trades/trades.spec.js +14 -0
  154. package/build/src/prebuilt/hashedMarketConfigKeys.json +3658 -0
  155. package/build/src/prebuilt/hashedMarketValuesKeys.json +1103 -0
  156. package/build/src/prebuilt/index.d.ts +14 -0
  157. package/build/src/prebuilt/index.js +9 -0
  158. package/build/src/types/amounts.d.ts +223 -0
  159. package/build/src/types/amounts.js +17 -0
  160. package/build/src/types/fees.d.ts +34 -0
  161. package/build/src/types/fees.js +1 -0
  162. package/build/src/types/markets.d.ts +143 -0
  163. package/build/src/types/markets.js +1 -0
  164. package/build/src/types/orders.d.ts +74 -0
  165. package/build/src/types/orders.js +33 -0
  166. package/build/src/types/positions.d.ts +53 -0
  167. package/build/src/types/positions.js +1 -0
  168. package/build/src/types/referrals.d.ts +124 -0
  169. package/build/src/types/referrals.js +9 -0
  170. package/build/src/types/sdk.d.ts +32 -0
  171. package/build/src/types/sdk.js +1 -0
  172. package/build/src/types/sidecarOrders.d.ts +54 -0
  173. package/build/src/types/sidecarOrders.js +1 -0
  174. package/build/src/types/syntheticsEvents.d.ts +88 -0
  175. package/build/src/types/syntheticsEvents.js +1 -0
  176. package/build/src/types/tokens.d.ts +89 -0
  177. package/build/src/types/tokens.js +1 -0
  178. package/build/src/types/trade.d.ts +223 -0
  179. package/build/src/types/trade.js +17 -0
  180. package/build/src/types/tradeHistory.d.ts +107 -0
  181. package/build/src/types/tradeHistory.js +8 -0
  182. package/build/src/utils/LruCache.d.ts +10 -0
  183. package/build/src/utils/LruCache.js +45 -0
  184. package/build/src/utils/bigmath.d.ts +7 -0
  185. package/build/src/utils/bigmath.js +23 -0
  186. package/build/src/utils/buildUrl.d.ts +1 -0
  187. package/build/src/utils/buildUrl.js +5 -0
  188. package/build/src/utils/callContract.d.ts +17 -0
  189. package/build/src/utils/callContract.js +133 -0
  190. package/build/src/utils/common.d.ts +2 -0
  191. package/build/src/utils/common.js +2 -0
  192. package/build/src/utils/fees/estimateOraclePriceCount.d.ts +6 -0
  193. package/build/src/utils/fees/estimateOraclePriceCount.js +19 -0
  194. package/build/src/utils/fees/executionFee.d.ts +59 -0
  195. package/build/src/utils/fees/executionFee.js +108 -0
  196. package/build/src/utils/fees/index.d.ts +29 -0
  197. package/build/src/utils/fees/index.js +89 -0
  198. package/build/src/utils/fees/priceImpact.d.ts +75 -0
  199. package/build/src/utils/fees/priceImpact.js +287 -0
  200. package/build/src/utils/graphqlFetcher.d.ts +1 -0
  201. package/build/src/utils/graphqlFetcher.js +18 -0
  202. package/build/src/utils/hash.d.ts +5 -0
  203. package/build/src/utils/hash.js +35 -0
  204. package/build/src/utils/marketKeysAndConfigs.d.ts +66 -0
  205. package/build/src/utils/marketKeysAndConfigs.js +257 -0
  206. package/build/src/utils/markets.d.ts +40 -0
  207. package/build/src/utils/markets.js +129 -0
  208. package/build/src/utils/multicall.d.ts +64 -0
  209. package/build/src/utils/multicall.js +116 -0
  210. package/build/src/utils/numbers.d.ts +9 -0
  211. package/build/src/utils/numbers.js +30 -0
  212. package/build/src/utils/objects.d.ts +18 -0
  213. package/build/src/utils/objects.js +30 -0
  214. package/build/src/utils/orders.d.ts +28 -0
  215. package/build/src/utils/orders.js +178 -0
  216. package/build/src/utils/positions.d.ts +60 -0
  217. package/build/src/utils/positions.js +133 -0
  218. package/build/src/utils/prices.d.ts +15 -0
  219. package/build/src/utils/prices.js +34 -0
  220. package/build/src/utils/referrals.d.ts +2 -0
  221. package/build/src/utils/referrals.js +27 -0
  222. package/build/src/utils/simulateExecuteOrder.d.ts +16 -0
  223. package/build/src/utils/simulateExecuteOrder.js +143 -0
  224. package/build/src/utils/slidingWindowFallbackSwitcher.d.ts +24 -0
  225. package/build/src/utils/slidingWindowFallbackSwitcher.js +40 -0
  226. package/build/src/utils/subgraph.d.ts +21 -0
  227. package/build/src/utils/subgraph.js +72 -0
  228. package/build/src/utils/swapStats.d.ts +35 -0
  229. package/build/src/utils/swapStats.js +197 -0
  230. package/build/src/utils/test.d.ts +2 -0
  231. package/build/src/utils/test.js +24 -0
  232. package/build/src/utils/tokens.d.ts +18 -0
  233. package/build/src/utils/tokens.js +64 -0
  234. package/build/src/utils/trade.d.ts +10 -0
  235. package/build/src/utils/trade.js +32 -0
  236. package/build/tsconfig.tsbuildinfo +1 -0
  237. package/package.json +96 -0
@@ -0,0 +1,132 @@
1
+ import { getContract } from "configs/contracts";
2
+ import { NATIVE_TOKEN_ADDRESS, createTokensMap, getToken, getTokensMap, getV2Tokens, getWrappedToken, } from "configs/tokens";
3
+ import Multicall from "abis/Multicall.json";
4
+ import Token from "abis/Token.json";
5
+ import { Module } from "../base";
6
+ import { parseContractPrice } from "utils/tokens";
7
+ export class Tokens extends Module {
8
+ constructor() {
9
+ super(...arguments);
10
+ this._tokensConfigs = undefined;
11
+ }
12
+ get tokensConfig() {
13
+ if (this._tokensConfigs) {
14
+ return this._tokensConfigs;
15
+ }
16
+ const tokenConfigs = this._tokensConfigs ??
17
+ (this.sdk.config.tokens ? createTokensMap(this.sdk.config.tokens) : getTokensMap(this.chainId));
18
+ this._tokensConfigs = tokenConfigs;
19
+ return tokenConfigs;
20
+ }
21
+ getTokenRecentPrices() {
22
+ return this.oracle.getTickers().then((priceItems) => {
23
+ const result = {};
24
+ priceItems.forEach((priceItem) => {
25
+ let tokenConfig;
26
+ try {
27
+ tokenConfig = getToken(this.chainId, priceItem.tokenAddress);
28
+ }
29
+ catch (e) {
30
+ // ignore unknown token errors
31
+ return;
32
+ }
33
+ result[tokenConfig.address] = {
34
+ minPrice: parseContractPrice(BigInt(priceItem.minPrice), tokenConfig.decimals),
35
+ maxPrice: parseContractPrice(BigInt(priceItem.maxPrice), tokenConfig.decimals),
36
+ };
37
+ });
38
+ const wrappedToken = getWrappedToken(this.chainId);
39
+ if (result[wrappedToken.address] && !result[NATIVE_TOKEN_ADDRESS]) {
40
+ result[NATIVE_TOKEN_ADDRESS] = result[wrappedToken.address];
41
+ }
42
+ return {
43
+ pricesData: result,
44
+ updatedAt: Date.now(),
45
+ };
46
+ });
47
+ }
48
+ getTokensBalances(account, tokensList) {
49
+ account = account || this.sdk.config.account;
50
+ tokensList = tokensList || getV2Tokens(this.chainId);
51
+ return this.sdk
52
+ .executeMulticall(tokensList.reduce((acc, token) => {
53
+ // Skip synthetic tokens
54
+ if (token.isSynthetic)
55
+ return acc;
56
+ const address = token.address;
57
+ if (address === NATIVE_TOKEN_ADDRESS) {
58
+ acc[address] = {
59
+ contractAddress: getContract(this.chainId, "Multicall"),
60
+ abi: Multicall.abi,
61
+ calls: {
62
+ balance: {
63
+ methodName: "getEthBalance",
64
+ params: [account],
65
+ },
66
+ },
67
+ };
68
+ }
69
+ else {
70
+ acc[address] = {
71
+ contractAddress: address,
72
+ abi: Token.abi,
73
+ calls: {
74
+ balance: {
75
+ methodName: "balanceOf",
76
+ params: [account],
77
+ },
78
+ },
79
+ };
80
+ }
81
+ return acc;
82
+ }, {}))
83
+ .then((res) => {
84
+ return Object.keys(res.data).reduce((tokenBalances, tokenAddress) => {
85
+ tokenBalances[tokenAddress] = res.data[tokenAddress].balance.returnValues[0];
86
+ return tokenBalances;
87
+ }, {});
88
+ });
89
+ }
90
+ getNativeToken() {
91
+ return this.tokensConfig[NATIVE_TOKEN_ADDRESS];
92
+ }
93
+ async getTokensData() {
94
+ const tokenConfigs = this.tokensConfig;
95
+ const [apiTokens, { pricesData, updatedAt: pricesUpdatedAt }] = await Promise.all([
96
+ this.sdk.oracle.getTokens(),
97
+ this.getTokenRecentPrices(),
98
+ ]);
99
+ const nativeToken = this.getNativeToken();
100
+ const tokens = [nativeToken, ...apiTokens];
101
+ const { balancesData } = this.account
102
+ ? await this.getTokensBalances(this.account, tokens)
103
+ : {
104
+ balancesData: {},
105
+ };
106
+ if (!pricesData) {
107
+ return {
108
+ tokensData: undefined,
109
+ pricesUpdatedAt: undefined,
110
+ };
111
+ }
112
+ return {
113
+ tokensData: tokens.reduce((acc, token) => {
114
+ const tokenAddress = token.address;
115
+ const prices = pricesData[tokenAddress];
116
+ const balance = balancesData?.[tokenAddress];
117
+ const tokenConfig = tokenConfigs[tokenAddress];
118
+ if (!prices) {
119
+ return acc;
120
+ }
121
+ acc[tokenAddress] = {
122
+ ...token,
123
+ ...tokenConfig,
124
+ prices,
125
+ balance,
126
+ };
127
+ return acc;
128
+ }, {}),
129
+ pricesUpdatedAt,
130
+ };
131
+ }
132
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,19 @@
1
+ import { arbitrumSdk } from "utils/test";
2
+ describe("Tokens", () => {
3
+ it("should be able to fetch tokens", async () => {
4
+ const response = await arbitrumSdk.oracle.getTokens();
5
+ expect(response).toBeDefined();
6
+ });
7
+ it("should be able to get tokens balances", async () => {
8
+ const response = await arbitrumSdk.tokens.getTokensBalances();
9
+ expect(response).toBeDefined();
10
+ });
11
+ it("should be able to get tokens prices", async () => {
12
+ const response = await arbitrumSdk.tokens.getTokenRecentPrices();
13
+ expect(response).toBeDefined();
14
+ });
15
+ it.only("should be able to get tokens data", async () => {
16
+ const response = await arbitrumSdk.tokens.getTokensData();
17
+ expect(response).toBeDefined();
18
+ });
19
+ });
@@ -0,0 +1,48 @@
1
+ import { MarketsInfoData } from "types/markets";
2
+ import { OrderType } from "types/orders";
3
+ import { TokensData } from "types/tokens";
4
+ import { TradeAction, TradeActionType } from "types/tradeHistory";
5
+ import { Address } from "viem";
6
+ import { Module } from "../base";
7
+ import { GmxSdk } from "index";
8
+ export type MarketFilterLongShortDirection = "long" | "short" | "swap" | "any";
9
+ export type MarketFilterLongShortItemData = {
10
+ marketAddress: Address | "any";
11
+ direction: MarketFilterLongShortDirection;
12
+ collateralAddress?: Address;
13
+ };
14
+ export declare class Trades extends Module {
15
+ getTradeHistory(p: {
16
+ forAllAccounts?: boolean;
17
+ pageSize: number;
18
+ fromTxTimestamp?: number;
19
+ toTxTimestamp?: number;
20
+ marketsInfoData: MarketsInfoData | undefined;
21
+ tokensData: TokensData | undefined;
22
+ pageIndex: number;
23
+ marketsDirectionsFilter?: MarketFilterLongShortItemData[];
24
+ orderEventCombinations?: {
25
+ eventName?: TradeActionType;
26
+ orderType?: OrderType;
27
+ isDepositOrWithdraw?: boolean;
28
+ }[];
29
+ }): Promise<TradeAction[]>;
30
+ }
31
+ export declare function fetchTradeActions({ sdk, pageIndex, pageSize, marketsDirectionsFilter, forAllAccounts, account, fromTxTimestamp, toTxTimestamp, orderEventCombinations, marketsInfoData, tokensData, }: {
32
+ sdk: GmxSdk;
33
+ pageIndex: number;
34
+ pageSize: number;
35
+ marketsDirectionsFilter: MarketFilterLongShortItemData[] | undefined;
36
+ forAllAccounts: boolean | undefined;
37
+ account: string | null | undefined;
38
+ fromTxTimestamp: number | undefined;
39
+ toTxTimestamp: number | undefined;
40
+ orderEventCombinations: {
41
+ eventName?: TradeActionType | undefined;
42
+ orderType?: OrderType | undefined;
43
+ isDepositOrWithdraw?: boolean | undefined;
44
+ }[] | undefined;
45
+ marketsInfoData: MarketsInfoData | undefined;
46
+ tokensData: TokensData | undefined;
47
+ }): Promise<TradeAction[]>;
48
+ export declare function bigNumberify(n?: bigint | string | null | undefined): bigint | undefined;
@@ -0,0 +1,390 @@
1
+ import { getSubgraphUrl } from "configs/subgraph";
2
+ import { getWrappedToken } from "configs/tokens";
3
+ import merge from "lodash/merge";
4
+ import { OrderType } from "types/orders";
5
+ import { TradeActionType } from "types/tradeHistory";
6
+ import graphqlFetcher from "utils/graphqlFetcher";
7
+ import { getByKey } from "utils/objects";
8
+ import { isIncreaseOrderType, isLimitOrderType, isSwapOrderType, isTriggerDecreaseOrderType } from "utils/orders";
9
+ import { buildFiltersBody } from "utils/subgraph";
10
+ import { getSwapPathOutputAddresses } from "utils/swapStats";
11
+ import { parseContractPrice } from "utils/tokens";
12
+ import { getAddress } from "viem";
13
+ import { Module } from "../base";
14
+ export class Trades extends Module {
15
+ async getTradeHistory(p) {
16
+ const chainId = this.chainId;
17
+ const account = this.account;
18
+ const { pageSize, forAllAccounts, fromTxTimestamp, toTxTimestamp, marketsDirectionsFilter, orderEventCombinations, marketsInfoData, pageIndex, tokensData, } = p;
19
+ const data = await fetchTradeActions({
20
+ sdk: this.sdk,
21
+ pageIndex,
22
+ pageSize,
23
+ marketsDirectionsFilter,
24
+ forAllAccounts,
25
+ account,
26
+ fromTxTimestamp,
27
+ toTxTimestamp,
28
+ orderEventCombinations,
29
+ marketsInfoData,
30
+ tokensData,
31
+ });
32
+ return data?.flat().filter(Boolean);
33
+ }
34
+ }
35
+ export async function fetchTradeActions({ sdk, pageIndex, pageSize, marketsDirectionsFilter = [], forAllAccounts, account, fromTxTimestamp, toTxTimestamp, orderEventCombinations, marketsInfoData, tokensData, }) {
36
+ const endpoint = getSubgraphUrl(sdk, "syntheticsStats");
37
+ const chainId = sdk.chainId;
38
+ if (!endpoint) {
39
+ return [];
40
+ }
41
+ const skip = pageIndex * pageSize;
42
+ const first = pageSize;
43
+ const nonSwapRelevantDefinedFiltersLowercased = marketsDirectionsFilter
44
+ .filter((filter) => filter.direction !== "swap" && filter.marketAddress !== "any")
45
+ .map((filter) => ({
46
+ marketAddress: filter.marketAddress.toLowerCase(),
47
+ direction: filter.direction,
48
+ collateralAddress: filter.collateralAddress?.toLowerCase(),
49
+ }));
50
+ const hasNonSwapRelevantDefinedMarkets = nonSwapRelevantDefinedFiltersLowercased.length > 0;
51
+ const pureDirectionFilters = marketsDirectionsFilter
52
+ .filter((filter) => filter.direction !== "any" && filter.marketAddress === "any")
53
+ .map((filter) => ({
54
+ marketAddress: filter.marketAddress.toLowerCase(),
55
+ direction: filter.direction,
56
+ }));
57
+ const hasPureDirectionFilters = pureDirectionFilters.length > 0;
58
+ const swapRelevantDefinedMarketsLowercased = marketsDirectionsFilter
59
+ .filter((filter) => (filter.direction === "any" || filter.direction === "swap") && filter.marketAddress !== "any")
60
+ .map((filter) => filter.marketAddress.toLowerCase());
61
+ const hasSwapRelevantDefinedMarkets = swapRelevantDefinedMarketsLowercased.length > 0;
62
+ const filtersStr = buildFiltersBody({
63
+ and: [
64
+ {
65
+ account: forAllAccounts ? undefined : account.toLowerCase(),
66
+ transaction: {
67
+ timestamp_gte: fromTxTimestamp,
68
+ timestamp_lte: toTxTimestamp,
69
+ },
70
+ },
71
+ {
72
+ or: !hasPureDirectionFilters
73
+ ? undefined
74
+ : pureDirectionFilters.map((filter) => filter.direction === "swap"
75
+ ? {
76
+ orderType_in: [OrderType.LimitSwap, OrderType.MarketSwap],
77
+ }
78
+ : {
79
+ isLong: filter.direction === "long",
80
+ orderType_not_in: [OrderType.LimitSwap, OrderType.MarketSwap],
81
+ }),
82
+ },
83
+ {
84
+ or: [
85
+ // For non-swap orders
86
+ {
87
+ and: !hasNonSwapRelevantDefinedMarkets
88
+ ? undefined
89
+ : [
90
+ {
91
+ orderType_not_in: [OrderType.LimitSwap, OrderType.MarketSwap],
92
+ },
93
+ {
94
+ or: nonSwapRelevantDefinedFiltersLowercased.map((filter) => ({
95
+ marketAddress: filter.marketAddress === "any" ? undefined : filter.marketAddress,
96
+ isLong: filter.direction === "any" ? undefined : filter.direction === "long",
97
+ // Collateral filtering is done outside of graphql on the client
98
+ })),
99
+ },
100
+ ],
101
+ },
102
+ // For defined markets on swap orders
103
+ {
104
+ and: !hasSwapRelevantDefinedMarkets
105
+ ? undefined
106
+ : [
107
+ {
108
+ orderType_in: [OrderType.LimitSwap, OrderType.MarketSwap],
109
+ },
110
+ {
111
+ or: [
112
+ // Source token is not in swap path so we add it to the or filter
113
+ {
114
+ marketAddress_in: swapRelevantDefinedMarketsLowercased,
115
+ },
116
+ ].concat(swapRelevantDefinedMarketsLowercased.map((marketAddress) => ({
117
+ swapPath_contains: [marketAddress],
118
+ })) || []),
119
+ },
120
+ ],
121
+ },
122
+ ],
123
+ },
124
+ {
125
+ or: orderEventCombinations?.map((combination) => {
126
+ let sizeDeltaUsdCondition = {};
127
+ if (combination.orderType !== undefined &&
128
+ [OrderType.MarketDecrease, OrderType.MarketIncrease].includes(combination.orderType)) {
129
+ if (combination.isDepositOrWithdraw) {
130
+ sizeDeltaUsdCondition = { sizeDeltaUsd: 0 };
131
+ }
132
+ else {
133
+ sizeDeltaUsdCondition = { sizeDeltaUsd_not: 0 };
134
+ }
135
+ }
136
+ return merge({
137
+ eventName: combination.eventName,
138
+ orderType: combination.orderType,
139
+ }, sizeDeltaUsdCondition);
140
+ }),
141
+ },
142
+ {
143
+ // We do not show create liquidation orders in the trade history, thus we filter it out
144
+ // ... && not (liquidation && orderCreated) === ... && (not liquidation || not orderCreated)
145
+ or: [{ orderType_not: OrderType.Liquidation }, { eventName_not: TradeActionType.OrderCreated }],
146
+ },
147
+ ],
148
+ });
149
+ const whereClause = `where: ${filtersStr}`;
150
+ const query = `{
151
+ tradeActions(
152
+ skip: ${skip},
153
+ first: ${first},
154
+ orderBy: transaction__timestamp,
155
+ orderDirection: desc,
156
+ ${whereClause}
157
+ ) {
158
+ id
159
+ eventName
160
+
161
+ account
162
+ marketAddress
163
+ swapPath
164
+ initialCollateralTokenAddress
165
+
166
+ initialCollateralDeltaAmount
167
+ sizeDeltaUsd
168
+ triggerPrice
169
+ acceptablePrice
170
+ executionPrice
171
+ minOutputAmount
172
+ executionAmountOut
173
+
174
+ priceImpactUsd
175
+ priceImpactDiffUsd
176
+ positionFeeAmount
177
+ borrowingFeeAmount
178
+ fundingFeeAmount
179
+ pnlUsd
180
+ basePnlUsd
181
+
182
+ collateralTokenPriceMax
183
+ collateralTokenPriceMin
184
+
185
+ indexTokenPriceMin
186
+ indexTokenPriceMax
187
+
188
+ orderType
189
+ orderKey
190
+ isLong
191
+ shouldUnwrapNativeToken
192
+
193
+ reason
194
+ reasonBytes
195
+
196
+ transaction {
197
+ timestamp
198
+ hash
199
+ }
200
+ }
201
+ }`;
202
+ const result = await graphqlFetcher(endpoint, query);
203
+ const rawTradeActions = result?.tradeActions || [];
204
+ if (!marketsInfoData || !tokensData) {
205
+ return [];
206
+ }
207
+ const wrappedToken = getWrappedToken(chainId);
208
+ const transformer = createRawTradeActionTransformer(marketsInfoData, wrappedToken, tokensData);
209
+ let tradeActions = rawTradeActions.map(transformer).filter(Boolean);
210
+ const collateralFilterTree = {
211
+ long: {},
212
+ short: {},
213
+ };
214
+ let hasCollateralFilter = false;
215
+ marketsDirectionsFilter.forEach((filter) => {
216
+ if (filter.direction === "any" || filter.direction === "swap" || !filter.collateralAddress) {
217
+ return;
218
+ }
219
+ if (!collateralFilterTree[filter.direction]) {
220
+ collateralFilterTree[filter.direction] = {};
221
+ }
222
+ if (!collateralFilterTree[filter.direction][filter.marketAddress]) {
223
+ collateralFilterTree[filter.direction][filter.marketAddress] = {};
224
+ }
225
+ hasCollateralFilter = true;
226
+ collateralFilterTree[filter.direction][filter.marketAddress][filter.collateralAddress] = true;
227
+ });
228
+ // Filter out trade actions that do not match the collateral filter
229
+ // We do this on the client side because the collateral filtering is too complex to be done in the graphql query
230
+ if (hasCollateralFilter) {
231
+ tradeActions = tradeActions.filter((tradeAction) => {
232
+ // All necessary filters for swaps are already applied in the graphql query
233
+ if (isSwapOrderType(tradeAction.orderType)) {
234
+ return true;
235
+ }
236
+ const positionTradeAction = tradeAction;
237
+ let collateralMatch = true;
238
+ const desiredCollateralAddresses = collateralFilterTree[positionTradeAction.isLong ? "long" : "short"]?.[positionTradeAction.marketAddress];
239
+ if (isLimitOrderType(tradeAction.orderType)) {
240
+ const wrappedToken = getWrappedToken(chainId);
241
+ if (!marketsInfoData) {
242
+ collateralMatch = true;
243
+ }
244
+ else {
245
+ const { outTokenAddress } = getSwapPathOutputAddresses({
246
+ marketsInfoData,
247
+ initialCollateralAddress: positionTradeAction.initialCollateralTokenAddress,
248
+ isIncrease: isIncreaseOrderType(tradeAction.orderType),
249
+ shouldUnwrapNativeToken: positionTradeAction.shouldUnwrapNativeToken,
250
+ swapPath: tradeAction.swapPath,
251
+ wrappedNativeTokenAddress: wrappedToken.address,
252
+ });
253
+ collateralMatch =
254
+ outTokenAddress !== undefined && Boolean(desiredCollateralAddresses?.[outTokenAddress]);
255
+ }
256
+ }
257
+ else if (isTriggerDecreaseOrderType(tradeAction.orderType)) {
258
+ collateralMatch = Boolean(desiredCollateralAddresses?.[positionTradeAction.initialCollateralTokenAddress]);
259
+ }
260
+ return collateralMatch;
261
+ });
262
+ }
263
+ return tradeActions;
264
+ }
265
+ function createRawTradeActionTransformer(marketsInfoData, wrappedToken, tokensData) {
266
+ return (rawAction) => {
267
+ const orderType = Number(rawAction.orderType);
268
+ console.log("-----------> ORDER TYPE", orderType);
269
+ if (isSwapOrderType(orderType)) {
270
+ const initialCollateralTokenAddress = getAddress(rawAction.initialCollateralTokenAddress);
271
+ const swapPath = rawAction.swapPath.map((address) => getAddress(address));
272
+ const swapPathOutputAddresses = getSwapPathOutputAddresses({
273
+ marketsInfoData,
274
+ swapPath,
275
+ initialCollateralAddress: initialCollateralTokenAddress,
276
+ wrappedNativeTokenAddress: wrappedToken.address,
277
+ shouldUnwrapNativeToken: rawAction.shouldUnwrapNativeToken,
278
+ isIncrease: false,
279
+ });
280
+ const initialCollateralToken = getByKey(tokensData, initialCollateralTokenAddress);
281
+ const targetCollateralToken = getByKey(tokensData, swapPathOutputAddresses.outTokenAddress);
282
+ if (!initialCollateralToken || !targetCollateralToken) {
283
+ return undefined;
284
+ }
285
+ const tradeAction = {
286
+ id: rawAction.id,
287
+ eventName: rawAction.eventName,
288
+ account: rawAction.account,
289
+ swapPath,
290
+ orderType,
291
+ orderKey: rawAction.orderKey,
292
+ initialCollateralTokenAddress: rawAction.initialCollateralTokenAddress,
293
+ initialCollateralDeltaAmount: bigNumberify(rawAction.initialCollateralDeltaAmount),
294
+ minOutputAmount: bigNumberify(rawAction.minOutputAmount),
295
+ executionAmountOut: rawAction.executionAmountOut ? bigNumberify(rawAction.executionAmountOut) : undefined,
296
+ shouldUnwrapNativeToken: rawAction.shouldUnwrapNativeToken,
297
+ targetCollateralToken,
298
+ initialCollateralToken,
299
+ transaction: rawAction.transaction,
300
+ reason: rawAction.reason,
301
+ reasonBytes: rawAction.reasonBytes,
302
+ };
303
+ return tradeAction;
304
+ }
305
+ else {
306
+ const marketAddress = getAddress(rawAction.marketAddress);
307
+ const marketInfo = getByKey(marketsInfoData, marketAddress);
308
+ const indexToken = marketInfo?.indexToken;
309
+ const initialCollateralTokenAddress = getAddress(rawAction.initialCollateralTokenAddress);
310
+ const swapPath = rawAction.swapPath.map((address) => getAddress(address));
311
+ const swapPathOutputAddresses = getSwapPathOutputAddresses({
312
+ marketsInfoData,
313
+ swapPath,
314
+ initialCollateralAddress: initialCollateralTokenAddress,
315
+ wrappedNativeTokenAddress: wrappedToken.address,
316
+ shouldUnwrapNativeToken: rawAction.shouldUnwrapNativeToken,
317
+ isIncrease: isIncreaseOrderType(rawAction.orderType),
318
+ });
319
+ const initialCollateralToken = getByKey(tokensData, initialCollateralTokenAddress);
320
+ const targetCollateralToken = getByKey(tokensData, swapPathOutputAddresses.outTokenAddress);
321
+ if (!marketInfo || !indexToken || !initialCollateralToken || !targetCollateralToken) {
322
+ console.log("VI UU VII VUUU----------->", marketInfo, indexToken, initialCollateralToken, targetCollateralToken);
323
+ return undefined;
324
+ }
325
+ const tradeAction = {
326
+ id: rawAction.id,
327
+ eventName: rawAction.eventName,
328
+ account: rawAction.account,
329
+ marketAddress,
330
+ marketInfo,
331
+ indexToken,
332
+ swapPath,
333
+ initialCollateralTokenAddress,
334
+ initialCollateralToken,
335
+ targetCollateralToken,
336
+ initialCollateralDeltaAmount: bigNumberify(rawAction.initialCollateralDeltaAmount),
337
+ sizeDeltaUsd: bigNumberify(rawAction.sizeDeltaUsd),
338
+ triggerPrice: rawAction.triggerPrice
339
+ ? parseContractPrice(bigNumberify(rawAction.triggerPrice), indexToken.decimals)
340
+ : undefined,
341
+ acceptablePrice: parseContractPrice(bigNumberify(rawAction.acceptablePrice), indexToken.decimals),
342
+ executionPrice: rawAction.executionPrice
343
+ ? parseContractPrice(bigNumberify(rawAction.executionPrice), indexToken.decimals)
344
+ : undefined,
345
+ minOutputAmount: bigNumberify(rawAction.minOutputAmount),
346
+ collateralTokenPriceMax: rawAction.collateralTokenPriceMax
347
+ ? parseContractPrice(bigNumberify(rawAction.collateralTokenPriceMax), initialCollateralToken.decimals)
348
+ : undefined,
349
+ collateralTokenPriceMin: rawAction.collateralTokenPriceMin
350
+ ? parseContractPrice(bigNumberify(rawAction.collateralTokenPriceMin), initialCollateralToken.decimals)
351
+ : undefined,
352
+ indexTokenPriceMin: rawAction.indexTokenPriceMin
353
+ ? parseContractPrice(BigInt(rawAction.indexTokenPriceMin), indexToken.decimals)
354
+ : undefined,
355
+ indexTokenPriceMax: rawAction.indexTokenPriceMax
356
+ ? parseContractPrice(BigInt(rawAction.indexTokenPriceMax), indexToken.decimals)
357
+ : undefined,
358
+ orderType,
359
+ orderKey: rawAction.orderKey,
360
+ isLong: rawAction.isLong,
361
+ pnlUsd: rawAction.pnlUsd ? BigInt(rawAction.pnlUsd) : undefined,
362
+ basePnlUsd: rawAction.basePnlUsd ? BigInt(rawAction.basePnlUsd) : undefined,
363
+ priceImpactDiffUsd: rawAction.priceImpactDiffUsd ? BigInt(rawAction.priceImpactDiffUsd) : undefined,
364
+ priceImpactUsd: rawAction.priceImpactUsd ? BigInt(rawAction.priceImpactUsd) : undefined,
365
+ positionFeeAmount: rawAction.positionFeeAmount ? BigInt(rawAction.positionFeeAmount) : undefined,
366
+ borrowingFeeAmount: rawAction.borrowingFeeAmount ? BigInt(rawAction.borrowingFeeAmount) : undefined,
367
+ fundingFeeAmount: rawAction.fundingFeeAmount ? BigInt(rawAction.fundingFeeAmount) : undefined,
368
+ reason: rawAction.reason,
369
+ reasonBytes: rawAction.reasonBytes,
370
+ transaction: rawAction.transaction,
371
+ shouldUnwrapNativeToken: rawAction.shouldUnwrapNativeToken,
372
+ };
373
+ return tradeAction;
374
+ }
375
+ };
376
+ }
377
+ export function bigNumberify(n) {
378
+ try {
379
+ if (n === undefined)
380
+ throw new Error("n is undefined");
381
+ if (n === null)
382
+ throw new Error("n is null");
383
+ return BigInt(n);
384
+ }
385
+ catch (e) {
386
+ // eslint-disable-next-line no-console
387
+ console.error("bigNumberify error", e);
388
+ return undefined;
389
+ }
390
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,14 @@
1
+ import { arbitrumSdk } from "utils/test";
2
+ describe("Trades", () => {
3
+ it("should be able to get positions", async () => {
4
+ const { marketsInfoData, tokensData } = await arbitrumSdk.markets.getMarketsInfo();
5
+ const trades = await arbitrumSdk.trades.getTradeHistory({
6
+ forAllAccounts: false,
7
+ pageSize: 50,
8
+ marketsInfoData,
9
+ tokensData,
10
+ pageIndex: 0,
11
+ });
12
+ expect(trades).toBeDefined();
13
+ });
14
+ });