@gmx-io/sdk 2.9.3 → 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (163) hide show
  1. package/build/cjs/src/abis/RatioVesterReader.js +45 -0
  2. package/build/cjs/src/abis/index.js +2 -0
  3. package/build/cjs/src/clients/v1/modules/oracle.js +15 -0
  4. package/build/cjs/src/clients/v1/modules/oracle.spec.js +20 -0
  5. package/build/cjs/src/clients/v1/modules/orders/helpers.js +16 -12
  6. package/build/cjs/src/clients/v1/modules/orders/helpers.spec.js +21 -0
  7. package/build/cjs/src/clients/v1/modules/orders/orders.js +4 -0
  8. package/build/cjs/src/clients/v1/modules/orders/utils.js +1 -0
  9. package/build/cjs/src/clients/v2/__tests__/subaccount.spec.js +74 -17
  10. package/build/cjs/src/clients/v2/__tests__/subaccountLifecycle.spec.js +1 -1
  11. package/build/cjs/src/clients/v2/__tests__/testUtil.js +14 -2
  12. package/build/cjs/src/clients/v2/index.js +28 -7
  13. package/build/cjs/src/clients/v2/solana.spec.js +81 -4
  14. package/build/cjs/src/codegen/prebuilt/hashedKinkModelMarketRatesKeys.json +56 -0
  15. package/build/cjs/src/codegen/prebuilt/hashedMarketConfigKeys.json +852 -0
  16. package/build/cjs/src/codegen/prebuilt/hashedMarketValuesKeys.json +105 -0
  17. package/build/cjs/src/configs/contracts.js +10 -0
  18. package/build/cjs/src/configs/dataStore.js +22 -4
  19. package/build/cjs/src/configs/express.js +1 -2
  20. package/build/cjs/src/configs/markets.js +50 -0
  21. package/build/cjs/src/configs/tokens.js +12 -0
  22. package/build/cjs/src/test/mockCrossFetch.js +1 -0
  23. package/build/cjs/src/utils/__tests__/fees.spec.js +52 -0
  24. package/build/cjs/src/utils/__tests__/gmsolUnits.spec.js +101 -0
  25. package/build/cjs/src/utils/__tests__/orderTransactions/batchUtils.spec.js +66 -0
  26. package/build/cjs/src/utils/__tests__/orderTransactions/decreaseOrders.spec.js +6 -6
  27. package/build/cjs/src/utils/__tests__/orderTransactions/exchangeRouterMulticall.spec.js +40 -0
  28. package/build/cjs/src/utils/__tests__/orderTransactions/updateOrder.spec.js +4 -2
  29. package/build/cjs/src/utils/__tests__/tokens.spec.js +63 -0
  30. package/build/cjs/src/utils/errors/transactionsErrors.js +6 -0
  31. package/build/cjs/src/utils/fees/index.js +5 -0
  32. package/build/cjs/src/utils/fees/priceImpact.js +39 -6
  33. package/build/cjs/src/utils/gmsol/index.js +15 -0
  34. package/build/cjs/src/utils/gmsol/units.js +106 -0
  35. package/build/cjs/src/utils/http/http.js +21 -25
  36. package/build/cjs/src/utils/http/httpFallback.js +3 -3
  37. package/build/cjs/src/utils/http/validation.js +9 -1
  38. package/build/cjs/src/utils/markets/hashKeys.js +8 -0
  39. package/build/cjs/src/utils/markets/multicall.js +10 -0
  40. package/build/cjs/src/utils/markets/utils.js +2 -0
  41. package/build/cjs/src/utils/multichain/__tests__/api.spec.js +49 -0
  42. package/build/cjs/src/utils/multichain/api.js +29 -2
  43. package/build/cjs/src/utils/orderTransactions/utils.js +63 -5
  44. package/build/cjs/src/utils/orders/api.js +66 -3
  45. package/build/cjs/src/utils/positions/__tests__/liquidationImpact.spec.js +44 -0
  46. package/build/cjs/src/utils/positions/__tests__/liquidationPrice.spec.js +159 -2
  47. package/build/cjs/src/utils/positions/__tests__/trackingCollateral.spec.js +395 -0
  48. package/build/cjs/src/utils/positions/api.js +4 -0
  49. package/build/cjs/src/utils/positions/utils.js +119 -44
  50. package/build/cjs/src/utils/prices/api.js +2 -2
  51. package/build/cjs/src/utils/referrals/api.js +5 -4
  52. package/build/cjs/src/utils/subaccount/generateSubaccount.js +14 -14
  53. package/build/cjs/src/utils/subaccount/sdkClient.js +40 -19
  54. package/build/cjs/src/utils/tokens/utils.js +23 -7
  55. package/build/cjs/src/utils/trade/__tests__/decrease.spec.js +152 -0
  56. package/build/cjs/src/utils/trade/__tests__/gmsolTradeMath.spec.js +43 -0
  57. package/build/cjs/src/utils/trade/decrease.js +113 -33
  58. package/build/cjs/src/utils/trade/decreaseMarginCheck.js +38 -2
  59. package/build/cjs/src/utils/trade/decreaseOutputs.js +20 -5
  60. package/build/cjs/src/utils/trade/increase.js +30 -11
  61. package/build/cjs/src/utils/trade/increaseMarginCheck.js +14 -35
  62. package/build/esm/src/abis/RatioVesterReader.js +43 -0
  63. package/build/esm/src/abis/index.js +2 -0
  64. package/build/esm/src/clients/v1/modules/oracle.js +15 -0
  65. package/build/esm/src/clients/v1/modules/oracle.spec.js +18 -0
  66. package/build/esm/src/clients/v1/modules/orders/helpers.js +17 -13
  67. package/build/esm/src/clients/v1/modules/orders/helpers.spec.js +21 -0
  68. package/build/esm/src/clients/v1/modules/orders/orders.js +4 -0
  69. package/build/esm/src/clients/v1/modules/orders/utils.js +1 -0
  70. package/build/esm/src/clients/v2/__tests__/subaccount.spec.js +74 -17
  71. package/build/esm/src/clients/v2/__tests__/subaccountLifecycle.spec.js +2 -2
  72. package/build/esm/src/clients/v2/__tests__/testUtil.js +13 -2
  73. package/build/esm/src/clients/v2/index.js +29 -8
  74. package/build/esm/src/clients/v2/solana.spec.js +79 -2
  75. package/build/esm/src/codegen/prebuilt/hashedKinkModelMarketRatesKeys.json +56 -0
  76. package/build/esm/src/codegen/prebuilt/hashedMarketConfigKeys.json +852 -0
  77. package/build/esm/src/codegen/prebuilt/hashedMarketValuesKeys.json +105 -0
  78. package/build/esm/src/configs/contracts.js +10 -0
  79. package/build/esm/src/configs/dataStore.js +14 -0
  80. package/build/esm/src/configs/express.js +0 -1
  81. package/build/esm/src/configs/markets.js +50 -0
  82. package/build/esm/src/configs/tokens.js +12 -0
  83. package/build/esm/src/test/mockCrossFetch.js +1 -0
  84. package/build/esm/src/utils/__tests__/fees.spec.js +53 -1
  85. package/build/esm/src/utils/__tests__/gmsolUnits.spec.js +99 -0
  86. package/build/esm/src/utils/__tests__/orderTransactions/batchUtils.spec.js +68 -2
  87. package/build/esm/src/utils/__tests__/orderTransactions/decreaseOrders.spec.js +6 -6
  88. package/build/esm/src/utils/__tests__/orderTransactions/exchangeRouterMulticall.spec.js +40 -0
  89. package/build/esm/src/utils/__tests__/orderTransactions/updateOrder.spec.js +5 -3
  90. package/build/esm/src/utils/__tests__/tokens.spec.js +64 -1
  91. package/build/esm/src/utils/errors/transactionsErrors.js +6 -0
  92. package/build/esm/src/utils/fees/index.js +5 -0
  93. package/build/esm/src/utils/fees/priceImpact.js +36 -5
  94. package/build/esm/src/utils/gmsol/index.js +1 -0
  95. package/build/esm/src/utils/gmsol/units.js +97 -0
  96. package/build/esm/src/utils/http/http.js +21 -25
  97. package/build/esm/src/utils/http/httpFallback.js +3 -3
  98. package/build/esm/src/utils/http/validation.js +7 -0
  99. package/build/esm/src/utils/markets/hashKeys.js +9 -1
  100. package/build/esm/src/utils/markets/multicall.js +10 -0
  101. package/build/esm/src/utils/markets/utils.js +2 -0
  102. package/build/esm/src/utils/multichain/__tests__/api.spec.js +46 -0
  103. package/build/esm/src/utils/multichain/api.js +29 -2
  104. package/build/esm/src/utils/orderTransactions/utils.js +59 -5
  105. package/build/esm/src/utils/orders/api.js +64 -2
  106. package/build/esm/src/utils/positions/__tests__/liquidationImpact.spec.js +42 -0
  107. package/build/esm/src/utils/positions/__tests__/liquidationPrice.spec.js +161 -4
  108. package/build/esm/src/utils/positions/__tests__/trackingCollateral.spec.js +393 -0
  109. package/build/esm/src/utils/positions/api.js +4 -0
  110. package/build/esm/src/utils/positions/utils.js +115 -44
  111. package/build/esm/src/utils/prices/api.js +2 -2
  112. package/build/esm/src/utils/referrals/api.js +6 -5
  113. package/build/esm/src/utils/subaccount/generateSubaccount.js +13 -14
  114. package/build/esm/src/utils/subaccount/sdkClient.js +38 -19
  115. package/build/esm/src/utils/tokens/utils.js +20 -6
  116. package/build/esm/src/utils/trade/__tests__/decrease.spec.js +150 -0
  117. package/build/esm/src/utils/trade/__tests__/gmsolTradeMath.spec.js +43 -0
  118. package/build/esm/src/utils/trade/decrease.js +115 -35
  119. package/build/esm/src/utils/trade/decreaseMarginCheck.js +37 -2
  120. package/build/esm/src/utils/trade/decreaseOutputs.js +19 -5
  121. package/build/esm/src/utils/trade/increase.js +32 -13
  122. package/build/esm/src/utils/trade/increaseMarginCheck.js +18 -39
  123. package/build/tsconfig.tsbuildinfo +1 -1
  124. package/build/types/src/abis/RatioVesterReader.d.ts +74 -0
  125. package/build/types/src/abis/index.d.ts +73 -0
  126. package/build/types/src/clients/v1/modules/oracle.d.ts +6 -1
  127. package/build/types/src/clients/v1/modules/oracle.spec.d.ts +1 -0
  128. package/build/types/src/clients/v2/__tests__/testUtil.d.ts +1 -0
  129. package/build/types/src/clients/v2/index.d.ts +26 -5
  130. package/build/types/src/codegen/prebuilt/index.d.ts +1113 -100
  131. package/build/types/src/configs/contracts.d.ts +10 -0
  132. package/build/types/src/configs/dataStore.d.ts +8 -0
  133. package/build/types/src/configs/express.d.ts +0 -1
  134. package/build/types/src/utils/__tests__/gmsolUnits.spec.d.ts +1 -0
  135. package/build/types/src/utils/errors/parseError.d.ts +1 -1
  136. package/build/types/src/utils/errors/transactionsErrors.d.ts +6 -0
  137. package/build/types/src/utils/fees/priceImpact.d.ts +10 -0
  138. package/build/types/src/utils/gmsol/index.d.ts +1 -0
  139. package/build/types/src/utils/gmsol/units.d.ts +53 -0
  140. package/build/types/src/utils/http/types.d.ts +1 -0
  141. package/build/types/src/utils/http/validation.d.ts +1 -0
  142. package/build/types/src/utils/markets/types.d.ts +5 -2
  143. package/build/types/src/utils/multichain/api.d.ts +4 -1
  144. package/build/types/src/utils/orderTransactions/utils.d.ts +19 -4
  145. package/build/types/src/utils/orders/api.d.ts +2 -1
  146. package/build/types/src/utils/orders/types.d.ts +24 -0
  147. package/build/types/src/utils/positions/__tests__/liquidationImpact.spec.d.ts +1 -0
  148. package/build/types/src/utils/positions/__tests__/trackingCollateral.spec.d.ts +1 -0
  149. package/build/types/src/utils/positions/types.d.ts +2 -0
  150. package/build/types/src/utils/positions/utils.d.ts +30 -0
  151. package/build/types/src/utils/prices/api.d.ts +2 -0
  152. package/build/types/src/utils/referrals/types.d.ts +4 -0
  153. package/build/types/src/utils/subaccount/generateSubaccount.d.ts +9 -4
  154. package/build/types/src/utils/subaccount/sdkClient.d.ts +7 -1
  155. package/build/types/src/utils/subaccount/types.d.ts +2 -0
  156. package/build/types/src/utils/tokens/types.d.ts +1 -0
  157. package/build/types/src/utils/tokens/utils.d.ts +6 -0
  158. package/build/types/src/utils/trade/__tests__/decrease.spec.d.ts +1 -0
  159. package/build/types/src/utils/trade/decrease.d.ts +3 -0
  160. package/build/types/src/utils/trade/decreaseMarginCheck.d.ts +11 -0
  161. package/build/types/src/utils/trade/decreaseOutputs.d.ts +7 -2
  162. package/build/types/src/utils/trade/increaseMarginCheck.d.ts +1 -0
  163. package/package.json +10 -1
