@gmx-io/sdk 2.9.3 → 3.0.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 (163) hide show
  1. package/build/cjs/src/abis/RatioVesterReader.js +45 -0
  2. package/build/cjs/src/abis/index.js +2 -0
  3. package/build/cjs/src/clients/v1/modules/oracle.js +15 -0
  4. package/build/cjs/src/clients/v1/modules/oracle.spec.js +20 -0
  5. package/build/cjs/src/clients/v1/modules/orders/helpers.js +16 -12
  6. package/build/cjs/src/clients/v1/modules/orders/helpers.spec.js +21 -0
  7. package/build/cjs/src/clients/v1/modules/orders/orders.js +4 -0
  8. package/build/cjs/src/clients/v1/modules/orders/utils.js +1 -0
  9. package/build/cjs/src/clients/v2/__tests__/subaccount.spec.js +74 -17
  10. package/build/cjs/src/clients/v2/__tests__/subaccountLifecycle.spec.js +1 -1
  11. package/build/cjs/src/clients/v2/__tests__/testUtil.js +14 -2
  12. package/build/cjs/src/clients/v2/index.js +28 -7
  13. package/build/cjs/src/clients/v2/solana.spec.js +81 -4
  14. package/build/cjs/src/codegen/prebuilt/hashedKinkModelMarketRatesKeys.json +48 -0
  15. package/build/cjs/src/codegen/prebuilt/hashedMarketConfigKeys.json +782 -0
  16. package/build/cjs/src/codegen/prebuilt/hashedMarketValuesKeys.json +90 -0
  17. package/build/cjs/src/configs/contracts.js +10 -0
  18. package/build/cjs/src/configs/dataStore.js +22 -4
  19. package/build/cjs/src/configs/express.js +1 -2
  20. package/build/cjs/src/configs/markets.js +42 -0
  21. package/build/cjs/src/configs/tokens.js +2 -0
  22. package/build/cjs/src/test/mockCrossFetch.js +1 -0
  23. package/build/cjs/src/utils/__tests__/fees.spec.js +52 -0
  24. package/build/cjs/src/utils/__tests__/gmsolUnits.spec.js +101 -0
  25. package/build/cjs/src/utils/__tests__/orderTransactions/batchUtils.spec.js +66 -0
  26. package/build/cjs/src/utils/__tests__/orderTransactions/decreaseOrders.spec.js +6 -6
  27. package/build/cjs/src/utils/__tests__/orderTransactions/exchangeRouterMulticall.spec.js +40 -0
  28. package/build/cjs/src/utils/__tests__/orderTransactions/updateOrder.spec.js +4 -2
  29. package/build/cjs/src/utils/__tests__/tokens.spec.js +63 -0
  30. package/build/cjs/src/utils/errors/transactionsErrors.js +6 -0
  31. package/build/cjs/src/utils/fees/index.js +5 -0
  32. package/build/cjs/src/utils/fees/priceImpact.js +39 -6
  33. package/build/cjs/src/utils/gmsol/index.js +15 -0
  34. package/build/cjs/src/utils/gmsol/units.js +106 -0
  35. package/build/cjs/src/utils/http/http.js +21 -25
  36. package/build/cjs/src/utils/http/httpFallback.js +3 -3
  37. package/build/cjs/src/utils/http/validation.js +9 -1
  38. package/build/cjs/src/utils/markets/hashKeys.js +8 -0
  39. package/build/cjs/src/utils/markets/multicall.js +10 -0
  40. package/build/cjs/src/utils/markets/utils.js +2 -0
  41. package/build/cjs/src/utils/multichain/__tests__/api.spec.js +49 -0
  42. package/build/cjs/src/utils/multichain/api.js +29 -2
  43. package/build/cjs/src/utils/orderTransactions/utils.js +63 -5
  44. package/build/cjs/src/utils/orders/api.js +66 -3
  45. package/build/cjs/src/utils/positions/__tests__/liquidationImpact.spec.js +44 -0
  46. package/build/cjs/src/utils/positions/__tests__/liquidationPrice.spec.js +159 -2
  47. package/build/cjs/src/utils/positions/__tests__/trackingCollateral.spec.js +395 -0
  48. package/build/cjs/src/utils/positions/api.js +4 -0
  49. package/build/cjs/src/utils/positions/utils.js +119 -44
  50. package/build/cjs/src/utils/prices/api.js +2 -2
  51. package/build/cjs/src/utils/referrals/api.js +5 -4
  52. package/build/cjs/src/utils/subaccount/generateSubaccount.js +14 -14
  53. package/build/cjs/src/utils/subaccount/sdkClient.js +40 -19
  54. package/build/cjs/src/utils/tokens/utils.js +23 -7
  55. package/build/cjs/src/utils/trade/__tests__/decrease.spec.js +152 -0
  56. package/build/cjs/src/utils/trade/__tests__/gmsolTradeMath.spec.js +43 -0
  57. package/build/cjs/src/utils/trade/decrease.js +113 -33
  58. package/build/cjs/src/utils/trade/decreaseMarginCheck.js +38 -2
  59. package/build/cjs/src/utils/trade/decreaseOutputs.js +20 -5
  60. package/build/cjs/src/utils/trade/increase.js +30 -11
  61. package/build/cjs/src/utils/trade/increaseMarginCheck.js +14 -35
  62. package/build/esm/src/abis/RatioVesterReader.js +43 -0
  63. package/build/esm/src/abis/index.js +2 -0
  64. package/build/esm/src/clients/v1/modules/oracle.js +15 -0
  65. package/build/esm/src/clients/v1/modules/oracle.spec.js +18 -0
  66. package/build/esm/src/clients/v1/modules/orders/helpers.js +17 -13
  67. package/build/esm/src/clients/v1/modules/orders/helpers.spec.js +21 -0
  68. package/build/esm/src/clients/v1/modules/orders/orders.js +4 -0
  69. package/build/esm/src/clients/v1/modules/orders/utils.js +1 -0
  70. package/build/esm/src/clients/v2/__tests__/subaccount.spec.js +74 -17
  71. package/build/esm/src/clients/v2/__tests__/subaccountLifecycle.spec.js +2 -2
  72. package/build/esm/src/clients/v2/__tests__/testUtil.js +13 -2
  73. package/build/esm/src/clients/v2/index.js +29 -8
  74. package/build/esm/src/clients/v2/solana.spec.js +79 -2
  75. package/build/esm/src/codegen/prebuilt/hashedKinkModelMarketRatesKeys.json +48 -0
  76. package/build/esm/src/codegen/prebuilt/hashedMarketConfigKeys.json +782 -0
  77. package/build/esm/src/codegen/prebuilt/hashedMarketValuesKeys.json +90 -0
  78. package/build/esm/src/configs/contracts.js +10 -0
  79. package/build/esm/src/configs/dataStore.js +14 -0
  80. package/build/esm/src/configs/express.js +0 -1
  81. package/build/esm/src/configs/markets.js +42 -0
  82. package/build/esm/src/configs/tokens.js +2 -0
  83. package/build/esm/src/test/mockCrossFetch.js +1 -0
  84. package/build/esm/src/utils/__tests__/fees.spec.js +53 -1
  85. package/build/esm/src/utils/__tests__/gmsolUnits.spec.js +99 -0
  86. package/build/esm/src/utils/__tests__/orderTransactions/batchUtils.spec.js +68 -2
  87. package/build/esm/src/utils/__tests__/orderTransactions/decreaseOrders.spec.js +6 -6
  88. package/build/esm/src/utils/__tests__/orderTransactions/exchangeRouterMulticall.spec.js +40 -0
  89. package/build/esm/src/utils/__tests__/orderTransactions/updateOrder.spec.js +5 -3
  90. package/build/esm/src/utils/__tests__/tokens.spec.js +64 -1
  91. package/build/esm/src/utils/errors/transactionsErrors.js +6 -0
  92. package/build/esm/src/utils/fees/index.js +5 -0
  93. package/build/esm/src/utils/fees/priceImpact.js +36 -5
  94. package/build/esm/src/utils/gmsol/index.js +1 -0
  95. package/build/esm/src/utils/gmsol/units.js +97 -0
  96. package/build/esm/src/utils/http/http.js +21 -25
  97. package/build/esm/src/utils/http/httpFallback.js +3 -3
  98. package/build/esm/src/utils/http/validation.js +7 -0
  99. package/build/esm/src/utils/markets/hashKeys.js +9 -1
  100. package/build/esm/src/utils/markets/multicall.js +10 -0
  101. package/build/esm/src/utils/markets/utils.js +2 -0
  102. package/build/esm/src/utils/multichain/__tests__/api.spec.js +46 -0
  103. package/build/esm/src/utils/multichain/api.js +29 -2
  104. package/build/esm/src/utils/orderTransactions/utils.js +59 -5
  105. package/build/esm/src/utils/orders/api.js +64 -2
  106. package/build/esm/src/utils/positions/__tests__/liquidationImpact.spec.js +42 -0
  107. package/build/esm/src/utils/positions/__tests__/liquidationPrice.spec.js +161 -4
  108. package/build/esm/src/utils/positions/__tests__/trackingCollateral.spec.js +393 -0
  109. package/build/esm/src/utils/positions/api.js +4 -0
  110. package/build/esm/src/utils/positions/utils.js +115 -44
  111. package/build/esm/src/utils/prices/api.js +2 -2
  112. package/build/esm/src/utils/referrals/api.js +6 -5
  113. package/build/esm/src/utils/subaccount/generateSubaccount.js +13 -14
  114. package/build/esm/src/utils/subaccount/sdkClient.js +38 -19
  115. package/build/esm/src/utils/tokens/utils.js +20 -6
  116. package/build/esm/src/utils/trade/__tests__/decrease.spec.js +150 -0
  117. package/build/esm/src/utils/trade/__tests__/gmsolTradeMath.spec.js +43 -0
  118. package/build/esm/src/utils/trade/decrease.js +115 -35
  119. package/build/esm/src/utils/trade/decreaseMarginCheck.js +37 -2
  120. package/build/esm/src/utils/trade/decreaseOutputs.js +19 -5
  121. package/build/esm/src/utils/trade/increase.js +32 -13
  122. package/build/esm/src/utils/trade/increaseMarginCheck.js +18 -39
  123. package/build/tsconfig.tsbuildinfo +1 -1
  124. package/build/types/src/abis/RatioVesterReader.d.ts +74 -0
  125. package/build/types/src/abis/index.d.ts +73 -0
  126. package/build/types/src/clients/v1/modules/oracle.d.ts +6 -1
  127. package/build/types/src/clients/v1/modules/oracle.spec.d.ts +1 -0
  128. package/build/types/src/clients/v2/__tests__/testUtil.d.ts +1 -0
  129. package/build/types/src/clients/v2/index.d.ts +26 -5
  130. package/build/types/src/codegen/prebuilt/index.d.ts +1045 -125
  131. package/build/types/src/configs/contracts.d.ts +10 -0
  132. package/build/types/src/configs/dataStore.d.ts +8 -0
  133. package/build/types/src/configs/express.d.ts +0 -1
  134. package/build/types/src/utils/__tests__/gmsolUnits.spec.d.ts +1 -0
  135. package/build/types/src/utils/errors/parseError.d.ts +1 -1
  136. package/build/types/src/utils/errors/transactionsErrors.d.ts +6 -0
  137. package/build/types/src/utils/fees/priceImpact.d.ts +10 -0
  138. package/build/types/src/utils/gmsol/index.d.ts +1 -0
  139. package/build/types/src/utils/gmsol/units.d.ts +53 -0
  140. package/build/types/src/utils/http/types.d.ts +1 -0
  141. package/build/types/src/utils/http/validation.d.ts +1 -0
  142. package/build/types/src/utils/markets/types.d.ts +5 -2
  143. package/build/types/src/utils/multichain/api.d.ts +4 -1
  144. package/build/types/src/utils/orderTransactions/utils.d.ts +19 -4
  145. package/build/types/src/utils/orders/api.d.ts +2 -1
  146. package/build/types/src/utils/orders/types.d.ts +24 -0
  147. package/build/types/src/utils/positions/__tests__/liquidationImpact.spec.d.ts +1 -0
  148. package/build/types/src/utils/positions/__tests__/trackingCollateral.spec.d.ts +1 -0
  149. package/build/types/src/utils/positions/types.d.ts +2 -0
  150. package/build/types/src/utils/positions/utils.d.ts +30 -0
  151. package/build/types/src/utils/prices/api.d.ts +2 -0
  152. package/build/types/src/utils/referrals/types.d.ts +4 -0
  153. package/build/types/src/utils/subaccount/generateSubaccount.d.ts +9 -4
  154. package/build/types/src/utils/subaccount/sdkClient.d.ts +7 -1
  155. package/build/types/src/utils/subaccount/types.d.ts +2 -0
  156. package/build/types/src/utils/tokens/types.d.ts +1 -0
  157. package/build/types/src/utils/tokens/utils.d.ts +6 -0
  158. package/build/types/src/utils/trade/__tests__/decrease.spec.d.ts +1 -0
  159. package/build/types/src/utils/trade/decrease.d.ts +3 -0
  160. package/build/types/src/utils/trade/decreaseMarginCheck.d.ts +11 -0
  161. package/build/types/src/utils/trade/decreaseOutputs.d.ts +7 -2
  162. package/build/types/src/utils/trade/increaseMarginCheck.d.ts +1 -0
  163. package/package.json +10 -1
