@gmx-io/sdk 2.9.1 → 2.9.3

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 (112) hide show
  1. package/build/cjs/src/clients/v2/index.js +61 -41
  2. package/build/cjs/src/clients/v2/solana.spec.js +188 -0
  3. package/build/cjs/src/configs/api.js +4 -0
  4. package/build/cjs/src/utils/fees/index.js +7 -1
  5. package/build/cjs/src/utils/fees/priceImpact.js +118 -18
  6. package/build/cjs/src/utils/gmsol/__tests__/fixtures/nativeMath.json +3171 -0
  7. package/build/cjs/src/utils/gmsol/__tests__/nativeMath.spec.js +213 -0
  8. package/build/cjs/src/utils/gmsol/constants.js +12 -0
  9. package/build/cjs/src/utils/gmsol/fees.js +19 -0
  10. package/build/cjs/src/utils/gmsol/index.js +66 -0
  11. package/build/cjs/src/utils/gmsol/markets.js +206 -0
  12. package/build/cjs/src/utils/gmsol/numbers.js +230 -0
  13. package/build/cjs/src/utils/gmsol/positions.js +152 -0
  14. package/build/cjs/src/utils/gmsol/types.js +2 -0
  15. package/build/cjs/src/utils/http/http.js +3 -4
  16. package/build/cjs/src/utils/http/httpFallback.js +11 -1
  17. package/build/cjs/src/utils/http/solana.js +17 -0
  18. package/build/cjs/src/utils/http/validation.js +21 -1
  19. package/build/cjs/src/utils/http/validation.spec.js +45 -0
  20. package/build/cjs/src/utils/markets/__tests__/api.spec.js +53 -0
  21. package/build/cjs/src/utils/markets/api.js +5 -0
  22. package/build/cjs/src/utils/markets/utils.js +25 -9
  23. package/build/cjs/src/utils/orders/api.js +3 -0
  24. package/build/cjs/src/utils/positions/__tests__/liquidationPrice.spec.js +64 -0
  25. package/build/cjs/src/utils/positions/api.js +3 -0
  26. package/build/cjs/src/utils/positions/utils.js +88 -19
  27. package/build/cjs/src/utils/prices/utils.js +69 -14
  28. package/build/cjs/src/utils/referrals/api.js +41 -0
  29. package/build/cjs/src/utils/swap/swapRouting.js +4 -0
  30. package/build/cjs/src/utils/swap/swapStats.js +6 -1
  31. package/build/cjs/src/utils/trade/__tests__/gmsolTradeMath.spec.js +1012 -0
  32. package/build/cjs/src/utils/trade/decrease.js +266 -56
  33. package/build/cjs/src/utils/trade/decreaseMarginCheck.js +23 -4
  34. package/build/cjs/src/utils/trade/increase.js +86 -28
  35. package/build/cjs/src/utils/trade/increaseMarginCheck.js +51 -9
  36. package/build/cjs/src/utils/trade/twapIncreaseMarginCheck.js +8 -3
  37. package/build/esm/src/clients/v2/index.js +39 -19
  38. package/build/esm/src/clients/v2/solana.spec.js +160 -0
  39. package/build/esm/src/configs/api.js +5 -1
  40. package/build/esm/src/utils/fees/index.js +7 -1
  41. package/build/esm/src/utils/fees/priceImpact.js +111 -12
  42. package/build/esm/src/utils/gmsol/__tests__/fixtures/nativeMath.json +3171 -0
  43. package/build/esm/src/utils/gmsol/__tests__/nativeMath.spec.js +208 -0
  44. package/build/esm/src/utils/gmsol/constants.js +9 -0
  45. package/build/esm/src/utils/gmsol/fees.js +15 -0
  46. package/build/esm/src/utils/gmsol/index.js +46 -0
  47. package/build/esm/src/utils/gmsol/markets.js +193 -0
  48. package/build/esm/src/utils/gmsol/numbers.js +226 -0
  49. package/build/esm/src/utils/gmsol/positions.js +148 -0
  50. package/build/esm/src/utils/gmsol/types.js +1 -0
  51. package/build/esm/src/utils/http/http.js +3 -4
  52. package/build/esm/src/utils/http/httpFallback.js +11 -1
  53. package/build/esm/src/utils/http/solana.js +12 -0
  54. package/build/esm/src/utils/http/validation.js +18 -0
  55. package/build/esm/src/utils/http/validation.spec.js +43 -0
  56. package/build/esm/src/utils/markets/__tests__/api.spec.js +53 -0
  57. package/build/esm/src/utils/markets/api.js +6 -1
  58. package/build/esm/src/utils/markets/utils.js +23 -8
  59. package/build/esm/src/utils/orders/api.js +3 -0
  60. package/build/esm/src/utils/positions/__tests__/liquidationPrice.spec.js +62 -0
  61. package/build/esm/src/utils/positions/api.js +3 -0
  62. package/build/esm/src/utils/positions/utils.js +89 -20
  63. package/build/esm/src/utils/prices/utils.js +70 -15
  64. package/build/esm/src/utils/referrals/api.js +36 -0
  65. package/build/esm/src/utils/swap/swapRouting.js +4 -0
  66. package/build/esm/src/utils/swap/swapStats.js +7 -2
  67. package/build/esm/src/utils/trade/__tests__/gmsolTradeMath.spec.js +1010 -0
  68. package/build/esm/src/utils/trade/decrease.js +266 -56
  69. package/build/esm/src/utils/trade/decreaseMarginCheck.js +23 -4
  70. package/build/esm/src/utils/trade/increase.js +86 -28
  71. package/build/esm/src/utils/trade/increaseMarginCheck.js +53 -11
  72. package/build/esm/src/utils/trade/twapIncreaseMarginCheck.js +8 -3
  73. package/build/tsconfig.tsbuildinfo +1 -1
  74. package/build/types/src/clients/v2/index.d.ts +21 -12
  75. package/build/types/src/clients/v2/solana.spec.d.ts +1 -0
  76. package/build/types/src/utils/fees/index.d.ts +1 -1
  77. package/build/types/src/utils/fees/priceImpact.d.ts +7 -0
  78. package/build/types/src/utils/gmsol/__tests__/nativeMath.spec.d.ts +1 -0
  79. package/build/types/src/utils/gmsol/constants.d.ts +9 -0
  80. package/build/types/src/utils/gmsol/fees.d.ts +6 -0
  81. package/build/types/src/utils/gmsol/index.d.ts +38 -0
  82. package/build/types/src/utils/gmsol/markets.d.ts +49 -0
  83. package/build/types/src/utils/gmsol/numbers.d.ts +11 -0
  84. package/build/types/src/utils/gmsol/positions.d.ts +7 -0
  85. package/build/types/src/utils/gmsol/types.d.ts +105 -0
  86. package/build/types/src/utils/http/http.d.ts +2 -5
  87. package/build/types/src/utils/http/httpFallback.d.ts +2 -5
  88. package/build/types/src/utils/http/solana.d.ts +4 -0
  89. package/build/types/src/utils/http/types.d.ts +17 -4
  90. package/build/types/src/utils/http/validation.d.ts +8 -0
  91. package/build/types/src/utils/http/validation.spec.d.ts +1 -0
  92. package/build/types/src/utils/markets/hashKeys.d.ts +1 -1
  93. package/build/types/src/utils/markets/types.d.ts +3 -2
  94. package/build/types/src/utils/markets/utils.d.ts +6 -2
  95. package/build/types/src/utils/orders/api.d.ts +2 -2
  96. package/build/types/src/utils/positions/__tests__/liquidationPrice.spec.d.ts +1 -0
  97. package/build/types/src/utils/positions/api.d.ts +2 -2
  98. package/build/types/src/utils/positions/types.d.ts +1 -0
  99. package/build/types/src/utils/positions/utils.d.ts +6 -1
  100. package/build/types/src/utils/prices/types.d.ts +16 -0
  101. package/build/types/src/utils/prices/utils.d.ts +3 -11
  102. package/build/types/src/utils/referrals/api.d.ts +8 -0
  103. package/build/types/src/utils/referrals/types.d.ts +5 -0
  104. package/build/types/src/utils/rpc/createViemRpc.d.ts +25 -3
  105. package/build/types/src/utils/trade/__tests__/gmsolTradeMath.spec.d.ts +1 -0
  106. package/build/types/src/utils/trade/decrease.d.ts +5 -0
  107. package/build/types/src/utils/trade/decreaseMarginCheck.d.ts +2 -0
  108. package/build/types/src/utils/trade/increase.d.ts +2 -0
  109. package/build/types/src/utils/trade/increaseMarginCheck.d.ts +2 -0
  110. package/build/types/src/utils/trade/twapIncreaseMarginCheck.d.ts +1 -0
  111. package/build/types/src/utils/trade/types.d.ts +6 -0
  112. package/package.json +10 -1