@@ -3,25 +3,22 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.createSubaccountSignerFromConfig = exports.decryptSubaccountPrivateKey = exports.generateSubaccount = void 0;
6
+ exports.createSubaccountSignerFromConfig = exports.decryptSubaccountPrivateKey = exports.generateSubaccount = exports.getSubaccountFromPrivateKey = void 0;
7
7
  const crypto_js_1 = __importDefault(require("crypto-js"));
8
- const viem_1 = require("viem");
9
8
  const accounts_1 = require("viem/accounts");
10
- const express_1 = require("../../configs/express");
11
9
  const signer_1 = require("../signer");
12
- async function generateSubaccount(mainSigner) {
13
- const signature = await mainSigner.signMessage(express_1.SUBACCOUNT_MESSAGE);
14
- const pk = (0, viem_1.keccak256)(signature);
15
- const account = (0, accounts_1.privateKeyToAccount)(pk);
16
- const signer = new signer_1.PrivateKeySigner(pk);
17
- const encryptedPrivateKey = crypto_js_1.default.AES.encrypt(pk, mainSigner.address).toString();
18
- return {
19
- address: account.address,
20
- signer,
21
- privateKey: encryptedPrivateKey,
22
- };
10
+ function getSubaccountFromPrivateKey(privateKey) {
11
+ const signer = new signer_1.PrivateKeySigner(privateKey);
12
+ return { address: signer.address, signer, privateKey };
13
+ }
14
+ exports.getSubaccountFromPrivateKey = getSubaccountFromPrivateKey;
15
+ function generateSubaccount() {
16
+ return getSubaccountFromPrivateKey((0, accounts_1.generatePrivateKey)());
23
17
  }
24
18
  exports.generateSubaccount = generateSubaccount;
19
+ /**
20
+ * @deprecated Only reads configs stored by SDK versions below 3.0.0.
21
+ */
25
22
  function decryptSubaccountPrivateKey(encryptedPrivateKey, mainAccountAddress) {
26
23
  const decrypted = crypto_js_1.default.AES.decrypt(encryptedPrivateKey, mainAccountAddress).toString(crypto_js_1.default.enc.Utf8);
27
24
  if (!decrypted) {
@@ -30,6 +27,9 @@ function decryptSubaccountPrivateKey(encryptedPrivateKey, mainAccountAddress) {
30
27
  return decrypted;
31
28
  }
32
29
  exports.decryptSubaccountPrivateKey = decryptSubaccountPrivateKey;
30
+ /**
31
+ * @deprecated Only reads configs stored by SDK versions below 3.0.0.
32
+ */
33
33
  function createSubaccountSignerFromConfig(encryptedPrivateKey, mainAccountAddress) {
34
34
  const pk = decryptSubaccountPrivateKey(encryptedPrivateKey, mainAccountAddress);
35
35
  return new signer_1.PrivateKeySigner(pk);
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.clearSdkSubaccount = exports.executeExpressOrderWithSubaccount = exports.submitOrderWithSubaccount = exports.signOrderWithSubaccount = exports.prepareWithSubaccount = exports.getSdkSubaccountApprovalForOrder = exports.activateSdkSubaccount = exports.refreshSdkSubaccountState = exports.reconcileSdkSubaccountApproval = exports.generateSdkSubaccount = exports.getSdkSubaccountApprovalMessage = exports.hasActiveSdkSubaccount = void 0;
3
+ exports.clearSdkSubaccount = exports.executeExpressOrderWithSubaccount = exports.submitOrderWithSubaccount = exports.signOrderWithSubaccount = exports.prepareWithSubaccount = exports.getSdkSubaccountApprovalForOrder = exports.activateSdkSubaccount = exports.refreshSdkSubaccountState = exports.reconcileSdkSubaccountApproval = exports.exportSdkSubaccount = exports.importSdkSubaccount = exports.generateSdkSubaccount = exports.getSdkSubaccountApprovalMessage = exports.hasActiveSdkSubaccount = void 0;
4
4
  const express_1 = require("../../configs/express");
5
5
  const api_1 = require("../orderTransactions/api");
6
6
  const time_1 = require("../time");
@@ -8,7 +8,7 @@ const api_2 = require("./api");
8
8
  const generateSubaccount_1 = require("./generateSubaccount");
9
9
  const getEmptySubaccountApproval_1 = require("./getEmptySubaccountApproval");
10
10
  const state_1 = require("./state");
11
- const sdkSubaccountSigners = new WeakMap();
11
+ const sdkSubaccountKeys = new WeakMap();
12
12
  const MAX_PREPARED_SUBACCOUNT_APPROVALS = 100;
13
13
  const SUBACCOUNT_STATUS_CACHE_TTL_MS = 15000;
14
14
  const LOW_SUBACCOUNT_ACTIONS_REFRESH_THRESHOLD = 1n;
@@ -21,10 +21,10 @@ const SUBMITTED_ORDER_STATUSES = new Set([
21
21
  ]);
22
22
  const FINAL_ORDER_STATUSES = new Set(["created", "executed"]);
23
23
  function hasSdkSubaccountSigner(owner) {
24
- return sdkSubaccountSigners.has(owner);
24
+ return sdkSubaccountKeys.has(owner);
25
25
  }
26
26
  function getSdkSubaccountSigner(owner) {
27
- return sdkSubaccountSigners.get(owner);
27
+ return sdkSubaccountKeys.get(owner)?.signer;
28
28
  }
29
29
  function isSameAddress(a, b) {
30
30
  return a !== undefined && b !== undefined && a.toLowerCase() === b.toLowerCase();
@@ -38,8 +38,14 @@ function throwSubaccountAccountMismatch(subaccount, account) {
38
38
  function throwSubaccountAddressMismatch(source, provided, expected) {
39
39
  throw new Error(`${source} ${provided} does not match generated subaccount ${expected}.`);
40
40
  }
41
+ function assertNoOtherSdkSubaccountKey(client, address) {
42
+ const heldAddress = sdkSubaccountKeys.get(client.owner)?.address;
43
+ if (heldAddress && !isSameAddress(heldAddress, address)) {
44
+ throw new Error(`Subaccount ${heldAddress} is already set. Call clearSubaccount() before setting another key.`);
45
+ }
46
+ }
41
47
  function resetSdkSubaccount(client) {
42
- sdkSubaccountSigners.delete(client.owner);
48
+ sdkSubaccountKeys.delete(client.owner);
43
49
  client.preparedSubaccountApprovals.clear();
44
50
  client.setSubaccount(undefined);
45
51
  }
@@ -120,17 +126,32 @@ function getSdkSubaccountApprovalMessage(client) {
120
126
  return getUsableSubaccountApproval(client);
121
127
  }
122
128
  exports.getSdkSubaccountApprovalMessage = getSdkSubaccountApprovalMessage;
123
- async function generateSdkSubaccount(client, mainSigner) {
129
+ function setSdkSubaccount(client, subaccount, account) {
124
130
  client.preparedSubaccountApprovals.clear();
125
- const result = await (0, generateSubaccount_1.generateSubaccount)(mainSigner);
126
- sdkSubaccountSigners.set(client.owner, result.signer);
127
- client.setSubaccount({
128
- account: mainSigner.address,
129
- address: result.address,
130
- });
131
- return result.address;
131
+ sdkSubaccountKeys.set(client.owner, subaccount);
132
+ client.setSubaccount({ account, address: subaccount.address });
133
+ return subaccount.address;
134
+ }
135
+ function generateSdkSubaccount(client, account) {
136
+ assertNoOtherSdkSubaccountKey(client);
137
+ return setSdkSubaccount(client, (0, generateSubaccount_1.generateSubaccount)(), account);
132
138
  }
133
139
  exports.generateSdkSubaccount = generateSdkSubaccount;
140
+ function importSdkSubaccount(client, exported) {
141
+ const subaccount = (0, generateSubaccount_1.getSubaccountFromPrivateKey)(exported.privateKey);
142
+ if (!isSameAddress(subaccount.address, exported.address)) {
143
+ throwSubaccountAddressMismatch("address", exported.address, subaccount.address);
144
+ }
145
+ assertNoOtherSdkSubaccountKey(client, subaccount.address);
146
+ return setSdkSubaccount(client, subaccount, exported.account);
147
+ }
148
+ exports.importSdkSubaccount = importSdkSubaccount;
149
+ function exportSdkSubaccount(client) {
150
+ const subaccount = sdkSubaccountKeys.get(client.owner);
151
+ const account = client.getSubaccount()?.account;
152
+ return subaccount && { address: subaccount.address, privateKey: subaccount.privateKey, ...(account && { account }) };
153
+ }
154
+ exports.exportSdkSubaccount = exportSdkSubaccount;
134
155
  function reconcileSdkSubaccountApproval(subaccount) {
135
156
  const approval = subaccount?.approval?.message;
136
157
  const status = subaccount?.onchainData;
@@ -181,13 +202,17 @@ async function getSdkSubaccountStatus(client, account, options) {
181
202
  async function activateSdkSubaccount(client, mainSigner, options, knownStatus) {
182
203
  const existingSubaccount = client.getSubaccount();
183
204
  if (existingSubaccount && hasDifferentSubaccountAccount(existingSubaccount, mainSigner.address)) {
184
- resetSdkSubaccount(client);
205
+ throwSubaccountAccountMismatch(existingSubaccount, mainSigner.address);
185
206
  }
186
207
  if (!client.getSubaccount()) {
187
- await generateSdkSubaccount(client, mainSigner);
208
+ generateSdkSubaccount(client, mainSigner.address);
188
209
  }
189
210
  const status = knownStatus ?? (await getSdkSubaccountStatus(client, mainSigner.address, { force: true }));
190
211
  const subaccount = client.getSubaccount();
212
+ if (status && !status.active && (status.revocationCounter > 0n || status.maxAllowedCount > 0n)) {
213
+ throw new Error(`Subaccount ${subaccount.address} was removed from account ${mainSigner.address} and is not approved again. ` +
214
+ "Call clearSubaccount() before activateSubaccount() to use a new key.");
215
+ }
191
216
  const requestedExpiresAt = BigInt((0, time_1.nowInSeconds)() + (options?.expiresInSeconds ?? express_1.DEFAULT_SUBACCOUNT_EXPIRY_DURATION));
192
217
  const expiresAt = status && status.expiresAt > requestedExpiresAt ? status.expiresAt : requestedExpiresAt;
193
218
  const requestedMaxAllowedCount = options?.maxAllowedCount !== undefined
@@ -224,10 +249,6 @@ async function getSdkSubaccountApprovalForOrder(client, account, mainSigner, opt
224
249
  return undefined;
225
250
  }
226
251
  if (hasDifferentSubaccountAccount(subaccount, account)) {
227
- if (mainSigner && isSameAddress(mainSigner.address, account)) {
228
- await activateSdkSubaccount(client, mainSigner);
229
- return client.getSubaccount()?.approval?.message ?? getUsableSubaccountApproval(client);
230
- }
231
252
  throwSubaccountAccountMismatch(subaccount, account);
232
253
  }
233
254
  const forceStatusRefresh = Boolean(options?.forceRefresh || subaccount.approval?.submittedRequestId !== undefined);
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getGlvToken = exports.getGmToken = exports.getTokensRatioByPrice = exports.getIsUnwrap = exports.getIsWrap = exports.getAmountByRatio = exports.getTokensRatioByMinOutputAmountAndTriggerPrice = exports.getTokensRatioByAmounts = exports.getTokenData = exports.getIsEquivalentTokens = exports.getMidPrice = exports.convertBetweenTokens = exports.convertToUsd = exports.convertToTokenAmountForIncrease = exports.convertToTokenAmount = exports.convertToContractTokenPrices = exports.convertToContractPrice = exports.parseContractPrice = void 0;
3
+ exports.getGlvToken = exports.getGmToken = exports.getTokensRatioByPriceInDirection = exports.getTokensRatioByPrice = exports.getIsUnwrap = exports.getIsWrap = exports.getAmountByRatio = exports.getTokensRatioByMinOutputAmountAndTriggerPrice = exports.getTokensRatioByAmounts = exports.getTokenData = exports.getIsTokenTrackingPrice = exports.getIsEquivalentTokens = exports.getMidPrice = exports.convertBetweenTokens = exports.convertToUsd = exports.convertToTokenAmountForIncrease = exports.convertToTokenAmount = exports.convertToContractTokenPrices = exports.convertToContractPrice = exports.parseContractPrice = void 0;
4
4
  const factors_1 = require("../../configs/factors");
5
5
  const tokens_1 = require("../../configs/tokens");
6
6
  const bigmath_1 = require("../bigmath");
@@ -73,6 +73,10 @@ function getIsEquivalentTokens(token1, token2) {
73
73
  return false;
74
74
  }
75
75
  exports.getIsEquivalentTokens = getIsEquivalentTokens;
76
+ function getIsTokenTrackingPrice(token, trackedToken) {
77
+ return token.tracksPriceOf !== undefined && token.tracksPriceOf === (trackedToken.baseSymbol ?? trackedToken.symbol);
78
+ }
79
+ exports.getIsTokenTrackingPrice = getIsTokenTrackingPrice;
76
80
  function getTokenData(tokensData, address, convertTo) {
77
81
  if (!address || !tokensData?.[address]) {
78
82
  return undefined;
@@ -120,7 +124,11 @@ function getTokensRatioByMinOutputAmountAndTriggerPrice(p) {
120
124
  const adjustedToAmount = (minOutputAmount * numbers_1.PRECISION) / (0, numbers_1.expandDecimals)(1, toToken.decimals);
121
125
  const adjustedMinOutputAmount = (minOutputAmount * numbers_1.PRECISION) / (0, numbers_1.expandDecimals)(1, toToken.decimals);
122
126
  const areBothStablecoins = fromToken.isStable && toToken.isStable;
123
- const isFromAmountLarger = adjustedFromAmount > adjustedToAmount;
127
+ const outputIfFromIsSmallest = triggerPrice === 0n ? 0n : (adjustedFromAmount * numbers_1.PRECISION) / triggerPrice;
128
+ const outputIfFromIsLargest = (adjustedFromAmount * triggerPrice) / numbers_1.PRECISION;
129
+ const isFromSmallestToken = triggerPrice === 0n
130
+ ? adjustedFromAmount > adjustedToAmount
131
+ : (adjustedMinOutputAmount - outputIfFromIsSmallest) * factors_1.BASIS_POINTS_DIVISOR_BIGINT < outputIfFromIsSmallest;
124
132
  if (areBothStablecoins) {
125
133
  smallestToken = fromToken;
126
134
  largestToken = toToken;
@@ -128,7 +136,7 @@ function getTokensRatioByMinOutputAmountAndTriggerPrice(p) {
128
136
  smallestAmount = adjustedToAmount;
129
137
  }
130
138
  else {
131
- [smallestToken, largestToken, largestAmount, smallestAmount] = isFromAmountLarger
139
+ [smallestToken, largestToken, largestAmount, smallestAmount] = isFromSmallestToken
132
140
  ? [fromToken, toToken, adjustedFromAmount, adjustedToAmount]
133
141
  : [toToken, fromToken, adjustedToAmount, adjustedFromAmount];
134
142
  }
@@ -138,10 +146,8 @@ function getTokensRatioByMinOutputAmountAndTriggerPrice(p) {
138
146
  acceptablePrice = ratio;
139
147
  }
140
148
  else {
141
- const shouldDivide = areBothStablecoins ? true : isFromAmountLarger;
142
- const outputAtTriggerPrice = shouldDivide
143
- ? (adjustedFromAmount * numbers_1.PRECISION) / triggerPrice
144
- : (adjustedFromAmount * triggerPrice) / numbers_1.PRECISION;
149
+ const shouldDivide = areBothStablecoins ? true : isFromSmallestToken;
150
+ const outputAtTriggerPrice = shouldDivide ? outputIfFromIsSmallest : outputIfFromIsLargest;
145
151
  allowedSwapSlippageBps =
146
152
  ((outputAtTriggerPrice - adjustedMinOutputAmount) * factors_1.BASIS_POINTS_DIVISOR_BIGINT) / outputAtTriggerPrice;
147
153
  acceptablePrice = ratio;
@@ -184,6 +190,16 @@ function getTokensRatioByPrice(p) {
184
190
  return { ratio, largestToken, smallestToken };
185
191
  }
186
192
  exports.getTokensRatioByPrice = getTokensRatioByPrice;
193
+ function getTokensRatioByPriceInDirection(p) {
194
+ const { fromToken, toToken, largestTokenAddress } = p;
195
+ const [largestToken, smallestToken] = largestTokenAddress === fromToken.address ? [fromToken, toToken] : [toToken, fromToken];
196
+ return {
197
+ ratio: (largestToken.prices.minPrice * numbers_1.PRECISION) / smallestToken.prices.minPrice,
198
+ largestToken,
199
+ smallestToken,
200
+ };
201
+ }
202
+ exports.getTokensRatioByPriceInDirection = getTokensRatioByPriceInDirection;
187
203
  function getGmToken(chainId, marketTokenAddress) {
188
204
  const stubToken = (0, tokens_1.getToken)(chainId, tokens_1.GM_STUB_ADDRESS);
189
205
  return {
@@ -0,0 +1,152 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const vitest_1 = require("vitest");
4
+ const factors_1 = require("../../../configs/factors");
5
+ const mock_1 = require("../../../test/mock");
6
+ const numbers_1 = require("../../numbers");
7
+ const types_1 = require("../../orders/types");
8
+ const tokens_1 = require("../../tokens");
9
+ const decrease_1 = require("../decrease");
10
+ const decreaseOutputs_1 = require("../decreaseOutputs");
11
+ const tokensData = (0, mock_1.mockTokensData)();
12
+ const usdc = tokensData.USDC;
13
+ const btc = tokensData.BTC;
14
+ // 0.05% position fee and no price impact: closing 50 000 pays 25 of position fees
15
+ const marketInfo = (0, mock_1.mockMarginCheckMarketInfo)(tokensData, {
16
+ positionFeeFactorForBalanceWasImproved: (0, numbers_1.expandDecimals)(5, 26),
17
+ positionFeeFactorForBalanceWasNotImproved: (0, numbers_1.expandDecimals)(5, 26),
18
+ });
19
+ function usd(value) {
20
+ return (BigInt(Math.round(value * 100)) * (0, numbers_1.expandDecimals)(1, factors_1.USD_DECIMALS)) / 100n;
21
+ }
22
+ // a 100 000 short with 6 666.67 USDC of collateral (15x)
23
+ function shortPosition({ pnl, borrowing, funding }) {
24
+ return {
25
+ marketInfo,
26
+ isLong: false,
27
+ sizeInUsd: usd(100000),
28
+ sizeInTokens: (0, tokens_1.convertToTokenAmount)(usd(100000 - pnl), btc.decimals, btc.prices.maxPrice),
29
+ collateralAmount: (0, tokens_1.convertToTokenAmount)(usd(6666.67), usdc.decimals, usdc.prices.minPrice),
30
+ pendingBorrowingFeesUsd: usd(borrowing),
31
+ pendingFundingFeesUsd: usd(funding),
32
+ pendingImpactAmount: 0n,
33
+ };
34
+ }
35
+ (0, vitest_1.it)("values a partial close using remaining pending impact and market balance after the close", () => {
36
+ const existingPosition = {
37
+ ...shortPosition({ pnl: 0, borrowing: 0, funding: 0 }),
38
+ collateralUsd: usd(10000),
39
+ collateralAmount: (0, numbers_1.expandDecimals)(10000, usdc.decimals),
40
+ pendingImpactAmount: -10000000n,
41
+ };
42
+ for (const [longInterest, expectedPrice] of [
43
+ [0, 23480],
44
+ [40000, 23300],
45
+ ]) {
46
+ const marketInfo = (0, mock_1.mockMarginCheckMarketInfo)(tokensData, {
47
+ useV221LiquidationImpact: true,
48
+ useOpenInterestInTokensForBalance: false,
49
+ shortInterestUsd: usd(100000),
50
+ longInterestUsd: usd(longInterest),
51
+ maxPositionImpactFactorNegative: usd(0.1),
52
+ positionFeeFactorForBalanceWasImproved: (0, numbers_1.expandDecimals)(1, 27),
53
+ positionFeeFactorForBalanceWasNotImproved: (0, numbers_1.expandDecimals)(1, 28),
54
+ });
55
+ const preview = (0, decrease_1.getNextPositionValuesForDecreaseTrade)({
56
+ existingPosition,
57
+ marketInfo,
58
+ collateralToken: usdc,
59
+ sizeDeltaUsd: usd(50000),
60
+ sizeDeltaInTokens: existingPosition.sizeInTokens / 2n,
61
+ estimatedPnl: 0n,
62
+ realizedPnl: 0n,
63
+ collateralDeltaUsd: 0n,
64
+ collateralDeltaAmount: 0n,
65
+ payedRemainingCollateralUsd: 0n,
66
+ payedRemainingCollateralAmount: 0n,
67
+ proportionalPendingImpactDeltaUsd: -usd(1000),
68
+ showPnlInLeverage: false,
69
+ isLong: false,
70
+ minCollateralUsd: usd(1),
71
+ userReferralInfo: undefined,
72
+ });
73
+ (0, vitest_1.expect)(preview.nextLiqPrice).toBe(usd(expectedPrice));
74
+ }
75
+ });
76
+ (0, vitest_1.describe)("getDecreasePositionAmounts, TWAP close", () => {
77
+ // closing 50 000 realizes half of the PnL, an equal share per part; the contract charges every pending
78
+ // fee to the first part and pays a part's costs from its profit first, then from the collateral
79
+ vitest_1.it.each([
80
+ { pnl: 3000, borrowing: 1320, funding: 0, keep: true, parts: 5, receive: 1180, fromCollateral: 1025 },
81
+ { pnl: 3000, borrowing: 1320, funding: 0, keep: false, parts: 5, receive: 1180, fromCollateral: 1025 },
82
+ { pnl: 3000, borrowing: 1000, funding: 320, keep: true, parts: 5, receive: 1180, fromCollateral: 1025 },
83
+ { pnl: 3000, borrowing: 1320, funding: 0, keep: true, parts: 2, receive: 737.5, fromCollateral: 582.5 },
84
+ { pnl: 3000, borrowing: 100, funding: 0, keep: true, parts: 5, receive: 1375, fromCollateral: 0 },
85
+ { pnl: 3000, borrowing: 2000, funding: 0, keep: true, parts: 5, receive: 1180, fromCollateral: 1705 },
86
+ { pnl: -1000, borrowing: 1320, funding: 0, keep: true, parts: 5, receive: 0, fromCollateral: 1845 },
87
+ // the parts field is empty while the user types: the estimate falls back to one order
88
+ { pnl: 3000, borrowing: 1320, funding: 0, keep: true, parts: 0, receive: 155, fromCollateral: 0 },
89
+ ])("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 }) => {
90
+ const amounts = (0, decrease_1.getDecreasePositionAmounts)({
91
+ marketInfo,
92
+ collateralToken: usdc,
93
+ isLong: false,
94
+ position: shortPosition({ pnl, borrowing, funding }),
95
+ closeSizeUsd: usd(50000),
96
+ keepLeverage: keep,
97
+ userReferralInfo: undefined,
98
+ minCollateralUsd: usd(1),
99
+ minPositionSizeUsd: usd(1),
100
+ uiFeeFactor: 0n,
101
+ isSetAcceptablePriceImpactEnabled: true,
102
+ isTwap: true,
103
+ numberOfParts: parts,
104
+ });
105
+ (0, vitest_1.expect)(amounts.collateralDeltaAmount).toBe(0n);
106
+ (0, vitest_1.expect)(amounts.receiveUsd).toBe(usd(receive));
107
+ (0, vitest_1.expect)(amounts.payedRemainingCollateralUsd).toBe(usd(fromCollateral));
108
+ });
109
+ // with split receive the profit leaves in BTC unswapped, so the contract pays every cost from the collateral
110
+ (0, vitest_1.it)("offers split receive on a partial close and pays its costs from the collateral TRD-42", () => {
111
+ const position = {
112
+ marketInfo,
113
+ isLong: true,
114
+ sizeInUsd: usd(100000),
115
+ sizeInTokens: (0, tokens_1.convertToTokenAmount)(usd(103000), btc.decimals, btc.prices.minPrice),
116
+ collateralToken: usdc,
117
+ collateralAmount: (0, tokens_1.convertToTokenAmount)(usd(6666.67), usdc.decimals, usdc.prices.minPrice),
118
+ pnlToken: btc,
119
+ pendingBorrowingFeesUsd: usd(1320),
120
+ pendingFundingFeesUsd: 0n,
121
+ pendingImpactAmount: 0n,
122
+ };
123
+ const amounts = (0, decrease_1.getDecreasePositionAmounts)({
124
+ marketInfo,
125
+ collateralToken: usdc,
126
+ isLong: true,
127
+ position,
128
+ closeSizeUsd: usd(50000),
129
+ keepLeverage: true,
130
+ userReferralInfo: undefined,
131
+ minCollateralUsd: usd(1),
132
+ minPositionSizeUsd: usd(1),
133
+ uiFeeFactor: 0n,
134
+ isSetAcceptablePriceImpactEnabled: true,
135
+ isTwap: true,
136
+ numberOfParts: 5,
137
+ forceDecreaseSwapType: types_1.DecreasePositionSwapType.NoSwap,
138
+ });
139
+ const outputs = (0, decreaseOutputs_1.getDecreaseReceiveOutputs)({ decreaseAmounts: amounts, tokensData });
140
+ (0, vitest_1.expect)(amounts.collateralDeltaAmount).toBe(0n);
141
+ (0, vitest_1.expect)(amounts.payedRemainingCollateralUsd).toBe(usd(1345));
142
+ (0, vitest_1.expect)(outputs).toEqual([
143
+ {
144
+ type: "primary",
145
+ token: btc,
146
+ amount: (0, tokens_1.convertToTokenAmount)(usd(1500), btc.decimals, btc.prices.minPrice),
147
+ usd: usd(1500),
148
+ },
149
+ ]);
150
+ (0, vitest_1.expect)((0, decreaseOutputs_1.getIsSplitReceiveAvailable)(position, outputs, { isTwap: true })).toBe(true);
151
+ });
152
+ });
@@ -386,6 +386,49 @@ function positionInfo(marketInfo, sizeInUsd, sizeInTokens, isLong = true) {
386
386
  (0, vitest_1.expect)(close.receiveUsd - position.netValueAfterAllFees).toBeLessThanOrEqual(10n ** 24n);
387
387
  }
388
388
  });
389
+ (0, vitest_1.it)("charges gmsol pending fees to the first TWAP part and withholds the impact beyond the cap", () => {
390
+ const impactBeyondCap = {
391
+ longInterestUsd: 2000n * P,
392
+ shortInterestUsd: 2000n * P,
393
+ positionImpactFactorNegative: P / 50n,
394
+ positionImpactExponentFactorNegative: P,
395
+ maxPositionImpactFactorNegative: P / 100n,
396
+ shortPoolAmount: 10000000n * 10n ** 6n,
397
+ maxPnlFactorForTradersShort: P,
398
+ };
399
+ // a short closes $1,000 of $2,000 in 2 parts; at 90 each part realizes $50 profit, at 100 none.
400
+ // part 1 pays every pending fee, from its own profit first; the impact beyond the cap is $5 a part
401
+ for (const [price, borrowingUsd, fundingAmount, overrides, receiveUsd, fromCollateralUsd] of [
402
+ [90n * P, 80n * P, 0n, {}, 50n * P, 30n * P],
403
+ [90n * P, 0n, 80000000n, {}, 50n * P, 30n * P],
404
+ [100n * P, 0n, 0n, impactBeyondCap, 0n, 20n * P],
405
+ [90n * P, 80n * P, 0n, impactBeyondCap, 40n * P, 40n * P],
406
+ ]) {
407
+ const marketInfo = market({ decimals: 8, minPrice: price, maxPrice: price, tradeMath: "gmsol", overrides });
408
+ const position = {
409
+ ...positionInfo(marketInfo, 2000n * P, 20n * 10n ** 8n, false),
410
+ pendingBorrowingFeesUsd: borrowingUsd,
411
+ fundingFeeAmount: fundingAmount,
412
+ };
413
+ const result = (0, decrease_1.getDecreasePositionAmounts)({
414
+ marketInfo,
415
+ collateralToken: marketInfo.shortToken,
416
+ isLong: false,
417
+ position,
418
+ closeSizeUsd: 1000n * P,
419
+ keepLeverage: false,
420
+ userReferralInfo: undefined,
421
+ minCollateralUsd: 0n,
422
+ minPositionSizeUsd: 0n,
423
+ uiFeeFactor: 0n,
424
+ isSetAcceptablePriceImpactEnabled: false,
425
+ forceDecreaseSwapType: types_1.DecreasePositionSwapType.NoSwap,
426
+ isTwap: true,
427
+ numberOfParts: 2,
428
+ });
429
+ (0, vitest_1.expect)([result.receiveUsd, result.payedRemainingCollateralUsd]).toEqual([receiveUsd, fromCollateralUsd]);
430
+ }
431
+ });
389
432
  (0, vitest_1.it)("rejects gmsol increases that fill no index token atoms FESOL-57", () => {
390
433
  const imbalanced = {
391
434
  longInterestUsd: 1000n * P,