@@ -0,0 +1,395 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const vitest_1 = require("vitest");
4
+ const chains_1 = require("../../../configs/chains");
5
+ const factors_1 = require("../../../configs/factors");
6
+ const tokens_1 = require("../../../configs/tokens");
7
+ const bigmath_1 = require("../../bigmath");
8
+ const mockMarkets_1 = require("../../markets/__tests__/mockMarkets");
9
+ const numbers_1 = require("../../numbers");
10
+ const types_1 = require("../../orders/types");
11
+ const positions_1 = require("..");
12
+ const swap_1 = require("../../swap");
13
+ const tokens_2 = require("../../tokens");
14
+ const decrease_1 = require("../../trade/decrease");
15
+ const increase_1 = require("../../trade/increase");
16
+ const increaseMarginCheck_1 = require("../../trade/increaseMarginCheck");
17
+ const usd = (value) => (0, numbers_1.expandDecimals)(Math.round(value * 1e6), factors_1.USD_DECIMALS - 6);
18
+ const amount = (value, decimals) => (BigInt(Math.round(value * 1e8)) * (0, numbers_1.expandDecimals)(1, decimals)) / 100000000n;
19
+ const isWithinBps = (value, expected, bps) => bigmath_1.bigMath.abs(value - expected) * 10000n <= bigmath_1.bigMath.abs(expected) * bps;
20
+ const withPrices = (token, minPrice, maxPrice) => ({
21
+ ...token,
22
+ prices: { minPrice: usd(minPrice), maxPrice: usd(maxPrice) },
23
+ });
24
+ const atPrice = (token, price) => ({
25
+ ...token,
26
+ prices: { minPrice: price, maxPrice: price },
27
+ });
28
+ const BTC = withPrices((0, tokens_1.getTokenBySymbol)(chains_1.ARBITRUM, "BTC", { isSynthetic: true }), 99990, 100010);
29
+ const TBTC = withPrices((0, tokens_1.getTokenBySymbol)(chains_1.ARBITRUM, "TBTC"), 99900, 99950);
30
+ const ETH = withPrices((0, tokens_1.getNativeToken)(chains_1.ARBITRUM), 2400, 2400.5);
31
+ const WETH = withPrices((0, tokens_1.getWrappedToken)(chains_1.ARBITRUM), 2400, 2400.5);
32
+ const WSTETH = withPrices((0, tokens_1.getTokenBySymbol)(chains_1.ARBITRUM, "WSTETH"), 2900, 2901);
33
+ const USDC = withPrices((0, tokens_1.getTokenBySymbol)(chains_1.ARBITRUM, "USDC"), 1, 1);
34
+ const USDE = withPrices((0, tokens_1.getTokenBySymbol)(chains_1.ARBITRUM, "USDE"), 1, 1);
35
+ const MIN_COLLATERAL_FACTOR_FOR_LIQUIDATION = (0, numbers_1.expandDecimals)(5, 27);
36
+ const POSITION_FEE_FACTOR = (0, numbers_1.expandDecimals)(7, 26);
37
+ const MIN_COLLATERAL_USD = usd(1);
38
+ function getMarketInfo(indexToken, longToken, shortToken) {
39
+ const tokensData = Object.fromEntries([indexToken, longToken, shortToken].map((token) => [token.address, token]));
40
+ const key = `${indexToken.address}-${longToken.address}-${shortToken.address}`;
41
+ return (0, mockMarkets_1.mockMarketsInfoData)(tokensData, [key], {
42
+ [key]: {
43
+ minCollateralFactorForLiquidation: MIN_COLLATERAL_FACTOR_FOR_LIQUIDATION,
44
+ positionFeeFactorForBalanceWasImproved: POSITION_FEE_FACTOR,
45
+ positionFeeFactorForBalanceWasNotImproved: POSITION_FEE_FACTOR,
46
+ maxPositionImpactFactorForLiquidations: (0, numbers_1.expandDecimals)(1, 28),
47
+ },
48
+ })[key];
49
+ }
50
+ (0, vitest_1.describe)("tBTC and wstETH collateral", () => {
51
+ (0, vitest_1.it)("returns the index price where the contract's remaining collateral reaches the liquidation threshold TRD-41", () => {
52
+ const cases = [
53
+ {
54
+ name: "tBTC long",
55
+ market: [BTC, TBTC, TBTC],
56
+ collateral: TBTC,
57
+ moves: "ratio",
58
+ isLong: true,
59
+ sizeUsd: 50000,
60
+ collateralAmount: 0.25,
61
+ fundingUsd: 2500,
62
+ borrowingUsd: 300,
63
+ },
64
+ {
65
+ name: "tBTC short",
66
+ market: [BTC, TBTC, TBTC],
67
+ collateral: TBTC,
68
+ moves: "ratio",
69
+ isLong: false,
70
+ sizeUsd: 30000,
71
+ collateralAmount: 0.1,
72
+ fundingUsd: 1000,
73
+ borrowingUsd: 100,
74
+ },
75
+ {
76
+ name: "wstETH long",
77
+ market: [ETH, WSTETH, USDE],
78
+ collateral: WSTETH,
79
+ moves: "ratio",
80
+ isLong: true,
81
+ sizeUsd: 5000,
82
+ collateralAmount: 500 / 2900,
83
+ fundingUsd: 50,
84
+ borrowingUsd: 5,
85
+ },
86
+ {
87
+ name: "wstETH short",
88
+ market: [ETH, WSTETH, USDE],
89
+ collateral: WSTETH,
90
+ moves: "ratio",
91
+ isLong: false,
92
+ sizeUsd: 10000,
93
+ collateralAmount: 2000 / 2900,
94
+ fundingUsd: 200,
95
+ borrowingUsd: 20,
96
+ },
97
+ {
98
+ name: "WETH long",
99
+ market: [ETH, WETH, USDC],
100
+ collateral: WETH,
101
+ moves: "index",
102
+ isLong: true,
103
+ sizeUsd: 12000,
104
+ collateralAmount: 1,
105
+ fundingUsd: 0,
106
+ borrowingUsd: 30,
107
+ },
108
+ {
109
+ name: "USDC long",
110
+ market: [ETH, WETH, USDC],
111
+ collateral: USDC,
112
+ moves: "none",
113
+ isLong: true,
114
+ sizeUsd: 10000,
115
+ collateralAmount: 2000,
116
+ fundingUsd: 100,
117
+ borrowingUsd: 20,
118
+ },
119
+ ];
120
+ for (const c of cases) {
121
+ const [indexToken, longToken, shortToken] = c.market;
122
+ const marketInfo = getMarketInfo(indexToken, longToken, shortToken);
123
+ const indexPrecision = (0, numbers_1.expandDecimals)(1, indexToken.decimals);
124
+ const collateralPrecision = (0, numbers_1.expandDecimals)(1, c.collateral.decimals);
125
+ const currentIndexPrice = c.isLong ? indexToken.prices.minPrice : indexToken.prices.maxPrice;
126
+ const sizeInUsd = usd(c.sizeUsd);
127
+ const sizeInTokens = (sizeInUsd * indexPrecision) / currentIndexPrice;
128
+ const collateralAmount = amount(c.collateralAmount, c.collateral.decimals);
129
+ const collateralUsd = (collateralAmount * c.collateral.prices.minPrice) / collateralPrecision;
130
+ const pendingFundingFeesUsd = usd(c.fundingUsd);
131
+ const pendingBorrowingFeesUsd = usd(c.borrowingUsd);
132
+ const liquidationPrice = (0, positions_1.getLiquidationPrice)({
133
+ sizeInUsd,
134
+ sizeInTokens,
135
+ collateralAmount,
136
+ collateralUsd,
137
+ collateralToken: c.collateral,
138
+ marketInfo,
139
+ pendingFundingFeesUsd,
140
+ pendingBorrowingFeesUsd,
141
+ pendingImpactAmount: 0n,
142
+ minCollateralUsd: MIN_COLLATERAL_USD,
143
+ isLong: c.isLong,
144
+ useMaxPriceImpact: true,
145
+ userReferralInfo: undefined,
146
+ });
147
+ (0, vitest_1.expect)(liquidationPrice, c.name).toBeDefined();
148
+ const priceImpactUsd = (0, positions_1.getLiquidationPriceImpactDeltaUsd)({
149
+ marketInfo,
150
+ sizeInUsd,
151
+ sizeInTokens,
152
+ pendingImpactAmount: 0n,
153
+ isLong: c.isLong,
154
+ useMaxPriceImpact: true,
155
+ });
156
+ // funding fees are held in collateral tokens, borrowing and closing fees are USD amounts
157
+ const getRemainingCollateralUsd = (indexPrice) => {
158
+ const collateralPrice = {
159
+ none: c.collateral.prices.minPrice,
160
+ index: indexPrice,
161
+ ratio: (c.collateral.prices.minPrice * indexPrice) / currentIndexPrice,
162
+ }[c.moves];
163
+ const fundingUsd = (pendingFundingFeesUsd * collateralPrice) / c.collateral.prices.minPrice;
164
+ const positionValueUsd = (sizeInTokens * indexPrice) / indexPrecision;
165
+ const pnlUsd = c.isLong ? positionValueUsd - sizeInUsd : sizeInUsd - positionValueUsd;
166
+ return ((collateralAmount * collateralPrice) / collateralPrecision -
167
+ fundingUsd -
168
+ pendingBorrowingFeesUsd -
169
+ (0, numbers_1.applyFactor)(sizeInUsd, POSITION_FEE_FACTOR) +
170
+ priceImpactUsd +
171
+ pnlUsd);
172
+ };
173
+ const threshold = (0, numbers_1.applyFactor)(sizeInUsd, MIN_COLLATERAL_FACTOR_FOR_LIQUIDATION);
174
+ const safeSide = c.isLong ? 10001n : 9999n;
175
+ const liquidatableSide = c.isLong ? 9999n : 10001n;
176
+ (0, vitest_1.expect)(getRemainingCollateralUsd((liquidationPrice * safeSide) / 10000n) > threshold, c.name).toBe(true);
177
+ (0, vitest_1.expect)(getRemainingCollateralUsd((liquidationPrice * liquidatableSide) / 10000n) < threshold, c.name).toBe(true);
178
+ }
179
+ });
180
+ (0, vitest_1.it)("values tBTC and wstETH collateral at the trigger price for TP/SL TRD-41", () => {
181
+ const cases = [
182
+ { name: "tBTC long", market: [BTC, TBTC, TBTC], collateral: TBTC, moves: "ratio", isLong: true },
183
+ { name: "tBTC short", market: [BTC, TBTC, TBTC], collateral: TBTC, moves: "ratio", isLong: false },
184
+ { name: "wstETH long", market: [ETH, WSTETH, USDE], collateral: WSTETH, moves: "ratio", isLong: true },
185
+ { name: "WETH long", market: [ETH, WETH, USDC], collateral: WETH, moves: "index", isLong: true },
186
+ { name: "USDC short", market: [ETH, WETH, USDC], collateral: USDC, moves: "none", isLong: false },
187
+ ];
188
+ for (const c of cases) {
189
+ const [indexToken] = c.market;
190
+ const marketInfo = getMarketInfo(...c.market);
191
+ const currentIndexPrice = c.isLong ? indexToken.prices.minPrice : indexToken.prices.maxPrice;
192
+ const triggerPrice = (currentIndexPrice * 8n) / 10n;
193
+ const collateralAmount = (0, tokens_2.convertToTokenAmount)(usd(3000), c.collateral.decimals, c.collateral.prices.minPrice);
194
+ const sizeInUsd = usd(9000);
195
+ const expectedCollateralPrice = {
196
+ none: c.collateral.prices.minPrice,
197
+ index: triggerPrice,
198
+ ratio: (c.collateral.prices.minPrice * triggerPrice) / currentIndexPrice,
199
+ }[c.moves];
200
+ const position = (0, positions_1.getPositionInfo)({
201
+ position: {
202
+ key: c.name,
203
+ contractKey: c.name,
204
+ account: "",
205
+ marketAddress: marketInfo.marketTokenAddress,
206
+ collateralTokenAddress: c.collateral.address,
207
+ sizeInUsd,
208
+ sizeInTokens: (0, tokens_2.convertToTokenAmount)(sizeInUsd, indexToken.decimals, currentIndexPrice),
209
+ collateralAmount,
210
+ pendingBorrowingFeesUsd: 0n,
211
+ increasedAtTime: 0n,
212
+ decreasedAtTime: 0n,
213
+ isLong: c.isLong,
214
+ fundingFeeAmount: 0n,
215
+ claimableLongTokenAmount: 0n,
216
+ claimableShortTokenAmount: 0n,
217
+ pnl: 0n,
218
+ positionFeeAmount: 0n,
219
+ traderDiscountAmount: 0n,
220
+ uiFeeAmount: 0n,
221
+ pendingImpactAmount: 0n,
222
+ positionValueInUsd: 0n,
223
+ data: "",
224
+ },
225
+ marketInfo,
226
+ minCollateralUsd: MIN_COLLATERAL_USD,
227
+ });
228
+ const decreaseAmounts = (0, decrease_1.getDecreasePositionAmounts)({
229
+ marketInfo,
230
+ collateralToken: c.collateral,
231
+ isLong: c.isLong,
232
+ position,
233
+ closeSizeUsd: sizeInUsd / 2n,
234
+ keepLeverage: true,
235
+ triggerPrice,
236
+ triggerOrderType: c.isLong ? types_1.OrderType.StopLossDecrease : types_1.OrderType.LimitDecrease,
237
+ userReferralInfo: undefined,
238
+ minCollateralUsd: MIN_COLLATERAL_USD,
239
+ minPositionSizeUsd: 0n,
240
+ uiFeeFactor: 0n,
241
+ isSetAcceptablePriceImpactEnabled: false,
242
+ });
243
+ (0, vitest_1.expect)(decreaseAmounts.collateralPrice, c.name).toBe(expectedCollateralPrice);
244
+ // Loss % and Gain % value the collateral as index tokens at the trigger price
245
+ const collateralInIndexTokens = (0, positions_1.getCollateralAmountInIndexTokens)({
246
+ collateralToken: c.collateral,
247
+ indexToken,
248
+ collateralAmount,
249
+ isLong: c.isLong,
250
+ });
251
+ if (c.moves === "none") {
252
+ (0, vitest_1.expect)(collateralInIndexTokens, c.name).toBeUndefined();
253
+ continue;
254
+ }
255
+ const valueInIndexTokens = (0, tokens_2.convertToUsd)(collateralInIndexTokens, indexToken.decimals, triggerPrice);
256
+ const collateralValueAtTrigger = (0, tokens_2.convertToUsd)(collateralAmount, c.collateral.decimals, expectedCollateralPrice);
257
+ (0, vitest_1.expect)(isWithinBps(valueInIndexTokens, collateralValueAtTrigger, 1n), c.name).toBe(true);
258
+ }
259
+ (0, vitest_1.expect)((0, positions_1.getCollateralPriceAtIndexPrice)({
260
+ collateralToken: TBTC,
261
+ indexToken: withPrices(BTC, 0, 0),
262
+ indexPrice: usd(80000),
263
+ isLong: true,
264
+ })).toBe(TBTC.prices.minPrice);
265
+ (0, vitest_1.expect)((0, positions_1.getCollateralPriceAtIndexPrice)({ collateralToken: TBTC, indexToken: ETH, indexPrice: usd(2000), isLong: true })).toBe(TBTC.prices.minPrice);
266
+ });
267
+ (0, vitest_1.it)("values tBTC and wstETH collateral at the trigger price in limit increase orders TRD-41", () => {
268
+ const leverage = 5n * factors_1.BASIS_POINTS_DIVISOR_BIGINT;
269
+ const depositUsd = usd(100);
270
+ const cases = [
271
+ {
272
+ name: "wstETH short paid in USDe",
273
+ market: [ETH, WSTETH, USDE],
274
+ payToken: USDE,
275
+ collateral: WSTETH,
276
+ isLong: false,
277
+ triggerBps: 11000n,
278
+ },
279
+ {
280
+ name: "wstETH long paid in USDe",
281
+ market: [ETH, WSTETH, USDE],
282
+ payToken: USDE,
283
+ collateral: WSTETH,
284
+ isLong: true,
285
+ triggerBps: 9000n,
286
+ },
287
+ {
288
+ name: "wstETH short paid in wstETH",
289
+ market: [ETH, WSTETH, USDE],
290
+ payToken: WSTETH,
291
+ collateral: WSTETH,
292
+ isLong: false,
293
+ triggerBps: 11000n,
294
+ },
295
+ {
296
+ name: "tBTC long paid in tBTC",
297
+ market: [BTC, TBTC, TBTC],
298
+ payToken: TBTC,
299
+ collateral: TBTC,
300
+ isLong: true,
301
+ triggerBps: 9000n,
302
+ },
303
+ ];
304
+ for (const c of cases) {
305
+ const [indexToken] = c.market;
306
+ const marketInfo = getMarketInfo(...c.market);
307
+ const marketsInfoData = { [marketInfo.marketTokenAddress]: marketInfo };
308
+ const currentIndexPrice = c.isLong ? indexToken.prices.minPrice : indexToken.prices.maxPrice;
309
+ const triggerPrice = (currentIndexPrice * c.triggerBps) / 10000n;
310
+ const collateralPriceAtTrigger = (c.collateral.prices.minPrice * triggerPrice) / currentIndexPrice;
311
+ const collateralMaxPriceAtTrigger = (c.collateral.prices.maxPrice * triggerPrice) / currentIndexPrice;
312
+ const payAmount = (0, tokens_2.convertToTokenAmount)(depositUsd, c.payToken.decimals, c.payToken.prices.minPrice);
313
+ const isSwap = c.payToken.address !== c.collateral.address;
314
+ const getSwapStats = (markets, usdIn) => (0, swap_1.getSwapPathStats)({
315
+ marketsInfoData: markets,
316
+ swapPath: [marketInfo.marketTokenAddress],
317
+ initialCollateralAddress: c.payToken.address,
318
+ wrappedNativeTokenAddress: WETH.address,
319
+ usdIn,
320
+ shouldUnwrapNativeToken: false,
321
+ shouldApplyPriceImpact: true,
322
+ swapPricingType: types_1.SwapPricingType.Swap,
323
+ });
324
+ const increaseAmounts = (0, increase_1.getIncreasePositionAmounts)({
325
+ marketInfo,
326
+ indexToken,
327
+ initialCollateralToken: c.payToken,
328
+ collateralToken: c.collateral,
329
+ isLong: c.isLong,
330
+ initialCollateralAmount: payAmount,
331
+ indexTokenAmount: undefined,
332
+ position: undefined,
333
+ externalSwapQuote: undefined,
334
+ userReferralInfo: undefined,
335
+ strategy: "leverageByCollateral",
336
+ leverage,
337
+ triggerPrice,
338
+ limitOrderType: types_1.OrderType.LimitIncrease,
339
+ findSwapPath: ((usdIn) => (isSwap ? getSwapStats(marketsInfoData, usdIn) : undefined)),
340
+ uiFeeFactor: 0n,
341
+ marketsInfoData,
342
+ chainId: chains_1.ARBITRUM,
343
+ externalSwapQuoteParams: undefined,
344
+ isSetAcceptablePriceImpactEnabled: false,
345
+ });
346
+ // the keeper executes at the trigger: the collateral and its oracle spread are repriced with the index,
347
+ // and the swap pays out at the collateral's max price
348
+ const atTrigger = (token) => token.address === c.collateral.address
349
+ ? { ...token, prices: { minPrice: collateralPriceAtTrigger, maxPrice: collateralMaxPriceAtTrigger } }
350
+ : token;
351
+ const marketAtTrigger = {
352
+ ...marketInfo,
353
+ indexToken: atPrice(indexToken, triggerPrice),
354
+ longToken: atTrigger(marketInfo.longToken),
355
+ shortToken: atTrigger(marketInfo.shortToken),
356
+ };
357
+ const collateralAmountAtExecution = isSwap
358
+ ? getSwapStats({ [marketInfo.marketTokenAddress]: marketAtTrigger }, depositUsd).amountOut
359
+ : payAmount;
360
+ const collateralUsdAtExecution = (0, tokens_2.convertToUsd)(collateralAmountAtExecution, c.collateral.decimals, collateralPriceAtTrigger) -
361
+ increaseAmounts.positionFeeUsd;
362
+ (0, vitest_1.expect)(isWithinBps(increaseAmounts.collateralDeltaAmount, (0, tokens_2.convertToTokenAmount)(collateralUsdAtExecution, c.collateral.decimals, collateralPriceAtTrigger), 1n), c.name).toBe(true);
363
+ (0, vitest_1.expect)(isWithinBps(increaseAmounts.sizeDeltaUsd, bigmath_1.bigMath.mulDiv(collateralUsdAtExecution, leverage, factors_1.BASIS_POINTS_DIVISOR_BIGINT), 1n), c.name).toBe(true);
364
+ const { collateralToken: collateralAtEvaluation } = (0, increaseMarginCheck_1.getMarketInfoAtIndexPrice)({
365
+ marketInfo,
366
+ collateralToken: c.collateral,
367
+ indexPrice: triggerPrice,
368
+ isLong: c.isLong,
369
+ });
370
+ (0, vitest_1.expect)(collateralAtEvaluation.prices, c.name).toEqual({
371
+ minPrice: collateralPriceAtTrigger,
372
+ maxPrice: collateralMaxPriceAtTrigger,
373
+ });
374
+ }
375
+ // a stablecoin collateral keeps its prices at the trigger, and so does the wstETH the position does not hold
376
+ const usdeWithSpread = withPrices(USDE, 0.999, 1.001);
377
+ const atTrigger = (0, increaseMarginCheck_1.getMarketInfoAtIndexPrice)({
378
+ marketInfo: getMarketInfo(ETH, WSTETH, usdeWithSpread),
379
+ collateralToken: usdeWithSpread,
380
+ indexPrice: usd(2640),
381
+ isLong: false,
382
+ });
383
+ (0, vitest_1.expect)(atTrigger.collateralToken.prices).toEqual(usdeWithSpread.prices);
384
+ (0, vitest_1.expect)(atTrigger.marketInfo.longToken.prices).toEqual(WSTETH.prices);
385
+ (0, vitest_1.expect)(atTrigger.marketInfo.indexToken.prices).toEqual({ minPrice: usd(2640), maxPrice: usd(2640) });
386
+ // the index price is not loaded yet: wstETH keeps its prices
387
+ const withoutIndexPrice = (0, increaseMarginCheck_1.getMarketInfoAtIndexPrice)({
388
+ marketInfo: { ...getMarketInfo(ETH, WSTETH, USDE), indexToken: withPrices(ETH, 0, 0) },
389
+ collateralToken: WSTETH,
390
+ indexPrice: usd(2640),
391
+ isLong: true,
392
+ });
393
+ (0, vitest_1.expect)(withoutIndexPrice.collateralToken.prices).toEqual(WSTETH.prices);
394
+ });
395
+ });
@@ -4,6 +4,7 @@ exports.fetchApiPositionsInfo = void 0;
4
4
  const solana_1 = require("../http/solana");
