@gmx-io/sdk 2.9.3 → 3.0.1

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