@gmx-io/sdk 2.9.3 → 3.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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 +56 -0
- package/build/cjs/src/codegen/prebuilt/hashedMarketConfigKeys.json +852 -0
- package/build/cjs/src/codegen/prebuilt/hashedMarketValuesKeys.json +105 -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 +50 -0
- package/build/cjs/src/configs/tokens.js +12 -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/index.js +15 -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 +56 -0
- package/build/esm/src/codegen/prebuilt/hashedMarketConfigKeys.json +852 -0
- package/build/esm/src/codegen/prebuilt/hashedMarketValuesKeys.json +105 -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 +50 -0
- package/build/esm/src/configs/tokens.js +12 -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/index.js +1 -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 +1113 -100
- 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/index.d.ts +1 -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
|
@@ -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
|
+
});
|
|
@@ -384,6 +384,49 @@ describe("gmsol trade math", () => {
|
|
|
384
384
|
expect(close.receiveUsd - position.netValueAfterAllFees).toBeLessThanOrEqual(10n ** 24n);
|
|
385
385
|
}
|
|
386
386
|
});
|
|
387
|
+
it("charges gmsol pending fees to the first TWAP part and withholds the impact beyond the cap", () => {
|
|
388
|
+
const impactBeyondCap = {
|
|
389
|
+
longInterestUsd: 2000n * P,
|
|
390
|
+
shortInterestUsd: 2000n * P,
|
|
391
|
+
positionImpactFactorNegative: P / 50n,
|
|
392
|
+
positionImpactExponentFactorNegative: P,
|
|
393
|
+
maxPositionImpactFactorNegative: P / 100n,
|
|
394
|
+
shortPoolAmount: 10000000n * 10n ** 6n,
|
|
395
|
+
maxPnlFactorForTradersShort: P,
|
|
396
|
+
};
|
|
397
|
+
// a short closes $1,000 of $2,000 in 2 parts; at 90 each part realizes $50 profit, at 100 none.
|
|
398
|
+
// part 1 pays every pending fee, from its own profit first; the impact beyond the cap is $5 a part
|
|
399
|
+
for (const [price, borrowingUsd, fundingAmount, overrides, receiveUsd, fromCollateralUsd] of [
|
|
400
|
+
[90n * P, 80n * P, 0n, {}, 50n * P, 30n * P],
|
|
401
|
+
[90n * P, 0n, 80000000n, {}, 50n * P, 30n * P],
|
|
402
|
+
[100n * P, 0n, 0n, impactBeyondCap, 0n, 20n * P],
|
|
403
|
+
[90n * P, 80n * P, 0n, impactBeyondCap, 40n * P, 40n * P],
|
|
404
|
+
]) {
|
|
405
|
+
const marketInfo = market({ decimals: 8, minPrice: price, maxPrice: price, tradeMath: "gmsol", overrides });
|
|
406
|
+
const position = {
|
|
407
|
+
...positionInfo(marketInfo, 2000n * P, 20n * 10n ** 8n, false),
|
|
408
|
+
pendingBorrowingFeesUsd: borrowingUsd,
|
|
409
|
+
fundingFeeAmount: fundingAmount,
|
|
410
|
+
};
|
|
411
|
+
const result = getDecreasePositionAmounts({
|
|
412
|
+
marketInfo,
|
|
413
|
+
collateralToken: marketInfo.shortToken,
|
|
414
|
+
isLong: false,
|
|
415
|
+
position,
|
|
416
|
+
closeSizeUsd: 1000n * P,
|
|
417
|
+
keepLeverage: false,
|
|
418
|
+
userReferralInfo: undefined,
|
|
419
|
+
minCollateralUsd: 0n,
|
|
420
|
+
minPositionSizeUsd: 0n,
|
|
421
|
+
uiFeeFactor: 0n,
|
|
422
|
+
isSetAcceptablePriceImpactEnabled: false,
|
|
423
|
+
forceDecreaseSwapType: DecreasePositionSwapType.NoSwap,
|
|
424
|
+
isTwap: true,
|
|
425
|
+
numberOfParts: 2,
|
|
426
|
+
});
|
|
427
|
+
expect([result.receiveUsd, result.payedRemainingCollateralUsd]).toEqual([receiveUsd, fromCollateralUsd]);
|
|
428
|
+
}
|
|
429
|
+
});
|
|
387
430
|
it("rejects gmsol increases that fill no index token atoms FESOL-57", () => {
|
|
388
431
|
const imbalanced = {
|
|
389
432
|
longInterestUsd: 1000n * P,
|