@@ -0,0 +1,1010 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { ARBITRUM } from "../../../configs/chainIds";
3
+ import { mockMarginCheckMarketInfo, mockTokensData } from "../../../test/mock";
4
+ import { capPositionImpactUsdByMaxPriceImpactFactor, getCappedPositionImpactUsd, getPositionFee, getPriceImpactForPosition, getPriceImpactUsd, GmsolPriceImpactError, } from "../../fees";
5
+ import { PRECISION } from "../../numbers";
6
+ import { DecreasePositionSwapType, OrderType, SwapPricingType } from "../../orders/types";
7
+ import { getPositionInfo } from "../../positions";
8
+ import { getAcceptablePriceInfo } from "../../prices";
9
+ import { createSwapEstimator, getBestSwapPath } from "../../swap/swapRouting";
10
+ import { getSwapPathStats } from "../../swap/swapStats";
11
+ import { getDecreasePositionAmounts, getOptimalDecreaseAndSwapAmounts } from "../decrease";
12
+ import { getDecreaseResultingPositionMarginState, getTriggerDecreaseRemainingPositionMarginState, } from "../decreaseMarginCheck";
13
+ import { getIncreasePositionAmounts } from "../increase";
14
+ import { getIncreaseResultingPositionState, getResultingPositionMarginState } from "../increaseMarginCheck";
15
+ import { getTwapIncreasePartsGrossCollateralUsd } from "../twapIncreaseMarginCheck";
16
+ const P = PRECISION;
17
+ function market(p) {
18
+ const tokens = mockTokensData({
19
+ BTC: { decimals: p.decimals, prices: { minPrice: p.minPrice, maxPrice: p.maxPrice } },
20
+ });
21
+ return {
22
+ ...mockMarginCheckMarketInfo(tokens, { positionImpactPoolAmount: 0n, ...p.overrides }),
23
+ tradeMath: p.tradeMath,
24
+ minCollateralUsd: 0n,
25
+ minPositionSizeUsd: 0n,
26
+ };
27
+ }
28
+ function increase(marketInfo, isLong, collateralAmount, trigger, fixed) {
29
+ return getIncreasePositionAmounts({
30
+ marketInfo,
31
+ indexToken: marketInfo.indexToken,
32
+ initialCollateralToken: marketInfo.shortToken,
33
+ collateralToken: marketInfo.shortToken,
34
+ isLong,
35
+ initialCollateralAmount: collateralAmount,
36
+ indexTokenAmount: undefined,
37
+ leverage: 10000n,
38
+ position: undefined,
39
+ externalSwapQuote: undefined,
40
+ userReferralInfo: undefined,
41
+ strategy: "leverageByCollateral",
42
+ findSwapPath: () => undefined,
43
+ uiFeeFactor: 0n,
44
+ marketsInfoData: { [marketInfo.marketTokenAddress]: marketInfo },
45
+ chainId: ARBITRUM,
46
+ externalSwapQuoteParams: undefined,
47
+ limitOrderType: trigger === undefined ? undefined : OrderType.LimitIncrease,
48
+ triggerPrice: trigger,
49
+ fixedAcceptablePriceImpactBps: fixed,
50
+ acceptablePriceImpactBuffer: 30,
51
+ isSetAcceptablePriceImpactEnabled: true,
52
+ });
53
+ }
54
+ function positionInfo(marketInfo, sizeInUsd, sizeInTokens, isLong = true) {
55
+ const value = (sizeInTokens * (isLong ? marketInfo.indexToken.prices.minPrice : marketInfo.indexToken.prices.maxPrice)) /
56
+ 10n ** BigInt(marketInfo.indexToken.decimals);
57
+ return getPositionInfo({
58
+ marketInfo,
59
+ minCollateralUsd: 0n,
60
+ position: {
61
+ key: "position",
62
+ contractKey: "position",
63
+ account: "account",
64
+ marketAddress: marketInfo.marketTokenAddress,
65
+ collateralTokenAddress: marketInfo.shortToken.address,
66
+ sizeInUsd,
67
+ sizeInTokens,
68
+ collateralAmount: 100000000n,
69
+ pendingBorrowingFeesUsd: 0n,
70
+ increasedAtTime: 0n,
71
+ decreasedAtTime: 0n,
72
+ isLong,
73
+ fundingFeeAmount: 0n,
74
+ claimableLongTokenAmount: 0n,
75
+ claimableShortTokenAmount: 0n,
76
+ pnl: isLong ? value - sizeInUsd : sizeInUsd - value,
77
+ positionValueInUsd: value,
78
+ positionFeeAmount: 0n,
79
+ traderDiscountAmount: 0n,
80
+ uiFeeAmount: 0n,
81
+ pendingImpactAmount: 0n,
82
+ data: "",
83
+ },
84
+ });
85
+ }
86
+ describe("gmsol trade math", () => {
87
+ it("accepts the native minimum margin boundary FESOL-57", () => {
88
+ const sizeInUsd = 10000000198019801980199n * 10n ** 10n;
89
+ const marketInfo = market({
90
+ decimals: 9,
91
+ minPrice: P,
92
+ maxPrice: P,
93
+ tradeMath: "gmsol",
94
+ overrides: { longInterestUsd: sizeInUsd, minCollateralFactor: P / 100n },
95
+ });
96
+ for (const collateralDelta of [-1n, 0n, 1n]) {
97
+ const margin = getResultingPositionMarginState({
98
+ marketInfo,
99
+ collateralToken: marketInfo.shortToken,
100
+ sizeInUsd,
101
+ sizeInTokens: 100n * 10n ** 9n,
102
+ collateralAmount: 1000002n + collateralDelta,
103
+ pendingImpactAmount: 0n,
104
+ minCollateralUsd: 0n,
105
+ isLong: true,
106
+ userReferralInfo: undefined,
107
+ });
108
+ expect(margin.minCollateralUsdForLeverage).toBe(100000001980198019801n * 10n ** 10n);
109
+ expect(margin.isLiquidatable).toBe(collateralDelta < 0n);
110
+ }
111
+ });
112
+ it("quantizes capped PnL before realizing a partial close FESOL-57", () => {
113
+ for (const isLong of [true, false]) {
114
+ const marketInfo = market({
115
+ decimals: 9,
116
+ minPrice: P,
117
+ maxPrice: P,
118
+ tradeMath: "gmsol",
119
+ overrides: {
120
+ longInterestUsd: 100n * P,
121
+ shortInterestUsd: 100n * P,
122
+ longInterestInTokens: 103n * 10n ** 9n,
123
+ shortInterestInTokens: 97n * 10n ** 9n,
124
+ longPoolAmount: 500000n * 10n ** 9n,
125
+ shortPoolAmount: 500000n * 10n ** 6n,
126
+ maxPnlFactorForTradersLong: P / 1000000n,
127
+ maxPnlFactorForTradersShort: P / 1000000n,
128
+ },
129
+ });
130
+ const position = positionInfo(marketInfo, 100n * P, (isLong ? 101n : 99n) * 10n ** 9n, isLong);
131
+ const close = getDecreasePositionAmounts({
132
+ marketInfo,
133
+ collateralToken: marketInfo.shortToken,
134
+ isLong,
135
+ position,
136
+ closeSizeUsd: 33n * P,
137
+ keepLeverage: false,
138
+ userReferralInfo: undefined,
139
+ minCollateralUsd: 0n,
140
+ minPositionSizeUsd: 0n,
141
+ uiFeeFactor: 0n,
142
+ isSetAcceptablePriceImpactEnabled: false,
143
+ });
144
+ expect(close.estimatedPnl).toBe(16666666666666666666n * 10n ** 10n);
145
+ expect(close.realizedPnl).toBe(5499999999999999999n * 10n ** 10n);
146
+ }
147
+ });
148
+ it("quantizes impact caps before settling collateral atoms FESOL-57", () => {
149
+ const nativeUnit = 10n ** 10n;
150
+ const canonicalSize = 100n * P + 3n * nativeUnit;
151
+ const cappedMarket = market({
152
+ decimals: 9,
153
+ minPrice: P,
154
+ maxPrice: P,
155
+ tradeMath: "gmsol",
156
+ overrides: {
157
+ longInterestUsd: 1000n * P,
158
+ shortInterestUsd: 1000n * P,
159
+ positionImpactFactorNegative: P,
160
+ maxPositionImpactFactorNegative: (3n * P) / 10n,
161
+ },
162
+ });
163
+ for (const sign of [-1n, 1n]) {
164
+ const requested = sign * (canonicalSize + nativeUnit - 1n);
165
+ expect(getPriceImpactForPosition(cappedMarket, requested, true)).toEqual(getPriceImpactForPosition(cappedMarket, sign * canonicalSize, true));
166
+ expect(getCappedPositionImpactUsd(cappedMarket, requested * sign, true, sign > 0n, {
167
+ shouldCapNegativeImpact: true,
168
+ }).priceImpactDeltaUsd).toBe(-30n * P);
169
+ }
170
+ expect(() => getPriceImpactForPosition({ ...cappedMarket, longInterestUsd: 1000n * P + 1n }, P, true)).toThrow(GmsolPriceImpactError);
171
+ const evmMarket = {
172
+ ...cappedMarket,
173
+ tradeMath: undefined,
174
+ useOpenInterestInTokensForBalance: false,
175
+ positionImpactExponentFactorNegative: P,
176
+ };
177
+ expect(getPriceImpactForPosition(evmMarket, canonicalSize + nativeUnit - 1n, true).priceImpactDeltaUsd).not.toBe(getPriceImpactForPosition(evmMarket, canonicalSize, true).priceImpactDeltaUsd);
178
+ for (const isLong of [true, false])
179
+ for (const dust of [0n, 10n ** 10n]) {
180
+ const marketInfo = market({
181
+ decimals: 9,
182
+ minPrice: P,
183
+ maxPrice: P,
184
+ tradeMath: "gmsol",
185
+ overrides: {
186
+ longInterestUsd: (isLong ? 100n : 200n) * P,
187
+ shortInterestUsd: (isLong ? 200n : 100n) * P,
188
+ positionImpactFactorNegative: 21n * 10n ** 25n,
189
+ maxPositionImpactFactorNegative: P / 100n,
190
+ maxPositionImpactFactorPositive: P / 100n,
191
+ },
192
+ });
193
+ const sizeDeltaUsd = 50n * P + dust;
194
+ const position = positionInfo(marketInfo, 100n * P, 100n * 10n ** 9n, isLong);
195
+ const close = getDecreasePositionAmounts({
196
+ marketInfo,
197
+ collateralToken: marketInfo.shortToken,
198
+ isLong,
199
+ position,
200
+ closeSizeUsd: sizeDeltaUsd,
201
+ keepLeverage: false,
202
+ userReferralInfo: undefined,
203
+ minCollateralUsd: 0n,
204
+ minPositionSizeUsd: 0n,
205
+ uiFeeFactor: 0n,
206
+ isSetAcceptablePriceImpactEnabled: false,
207
+ });
208
+ expect(close.totalPendingImpactDeltaUsd).toBe(-P / 2n);
209
+ expect(close.priceImpactDiffUsd).toBe((17n * P) / 8n);
210
+ expect(position.collateralAmount - close.payedRemainingCollateralAmount).toBe(97375000n);
211
+ for (const sign of [-1n, 1n]) {
212
+ expect(capPositionImpactUsdByMaxPriceImpactFactor(marketInfo, sizeDeltaUsd, sign * P)).toBe((sign * P) / 2n);
213
+ }
214
+ }
215
+ });
216
+ it("deducts increase fees in collateral token atoms FESOL-57", () => {
217
+ const marketInfo = market({
218
+ decimals: 8,
219
+ minPrice: 60000n * P,
220
+ maxPrice: 60000n * P,
221
+ tradeMath: "gmsol",
222
+ overrides: {
223
+ positionFeeFactorForBalanceWasImproved: P / 2500n,
224
+ positionFeeFactorForBalanceWasNotImproved: P / 2500n,
225
+ },
226
+ });
227
+ const result = getIncreasePositionAmounts({
228
+ marketInfo,
229
+ indexToken: marketInfo.indexToken,
230
+ initialCollateralToken: marketInfo.longToken,
231
+ collateralToken: marketInfo.longToken,
232
+ isLong: true,
233
+ initialCollateralAmount: 100000n,
234
+ indexTokenAmount: 1667083n,
235
+ position: undefined,
236
+ externalSwapQuote: undefined,
237
+ userReferralInfo: undefined,
238
+ strategy: "independent",
239
+ findSwapPath: () => undefined,
240
+ uiFeeFactor: 0n,
241
+ marketsInfoData: { [marketInfo.marketTokenAddress]: marketInfo },
242
+ chainId: ARBITRUM,
243
+ externalSwapQuoteParams: undefined,
244
+ isSetAcceptablePriceImpactEnabled: false,
245
+ });
246
+ expect(result.sizeDeltaUsd).toBe((10002498n * P) / 10000n);
247
+ expect(result.positionFeeUsd).toBe((40009992n * P) / 100000000n);
248
+ expect(result.collateralDeltaAmount).toBe(99334n);
249
+ expect(result.collateralDeltaUsd).toBe((596004n * P) / 10000n);
250
+ });
251
+ it("values trigger collateral and funding at the execution price FESOL-57", () => {
252
+ const marketInfo = market({ decimals: 8, minPrice: 50000n * P, maxPrice: 50000n * P, tradeMath: "gmsol" });
253
+ const position = getPositionInfo({
254
+ marketInfo,
255
+ minCollateralUsd: 0n,
256
+ position: {
257
+ ...positionInfo(marketInfo, 600n * P, 1000000n),
258
+ collateralTokenAddress: marketInfo.longTokenAddress,
259
+ collateralAmount: 100000n,
260
+ fundingFeeAmount: 1000n,
261
+ },
262
+ });
263
+ const result = getDecreasePositionAmounts({
264
+ marketInfo,
265
+ collateralToken: marketInfo.longToken,
266
+ isLong: true,
267
+ position,
268
+ closeSizeUsd: position.sizeInUsd,
269
+ keepLeverage: false,
270
+ userReferralInfo: undefined,
271
+ minCollateralUsd: 0n,
272
+ minPositionSizeUsd: 0n,
273
+ uiFeeFactor: 0n,
274
+ isSetAcceptablePriceImpactEnabled: false,
275
+ forceDecreaseSwapType: DecreasePositionSwapType.NoSwap,
276
+ triggerOrderType: OrderType.LimitDecrease,
277
+ triggerPrice: 60000n * P,
278
+ });
279
+ expect(result.fundingFeeUsd).toBe((6n * P) / 10n);
280
+ expect(result.collateralDeltaUsd).toBe(60n * P);
281
+ expect(result.receiveTokenAmount).toBe(99000n);
282
+ expect(result.receiveUsd).toBe((594n * P) / 10n);
283
+ expect(position.pendingFundingFeesUsd).toBe(P / 2n);
284
+ });
285
+ it("settles each collateral shortfall in PnL token atoms FESOL-57", () => {
286
+ const size = (250125n * P) / 100n;
287
+ for (const [markPrice, triggerPrice, isTwap, fundingFeeAmount, feeFactor, pnlAmount, collateralAmount, pnlUsd, unpaidUsd,] of [
288
+ [60000n * P, undefined, false, 10000300n, P / 2500n, 829583n, 0n, (4977498n * P) / 10000n, 0n],
289
+ [60000n * P, 60000n * P, false, 10000300n, P / 2500n, 829583n, 0n, (4977498n * P) / 10000n, 0n],
290
+ [60000n * P, undefined, true, 10000300n, P / 2500n, 829583n, 0n, (4977498n * P) / 10000n, 0n],
291
+ [50000n * P, 60000n * P, false, 0n, 0n, 831250n, 10000000n, (49875n * P) / 100n, 0n],
292
+ [60000n * P, undefined, false, 509750000n, 0n, 0n, 0n, 0n, (9996n * P) / 10000n],
293
+ ]) {
294
+ const marketInfo = market({
295
+ decimals: 8,
296
+ minPrice: markPrice,
297
+ maxPrice: markPrice,
298
+ tradeMath: "gmsol",
299
+ overrides: {
300
+ longInterestUsd: size,
301
+ shortInterestUsd: size,
302
+ longInterestInTokens: 5000000n,
303
+ shortInterestInTokens: 5000000n,
304
+ longPoolAmount: 100n * 10n ** 8n,
305
+ shortPoolAmount: 1000000n * 10n ** 6n,
306
+ maxPnlFactorForTradersLong: P,
307
+ positionFeeFactorForBalanceWasImproved: feeFactor,
308
+ positionFeeFactorForBalanceWasNotImproved: feeFactor,
309
+ },
310
+ });
311
+ const position = getPositionInfo({
312
+ marketInfo,
313
+ minCollateralUsd: 0n,
314
+ position: {
315
+ ...positionInfo(marketInfo, size, 5000000n),
316
+ collateralAmount: 10000000n,
317
+ fundingFeeAmount,
318
+ },
319
+ });
320
+ const result = getDecreasePositionAmounts({
321
+ marketInfo,
322
+ collateralToken: marketInfo.shortToken,
323
+ isLong: true,
324
+ position,
325
+ closeSizeUsd: size,
326
+ keepLeverage: false,
327
+ userReferralInfo: undefined,
328
+ minCollateralUsd: 0n,
329
+ minPositionSizeUsd: 0n,
330
+ uiFeeFactor: 0n,
331
+ isSetAcceptablePriceImpactEnabled: false,
332
+ forceDecreaseSwapType: DecreasePositionSwapType.NoSwap,
333
+ triggerOrderType: triggerPrice === undefined ? undefined : OrderType.LimitDecrease,
334
+ triggerPrice,
335
+ isTwap,
336
+ });
337
+ expect(result.primaryOutput).toEqual({
338
+ tokenAddress: marketInfo.longTokenAddress,
339
+ amount: pnlAmount,
340
+ usd: pnlUsd,
341
+ });
342
+ expect(result.secondaryOutput.amount).toBe(collateralAmount);
343
+ expect(result.payedRemainingCollateralAmount).toBe(10000000n - collateralAmount);
344
+ expect(result.unpaidCostUsd).toBe(unpaidUsd);
345
+ expect(marketInfo.indexToken.prices.minPrice).toBe(markPrice);
346
+ }
347
+ });
348
+ it("values a gmsol close with the impact withheld beyond the cap FESOL-57", () => {
349
+ for (const tradeMath of ["gmsol", undefined]) {
350
+ const marketInfo = market({
351
+ decimals: 8,
352
+ minPrice: P,
353
+ maxPrice: P,
354
+ tradeMath,
355
+ overrides: {
356
+ longInterestUsd: 100n * P,
357
+ shortInterestUsd: 100n * P,
358
+ longInterestInTokens: 100n * 10n ** 8n,
359
+ shortInterestInTokens: 100n * 10n ** 8n,
360
+ positionImpactFactorNegative: 2n * 10n ** 27n,
361
+ maxPositionImpactFactorNegative: 5n * 10n ** 28n,
362
+ },
363
+ });
364
+ const position = positionInfo(marketInfo, 100n * P, 100n * 10n ** 8n);
365
+ const close = getDecreasePositionAmounts({
366
+ marketInfo,
367
+ collateralToken: marketInfo.shortToken,
368
+ isLong: true,
369
+ position,
370
+ closeSizeUsd: position.sizeInUsd,
371
+ keepLeverage: false,
372
+ userReferralInfo: undefined,
373
+ minCollateralUsd: 0n,
374
+ minPositionSizeUsd: 0n,
375
+ uiFeeFactor: 0n,
376
+ isSetAcceptablePriceImpactEnabled: false,
377
+ });
378
+ expect(position.closePriceImpactDeltaUsd).toBe(close.closePriceImpactDeltaUsd);
379
+ expect(position.closePriceImpactDeltaUsd).toBeLessThan(-19n * P);
380
+ expect(position.netPriceImapctDeltaUsd).toBe(tradeMath ? -5n * P : position.closePriceImpactDeltaUsd);
381
+ expect(position.netValueAfterAllFees).toBe(position.collateralUsd + position.closePriceImpactDeltaUsd);
382
+ expect(position.pnlAfterAllFees).toBe(position.closePriceImpactDeltaUsd);
383
+ expect(position.netValueAfterAllFees - close.receiveUsd).toBeLessThanOrEqual(10n ** 24n);
384
+ expect(close.receiveUsd - position.netValueAfterAllFees).toBeLessThanOrEqual(10n ** 24n);
385
+ }
386
+ });
387
+ it("rejects gmsol increases that fill no index token atoms FESOL-57", () => {
388
+ const imbalanced = {
389
+ longInterestUsd: 1000n * P,
390
+ longInterestInTokens: 5n * 10n ** 6n,
391
+ positionImpactFactorNegative: 10n ** 25n,
392
+ positionImpactExponentFactorNegative: P,
393
+ };
394
+ for (const { name, overrides, collateralAmount } of [
395
+ { name: "below one atom", overrides: {}, collateralAmount: 100n },
396
+ { name: "one atom consumed by impact", overrides: imbalanced, collateralAmount: 300n },
397
+ { name: "below one atom with impact", overrides: imbalanced, collateralAmount: 100n },
398
+ ]) {
399
+ const marketInfo = market({
400
+ decimals: 8,
401
+ minPrice: 20000n * P,
402
+ maxPrice: 20000n * P,
403
+ overrides,
404
+ tradeMath: "gmsol",
405
+ });
406
+ const values = increase(marketInfo, true, collateralAmount);
407
+ const sizeDeltaUsd = collateralAmount * 10n ** 24n;
408
+ expect([name, values.sizeDeltaUsd, values.sizeDeltaInTokens, values.acceptablePrice]).toEqual([name, 0n, 0n, 0n]);
409
+ expect(getIncreaseResultingPositionState({
410
+ marketInfo,
411
+ collateralToken: marketInfo.shortToken,
412
+ isLong: true,
413
+ existingPosition: {
414
+ sizeInUsd: 100n * P,
415
+ sizeInTokens: 5n * 10n ** 5n,
416
+ collateralAmount: 100n * 10n ** 6n,
417
+ pendingImpactAmount: 0n,
418
+ },
419
+ sizeDeltaUsd,
420
+ sizeDeltaInTokens: 1n,
421
+ collateralDeltaAmount: collateralAmount,
422
+ minCollateralUsd: 0n,
423
+ userReferralInfo: undefined,
424
+ })).toBeUndefined();
425
+ }
426
+ });
427
+ it("rounds decrease execution adjustments in native price units FESOL-57", () => {
428
+ for (const { isLong, improved, cap, expectedUnitPrice } of [
429
+ { isLong: true, improved: false, cap: P, expectedUnitPrice: 74750000000n },
430
+ { isLong: false, improved: true, cap: P, expectedUnitPrice: 76850000000n },
431
+ { isLong: true, improved: false, cap: P / 100n, expectedUnitPrice: 79000000000n },
432
+ { isLong: false, improved: true, cap: P / 100n, expectedUnitPrice: 79000000000n },
433
+ ]) {
434
+ const sideOi = improved ? 200n : 100n;
435
+ const otherOi = improved ? 100n : 200n;
436
+ const marketInfo = market({
437
+ decimals: 9,
438
+ minPrice: (4n * P) / 5n,
439
+ maxPrice: (4n * P) / 5n,
440
+ tradeMath: "gmsol",
441
+ overrides: {
442
+ longInterestUsd: (isLong ? sideOi : otherOi) * P,
443
+ shortInterestUsd: (isLong ? otherOi : sideOi) * P,
444
+ positionImpactFactorPositive: (21n * P) / 100000n,
445
+ positionImpactFactorNegative: (21n * P) / 100000n,
446
+ positionImpactExponentFactorPositive: 2n * P,
447
+ positionImpactExponentFactorNegative: 2n * P,
448
+ positionImpactPoolAmount: 10000000000n,
449
+ maxPositionImpactFactorPositive: cap,
450
+ maxPositionImpactFactorNegative: cap,
451
+ },
452
+ });
453
+ for (const sizeDeltaInTokens of [undefined, 0n, 50000000000n]) {
454
+ const result = getAcceptablePriceInfo({
455
+ marketInfo,
456
+ isIncrease: false,
457
+ isLimit: false,
458
+ isLong,
459
+ indexPrice: (4n * P) / 5n,
460
+ sizeDeltaUsd: 50n * P,
461
+ sizeDeltaInTokens,
462
+ positionSizeInUsd: 100n * P,
463
+ positionSizeInTokens: 99999999999n,
464
+ });
465
+ expect(result.acceptablePrice).toBe(expectedUnitPrice * 10n ** 19n);
466
+ }
467
+ }
468
+ });
469
+ it("evaluates gmsol limit increases at the trigger and covers the execution FESOL-57", () => {
470
+ for (const isLong of [false, true]) {
471
+ const marketInfo = market({
472
+ decimals: 9,
473
+ minPrice: P,
474
+ maxPrice: P,
475
+ tradeMath: "gmsol",
476
+ overrides: { positionImpactFactorNegative: 0n, positionImpactFactorPositive: 0n },
477
+ });
478
+ for (const dust of [0n, 1n, 9999999999n]) {
479
+ expect(getAcceptablePriceInfo({
480
+ marketInfo,
481
+ sizeDeltaUsd: P + dust,
482
+ indexPrice: P,
483
+ isIncrease: true,
484
+ isLimit: false,
485
+ isLong,
486
+ }).acceptablePrice).toBe(P);
487
+ }
488
+ }
489
+ for (const { isLong, isLimit, indexPrice, nativeUnitPrice } of [
490
+ { isLong: true, isLimit: false, indexPrice: 110n * P, nativeUnitPrice: 111361079865016872890n },
491
+ { isLong: false, isLimit: false, indexPrice: 90n * P, nativeUnitPrice: 89108910891089108910n },
492
+ { isLong: true, isLimit: true, indexPrice: 100n * P, nativeUnitPrice: 101020408163265306122n },
493
+ { isLong: false, isLimit: true, indexPrice: 100n * P, nativeUnitPrice: 99000000000000000000n },
494
+ ]) {
495
+ const marketInfo = market({
496
+ decimals: 2,
497
+ minPrice: 90n * P,
498
+ maxPrice: 110n * P,
499
+ tradeMath: "gmsol",
500
+ overrides: {
501
+ longInterestUsd: 100n * P,
502
+ shortInterestUsd: 100n * P,
503
+ positionImpactFactorNegative: P / 100n,
504
+ positionImpactExponentFactorNegative: P,
505
+ },
506
+ });
507
+ const result = getAcceptablePriceInfo({
508
+ marketInfo,
509
+ isIncrease: true,
510
+ isLimit,
511
+ isLong,
512
+ indexPrice,
513
+ sizeDeltaUsd: 990n * P,
514
+ });
515
+ expect(result.acceptablePrice).toBe(nativeUnitPrice * 10n ** 12n);
516
+ expect(marketInfo.indexToken.prices).toEqual({ minPrice: 90n * P, maxPrice: 110n * P });
517
+ }
518
+ for (const { tradeMath, isLong, decimals, price, factor, exponent, minBps } of [
519
+ { tradeMath: "gmsol", isLong: true, decimals: 6, price: P, factor: P / 1000n, exponent: 2n * P, minBps: 1142n },
520
+ { tradeMath: "gmsol", isLong: false, decimals: 6, price: P, factor: P / 1000n, exponent: 2n * P, minBps: 940n },
521
+ { tradeMath: "gmsol", isLong: true, decimals: 2, price: 3n * P, factor: 0n, exponent: P, minBps: 132n },
522
+ { tradeMath: "gmsol", isLong: false, decimals: 2, price: 3n * P, factor: 0n, exponent: P, minBps: 227n },
523
+ { tradeMath: undefined, isLong: true, decimals: 2, price: 3n * P, factor: 0n, exponent: P, minBps: 30n },
524
+ ]) {
525
+ const marketInfo = market({
526
+ decimals,
527
+ minPrice: price,
528
+ maxPrice: price,
529
+ tradeMath,
530
+ overrides: {
531
+ longInterestUsd: 100n * P,
532
+ shortInterestUsd: 100n * P,
533
+ positionImpactFactorNegative: factor,
534
+ positionImpactExponentFactorNegative: exponent,
535
+ maxPositionImpactFactorNegative: P / 2n,
536
+ },
537
+ });
538
+ const sizeDeltaUsd = (decimals === 6 ? 100n : 1n) * P;
539
+ const values = increase(marketInfo, isLong, sizeDeltaUsd / 10n ** 24n, price);
540
+ const execution = (values.sizeDeltaUsd * 10n ** BigInt(decimals)) / values.sizeDeltaInTokens;
541
+ const bufferUsd = (price * 30n) / 10000n;
542
+ expect(values.recommendedAcceptablePriceDeltaBps).toBe(minBps);
543
+ if (tradeMath) {
544
+ expect(isLong ? values.acceptablePrice - execution : execution - values.acceptablePrice).toBeGreaterThanOrEqual(bufferUsd);
545
+ }
546
+ }
547
+ const fixedMarket = market({
548
+ decimals: 6,
549
+ minPrice: P,
550
+ maxPrice: P,
551
+ tradeMath: "gmsol",
552
+ overrides: {
553
+ longInterestUsd: 100n * P,
554
+ shortInterestUsd: 100n * P,
555
+ positionImpactFactorNegative: P / 1000n,
556
+ positionImpactExponentFactorNegative: 2n * P,
557
+ },
558
+ });
559
+ const fixed = increase(fixedMarket, true, 100000000n, P, 500n);
560
+ expect(fixed.acceptablePrice).toBe((105n * P) / 100n);
561
+ });
562
+ it("preserves native partial-close boundaries and zero UI fees FESOL-57", () => {
563
+ for (const { tradeMath, price, size, closeSize, units, minimum, full, withdrawal } of [
564
+ {
565
+ tradeMath: "gmsol",
566
+ price: 94n * P,
567
+ size: 1000n * P,
568
+ closeSize: 500n * P,
569
+ units: 10000000000n,
570
+ minimum: 0n,
571
+ full: false,
572
+ withdrawal: 20n * P,
573
+ },
574
+ {
575
+ tradeMath: "gmsol",
576
+ price: 92n * P,
577
+ size: 1000n * P,
578
+ closeSize: 500n * P,
579
+ units: 10000000000n,
580
+ minimum: 0n,
581
+ full: false,
582
+ withdrawal: 10n * P,
583
+ },
584
+ {
585
+ tradeMath: "gmsol",
586
+ price: (91998n * P) / 1000n,
587
+ size: 1000n * P,
588
+ closeSize: 500n * P,
589
+ units: 10000000000n,
590
+ minimum: 0n,
591
+ full: true,
592
+ withdrawal: 100n * P,
593
+ },
594
+ {
595
+ tradeMath: undefined,
596
+ price: 94n * P,
597
+ size: 1000n * P,
598
+ closeSize: 500n * P,
599
+ units: 10000000000n,
600
+ minimum: 0n,
601
+ full: false,
602
+ withdrawal: 20n * P,
603
+ },
604
+ {
605
+ tradeMath: "gmsol",
606
+ price: 100n * P,
607
+ size: 10n * P,
608
+ closeSize: (95n * P) / 10n,
609
+ units: 100000000n,
610
+ minimum: P / 10n,
611
+ full: false,
612
+ withdrawal: 0n,
613
+ },
614
+ {
615
+ tradeMath: undefined,
616
+ price: 100n * P,
617
+ size: 10n * P,
618
+ closeSize: (95n * P) / 10n,
619
+ units: 100000000n,
620
+ minimum: P / 10n,
621
+ full: true,
622
+ withdrawal: 100n * P,
623
+ },
624
+ ]) {
625
+ const marketInfo = market({
626
+ decimals: 9,
627
+ minPrice: price,
628
+ maxPrice: price,
629
+ tradeMath,
630
+ overrides: { minCollateralFactor: P / 50n },
631
+ });
632
+ marketInfo.minCollateralUsd = 10n * P;
633
+ marketInfo.minPositionSizeUsd = minimum;
634
+ const position = positionInfo(marketInfo, size, units);
635
+ const result = getDecreasePositionAmounts({
636
+ marketInfo,
637
+ collateralToken: marketInfo.shortToken,
638
+ isLong: true,
639
+ position,
640
+ closeSizeUsd: closeSize,
641
+ keepLeverage: size > 10n * P,
642
+ userReferralInfo: undefined,
643
+ minCollateralUsd: 10n * P,
644
+ minPositionSizeUsd: minimum,
645
+ uiFeeFactor: 0n,
646
+ isSetAcceptablePriceImpactEnabled: false,
647
+ forceDecreaseSwapType: DecreasePositionSwapType.NoSwap,
648
+ });
649
+ expect([result.isFullClose, result.sizeDeltaUsd, result.collateralDeltaUsd]).toEqual([
650
+ full,
651
+ full ? size : closeSize,
652
+ withdrawal,
653
+ ]);
654
+ }
655
+ for (const triggerOrderType of [undefined, OrderType.LimitDecrease]) {
656
+ const marketInfo = market({
657
+ decimals: 8,
658
+ minPrice: 100n * P,
659
+ maxPrice: 100n * P,
660
+ tradeMath: "gmsol",
661
+ overrides: {
662
+ longInterestUsd: 1000n * P,
663
+ shortInterestUsd: 1000n * P,
664
+ positionImpactFactorNegative: P / 25n,
665
+ positionImpactExponentFactorNegative: P,
666
+ maxPositionImpactFactorNegative: P / 50n,
667
+ },
668
+ });
669
+ const position = positionInfo(marketInfo, 1000n * P, 10n * 10n ** 8n);
670
+ const result = getDecreasePositionAmounts({
671
+ marketInfo,
672
+ collateralToken: marketInfo.shortToken,
673
+ isLong: true,
674
+ position,
675
+ closeSizeUsd: 500n * P,
676
+ keepLeverage: true,
677
+ userReferralInfo: undefined,
678
+ minCollateralUsd: 0n,
679
+ minPositionSizeUsd: 0n,
680
+ uiFeeFactor: 0n,
681
+ triggerOrderType,
682
+ triggerPrice: 100n * P,
683
+ isSetAcceptablePriceImpactEnabled: false,
684
+ forceDecreaseSwapType: DecreasePositionSwapType.NoSwap,
685
+ });
686
+ expect(result.isFullClose).toBe(false);
687
+ expect(result.closePriceImpactDeltaUsd).toBe(-20n * P);
688
+ expect(result.priceImpactDiffUsd).toBe(10n * P);
689
+ expect(result.collateralDeltaUsd).toBe(30n * P);
690
+ expect(result.payedRemainingCollateralUsd).toBe(20n * P);
691
+ expect(result.receiveUsd).toBe(20n * P);
692
+ }
693
+ for (const tradeMath of ["gmsol", undefined]) {
694
+ const marketInfo = market({
695
+ decimals: 8,
696
+ minPrice: P,
697
+ maxPrice: P,
698
+ tradeMath,
699
+ overrides: {
700
+ swapFeeFactorForBalanceWasImproved: 0n,
701
+ swapFeeFactorForBalanceWasNotImproved: 0n,
702
+ swapImpactFactorPositive: 0n,
703
+ swapImpactFactorNegative: 0n,
704
+ },
705
+ });
706
+ const position = positionInfo(marketInfo, 100n * P, 100n * 10n ** 8n, false);
707
+ const marketsInfoData = { [marketInfo.marketTokenAddress]: marketInfo };
708
+ const findSwapPath = (usdIn) => getSwapPathStats({
709
+ marketsInfoData,
710
+ swapPath: [marketInfo.marketTokenAddress],
711
+ initialCollateralAddress: marketInfo.shortToken.address,
712
+ wrappedNativeTokenAddress: "WETH",
713
+ usdIn,
714
+ shouldUnwrapNativeToken: false,
715
+ shouldApplyPriceImpact: true,
716
+ swapPricingType: SwapPricingType.Swap,
717
+ });
718
+ for (const uiFeeFactor of [0n, P / 100n]) {
719
+ const result = getOptimalDecreaseAndSwapAmounts({
720
+ marketInfo,
721
+ collateralToken: marketInfo.shortToken,
722
+ isLong: false,
723
+ position,
724
+ closeSizeUsd: position.sizeInUsd,
725
+ keepLeverage: false,
726
+ userReferralInfo: undefined,
727
+ minCollateralUsd: 0n,
728
+ minPositionSizeUsd: 0n,
729
+ uiFeeFactor,
730
+ isSetAcceptablePriceImpactEnabled: false,
731
+ receiveToken: marketInfo.indexToken,
732
+ findSwapPath,
733
+ findSwapPathFromPnl: findSwapPath,
734
+ marketsInfoData,
735
+ chainId: ARBITRUM,
736
+ });
737
+ expect(result.swapAmounts?.usdOut).toBe(tradeMath || uiFeeFactor === 0n ? 100n * P : (9801n * P) / 100n);
738
+ expect(result.decreaseAmounts.uiFeeUsd).toBe(tradeMath || uiFeeFactor === 0n ? 0n : P);
739
+ }
740
+ }
741
+ const evm = market({
742
+ decimals: 8,
743
+ minPrice: P,
744
+ maxPrice: P,
745
+ overrides: {
746
+ swapFeeFactorForBalanceWasImproved: 0n,
747
+ swapFeeFactorForBalanceWasNotImproved: 0n,
748
+ swapImpactFactorPositive: 0n,
749
+ swapImpactFactorNegative: 0n,
750
+ },
751
+ });
752
+ const marketsInfoData = {
753
+ evm: { ...evm, marketTokenAddress: "evm" },
754
+ gmsol: { ...evm, marketTokenAddress: "gmsol", tradeMath: "gmsol" },
755
+ };
756
+ for (const [swapPath, collateralToken, partUsd] of [
757
+ [["evm"], evm.shortToken, 99n * P],
758
+ [["gmsol"], evm.shortToken, 100n * P],
759
+ [["gmsol", "evm"], evm.longToken, 99n * P],
760
+ ]) {
761
+ const parts = getTwapIncreasePartsGrossCollateralUsd({
762
+ marketsInfoData,
763
+ swapPath: [...swapPath],
764
+ initialCollateralToken: evm.longToken,
765
+ collateralToken,
766
+ initialCollateralAmountPerPart: 100n * 10n ** 8n,
767
+ numberOfParts: 2,
768
+ uiFeeFactor: P / 100n,
769
+ wrappedNativeTokenAddress: "WETH",
770
+ });
771
+ expect([swapPath, parts]).toEqual([swapPath, [partUsd, partUsd]]);
772
+ }
773
+ });
774
+ it("settles gmsol closes, close margins and closing fees with native rounding FESOL-57", () => {
775
+ for (const [tradeMath, priceDelta, longOi, impactFactor, capFactor, exponent, receive] of [
776
+ ["gmsol", 0n, 100n, 200000005n * 10n ** 21n, P / 20n, 1n, 79999999n],
777
+ [undefined, 0n, 100n, 200000005n * 10n ** 21n, P / 20n, 1n, 80000000n],
778
+ ["gmsol", 0n, 100n, 20000001n * 10n ** 22n, 50000005n * 10n ** 21n, 1n, 79999998n],
779
+ ["gmsol", -6n * 10n ** 21n, 100n, 6n * 10n ** 21n, P, 1n, 99999998n],
780
+ ["gmsol", 6n * 10n ** 21n, 200n, 6n * 10n ** 21n, P, 1n, 100000000n],
781
+ ["gmsol", 0n, 200n, 21n * 10n ** 25n, P, 2n, 102100000n],
782
+ ["gmsol", 0n, 200n, 21n * 10n ** 23n, P, 3n, 102100000n],
783
+ ["gmsol", 0n, 200n, 21n * 10n ** 21n, P, 4n, 102100000n],
784
+ [undefined, 0n, 200n, 21n * 10n ** 25n, P, 2n, 102099999n],
785
+ ]) {
786
+ const marketInfo = market({
787
+ decimals: 9,
788
+ minPrice: P + priceDelta,
789
+ maxPrice: P + priceDelta,
790
+ tradeMath,
791
+ overrides: {
792
+ longInterestUsd: longOi * P,
793
+ shortInterestUsd: 100n * P,
794
+ longInterestInTokens: longOi * 10n ** 9n,
795
+ shortInterestInTokens: 100n * 10n ** 9n,
796
+ positionImpactPoolAmount: 10n * 10n ** 9n,
797
+ positionImpactFactorPositive: impactFactor,
798
+ positionImpactFactorNegative: impactFactor,
799
+ positionImpactExponentFactorPositive: exponent * P,
800
+ positionImpactExponentFactorNegative: exponent * P,
801
+ maxPositionImpactFactorPositive: P,
802
+ maxPositionImpactFactorNegative: capFactor,
803
+ longPoolAmount: 1000000000000n,
804
+ shortPoolAmount: 1000000000000n,
805
+ maxPnlFactorForTradersLong: P,
806
+ },
807
+ });
808
+ marketInfo.longToken = marketInfo.shortToken;
809
+ marketInfo.longTokenAddress = marketInfo.shortTokenAddress;
810
+ marketInfo.isSameCollaterals = true;
811
+ const position = positionInfo(marketInfo, 100n * P, 100n * 10n ** 9n);
812
+ const close = getDecreasePositionAmounts({
813
+ marketInfo,
814
+ collateralToken: marketInfo.shortToken,
815
+ isLong: true,
816
+ position,
817
+ closeSizeUsd: position.sizeInUsd,
818
+ keepLeverage: false,
819
+ userReferralInfo: undefined,
820
+ minCollateralUsd: 0n,
821
+ minPositionSizeUsd: 0n,
822
+ uiFeeFactor: 0n,
823
+ isSetAcceptablePriceImpactEnabled: false,
824
+ forceDecreaseSwapType: DecreasePositionSwapType.NoSwap,
825
+ });
826
+ expect([priceDelta, impactFactor, close.receiveTokenAmount]).toEqual([priceDelta, impactFactor, receive]);
827
+ }
828
+ for (const [tradeMath, minCollateralFactor, sizeDeltaUsd, withdrawal, expected] of [
829
+ ["gmsol", P / 100n, 500n * P, 50000000n, undefined],
830
+ [undefined, P / 100n, 500n * P, 50000000n, [false, true]],
831
+ ["gmsol", P / 100n, 500n * P, 20000000n, [false, false]],
832
+ ["gmsol", (15n * P) / 100n, 500n * P, 50000000n, [false, true]],
833
+ ["gmsol", P / 100n, 0n, 50000000n, [true, false]],
834
+ ]) {
835
+ const marketInfo = market({
836
+ decimals: 9,
837
+ minPrice: P,
838
+ maxPrice: P,
839
+ tradeMath,
840
+ overrides: { minCollateralFactor, longInterestUsd: 1000n * P, shortInterestUsd: 1000n * P },
841
+ });
842
+ marketInfo.minCollateralUsd = 75n * P;
843
+ const params = {
844
+ marketInfo,
845
+ collateralToken: marketInfo.shortToken,
846
+ isLong: true,
847
+ position: positionInfo(marketInfo, 1000n * P, 1000n * 10n ** 9n),
848
+ minCollateralUsd: 75n * P,
849
+ minPositionSizeUsd: 0n,
850
+ userReferralInfo: undefined,
851
+ };
852
+ const direct = getDecreaseResultingPositionMarginState({
853
+ ...params,
854
+ sizeDeltaUsd,
855
+ sizeDeltaInTokens: sizeDeltaUsd / 10n ** 21n,
856
+ collateralDeltaAmount: withdrawal,
857
+ payedRemainingCollateralAmount: 0n,
858
+ priceImpactDiffUsd: 0n,
859
+ });
860
+ const row = [tradeMath, minCollateralFactor, sizeDeltaUsd, withdrawal];
861
+ expect([row, direct && [direct.isLiquidatable, direct.isCollateralWithdrawalCancelled]]).toEqual([row, expected]);
862
+ if (sizeDeltaUsd > 0n) {
863
+ const decreaseAmounts = getDecreasePositionAmounts({
864
+ ...params,
865
+ closeSizeUsd: sizeDeltaUsd,
866
+ keepLeverage: false,
867
+ uiFeeFactor: 0n,
868
+ triggerOrderType: OrderType.LimitDecrease,
869
+ triggerPrice: P,
870
+ isSetAcceptablePriceImpactEnabled: false,
871
+ });
872
+ const stored = getTriggerDecreaseRemainingPositionMarginState({
873
+ ...params,
874
+ decreaseAmounts,
875
+ collateralDeltaAmount: withdrawal,
876
+ });
877
+ expect([row, stored]).toEqual([row, direct]);
878
+ }
879
+ }
880
+ for (const [tradeMath, collateralAmount, remainingCollateralUsd, isLiquidatable] of [
881
+ ["gmsol", 1005150n, (100015n * P) / 100000n, false],
882
+ ["gmsol", 1005149n, (1000149n * P) / 1000000n, true],
883
+ [undefined, 1005150n, (1000149n * P) / 1000000n, true],
884
+ ]) {
885
+ const marketInfo = market({
886
+ decimals: 9,
887
+ minPrice: P,
888
+ maxPrice: P,
889
+ tradeMath,
890
+ overrides: {
891
+ positionFeeFactorForBalanceWasImproved: 10n ** 26n,
892
+ positionFeeFactorForBalanceWasNotImproved: 10n ** 26n,
893
+ },
894
+ });
895
+ const state = getResultingPositionMarginState({
896
+ marketInfo,
897
+ collateralToken: marketInfo.shortToken,
898
+ sizeInUsd: (100015n * P) / 1000n,
899
+ sizeInTokens: 100015000000n,
900
+ collateralAmount,
901
+ pendingImpactAmount: 0n,
902
+ minCollateralUsd: 0n,
903
+ isLong: true,
904
+ userReferralInfo: undefined,
905
+ proDiscountFactor: P / 2n,
906
+ feeDiscountFactor: P / 2n,
907
+ });
908
+ expect([collateralAmount, state.remainingCollateralUsd, state.isLiquidatable]).toEqual([
909
+ collateralAmount,
910
+ remainingCollateralUsd,
911
+ isLiquidatable,
912
+ ]);
913
+ const fee = getPositionFee(marketInfo, P + 15000n * 10n ** 10n, false, undefined, undefined, P / 2n, P / 2n);
914
+ expect([fee.positionFeeUsd, fee.discountUsd]).toEqual(tradeMath === "gmsol"
915
+ ? [50000000000000010000000000n, 50000000000000000000000000n]
916
+ : [50000000000000007500000000n, 50000000000000007500000000n]);
917
+ }
918
+ });
919
+ it("keeps native impact precision and propagates unavailable Solana quotes FESOL-57", () => {
920
+ const calculate = (diff, exponent, next = 0n) => getPriceImpactUsd({
921
+ currentLongUsd: diff,
922
+ currentShortUsd: 0n,
923
+ nextLongUsd: next,
924
+ nextShortUsd: 0n,
925
+ factorPositive: P,
926
+ factorNegative: P,
927
+ exponentFactorPositive: exponent,
928
+ exponentFactorNegative: exponent,
929
+ tradeMath: "gmsol",
930
+ }).priceImpactDeltaUsd;
931
+ for (const [diff, exponent, expected] of [
932
+ [P - 10n ** 10n, 0n, 0n],
933
+ [P, P / 2n, P],
934
+ [2n * P, P / 2n, 1414213557n * 10n ** 21n],
935
+ [100n * P, (3n * P) / 2n, 999999998638n * 10n ** 21n],
936
+ [(123456n * P) / 10n, (11n * P) / 10n, 31670982733137n * 10n ** 21n],
937
+ [123456789123456789123n * 10n ** 10n, 2n * P + 10n ** 10n, 1524157877n * 10n ** 21n],
938
+ [P + 10n ** 21n, (257n * P) / 2n, 1000000129n * 10n ** 21n],
939
+ [2n * P - 10n ** 10n, 10n ** 10n, P],
940
+ [9223372036854775807n * 10n ** 21n, P / 2n, 96035880027389n * 10n ** 21n],
941
+ [18446744073709551615n * 10n ** 21n, P + 10n ** 10n, 18446744073709551615n * 10n ** 21n],
942
+ [(13n * P) / 10n + 10n ** 10n, 4n * P, 285610000000000000007n * 10n ** 10n],
943
+ [P + 10n ** 10n, 128n * P, P + 128n * 10n ** 10n],
944
+ ])
945
+ expect(calculate(diff, exponent)).toBe(expected);
946
+ for (const [diff, exponent] of [
947
+ [10000000000n * P, P / 2n],
948
+ [2n * P, (257n * P) / 2n],
949
+ [P + 10n ** 10n, 9223372036854775808n * 10n ** 21n],
950
+ [P + 10n ** 10n, 129n * P],
951
+ [P + 1n, P],
952
+ [(1n << 127n) * 10n ** 10n, P],
953
+ [((1n << 128n) - 1n) * 10n ** 10n, 2n * P],
954
+ ])
955
+ expect(() => calculate(diff, exponent)).toThrow(GmsolPriceImpactError);
956
+ for (const tradeMath of ["gmsol", undefined]) {
957
+ const m = market({
958
+ decimals: 8,
959
+ minPrice: P,
960
+ maxPrice: P,
961
+ tradeMath,
962
+ overrides: {
963
+ swapImpactExponentFactor: 129n * P,
964
+ longPoolAmount: 1000000n * 10n ** 8n,
965
+ shortPoolAmount: 1000000n * 10n ** 6n,
966
+ swapImpactFactorPositive: P / 1000n,
967
+ swapImpactFactorNegative: P / 1000n,
968
+ },
969
+ });
970
+ const marketsInfoData = { [m.marketTokenAddress]: m };
971
+ const route = [{ marketAddress: m.marketTokenAddress, from: m.longTokenAddress, to: m.shortTokenAddress }];
972
+ const quote = () => getSwapPathStats({
973
+ marketsInfoData,
974
+ swapPath: [m.marketTokenAddress],
975
+ initialCollateralAddress: m.longTokenAddress,
976
+ wrappedNativeTokenAddress: "WETH",
977
+ usdIn: 100n * P,
978
+ shouldUnwrapNativeToken: false,
979
+ shouldApplyPriceImpact: true,
980
+ swapPricingType: SwapPricingType.Swap,
981
+ });
982
+ const best = () => getBestSwapPath({
983
+ routes: [route],
984
+ usdIn: 100n * P,
985
+ estimator: createSwapEstimator(marketsInfoData, SwapPricingType.Swap),
986
+ });
987
+ if (tradeMath) {
988
+ expect(quote).toThrow(GmsolPriceImpactError);
989
+ expect(best).toThrow(GmsolPriceImpactError);
990
+ }
991
+ else {
992
+ expect(quote).not.toThrow();
993
+ expect(best()).toEqual(route);
994
+ }
995
+ m.longToken.prices = { minPrice: P, maxPrice: 2n * P };
996
+ Object.assign(m, {
997
+ swapImpactExponentFactor: 2n * P,
998
+ longPoolAmount: 1000n * 10n ** BigInt(m.longToken.decimals),
999
+ shortPoolAmount: 1500n * 10n ** BigInt(m.shortToken.decimals),
1000
+ swapImpactFactorPositive: P / 1000000n,
1001
+ swapImpactFactorNegative: P / 1000000n,
1002
+ longInterestUsd: 0n,
1003
+ shortInterestUsd: 0n,
1004
+ longInterestInTokens: 0n,
1005
+ shortInterestInTokens: 0n,
1006
+ });
1007
+ expect(quote()?.totalSwapPriceImpactDeltaUsd).toBe((-(tradeMath ? 9n : 4n) * P) / 100n);
1008
+ }
1009
+ });
1010
+ });