@gmx-io/sdk 2.2.0 → 2.3.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.
- package/build/cjs/src/abis/TransitStation.js +2222 -0
- package/build/cjs/src/abis/index.js +2 -0
- package/build/cjs/src/clients/v2/index.js +54 -27
- package/build/cjs/src/codegen/prebuilt/hashedKinkModelMarketRatesKeys.json +32 -0
- package/build/cjs/src/codegen/prebuilt/hashedMarketConfigKeys.json +272 -0
- package/build/cjs/src/codegen/prebuilt/hashedMarketValuesKeys.json +60 -0
- package/build/cjs/src/configs/markets.js +28 -0
- package/build/cjs/src/configs/tokens.js +9 -0
- package/build/cjs/src/test/mock.js +32 -4
- package/build/cjs/src/utils/markets/utils.js +45 -1
- package/build/cjs/src/utils/paxos/__tests__/api.spec.js +128 -0
- package/build/cjs/src/utils/paxos/api.js +129 -0
- package/build/cjs/src/utils/paxos/types.js +2 -0
- package/build/cjs/src/utils/trade/__tests__/increaseMarginCheck.spec.js +14 -35
- package/build/cjs/src/utils/trade/__tests__/twapIncreaseMarginCheck.spec.js +368 -0
- package/build/cjs/src/utils/trade/increaseMarginCheck.js +27 -13
- package/build/cjs/src/utils/trade/twapIncreaseMarginCheck.js +180 -0
- package/build/cjs/src/utils/twap/index.js +13 -4
- package/build/cjs/src/utils/usdgBoostApr/api.js +7 -0
- package/build/cjs/src/utils/usdgBoostApr/types.js +2 -0
- package/build/cjs/src/utils/whitelists/api.js +9 -0
- package/build/cjs/src/utils/whitelists/types.js +2 -0
- package/build/esm/src/abis/TransitStation.js +2220 -0
- package/build/esm/src/abis/index.js +2 -0
- package/build/esm/src/clients/v2/index.js +27 -0
- package/build/esm/src/codegen/prebuilt/hashedKinkModelMarketRatesKeys.json +32 -0
- package/build/esm/src/codegen/prebuilt/hashedMarketConfigKeys.json +272 -0
- package/build/esm/src/codegen/prebuilt/hashedMarketValuesKeys.json +60 -0
- package/build/esm/src/configs/markets.js +28 -0
- package/build/esm/src/configs/tokens.js +9 -0
- package/build/esm/src/test/mock.js +27 -0
- package/build/esm/src/utils/markets/utils.js +44 -1
- package/build/esm/src/utils/paxos/__tests__/api.spec.js +126 -0
- package/build/esm/src/utils/paxos/api.js +120 -0
- package/build/esm/src/utils/paxos/types.js +1 -0
- package/build/esm/src/utils/trade/__tests__/increaseMarginCheck.spec.js +15 -36
- package/build/esm/src/utils/trade/__tests__/twapIncreaseMarginCheck.spec.js +366 -0
- package/build/esm/src/utils/trade/increaseMarginCheck.js +24 -11
- package/build/esm/src/utils/trade/twapIncreaseMarginCheck.js +172 -0
- package/build/esm/src/utils/twap/index.js +10 -3
- package/build/esm/src/utils/usdgBoostApr/api.js +3 -0
- package/build/esm/src/utils/usdgBoostApr/types.js +1 -0
- package/build/esm/src/utils/whitelists/api.js +5 -0
- package/build/esm/src/utils/whitelists/types.js +1 -0
- package/build/tsconfig.tsbuildinfo +1 -1
- package/build/types/src/abis/TransitStation.d.ts +1710 -0
- package/build/types/src/abis/index.d.ts +1709 -0
- package/build/types/src/clients/v2/index.d.ts +20 -0
- package/build/types/src/codegen/prebuilt/index.d.ts +364 -0
- package/build/types/src/test/mock.d.ts +5 -0
- package/build/types/src/utils/markets/utils.d.ts +3 -0
- package/build/types/src/utils/paxos/__tests__/api.spec.d.ts +1 -0
- package/build/types/src/utils/paxos/api.d.ts +24 -0
- package/build/types/src/utils/paxos/types.d.ts +139 -0
- package/build/types/src/utils/trade/__tests__/twapIncreaseMarginCheck.spec.d.ts +1 -0
- package/build/types/src/utils/trade/increaseMarginCheck.d.ts +15 -7
- package/build/types/src/utils/trade/twapIncreaseMarginCheck.d.ts +50 -0
- package/build/types/src/utils/trade/types.d.ts +2 -0
- package/build/types/src/utils/twap/index.d.ts +2 -0
- package/build/types/src/utils/usdgBoostApr/api.d.ts +5 -0
- package/build/types/src/utils/usdgBoostApr/types.d.ts +19 -0
- package/build/types/src/utils/whitelists/api.d.ts +7 -0
- package/build/types/src/utils/whitelists/types.d.ts +6 -0
- package/package.json +10 -1
|
@@ -0,0 +1,366 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
import { mockMarginCheckMarketInfo, mockTokensData, usdToToken } from "../../../test/mock";
|
|
3
|
+
import { bigMath } from "../../bigmath";
|
|
4
|
+
import { getBorrowingFeeRateUsd } from "../../fees";
|
|
5
|
+
import { getMarketInfoWithSwapDelta } from "../../markets";
|
|
6
|
+
import { USD_DECIMALS, expandDecimals } from "../../numbers";
|
|
7
|
+
import { SwapPricingType } from "../../orders/types";
|
|
8
|
+
import { getSwapPathStats } from "../../swap/swapStats";
|
|
9
|
+
import { convertToUsd } from "../../tokens";
|
|
10
|
+
import { PositionMarginFailureReason, getIncreaseResultingPositionMarginState, getIncreaseResultingPositionState, getIsMaxLeverageMarginReason, } from "../increaseMarginCheck";
|
|
11
|
+
import { getTwapIncreasePartsGrossCollateralUsd, getTwapIncreaseSequentialMarginState, } from "../twapIncreaseMarginCheck";
|
|
12
|
+
import { getTwapPartDelaysSeconds } from "../../twap";
|
|
13
|
+
const tokensData = mockTokensData();
|
|
14
|
+
const usdc = tokensData.USDC;
|
|
15
|
+
function usd(amount) {
|
|
16
|
+
return expandDecimals(amount, USD_DECIMALS);
|
|
17
|
+
}
|
|
18
|
+
/** A position of `sizeUsd` whose tokens are worth `valueUsd` at the oracle: the loss is the difference. */
|
|
19
|
+
function position({ sizeUsd, valueUsd, collateralUsd }) {
|
|
20
|
+
return {
|
|
21
|
+
sizeInUsd: usd(sizeUsd),
|
|
22
|
+
sizeInTokens: usdToToken(valueUsd, tokensData.BTC),
|
|
23
|
+
collateralAmount: usdToToken(collateralUsd, usdc),
|
|
24
|
+
pendingImpactAmount: 0n,
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
const HOUR = 3600;
|
|
28
|
+
// parts spaced an hour apart, the first one executable now
|
|
29
|
+
function hourlyDelays(numberOfParts) {
|
|
30
|
+
return getTwapPartDelaysSeconds({ hours: numberOfParts - 1, minutes: 0 }, numberOfParts);
|
|
31
|
+
}
|
|
32
|
+
// a 50x position of 10 000 on 200 of collateral, topped up by four parts of 25 each
|
|
33
|
+
function baseParams({ partGrossCollateralUsd = usd(25), ...overrides } = {}) {
|
|
34
|
+
const numberOfParts = overrides.numberOfParts ?? 4;
|
|
35
|
+
return {
|
|
36
|
+
marketInfo: mockMarginCheckMarketInfo(tokensData),
|
|
37
|
+
collateralToken: usdc,
|
|
38
|
+
isLong: true,
|
|
39
|
+
existingPosition: position({ sizeUsd: 10000, valueUsd: 10000, collateralUsd: 200 }),
|
|
40
|
+
numberOfParts,
|
|
41
|
+
partDelaysSeconds: hourlyDelays(numberOfParts),
|
|
42
|
+
partGrossCollateralUsds: Array.from({ length: numberOfParts }, () => partGrossCollateralUsd),
|
|
43
|
+
partSizeDeltaUsd: usd(10000),
|
|
44
|
+
pendingFeesUsd: 0n,
|
|
45
|
+
uiFeeFactor: 0n,
|
|
46
|
+
minCollateralUsd: usd(1),
|
|
47
|
+
userReferralInfo: undefined,
|
|
48
|
+
...overrides,
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
describe("getTwapIncreaseSequentialMarginState", () => {
|
|
52
|
+
describe.each([
|
|
53
|
+
{ side: "long", isLong: true },
|
|
54
|
+
{ side: "short", isLong: false },
|
|
55
|
+
])("$side", ({ isLong }) => {
|
|
56
|
+
// after part k the position holds 10 000 + k × size on 200 + k × 25 of collateral against a 1% minimum
|
|
57
|
+
it.each([
|
|
58
|
+
{
|
|
59
|
+
name: "every part stays within the max leverage",
|
|
60
|
+
partSizeUsd: 1000,
|
|
61
|
+
partDelaysSeconds: hourlyDelays(4),
|
|
62
|
+
failingPartIndex: undefined,
|
|
63
|
+
blocking: false,
|
|
64
|
+
},
|
|
65
|
+
{
|
|
66
|
+
name: "a later part crosses the max leverage",
|
|
67
|
+
partSizeUsd: 10000,
|
|
68
|
+
partDelaysSeconds: hourlyDelays(4),
|
|
69
|
+
failingPartIndex: 1,
|
|
70
|
+
blocking: false,
|
|
71
|
+
},
|
|
72
|
+
{
|
|
73
|
+
name: "the first part crosses the max leverage",
|
|
74
|
+
partSizeUsd: 20000,
|
|
75
|
+
partDelaysSeconds: hourlyDelays(4),
|
|
76
|
+
failingPartIndex: 0,
|
|
77
|
+
blocking: true,
|
|
78
|
+
},
|
|
79
|
+
{
|
|
80
|
+
name: "a zero duration makes the crossing part eligible now",
|
|
81
|
+
partSizeUsd: 10000,
|
|
82
|
+
partDelaysSeconds: [0, 0, 0, 0],
|
|
83
|
+
failingPartIndex: 1,
|
|
84
|
+
blocking: true,
|
|
85
|
+
},
|
|
86
|
+
])("$name", ({ partSizeUsd, partDelaysSeconds, failingPartIndex, blocking }) => {
|
|
87
|
+
const state = getTwapIncreaseSequentialMarginState(baseParams({ isLong, partSizeDeltaUsd: usd(partSizeUsd), partDelaysSeconds }));
|
|
88
|
+
expect(state.failingPartIndex).toBe(failingPartIndex);
|
|
89
|
+
expect(state.isFailingPartEligibleNow).toBe(blocking);
|
|
90
|
+
expect(state.marginState.isLiquidatable).toBe(failingPartIndex !== undefined);
|
|
91
|
+
if (failingPartIndex !== undefined) {
|
|
92
|
+
expect(getIsMaxLeverageMarginReason(state.marginState.reason)).toBe(true);
|
|
93
|
+
}
|
|
94
|
+
});
|
|
95
|
+
});
|
|
96
|
+
it("settles the existing position's pending fees once, with the first part", () => {
|
|
97
|
+
// 500 of collateral plus 100 deposited across the parts, less 40 of pending fees, leaves 560 whatever the split
|
|
98
|
+
const remaining = [1, 2, 4].map((numberOfParts) => getTwapIncreaseSequentialMarginState(baseParams({
|
|
99
|
+
existingPosition: position({ sizeUsd: 10000, valueUsd: 10000, collateralUsd: 500 }),
|
|
100
|
+
numberOfParts,
|
|
101
|
+
partSizeDeltaUsd: usd(4000 / numberOfParts),
|
|
102
|
+
partGrossCollateralUsd: usd(100 / numberOfParts),
|
|
103
|
+
pendingFeesUsd: usd(40),
|
|
104
|
+
})).marginState.remainingCollateralUsd);
|
|
105
|
+
expect(remaining).toEqual([usd(560), usd(560), usd(560)]);
|
|
106
|
+
});
|
|
107
|
+
it("charges every part the open interest left by the parts before it", () => {
|
|
108
|
+
// 1e-8 of min collateral per usd of long open interest: 1% at the 1M already open
|
|
109
|
+
const marketInfo = mockMarginCheckMarketInfo(tokensData, {
|
|
110
|
+
minCollateralFactorForOpenInterestLong: expandDecimals(1, 22),
|
|
111
|
+
longInterestUsd: usd(1000000),
|
|
112
|
+
longInterestInTokens: usdToToken(1000000, tokensData.BTC),
|
|
113
|
+
});
|
|
114
|
+
const part = {
|
|
115
|
+
sizeDeltaUsd: usd(250000),
|
|
116
|
+
sizeDeltaInTokens: usdToToken(250000, tokensData.BTC),
|
|
117
|
+
collateralDeltaAmount: usdToToken(4000, usdc),
|
|
118
|
+
};
|
|
119
|
+
const state = getTwapIncreaseSequentialMarginState(baseParams({
|
|
120
|
+
marketInfo,
|
|
121
|
+
existingPosition: undefined,
|
|
122
|
+
partSizeDeltaUsd: part.sizeDeltaUsd,
|
|
123
|
+
partGrossCollateralUsd: usd(4000),
|
|
124
|
+
}));
|
|
125
|
+
// parts 1 and 2 clear 1.25% and 1.5% of their cumulative size; part 3 needs 1.75% of 750 000 = 13 125 on 12 000
|
|
126
|
+
expect(state.failingPartIndex).toBe(2);
|
|
127
|
+
expect(state.marginState.reason).toBe(PositionMarginFailureReason.InsufficientCollateralUsd);
|
|
128
|
+
const standalone = getIncreaseResultingPositionMarginState({
|
|
129
|
+
marketInfo,
|
|
130
|
+
collateralToken: usdc,
|
|
131
|
+
isLong: true,
|
|
132
|
+
existingPosition: undefined,
|
|
133
|
+
...part,
|
|
134
|
+
minCollateralUsd: usd(1),
|
|
135
|
+
userReferralInfo: undefined,
|
|
136
|
+
});
|
|
137
|
+
expect(standalone?.isLiquidatable).toBe(false);
|
|
138
|
+
});
|
|
139
|
+
it("counts the existing position's unrealized loss against the remaining margin of later parts", () => {
|
|
140
|
+
// four parts of 5 000 on 25 of collateral each; 2 350 of loss on 2 500 of collateral
|
|
141
|
+
const parts = { partSizeDeltaUsd: usd(5000), partGrossCollateralUsd: usd(25) };
|
|
142
|
+
const flat = getTwapIncreaseSequentialMarginState(baseParams({ ...parts, existingPosition: position({ sizeUsd: 10000, valueUsd: 10000, collateralUsd: 2500 }) }));
|
|
143
|
+
const losing = getTwapIncreaseSequentialMarginState(baseParams({ ...parts, existingPosition: position({ sizeUsd: 10000, valueUsd: 7650, collateralUsd: 2500 }) }));
|
|
144
|
+
expect(flat.failingPartIndex).toBeUndefined();
|
|
145
|
+
// 150 + 25 × k of remaining margin against 1% of 10 000 + 5 000 × k: the third part is the first short of it
|
|
146
|
+
expect(losing.failingPartIndex).toBe(2);
|
|
147
|
+
expect(losing.marginState.reason).toBe(PositionMarginFailureReason.MinCollateralForLeverage);
|
|
148
|
+
});
|
|
149
|
+
it("carries each part's price impact into the next part without double counting", () => {
|
|
150
|
+
const marketInfo = mockMarginCheckMarketInfo(tokensData, {
|
|
151
|
+
positionImpactFactorPositive: expandDecimals(5, 22),
|
|
152
|
+
positionImpactFactorNegative: expandDecimals(1, 23),
|
|
153
|
+
maxPositionImpactFactorNegative: expandDecimals(1, 28),
|
|
154
|
+
maxPositionImpactFactorForLiquidations: expandDecimals(1, 28),
|
|
155
|
+
});
|
|
156
|
+
const parts = { existingPosition: undefined, partSizeDeltaUsd: usd(50000), partGrossCollateralUsd: usd(5000) };
|
|
157
|
+
const split = getTwapIncreaseSequentialMarginState(baseParams({ ...parts, marketInfo }));
|
|
158
|
+
const noImpact = getTwapIncreaseSequentialMarginState(baseParams(parts));
|
|
159
|
+
const aggregate = getIncreaseResultingPositionState({
|
|
160
|
+
marketInfo,
|
|
161
|
+
collateralToken: usdc,
|
|
162
|
+
isLong: true,
|
|
163
|
+
existingPosition: undefined,
|
|
164
|
+
sizeDeltaUsd: usd(200000),
|
|
165
|
+
sizeDeltaInTokens: usdToToken(200000, tokensData.BTC),
|
|
166
|
+
collateralDeltaAmount: usdToToken(20000, usdc),
|
|
167
|
+
minCollateralUsd: usd(1),
|
|
168
|
+
userReferralInfo: undefined,
|
|
169
|
+
});
|
|
170
|
+
expect(aggregate.position.pendingImpactAmount).toBeLessThan(0n);
|
|
171
|
+
expect(split.marginState.remainingCollateralUsd).toBeLessThan(noImpact.marginState.remainingCollateralUsd);
|
|
172
|
+
// the impact of four steps through the same open interest telescopes to the one-shot impact, up to rounding
|
|
173
|
+
expect(bigMath.abs(split.marginState.remainingCollateralUsd - aggregate.marginState.remainingCollateralUsd)).toBeLessThan(expandDecimals(1, 28));
|
|
174
|
+
});
|
|
175
|
+
});
|
|
176
|
+
describe("getTwapIncreaseSequentialMarginState — the market's max allowed leverage", () => {
|
|
177
|
+
// 0.5% for both factors: the contract accepts up to 200x, the ui caps an order's resulting position at 100x
|
|
178
|
+
const capOnlyMarket = mockMarginCheckMarketInfo(tokensData, { minCollateralFactor: expandDecimals(5, 27) });
|
|
179
|
+
it.each([
|
|
180
|
+
{
|
|
181
|
+
name: "a fresh position's first part at 150x",
|
|
182
|
+
existingPosition: undefined,
|
|
183
|
+
partSizeUsd: 3750,
|
|
184
|
+
failingPartIndex: 0,
|
|
185
|
+
isFailingPartEligibleNow: true,
|
|
186
|
+
},
|
|
187
|
+
{
|
|
188
|
+
// 30 800 of size on 300 of collateral after the fourth part: 102.7x
|
|
189
|
+
name: "the last part on a 50x position",
|
|
190
|
+
existingPosition: position({ sizeUsd: 10000, valueUsd: 10000, collateralUsd: 200 }),
|
|
191
|
+
partSizeUsd: 5200,
|
|
192
|
+
failingPartIndex: 3,
|
|
193
|
+
isFailingPartEligibleNow: false,
|
|
194
|
+
},
|
|
195
|
+
].flatMap((row) => [
|
|
196
|
+
{ ...row, side: "long", isLong: true },
|
|
197
|
+
{ ...row, side: "short", isLong: false },
|
|
198
|
+
]))("fails $name ($side) that the contract would accept", ({ existingPosition, partSizeUsd, isLong, failingPartIndex, isFailingPartEligibleNow }) => {
|
|
199
|
+
const state = getTwapIncreaseSequentialMarginState(baseParams({ marketInfo: capOnlyMarket, isLong, existingPosition, partSizeDeltaUsd: usd(partSizeUsd) }));
|
|
200
|
+
expect(state).toMatchObject({ failingPartIndex, isFailingPartEligibleNow });
|
|
201
|
+
expect(state.marginState.reason).toBe(PositionMarginFailureReason.MaxAllowedLeverage);
|
|
202
|
+
expect(getIsMaxLeverageMarginReason(state.marginState.reason)).toBe(true);
|
|
203
|
+
expect(state.contractMarginState.isLiquidatable).toBe(false);
|
|
204
|
+
});
|
|
205
|
+
});
|
|
206
|
+
describe("getTwapIncreaseSequentialMarginState — fees accrued between the parts PRO-4134", () => {
|
|
207
|
+
// 2e-8 of borrowing per second: 1 h on 10 000 of size costs 0.72
|
|
208
|
+
const borrowingMarket = mockMarginCheckMarketInfo(tokensData, {
|
|
209
|
+
borrowingFactorPerSecondForLongs: expandDecimals(2, 22),
|
|
210
|
+
borrowingFactorPerSecondForShorts: expandDecimals(2, 22),
|
|
211
|
+
});
|
|
212
|
+
// four parts of 7 500 on 25 each: the second part lands exactly on the 1% minimum (250 on 25 000)
|
|
213
|
+
const edgeParts = { partSizeDeltaUsd: usd(7500), partGrossCollateralUsd: usd(25) };
|
|
214
|
+
it("settles the borrowing accrued since the previous part at the snapshot rate", () => {
|
|
215
|
+
const parts = { existingPosition: undefined, partSizeDeltaUsd: usd(5000), partGrossCollateralUsd: usd(500) };
|
|
216
|
+
const noDelay = getTwapIncreaseSequentialMarginState(baseParams({ ...parts, marketInfo: borrowingMarket, partDelaysSeconds: [0, 0, 0, 0] }));
|
|
217
|
+
const hourly = getTwapIncreaseSequentialMarginState(baseParams({ ...parts, marketInfo: borrowingMarket }));
|
|
218
|
+
// parts 2–4 each pay an hour of borrowing on the size the previous parts left: 5 000, 10 000, 15 000
|
|
219
|
+
const accruedUsd = [5000, 10000, 15000].reduce((sum, sizeUsd) => sum + getBorrowingFeeRateUsd(borrowingMarket, true, usd(sizeUsd), BigInt(HOUR)), 0n);
|
|
220
|
+
expect(accruedUsd).toBe(usd(216) / 100n);
|
|
221
|
+
expect(noDelay.marginState.remainingCollateralUsd - hourly.marginState.remainingCollateralUsd).toBe(accruedUsd);
|
|
222
|
+
});
|
|
223
|
+
it("fails a later part that passes at the snapshot once the borrowing before it is settled", () => {
|
|
224
|
+
const atSnapshot = getTwapIncreaseSequentialMarginState(baseParams({ ...edgeParts, marketInfo: borrowingMarket, partDelaysSeconds: [0, 0, 0, 0] }));
|
|
225
|
+
const hourly = getTwapIncreaseSequentialMarginState(baseParams({ ...edgeParts, marketInfo: borrowingMarket }));
|
|
226
|
+
expect(atSnapshot.failingPartIndex).toBe(2);
|
|
227
|
+
expect(hourly).toMatchObject({ failingPartIndex: 1, isFailingPartEligibleNow: false });
|
|
228
|
+
// 1.26 of borrowing on 17 500 pushes the part past both the 100x cap and the contract's 1% minimum
|
|
229
|
+
expect(getIsMaxLeverageMarginReason(hourly.marginState.reason)).toBe(true);
|
|
230
|
+
expect(hourly.contractMarginState.isLiquidatable).toBe(true);
|
|
231
|
+
expect(getIsMaxLeverageMarginReason(hourly.contractMarginState.reason)).toBe(true);
|
|
232
|
+
});
|
|
233
|
+
it("charges the existing position for the wait before a first part that is not executable yet", () => {
|
|
234
|
+
const delays = hourlyDelays(4);
|
|
235
|
+
const now = getTwapIncreaseSequentialMarginState(baseParams({ ...edgeParts, marketInfo: borrowingMarket }));
|
|
236
|
+
const inAnHour = getTwapIncreaseSequentialMarginState(baseParams({ ...edgeParts, marketInfo: borrowingMarket, partDelaysSeconds: delays.map((d) => d + HOUR) }));
|
|
237
|
+
expect(inAnHour.isFailingPartEligibleNow).toBe(false);
|
|
238
|
+
expect(now.marginState.remainingCollateralUsd - inAnHour.marginState.remainingCollateralUsd).toBe(getBorrowingFeeRateUsd(borrowingMarket, true, usd(10000), BigInt(HOUR)));
|
|
239
|
+
});
|
|
240
|
+
it("settles funding only for the side that pays it", () => {
|
|
241
|
+
// longs pay 1e-8 per second; the market needs open interest on both sides to split the funding
|
|
242
|
+
const fundingMarket = (longsPayShorts) => mockMarginCheckMarketInfo(tokensData, {
|
|
243
|
+
fundingFactorPerSecond: expandDecimals(1, 22),
|
|
244
|
+
longsPayShorts,
|
|
245
|
+
longInterestUsd: usd(1000000),
|
|
246
|
+
shortInterestUsd: usd(1000000),
|
|
247
|
+
longInterestInTokens: usdToToken(1000000, tokensData.BTC),
|
|
248
|
+
shortInterestInTokens: usdToToken(1000000, tokensData.BTC),
|
|
249
|
+
});
|
|
250
|
+
const parts = { existingPosition: undefined, partSizeDeltaUsd: usd(5000), partGrossCollateralUsd: usd(500) };
|
|
251
|
+
const remaining = (longsPayShorts) => getTwapIncreaseSequentialMarginState(baseParams({ ...parts, marketInfo: fundingMarket(longsPayShorts) }))
|
|
252
|
+
.marginState.remainingCollateralUsd;
|
|
253
|
+
// paying: an hour on 5 000 + 10 000 + 15 000 at 1e-8/s = 1.08; receiving: nothing leaves the collateral
|
|
254
|
+
expect(remaining(false) - remaining(true)).toBe(usd(108) / 100n);
|
|
255
|
+
expect(remaining(false)).toBe(getTwapIncreaseSequentialMarginState(baseParams(parts)).marginState.remainingCollateralUsd);
|
|
256
|
+
});
|
|
257
|
+
});
|
|
258
|
+
describe("getTwapIncreasePartsGrossCollateralUsd — each part swaps its own deposit PRO-4134", () => {
|
|
259
|
+
const NO_NATIVE = "0x0000000000000000000000000000000000000000";
|
|
260
|
+
// the mock pools hold 1 000 of each token: four deposits of 100 BTC-worth move them a lot
|
|
261
|
+
const market = mockMarginCheckMarketInfo(tokensData);
|
|
262
|
+
const marketsInfoData = { [market.marketTokenAddress]: market };
|
|
263
|
+
const btc = tokensData.BTC;
|
|
264
|
+
function quote(numberOfParts, depositUsd, swapPath = [market.marketTokenAddress]) {
|
|
265
|
+
return getTwapIncreasePartsGrossCollateralUsd({
|
|
266
|
+
marketsInfoData,
|
|
267
|
+
swapPath,
|
|
268
|
+
initialCollateralToken: btc,
|
|
269
|
+
collateralToken: usdc,
|
|
270
|
+
initialCollateralAmountPerPart: usdToToken(depositUsd, btc),
|
|
271
|
+
numberOfParts,
|
|
272
|
+
uiFeeFactor: 0n,
|
|
273
|
+
wrappedNativeTokenAddress: NO_NATIVE,
|
|
274
|
+
});
|
|
275
|
+
}
|
|
276
|
+
it("gives every part its deposit when no swap is needed", () => {
|
|
277
|
+
expect(quote(4, 25, [])).toEqual([usd(25), usd(25), usd(25), usd(25)]);
|
|
278
|
+
});
|
|
279
|
+
it("quotes each part against the pool the previous parts leave, so the first part gets the most", () => {
|
|
280
|
+
const parts = quote(4, 100);
|
|
281
|
+
const oneShot = getSwapPathStats({
|
|
282
|
+
marketsInfoData,
|
|
283
|
+
swapPath: [market.marketTokenAddress],
|
|
284
|
+
initialCollateralAddress: btc.address,
|
|
285
|
+
wrappedNativeTokenAddress: NO_NATIVE,
|
|
286
|
+
usdIn: usd(400),
|
|
287
|
+
shouldUnwrapNativeToken: false,
|
|
288
|
+
shouldApplyPriceImpact: true,
|
|
289
|
+
swapPricingType: SwapPricingType.Swap,
|
|
290
|
+
});
|
|
291
|
+
const oneShotUsd = convertToUsd(oneShot.amountOut, usdc.decimals, usdc.prices.minPrice);
|
|
292
|
+
const total = parts.reduce((sum, part) => sum + part, 0n);
|
|
293
|
+
expect(parts[0]).toBeGreaterThan(parts[1]);
|
|
294
|
+
expect(parts[1]).toBeGreaterThan(parts[2]);
|
|
295
|
+
expect(parts[2]).toBeGreaterThan(parts[3]);
|
|
296
|
+
// a split of the one-shot output would give every part the average price impact
|
|
297
|
+
expect(parts[0]).toBeGreaterThan(oneShotUsd / 4n);
|
|
298
|
+
expect(parts[3]).toBeLessThan(oneShotUsd / 4n);
|
|
299
|
+
// the impact telescopes: the four swaps together cost about what the one-shot swap does
|
|
300
|
+
expect(bigMath.abs(total - oneShotUsd)).toBeLessThan(oneShotUsd / 100n);
|
|
301
|
+
});
|
|
302
|
+
});
|
|
303
|
+
describe("getMarketInfoWithSwapDelta — the pools a swap step leaves, as SwapUtils._swap leaves them", () => {
|
|
304
|
+
const btc = tokensData.BTC;
|
|
305
|
+
function swapStep(overrides = {}) {
|
|
306
|
+
return {
|
|
307
|
+
marketAddress: "",
|
|
308
|
+
tokenInAddress: btc.address,
|
|
309
|
+
tokenOutAddress: usdc.address,
|
|
310
|
+
isWrap: false,
|
|
311
|
+
isUnwrap: false,
|
|
312
|
+
swapFeeAmount: usdToToken(1, btc),
|
|
313
|
+
swapFeeUsd: usd(1),
|
|
314
|
+
priceImpactDeltaUsd: 0n,
|
|
315
|
+
amountIn: usdToToken(100, btc),
|
|
316
|
+
amountInAfterFees: usdToToken(99, btc),
|
|
317
|
+
usdIn: usd(100),
|
|
318
|
+
amountOut: usdToToken(99, usdc),
|
|
319
|
+
usdOut: usd(99),
|
|
320
|
+
...overrides,
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
it("moves the swapped amounts between the pools, and the virtual pools when the market has them", () => {
|
|
324
|
+
const market = mockMarginCheckMarketInfo(tokensData, {
|
|
325
|
+
virtualPoolAmountForLongToken: usdToToken(5000, btc),
|
|
326
|
+
virtualPoolAmountForShortToken: 0n,
|
|
327
|
+
});
|
|
328
|
+
const next = getMarketInfoWithSwapDelta(market, swapStep());
|
|
329
|
+
expect(next.longPoolAmount - market.longPoolAmount).toBe(usdToToken(99, btc));
|
|
330
|
+
expect(market.shortPoolAmount - next.shortPoolAmount).toBe(usdToToken(99, usdc));
|
|
331
|
+
expect(next.virtualPoolAmountForLongToken - market.virtualPoolAmountForLongToken).toBe(usdToToken(99, btc));
|
|
332
|
+
expect(next.virtualPoolAmountForShortToken).toBe(0n);
|
|
333
|
+
expect(next.swapImpactPoolAmountLong).toBe(market.swapImpactPoolAmountLong);
|
|
334
|
+
expect(next.swapImpactPoolAmountShort).toBe(market.swapImpactPoolAmountShort);
|
|
335
|
+
});
|
|
336
|
+
it("keeps a negative impact out of the pool: it goes to the swap impact pool of the token in", () => {
|
|
337
|
+
const market = mockMarginCheckMarketInfo(tokensData);
|
|
338
|
+
// of the 99 left after fees, 2 of impact stay in the impact pool and 97 reach the pool; 97 leave the other side
|
|
339
|
+
const next = getMarketInfoWithSwapDelta(market, swapStep({ priceImpactDeltaUsd: -usd(2), amountOut: usdToToken(97, usdc), usdOut: usd(97) }));
|
|
340
|
+
expect(next.longPoolAmount - market.longPoolAmount).toBe(usdToToken(97, btc));
|
|
341
|
+
expect(next.swapImpactPoolAmountLong - market.swapImpactPoolAmountLong).toBe(usdToToken(2, btc));
|
|
342
|
+
expect(market.shortPoolAmount - next.shortPoolAmount).toBe(usdToToken(97, usdc));
|
|
343
|
+
expect(next.swapImpactPoolAmountShort).toBe(market.swapImpactPoolAmountShort);
|
|
344
|
+
});
|
|
345
|
+
it("pays a positive impact from the impact pools, the token out first, then the token in", () => {
|
|
346
|
+
const market = mockMarginCheckMarketInfo(tokensData, {
|
|
347
|
+
swapImpactPoolAmountShort: usdToToken(3, usdc),
|
|
348
|
+
swapImpactPoolAmountLong: usdToToken(10, btc),
|
|
349
|
+
});
|
|
350
|
+
// 5 of impact on top of the 99 swapped: 3 USDC drain the short impact pool, 2 worth of BTC come from the long one
|
|
351
|
+
const next = getMarketInfoWithSwapDelta(market, swapStep({ priceImpactDeltaUsd: usd(5), amountOut: usdToToken(104, usdc), usdOut: usd(104) }));
|
|
352
|
+
expect(next.swapImpactPoolAmountShort).toBe(0n);
|
|
353
|
+
expect(market.swapImpactPoolAmountLong - next.swapImpactPoolAmountLong).toBe(usdToToken(2, btc));
|
|
354
|
+
expect(market.shortPoolAmount - next.shortPoolAmount).toBe(usdToToken(101, usdc));
|
|
355
|
+
expect(next.longPoolAmount - market.longPoolAmount).toBe(usdToToken(101, btc));
|
|
356
|
+
});
|
|
357
|
+
});
|
|
358
|
+
describe("getTwapPartDelaysSeconds", () => {
|
|
359
|
+
it.each([
|
|
360
|
+
{ duration: { hours: 10, minutes: 0 }, numberOfParts: 5, delays: [0, 9000, 18000, 27000, 36000] },
|
|
361
|
+
{ duration: { hours: 0, minutes: 0 }, numberOfParts: 5, delays: [0, 0, 0, 0, 0] },
|
|
362
|
+
{ duration: { hours: 10, minutes: 0 }, numberOfParts: 1, delays: [0] },
|
|
363
|
+
])("$duration.hours h over $numberOfParts parts", ({ duration, numberOfParts, delays }) => {
|
|
364
|
+
expect(getTwapPartDelaysSeconds(duration, numberOfParts)).toEqual(delays);
|
|
365
|
+
});
|
|
366
|
+
});
|
|
@@ -9,10 +9,12 @@ export var PositionMarginFailureReason;
|
|
|
9
9
|
PositionMarginFailureReason["NonPositiveRemainingMargin"] = "< 0";
|
|
10
10
|
PositionMarginFailureReason["MinCollateralForLeverage"] = "min collateral for leverage";
|
|
11
11
|
PositionMarginFailureReason["InsufficientCollateralUsd"] = "insufficient collateral usd";
|
|
12
|
+
PositionMarginFailureReason["MaxAllowedLeverage"] = "max allowed leverage";
|
|
12
13
|
})(PositionMarginFailureReason || (PositionMarginFailureReason = {}));
|
|
13
14
|
export function getIsMaxLeverageMarginReason(reason) {
|
|
14
15
|
return (reason === PositionMarginFailureReason.MinCollateralForLeverage ||
|
|
15
|
-
reason === PositionMarginFailureReason.InsufficientCollateralUsd
|
|
16
|
+
reason === PositionMarginFailureReason.InsufficientCollateralUsd ||
|
|
17
|
+
reason === PositionMarginFailureReason.MaxAllowedLeverage);
|
|
16
18
|
}
|
|
17
19
|
/**
|
|
18
20
|
* Port of `PositionUtils.isPositionLiquidatable` from the gmx-synthetics build deployed on Arbitrum
|
|
@@ -98,6 +100,9 @@ function withPriceOverride(token, indexToken, price) {
|
|
|
98
100
|
* then `validatePosition` on the resulting position.
|
|
99
101
|
*/
|
|
100
102
|
export function getIncreaseResultingPositionMarginState(p) {
|
|
103
|
+
return getIncreaseResultingPositionState(p)?.marginState;
|
|
104
|
+
}
|
|
105
|
+
export function getIncreaseResultingPositionState(p) {
|
|
101
106
|
const { isLong, existingPosition, sizeDeltaUsd, sizeDeltaInTokens, collateralDeltaAmount, minCollateralUsd, userReferralInfo, proDiscountFactor, indexPriceForEvaluation, } = p;
|
|
102
107
|
let { marketInfo, collateralToken } = p;
|
|
103
108
|
if (sizeDeltaUsd <= 0n || sizeDeltaInTokens <= 0n) {
|
|
@@ -149,25 +154,33 @@ export function getIncreaseResultingPositionMarginState(p) {
|
|
|
149
154
|
minCollateralFactorForOpenInterest = nextMarketInfo.minCollateralFactor;
|
|
150
155
|
}
|
|
151
156
|
const minCollateralUsdForOpenInterest = applyFactor(nextSizeInUsd, minCollateralFactorForOpenInterest);
|
|
157
|
+
const position = {
|
|
158
|
+
sizeInUsd: nextSizeInUsd,
|
|
159
|
+
sizeInTokens: nextSizeInTokens,
|
|
160
|
+
collateralAmount: nextCollateralAmountClamped,
|
|
161
|
+
pendingImpactAmount: nextPendingImpactAmount,
|
|
162
|
+
};
|
|
152
163
|
if (remainingCollateralUsdForOpenInterest < minCollateralUsdForOpenInterest) {
|
|
153
164
|
return {
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
165
|
+
marginState: {
|
|
166
|
+
isLiquidatable: true,
|
|
167
|
+
reason: PositionMarginFailureReason.InsufficientCollateralUsd,
|
|
168
|
+
remainingCollateralUsd: remainingCollateralUsdForOpenInterest,
|
|
169
|
+
minCollateralUsd,
|
|
170
|
+
minCollateralUsdForLeverage: minCollateralUsdForOpenInterest,
|
|
171
|
+
},
|
|
172
|
+
position,
|
|
173
|
+
marketInfo: nextMarketInfo,
|
|
159
174
|
};
|
|
160
175
|
}
|
|
161
|
-
|
|
176
|
+
const marginState = getResultingPositionMarginState({
|
|
162
177
|
marketInfo: nextMarketInfo,
|
|
163
178
|
collateralToken,
|
|
164
|
-
|
|
165
|
-
sizeInTokens: nextSizeInTokens,
|
|
166
|
-
collateralAmount: nextCollateralAmountClamped,
|
|
167
|
-
pendingImpactAmount: nextPendingImpactAmount,
|
|
179
|
+
...position,
|
|
168
180
|
minCollateralUsd,
|
|
169
181
|
isLong,
|
|
170
182
|
userReferralInfo,
|
|
171
183
|
proDiscountFactor,
|
|
172
184
|
});
|
|
185
|
+
return { marginState, position, marketInfo: nextMarketInfo };
|
|
173
186
|
}
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import { BASIS_POINTS_DIVISOR_BIGINT } from "../../configs/factors";
|
|
2
|
+
import { bigMath } from "../bigmath";
|
|
3
|
+
import { getBorrowingFeeRateUsd, getFundingFeeRateUsd, getPositionFee, getPriceImpactForPosition, getTotalSwapVolumeFromSwapStats, } from "../fees";
|
|
4
|
+
import { getMarketInfoWithSwapDelta, getMaxAllowedLeverage } from "../markets";
|
|
5
|
+
import { applyFactor } from "../numbers";
|
|
6
|
+
import { SwapPricingType } from "../orders/types";
|
|
7
|
+
import { getLeverage } from "../positions";
|
|
8
|
+
import { getMarkPrice } from "../prices";
|
|
9
|
+
import { getSwapPathStats } from "../swap/swapStats";
|
|
10
|
+
import { convertToTokenAmount, convertToTokenAmountForIncrease, convertToUsd } from "../tokens";
|
|
11
|
+
import { getIncreaseResultingPositionState, PositionMarginFailureReason, } from "./increaseMarginCheck";
|
|
12
|
+
export function getTwapIncreaseAggregateAmounts(increaseAmounts) {
|
|
13
|
+
return {
|
|
14
|
+
sizeDeltaUsd: increaseAmounts.sizeDeltaUsd,
|
|
15
|
+
pendingFeesUsd: increaseAmounts.borrowingFeeUsd + increaseAmounts.fundingFeeUsd,
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
export function getTwapIncreasePartAmounts({ sizeDeltaUsd, pendingFeesUsd }, numberOfParts) {
|
|
19
|
+
if (numberOfParts < 1) {
|
|
20
|
+
return { partSizeDeltaUsd: 0n, pendingFeesUsd };
|
|
21
|
+
}
|
|
22
|
+
return { partSizeDeltaUsd: sizeDeltaUsd / BigInt(numberOfParts), pendingFeesUsd };
|
|
23
|
+
}
|
|
24
|
+
export function getTwapIncreasePartsGrossCollateralUsd(p) {
|
|
25
|
+
const { swapPath, initialCollateralToken, collateralToken, initialCollateralAmountPerPart, numberOfParts, uiFeeFactor, wrappedNativeTokenAddress, } = p;
|
|
26
|
+
if (numberOfParts < 1) {
|
|
27
|
+
return [];
|
|
28
|
+
}
|
|
29
|
+
const usdIn = convertToUsd(initialCollateralAmountPerPart, initialCollateralToken.decimals, initialCollateralToken.prices.minPrice);
|
|
30
|
+
if (swapPath.length === 0) {
|
|
31
|
+
return Array.from({ length: numberOfParts }, () => usdIn);
|
|
32
|
+
}
|
|
33
|
+
let marketsInfoData = p.marketsInfoData;
|
|
34
|
+
const partGrossCollateralUsds = [];
|
|
35
|
+
for (let partIndex = 0; partIndex < numberOfParts; partIndex++) {
|
|
36
|
+
const swapPathStats = getSwapPathStats({
|
|
37
|
+
marketsInfoData,
|
|
38
|
+
swapPath,
|
|
39
|
+
initialCollateralAddress: initialCollateralToken.address,
|
|
40
|
+
wrappedNativeTokenAddress,
|
|
41
|
+
usdIn,
|
|
42
|
+
shouldUnwrapNativeToken: false,
|
|
43
|
+
shouldApplyPriceImpact: true,
|
|
44
|
+
swapPricingType: SwapPricingType.Swap,
|
|
45
|
+
});
|
|
46
|
+
if (!swapPathStats || swapPathStats.amountOut <= 0n) {
|
|
47
|
+
return undefined;
|
|
48
|
+
}
|
|
49
|
+
const grossCollateralUsd = convertToUsd(swapPathStats.amountOut, collateralToken.decimals, collateralToken.prices.minPrice);
|
|
50
|
+
const swapUiFeeUsd = applyFactor(getTotalSwapVolumeFromSwapStats(swapPathStats.swapSteps), uiFeeFactor);
|
|
51
|
+
partGrossCollateralUsds.push(grossCollateralUsd - swapUiFeeUsd);
|
|
52
|
+
marketsInfoData = swapPathStats.swapSteps.reduce((acc, swapStep) => ({
|
|
53
|
+
...acc,
|
|
54
|
+
[swapStep.marketAddress]: getMarketInfoWithSwapDelta(acc[swapStep.marketAddress], swapStep),
|
|
55
|
+
}), marketsInfoData);
|
|
56
|
+
}
|
|
57
|
+
return partGrossCollateralUsds;
|
|
58
|
+
}
|
|
59
|
+
function getMaxAllowedLeverageMarginState({ position, collateralToken, maxAllowedLeverage, minCollateralUsd, }) {
|
|
60
|
+
const collateralUsd = convertToUsd(position.collateralAmount, collateralToken.decimals, collateralToken.prices.minPrice);
|
|
61
|
+
const leverage = getLeverage({
|
|
62
|
+
sizeInUsd: position.sizeInUsd,
|
|
63
|
+
collateralUsd,
|
|
64
|
+
pnl: undefined,
|
|
65
|
+
pendingBorrowingFeesUsd: 0n,
|
|
66
|
+
pendingFundingFeesUsd: 0n,
|
|
67
|
+
});
|
|
68
|
+
if (maxAllowedLeverage <= 0n || leverage === undefined || leverage <= maxAllowedLeverage) {
|
|
69
|
+
return undefined;
|
|
70
|
+
}
|
|
71
|
+
return {
|
|
72
|
+
isLiquidatable: true,
|
|
73
|
+
reason: PositionMarginFailureReason.MaxAllowedLeverage,
|
|
74
|
+
remainingCollateralUsd: collateralUsd,
|
|
75
|
+
minCollateralUsd,
|
|
76
|
+
minCollateralUsdForLeverage: bigMath.mulDiv(position.sizeInUsd, BASIS_POINTS_DIVISOR_BIGINT, maxAllowedLeverage),
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
function getPositionFeesAccruedUsd(marketInfo, isLong, sizeInUsd, periodSeconds) {
|
|
80
|
+
if (periodSeconds <= 0 || sizeInUsd <= 0n) {
|
|
81
|
+
return 0n;
|
|
82
|
+
}
|
|
83
|
+
const period = BigInt(periodSeconds);
|
|
84
|
+
const borrowingUsd = getBorrowingFeeRateUsd(marketInfo, isLong, sizeInUsd, period);
|
|
85
|
+
const fundingUsd = getFundingFeeRateUsd(marketInfo, isLong, sizeInUsd, period);
|
|
86
|
+
return borrowingUsd + (fundingUsd < 0n ? -fundingUsd : 0n);
|
|
87
|
+
}
|
|
88
|
+
export function getTwapIncreaseSequentialMarginState(p) {
|
|
89
|
+
const { collateralToken, isLong, numberOfParts, partDelaysSeconds, partGrossCollateralUsds, partSizeDeltaUsd, pendingFeesUsd, uiFeeFactor, minCollateralUsd, userReferralInfo, proDiscountFactor, } = p;
|
|
90
|
+
if (numberOfParts < 1 || partSizeDeltaUsd <= 0n || partGrossCollateralUsds.length < numberOfParts) {
|
|
91
|
+
return undefined;
|
|
92
|
+
}
|
|
93
|
+
const { indexToken } = p.marketInfo;
|
|
94
|
+
const indexPrice = getMarkPrice({ prices: indexToken.prices, isIncrease: true, isLong });
|
|
95
|
+
const collateralPrice = collateralToken.prices.minPrice;
|
|
96
|
+
if (indexPrice <= 0n || collateralPrice <= 0n) {
|
|
97
|
+
return undefined;
|
|
98
|
+
}
|
|
99
|
+
const partSizeDeltaInTokens = convertToTokenAmountForIncrease(partSizeDeltaUsd, indexToken.decimals, indexPrice, isLong);
|
|
100
|
+
if (partSizeDeltaInTokens <= 0n) {
|
|
101
|
+
return undefined;
|
|
102
|
+
}
|
|
103
|
+
const maxAllowedLeverage = BigInt(getMaxAllowedLeverage({
|
|
104
|
+
marketAddress: p.marketInfo.marketTokenAddress,
|
|
105
|
+
minCollateralFactor: p.marketInfo.minCollateralFactor,
|
|
106
|
+
minCollateralFactorForLiquidation: p.marketInfo.minCollateralFactorForLiquidation,
|
|
107
|
+
positionFeeFactorForBalanceWasNotImproved: p.marketInfo.positionFeeFactorForBalanceWasNotImproved,
|
|
108
|
+
}));
|
|
109
|
+
let marketInfo = p.marketInfo;
|
|
110
|
+
let position = p.existingPosition;
|
|
111
|
+
let contractMarginState;
|
|
112
|
+
let previousPartDelaySeconds = 0;
|
|
113
|
+
for (let partIndex = 0; partIndex < numberOfParts; partIndex++) {
|
|
114
|
+
const partDelaySeconds = Math.max(0, partDelaysSeconds[partIndex] ?? 0);
|
|
115
|
+
const accruedFeesUsd = position
|
|
116
|
+
? getPositionFeesAccruedUsd(marketInfo, isLong, position.sizeInUsd, partDelaySeconds - previousPartDelaySeconds)
|
|
117
|
+
: 0n;
|
|
118
|
+
previousPartDelaySeconds = partDelaySeconds;
|
|
119
|
+
const { balanceWasImproved } = getPriceImpactForPosition(marketInfo, partSizeDeltaUsd, isLong, {
|
|
120
|
+
fallbackToZero: true,
|
|
121
|
+
sizeDeltaInTokens: partSizeDeltaInTokens,
|
|
122
|
+
});
|
|
123
|
+
const { positionFeeUsd } = getPositionFee(marketInfo, partSizeDeltaUsd, balanceWasImproved, userReferralInfo, undefined, proDiscountFactor);
|
|
124
|
+
const uiFeeUsd = applyFactor(partSizeDeltaUsd, uiFeeFactor);
|
|
125
|
+
const settledFeesUsd = (partIndex === 0 ? pendingFeesUsd : 0n) + accruedFeesUsd;
|
|
126
|
+
const collateralDeltaUsd = partGrossCollateralUsds[partIndex] - positionFeeUsd - uiFeeUsd - settledFeesUsd;
|
|
127
|
+
const collateralDeltaAmount = convertToTokenAmount(collateralDeltaUsd, collateralToken.decimals, collateralPrice);
|
|
128
|
+
const resultingState = getIncreaseResultingPositionState({
|
|
129
|
+
marketInfo,
|
|
130
|
+
collateralToken,
|
|
131
|
+
isLong,
|
|
132
|
+
existingPosition: position,
|
|
133
|
+
sizeDeltaUsd: partSizeDeltaUsd,
|
|
134
|
+
sizeDeltaInTokens: partSizeDeltaInTokens,
|
|
135
|
+
collateralDeltaAmount,
|
|
136
|
+
minCollateralUsd,
|
|
137
|
+
userReferralInfo,
|
|
138
|
+
proDiscountFactor,
|
|
139
|
+
});
|
|
140
|
+
if (!resultingState) {
|
|
141
|
+
return undefined;
|
|
142
|
+
}
|
|
143
|
+
contractMarginState = resultingState.marginState;
|
|
144
|
+
const marginState = getMaxAllowedLeverageMarginState({
|
|
145
|
+
position: resultingState.position,
|
|
146
|
+
collateralToken,
|
|
147
|
+
maxAllowedLeverage,
|
|
148
|
+
minCollateralUsd,
|
|
149
|
+
}) ?? contractMarginState;
|
|
150
|
+
if (marginState.isLiquidatable) {
|
|
151
|
+
return {
|
|
152
|
+
numberOfParts,
|
|
153
|
+
failingPartIndex: partIndex,
|
|
154
|
+
isFailingPartEligibleNow: partDelaySeconds === 0,
|
|
155
|
+
marginState,
|
|
156
|
+
contractMarginState,
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
marketInfo = resultingState.marketInfo;
|
|
160
|
+
position = resultingState.position;
|
|
161
|
+
}
|
|
162
|
+
return {
|
|
163
|
+
numberOfParts,
|
|
164
|
+
failingPartIndex: undefined,
|
|
165
|
+
isFailingPartEligibleNow: false,
|
|
166
|
+
marginState: contractMarginState,
|
|
167
|
+
contractMarginState: contractMarginState,
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
export function getIsTwapIncreaseSequenceSafe(state) {
|
|
171
|
+
return state?.failingPartIndex === undefined;
|
|
172
|
+
}
|
|
@@ -11,11 +11,18 @@ export function getIsValidTwapParams(duration, numberOfParts) {
|
|
|
11
11
|
export function getTwapDurationInSeconds(duration) {
|
|
12
12
|
return duration.hours * 60 * 60 + duration.minutes * 60;
|
|
13
13
|
}
|
|
14
|
+
export function getTwapPartDelaySeconds(duration, numberOfParts, partIndex) {
|
|
15
|
+
if (numberOfParts <= 1) {
|
|
16
|
+
return 0;
|
|
17
|
+
}
|
|
18
|
+
return Math.floor((getTwapDurationInSeconds(duration) / (numberOfParts - 1)) * partIndex);
|
|
19
|
+
}
|
|
14
20
|
export function getTwapValidFromTime(duration, numberOfParts, partIndex) {
|
|
15
|
-
const durationMinutes = duration.hours * 60 + duration.minutes;
|
|
16
|
-
const durationMs = durationMinutes * 60;
|
|
17
21
|
const startTime = Math.ceil(Date.now() / 1000);
|
|
18
|
-
return BigInt(
|
|
22
|
+
return BigInt(startTime + getTwapPartDelaySeconds(duration, numberOfParts, partIndex));
|
|
23
|
+
}
|
|
24
|
+
export function getTwapPartDelaysSeconds(duration, numberOfParts) {
|
|
25
|
+
return Array.from({ length: numberOfParts }, (_, partIndex) => getTwapPartDelaySeconds(duration, numberOfParts, partIndex));
|
|
19
26
|
}
|
|
20
27
|
export function changeTwapNumberOfPartsValue(value) {
|
|
21
28
|
if (value < MIN_TWAP_NUMBER_OF_PARTS) {
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|