5
5
  const validation_1 = require("../http/validation");
6
6
  const numbers_1 = require("../numbers");
7
+ const api_1 = require("../orders/api");
7
8
  async function fetchApiPositionsInfo(ctx, params) {
8
9
  const positions = await ctx.api.fetchJson("/v1/positions", {
9
10
  query: {
@@ -17,6 +18,9 @@ async function fetchApiPositionsInfo(ctx, params) {
17
18
  return positions.map((position, index) => {
18
19
  const parsed = (0, numbers_1.deserializeBigIntsInObject)(position, { handleInts: true });
19
20
  (0, validation_1.assertApiFields)(parsed, [{ name: "positionValueInUsd", type: "bigint" }], "/v1/positions", index);
21
+ if (position.relatedOrders !== undefined) {
22
+ parsed.relatedOrders = (0, api_1.parseApiOrders)(position.relatedOrders, "/v1/positions");
23
+ }
20
24
  return parsed;
21
25
  });
22
26
  }
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getPositionInfo = exports.getContractPositionDynamicFees = exports.getMinCollateralFactorForPosition = exports.getPriceImpactDiffUsd = exports.getNetPriceImpactDeltaUsdForDecrease = exports.getIsPositionBelowMinCollateralForLeverage = exports.getMinCollateralUsdForLiquidationPrice = exports.getLiquidationPrice = exports.getLiquidationPriceImpactDeltaUsd = exports.getLeverage = exports.getPositionPnlAfterAllFees = exports.getPositionPnlAfterFees = exports.getPositionNetValueAfterAllFees = exports.getPositionNetValue = exports.getPositionPendingFeesUsd = exports.getPositionValueUsd = exports.getPositionPnlUsd = exports.getEntryPrice = exports.parsePositionKey = exports.getPositionKey = void 0;
3
+ exports.getPositionInfo = exports.getContractPositionDynamicFees = exports.getMinCollateralFactorForPosition = exports.getPriceImpactDiffUsd = exports.getNetPriceImpactDeltaUsdForDecrease = exports.getIsPositionBelowMinCollateralForLeverage = exports.getMinCollateralUsdForLiquidationPrice = exports.getLiquidationPrice = exports.getCollateralPriceAtIndexPrice = exports.getTokenAtIndexPrice = exports.getCollateralAmountInIndexTokens = exports.getLiquidationPriceImpactDeltaUsd = exports.getLiquidationPriceImpact = exports.getLeverage = exports.getPositionPnlAfterAllFees = exports.getPositionPnlAfterFees = exports.getPositionNetValueAfterAllFees = exports.getPositionNetValue = exports.getPositionPendingFeesUsd = exports.getPositionValueUsd = exports.getPositionPnlUsd = exports.getEntryPrice = exports.parsePositionKey = exports.getPositionKey = void 0;
4
4
  const factors_1 = require("../../configs/factors");
5
5
  const bigmath_1 = require("../bigmath");
6
6
  const fees_1 = require("../fees");
@@ -92,47 +92,93 @@ function getLeverage(p) {
92
92
  return bigmath_1.bigMath.mulDiv(sizeInUsd, factors_1.BASIS_POINTS_DIVISOR_BIGINT, remainingCollateralUsd);
93
93
  }
94
94
  exports.getLeverage = getLeverage;
95
- function getLiquidationPriceImpactDeltaUsd(p) {
96
- const { marketInfo, sizeInUsd, sizeInTokens, pendingImpactAmount, isLong, useMaxPriceImpact } = p;
97
- let maxNegativePriceImpactUsd = -1n * (0, numbers_1.applyFactor)(sizeInUsd, marketInfo.maxPositionImpactFactorForLiquidations);
98
- if (marketInfo.tradeMath === "gmsol") {
99
- maxNegativePriceImpactUsd = (0, gmsol_1.getGmsolUsdAmount)(maxNegativePriceImpactUsd);
95
+ function getNegativeImpactCapUsd(marketInfo, sizeInUsd, factor) {
96
+ const capUsd = -1n * (0, numbers_1.applyFactor)(sizeInUsd, factor);
97
+ return marketInfo.tradeMath === "gmsol" ? (0, gmsol_1.getGmsolUsdAmount)(capUsd) : capUsd;
98
+ }
99
+ function getLiquidationPriceImpact(p) {
100
+ const { marketInfo, sizeInUsd, sizeInTokens, pendingImpactAmount, isLong } = p;
101
+ const liquidationCapUsd = getNegativeImpactCapUsd(marketInfo, sizeInUsd, marketInfo.maxPositionImpactFactorForLiquidations);
102
+ const capExitBeforePending = marketInfo.tradeMath !== "gmsol" && marketInfo.useV221LiquidationImpact;
103
+ if (p.useMaxPriceImpact && !capExitBeforePending) {
104
+ return { priceImpactDeltaUsd: liquidationCapUsd, balanceWasImproved: false };
105
+ }
106
+ const maxNegativeImpactUsd = capExitBeforePending
107
+ ? getNegativeImpactCapUsd(marketInfo, sizeInUsd, marketInfo.maxPositionImpactFactorNegative)
108
+ : liquidationCapUsd;
109
+ const closeImpact = p.useMaxPriceImpact
110
+ ? { priceImpactDeltaUsd: liquidationCapUsd, balanceWasImproved: false }
111
+ : (0, fees_1.getPriceImpactForPosition)(marketInfo, -sizeInUsd, isLong, {
112
+ fallbackToZero: true,
113
+ sizeDeltaInTokens: sizeInTokens,
114
+ });
115
+ let exitImpactUsd = closeImpact.priceImpactDeltaUsd;
116
+ if (exitImpactUsd > 0) {
117
+ exitImpactUsd = (0, fees_1.capPositionImpactUsdByMaxPriceImpactFactor)(marketInfo, sizeInUsd, exitImpactUsd);
100
118
  }
101
- if (useMaxPriceImpact) {
102
- return maxNegativePriceImpactUsd;
103
- }
104
- let priceImpactDeltaUsd = (0, fees_1.getPriceImpactForPosition)(marketInfo, -sizeInUsd, isLong, {
105
- fallbackToZero: true,
106
- sizeDeltaInTokens: sizeInTokens,
107
- }).priceImpactDeltaUsd;
108
- if (priceImpactDeltaUsd > 0) {
109
- priceImpactDeltaUsd = (0, fees_1.capPositionImpactUsdByMaxPriceImpactFactor)(marketInfo, sizeInUsd, priceImpactDeltaUsd);
119
+ else if (capExitBeforePending && exitImpactUsd < liquidationCapUsd) {
120
+ exitImpactUsd = liquidationCapUsd;
110
121
  }
111
122
  const pendingImpactUsd = (0, tokens_1.convertToUsd)(marketInfo.tradeMath === "gmsol" ? 0n : pendingImpactAmount, marketInfo.indexToken.decimals, pendingImpactAmount > 0 ? marketInfo.indexToken.prices.minPrice : marketInfo.indexToken.prices.maxPrice);
112
- priceImpactDeltaUsd = priceImpactDeltaUsd + pendingImpactUsd;
123
+ let priceImpactDeltaUsd = exitImpactUsd + pendingImpactUsd;
113
124
  if (priceImpactDeltaUsd > 0) {
114
- return 0n;
125
+ priceImpactDeltaUsd = 0n;
115
126
  }
116
- if (priceImpactDeltaUsd < maxNegativePriceImpactUsd) {
117
- return maxNegativePriceImpactUsd;
127
+ else if (priceImpactDeltaUsd < maxNegativeImpactUsd) {
128
+ priceImpactDeltaUsd = maxNegativeImpactUsd;
118
129
  }
119
- return priceImpactDeltaUsd;
130
+ return { priceImpactDeltaUsd, balanceWasImproved: closeImpact.balanceWasImproved };
131
+ }
132
+ exports.getLiquidationPriceImpact = getLiquidationPriceImpact;
133
+ function getLiquidationPriceImpactDeltaUsd(p) {
134
+ return getLiquidationPriceImpact(p).priceImpactDeltaUsd;
120
135
  }
121
136
  exports.getLiquidationPriceImpactDeltaUsd = getLiquidationPriceImpactDeltaUsd;
137
+ function getCollateralAmountInIndexTokens(p) {
138
+ const { collateralToken, indexToken, collateralAmount, isLong } = p;
139
+ if ((0, tokens_1.getIsEquivalentTokens)(collateralToken, indexToken)) {
140
+ return bigmath_1.bigMath.mulDiv(collateralAmount, (0, numbers_1.expandDecimals)(1, indexToken.decimals), (0, numbers_1.expandDecimals)(1, collateralToken.decimals));
141
+ }
142
+ if (!(0, tokens_1.getIsTokenTrackingPrice)(collateralToken, indexToken)) {
143
+ return undefined;
144
+ }
145
+ const collateralUsd = (0, tokens_1.convertToUsd)(collateralAmount, collateralToken.decimals, collateralToken.prices.minPrice);
146
+ const indexPrice = (0, prices_1.getMarkPrice)({ prices: indexToken.prices, isIncrease: false, isLong });
147
+ return (0, tokens_1.convertToTokenAmount)(collateralUsd, indexToken.decimals, indexPrice);
148
+ }
149
+ exports.getCollateralAmountInIndexTokens = getCollateralAmountInIndexTokens;
150
+ function getTokenAtIndexPrice(p) {
151
+ const { token, collateralToken, indexToken, indexPrice, isLong } = p;
152
+ if ((0, tokens_1.getIsEquivalentTokens)(token, indexToken)) {
153
+ return { ...token, prices: { minPrice: indexPrice, maxPrice: indexPrice } };
154
+ }
155
+ if (token.address !== collateralToken.address || !(0, tokens_1.getIsTokenTrackingPrice)(token, indexToken)) {
156
+ return token;
157
+ }
158
+ const currentIndexPrice = (0, prices_1.getMarkPrice)({ prices: indexToken.prices, isIncrease: false, isLong });
159
+ if (currentIndexPrice <= 0n) {
160
+ return token;
161
+ }
162
+ return {
163
+ ...token,
164
+ prices: {
165
+ minPrice: bigmath_1.bigMath.mulDiv(token.prices.minPrice, indexPrice, currentIndexPrice),
166
+ maxPrice: bigmath_1.bigMath.mulDiv(token.prices.maxPrice, indexPrice, currentIndexPrice),
167
+ },
168
+ };
169
+ }
170
+ exports.getTokenAtIndexPrice = getTokenAtIndexPrice;
171
+ function getCollateralPriceAtIndexPrice(p) {
172
+ return getTokenAtIndexPrice({ ...p, token: p.collateralToken }).prices.minPrice;
173
+ }
174
+ exports.getCollateralPriceAtIndexPrice = getCollateralPriceAtIndexPrice;
122
175
  function getLiquidationPrice(p) {
123
176
  const { sizeInUsd, sizeInTokens, collateralUsd, collateralAmount, marketInfo, collateralToken, pendingFundingFeesUsd, pendingBorrowingFeesUsd, pendingImpactAmount, minCollateralUsd, isLong, userReferralInfo, useMaxPriceImpact, } = p;
124
177
  if (sizeInUsd <= 0 || sizeInTokens <= 0) {
125
178
  return undefined;
126
179
  }
127
180
  const { indexToken } = marketInfo;
128
- const closingFeeUsd = (0, fees_1.getPositionFee)(marketInfo, sizeInUsd, marketInfo.tradeMath === "gmsol" &&
129
- (0, fees_1.getPriceImpactForPosition)(marketInfo, -sizeInUsd, isLong, {
130
- fallbackToZero: true,
131
- sizeDeltaInTokens: sizeInTokens,
132
- }).balanceWasImproved, userReferralInfo, undefined, undefined, p.feeDiscountFactor).positionFeeUsd;
133
- const totalPendingFeesUsd = getPositionPendingFeesUsd({ pendingFundingFeesUsd, pendingBorrowingFeesUsd });
134
- const totalFeesUsd = totalPendingFeesUsd + closingFeeUsd;
135
- const priceImpactDeltaUsd = getLiquidationPriceImpactDeltaUsd({
181
+ const { priceImpactDeltaUsd, balanceWasImproved } = getLiquidationPriceImpact({
136
182
  marketInfo,
137
183
  sizeInUsd,
138
184
  sizeInTokens,
@@ -140,6 +186,15 @@ function getLiquidationPrice(p) {
140
186
  isLong,
141
187
  useMaxPriceImpact,
142
188
  });
189
+ const useImprovedFee = marketInfo.tradeMath === "gmsol" && useMaxPriceImpact
190
+ ? (0, fees_1.getPriceImpactForPosition)(marketInfo, -sizeInUsd, isLong, {
191
+ fallbackToZero: true,
192
+ sizeDeltaInTokens: sizeInTokens,
193
+ }).balanceWasImproved
194
+ : (marketInfo.tradeMath === "gmsol" || marketInfo.useV221LiquidationImpact === true) && balanceWasImproved;
195
+ const closingFeeUsd = (0, fees_1.getPositionFee)(marketInfo, sizeInUsd, useImprovedFee, userReferralInfo, undefined, undefined, p.feeDiscountFactor).positionFeeUsd;
196
+ const totalPendingFeesUsd = getPositionPendingFeesUsd({ pendingFundingFeesUsd, pendingBorrowingFeesUsd });
197
+ const totalFeesUsd = totalPendingFeesUsd + closingFeeUsd;
143
198
  const effectiveMinCollateralUsd = marketInfo.tradeMath === "gmsol" ? marketInfo.minCollateralUsd ?? minCollateralUsd : minCollateralUsd;
144
199
  let liquidationCollateralUsd = (0, numbers_1.applyFactor)(sizeInUsd, marketInfo.minCollateralFactorForLiquidation);
145
200
  if (marketInfo.tradeMath === "gmsol") {
@@ -168,24 +223,44 @@ function getLiquidationPrice(p) {
168
223
  liquidationPrice = bigmath_1.bigMath.mulDiv(numerator, (0, numbers_1.expandDecimals)(1, indexToken.decimals), denominator);
169
224
  }
170
225
  else if ((0, tokens_1.getIsEquivalentTokens)(collateralToken, indexToken)) {
171
- if (isLong) {
172
- const denominator = sizeInTokens + collateralAmount;
173
- if (denominator == 0n) {
174
- return undefined;
175
- }
176
- liquidationPrice =
177
- ((sizeInUsd + liquidationCollateralUsd - priceImpactDeltaUsd + totalFeesUsd) / denominator) *
178
- (0, numbers_1.expandDecimals)(1, indexToken.decimals);
226
+ const fundingFeeAmount = p.fundingFeeAmount ??
227
+ (pendingFundingFeesUsd === 0n
228
+ ? 0n
229
+ : (0, tokens_1.convertToTokenAmount)(pendingFundingFeesUsd, collateralToken.decimals, collateralToken.prices.minPrice));
230
+ if (fundingFeeAmount === undefined) {
231
+ return undefined;
179
232
  }
180
- else {
181
- const denominator = sizeInTokens - collateralAmount;
182
- if (denominator == 0n) {
183
- return undefined;
184
- }
185
- liquidationPrice =
186
- ((sizeInUsd - liquidationCollateralUsd + priceImpactDeltaUsd - totalFeesUsd) / denominator) *
187
- (0, numbers_1.expandDecimals)(1, indexToken.decimals);
233
+ // the contract charges funding in collateral tokens, so it moves with the index price like the collateral
234
+ const netCollateralAmount = getCollateralAmountInIndexTokens({
235
+ collateralToken,
236
+ indexToken,
237
+ collateralAmount: collateralAmount - fundingFeeAmount,
238
+ isLong,
239
+ });
240
+ const denominator = isLong ? sizeInTokens + netCollateralAmount : sizeInTokens - netCollateralAmount;
241
+ if (denominator === 0n) {
242
+ return undefined;
188
243
  }
244
+ const fixedFeesUsd = pendingBorrowingFeesUsd + closingFeeUsd;
245
+ const numerator = isLong
246
+ ? sizeInUsd + liquidationCollateralUsd - priceImpactDeltaUsd + fixedFeesUsd
247
+ : sizeInUsd - liquidationCollateralUsd + priceImpactDeltaUsd - fixedFeesUsd;
248
+ liquidationPrice = bigmath_1.bigMath.mulDiv(numerator, (0, numbers_1.expandDecimals)(1, indexToken.decimals), denominator);
249
+ }
250
+ else if ((0, tokens_1.getIsTokenTrackingPrice)(collateralToken, indexToken)) {
251
+ const indexPrice = (0, prices_1.getMarkPrice)({ prices: indexToken.prices, isIncrease: false, isLong });
252
+ const positionValueUsd = (0, tokens_1.convertToUsd)(sizeInTokens, indexToken.decimals, indexPrice);
253
+ const collateralValueUsd = (0, tokens_1.convertToUsd)(collateralAmount, collateralToken.decimals, collateralToken.prices.minPrice) -
254
+ pendingFundingFeesUsd;
255
+ const fixedFeesUsd = pendingBorrowingFeesUsd + closingFeeUsd;
256
+ const denominator = isLong ? positionValueUsd + collateralValueUsd : positionValueUsd - collateralValueUsd;
257
+ if (denominator == 0n) {
258
+ return undefined;
259
+ }
260
+ const numerator = isLong
261
+ ? sizeInUsd + liquidationCollateralUsd - priceImpactDeltaUsd + fixedFeesUsd
262
+ : sizeInUsd - liquidationCollateralUsd + priceImpactDeltaUsd - fixedFeesUsd;
263
+ liquidationPrice = bigmath_1.bigMath.mulDiv(indexPrice, numerator, denominator);
189
264
  }
190
265
  else {
191
266
  if (sizeInTokens == 0n) {
@@ -18,8 +18,8 @@ function parseApiTokenPrices(raw) {
18
18
  return (0, numbers_1.deserializeBigIntsInObject)(raw, { handleInts: true });
19
19
  }
20
20
  exports.parseApiTokenPrices = parseApiTokenPrices;
21
- async function fetchApiTokenPrices(ctx) {
22
- const raw = await ctx.api.fetchJson("/v1/prices/tickers");
21
+ async function fetchApiTokenPrices(ctx, opts) {
22
+ const raw = await ctx.api.fetchJson("/v1/prices/tickers", { signal: opts?.signal });
23
23
  if (!(0, objects_1.isRecord)(raw) || !(0, objects_1.isRecord)(raw.prices) || typeof raw.originTs !== "number") {
24
24
  throw new Error("Invalid /v1/prices/tickers response");
25
25
  }
@@ -13,9 +13,6 @@ function parseFeeDiscount(raw) {
13
13
  if (typeof record.attachedOnChain !== "boolean") {
14
14
  throw new Error(`${FEE_DISCOUNT_ENDPOINT}: expected boolean field "attachedOnChain"`);
15
15
  }
16
- if (typeof record.tierId !== "number" || !Number.isSafeInteger(record.tierId) || record.tierId < 0) {
17
- throw new Error(`${FEE_DISCOUNT_ENDPOINT}: expected number field "tierId"`);
18
- }
19
16
  return {
20
17
  userReferralInfo: {
21
18
  userReferralCode: (0, validation_1.readApiString)({ record, name: "userReferralCode", endpoint }),
@@ -23,13 +20,17 @@ function parseFeeDiscount(raw) {
23
20
  referralCodeForTxn: (0, validation_1.readApiString)({ record, name: "referralCodeForTxn", endpoint }),
24
21
  attachedOnChain: record.attachedOnChain,
25
22
  affiliate: (0, validation_1.readApiString)({ record, name: "affiliate", endpoint }),
26
- tierId: record.tierId,
23
+ tierId: (0, validation_1.readApiUnsignedInteger)({ record, name: "tierId", endpoint }),
27
24
  totalRebate: (0, validation_1.readApiUnsignedBigInt)({ record, name: "totalRebate", endpoint }),
28
25
  totalRebateFactor: (0, validation_1.readApiUnsignedBigInt)({ record, name: "totalRebateFactor", endpoint }),
29
26
  discountShare: (0, validation_1.readApiUnsignedBigInt)({ record, name: "discountShare", endpoint }),
30
27
  discountFactor: (0, validation_1.readApiUnsignedBigInt)({ record, name: "discountFactor", endpoint }),
31
28
  },
32
29
  orderFeeDiscountFactor: (0, validation_1.readApiUnsignedBigInt)({ record, name: "orderFeeDiscountFactor", endpoint }),
30
+ gtRank: (0, validation_1.readApiUnsignedInteger)({ record, name: "gtRank", endpoint }),
31
+ rankDiscountFactor: (0, validation_1.readApiUnsignedBigInt)({ record, name: "rankDiscountFactor", endpoint }),
32
+ referrer: record.referrer === null ? undefined : (0, validation_1.readApiString)({ record, name: "referrer", endpoint }),
33
+ referredUserDiscountFactor: (0, validation_1.readApiUnsignedBigInt)({ record, name: "referredUserDiscountFactor", endpoint }),
33
34
  updatedAt: typeof record.updatedAt === "number" ? record.updatedAt : undefined,
34
35
  };
35
36
  }