@gmx-io/sdk 2.3.1 → 2.4.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.
- 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/chains.js +13 -1
- package/build/cjs/src/configs/markets.js +40 -7
- package/build/cjs/src/configs/tokens.js +12 -7
- package/build/cjs/src/utils/__tests__/numbers.spec.js +24 -0
- package/build/cjs/src/utils/__tests__/parseError.spec.js +61 -0
- package/build/cjs/src/utils/errors/parseError.js +10 -0
- package/build/cjs/src/utils/errors/transactionsErrors.js +6 -0
- package/build/cjs/src/utils/markets/__tests__/multicall.spec.js +27 -0
- package/build/cjs/src/utils/markets/multicall.js +5 -7
- package/build/cjs/src/utils/numbers/utils.js +7 -1
- package/build/cjs/src/utils/orders/utils.js +8 -1
- package/build/cjs/src/utils/paxos/__tests__/api.spec.js +23 -3
- package/build/cjs/src/utils/paxos/api.js +6 -0
- package/build/cjs/src/utils/swap/preparedSwapData.js +6 -4
- package/build/cjs/src/utils/swap/swapPath.js +1 -1
- package/build/cjs/src/utils/trade/__tests__/decreaseMarginCheck.spec.js +224 -0
- package/build/cjs/src/utils/trade/__tests__/getMaxWithdrawAmount.spec.js +128 -9
- package/build/cjs/src/utils/trade/decrease.js +198 -33
- package/build/cjs/src/utils/trade/decreaseMarginCheck.js +157 -0
- package/build/cjs/src/utils/trade/increaseMarginCheck.js +27 -15
- package/build/cjs/src/utils/trade/index.js +1 -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/chains.js +11 -0
- package/build/esm/src/configs/markets.js +41 -8
- package/build/esm/src/configs/tokens.js +13 -8
- package/build/esm/src/utils/__tests__/numbers.spec.js +25 -1
- package/build/esm/src/utils/__tests__/parseError.spec.js +62 -1
- package/build/esm/src/utils/errors/parseError.js +11 -1
- package/build/esm/src/utils/errors/transactionsErrors.js +6 -0
- package/build/esm/src/utils/markets/__tests__/multicall.spec.js +25 -0
- package/build/esm/src/utils/markets/multicall.js +5 -7
- package/build/esm/src/utils/numbers/utils.js +5 -0
- package/build/esm/src/utils/orders/utils.js +6 -0
- package/build/esm/src/utils/paxos/__tests__/api.spec.js +23 -3
- package/build/esm/src/utils/paxos/api.js +6 -0
- package/build/esm/src/utils/swap/preparedSwapData.js +6 -4
- package/build/esm/src/utils/swap/swapPath.js +2 -2
- package/build/esm/src/utils/trade/__tests__/decreaseMarginCheck.spec.js +222 -0
- package/build/esm/src/utils/trade/__tests__/getMaxWithdrawAmount.spec.js +129 -10
- package/build/esm/src/utils/trade/decrease.js +195 -32
- package/build/esm/src/utils/trade/decreaseMarginCheck.js +152 -0
- package/build/esm/src/utils/trade/increaseMarginCheck.js +25 -14
- package/build/esm/src/utils/trade/index.js +1 -0
- package/build/tsconfig.tsbuildinfo +1 -1
- package/build/types/src/codegen/prebuilt/index.d.ts +364 -0
- package/build/types/src/configs/chains.d.ts +6 -2
- package/build/types/src/configs/markets.d.ts +4 -4
- package/build/types/src/utils/markets/__tests__/multicall.spec.d.ts +1 -0
- package/build/types/src/utils/numbers/utils.d.ts +1 -0
- package/build/types/src/utils/orderTransactions/api.d.ts +1 -0
- package/build/types/src/utils/orders/utils.d.ts +1 -0
- package/build/types/src/utils/paxos/types.d.ts +2 -0
- package/build/types/src/utils/trade/__tests__/decreaseMarginCheck.spec.d.ts +1 -0
- package/build/types/src/utils/trade/decrease.d.ts +18 -0
- package/build/types/src/utils/trade/decreaseMarginCheck.d.ts +52 -0
- package/build/types/src/utils/trade/increaseMarginCheck.d.ts +11 -1
- package/build/types/src/utils/trade/index.d.ts +1 -0
- package/build/types/src/utils/trade/types.d.ts +1 -0
- package/package.json +1 -1
|
@@ -332,6 +332,30 @@ const ONE_USD = 1000000000000000000000000000000n;
|
|
|
332
332
|
(0, vitest_1.expect)((0, numbers_1.formatAmountHuman)(ONE_USD * 1500000n, factors_1.USD_DECIMALS, false, 0)).toBe("2m");
|
|
333
333
|
});
|
|
334
334
|
});
|
|
335
|
+
(0, vitest_1.describe)("truncateToBalanceDisplayDecimals", () => {
|
|
336
|
+
(0, vitest_1.it)("rounds a stable amount down to the two decimals its balance is shown with", () => {
|
|
337
|
+
// 135.938928 USDC is shown as 135.94; the largest amount that can be typed back as shown is 135.93
|
|
338
|
+
(0, vitest_1.expect)((0, numbers_1.truncateToBalanceDisplayDecimals)(135938928n, 6, true)).toBe(135930000n);
|
|
339
|
+
(0, vitest_1.expect)((0, numbers_1.formatBalanceAmount)(135930000n, 6, undefined, { isStable: true })).toBe("135.93");
|
|
340
|
+
});
|
|
341
|
+
(0, vitest_1.it)("keeps an amount that is already at display precision", () => {
|
|
342
|
+
(0, vitest_1.expect)((0, numbers_1.truncateToBalanceDisplayDecimals)(135930000n, 6, true)).toBe(135930000n);
|
|
343
|
+
(0, vitest_1.expect)((0, numbers_1.truncateToBalanceDisplayDecimals)(0n, 6, true)).toBe(0n);
|
|
344
|
+
});
|
|
345
|
+
(0, vitest_1.it)("uses the finer precision small and non-stable amounts are shown with", () => {
|
|
346
|
+
// 0.0494382912 ETH is shown with 6 decimals
|
|
347
|
+
const amount = 49438291200000000n;
|
|
348
|
+
const truncated = (0, numbers_1.truncateToBalanceDisplayDecimals)(amount, 18);
|
|
349
|
+
(0, vitest_1.expect)(truncated).toBe(49438000000000000n);
|
|
350
|
+
(0, vitest_1.expect)((0, numbers_1.formatBalanceAmount)(truncated, 18)).toBe("0.049438");
|
|
351
|
+
});
|
|
352
|
+
vitest_1.it.each([135938928n, 99999999n, 1005000n, 104999n, 9999n])("never exceeds the amount and always reads back as displayed (%s)", (amount) => {
|
|
353
|
+
const truncated = (0, numbers_1.truncateToBalanceDisplayDecimals)(amount, 6, true);
|
|
354
|
+
const displayed = (0, numbers_1.formatBalanceAmount)(truncated, 6, undefined, { isStable: true, showZero: true });
|
|
355
|
+
(0, vitest_1.expect)(truncated).toBeLessThanOrEqual(amount);
|
|
356
|
+
(0, vitest_1.expect)((0, numbers_1.parseValue)(displayed.replace(/,/g, ""), 6)).toBe(truncated);
|
|
357
|
+
});
|
|
358
|
+
});
|
|
335
359
|
(0, vitest_1.describe)("formatBalanceAmount", () => {
|
|
336
360
|
const NBSP = "\u00a0";
|
|
337
361
|
(0, vitest_1.it)("should display balance amount", () => {
|
|
@@ -115,6 +115,54 @@ const transactionsErrors_1 = require("../errors/transactionsErrors");
|
|
|
115
115
|
errorGroup: "Txn Error: USER_DENIED",
|
|
116
116
|
}));
|
|
117
117
|
});
|
|
118
|
+
vitest_1.it.each([
|
|
119
|
+
["The user rejected the request"],
|
|
120
|
+
["Request rejected"],
|
|
121
|
+
["MetaMask Typed Message Signature: User denied message signature."],
|
|
122
|
+
])("should treat EIP-1193 code 4001 as a user rejection: %s", (message) => {
|
|
123
|
+
// ethers v6 ACTION_REJECTED keeps the wallet error in info.error
|
|
124
|
+
const error = {
|
|
125
|
+
code: "ACTION_REJECTED",
|
|
126
|
+
message: "user rejected action",
|
|
127
|
+
info: { error: { code: 4001, message } },
|
|
128
|
+
};
|
|
129
|
+
(0, vitest_1.expect)((0, errors_1.parseError)(error)).toEqual(vitest_1.expect.objectContaining({
|
|
130
|
+
txErrorType: transactionsErrors_1.TxErrorType.UserDenied,
|
|
131
|
+
isUserError: true,
|
|
132
|
+
isUserRejectedError: true,
|
|
133
|
+
}));
|
|
134
|
+
});
|
|
135
|
+
(0, vitest_1.it)("should trust the ethers ACTION_REJECTED code when the wallet error has another code", () => {
|
|
136
|
+
const error = {
|
|
137
|
+
code: "ACTION_REJECTED",
|
|
138
|
+
message: "user rejected action",
|
|
139
|
+
info: { error: { code: -32603, message: "User denied message signature" } },
|
|
140
|
+
};
|
|
141
|
+
(0, vitest_1.expect)((0, errors_1.parseError)(error)).toEqual(vitest_1.expect.objectContaining({
|
|
142
|
+
errorMessage: "User denied message signature",
|
|
143
|
+
txErrorType: transactionsErrors_1.TxErrorType.UserDenied,
|
|
144
|
+
isUserRejectedError: true,
|
|
145
|
+
errorGroup: "Txn Error: USER_DENIED",
|
|
146
|
+
}));
|
|
147
|
+
});
|
|
148
|
+
vitest_1.it.each([
|
|
149
|
+
["EIP-1193", 4001],
|
|
150
|
+
["WalletConnect CAIP-25", 5000],
|
|
151
|
+
])("should treat a raw %s rejection code with an unknown message as a user rejection", (_standard, code) => {
|
|
152
|
+
const error = { code, message: "Request rejected" };
|
|
153
|
+
(0, vitest_1.expect)((0, errors_1.parseError)(error)).toEqual(vitest_1.expect.objectContaining({ txErrorType: transactionsErrors_1.TxErrorType.UserDenied, isUserRejectedError: true }));
|
|
154
|
+
});
|
|
155
|
+
(0, vitest_1.it)("should keep message patterns ahead of code 4001", () => {
|
|
156
|
+
const error = { code: 4001, message: "Request expired" };
|
|
157
|
+
(0, vitest_1.expect)((0, errors_1.parseError)(error)).toEqual(vitest_1.expect.objectContaining({ txErrorType: transactionsErrors_1.TxErrorType.Expired, isUserRejectedError: false }));
|
|
158
|
+
});
|
|
159
|
+
(0, vitest_1.it)("should not treat other EIP-1193 provider codes as a user rejection", () => {
|
|
160
|
+
const error = {
|
|
161
|
+
code: 4100,
|
|
162
|
+
message: "The requested account and/or method has not been authorized by the user.",
|
|
163
|
+
};
|
|
164
|
+
(0, vitest_1.expect)((0, errors_1.parseError)(error)).toEqual(vitest_1.expect.objectContaining({ isUserRejectedError: false }));
|
|
165
|
+
});
|
|
118
166
|
(0, vitest_1.it)("should handle ethers v6 insufficient funds error", () => {
|
|
119
167
|
const error = {
|
|
120
168
|
info: {
|
|
@@ -301,6 +349,19 @@ const transactionsErrors_1 = require("../errors/transactionsErrors");
|
|
|
301
349
|
}));
|
|
302
350
|
});
|
|
303
351
|
});
|
|
352
|
+
(0, vitest_1.describe)("custom errors", () => {
|
|
353
|
+
(0, vitest_1.it)("reads the contract error that the order simulation rethrows as a CustomError", () => {
|
|
354
|
+
const args = { estimatedRemainingCollateralUsd: 90n };
|
|
355
|
+
const error = (0, errors_1.extendError)(new errors_1.CustomError({ name: "UnableToWithdrawCollateral", message: "{}", args }), {
|
|
356
|
+
errorContext: "simulation",
|
|
357
|
+
});
|
|
358
|
+
(0, vitest_1.expect)((0, errors_1.parseError)(error)).toEqual(vitest_1.expect.objectContaining({
|
|
359
|
+
contractError: "UnableToWithdrawCollateral",
|
|
360
|
+
contractErrorArgs: args,
|
|
361
|
+
errorContext: "simulation",
|
|
362
|
+
}));
|
|
363
|
+
});
|
|
364
|
+
});
|
|
304
365
|
});
|
|
305
366
|
(0, vitest_1.describe)("decodeSimulationErrorFromViemError", () => {
|
|
306
367
|
(0, vitest_1.it)("decodes the nested SimulationRouter sentinel from ExternalCallFailed", () => {
|
|
@@ -95,10 +95,20 @@ function parseError(error, errorDepth = 0) {
|
|
|
95
95
|
isUserError = type ? (0, transactionsErrors_1.getIsUserError)(type) : false;
|
|
96
96
|
isUserRejectedError = type ? (0, transactionsErrors_1.getIsUserRejectedError)(type) : false;
|
|
97
97
|
}
|
|
98
|
+
// ethers already classified it as a user rejection, whatever the wallet error looks like
|
|
99
|
+
if (typeof error === "object" && error?.code === "ACTION_REJECTED") {
|
|
100
|
+
txErrorType = transactionsErrors_1.TxErrorType.UserDenied;
|
|
101
|
+
isUserError = true;
|
|
102
|
+
isUserRejectedError = true;
|
|
103
|
+
}
|
|
98
104
|
}
|
|
99
105
|
catch (e) {
|
|
100
106
|
//
|
|
101
107
|
}
|
|
108
|
+
if (isCustomError(error)) {
|
|
109
|
+
contractError = error.name;
|
|
110
|
+
contractErrorArgs = error.args;
|
|
111
|
+
}
|
|
102
112
|
if (!contractError) {
|
|
103
113
|
const errorData = (error && typeof error === "object" ? extractErrorDataFromViemError(error) : undefined) ??
|
|
104
114
|
(0, transactionsErrors_1.extractDataFromError)(errorMessage) ??
|
|
@@ -60,6 +60,9 @@ const TX_ERROR_PATTERNS = {
|
|
|
60
60
|
{ msg: "couldn't connect to the network" },
|
|
61
61
|
],
|
|
62
62
|
};
|
|
63
|
+
// EIP-1193 and WalletConnect (CAIP-25) user rejection codes, as viem maps them; ethers' BrowserProvider maps only 4001.
|
|
64
|
+
// Checked after the patterns so they only classify otherwise unknown errors
|
|
65
|
+
const USER_REJECTED_REQUEST_CODES = [4001, 5000];
|
|
63
66
|
var CustomErrorName;
|
|
64
67
|
(function (CustomErrorName) {
|
|
65
68
|
CustomErrorName["DisabledMarket"] = "DisabledMarket";
|
|
@@ -149,6 +152,9 @@ function extractTxnError(ex) {
|
|
|
149
152
|
}
|
|
150
153
|
}
|
|
151
154
|
}
|
|
155
|
+
if (typeof code === "number" && USER_REJECTED_REQUEST_CODES.includes(code)) {
|
|
156
|
+
return [message, TxErrorType.UserDenied, ex.data];
|
|
157
|
+
}
|
|
152
158
|
return [message, null, ex.data];
|
|
153
159
|
}
|
|
154
160
|
exports.extractTxnError = extractTxnError;
|
|
@@ -0,0 +1,27 @@
|
|
|
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 multicall_1 = require("../multicall");
|
|
6
|
+
const ETH_USDC_MARKET = "0x70d95587d40A2caf56bd97485aB3Eec10Bee6336";
|
|
7
|
+
const marketsData = {
|
|
8
|
+
[ETH_USDC_MARKET]: {
|
|
9
|
+
marketTokenAddress: ETH_USDC_MARKET,
|
|
10
|
+
indexTokenAddress: "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",
|
|
11
|
+
longTokenAddress: "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",
|
|
12
|
+
shortTokenAddress: "0xaf88d065e77c8cC2239327C5EDb3A432268e5831",
|
|
13
|
+
isSameCollaterals: false,
|
|
14
|
+
isSpotOnly: false,
|
|
15
|
+
name: "ETH/USD [WETH-USDC]",
|
|
16
|
+
data: "",
|
|
17
|
+
},
|
|
18
|
+
};
|
|
19
|
+
(0, vitest_1.describe)("buildMarketsConfigsRequest", () => {
|
|
20
|
+
(0, vitest_1.it)("hashes the keys of a market without pre-built keys", async () => {
|
|
21
|
+
// The keys of this market are pre-built for Arbitrum only, so on Avalanche they are hashed at runtime
|
|
22
|
+
const params = { marketsAddresses: [ETH_USDC_MARKET], marketsData };
|
|
23
|
+
const prebuiltRequest = await (0, multicall_1.buildMarketsConfigsRequest)(chains_1.ARBITRUM, params);
|
|
24
|
+
const hashedRequest = await (0, multicall_1.buildMarketsConfigsRequest)(chains_1.AVALANCHE, params);
|
|
25
|
+
(0, vitest_1.expect)(hashedRequest[`${ETH_USDC_MARKET}-dataStore`].calls).toEqual(prebuiltRequest[`${ETH_USDC_MARKET}-dataStore`].calls);
|
|
26
|
+
});
|
|
27
|
+
});
|
|
@@ -7,6 +7,7 @@ const dataStore_1 = require("../../configs/dataStore");
|
|
|
7
7
|
const hash_1 = require("../hash");
|
|
8
8
|
const markets_1 = require("./");
|
|
9
9
|
const objects_1 = require("../objects");
|
|
10
|
+
const hashKeys_1 = require("./hashKeys");
|
|
10
11
|
function buildMarketsRiskValuesRequest(chainId, markets) {
|
|
11
12
|
const dataStoreAddress = (0, contracts_1.getContract)(chainId, "DataStore");
|
|
12
13
|
return markets.reduce((request, market) => {
|
|
@@ -150,10 +151,7 @@ async function buildMarketsValuesRequest(chainId, { marketsAddresses, marketsDat
|
|
|
150
151
|
},
|
|
151
152
|
},
|
|
152
153
|
};
|
|
153
|
-
const prebuiltHashedKeys = prebuilt_1.HASHED_MARKET_VALUES_KEYS[chainId]?.[marketAddress];
|
|
154
|
-
if (!prebuiltHashedKeys) {
|
|
155
|
-
throw new Error(`No pre-built hashed market keys found for the market ${marketAddress}.`);
|
|
156
|
-
}
|
|
154
|
+
const prebuiltHashedKeys = prebuilt_1.HASHED_MARKET_VALUES_KEYS[chainId]?.[marketAddress] ?? (0, hashKeys_1.hashMarketValuesKeys)(market);
|
|
157
155
|
request[`${marketAddress}-dataStore`] = {
|
|
158
156
|
contractAddress: dataStoreAddress,
|
|
159
157
|
abiId: "DataStore",
|
|
@@ -278,10 +276,10 @@ async function buildMarketsConfigsRequest(chainId, { marketsAddresses, marketsDa
|
|
|
278
276
|
const request = {};
|
|
279
277
|
for (const marketAddress of marketsAddresses || []) {
|
|
280
278
|
const market = (0, objects_1.getByKey)(marketsData, marketAddress);
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
throw new Error(`No pre-built hashed config keys found for the market ${marketAddress}.`);
|
|
279
|
+
if (!market) {
|
|
280
|
+
throw new Error(`No market data found for the market ${marketAddress}.`);
|
|
284
281
|
}
|
|
282
|
+
const prebuiltHashedKeys = prebuilt_1.HASHED_MARKET_CONFIG_KEYS[chainId]?.[marketAddress] ?? (0, hashKeys_1.hashMarketConfigKeys)(market);
|
|
285
283
|
request[`${marketAddress}-dataStore`] = {
|
|
286
284
|
contractAddress: dataStoreAddress,
|
|
287
285
|
abiId: "DataStore",
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.formatAmountHumanParts = exports.formatNumberHuman = exports.formatNumberHumanParts = exports.formatPercentageDisplay = exports.formatUsdPrice = exports.formatUsdPriceParts = exports.formatRatePercentage = exports.formatTokenAmountWithUsd = exports.formatTokenAmountWithUsdParts = exports.formatTokenAmount = exports.formatPercentage = exports.formatDeltaUsd = exports.formatDeltaUsdParts = exports.formatBigUsd = exports.formatBigUsdParts = exports.formatUsd = exports.formatUsdParts = exports.adjustForDecimals = exports.bigintToNumber = exports.trimZeroDecimals = exports.numberToBigint = exports.applyFactor = exports.roundsToZero = exports.roundUpMagnitudeDivision = exports.formatPriceImpactBps = exports.formatBasisPoints = exports.getBasisPoints = exports.basisPointsToFloat = exports.toBigInt = exports.expandDecimals = exports.safeDivide = exports.isNonZero = exports.TRIGGER_PREFIX_BELOW = exports.TRIGGER_PREFIX_ABOVE = exports.PERCENT_PRECISION_DECIMALS = exports.isUint256 = exports.parseUint256DecimalString = exports.MaxInt256 = exports.MaxUint256 = exports.BN_NEGATIVE_ONE = exports.BN_ONE = exports.BN_ZERO = exports.FLOAT_PRECISION_SQRT = exports.FLOAT_PRECISION_SQRT_DECIMALS = exports.PRECISION = exports.PRECISION_DECIMALS = exports.BASIS_POINTS_DECIMALS = exports.BASIS_POINTS_DIVISOR_BIGINT = exports.BASIS_POINTS_DIVISOR = exports.USD_DECIMALS = void 0;
|
|
4
|
-
exports.absDiffBps = exports.clamp = exports.calculateDisplayDecimals = exports.deserializeBigIntsInObject = exports.serializeBigIntsInObject = exports.removeTrailingZeros = exports.maxbigint = exports.minBigNumber = exports.roundBigIntToDecimals = exports.roundToOrder = exports.roundToTwoDecimals = exports.roundUpDivision = exports.parseValue = exports.toBigNumberWithDecimals = exports.roundWithDecimals = exports.getPlusOrMinusSymbol = exports.padDecimals = exports.limitDecimals = exports.getLimitedDisplay = exports.formatAmountFree = exports.formatArrayAmount = exports.formatKeyAmount = exports.formatAmount = exports.numberWithCommas = exports.numberWithCommasParts = exports.formatFactor = exports.formatBalanceAmount = exports.formatAmountHuman = void 0;
|
|
4
|
+
exports.absDiffBps = exports.clamp = exports.calculateDisplayDecimals = exports.deserializeBigIntsInObject = exports.serializeBigIntsInObject = exports.removeTrailingZeros = exports.maxbigint = exports.minBigNumber = exports.roundBigIntToDecimals = exports.roundToOrder = exports.roundToTwoDecimals = exports.roundUpDivision = exports.parseValue = exports.toBigNumberWithDecimals = exports.roundWithDecimals = exports.getPlusOrMinusSymbol = exports.padDecimals = exports.limitDecimals = exports.getLimitedDisplay = exports.formatAmountFree = exports.formatArrayAmount = exports.formatKeyAmount = exports.formatAmount = exports.numberWithCommas = exports.numberWithCommasParts = exports.formatFactor = exports.truncateToBalanceDisplayDecimals = exports.formatBalanceAmount = exports.formatAmountHuman = void 0;
|
|
5
5
|
const viem_1 = require("viem");
|
|
6
6
|
const bigmath_1 = require("../bigmath");
|
|
7
7
|
const parts_1 = require("./parts");
|
|
@@ -432,6 +432,12 @@ function formatBalanceAmount(amount, tokenDecimals, tokenSymbol, { showZero = fa
|
|
|
432
432
|
return `${sign}${value}`;
|
|
433
433
|
}
|
|
434
434
|
exports.formatBalanceAmount = formatBalanceAmount;
|
|
435
|
+
function truncateToBalanceDisplayDecimals(amount, tokenDecimals, isStable = false) {
|
|
436
|
+
const displayDecimals = calculateDisplayDecimals(amount, tokenDecimals, 1, isStable);
|
|
437
|
+
const displayStep = expandDecimals(1, Math.max(tokenDecimals - displayDecimals, 0));
|
|
438
|
+
return amount - (amount % displayStep);
|
|
439
|
+
}
|
|
440
|
+
exports.truncateToBalanceDisplayDecimals = truncateToBalanceDisplayDecimals;
|
|
435
441
|
function formatFactor(factor) {
|
|
436
442
|
if (factor == 0n) {
|
|
437
443
|
return "0";
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.getOrderTradeboxKey = exports.isOrderForPositionByData = exports.isOrderForPosition = exports.isVisibleOrder = exports.getOrderInfo = exports.getOrderKeys = exports.isPositionOrder = exports.isSwapOrder = exports.isTwapPositionOrder = exports.isTwapSwapOrder = exports.isTwapOrder = exports.isStopIncreaseOrderType = exports.isLimitIncreaseOrderType = exports.isLimitDecreaseOrderType = exports.isStopLossOrderType = exports.isLiquidationOrderType = exports.isLimitSwapOrderType = exports.isSwapOrderType = exports.isIncreaseOrderType = exports.isDecreaseOrderType = exports.isTriggerDecreaseOrderType = exports.isLimitOrderType = exports.isMarketOrderType = void 0;
|
|
3
|
+
exports.getOrderTradeboxKey = exports.getOrderPositionKey = exports.isOrderForPositionByData = exports.isOrderForPosition = exports.isVisibleOrder = exports.getOrderInfo = exports.getOrderKeys = exports.isPositionOrder = exports.isSwapOrder = exports.isTwapPositionOrder = exports.isTwapSwapOrder = exports.isTwapOrder = exports.isStopIncreaseOrderType = exports.isLimitIncreaseOrderType = exports.isLimitDecreaseOrderType = exports.isStopLossOrderType = exports.isLiquidationOrderType = exports.isLimitSwapOrderType = exports.isSwapOrderType = exports.isIncreaseOrderType = exports.isDecreaseOrderType = exports.isTriggerDecreaseOrderType = exports.isLimitOrderType = exports.isMarketOrderType = void 0;
|
|
4
4
|
const factors_1 = require("../../configs/factors");
|
|
5
5
|
const bigmath_1 = require("../bigmath");
|
|
6
6
|
const objects_1 = require("../objects");
|
|
@@ -245,6 +245,13 @@ function isOrderForPositionByData(order, { account, marketAddress, collateralAdd
|
|
|
245
245
|
return isMatch;
|
|
246
246
|
}
|
|
247
247
|
exports.isOrderForPositionByData = isOrderForPositionByData;
|
|
248
|
+
function getOrderPositionKey(order) {
|
|
249
|
+
const collateralAddress = isDecreaseOrderType(order.orderType)
|
|
250
|
+
? order.initialCollateralTokenAddress
|
|
251
|
+
: order.targetCollateralToken.address;
|
|
252
|
+
return (0, positions_1.getPositionKey)(order.account, order.marketAddress, collateralAddress, order.isLong);
|
|
253
|
+
}
|
|
254
|
+
exports.getOrderPositionKey = getOrderPositionKey;
|
|
248
255
|
function getOrderTradeboxKey(order) {
|
|
249
256
|
if (isPositionOrder(order) || isTwapPositionOrder(order)) {
|
|
250
257
|
return `POSITION-${(0, positions_1.getPositionKey)(order.account, order.marketAddress, order.initialCollateralTokenAddress, order.isLong)}`;
|
|
@@ -74,12 +74,32 @@ const RAW_ORDER = {
|
|
|
74
74
|
await (0, api_1.fetchApiTransitRoutes)({ api }, { feeTier: "zeroFee" });
|
|
75
75
|
(0, vitest_1.expect)(calls).toEqual([{ path: "/v1/paxos/transit/routes", query: { filter: undefined, feeTier: "zeroFee" } }]);
|
|
76
76
|
});
|
|
77
|
-
(0, vitest_1.it)("parses fee tier capacity as bigint", async () => {
|
|
77
|
+
(0, vitest_1.it)("parses the fee tier with capacity as bigint and the reopen time in seconds", async () => {
|
|
78
78
|
const calls = [];
|
|
79
|
-
const api = createApi(calls, {
|
|
79
|
+
const api = createApi(calls, {
|
|
80
|
+
feeTier: "zeroFee",
|
|
81
|
+
zeroFeeCapacity: "250000000000",
|
|
82
|
+
isZeroFeeAvailable: false,
|
|
83
|
+
zeroFeeExpectedReopenAt: "2026-10-26T13:00:00Z",
|
|
84
|
+
});
|
|
80
85
|
const result = await (0, api_1.fetchApiTransitFeeTier)({ api }, { userAddress: USER });
|
|
81
86
|
(0, vitest_1.expect)(calls).toEqual([{ path: "/v1/paxos/transit/fee-tier", query: { userAddress: USER } }]);
|
|
82
|
-
(0, vitest_1.expect)(result).toEqual({
|
|
87
|
+
(0, vitest_1.expect)(result).toEqual({
|
|
88
|
+
feeTier: "zeroFee",
|
|
89
|
+
zeroFeeCapacity: 250000000000n,
|
|
90
|
+
isZeroFeeAvailable: false,
|
|
91
|
+
zeroFeeExpectedReopenAt: Date.UTC(2026, 9, 26, 13) / 1000,
|
|
92
|
+
});
|
|
93
|
+
});
|
|
94
|
+
vitest_1.it.each([undefined, null, "soon"])("drops a reopen time of %s", async (zeroFeeExpectedReopenAt) => {
|
|
95
|
+
const api = createApi([], {
|
|
96
|
+
feeTier: "zeroFee",
|
|
97
|
+
zeroFeeCapacity: "0",
|
|
98
|
+
isZeroFeeAvailable: false,
|
|
99
|
+
zeroFeeExpectedReopenAt,
|
|
100
|
+
});
|
|
101
|
+
const result = await (0, api_1.fetchApiTransitFeeTier)({ api }, { userAddress: USER });
|
|
102
|
+
(0, vitest_1.expect)(result.zeroFeeExpectedReopenAt).toBeUndefined();
|
|
83
103
|
});
|
|
84
104
|
(0, vitest_1.it)("sends quote amounts as strings and parses fees", async () => {
|
|
85
105
|
const calls = [];
|
|
@@ -12,9 +12,15 @@ async function fetchApiTransitFeeTier(ctx, params) {
|
|
|
12
12
|
const raw = await ctx.api.fetchJson("/v1/paxos/transit/fee-tier", {
|
|
13
13
|
query: { userAddress: params.userAddress },
|
|
14
14
|
});
|
|
15
|
+
const zeroFeeExpectedReopenAtMs = Date.parse(raw.zeroFeeExpectedReopenAt);
|
|
16
|
+
const zeroFeeExpectedReopenAt = Number.isFinite(zeroFeeExpectedReopenAtMs)
|
|
17
|
+
? Math.floor(zeroFeeExpectedReopenAtMs / 1000)
|
|
18
|
+
: undefined;
|
|
15
19
|
return {
|
|
16
20
|
feeTier: raw.feeTier,
|
|
17
21
|
zeroFeeCapacity: BigInt(raw.zeroFeeCapacity),
|
|
22
|
+
isZeroFeeAvailable: raw.isZeroFeeAvailable,
|
|
23
|
+
zeroFeeExpectedReopenAt,
|
|
18
24
|
};
|
|
19
25
|
}
|
|
20
26
|
exports.fetchApiTransitFeeTier = fetchApiTransitFeeTier;
|
|
@@ -1,27 +1,29 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.TOKEN_SWAP_PATHS = exports.REACHABLE_TOKENS = exports.MARKETS_ADJACENCY_GRAPH = void 0;
|
|
4
|
+
const chains_1 = require("../../configs/chains");
|
|
4
5
|
const markets_1 = require("../../configs/markets");
|
|
5
6
|
const buildMarketsAdjacencyGraph_1 = require("./buildMarketsAdjacencyGraph");
|
|
6
7
|
const findReachableTokens_1 = require("./findReachableTokens");
|
|
7
8
|
const findSwapPathsBetweenTokens_1 = require("./findSwapPathsBetweenTokens");
|
|
9
|
+
const SWAP_MARKETS = { ...markets_1.MARKETS, [chains_1.SOLANA_NETWORK_ID]: {} };
|
|
8
10
|
const MARKETS_ADJACENCY_GRAPH = {};
|
|
9
11
|
exports.MARKETS_ADJACENCY_GRAPH = MARKETS_ADJACENCY_GRAPH;
|
|
10
|
-
for (const chainId in
|
|
11
|
-
const markets =
|
|
12
|
+
for (const chainId in SWAP_MARKETS) {
|
|
13
|
+
const markets = SWAP_MARKETS[chainId];
|
|
12
14
|
const chainGraph = (0, buildMarketsAdjacencyGraph_1.buildMarketsAdjacencyGraph)(markets);
|
|
13
15
|
MARKETS_ADJACENCY_GRAPH[chainId] = chainGraph;
|
|
14
16
|
}
|
|
15
17
|
const TOKEN_SWAP_PATHS = {};
|
|
16
18
|
exports.TOKEN_SWAP_PATHS = TOKEN_SWAP_PATHS;
|
|
17
|
-
for (const chainId in
|
|
19
|
+
for (const chainId in SWAP_MARKETS) {
|
|
18
20
|
const chainGraph = MARKETS_ADJACENCY_GRAPH[chainId];
|
|
19
21
|
const chainSwapPaths = (0, findSwapPathsBetweenTokens_1.findSwapPathsBetweenTokens)(chainGraph);
|
|
20
22
|
TOKEN_SWAP_PATHS[chainId] = chainSwapPaths;
|
|
21
23
|
}
|
|
22
24
|
const REACHABLE_TOKENS = {};
|
|
23
25
|
exports.REACHABLE_TOKENS = REACHABLE_TOKENS;
|
|
24
|
-
for (const chainId in
|
|
26
|
+
for (const chainId in SWAP_MARKETS) {
|
|
25
27
|
const chainGraph = MARKETS_ADJACENCY_GRAPH[chainId];
|
|
26
28
|
const chainReachableTokens = (0, findReachableTokens_1.findReachableTokens)(chainGraph);
|
|
27
29
|
REACHABLE_TOKENS[chainId] = chainReachableTokens;
|
|
@@ -24,7 +24,7 @@ function buildMarketAdjacencyGraph(chainId, disabledMarkets) {
|
|
|
24
24
|
return cachedGraph;
|
|
25
25
|
}
|
|
26
26
|
const disabledMarketAddresses = disabledMarkets;
|
|
27
|
-
const strippedMarkets = Object.fromEntries(Object.entries(markets_1.
|
|
27
|
+
const strippedMarkets = Object.fromEntries(Object.entries((0, markets_1.getMarketsByChainId)(chainId)).filter(([marketAddress]) => !disabledMarketAddresses.includes(marketAddress)));
|
|
28
28
|
const graph = (0, buildMarketsAdjacencyGraph_1.buildMarketsAdjacencyGraph)(strippedMarkets);
|
|
29
29
|
DEBUG_MARKET_ADJACENCY_GRAPH_CACHE.set(cacheKey, graph);
|
|
30
30
|
return graph;
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
const vitest_1 = require("vitest");
|
|
4
|
+
const mock_1 = require("../../../test/mock");
|
|
5
|
+
const numbers_1 = require("../../numbers");
|
|
6
|
+
const tokens_1 = require("../../tokens");
|
|
7
|
+
const decreaseMarginCheck_1 = require("../decreaseMarginCheck");
|
|
8
|
+
const increaseMarginCheck_1 = require("../increaseMarginCheck");
|
|
9
|
+
const tokensData = (0, mock_1.mockTokensData)();
|
|
10
|
+
const usdc = tokensData.USDC;
|
|
11
|
+
/** 1% min collateral factor → 100x, 0.5% for liquidation. Fees and impact off unless a test needs them. */
|
|
12
|
+
function buildMarket(overrides = {}) {
|
|
13
|
+
return (0, mock_1.mockMarketsInfoData)(tokensData, ["BTC-BTC-USDC"], {
|
|
14
|
+
"BTC-BTC-USDC": {
|
|
15
|
+
minCollateralFactor: (0, numbers_1.expandDecimals)(1, 28),
|
|
16
|
+
minCollateralFactorForLiquidation: (0, numbers_1.expandDecimals)(5, 27),
|
|
17
|
+
minCollateralFactorForOpenInterestLong: 0n,
|
|
18
|
+
minCollateralFactorForOpenInterestShort: 0n,
|
|
19
|
+
positionFeeFactorForBalanceWasImproved: 0n,
|
|
20
|
+
positionFeeFactorForBalanceWasNotImproved: 0n,
|
|
21
|
+
positionImpactFactorPositive: 0n,
|
|
22
|
+
positionImpactFactorNegative: 0n,
|
|
23
|
+
maxPositionImpactFactorPositive: 0n,
|
|
24
|
+
maxPositionImpactFactorNegative: 0n,
|
|
25
|
+
maxPositionImpactFactorForLiquidations: 0n,
|
|
26
|
+
longInterestUsd: (0, numbers_1.expandDecimals)(1000000, numbers_1.USD_DECIMALS),
|
|
27
|
+
shortInterestUsd: (0, numbers_1.expandDecimals)(1000000, numbers_1.USD_DECIMALS),
|
|
28
|
+
longInterestInTokens: (0, numbers_1.expandDecimals)(50, 8),
|
|
29
|
+
shortInterestInTokens: (0, numbers_1.expandDecimals)(50, 8),
|
|
30
|
+
...overrides,
|
|
31
|
+
},
|
|
32
|
+
})["BTC-BTC-USDC"];
|
|
33
|
+
}
|
|
34
|
+
/** USD value with 30 decimals, accepting fractional amounts. */
|
|
35
|
+
function usd(value) {
|
|
36
|
+
return (BigInt(Math.round(value * 100)) * (0, numbers_1.expandDecimals)(1, numbers_1.USD_DECIMALS)) / 100n;
|
|
37
|
+
}
|
|
38
|
+
function usdcAmount(value) {
|
|
39
|
+
return (0, tokens_1.convertToTokenAmount)(usd(value), usdc.decimals, usdc.prices.minPrice);
|
|
40
|
+
}
|
|
41
|
+
/** tokens of a 10 000 USD long that are worth `value` at the oracle price */
|
|
42
|
+
function sizeInTokensWorth(value) {
|
|
43
|
+
return (0, tokens_1.convertToTokenAmount)(usd(value), tokensData.BTC.decimals, tokensData.BTC.prices.minPrice);
|
|
44
|
+
}
|
|
45
|
+
const LOSING_2000 = sizeInTokensWorth(8000);
|
|
46
|
+
const FLAT = sizeInTokensWorth(10000);
|
|
47
|
+
const PROFITABLE_2000 = sizeInTokensWorth(12000);
|
|
48
|
+
/**
|
|
49
|
+
* A 10 000 USD long. `closeShare` closes that share of it and pays `realizedLossUsd` out of the collateral,
|
|
50
|
+
* the way `getDecreasePositionAmounts` reports it in `payedRemainingCollateralAmount`.
|
|
51
|
+
*/
|
|
52
|
+
function params({ position, closeShare = 0, realizedLossUsd = 0, ...overrides } = {}) {
|
|
53
|
+
const fullPosition = {
|
|
54
|
+
sizeInUsd: usd(10000),
|
|
55
|
+
sizeInTokens: LOSING_2000,
|
|
56
|
+
collateralAmount: usdcAmount(2060),
|
|
57
|
+
pendingImpactAmount: 0n,
|
|
58
|
+
...position,
|
|
59
|
+
};
|
|
60
|
+
const closeBps = BigInt(Math.round(closeShare * 10000));
|
|
61
|
+
return {
|
|
62
|
+
marketInfo: buildMarket(),
|
|
63
|
+
collateralToken: usdc,
|
|
64
|
+
isLong: true,
|
|
65
|
+
position: fullPosition,
|
|
66
|
+
sizeDeltaUsd: (fullPosition.sizeInUsd * closeBps) / 10000n,
|
|
67
|
+
sizeDeltaInTokens: (fullPosition.sizeInTokens * closeBps) / 10000n,
|
|
68
|
+
collateralDeltaAmount: 0n,
|
|
69
|
+
payedRemainingCollateralAmount: usdcAmount(realizedLossUsd),
|
|
70
|
+
priceImpactDiffUsd: 0n,
|
|
71
|
+
minCollateralUsd: usd(1),
|
|
72
|
+
minPositionSizeUsd: usd(1),
|
|
73
|
+
userReferralInfo: undefined,
|
|
74
|
+
...overrides,
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
(0, vitest_1.describe)("getDecreaseResultingPositionMarginState — partial close", () => {
|
|
78
|
+
// collateral 2 060 with a 2 000 loss leaves 60 of margin: under the 1% regular minimum of the full
|
|
79
|
+
// position (100), above its 0.5% liquidation minimum (50)
|
|
80
|
+
(0, vitest_1.it)("rejects a partial close whose remainder stays above max leverage", () => {
|
|
81
|
+
const state = (0, decreaseMarginCheck_1.getDecreaseResultingPositionMarginState)(params({ closeShare: 0.25, realizedLossUsd: 500 }));
|
|
82
|
+
(0, vitest_1.expect)(state?.isLiquidatable).toBe(true);
|
|
83
|
+
(0, vitest_1.expect)(state?.reason).toBe(increaseMarginCheck_1.PositionMarginFailureReason.MinCollateralForLeverage);
|
|
84
|
+
(0, vitest_1.expect)(state?.remainingCollateralUsd).toBe(usd(60));
|
|
85
|
+
(0, vitest_1.expect)(state?.minCollateralUsdForLeverage).toBe(usd(75));
|
|
86
|
+
});
|
|
87
|
+
(0, vitest_1.it)("passes when the remaining margin equals the leverage-based minimum", () => {
|
|
88
|
+
const state = (0, decreaseMarginCheck_1.getDecreaseResultingPositionMarginState)(params({ closeShare: 0.4, realizedLossUsd: 800 }));
|
|
89
|
+
(0, vitest_1.expect)(state?.remainingCollateralUsd).toBe(usd(60));
|
|
90
|
+
(0, vitest_1.expect)(state?.minCollateralUsdForLeverage).toBe(usd(60));
|
|
91
|
+
(0, vitest_1.expect)(state?.isLiquidatable).toBe(false);
|
|
92
|
+
});
|
|
93
|
+
(0, vitest_1.it)("passes once a larger part is closed", () => {
|
|
94
|
+
const state = (0, decreaseMarginCheck_1.getDecreaseResultingPositionMarginState)(params({ closeShare: 0.5, realizedLossUsd: 1000 }));
|
|
95
|
+
(0, vitest_1.expect)(state?.isLiquidatable).toBe(false);
|
|
96
|
+
});
|
|
97
|
+
(0, vitest_1.it)("never validates a full close", () => {
|
|
98
|
+
(0, vitest_1.expect)((0, decreaseMarginCheck_1.getDecreaseResultingPositionMarginState)(params({ closeShare: 1, realizedLossUsd: 2000 }))).toBeUndefined();
|
|
99
|
+
});
|
|
100
|
+
(0, vitest_1.it)("counts the costs paid out of the collateral against the remainder", () => {
|
|
101
|
+
// closing 50% passes with 60 of margin against a 50 minimum; 10.01 of fees on the closed part tips it over
|
|
102
|
+
const state = (0, decreaseMarginCheck_1.getDecreaseResultingPositionMarginState)(params({ closeShare: 0.5, realizedLossUsd: 1010.01 }));
|
|
103
|
+
(0, vitest_1.expect)(state?.reason).toBe(increaseMarginCheck_1.PositionMarginFailureReason.MinCollateralForLeverage);
|
|
104
|
+
});
|
|
105
|
+
(0, vitest_1.it)("charges the closing fee of the remainder", () => {
|
|
106
|
+
// 0.2% of the remaining 5 000 = 10 → 60 - 10 = 50, exactly the minimum; one more cent of loss fails
|
|
107
|
+
const marketInfo = buildMarket({
|
|
108
|
+
positionFeeFactorForBalanceWasImproved: (0, numbers_1.expandDecimals)(2, 27),
|
|
109
|
+
positionFeeFactorForBalanceWasNotImproved: (0, numbers_1.expandDecimals)(2, 27),
|
|
110
|
+
});
|
|
111
|
+
(0, vitest_1.expect)((0, decreaseMarginCheck_1.getDecreaseResultingPositionMarginState)(params({ marketInfo, closeShare: 0.5, realizedLossUsd: 1000 }))
|
|
112
|
+
?.isLiquidatable).toBe(false);
|
|
113
|
+
(0, vitest_1.expect)((0, decreaseMarginCheck_1.getDecreaseResultingPositionMarginState)(params({ marketInfo, closeShare: 0.5, realizedLossUsd: 1000.01 }))
|
|
114
|
+
?.reason).toBe(increaseMarginCheck_1.PositionMarginFailureReason.MinCollateralForLeverage);
|
|
115
|
+
});
|
|
116
|
+
(0, vitest_1.it)("does not apply the fixed minimum to the remainder", () => {
|
|
117
|
+
// remainder: 60 of margin, 50 leverage minimum; a 61 USD fixed minimum is only checked after an increase
|
|
118
|
+
const state = (0, decreaseMarginCheck_1.getDecreaseResultingPositionMarginState)(params({
|
|
119
|
+
closeShare: 0.5,
|
|
120
|
+
realizedLossUsd: 1000,
|
|
121
|
+
position: { collateralAmount: usdcAmount(2061) },
|
|
122
|
+
minCollateralUsd: usd(61),
|
|
123
|
+
marketInfo: buildMarket({
|
|
124
|
+
positionFeeFactorForBalanceWasImproved: (0, numbers_1.expandDecimals)(2, 26),
|
|
125
|
+
positionFeeFactorForBalanceWasNotImproved: (0, numbers_1.expandDecimals)(2, 26),
|
|
126
|
+
}),
|
|
127
|
+
}));
|
|
128
|
+
(0, vitest_1.expect)(state?.remainingCollateralUsd).toBe(usd(60));
|
|
129
|
+
(0, vitest_1.expect)(state?.isLiquidatable).toBe(false);
|
|
130
|
+
});
|
|
131
|
+
(0, vitest_1.it)("returns a non-positive remaining margin as its own reason", () => {
|
|
132
|
+
const state = (0, decreaseMarginCheck_1.getDecreaseResultingPositionMarginState)(params({ closeShare: 0.25, realizedLossUsd: 500, position: { collateralAmount: usdcAmount(2002) } }));
|
|
133
|
+
// 2 of margin: over the 1 USD fixed minimum, so the contract keeps the close partial
|
|
134
|
+
(0, vitest_1.expect)(state?.reason).toBe(increaseMarginCheck_1.PositionMarginFailureReason.MinCollateralForLeverage);
|
|
135
|
+
const underwater = (0, decreaseMarginCheck_1.getDecreaseResultingPositionMarginState)(params({
|
|
136
|
+
closeShare: 0.25,
|
|
137
|
+
realizedLossUsd: 503,
|
|
138
|
+
position: { collateralAmount: usdcAmount(2002) },
|
|
139
|
+
}));
|
|
140
|
+
(0, vitest_1.expect)(underwater?.reason).toBe(increaseMarginCheck_1.PositionMarginFailureReason.NonPositiveRemainingMargin);
|
|
141
|
+
});
|
|
142
|
+
(0, vitest_1.it)("validates nothing when the contract turns the order into a full close", () => {
|
|
143
|
+
// estimated remainder: 2 000.5 - 500 of collateral and -1 500 of pnl → 0.5, under the 1 USD fixed minimum
|
|
144
|
+
(0, vitest_1.expect)((0, decreaseMarginCheck_1.getDecreaseResultingPositionMarginState)(params({ closeShare: 0.25, realizedLossUsd: 500, position: { collateralAmount: usdcAmount(2000.5) } }))).toBeUndefined();
|
|
145
|
+
(0, vitest_1.expect)((0, decreaseMarginCheck_1.getDecreaseResultingPositionMarginState)(params({ closeShare: 0.5, realizedLossUsd: 1000, minPositionSizeUsd: usd(5001) }))).toBeUndefined();
|
|
146
|
+
});
|
|
147
|
+
});
|
|
148
|
+
(0, vitest_1.describe)("getDecreaseResultingPositionMarginState — keep-leverage collateral withdrawal", () => {
|
|
149
|
+
const flat = { sizeInTokens: FLAT, collateralAmount: usdcAmount(200) };
|
|
150
|
+
(0, vitest_1.it)("withdraws the collateral when the preliminary gate passes", () => {
|
|
151
|
+
// remaining size 5 000 → 50 required without pnl; 200 - 150 = 50
|
|
152
|
+
const state = (0, decreaseMarginCheck_1.getDecreaseResultingPositionMarginState)(params({ closeShare: 0.5, position: flat, collateralDeltaAmount: usdcAmount(150) }));
|
|
153
|
+
(0, vitest_1.expect)(state?.remainingCollateralUsd).toBe(usd(50));
|
|
154
|
+
(0, vitest_1.expect)(state?.isLiquidatable).toBe(false);
|
|
155
|
+
});
|
|
156
|
+
(0, vitest_1.it)("keeps the collateral in the position when the preliminary gate fails", () => {
|
|
157
|
+
const state = (0, decreaseMarginCheck_1.getDecreaseResultingPositionMarginState)(params({ closeShare: 0.5, position: flat, collateralDeltaAmount: usdcAmount(150.01) }));
|
|
158
|
+
(0, vitest_1.expect)(state?.remainingCollateralUsd).toBe(usd(200));
|
|
159
|
+
(0, vitest_1.expect)(state?.isLiquidatable).toBe(false);
|
|
160
|
+
});
|
|
161
|
+
(0, vitest_1.it)("trims the withdrawal by the negative impact past the cap, as the contract does", () => {
|
|
162
|
+
// 30 of the close's negative impact is past the cap: it is paid out of the collateral and the contract
|
|
163
|
+
// withdraws 150 - 30, so 200 - 30 - 120 = 50 stays against the 50 required
|
|
164
|
+
const state = (0, decreaseMarginCheck_1.getDecreaseResultingPositionMarginState)(params({
|
|
165
|
+
closeShare: 0.5,
|
|
166
|
+
position: flat,
|
|
167
|
+
collateralDeltaAmount: usdcAmount(150),
|
|
168
|
+
payedRemainingCollateralAmount: usdcAmount(30),
|
|
169
|
+
priceImpactDiffUsd: usd(30),
|
|
170
|
+
}));
|
|
171
|
+
(0, vitest_1.expect)(state?.remainingCollateralUsd).toBe(usd(50));
|
|
172
|
+
(0, vitest_1.expect)(state?.isLiquidatable).toBe(false);
|
|
173
|
+
});
|
|
174
|
+
(0, vitest_1.it)("evaluates the open-interest factor on the open interest left after the close", () => {
|
|
175
|
+
// 2% at 1 000 000 of open interest; closing 5 000 leaves 995 000 → 1.99% → 99.5 on the remaining 5 000
|
|
176
|
+
const marketInfo = buildMarket({ minCollateralFactorForOpenInterestLong: (0, numbers_1.expandDecimals)(2, 22) });
|
|
177
|
+
(0, vitest_1.expect)((0, decreaseMarginCheck_1.getDecreaseResultingPositionMarginState)(params({ marketInfo, closeShare: 0.5, position: flat, collateralDeltaAmount: usdcAmount(100.5) }))?.remainingCollateralUsd).toBe(usd(99.5));
|
|
178
|
+
(0, vitest_1.expect)((0, decreaseMarginCheck_1.getDecreaseResultingPositionMarginState)(params({ marketInfo, closeShare: 0.5, position: flat, collateralDeltaAmount: usdcAmount(100.51) }))?.remainingCollateralUsd).toBe(usd(200));
|
|
179
|
+
});
|
|
180
|
+
});
|
|
181
|
+
(0, vitest_1.describe)("getDecreaseResultingPositionMarginState — withdrawal", () => {
|
|
182
|
+
(0, vitest_1.it)("passes up to the leverage-based minimum with pnl and fails past it", () => {
|
|
183
|
+
// 2 200 of collateral and a 2 000 loss: 200 of margin against a 100 minimum
|
|
184
|
+
const position = { collateralAmount: usdcAmount(2200) };
|
|
185
|
+
const atThreshold = (0, decreaseMarginCheck_1.getDecreaseResultingPositionMarginState)(params({ position, collateralDeltaAmount: usdcAmount(100) }));
|
|
186
|
+
const pastThreshold = (0, decreaseMarginCheck_1.getDecreaseResultingPositionMarginState)(params({ position, collateralDeltaAmount: usdcAmount(100.01) }));
|
|
187
|
+
(0, vitest_1.expect)(atThreshold?.remainingCollateralUsd).toBe(usd(100));
|
|
188
|
+
(0, vitest_1.expect)(atThreshold?.isLiquidatable).toBe(false);
|
|
189
|
+
(0, vitest_1.expect)(pastThreshold?.reason).toBe(increaseMarginCheck_1.PositionMarginFailureReason.MinCollateralForLeverage);
|
|
190
|
+
});
|
|
191
|
+
(0, vitest_1.it)("uses the regular factor where the liquidation one would still pass", () => {
|
|
192
|
+
// 60 of margin left: above the 0.5% liquidation minimum (50), under the 1% regular one (100)
|
|
193
|
+
const state = (0, decreaseMarginCheck_1.getDecreaseResultingPositionMarginState)(params({ position: { collateralAmount: usdcAmount(2200) }, collateralDeltaAmount: usdcAmount(140) }));
|
|
194
|
+
(0, vitest_1.expect)(state?.remainingCollateralUsd).toBe(usd(60));
|
|
195
|
+
(0, vitest_1.expect)(state?.minCollateralUsdForLeverage).toBe(usd(100));
|
|
196
|
+
(0, vitest_1.expect)(state?.isLiquidatable).toBe(true);
|
|
197
|
+
});
|
|
198
|
+
(0, vitest_1.it)("settles pending fees out of the collateral before the final validation", () => {
|
|
199
|
+
const state = (0, decreaseMarginCheck_1.getDecreaseResultingPositionMarginState)(params({
|
|
200
|
+
position: { collateralAmount: usdcAmount(2200) },
|
|
201
|
+
collateralDeltaAmount: usdcAmount(95),
|
|
202
|
+
payedRemainingCollateralAmount: usdcAmount(5.01),
|
|
203
|
+
}));
|
|
204
|
+
(0, vitest_1.expect)(state?.reason).toBe(increaseMarginCheck_1.PositionMarginFailureReason.MinCollateralForLeverage);
|
|
205
|
+
});
|
|
206
|
+
(0, vitest_1.it)("reverts at the preliminary gate, which ignores pnl", () => {
|
|
207
|
+
// profitable by 2 000, but 150 - 50.01 of collateral is under the 100 the gate requires without pnl
|
|
208
|
+
const position = { sizeInTokens: PROFITABLE_2000, collateralAmount: usdcAmount(150) };
|
|
209
|
+
(0, vitest_1.expect)((0, decreaseMarginCheck_1.getDecreaseResultingPositionMarginState)(params({ position, collateralDeltaAmount: usdcAmount(50) }))
|
|
210
|
+
?.isLiquidatable).toBe(false);
|
|
211
|
+
const state = (0, decreaseMarginCheck_1.getDecreaseResultingPositionMarginState)(params({ position, collateralDeltaAmount: usdcAmount(50.01) }));
|
|
212
|
+
(0, vitest_1.expect)(state?.reason).toBe(increaseMarginCheck_1.PositionMarginFailureReason.UnableToWithdrawCollateral);
|
|
213
|
+
(0, vitest_1.expect)(state?.remainingCollateralUsd).toBe(usd(99.99));
|
|
214
|
+
(0, vitest_1.expect)(state?.minCollateralUsdForLeverage).toBe(usd(100));
|
|
215
|
+
});
|
|
216
|
+
(0, vitest_1.it)("reverts at the preliminary gate when collateral with pnl falls under the fixed minimum", () => {
|
|
217
|
+
const state = (0, decreaseMarginCheck_1.getDecreaseResultingPositionMarginState)(params({
|
|
218
|
+
position: { collateralAmount: usdcAmount(2200) },
|
|
219
|
+
collateralDeltaAmount: usdcAmount(50),
|
|
220
|
+
minCollateralUsd: usd(150.01),
|
|
221
|
+
}));
|
|
222
|
+
(0, vitest_1.expect)(state?.reason).toBe(increaseMarginCheck_1.PositionMarginFailureReason.UnableToWithdrawCollateral);
|
|
223
|
+
});
|
|
224
|
+
});
|