@gmx-io/sdk 2.9.2 → 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/cjs/src/abis/RatioVesterReader.js +45 -0
- package/build/cjs/src/abis/index.js +2 -0
- package/build/cjs/src/clients/v1/modules/oracle.js +15 -0
- package/build/cjs/src/clients/v1/modules/oracle.spec.js +20 -0
- package/build/cjs/src/clients/v1/modules/orders/helpers.js +16 -12
- package/build/cjs/src/clients/v1/modules/orders/helpers.spec.js +21 -0
- package/build/cjs/src/clients/v1/modules/orders/orders.js +4 -0
- package/build/cjs/src/clients/v1/modules/orders/utils.js +1 -0
- package/build/cjs/src/clients/v2/__tests__/subaccount.spec.js +74 -17
- package/build/cjs/src/clients/v2/__tests__/subaccountLifecycle.spec.js +1 -1
- package/build/cjs/src/clients/v2/__tests__/testUtil.js +14 -2
- package/build/cjs/src/clients/v2/index.js +28 -7
- package/build/cjs/src/clients/v2/solana.spec.js +81 -4
- package/build/cjs/src/codegen/prebuilt/hashedKinkModelMarketRatesKeys.json +48 -0
- package/build/cjs/src/codegen/prebuilt/hashedMarketConfigKeys.json +782 -0
- package/build/cjs/src/codegen/prebuilt/hashedMarketValuesKeys.json +90 -0
- package/build/cjs/src/configs/contracts.js +10 -0
- package/build/cjs/src/configs/dataStore.js +22 -4
- package/build/cjs/src/configs/express.js +1 -2
- package/build/cjs/src/configs/markets.js +42 -0
- package/build/cjs/src/configs/tokens.js +2 -0
- package/build/cjs/src/test/mockCrossFetch.js +1 -0
- package/build/cjs/src/utils/__tests__/fees.spec.js +52 -0
- package/build/cjs/src/utils/__tests__/gmsolUnits.spec.js +101 -0
- package/build/cjs/src/utils/__tests__/orderTransactions/batchUtils.spec.js +66 -0
- package/build/cjs/src/utils/__tests__/orderTransactions/decreaseOrders.spec.js +6 -6
- package/build/cjs/src/utils/__tests__/orderTransactions/exchangeRouterMulticall.spec.js +40 -0
- package/build/cjs/src/utils/__tests__/orderTransactions/updateOrder.spec.js +4 -2
- package/build/cjs/src/utils/__tests__/tokens.spec.js +63 -0
- package/build/cjs/src/utils/errors/transactionsErrors.js +6 -0
- package/build/cjs/src/utils/fees/index.js +5 -0
- package/build/cjs/src/utils/fees/priceImpact.js +39 -6
- package/build/cjs/src/utils/gmsol/__tests__/fixtures/nativeMath.json +3171 -0
- package/build/cjs/src/utils/gmsol/__tests__/nativeMath.spec.js +213 -0
- package/build/cjs/src/utils/gmsol/constants.js +4 -1
- package/build/cjs/src/utils/gmsol/fees.js +19 -0
- package/build/cjs/src/utils/gmsol/index.js +29 -1
- package/build/cjs/src/utils/gmsol/markets.js +206 -0
- package/build/cjs/src/utils/gmsol/numbers.js +55 -1
- package/build/cjs/src/utils/gmsol/positions.js +152 -0
- package/build/cjs/src/utils/gmsol/units.js +106 -0
- package/build/cjs/src/utils/http/http.js +21 -25
- package/build/cjs/src/utils/http/httpFallback.js +3 -3
- package/build/cjs/src/utils/http/validation.js +9 -1
- package/build/cjs/src/utils/markets/hashKeys.js +8 -0
- package/build/cjs/src/utils/markets/multicall.js +10 -0
- package/build/cjs/src/utils/markets/utils.js +2 -0
- package/build/cjs/src/utils/multichain/__tests__/api.spec.js +49 -0
- package/build/cjs/src/utils/multichain/api.js +29 -2
- package/build/cjs/src/utils/orderTransactions/utils.js +63 -5
- package/build/cjs/src/utils/orders/api.js +66 -3
- package/build/cjs/src/utils/positions/__tests__/liquidationImpact.spec.js +44 -0
- package/build/cjs/src/utils/positions/__tests__/liquidationPrice.spec.js +159 -2
- package/build/cjs/src/utils/positions/__tests__/trackingCollateral.spec.js +395 -0
- package/build/cjs/src/utils/positions/api.js +4 -0
- package/build/cjs/src/utils/positions/utils.js +119 -44
- package/build/cjs/src/utils/prices/api.js +2 -2
- package/build/cjs/src/utils/referrals/api.js +5 -4
- package/build/cjs/src/utils/subaccount/generateSubaccount.js +14 -14
- package/build/cjs/src/utils/subaccount/sdkClient.js +40 -19
- package/build/cjs/src/utils/tokens/utils.js +23 -7
- package/build/cjs/src/utils/trade/__tests__/decrease.spec.js +152 -0
- package/build/cjs/src/utils/trade/__tests__/gmsolTradeMath.spec.js +43 -0
- package/build/cjs/src/utils/trade/decrease.js +113 -33
- package/build/cjs/src/utils/trade/decreaseMarginCheck.js +38 -2
- package/build/cjs/src/utils/trade/decreaseOutputs.js +20 -5
- package/build/cjs/src/utils/trade/increase.js +30 -11
- package/build/cjs/src/utils/trade/increaseMarginCheck.js +14 -35
- package/build/esm/src/abis/RatioVesterReader.js +43 -0
- package/build/esm/src/abis/index.js +2 -0
- package/build/esm/src/clients/v1/modules/oracle.js +15 -0
- package/build/esm/src/clients/v1/modules/oracle.spec.js +18 -0
- package/build/esm/src/clients/v1/modules/orders/helpers.js +17 -13
- package/build/esm/src/clients/v1/modules/orders/helpers.spec.js +21 -0
- package/build/esm/src/clients/v1/modules/orders/orders.js +4 -0
- package/build/esm/src/clients/v1/modules/orders/utils.js +1 -0
- package/build/esm/src/clients/v2/__tests__/subaccount.spec.js +74 -17
- package/build/esm/src/clients/v2/__tests__/subaccountLifecycle.spec.js +2 -2
- package/build/esm/src/clients/v2/__tests__/testUtil.js +13 -2
- package/build/esm/src/clients/v2/index.js +29 -8
- package/build/esm/src/clients/v2/solana.spec.js +79 -2
- package/build/esm/src/codegen/prebuilt/hashedKinkModelMarketRatesKeys.json +48 -0
- package/build/esm/src/codegen/prebuilt/hashedMarketConfigKeys.json +782 -0
- package/build/esm/src/codegen/prebuilt/hashedMarketValuesKeys.json +90 -0
- package/build/esm/src/configs/contracts.js +10 -0
- package/build/esm/src/configs/dataStore.js +14 -0
- package/build/esm/src/configs/express.js +0 -1
- package/build/esm/src/configs/markets.js +42 -0
- package/build/esm/src/configs/tokens.js +2 -0
- package/build/esm/src/test/mockCrossFetch.js +1 -0
- package/build/esm/src/utils/__tests__/fees.spec.js +53 -1
- package/build/esm/src/utils/__tests__/gmsolUnits.spec.js +99 -0
- package/build/esm/src/utils/__tests__/orderTransactions/batchUtils.spec.js +68 -2
- package/build/esm/src/utils/__tests__/orderTransactions/decreaseOrders.spec.js +6 -6
- package/build/esm/src/utils/__tests__/orderTransactions/exchangeRouterMulticall.spec.js +40 -0
- package/build/esm/src/utils/__tests__/orderTransactions/updateOrder.spec.js +5 -3
- package/build/esm/src/utils/__tests__/tokens.spec.js +64 -1
- package/build/esm/src/utils/errors/transactionsErrors.js +6 -0
- package/build/esm/src/utils/fees/index.js +5 -0
- package/build/esm/src/utils/fees/priceImpact.js +36 -5
- package/build/esm/src/utils/gmsol/__tests__/fixtures/nativeMath.json +3171 -0
- package/build/esm/src/utils/gmsol/__tests__/nativeMath.spec.js +208 -0
- package/build/esm/src/utils/gmsol/constants.js +3 -0
- package/build/esm/src/utils/gmsol/fees.js +15 -0
- package/build/esm/src/utils/gmsol/index.js +6 -2
- package/build/esm/src/utils/gmsol/markets.js +193 -0
- package/build/esm/src/utils/gmsol/numbers.js +55 -1
- package/build/esm/src/utils/gmsol/positions.js +148 -0
- package/build/esm/src/utils/gmsol/units.js +97 -0
- package/build/esm/src/utils/http/http.js +21 -25
- package/build/esm/src/utils/http/httpFallback.js +3 -3
- package/build/esm/src/utils/http/validation.js +7 -0
- package/build/esm/src/utils/markets/hashKeys.js +9 -1
- package/build/esm/src/utils/markets/multicall.js +10 -0
- package/build/esm/src/utils/markets/utils.js +2 -0
- package/build/esm/src/utils/multichain/__tests__/api.spec.js +46 -0
- package/build/esm/src/utils/multichain/api.js +29 -2
- package/build/esm/src/utils/orderTransactions/utils.js +59 -5
- package/build/esm/src/utils/orders/api.js +64 -2
- package/build/esm/src/utils/positions/__tests__/liquidationImpact.spec.js +42 -0
- package/build/esm/src/utils/positions/__tests__/liquidationPrice.spec.js +161 -4
- package/build/esm/src/utils/positions/__tests__/trackingCollateral.spec.js +393 -0
- package/build/esm/src/utils/positions/api.js +4 -0
- package/build/esm/src/utils/positions/utils.js +115 -44
- package/build/esm/src/utils/prices/api.js +2 -2
- package/build/esm/src/utils/referrals/api.js +6 -5
- package/build/esm/src/utils/subaccount/generateSubaccount.js +13 -14
- package/build/esm/src/utils/subaccount/sdkClient.js +38 -19
- package/build/esm/src/utils/tokens/utils.js +20 -6
- package/build/esm/src/utils/trade/__tests__/decrease.spec.js +150 -0
- package/build/esm/src/utils/trade/__tests__/gmsolTradeMath.spec.js +43 -0
- package/build/esm/src/utils/trade/decrease.js +115 -35
- package/build/esm/src/utils/trade/decreaseMarginCheck.js +37 -2
- package/build/esm/src/utils/trade/decreaseOutputs.js +19 -5
- package/build/esm/src/utils/trade/increase.js +32 -13
- package/build/esm/src/utils/trade/increaseMarginCheck.js +18 -39
- package/build/tsconfig.tsbuildinfo +1 -1
- package/build/types/src/abis/RatioVesterReader.d.ts +74 -0
- package/build/types/src/abis/index.d.ts +73 -0
- package/build/types/src/clients/v1/modules/oracle.d.ts +6 -1
- package/build/types/src/clients/v1/modules/oracle.spec.d.ts +1 -0
- package/build/types/src/clients/v2/__tests__/testUtil.d.ts +1 -0
- package/build/types/src/clients/v2/index.d.ts +26 -5
- package/build/types/src/codegen/prebuilt/index.d.ts +1045 -125
- package/build/types/src/configs/contracts.d.ts +10 -0
- package/build/types/src/configs/dataStore.d.ts +8 -0
- package/build/types/src/configs/express.d.ts +0 -1
- package/build/types/src/utils/__tests__/gmsolUnits.spec.d.ts +1 -0
- package/build/types/src/utils/errors/parseError.d.ts +1 -1
- package/build/types/src/utils/errors/transactionsErrors.d.ts +6 -0
- package/build/types/src/utils/fees/priceImpact.d.ts +10 -0
- package/build/types/src/utils/gmsol/__tests__/nativeMath.spec.d.ts +1 -0
- package/build/types/src/utils/gmsol/constants.d.ts +4 -0
- package/build/types/src/utils/gmsol/fees.d.ts +6 -0
- package/build/types/src/utils/gmsol/index.d.ts +7 -3
- package/build/types/src/utils/gmsol/markets.d.ts +49 -0
- package/build/types/src/utils/gmsol/numbers.d.ts +10 -0
- package/build/types/src/utils/gmsol/positions.d.ts +7 -0
- package/build/types/src/utils/gmsol/types.d.ts +96 -0
- package/build/types/src/utils/gmsol/units.d.ts +53 -0
- package/build/types/src/utils/http/types.d.ts +1 -0
- package/build/types/src/utils/http/validation.d.ts +1 -0
- package/build/types/src/utils/markets/types.d.ts +5 -2
- package/build/types/src/utils/multichain/api.d.ts +4 -1
- package/build/types/src/utils/orderTransactions/utils.d.ts +19 -4
- package/build/types/src/utils/orders/api.d.ts +2 -1
- package/build/types/src/utils/orders/types.d.ts +24 -0
- package/build/types/src/utils/positions/__tests__/liquidationImpact.spec.d.ts +1 -0
- package/build/types/src/utils/positions/__tests__/trackingCollateral.spec.d.ts +1 -0
- package/build/types/src/utils/positions/types.d.ts +2 -0
- package/build/types/src/utils/positions/utils.d.ts +30 -0
- package/build/types/src/utils/prices/api.d.ts +2 -0
- package/build/types/src/utils/referrals/types.d.ts +4 -0
- package/build/types/src/utils/subaccount/generateSubaccount.d.ts +9 -4
- package/build/types/src/utils/subaccount/sdkClient.d.ts +7 -1
- package/build/types/src/utils/subaccount/types.d.ts +2 -0
- package/build/types/src/utils/tokens/types.d.ts +1 -0
- package/build/types/src/utils/tokens/utils.d.ts +6 -0
- package/build/types/src/utils/trade/__tests__/decrease.spec.d.ts +1 -0
- package/build/types/src/utils/trade/decrease.d.ts +3 -0
- package/build/types/src/utils/trade/decreaseMarginCheck.d.ts +11 -0
- package/build/types/src/utils/trade/decreaseOutputs.d.ts +7 -2
- package/build/types/src/utils/trade/increaseMarginCheck.d.ts +1 -0
- package/package.json +10 -1
|
@@ -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
|
-
|
|
82
|
-
const
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
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 (
|
|
88
|
-
|
|
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 =
|
|
109
|
+
let priceImpactDeltaUsd = exitImpactUsd + pendingImpactUsd;
|
|
99
110
|
if (priceImpactDeltaUsd > 0) {
|
|
100
|
-
|
|
111
|
+
priceImpactDeltaUsd = 0n;
|
|
101
112
|
}
|
|
102
|
-
if (priceImpactDeltaUsd <
|
|
103
|
-
|
|
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
|
|
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
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
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
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
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
|
|
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
|
}
|
|
@@ -1,20 +1,16 @@
|
|
|
1
1
|
import cryptoJs from "crypto-js";
|
|
2
|
-
import {
|
|
3
|
-
import { privateKeyToAccount } from "viem/accounts";
|
|
4
|
-
import { SUBACCOUNT_MESSAGE } from "../../configs/express";
|
|
2
|
+
import { generatePrivateKey } from "viem/accounts";
|
|
5
3
|
import { PrivateKeySigner } from "../signer";
|
|
6
|
-
export
|
|
7
|
-
const
|
|
8
|
-
|
|
9
|
-
const account = privateKeyToAccount(pk);
|
|
10
|
-
const signer = new PrivateKeySigner(pk);
|
|
11
|
-
const encryptedPrivateKey = cryptoJs.AES.encrypt(pk, mainSigner.address).toString();
|
|
12
|
-
return {
|
|
13
|
-
address: account.address,
|
|
14
|
-
signer,
|
|
15
|
-
privateKey: encryptedPrivateKey,
|
|
16
|
-
};
|
|
4
|
+
export function getSubaccountFromPrivateKey(privateKey) {
|
|
5
|
+
const signer = new PrivateKeySigner(privateKey);
|
|
6
|
+
return { address: signer.address, signer, privateKey };
|
|
17
7
|
}
|
|
8
|
+
export function generateSubaccount() {
|
|
9
|
+
return getSubaccountFromPrivateKey(generatePrivateKey());
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* @deprecated Only reads configs stored by SDK versions below 3.0.0.
|
|
13
|
+
*/
|
|
18
14
|
export function decryptSubaccountPrivateKey(encryptedPrivateKey, mainAccountAddress) {
|
|
19
15
|
const decrypted = cryptoJs.AES.decrypt(encryptedPrivateKey, mainAccountAddress).toString(cryptoJs.enc.Utf8);
|
|
20
16
|
if (!decrypted) {
|
|
@@ -22,6 +18,9 @@ export function decryptSubaccountPrivateKey(encryptedPrivateKey, mainAccountAddr
|
|
|
22
18
|
}
|
|
23
19
|
return decrypted;
|
|
24
20
|
}
|
|
21
|
+
/**
|
|
22
|
+
* @deprecated Only reads configs stored by SDK versions below 3.0.0.
|
|
23
|
+
*/
|
|
25
24
|
export function createSubaccountSignerFromConfig(encryptedPrivateKey, mainAccountAddress) {
|
|
26
25
|
const pk = decryptSubaccountPrivateKey(encryptedPrivateKey, mainAccountAddress);
|
|
27
26
|
return new PrivateKeySigner(pk);
|
|
@@ -2,10 +2,10 @@ import { DEFAULT_SUBACCOUNT_EXPIRY_DURATION, DEFAULT_SUBACCOUNT_MAX_ALLOWED_COUN
|
|
|
2
2
|
import { prepareOrder as prepareOrderRaw, signPreparedOrder, submitOrder as submitOrderRaw, } from "../orderTransactions/api";
|
|
3
3
|
import { nowInSeconds } from "../time";
|
|
4
4
|
import { fetchSubaccountStatus, prepareSubaccountApproval, signSubaccountApproval } from "./api";
|
|
5
|
-
import { generateSubaccount } from "./generateSubaccount";
|
|
5
|
+
import { generateSubaccount, getSubaccountFromPrivateKey } from "./generateSubaccount";
|
|
6
6
|
import { getEmptySubaccountApproval } from "./getEmptySubaccountApproval";
|
|
7
7
|
import { isEmptySubaccountApproval, isSameSubaccountApproval, isSubaccountApprovalExpired, isSubaccountApprovalNonceExpired, isSubaccountApprovalRevoked, isSubaccountApprovalSynced, isSubaccountStatusUsable, parseSubaccountStatus, shouldRefreshExplicitSubaccountApproval, toSignedSubaccountApproval, } from "./state";
|
|
8
|
-
const
|
|
8
|
+
const sdkSubaccountKeys = new WeakMap();
|
|
9
9
|
const MAX_PREPARED_SUBACCOUNT_APPROVALS = 100;
|
|
10
10
|
const SUBACCOUNT_STATUS_CACHE_TTL_MS = 15000;
|
|
11
11
|
const LOW_SUBACCOUNT_ACTIONS_REFRESH_THRESHOLD = 1n;
|
|
@@ -18,10 +18,10 @@ const SUBMITTED_ORDER_STATUSES = new Set([
|
|
|
18
18
|
]);
|
|
19
19
|
const FINAL_ORDER_STATUSES = new Set(["created", "executed"]);
|
|
20
20
|
function hasSdkSubaccountSigner(owner) {
|
|
21
|
-
return
|
|
21
|
+
return sdkSubaccountKeys.has(owner);
|
|
22
22
|
}
|
|
23
23
|
function getSdkSubaccountSigner(owner) {
|
|
24
|
-
return
|
|
24
|
+
return sdkSubaccountKeys.get(owner)?.signer;
|
|
25
25
|
}
|
|
26
26
|
function isSameAddress(a, b) {
|
|
27
27
|
return a !== undefined && b !== undefined && a.toLowerCase() === b.toLowerCase();
|
|
@@ -35,8 +35,14 @@ function throwSubaccountAccountMismatch(subaccount, account) {
|
|
|
35
35
|
function throwSubaccountAddressMismatch(source, provided, expected) {
|
|
36
36
|
throw new Error(`${source} ${provided} does not match generated subaccount ${expected}.`);
|
|
37
37
|
}
|
|
38
|
+
function assertNoOtherSdkSubaccountKey(client, address) {
|
|
39
|
+
const heldAddress = sdkSubaccountKeys.get(client.owner)?.address;
|
|
40
|
+
if (heldAddress && !isSameAddress(heldAddress, address)) {
|
|
41
|
+
throw new Error(`Subaccount ${heldAddress} is already set. Call clearSubaccount() before setting another key.`);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
38
44
|
function resetSdkSubaccount(client) {
|
|
39
|
-
|
|
45
|
+
sdkSubaccountKeys.delete(client.owner);
|
|
40
46
|
client.preparedSubaccountApprovals.clear();
|
|
41
47
|
client.setSubaccount(undefined);
|
|
42
48
|
}
|
|
@@ -115,15 +121,28 @@ export function getSdkSubaccountApprovalMessage(client) {
|
|
|
115
121
|
}
|
|
116
122
|
return getUsableSubaccountApproval(client);
|
|
117
123
|
}
|
|
118
|
-
|
|
124
|
+
function setSdkSubaccount(client, subaccount, account) {
|
|
119
125
|
client.preparedSubaccountApprovals.clear();
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
return
|
|
126
|
+
sdkSubaccountKeys.set(client.owner, subaccount);
|
|
127
|
+
client.setSubaccount({ account, address: subaccount.address });
|
|
128
|
+
return subaccount.address;
|
|
129
|
+
}
|
|
130
|
+
export function generateSdkSubaccount(client, account) {
|
|
131
|
+
assertNoOtherSdkSubaccountKey(client);
|
|
132
|
+
return setSdkSubaccount(client, generateSubaccount(), account);
|
|
133
|
+
}
|
|
134
|
+
export function importSdkSubaccount(client, exported) {
|
|
135
|
+
const subaccount = getSubaccountFromPrivateKey(exported.privateKey);
|
|
136
|
+
if (!isSameAddress(subaccount.address, exported.address)) {
|
|
137
|
+
throwSubaccountAddressMismatch("address", exported.address, subaccount.address);
|
|
138
|
+
}
|
|
139
|
+
assertNoOtherSdkSubaccountKey(client, subaccount.address);
|
|
140
|
+
return setSdkSubaccount(client, subaccount, exported.account);
|
|
141
|
+
}
|
|
142
|
+
export function exportSdkSubaccount(client) {
|
|
143
|
+
const subaccount = sdkSubaccountKeys.get(client.owner);
|
|
144
|
+
const account = client.getSubaccount()?.account;
|
|
145
|
+
return subaccount && { address: subaccount.address, privateKey: subaccount.privateKey, ...(account && { account }) };
|
|
127
146
|
}
|
|
128
147
|
export function reconcileSdkSubaccountApproval(subaccount) {
|
|
129
148
|
const approval = subaccount?.approval?.message;
|
|
@@ -173,13 +192,17 @@ async function getSdkSubaccountStatus(client, account, options) {
|
|
|
173
192
|
export async function activateSdkSubaccount(client, mainSigner, options, knownStatus) {
|
|
174
193
|
const existingSubaccount = client.getSubaccount();
|
|
175
194
|
if (existingSubaccount && hasDifferentSubaccountAccount(existingSubaccount, mainSigner.address)) {
|
|
176
|
-
|
|
195
|
+
throwSubaccountAccountMismatch(existingSubaccount, mainSigner.address);
|
|
177
196
|
}
|
|
178
197
|
if (!client.getSubaccount()) {
|
|
179
|
-
|
|
198
|
+
generateSdkSubaccount(client, mainSigner.address);
|
|
180
199
|
}
|
|
181
200
|
const status = knownStatus ?? (await getSdkSubaccountStatus(client, mainSigner.address, { force: true }));
|
|
182
201
|
const subaccount = client.getSubaccount();
|
|
202
|
+
if (status && !status.active && (status.revocationCounter > 0n || status.maxAllowedCount > 0n)) {
|
|
203
|
+
throw new Error(`Subaccount ${subaccount.address} was removed from account ${mainSigner.address} and is not approved again. ` +
|
|
204
|
+
"Call clearSubaccount() before activateSubaccount() to use a new key.");
|
|
205
|
+
}
|
|
183
206
|
const requestedExpiresAt = BigInt(nowInSeconds() + (options?.expiresInSeconds ?? DEFAULT_SUBACCOUNT_EXPIRY_DURATION));
|
|
184
207
|
const expiresAt = status && status.expiresAt > requestedExpiresAt ? status.expiresAt : requestedExpiresAt;
|
|
185
208
|
const requestedMaxAllowedCount = options?.maxAllowedCount !== undefined
|
|
@@ -215,10 +238,6 @@ export async function getSdkSubaccountApprovalForOrder(client, account, mainSign
|
|
|
215
238
|
return undefined;
|
|
216
239
|
}
|
|
217
240
|
if (hasDifferentSubaccountAccount(subaccount, account)) {
|
|
218
|
-
if (mainSigner && isSameAddress(mainSigner.address, account)) {
|
|
219
|
-
await activateSdkSubaccount(client, mainSigner);
|
|
220
|
-
return client.getSubaccount()?.approval?.message ?? getUsableSubaccountApproval(client);
|
|
221
|
-
}
|
|
222
241
|
throwSubaccountAccountMismatch(subaccount, account);
|
|
223
242
|
}
|
|
224
243
|
const forceStatusRefresh = Boolean(options?.forceRefresh || subaccount.approval?.submittedRequestId !== undefined);
|
|
@@ -61,6 +61,9 @@ export function getIsEquivalentTokens(token1, token2) {
|
|
|
61
61
|
}
|
|
62
62
|
return false;
|
|
63
63
|
}
|
|
64
|
+
export function getIsTokenTrackingPrice(token, trackedToken) {
|
|
65
|
+
return token.tracksPriceOf !== undefined && token.tracksPriceOf === (trackedToken.baseSymbol ?? trackedToken.symbol);
|
|
66
|
+
}
|
|
64
67
|
export function getTokenData(tokensData, address, convertTo) {
|
|
65
68
|
if (!address || !tokensData?.[address]) {
|
|
66
69
|
return undefined;
|
|
@@ -106,7 +109,11 @@ export function getTokensRatioByMinOutputAmountAndTriggerPrice(p) {
|
|
|
106
109
|
const adjustedToAmount = (minOutputAmount * PRECISION) / expandDecimals(1, toToken.decimals);
|
|
107
110
|
const adjustedMinOutputAmount = (minOutputAmount * PRECISION) / expandDecimals(1, toToken.decimals);
|
|
108
111
|
const areBothStablecoins = fromToken.isStable && toToken.isStable;
|
|
109
|
-
const
|
|
112
|
+
const outputIfFromIsSmallest = triggerPrice === 0n ? 0n : (adjustedFromAmount * PRECISION) / triggerPrice;
|
|
113
|
+
const outputIfFromIsLargest = (adjustedFromAmount * triggerPrice) / PRECISION;
|
|
114
|
+
const isFromSmallestToken = triggerPrice === 0n
|
|
115
|
+
? adjustedFromAmount > adjustedToAmount
|
|
116
|
+
: (adjustedMinOutputAmount - outputIfFromIsSmallest) * BASIS_POINTS_DIVISOR_BIGINT < outputIfFromIsSmallest;
|
|
110
117
|
if (areBothStablecoins) {
|
|
111
118
|
smallestToken = fromToken;
|
|
112
119
|
largestToken = toToken;
|
|
@@ -114,7 +121,7 @@ export function getTokensRatioByMinOutputAmountAndTriggerPrice(p) {
|
|
|
114
121
|
smallestAmount = adjustedToAmount;
|
|
115
122
|
}
|
|
116
123
|
else {
|
|
117
|
-
[smallestToken, largestToken, largestAmount, smallestAmount] =
|
|
124
|
+
[smallestToken, largestToken, largestAmount, smallestAmount] = isFromSmallestToken
|
|
118
125
|
? [fromToken, toToken, adjustedFromAmount, adjustedToAmount]
|
|
119
126
|
: [toToken, fromToken, adjustedToAmount, adjustedFromAmount];
|
|
120
127
|
}
|
|
@@ -124,10 +131,8 @@ export function getTokensRatioByMinOutputAmountAndTriggerPrice(p) {
|
|
|
124
131
|
acceptablePrice = ratio;
|
|
125
132
|
}
|
|
126
133
|
else {
|
|
127
|
-
const shouldDivide = areBothStablecoins ? true :
|
|
128
|
-
const outputAtTriggerPrice = shouldDivide
|
|
129
|
-
? (adjustedFromAmount * PRECISION) / triggerPrice
|
|
130
|
-
: (adjustedFromAmount * triggerPrice) / PRECISION;
|
|
134
|
+
const shouldDivide = areBothStablecoins ? true : isFromSmallestToken;
|
|
135
|
+
const outputAtTriggerPrice = shouldDivide ? outputIfFromIsSmallest : outputIfFromIsLargest;
|
|
131
136
|
allowedSwapSlippageBps =
|
|
132
137
|
((outputAtTriggerPrice - adjustedMinOutputAmount) * BASIS_POINTS_DIVISOR_BIGINT) / outputAtTriggerPrice;
|
|
133
138
|
acceptablePrice = ratio;
|
|
@@ -165,6 +170,15 @@ export function getTokensRatioByPrice(p) {
|
|
|
165
170
|
const ratio = (largestPrice * PRECISION) / smallestPrice;
|
|
166
171
|
return { ratio, largestToken, smallestToken };
|
|
167
172
|
}
|
|
173
|
+
export function getTokensRatioByPriceInDirection(p) {
|
|
174
|
+
const { fromToken, toToken, largestTokenAddress } = p;
|
|
175
|
+
const [largestToken, smallestToken] = largestTokenAddress === fromToken.address ? [fromToken, toToken] : [toToken, fromToken];
|
|
176
|
+
return {
|
|
177
|
+
ratio: (largestToken.prices.minPrice * PRECISION) / smallestToken.prices.minPrice,
|
|
178
|
+
largestToken,
|
|
179
|
+
smallestToken,
|
|
180
|
+
};
|
|
181
|
+
}
|
|
168
182
|
export function getGmToken(chainId, marketTokenAddress) {
|
|
169
183
|
const stubToken = getToken(chainId, GM_STUB_ADDRESS);
|
|
170
184
|
return {
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
import { USD_DECIMALS } from "../../../configs/factors";
|
|
3
|
+
import { mockMarginCheckMarketInfo, mockTokensData } from "../../../test/mock";
|
|
4
|
+
import { expandDecimals } from "../../numbers";
|
|
5
|
+
import { DecreasePositionSwapType } from "../../orders/types";
|
|
6
|
+
import { convertToTokenAmount } from "../../tokens";
|
|
7
|
+
import { getDecreasePositionAmounts, getNextPositionValuesForDecreaseTrade } from "../decrease";
|
|
8
|
+
import { getDecreaseReceiveOutputs, getIsSplitReceiveAvailable } from "../decreaseOutputs";
|
|
9
|
+
const tokensData = mockTokensData();
|
|
10
|
+
const usdc = tokensData.USDC;
|
|
11
|
+
const btc = tokensData.BTC;
|
|
12
|
+
// 0.05% position fee and no price impact: closing 50 000 pays 25 of position fees
|
|
13
|
+
const marketInfo = mockMarginCheckMarketInfo(tokensData, {
|
|
14
|
+
positionFeeFactorForBalanceWasImproved: expandDecimals(5, 26),
|
|
15
|
+
positionFeeFactorForBalanceWasNotImproved: expandDecimals(5, 26),
|
|
16
|
+
});
|
|
17
|
+
function usd(value) {
|
|
18
|
+
return (BigInt(Math.round(value * 100)) * expandDecimals(1, USD_DECIMALS)) / 100n;
|
|
19
|
+
}
|
|
20
|
+
// a 100 000 short with 6 666.67 USDC of collateral (15x)
|
|
21
|
+
function shortPosition({ pnl, borrowing, funding }) {
|
|
22
|
+
return {
|
|
23
|
+
marketInfo,
|
|
24
|
+
isLong: false,
|
|
25
|
+
sizeInUsd: usd(100000),
|
|
26
|
+
sizeInTokens: convertToTokenAmount(usd(100000 - pnl), btc.decimals, btc.prices.maxPrice),
|
|
27
|
+
collateralAmount: convertToTokenAmount(usd(6666.67), usdc.decimals, usdc.prices.minPrice),
|
|
28
|
+
pendingBorrowingFeesUsd: usd(borrowing),
|
|
29
|
+
pendingFundingFeesUsd: usd(funding),
|
|
30
|
+
pendingImpactAmount: 0n,
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
it("values a partial close using remaining pending impact and market balance after the close", () => {
|
|
34
|
+
const existingPosition = {
|
|
35
|
+
...shortPosition({ pnl: 0, borrowing: 0, funding: 0 }),
|
|
36
|
+
collateralUsd: usd(10000),
|
|
37
|
+
collateralAmount: expandDecimals(10000, usdc.decimals),
|
|
38
|
+
pendingImpactAmount: -10000000n,
|
|
39
|
+
};
|
|
40
|
+
for (const [longInterest, expectedPrice] of [
|
|
41
|
+
[0, 23480],
|
|
42
|
+
[40000, 23300],
|
|
43
|
+
]) {
|
|
44
|
+
const marketInfo = mockMarginCheckMarketInfo(tokensData, {
|
|
45
|
+
useV221LiquidationImpact: true,
|
|
46
|
+
useOpenInterestInTokensForBalance: false,
|
|
47
|
+
shortInterestUsd: usd(100000),
|
|
48
|
+
longInterestUsd: usd(longInterest),
|
|
49
|
+
maxPositionImpactFactorNegative: usd(0.1),
|
|
50
|
+
positionFeeFactorForBalanceWasImproved: expandDecimals(1, 27),
|
|
51
|
+
positionFeeFactorForBalanceWasNotImproved: expandDecimals(1, 28),
|
|
52
|
+
});
|
|
53
|
+
const preview = getNextPositionValuesForDecreaseTrade({
|
|
54
|
+
existingPosition,
|
|
55
|
+
marketInfo,
|
|
56
|
+
collateralToken: usdc,
|
|
57
|
+
sizeDeltaUsd: usd(50000),
|
|
58
|
+
sizeDeltaInTokens: existingPosition.sizeInTokens / 2n,
|
|
59
|
+
estimatedPnl: 0n,
|
|
60
|
+
realizedPnl: 0n,
|
|
61
|
+
collateralDeltaUsd: 0n,
|
|
62
|
+
collateralDeltaAmount: 0n,
|
|
63
|
+
payedRemainingCollateralUsd: 0n,
|
|
64
|
+
payedRemainingCollateralAmount: 0n,
|
|
65
|
+
proportionalPendingImpactDeltaUsd: -usd(1000),
|
|
66
|
+
showPnlInLeverage: false,
|
|
67
|
+
isLong: false,
|
|
68
|
+
minCollateralUsd: usd(1),
|
|
69
|
+
userReferralInfo: undefined,
|
|
70
|
+
});
|
|
71
|
+
expect(preview.nextLiqPrice).toBe(usd(expectedPrice));
|
|
72
|
+
}
|
|
73
|
+
});
|
|
74
|
+
describe("getDecreasePositionAmounts, TWAP close", () => {
|
|
75
|
+
// closing 50 000 realizes half of the PnL, an equal share per part; the contract charges every pending
|
|
76
|
+
// fee to the first part and pays a part's costs from its profit first, then from the collateral
|
|
77
|
+
it.each([
|
|
78
|
+
{ pnl: 3000, borrowing: 1320, funding: 0, keep: true, parts: 5, receive: 1180, fromCollateral: 1025 },
|
|
79
|
+
{ pnl: 3000, borrowing: 1320, funding: 0, keep: false, parts: 5, receive: 1180, fromCollateral: 1025 },
|
|
80
|
+
{ pnl: 3000, borrowing: 1000, funding: 320, keep: true, parts: 5, receive: 1180, fromCollateral: 1025 },
|
|
81
|
+
{ pnl: 3000, borrowing: 1320, funding: 0, keep: true, parts: 2, receive: 737.5, fromCollateral: 582.5 },
|
|
82
|
+
{ pnl: 3000, borrowing: 100, funding: 0, keep: true, parts: 5, receive: 1375, fromCollateral: 0 },
|
|
83
|
+
{ pnl: 3000, borrowing: 2000, funding: 0, keep: true, parts: 5, receive: 1180, fromCollateral: 1705 },
|
|
84
|
+
{ pnl: -1000, borrowing: 1320, funding: 0, keep: true, parts: 5, receive: 0, fromCollateral: 1845 },
|
|
85
|
+
// the parts field is empty while the user types: the estimate falls back to one order
|
|
86
|
+
{ pnl: 3000, borrowing: 1320, funding: 0, keep: true, parts: 0, receive: 155, fromCollateral: 0 },
|
|
87
|
+
])("withdraws no collateral on a partial close and charges the pending fees to part 1 TRD-42: pnl $pnl, borrowing $borrowing, funding $funding, $parts parts, keep leverage $keep", ({ pnl, borrowing, funding, keep, parts, receive, fromCollateral }) => {
|
|
88
|
+
const amounts = getDecreasePositionAmounts({
|
|
89
|
+
marketInfo,
|
|
90
|
+
collateralToken: usdc,
|
|
91
|
+
isLong: false,
|
|
92
|
+
position: shortPosition({ pnl, borrowing, funding }),
|
|
93
|
+
closeSizeUsd: usd(50000),
|
|
94
|
+
keepLeverage: keep,
|
|
95
|
+
userReferralInfo: undefined,
|
|
96
|
+
minCollateralUsd: usd(1),
|
|
97
|
+
minPositionSizeUsd: usd(1),
|
|
98
|
+
uiFeeFactor: 0n,
|
|
99
|
+
isSetAcceptablePriceImpactEnabled: true,
|
|
100
|
+
isTwap: true,
|
|
101
|
+
numberOfParts: parts,
|
|
102
|
+
});
|
|
103
|
+
expect(amounts.collateralDeltaAmount).toBe(0n);
|
|
104
|
+
expect(amounts.receiveUsd).toBe(usd(receive));
|
|
105
|
+
expect(amounts.payedRemainingCollateralUsd).toBe(usd(fromCollateral));
|
|
106
|
+
});
|
|
107
|
+
// with split receive the profit leaves in BTC unswapped, so the contract pays every cost from the collateral
|
|
108
|
+
it("offers split receive on a partial close and pays its costs from the collateral TRD-42", () => {
|
|
109
|
+
const position = {
|
|
110
|
+
marketInfo,
|
|
111
|
+
isLong: true,
|
|
112
|
+
sizeInUsd: usd(100000),
|
|
113
|
+
sizeInTokens: convertToTokenAmount(usd(103000), btc.decimals, btc.prices.minPrice),
|
|
114
|
+
collateralToken: usdc,
|
|
115
|
+
collateralAmount: convertToTokenAmount(usd(6666.67), usdc.decimals, usdc.prices.minPrice),
|
|
116
|
+
pnlToken: btc,
|
|
117
|
+
pendingBorrowingFeesUsd: usd(1320),
|
|
118
|
+
pendingFundingFeesUsd: 0n,
|
|
119
|
+
pendingImpactAmount: 0n,
|
|
120
|
+
};
|
|
121
|
+
const amounts = getDecreasePositionAmounts({
|
|
122
|
+
marketInfo,
|
|
123
|
+
collateralToken: usdc,
|
|
124
|
+
isLong: true,
|
|
125
|
+
position,
|
|
126
|
+
closeSizeUsd: usd(50000),
|
|
127
|
+
keepLeverage: true,
|
|
128
|
+
userReferralInfo: undefined,
|
|
129
|
+
minCollateralUsd: usd(1),
|
|
130
|
+
minPositionSizeUsd: usd(1),
|
|
131
|
+
uiFeeFactor: 0n,
|
|
132
|
+
isSetAcceptablePriceImpactEnabled: true,
|
|
133
|
+
isTwap: true,
|
|
134
|
+
numberOfParts: 5,
|
|
135
|
+
forceDecreaseSwapType: DecreasePositionSwapType.NoSwap,
|
|
136
|
+
});
|
|
137
|
+
const outputs = getDecreaseReceiveOutputs({ decreaseAmounts: amounts, tokensData });
|
|
138
|
+
expect(amounts.collateralDeltaAmount).toBe(0n);
|
|
139
|
+
expect(amounts.payedRemainingCollateralUsd).toBe(usd(1345));
|
|
140
|
+
expect(outputs).toEqual([
|
|
141
|
+
{
|
|
142
|
+
type: "primary",
|
|
143
|
+
token: btc,
|
|
144
|
+
amount: convertToTokenAmount(usd(1500), btc.decimals, btc.prices.minPrice),
|
|
145
|
+
usd: usd(1500),
|
|
146
|
+
},
|
|
147
|
+
]);
|
|
148
|
+
expect(getIsSplitReceiveAvailable(position, outputs, { isTwap: true })).toBe(true);
|
|
149
|
+
});
|
|
150
|
+
});
|