@gmx-io/sdk 0.1.1 → 0.2.0

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 (94) hide show
  1. package/README.md +31 -5
  2. package/build/src/configs/batch.d.ts +2 -3
  3. package/build/src/configs/chains.d.ts +5 -1
  4. package/build/src/configs/chains.js +9 -2
  5. package/build/src/configs/contracts.d.ts +220 -1
  6. package/build/src/configs/contracts.js +67 -8
  7. package/build/src/configs/markets.js +70 -0
  8. package/build/src/configs/tokens.js +128 -5
  9. package/build/src/modules/accounts/accounts.spec.js +1 -0
  10. package/build/src/modules/markets/index.js +2 -8
  11. package/build/src/modules/markets/markets.spec.js +1 -0
  12. package/build/src/modules/markets/query-builders.d.ts +1 -1
  13. package/build/src/modules/markets/query-builders.js +1 -1
  14. package/build/src/modules/markets/types.d.ts +4 -1
  15. package/build/src/modules/orders/orders.spec.js +1 -0
  16. package/build/src/modules/orders/utils.js +1 -1
  17. package/build/src/modules/positions/positions.d.ts +2 -2
  18. package/build/src/modules/positions/positions.js +21 -8
  19. package/build/src/modules/positions/positions.spec.js +2 -1
  20. package/build/src/modules/tokens/tokens.spec.js +1 -0
  21. package/build/src/modules/trades/trades.spec.js +1 -0
  22. package/build/src/modules/utils/utils.d.ts +1 -1
  23. package/build/src/modules/utils/utils.js +1 -1
  24. package/build/src/prebuilt/hashedKinkModelMarketRatesKeys.json +80 -0
  25. package/build/src/prebuilt/hashedMarketConfigKeys.json +500 -0
  26. package/build/src/prebuilt/hashedMarketValuesKeys.json +150 -0
  27. package/build/src/types/common.d.ts +1 -0
  28. package/build/src/types/fees.d.ts +2 -1
  29. package/build/src/types/markets.d.ts +7 -19
  30. package/build/src/types/orders.d.ts +3 -5
  31. package/build/src/types/positions.d.ts +11 -4
  32. package/build/src/types/trade.d.ts +1 -0
  33. package/build/src/types/tradeHistory.d.ts +4 -1
  34. package/build/src/utils/__tests__/LruCache.spec.d.ts +1 -0
  35. package/build/src/utils/__tests__/LruCache.spec.js +43 -0
  36. package/build/src/utils/__tests__/bigmath.spec.d.ts +1 -0
  37. package/build/src/utils/__tests__/bigmath.spec.js +38 -0
  38. package/build/src/utils/__tests__/fees.spec.d.ts +1 -0
  39. package/build/src/utils/__tests__/fees.spec.js +62 -0
  40. package/build/src/utils/__tests__/hash.spec.d.ts +1 -0
  41. package/build/src/utils/__tests__/hash.spec.js +41 -0
  42. package/build/src/utils/__tests__/markets.spec.d.ts +1 -0
  43. package/build/src/utils/__tests__/markets.spec.js +265 -0
  44. package/build/src/utils/__tests__/numbers.spec.d.ts +1 -0
  45. package/build/src/utils/__tests__/numbers.spec.js +81 -0
  46. package/build/src/utils/__tests__/objects.spec.d.ts +1 -0
  47. package/build/src/utils/__tests__/objects.spec.js +59 -0
  48. package/build/src/utils/__tests__/positions.spec.d.ts +1 -0
  49. package/build/src/utils/__tests__/positions.spec.js +178 -0
  50. package/build/src/utils/__tests__/prices.spec.d.ts +1 -0
  51. package/build/src/utils/__tests__/prices.spec.js +59 -0
  52. package/build/src/utils/__tests__/referrals.spec.d.ts +1 -0
  53. package/build/src/utils/__tests__/referrals.spec.js +18 -0
  54. package/build/src/utils/__tests__/subgraph.spec.d.ts +1 -0
  55. package/build/src/utils/__tests__/subgraph.spec.js +163 -0
  56. package/build/src/utils/__tests__/tokens.spec.d.ts +1 -0
  57. package/build/src/utils/__tests__/tokens.spec.js +83 -0
  58. package/build/src/utils/__tests__/trade.spec.d.ts +1 -0
  59. package/build/src/utils/__tests__/trade.spec.js +36 -0
  60. package/build/src/utils/bigmath.d.ts +1 -1
  61. package/build/src/utils/bigmath.js +6 -1
  62. package/build/src/utils/callContract.js +5 -1
  63. package/build/src/utils/common.d.ts +6 -1
  64. package/build/src/utils/common.js +9 -1
  65. package/build/src/utils/contracts.d.ts +4 -0
  66. package/build/src/utils/contracts.js +2 -0
  67. package/build/src/utils/fees/executionFee.d.ts +22 -21
  68. package/build/src/utils/fees/executionFee.js +26 -26
  69. package/build/src/utils/fees/executionFee.spec.d.ts +1 -0
  70. package/build/src/utils/fees/executionFee.spec.js +64 -0
  71. package/build/src/utils/fees/index.d.ts +2 -0
  72. package/build/src/utils/fees/index.js +21 -9
  73. package/build/src/utils/markets.d.ts +9 -2
  74. package/build/src/utils/markets.js +33 -10
  75. package/build/src/utils/multicall.js +4 -3
  76. package/build/src/utils/numbers.d.ts +2 -0
  77. package/build/src/utils/numbers.js +28 -0
  78. package/build/src/utils/orders.js +0 -8
  79. package/build/src/utils/positions.js +3 -3
  80. package/build/src/utils/prices.d.ts +1 -6
  81. package/build/src/utils/prices.js +0 -9
  82. package/build/src/utils/referrals.d.ts +2 -0
  83. package/build/src/utils/referrals.js +17 -15
  84. package/build/src/utils/swapStats.d.ts +1 -0
  85. package/build/src/utils/swapStats.js +12 -1
  86. package/build/src/utils/testUtil.d.ts +14314 -326
  87. package/build/src/utils/tokens.d.ts +4 -0
  88. package/build/src/utils/tokens.js +4 -0
  89. package/build/tsconfig.tsbuildinfo +1 -1
  90. package/package.json +6 -29
  91. package/build/src/types/amounts.d.ts +0 -223
  92. package/build/src/types/amounts.js +0 -17
  93. package/build/src/types/syntheticsEvents.d.ts +0 -88
  94. /package/build/src/types/{syntheticsEvents.js → common.js} +0 -0
