@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,107 @@
1
+ import { MarketInfo } from "./markets";
2
+ import { OrderType } from "./orders";
3
+ import { TokenData } from "./tokens";
4
+ export declare enum TradeActionType {
5
+ OrderCreated = "OrderCreated",
6
+ OrderExecuted = "OrderExecuted",
7
+ OrderCancelled = "OrderCancelled",
8
+ OrderUpdated = "OrderUpdated",
9
+ OrderFrozen = "OrderFrozen"
10
+ }
11
+ export type RawTradeAction = {
12
+ id: string;
13
+ eventName: TradeActionType;
14
+ account: string;
15
+ marketAddress?: string;
16
+ swapPath?: string[];
17
+ initialCollateralTokenAddress?: string;
18
+ initialCollateralDeltaAmount?: string;
19
+ sizeDeltaUsd?: string;
20
+ triggerPrice?: string;
21
+ acceptablePrice?: string;
22
+ executionPrice?: string;
23
+ minOutputAmount?: string;
24
+ executionAmountOut?: string;
25
+ priceImpactDiffUsd?: string;
26
+ priceImpactUsd?: string;
27
+ positionFeeAmount?: string;
28
+ borrowingFeeAmount?: string;
29
+ fundingFeeAmount?: string;
30
+ pnlUsd?: string;
31
+ basePnlUsd?: string;
32
+ collateralTokenPriceMax?: string;
33
+ collateralTokenPriceMin?: string;
34
+ indexTokenPriceMin?: string;
35
+ indexTokenPriceMax?: string;
36
+ orderType: OrderType;
37
+ orderKey: string;
38
+ isLong?: boolean;
39
+ shouldUnwrapNativeToken?: boolean;
40
+ reason?: string;
41
+ reasonBytes?: string | Uint8Array;
42
+ transaction: {
43
+ timestamp: number;
44
+ hash: string;
45
+ };
46
+ };
47
+ export type PositionTradeAction = {
48
+ id: string;
49
+ eventName: TradeActionType;
50
+ marketInfo: MarketInfo;
51
+ marketAddress: string;
52
+ account: string;
53
+ initialCollateralTokenAddress: string;
54
+ initialCollateralToken: TokenData;
55
+ targetCollateralToken: TokenData;
56
+ indexToken: TokenData;
57
+ swapPath: string[];
58
+ initialCollateralDeltaAmount: bigint;
59
+ sizeDeltaUsd: bigint;
60
+ indexTokenPriceMin?: bigint;
61
+ indexTokenPriceMax?: bigint;
62
+ triggerPrice?: bigint;
63
+ acceptablePrice: bigint;
64
+ executionPrice?: bigint;
65
+ collateralTokenPriceMin?: bigint;
66
+ collateralTokenPriceMax?: bigint;
67
+ minOutputAmount: bigint;
68
+ priceImpactUsd?: bigint;
69
+ priceImpactDiffUsd?: bigint;
70
+ positionFeeAmount?: bigint;
71
+ borrowingFeeAmount?: bigint;
72
+ fundingFeeAmount?: bigint;
73
+ pnlUsd?: bigint;
74
+ basePnlUsd?: bigint;
75
+ orderType: OrderType;
76
+ orderKey: string;
77
+ isLong: boolean;
78
+ reason?: string;
79
+ reasonBytes?: string | Uint8Array;
80
+ shouldUnwrapNativeToken: boolean;
81
+ transaction: {
82
+ timestamp: number;
83
+ hash: string;
84
+ };
85
+ };
86
+ export type SwapTradeAction = {
87
+ id: string;
88
+ account: string;
89
+ eventName: TradeActionType;
90
+ initialCollateralTokenAddress: string;
91
+ initialCollateralToken: TokenData;
92
+ targetCollateralToken: TokenData;
93
+ shouldUnwrapNativeToken: boolean;
94
+ swapPath: string[];
95
+ initialCollateralDeltaAmount: bigint;
96
+ minOutputAmount: bigint;
97
+ executionAmountOut?: bigint;
98
+ orderType: OrderType;
99
+ orderKey: string;
100
+ reason?: string;
101
+ reasonBytes?: string | Uint8Array;
102
+ transaction: {
103
+ timestamp: number;
104
+ hash: string;
105
+ };
106
+ };
107
+ export type TradeAction = PositionTradeAction | SwapTradeAction;
@@ -0,0 +1,8 @@
1
+ export var TradeActionType;
2
+ (function (TradeActionType) {
3
+ TradeActionType["OrderCreated"] = "OrderCreated";
4
+ TradeActionType["OrderExecuted"] = "OrderExecuted";
5
+ TradeActionType["OrderCancelled"] = "OrderCancelled";
6
+ TradeActionType["OrderUpdated"] = "OrderUpdated";
7
+ TradeActionType["OrderFrozen"] = "OrderFrozen";
8
+ })(TradeActionType || (TradeActionType = {}));
@@ -0,0 +1,10 @@
1
+ export declare class LRUCache<T> {
2
+ private capacity;
3
+ private cache;
4
+ private recentKeys;
5
+ constructor(capacity: number);
6
+ has(key: string): boolean;
7
+ get(key: string): T | undefined;
8
+ set(key: string, value: T): void;
9
+ private updateRecentKeys;
10
+ }
@@ -0,0 +1,45 @@
1
+ export class LRUCache {
2
+ constructor(capacity) {
3
+ this.capacity = capacity;
4
+ this.cache = new Map();
5
+ this.recentKeys = [];
6
+ }
7
+ has(key) {
8
+ return this.cache.has(key);
9
+ }
10
+ get(key) {
11
+ if (this.cache.has(key)) {
12
+ // Update recentKeys to reflect the usage
13
+ this.updateRecentKeys(key);
14
+ return this.cache.get(key);
15
+ }
16
+ return undefined;
17
+ }
18
+ set(key, value) {
19
+ if (typeof key !== "string") {
20
+ throw new Error("Key must be a string");
21
+ }
22
+ // If key exists, update its value and move it to the front of recentKeys
23
+ if (this.cache.has(key)) {
24
+ this.cache.set(key, value);
25
+ this.updateRecentKeys(key);
26
+ }
27
+ else {
28
+ // If capacity is reached, remove least recently used item
29
+ if (this.cache.size === this.capacity) {
30
+ const lruKey = this.recentKeys.shift();
31
+ if (lruKey) {
32
+ this.cache.delete(lruKey);
33
+ }
34
+ }
35
+ // Add the new key-value pair to the cache and recentKeys
36
+ this.cache.set(key, value);
37
+ this.recentKeys.push(key);
38
+ }
39
+ }
40
+ updateRecentKeys(key) {
41
+ // Move the key to the end (most recently used) of recentKeys
42
+ this.recentKeys = this.recentKeys.filter((k) => k !== key);
43
+ this.recentKeys.push(key);
44
+ }
45
+ }
@@ -0,0 +1,7 @@
1
+ export declare const bigMath: {
2
+ abs(x: bigint): bigint;
3
+ mulDiv(x: bigint, y: bigint, z: bigint): bigint;
4
+ max(max: bigint, ...rest: bigint[]): bigint;
5
+ min(min: bigint, ...rest: bigint[]): bigint;
6
+ avg(...values: (bigint | undefined)[]): bigint;
7
+ };
@@ -0,0 +1,23 @@
1
+ export const bigMath = {
2
+ abs(x) {
3
+ return x < 0n ? -x : x;
4
+ },
5
+ mulDiv(x, y, z) {
6
+ return (x * y) / z;
7
+ },
8
+ max(max, ...rest) {
9
+ return rest.reduce((currentMax, val) => (currentMax < val ? val : currentMax), max);
10
+ },
11
+ min(min, ...rest) {
12
+ return rest.reduce((currentMin, val) => (currentMin > val ? val : currentMin), min);
13
+ },
14
+ avg(...values) {
15
+ let sum = 0n;
16
+ for (const value of values) {
17
+ if (value !== undefined) {
18
+ sum += value;
19
+ }
20
+ }
21
+ return sum / BigInt(values.length);
22
+ },
23
+ };
@@ -0,0 +1 @@
1
+ export declare function buildUrl(baseUrl: string, path: string, query?: Record<string, string | number | boolean | undefined>): string;
@@ -0,0 +1,5 @@
1
+ import queryString from "query-string";
2
+ export function buildUrl(baseUrl, path, query) {
3
+ const qs = query ? `?${queryString.stringify(query)}` : "";
4
+ return `${baseUrl}${path}${qs}`;
5
+ }
@@ -0,0 +1,17 @@
1
+ import { Abi, Address, PublicClient } from "viem";
2
+ import type { GmxSdk } from "../index";
3
+ export declare function getGasPrice(client: PublicClient, chainId: number): Promise<{
4
+ maxFeePerGas: bigint;
5
+ maxPriorityFeePerGas: bigint;
6
+ gasPrice?: undefined;
7
+ } | {
8
+ gasPrice: bigint;
9
+ maxFeePerGas?: undefined;
10
+ maxPriorityFeePerGas?: undefined;
11
+ }>;
12
+ export declare function getGasLimit(client: PublicClient, account: Address, contractAddress: Address, abi: Abi, method: string, params?: any[], value?: bigint | number): Promise<bigint>;
13
+ export interface CallContractOpts {
14
+ value?: bigint | number;
15
+ gasLimit?: bigint | number;
16
+ }
17
+ export declare function callContract(sdk: GmxSdk, contractAddress: Address, abi: Abi, method: string, params: any[], opts?: CallContractOpts): Promise<`0x${string}`>;
@@ -0,0 +1,133 @@
1
+ import { encodeFunctionData, withRetry } from "viem";
2
+ import { GAS_PRICE_BUFFER_MAP, GAS_PRICE_PREMIUM_MAP, getChain, MAX_FEE_PER_GAS_MAP, MAX_PRIORITY_FEE_PER_GAS_MAP, } from "configs/chains";
3
+ import { BASIS_POINTS_DIVISOR_BIGINT } from "configs/factors";
4
+ import { bigMath } from "./bigmath";
5
+ export async function getGasPrice(client, chainId) {
6
+ let maxFeePerGas = MAX_FEE_PER_GAS_MAP[chainId];
7
+ const premium = GAS_PRICE_PREMIUM_MAP[chainId] || 0n;
8
+ const feeData = await withRetry(() => client.estimateFeesPerGas({
9
+ type: "legacy",
10
+ chain: getChain(chainId),
11
+ }), {
12
+ delay: 200,
13
+ retryCount: 2,
14
+ shouldRetry: ({ error }) => {
15
+ const isInvalidBlockError = error?.message?.includes("invalid value for value.hash");
16
+ return isInvalidBlockError;
17
+ },
18
+ });
19
+ const gasPrice = feeData.gasPrice;
20
+ if (maxFeePerGas) {
21
+ if (gasPrice !== undefined && gasPrice !== null) {
22
+ maxFeePerGas = bigMath.max(gasPrice, maxFeePerGas);
23
+ }
24
+ // Fetch the latest block to get baseFeePerGas for EIP-1559 fee data
25
+ const block = await client.getBlock({ blockTag: "pending" });
26
+ if (block.baseFeePerGas !== undefined && block.baseFeePerGas !== null) {
27
+ const baseFeePerGas = block.baseFeePerGas;
28
+ const maxPriorityFeePerGas = bigMath.max(MAX_PRIORITY_FEE_PER_GAS_MAP[chainId] ?? 0n, premium);
29
+ // Calculate maxFeePerGas
30
+ const calculatedMaxFeePerGas = baseFeePerGas + maxPriorityFeePerGas + premium;
31
+ return {
32
+ maxFeePerGas: bigMath.max(maxFeePerGas, calculatedMaxFeePerGas),
33
+ maxPriorityFeePerGas: maxPriorityFeePerGas + premium,
34
+ };
35
+ }
36
+ }
37
+ if (gasPrice === null || gasPrice === undefined) {
38
+ throw new Error("Can't fetch gas price");
39
+ }
40
+ const bufferBps = GAS_PRICE_BUFFER_MAP[chainId] || 0n;
41
+ const buffer = bigMath.mulDiv(gasPrice, bufferBps, BASIS_POINTS_DIVISOR_BIGINT);
42
+ return {
43
+ gasPrice: gasPrice + buffer + premium,
44
+ };
45
+ }
46
+ export async function getGasLimit(client, account, contractAddress, abi, method, params = [], value) {
47
+ const defaultValue = 0n;
48
+ if (value === undefined || value === null) {
49
+ value = defaultValue;
50
+ }
51
+ let gasLimit = 0n;
52
+ const data = encodeFunctionData({
53
+ abi,
54
+ functionName: method,
55
+ args: params,
56
+ });
57
+ try {
58
+ const estimateGasParams = {
59
+ to: contractAddress,
60
+ data,
61
+ value: BigInt(value),
62
+ account,
63
+ };
64
+ gasLimit = await client.estimateGas(estimateGasParams);
65
+ }
66
+ catch (error) {
67
+ // This call should throw another error instead of the `error`
68
+ const callParams = {
69
+ to: contractAddress,
70
+ data,
71
+ value: BigInt(value),
72
+ };
73
+ if (client.account) {
74
+ callParams.account = client.account;
75
+ }
76
+ await client.call(callParams);
77
+ // If not, we throw the original estimateGas error
78
+ throw error;
79
+ }
80
+ if (gasLimit < 22000n) {
81
+ gasLimit = 22000n;
82
+ }
83
+ // Add a 10% buffer to the gas limit
84
+ return (gasLimit * 11n) / 10n;
85
+ }
86
+ export async function callContract(sdk, contractAddress, abi, method, params, opts = {}) {
87
+ const txnOpts = {};
88
+ const chain = getChain(sdk.chainId);
89
+ if (opts.value) {
90
+ txnOpts.value = BigInt(opts.value);
91
+ }
92
+ const clients = [sdk.publicClient];
93
+ const data = encodeFunctionData({
94
+ abi,
95
+ functionName: method,
96
+ args: params,
97
+ });
98
+ const txnCalls = clients.map(async (client) => {
99
+ const txnInstance = { ...txnOpts };
100
+ async function retrieveGasLimit() {
101
+ return opts.gasLimit
102
+ ? BigInt(opts.gasLimit)
103
+ : await getGasLimit(client, sdk.config.account, contractAddress, abi, method, params, opts.value !== undefined ? BigInt(opts.value) : undefined);
104
+ }
105
+ const gasLimitPromise = retrieveGasLimit().then((gasLimit) => {
106
+ txnInstance.gas = gasLimit;
107
+ });
108
+ const gasPriceDataPromise = getGasPrice(sdk.publicClient, sdk.chainId).then((gasPriceData) => {
109
+ if (gasPriceData.gasPrice !== undefined) {
110
+ txnInstance.gasPrice = gasPriceData.gasPrice;
111
+ }
112
+ else {
113
+ txnInstance.maxFeePerGas = gasPriceData.maxFeePerGas;
114
+ txnInstance.maxPriorityFeePerGas = gasPriceData.maxPriorityFeePerGas;
115
+ }
116
+ });
117
+ await Promise.all([gasLimitPromise, gasPriceDataPromise]);
118
+ return sdk.walletClient.sendTransaction({
119
+ to: contractAddress,
120
+ data,
121
+ chain,
122
+ ...txnInstance,
123
+ });
124
+ });
125
+ const res = await Promise.any(txnCalls).catch((error) => {
126
+ if (error.errors && error.errors.length > 1) {
127
+ // eslint-disable-next-line no-console
128
+ console.error("All transactions failed", ...error.errors);
129
+ }
130
+ throw error.errors ? error.errors[0] : error;
131
+ });
132
+ return res;
133
+ }
@@ -0,0 +1,2 @@
1
+ export declare const sleep: (ms: number) => Promise<unknown>;
2
+ export declare const TIMEZONE_OFFSET_SEC: number;
@@ -0,0 +1,2 @@
1
+ export const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
2
+ export const TIMEZONE_OFFSET_SEC = -new Date().getTimezoneOffset() * 60;
@@ -0,0 +1,6 @@
1
+ export declare function estimateDepositOraclePriceCount(swapsCount: number): bigint;
2
+ export declare function estimateWithdrawalOraclePriceCount(swapsCount: number): bigint;
3
+ export declare function estimateOrderOraclePriceCount(swapsCount: number): bigint;
4
+ export declare function estimateShiftOraclePriceCount(): bigint;
5
+ export declare function estimateGlvDepositOraclePriceCount(marketCount: bigint, swapsCount?: bigint): bigint;
6
+ export declare function estimateGlvWithdrawalOraclePriceCount(marketCount: bigint, swapsCount?: bigint): bigint;
@@ -0,0 +1,19 @@
1
+ // @see https://github.com/gmx-io/gmx-synthetics/blob/6ed9be061d8fcc0dc7bc5d34dee3bf091408a1bf/contracts/gas/GasUtils.sol#L218-L234
2
+ export function estimateDepositOraclePriceCount(swapsCount) {
3
+ return 3n + BigInt(swapsCount);
4
+ }
5
+ export function estimateWithdrawalOraclePriceCount(swapsCount) {
6
+ return 3n + BigInt(swapsCount);
7
+ }
8
+ export function estimateOrderOraclePriceCount(swapsCount) {
9
+ return 3n + BigInt(swapsCount);
10
+ }
11
+ export function estimateShiftOraclePriceCount() {
12
+ return 4n;
13
+ }
14
+ export function estimateGlvDepositOraclePriceCount(marketCount, swapsCount = 0n) {
15
+ return 2n + marketCount + swapsCount;
16
+ }
17
+ export function estimateGlvWithdrawalOraclePriceCount(marketCount, swapsCount = 0n) {
18
+ return 2n + marketCount + swapsCount;
19
+ }
@@ -0,0 +1,59 @@
1
+ import { ExecutionFee, GasLimitsConfig } from "types/fees";
2
+ import { DecreasePositionSwapType } from "types/orders";
3
+ import { TokensData } from "types/tokens";
4
+ import type { GmxSdk } from "../../index";
5
+ export declare function getExecutionFee(sdk: GmxSdk, gasLimits: GasLimitsConfig, tokensData: TokensData, estimatedGasLimit: bigint, gasPrice: bigint, oraclePriceCount: bigint): ExecutionFee | undefined;
6
+ /**
7
+ * Only GM deposits. Do not confuse with increase with zero delta size.
8
+ *
9
+ * Copy from contract: `estimateExecuteDepositGasLimit`
10
+ */
11
+ export declare function estimateExecuteDepositGasLimit(gasLimits: GasLimitsConfig, deposit: {
12
+ longTokenSwapsCount?: number;
13
+ shortTokenSwapsCount?: number;
14
+ initialLongTokenAmount?: bigint;
15
+ initialShortTokenAmount?: bigint;
16
+ callbackGasLimit?: bigint;
17
+ }): bigint;
18
+ export declare function estimateExecuteGlvDepositGasLimit(gasLimits: GasLimitsConfig, { marketsCount, isMarketTokenDeposit, initialLongTokenAmount, initialShortTokenAmount, }: {
19
+ isMarketTokenDeposit: any;
20
+ marketsCount: bigint;
21
+ initialLongTokenAmount: bigint;
22
+ initialShortTokenAmount: bigint;
23
+ }): bigint;
24
+ export declare function estimateExecuteGlvWithdrawalGasLimit(gasLimits: GasLimitsConfig, { marketsCount, }: {
25
+ marketsCount: bigint;
26
+ }): bigint;
27
+ /**
28
+ * Only GM withdrawals. Do not confuse with decrease with zero delta size.
29
+ *
30
+ * Copy from contract: `estimateExecuteWithdrawalGasLimit`
31
+ */
32
+ export declare function estimateExecuteWithdrawalGasLimit(gasLimits: GasLimitsConfig, withdrawal: {
33
+ callbackGasLimit?: bigint;
34
+ }): bigint;
35
+ /**
36
+ * Copy from contract: `estimateExecuteShiftGasLimit`
37
+ */
38
+ export declare function estimateExecuteShiftGasLimit(gasLimits: GasLimitsConfig, shift: {
39
+ callbackGasLimit?: bigint;
40
+ }): bigint;
41
+ /**
42
+ * Copy from contract: `estimateExecuteIncreaseOrderGasLimit`
43
+ */
44
+ export declare function estimateExecuteIncreaseOrderGasLimit(gasLimits: GasLimitsConfig, order: {
45
+ swapsCount?: number;
46
+ callbackGasLimit?: bigint;
47
+ }): bigint;
48
+ /**
49
+ * Copy from contract: `estimateExecuteDecreaseOrderGasLimit`
50
+ */
51
+ export declare function estimateExecuteDecreaseOrderGasLimit(gasLimits: GasLimitsConfig, order: {
52
+ swapsCount: number;
53
+ callbackGasLimit?: bigint;
54
+ decreaseSwapType?: DecreasePositionSwapType;
55
+ }): bigint;
56
+ export declare function estimateExecuteSwapOrderGasLimit(gasLimits: GasLimitsConfig, order: {
57
+ swapsCount: number;
58
+ callbackGasLimit?: bigint;
59
+ }): bigint;
@@ -0,0 +1,108 @@
1
+ import { getExcessiveExecutionFee, getHighExecutionFee } from "configs/chains";
2
+ import { USD_DECIMALS } from "configs/factors";
3
+ import { NATIVE_TOKEN_ADDRESS } from "configs/tokens";
4
+ import { DecreasePositionSwapType } from "types/orders";
5
+ import { applyFactor, expandDecimals } from "utils/numbers";
6
+ import { convertToUsd, getTokenData } from "utils/tokens";
7
+ export function getExecutionFee(sdk, gasLimits, tokensData, estimatedGasLimit, gasPrice, oraclePriceCount) {
8
+ const nativeToken = getTokenData(tokensData, NATIVE_TOKEN_ADDRESS);
9
+ const chainId = sdk.chainId;
10
+ if (!nativeToken)
11
+ return undefined;
12
+ // #region adjustGasLimitForEstimate. Copy from contract.
13
+ let baseGasLimit = gasLimits.estimatedGasFeeBaseAmount;
14
+ baseGasLimit += gasLimits.estimatedGasFeePerOraclePrice * oraclePriceCount;
15
+ const multiplierFactor = gasLimits.estimatedFeeMultiplierFactor;
16
+ const gasLimit = baseGasLimit + applyFactor(estimatedGasLimit, multiplierFactor);
17
+ // #endregion
18
+ const feeTokenAmount = gasLimit * gasPrice;
19
+ const feeUsd = convertToUsd(feeTokenAmount, nativeToken.decimals, nativeToken.prices.minPrice);
20
+ const isFeeHigh = feeUsd > expandDecimals(getHighExecutionFee(chainId), USD_DECIMALS);
21
+ const isFeeVeryHigh = feeUsd > expandDecimals(getExcessiveExecutionFee(chainId), USD_DECIMALS);
22
+ return {
23
+ feeUsd,
24
+ feeTokenAmount,
25
+ feeToken: nativeToken,
26
+ isFeeHigh,
27
+ isFeeVeryHigh,
28
+ };
29
+ }
30
+ /**
31
+ * Only GM deposits. Do not confuse with increase with zero delta size.
32
+ *
33
+ * Copy from contract: `estimateExecuteDepositGasLimit`
34
+ */
35
+ export function estimateExecuteDepositGasLimit(gasLimits, deposit) {
36
+ const gasPerSwap = gasLimits.singleSwap;
37
+ const swapsCount = BigInt((deposit.longTokenSwapsCount ?? 0) + (deposit.shortTokenSwapsCount ?? 0));
38
+ const gasForSwaps = swapsCount * gasPerSwap;
39
+ if (deposit.initialLongTokenAmount === undefined ||
40
+ deposit.initialLongTokenAmount === 0n ||
41
+ deposit.initialShortTokenAmount === undefined ||
42
+ deposit.initialShortTokenAmount === 0n) {
43
+ return gasLimits.depositSingleToken + (deposit.callbackGasLimit ?? 0n) + gasForSwaps;
44
+ }
45
+ return gasLimits.depositMultiToken + (deposit.callbackGasLimit ?? 0n) + gasForSwaps;
46
+ }
47
+ export function estimateExecuteGlvDepositGasLimit(gasLimits, { marketsCount, isMarketTokenDeposit, initialLongTokenAmount, initialShortTokenAmount, }) {
48
+ const gasPerGlvPerMarket = gasLimits.glvPerMarketGasLimit;
49
+ const gasForGlvMarkets = gasPerGlvPerMarket * marketsCount;
50
+ const glvDepositGasLimit = gasLimits.glvDepositGasLimit;
51
+ const gasLimit = glvDepositGasLimit + gasForGlvMarkets;
52
+ if (isMarketTokenDeposit) {
53
+ return gasLimit;
54
+ }
55
+ if (initialLongTokenAmount == 0n || initialShortTokenAmount === 0n) {
56
+ return gasLimit + gasLimits.depositSingleToken;
57
+ }
58
+ return gasLimit + gasLimits.depositMultiToken;
59
+ }
60
+ export function estimateExecuteGlvWithdrawalGasLimit(gasLimits, { marketsCount, }) {
61
+ const gasPerGlvPerMarket = gasLimits.glvPerMarketGasLimit;
62
+ const gasForGlvMarkets = gasPerGlvPerMarket * marketsCount;
63
+ const glvWithdrawalGasLimit = gasLimits.glvWithdrawalGasLimit;
64
+ const gasLimit = glvWithdrawalGasLimit + gasForGlvMarkets;
65
+ return gasLimit + gasLimits.withdrawalMultiToken;
66
+ }
67
+ /**
68
+ * Only GM withdrawals. Do not confuse with decrease with zero delta size.
69
+ *
70
+ * Copy from contract: `estimateExecuteWithdrawalGasLimit`
71
+ */
72
+ export function estimateExecuteWithdrawalGasLimit(gasLimits, withdrawal) {
73
+ // Swap is not used but supported in the contract.
74
+ // const gasPerSwap = gasLimits.singleSwap;
75
+ // const swapsCount = 0n;
76
+ // const gasForSwaps = swapsCount * gasPerSwap;
77
+ return gasLimits.withdrawalMultiToken + (withdrawal.callbackGasLimit ?? 0n);
78
+ }
79
+ /**
80
+ * Copy from contract: `estimateExecuteShiftGasLimit`
81
+ */
82
+ export function estimateExecuteShiftGasLimit(gasLimits, shift) {
83
+ return gasLimits.shift + (shift.callbackGasLimit ?? 0n);
84
+ }
85
+ /**
86
+ * Copy from contract: `estimateExecuteIncreaseOrderGasLimit`
87
+ */
88
+ export function estimateExecuteIncreaseOrderGasLimit(gasLimits, order) {
89
+ const gasPerSwap = gasLimits.singleSwap;
90
+ const swapsCount = BigInt(order.swapsCount ?? 0);
91
+ return gasLimits.increaseOrder + gasPerSwap * swapsCount + (order.callbackGasLimit ?? 0n);
92
+ }
93
+ /**
94
+ * Copy from contract: `estimateExecuteDecreaseOrderGasLimit`
95
+ */
96
+ export function estimateExecuteDecreaseOrderGasLimit(gasLimits, order) {
97
+ const gasPerSwap = gasLimits.singleSwap;
98
+ let swapsCount = BigInt(order.swapsCount);
99
+ if (order.decreaseSwapType !== DecreasePositionSwapType.NoSwap) {
100
+ swapsCount += 1n;
101
+ }
102
+ return gasLimits.decreaseOrder + gasPerSwap * swapsCount + (order.callbackGasLimit ?? 0n);
103
+ }
104
+ export function estimateExecuteSwapOrderGasLimit(gasLimits, order) {
105
+ const gasPerSwap = gasLimits.singleSwap;
106
+ const swapsCount = BigInt(order.swapsCount);
107
+ return gasLimits.swapOrder + gasPerSwap * swapsCount + (order.callbackGasLimit ?? 0n);
108
+ }
@@ -0,0 +1,29 @@
1
+ import { FeeItem } from "types/fees";
2
+ import { MarketInfo } from "types/markets";
3
+ import { SwapStats } from "types/trade";
4
+ export * from "./priceImpact";
5
+ export declare function getSwapFee(marketInfo: MarketInfo, swapAmount: bigint, forPositiveImpact: boolean): bigint;
6
+ export declare function getPositionFee(marketInfo: MarketInfo, sizeDeltaUsd: bigint, forPositiveImpact: boolean, referralInfo: {
7
+ totalRebateFactor: bigint;
8
+ discountFactor: bigint;
9
+ } | undefined, uiFeeFactor?: bigint): {
10
+ positionFeeUsd: bigint;
11
+ discountUsd: bigint;
12
+ totalRebateUsd: bigint;
13
+ uiFeeUsd?: undefined;
14
+ } | {
15
+ positionFeeUsd: bigint;
16
+ discountUsd: bigint;
17
+ totalRebateUsd: bigint;
18
+ uiFeeUsd: bigint;
19
+ };
20
+ export declare function getFundingFactorPerPeriod(marketInfo: MarketInfo, isLong: boolean, periodInSeconds: number): bigint;
21
+ export declare function getFundingFeeRateUsd(marketInfo: MarketInfo, isLong: boolean, sizeInUsd: bigint, periodInSeconds: number): bigint;
22
+ export declare function getBorrowingFactorPerPeriod(marketInfo: MarketInfo, isLong: boolean, periodInSeconds: number): bigint;
23
+ export declare function getBorrowingFeeRateUsd(marketInfo: MarketInfo, isLong: boolean, sizeInUsd: bigint, periodInSeconds: number): bigint;
24
+ export declare function getIsHighPriceImpact(positionPriceImpact?: FeeItem, swapPriceImpact?: FeeItem): boolean;
25
+ export declare function getFeeItem(feeDeltaUsd?: bigint, basis?: bigint, opts?: {
26
+ shouldRoundUp?: boolean;
27
+ }): FeeItem | undefined;
28
+ export declare function getTotalFeeItem(feeItems: (FeeItem | undefined)[]): FeeItem;
29
+ export declare function getTotalSwapVolumeFromSwapStats(swapSteps?: SwapStats[]): bigint;