@@ -0,0 +1,265 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { getMarketFullName, getMarketIndexName, getMarketPoolName, getContractMarketPrices, getTokenPoolType, getPoolUsdWithoutPnl, getCappedPoolPnl, getMaxLeverageByMinCollateralFactor, getMaxAllowedLeverageByMinCollateralFactor, getOppositeCollateral, getAvailableUsdLiquidityForCollateral, getReservedUsd, getMarketDivisor, getMarketPnl, getOpenInterestUsd, getOpenInterestInTokens, getPriceForPnl, } from "../markets";
3
+ import { TOKENS } from "../../configs/tokens";
4
+ import { ARBITRUM } from "../../configs/chains";
5
+ import { expandDecimals } from "../numbers";
6
+ function getToken(symbol) {
7
+ return TOKENS[ARBITRUM].find((token) => token.symbol === symbol);
8
+ }
9
+ describe("getMarketFullName", () => {
10
+ it("returns proper full name", () => {
11
+ const longToken = getToken("ETH");
12
+ const shortToken = getToken("USDC");
13
+ const indexToken = getToken("BTC");
14
+ const name = getMarketFullName({
15
+ longToken,
16
+ shortToken,
17
+ indexToken,
18
+ isSpotOnly: false,
19
+ });
20
+ expect(name).toBe("BTC/USD [ETH-USDC]");
21
+ });
22
+ it("returns swap-only name", () => {
23
+ const indexToken = { symbol: "ETH", address: "0xeth", decimals: 18 };
24
+ const name = getMarketFullName({
25
+ longToken: indexToken,
26
+ shortToken: indexToken,
27
+ indexToken,
28
+ isSpotOnly: true,
29
+ });
30
+ expect(name).toBe("SWAP-ONLY [ETH]");
31
+ });
32
+ });
33
+ describe("getMarketIndexName", () => {
34
+ it("returns 'SWAP-ONLY' if isSpotOnly is true", () => {
35
+ expect(getMarketIndexName({
36
+ indexToken: getToken("ETH"),
37
+ isSpotOnly: true,
38
+ })).toBe("SWAP-ONLY");
39
+ });
40
+ it("returns prefix + baseSymbol/symbol + /USD", () => {
41
+ const eth = getToken("ETH");
42
+ expect(getMarketIndexName({ indexToken: eth, isSpotOnly: false })).toBe("ETH/USD");
43
+ const pepe = getToken("PEPE");
44
+ expect(getMarketIndexName({ indexToken: pepe, isSpotOnly: false })).toBe("kPEPE/USD");
45
+ });
46
+ });
47
+ describe("getMarketPoolName", () => {
48
+ it("returns single token symbol if long and short are the same", () => {
49
+ const token = getToken("ETH");
50
+ expect(getMarketPoolName({ longToken: token, shortToken: token })).toBe("ETH");
51
+ });
52
+ it("returns combined symbol otherwise", () => {
53
+ const longToken = getToken("ETH");
54
+ const shortToken = getToken("USDC");
55
+ expect(getMarketPoolName({ longToken, shortToken })).toBe("ETH-USDC");
56
+ });
57
+ });
58
+ describe("getContractMarketPrices", () => {
59
+ it("returns undefined if any token is missing", () => {
60
+ const market = {
61
+ indexTokenAddress: "0xbtc",
62
+ longTokenAddress: "0xeth",
63
+ shortTokenAddress: "0xusdc",
64
+ };
65
+ expect(getContractMarketPrices({}, market)).toBeUndefined();
66
+ });
67
+ it("returns converted contract prices if all tokens exist", () => {
68
+ const tokensData = {
69
+ "0xbtc": { decimals: 8, prices: { minPrice: 1000n, maxPrice: 2000n } },
70
+ "0xeth": { decimals: 18, prices: { minPrice: 3000n, maxPrice: 4000n } },
71
+ "0xusdc": { decimals: 6, prices: { minPrice: 1n, maxPrice: 2n } },
72
+ };
73
+ const market = {
74
+ indexTokenAddress: "0xbtc",
75
+ longTokenAddress: "0xeth",
76
+ shortTokenAddress: "0xusdc",
77
+ };
78
+ const result = getContractMarketPrices(tokensData, market);
79
+ expect(result).toBeDefined();
80
+ expect(result?.indexTokenPrice?.min).toBeDefined();
81
+ });
82
+ });
83
+ describe("getTokenPoolType", () => {
84
+ it("returns 'long' for single-token markets if matches address", () => {
85
+ const token = getToken("ETH");
86
+ expect(getTokenPoolType({ longToken: token, shortToken: token }, token.address)).toBe("long");
87
+ });
88
+ it("returns 'short' for shortToken match", () => {
89
+ const longToken = getToken("ETH");
90
+ const shortToken = getToken("USDC");
91
+ expect(getTokenPoolType({ longToken, shortToken }, shortToken.address)).toBe("short");
92
+ });
93
+ });
94
+ describe("getPoolUsdWithoutPnl", () => {
95
+ const marketInfo = {
96
+ longPoolAmount: 1n,
97
+ shortPoolAmount: 1n,
98
+ longToken: { decimals: 18, prices: { minPrice: expandDecimals(5, 30), maxPrice: expandDecimals(15, 30) } },
99
+ shortToken: { decimals: 18, prices: { minPrice: expandDecimals(2, 30), maxPrice: expandDecimals(4, 30) } },
100
+ };
101
+ it("calculates poolUsd for isLong = true", () => {
102
+ expect(getPoolUsdWithoutPnl(marketInfo, true, "minPrice")).toBe(5000000000000n);
103
+ expect(getPoolUsdWithoutPnl(marketInfo, true, "maxPrice")).toBe(15000000000000n);
104
+ });
105
+ it("calculates poolUsd for isLong = false", () => {
106
+ expect(getPoolUsdWithoutPnl(marketInfo, false, "minPrice")).toBe(2000000000000n);
107
+ expect(getPoolUsdWithoutPnl(marketInfo, false, "maxPrice")).toBe(4000000000000n);
108
+ });
109
+ });
110
+ describe("getCappedPoolPnl", () => {
111
+ it("returns capped pnl if poolPnl > maxPnl", () => {
112
+ const marketInfo = {
113
+ maxPnlFactorForTradersLong: 20000n,
114
+ maxPnlFactorForTradersShort: 10000n,
115
+ };
116
+ const result = getCappedPoolPnl({
117
+ marketInfo,
118
+ poolUsd: expandDecimals(1000, 30),
119
+ poolPnl: 30000n,
120
+ isLong: true,
121
+ });
122
+ expect(result).toBe(30000n);
123
+ });
124
+ it("returns poolPnl if below maxPnl", () => {
125
+ const marketInfo = { maxPnlFactorForTradersLong: 20000n };
126
+ expect(getCappedPoolPnl({
127
+ marketInfo,
128
+ poolUsd: expandDecimals(1000, 30),
129
+ poolPnl: 5000n,
130
+ isLong: true,
131
+ })).toBe(5000n);
132
+ });
133
+ });
134
+ describe("getMaxLeverageByMinCollateralFactor", () => {
135
+ it("returns default if minCollateralFactor is undefined", () => {
136
+ expect(getMaxLeverageByMinCollateralFactor(undefined)).toBe(1000000);
137
+ });
138
+ it("returns correct leverage for a given factor", () => {
139
+ expect(getMaxLeverageByMinCollateralFactor(1000000000000000000n)).toBe(10000000000000000);
140
+ });
141
+ });
142
+ describe("getMaxAllowedLeverageByMinCollateralFactor", () => {
143
+ it("returns half of max leverage", () => {
144
+ expect(getMaxAllowedLeverageByMinCollateralFactor(1000000000000000000n)).toBe(5000000000000000);
145
+ });
146
+ });
147
+ describe("getOppositeCollateral", () => {
148
+ const marketInfo = {
149
+ longToken: getToken("ETH"),
150
+ shortToken: getToken("USDC"),
151
+ };
152
+ it("returns shortToken if token is long", () => {
153
+ expect(getOppositeCollateral(marketInfo, marketInfo.longToken.address)).toEqual(marketInfo.shortToken);
154
+ });
155
+ it("returns undefined if pool type is not found", () => {
156
+ expect(getOppositeCollateral(marketInfo, "0xbtc")).toBeUndefined();
157
+ });
158
+ });
159
+ describe("getAvailableUsdLiquidityForCollateral", () => {
160
+ it("returns poolUsd if isSpotOnly", () => {
161
+ const marketInfo = {
162
+ isSpotOnly: true,
163
+ longPoolAmount: 1n,
164
+ indexToken: {
165
+ ...getToken("ETH"),
166
+ prices: { minPrice: expandDecimals(10, 18), maxPrice: expandDecimals(15, 18) },
167
+ },
168
+ longToken: { decimals: 18, prices: { minPrice: expandDecimals(1, 18), maxPrice: expandDecimals(2, 18) } },
169
+ };
170
+ expect(getAvailableUsdLiquidityForCollateral(marketInfo, true)).toBe(1n);
171
+ });
172
+ it("calculates liquidity if not spot only", () => {
173
+ const marketInfo = {
174
+ isSpotOnly: false,
175
+ reserveFactorLong: 1n,
176
+ longPoolAmount: expandDecimals(5, 30),
177
+ longInterestInTokens: 1n,
178
+ indexToken: {
179
+ ...getToken("ETH"),
180
+ prices: { minPrice: expandDecimals(10, 18), maxPrice: expandDecimals(15, 18) },
181
+ },
182
+ longToken: { decimals: 18, prices: { minPrice: expandDecimals(10, 18), maxPrice: expandDecimals(15, 18) } },
183
+ };
184
+ expect(getAvailableUsdLiquidityForCollateral(marketInfo, true)).toBe(expandDecimals(35, 30));
185
+ });
186
+ });
187
+ describe("getReservedUsd", () => {
188
+ it("calculates reservedUsd for long side", () => {
189
+ const marketInfo = {
190
+ longInterestInTokens: 100n,
191
+ indexToken: {
192
+ decimals: 18,
193
+ prices: { maxPrice: expandDecimals(10, 18) },
194
+ },
195
+ };
196
+ expect(getReservedUsd(marketInfo, true)).toBe(1000n);
197
+ });
198
+ it("returns shortInterestUsd if isLong=false", () => {
199
+ const marketInfo = { shortInterestUsd: 9999n };
200
+ expect(getReservedUsd(marketInfo, false)).toBe(9999n);
201
+ });
202
+ });
203
+ describe("getMarketDivisor", () => {
204
+ it("returns 2n if longTokenAddress equals shortTokenAddress", () => {
205
+ expect(getMarketDivisor({
206
+ longTokenAddress: "0xsame",
207
+ shortTokenAddress: "0xsame",
208
+ })).toBe(2n);
209
+ });
210
+ it("returns 1n otherwise", () => {
211
+ expect(getMarketDivisor({
212
+ longTokenAddress: "0xeth",
213
+ shortTokenAddress: "0xusdc",
214
+ })).toBe(1n);
215
+ });
216
+ });
217
+ describe("getMarketPnl", () => {
218
+ it("returns 0n if openInterest is 0", () => {
219
+ const marketInfo = {
220
+ indexToken: {
221
+ decimals: 18,
222
+ prices: { minPrice: expandDecimals(1000, 18), maxPrice: expandDecimals(2000, 18) },
223
+ },
224
+ longInterestUsd: 0n,
225
+ longInterestInTokens: 0n,
226
+ };
227
+ expect(getMarketPnl(marketInfo, true, false)).toBe(0n);
228
+ });
229
+ it("calculates pnl for long positions", () => {
230
+ const marketInfo = {
231
+ indexToken: {
232
+ decimals: 18,
233
+ prices: { minPrice: expandDecimals(1000, 18), maxPrice: expandDecimals(2000, 18) },
234
+ },
235
+ longInterestUsd: 1000n,
236
+ longInterestInTokens: 1n,
237
+ };
238
+ // maximize = false => use minPrice for long
239
+ expect(getMarketPnl(marketInfo, true, true)).toBe(0n); // openInterestValue(1000n) - openInterestUsd(1000n) = 0
240
+ });
241
+ });
242
+ describe("getOpenInterestUsd", () => {
243
+ it("returns longInterestUsd for isLong", () => {
244
+ expect(getOpenInterestUsd({ longInterestUsd: 1234n, shortInterestUsd: 9999n }, true)).toBe(1234n);
245
+ });
246
+ it("returns shortInterestUsd for !isLong", () => {
247
+ expect(getOpenInterestUsd({ longInterestUsd: 1234n, shortInterestUsd: 9999n }, false)).toBe(9999n);
248
+ });
249
+ });
250
+ describe("getOpenInterestInTokens", () => {
251
+ it("returns longInterestInTokens for isLong", () => {
252
+ expect(getOpenInterestInTokens({ longInterestInTokens: 100n, shortInterestInTokens: 200n }, true)).toBe(100n);
253
+ });
254
+ it("returns shortInterestInTokens for !isLong", () => {
255
+ expect(getOpenInterestInTokens({ longInterestInTokens: 100n, shortInterestInTokens: 200n }, false)).toBe(200n);
256
+ });
257
+ });
258
+ describe("getPriceForPnl", () => {
259
+ it("uses maxPrice for long when maximize=true", () => {
260
+ expect(getPriceForPnl({ minPrice: 1000n, maxPrice: 2000n }, true, true)).toBe(2000n);
261
+ });
262
+ it("uses maxPrice for short when maximize=false", () => {
263
+ expect(getPriceForPnl({ minPrice: 1000n, maxPrice: 2000n }, false, false)).toBe(2000n);
264
+ });
265
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,81 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { BASIS_POINTS_DIVISOR_BIGINT } from "../../configs/factors";
3
+ import { BN_NEGATIVE_ONE, BN_ONE, BN_ZERO, PRECISION, applyFactor, basisPointsToFloat, bigintToNumber, expandDecimals, getBasisPoints, numberToBigint, roundUpMagnitudeDivision, } from "../numbers";
4
+ describe("numbers utils", () => {
5
+ it("constants", () => {
6
+ // Just to confirm they exist and have no unexpected changes
7
+ expect(PRECISION).toBe(expandDecimals(1, 30));
8
+ expect(BN_ZERO).toBe(0n);
9
+ expect(BN_ONE).toBe(1n);
10
+ expect(BN_NEGATIVE_ONE).toBe(-1n);
11
+ });
12
+ describe("expandDecimals", () => {
13
+ it("multiplies by 10^decimals", () => {
14
+ expect(expandDecimals(1, 0)).toBe(1n);
15
+ expect(expandDecimals(1, 1)).toBe(10n);
16
+ expect(expandDecimals(1, 2)).toBe(100n);
17
+ expect(expandDecimals(5, 3)).toBe(5000n);
18
+ });
19
+ it("handles zero gracefully", () => {
20
+ expect(expandDecimals(0, 5)).toBe(0n);
21
+ });
22
+ });
23
+ describe("basisPointsToFloat", () => {
24
+ it("converts basis points to scaled big int float using PRECISION", () => {
25
+ const result = basisPointsToFloat(100n);
26
+ expect(result).toBe(expandDecimals(1, 28));
27
+ });
28
+ });
29
+ describe("getBasisPoints", () => {
30
+ it("calculates basis points as (numerator * 10000) / denominator", () => {
31
+ expect(getBasisPoints(2n, 1n)).toBe(2n * BASIS_POINTS_DIVISOR_BIGINT);
32
+ expect(getBasisPoints(1n, 2n)).toBe(5000n);
33
+ });
34
+ it("rounds up if remainder != 0 and shouldRoundUp=true", () => {
35
+ expect(getBasisPoints(7n, 3n, true)).toBe(23334n);
36
+ });
37
+ it("returns same result if remainder=0, even if shouldRoundUp=true", () => {
38
+ expect(getBasisPoints(2n, 1n, true)).toBe(20000n);
39
+ });
40
+ });
41
+ describe("roundUpMagnitudeDivision", () => {
42
+ it("rounds positive numbers up", () => {
43
+ expect(roundUpMagnitudeDivision(10n, 3n)).toBe(4n);
44
+ expect(roundUpMagnitudeDivision(9n, 3n)).toBe(3n);
45
+ });
46
+ it("rounds negative numbers up in magnitude", () => {
47
+ expect(roundUpMagnitudeDivision(-10n, 3n)).toBe(-4n);
48
+ });
49
+ });
50
+ describe("applyFactor", () => {
51
+ it("applies factor by (value * factor)/PRECISION", () => {
52
+ const value = expandDecimals(100, 30);
53
+ const factor = 200n;
54
+ expect(applyFactor(value, factor)).toBe(20000n);
55
+ });
56
+ });
57
+ it("bigintToNumber", () => {
58
+ expect(bigintToNumber(0n, 30)).toEqual(0);
59
+ expect(bigintToNumber(1n, 30)).toEqual(1e-30);
60
+ expect(bigintToNumber(PRECISION, 30)).toEqual(1);
61
+ expect(bigintToNumber(PRECISION * 100n, 30)).toEqual(100);
62
+ expect(bigintToNumber(PRECISION * 2n, 30)).toEqual(2);
63
+ expect(bigintToNumber(PRECISION / 2n, 30)).toEqual(0.5);
64
+ expect(bigintToNumber(1123456n, 6)).toEqual(1.123456);
65
+ expect(bigintToNumber(-1123456n, 6)).toEqual(-1.123456);
66
+ });
67
+ it("numberToBigint", () => {
68
+ expect(numberToBigint(0, 30)).toEqual(0n);
69
+ expect(numberToBigint(1e-30, 30)).toEqual(1n);
70
+ expect(numberToBigint(-1e-30, 30)).toEqual(-1n);
71
+ expect(numberToBigint(1, 30)).toEqual(PRECISION);
72
+ expect(numberToBigint(100, 30)).toEqual(PRECISION * 100n);
73
+ expect(numberToBigint(2, 30)).toEqual(PRECISION * 2n);
74
+ expect(numberToBigint(0.5, 30)).toEqual(PRECISION / 2n);
75
+ expect(numberToBigint(-0.5, 30)).toEqual(-PRECISION / 2n);
76
+ expect(numberToBigint(1.1234567, 6)).toEqual(1123456n);
77
+ expect(numberToBigint(1.12345678, 6)).toEqual(1123456n);
78
+ expect(numberToBigint(1.123456789, 6)).toEqual(1123456n);
79
+ expect(numberToBigint(-1.123456789, 6)).toEqual(-1123456n);
80
+ });
81
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,59 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { setByKey, updateByKey, getByKey } from "../objects";
3
+ describe("setByKey", () => {
4
+ it("should set a key in an object", () => {
5
+ const obj = { a: 1, b: 2 };
6
+ const key = "c";
7
+ const data = 3;
8
+ expect(setByKey(obj, key, data)).toEqual({ a: 1, b: 2, c: 3 });
9
+ });
10
+ it("should set a key in an empty object", () => {
11
+ const obj = {};
12
+ const key = "c";
13
+ const data = 3;
14
+ expect(setByKey(obj, key, data)).toEqual({ c: 3 });
15
+ });
16
+ it("should set a key in an object with existing key", () => {
17
+ const obj = { a: 1, b: 2 };
18
+ const key = "b";
19
+ const data = 3;
20
+ expect(setByKey(obj, key, data)).toEqual({ a: 1, b: 3 });
21
+ });
22
+ });
23
+ describe("updateByKey", () => {
24
+ it("should update a key in an object", () => {
25
+ const obj = { a: { x: 1, y: 2 }, b: { x: 3, y: 4 } };
26
+ const key = "b";
27
+ const data = { y: 5 };
28
+ expect(updateByKey(obj, key, data)).toEqual({ a: { x: 1, y: 2 }, b: { x: 3, y: 5 } });
29
+ });
30
+ it("should update a key in an empty object", () => {
31
+ const obj = {};
32
+ const key = "b";
33
+ const data = { y: 5 };
34
+ expect(updateByKey(obj, key, data)).toEqual({});
35
+ });
36
+ it("should update a key in an object with non-existing key", () => {
37
+ const obj = { a: { x: 1, y: 2 }, b: { x: 3, y: 4 } };
38
+ const key = "c";
39
+ const data = { y: 5 };
40
+ expect(updateByKey(obj, key, data)).toEqual({ a: { x: 1, y: 2 }, b: { x: 3, y: 4 } });
41
+ });
42
+ });
43
+ describe("getByKey", () => {
44
+ it("should get a key in an object", () => {
45
+ const obj = { a: 1, b: 2 };
46
+ const key = "b";
47
+ expect(getByKey(obj, key)).toEqual(2);
48
+ });
49
+ it("should get a key in an empty object", () => {
50
+ const obj = {};
51
+ const key = "b";
52
+ expect(getByKey(obj, key)).toEqual(undefined);
53
+ });
54
+ it("should get a non-existing key in an object", () => {
55
+ const obj = { a: 1, b: 2 };
56
+ const key = "c";
57
+ expect(getByKey(obj, key)).toEqual(undefined);
58
+ });
59
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,178 @@
1
+ import { describe, expect, it, vi, beforeEach } from "vitest";
2
+ import { bigMath } from "../bigmath";
3
+ import { getPositionFee, getPriceImpactForPosition } from "../fees";
4
+ import { getCappedPoolPnl, getMarketPnl, getPoolUsdWithoutPnl } from "../markets";
5
+ import { getEntryPrice, getLeverage, getLiquidationPrice, getPositionKey, getPositionNetValue, getPositionPendingFeesUsd, getPositionPnlUsd, getPositionValueUsd, parsePositionKey, } from "../positions";
6
+ import { convertToUsd, getIsEquivalentTokens } from "../tokens";
7
+ vi.mock("../markets", () => ({
8
+ ...vi.importActual("../markets"),
9
+ getMarketPnl: vi.fn(),
10
+ getPoolUsdWithoutPnl: vi.fn(),
11
+ getCappedPoolPnl: vi.fn(),
12
+ }));
13
+ vi.mock("../tokens", () => ({
14
+ ...vi.importActual("../tokens"),
15
+ convertToUsd: vi.fn(),
16
+ getIsEquivalentTokens: vi.fn(),
17
+ }));
18
+ vi.mock("../fees", () => ({
19
+ getPositionFee: vi.fn(),
20
+ getPriceImpactForPosition: vi.fn(),
21
+ }));
22
+ describe("getPositionKey", () => {
23
+ it("returns key in expected format", () => {
24
+ expect(getPositionKey("0xabc", "0xmarket", "0xcollateral", true)).toBe("0xabc:0xmarket:0xcollateral:true");
25
+ });
26
+ });
27
+ describe("parsePositionKey", () => {
28
+ it("parses position key string into an object", () => {
29
+ const result = parsePositionKey("0xabc:0xmarket:0xcollateral:false");
30
+ expect(result).toEqual({
31
+ account: "0xabc",
32
+ marketAddress: "0xmarket",
33
+ collateralAddress: "0xcollateral",
34
+ isLong: false,
35
+ });
36
+ });
37
+ });
38
+ describe("getEntryPrice", () => {
39
+ it("returns undefined if sizeInTokens <= 0", () => {
40
+ const token = { decimals: 18 };
41
+ expect(getEntryPrice({ sizeInUsd: 1000n, sizeInTokens: 0n, indexToken: token })).toBeUndefined();
42
+ });
43
+ it("returns mulDiv of sizeInUsd if sizeInTokens > 0", () => {
44
+ const token = { decimals: 2 };
45
+ const result = getEntryPrice({ sizeInUsd: 1000n, sizeInTokens: 100n, indexToken: token });
46
+ expect(result).toBe(1000n);
47
+ });
48
+ });
49
+ describe("getPositionValueUsd", () => {
50
+ it("uses convertToUsd under the hood", () => {
51
+ convertToUsd.mockReturnValueOnce(5000n);
52
+ const token = { decimals: 18 };
53
+ const result = getPositionValueUsd({ indexToken: token, sizeInTokens: 100n, markPrice: 10n });
54
+ expect(convertToUsd).toHaveBeenCalledWith(100n, 18, 10n);
55
+ expect(result).toBe(5000n);
56
+ });
57
+ });
58
+ describe("getPositionPnlUsd", () => {
59
+ const marketInfo = { indexToken: {}, maxPositionImpactFactorForLiquidations: 2n };
60
+ beforeEach(() => {
61
+ getMarketPnl.mockReturnValue(1000n);
62
+ getPoolUsdWithoutPnl.mockReturnValue(5000n);
63
+ getCappedPoolPnl.mockReturnValue(800n);
64
+ });
65
+ it("returns negative PnL if positionValueUsd < sizeInUsd for a long", () => {
66
+ convertToUsd.mockReturnValueOnce(900n); // positionValueUsd
67
+ const result = getPositionPnlUsd({
68
+ marketInfo,
69
+ sizeInUsd: 1000n,
70
+ sizeInTokens: 100n,
71
+ markPrice: 10n,
72
+ isLong: true,
73
+ });
74
+ expect(result).toBe(900n - 1000n); // -100n
75
+ });
76
+ });
77
+ describe("getPositionPendingFeesUsd", () => {
78
+ it("sums up funding and borrowing fees", () => {
79
+ expect(getPositionPendingFeesUsd({ pendingFundingFeesUsd: 10n, pendingBorrowingFeesUsd: 15n })).toBe(25n);
80
+ });
81
+ });
82
+ describe("getPositionNetValue", () => {
83
+ it("calculates net position value", () => {
84
+ const result = getPositionNetValue({
85
+ collateralUsd: 1000n,
86
+ pendingFundingFeesUsd: 10n,
87
+ pendingBorrowingFeesUsd: 15n,
88
+ closingFeeUsd: 5n,
89
+ uiFeeUsd: 20n,
90
+ pnl: 200n,
91
+ });
92
+ // netValue = 1000n - (10n+15n) -5n -20n + 200n = 1000n -25n -5n -20n +200n=1150n
93
+ expect(result).toBe(1150n);
94
+ });
95
+ });
96
+ describe("getLeverage", () => {
97
+ it("returns undefined if remainingCollateralUsd <= 0", () => {
98
+ const result = getLeverage({
99
+ sizeInUsd: 1000n,
100
+ collateralUsd: 100n,
101
+ pnl: -200n,
102
+ pendingFundingFeesUsd: 100n,
103
+ pendingBorrowingFeesUsd: 0n,
104
+ });
105
+ // remainingCollateralUsd=100n +(-200n)-100n= -200n
106
+ expect(result).toBeUndefined();
107
+ });
108
+ it("returns correct leverage if collateralUsd > 0", () => {
109
+ const result = getLeverage({
110
+ sizeInUsd: 2000n,
111
+ collateralUsd: 1000n,
112
+ pnl: 200n,
113
+ pendingFundingFeesUsd: 50n,
114
+ pendingBorrowingFeesUsd: 50n,
115
+ });
116
+ // remainingCollateralUsd=1000n +200n -100n=1100n
117
+ // leverage= mulDiv(2000n, 10000n, 1100n)= (2000n*10000n)/1100n= ~18181n
118
+ expect(result).toBe(bigMath.mulDiv(2000n, 10000n, 1100n));
119
+ });
120
+ });
121
+ describe("getLiquidationPrice", () => {
122
+ beforeEach(() => {
123
+ getPositionFee.mockReturnValue({ positionFeeUsd: 50n });
124
+ getPriceImpactForPosition.mockReturnValue(-100n);
125
+ getIsEquivalentTokens.mockReturnValue(false);
126
+ });
127
+ it("returns undefined if sizeInUsd <= 0 or sizeInTokens <= 0", () => {
128
+ const marketInfo = { indexToken: { decimals: 18 } };
129
+ expect(getLiquidationPrice({
130
+ sizeInUsd: 0n,
131
+ sizeInTokens: 100n,
132
+ collateralAmount: 10n,
133
+ collateralUsd: 1000n,
134
+ collateralToken: {},
135
+ marketInfo,
136
+ pendingFundingFeesUsd: 0n,
137
+ pendingBorrowingFeesUsd: 0n,
138
+ minCollateralUsd: 100n,
139
+ isLong: true,
140
+ userReferralInfo: undefined,
141
+ })).toBeUndefined();
142
+ expect(getLiquidationPrice({
143
+ sizeInUsd: 100n,
144
+ sizeInTokens: 0n,
145
+ collateralAmount: 10n,
146
+ collateralUsd: 1000n,
147
+ collateralToken: {},
148
+ marketInfo,
149
+ pendingFundingFeesUsd: 0n,
150
+ pendingBorrowingFeesUsd: 0n,
151
+ minCollateralUsd: 100n,
152
+ isLong: true,
153
+ userReferralInfo: undefined,
154
+ })).toBeUndefined();
155
+ });
156
+ it("computes liquidation price for non-equivalent tokens and isLong=true", () => {
157
+ getIsEquivalentTokens.mockReturnValue(false);
158
+ const marketInfo = {
159
+ indexToken: { decimals: 8 },
160
+ minCollateralFactor: 1000n, // 0.001
161
+ maxPositionImpactFactorForLiquidations: 500n, // 0.005
162
+ };
163
+ const result = getLiquidationPrice({
164
+ sizeInUsd: 1000n,
165
+ sizeInTokens: 100n,
166
+ collateralAmount: 50n, // not used if tokens not equivalent
167
+ collateralToken: {},
168
+ collateralUsd: 400n,
169
+ marketInfo,
170
+ pendingFundingFeesUsd: 0n,
171
+ pendingBorrowingFeesUsd: 0n,
172
+ minCollateralUsd: 200n,
173
+ isLong: true,
174
+ userReferralInfo: undefined,
175
+ });
176
+ expect(result).toBeDefined();
177
+ });
178
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,59 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { getMarkPrice, getShouldUseMaxPrice, getTriggerThresholdType } from "../prices";
3
+ import { OrderType } from "../../types/orders";
4
+ import { TriggerThresholdType } from "../../types/trade";
5
+ describe("getMarkPrice", () => {
6
+ it("returns maxPrice if getShouldUseMaxPrice => true", () => {
7
+ const prices = { minPrice: 1000n, maxPrice: 1500n };
8
+ // isIncrease=true, isLong=true => getShouldUseMaxPrice => true
9
+ const result = getMarkPrice({ prices, isIncrease: true, isLong: true });
10
+ expect(result).toBe(1500n);
11
+ });
12
+ it("returns minPrice if getShouldUseMaxPrice => false", () => {
13
+ const prices = { minPrice: 1000n, maxPrice: 1500n };
14
+ // isIncrease=false, isLong=true => getShouldUseMaxPrice => false
15
+ const result = getMarkPrice({ prices, isIncrease: false, isLong: true });
16
+ expect(result).toBe(1000n);
17
+ });
18
+ });
19
+ describe("getShouldUseMaxPrice", () => {
20
+ it("returns isLong if isIncrease=true", () => {
21
+ // isIncrease=true => return isLong
22
+ expect(getShouldUseMaxPrice(true, true)).toBe(true);
23
+ expect(getShouldUseMaxPrice(true, false)).toBe(false);
24
+ });
25
+ it("returns !isLong if isIncrease=false", () => {
26
+ // isIncrease=false => return !isLong
27
+ expect(getShouldUseMaxPrice(false, true)).toBe(false);
28
+ expect(getShouldUseMaxPrice(false, false)).toBe(true);
29
+ });
30
+ });
31
+ describe("getTriggerThresholdType", () => {
32
+ it("returns Below for LimitIncrease when isLong=true", () => {
33
+ const result = getTriggerThresholdType(OrderType.LimitIncrease, true);
34
+ expect(result).toBe(TriggerThresholdType.Below);
35
+ });
36
+ it("returns Above for LimitIncrease when isLong=false", () => {
37
+ const result = getTriggerThresholdType(OrderType.LimitIncrease, false);
38
+ expect(result).toBe(TriggerThresholdType.Above);
39
+ });
40
+ it("returns Above for LimitDecrease when isLong=true", () => {
41
+ const result = getTriggerThresholdType(OrderType.LimitDecrease, true);
42
+ expect(result).toBe(TriggerThresholdType.Above);
43
+ });
44
+ it("returns Below for LimitDecrease when isLong=false", () => {
45
+ const result = getTriggerThresholdType(OrderType.LimitDecrease, false);
46
+ expect(result).toBe(TriggerThresholdType.Below);
47
+ });
48
+ it("returns Below for StopLossDecrease when isLong=true", () => {
49
+ const result = getTriggerThresholdType(OrderType.StopLossDecrease, true);
50
+ expect(result).toBe(TriggerThresholdType.Below);
51
+ });
52
+ it("returns Above for StopLossDecrease when isLong=false", () => {
53
+ const result = getTriggerThresholdType(OrderType.StopLossDecrease, false);
54
+ expect(result).toBe(TriggerThresholdType.Above);
55
+ });
56
+ it("throws error for invalid order type", () => {
57
+ expect(() => getTriggerThresholdType("SomeInvalidType", true)).toThrow("Invalid trigger order type");
58
+ });
59
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,18 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { decodeReferralCode, encodeReferralCode, MAX_REFERRAL_CODE_LENGTH } from "../referrals";
3
+ import { zeroHash } from "viem";
4
+ describe("utils/referrals", () => {
5
+ it("decode(encode(x)) === x", () => {
6
+ const code = "test";
7
+ const encoded = encodeReferralCode(code);
8
+ const decoded = decodeReferralCode(encoded);
9
+ expect(decoded).toEqual(code);
10
+ });
11
+ it("decodeReferralCode defaults", () => {
12
+ expect(decodeReferralCode()).toEqual("");
13
+ expect(decodeReferralCode(zeroHash)).toEqual("");
14
+ });
15
+ it("encodeReferralCode defaults", () => {
16
+ expect(encodeReferralCode(new Array(MAX_REFERRAL_CODE_LENGTH + 1).fill("0").join(""))).toEqual(zeroHash);
17
+ });
18
+ });
@@ -0,0 +1 @@
1
+ export {};