@gmx-io/sdk 1.1.2 → 1.2.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 (128) hide show
  1. package/build/cjs/src/abis/ClaimHandler.json +439 -0
  2. package/build/cjs/src/abis/StBTC.json +1225 -0
  3. package/build/cjs/src/abis/SyntheticsReader.json +480 -19
  4. package/build/cjs/src/abis/index.js +4 -0
  5. package/build/cjs/src/configs/__tests__/markets.spec.js +1 -1
  6. package/build/cjs/src/configs/__tests__/tokens.spec.js +2 -1
  7. package/build/cjs/src/configs/batch.js +12 -0
  8. package/build/cjs/src/configs/chains.js +57 -6
  9. package/build/cjs/src/configs/contracts.js +66 -68
  10. package/build/cjs/src/configs/dataStore.js +14 -3
  11. package/build/cjs/src/configs/express.js +4 -2
  12. package/build/cjs/src/configs/markets.js +72 -0
  13. package/build/cjs/src/configs/oracleKeeper.js +19 -34
  14. package/build/cjs/src/configs/tokens.js +185 -1
  15. package/build/cjs/src/index.js +3 -3
  16. package/build/cjs/src/modules/orders/helpers.js +21 -13
  17. package/build/cjs/src/modules/orders/helpers.spec.js +1 -1
  18. package/build/cjs/src/modules/orders/orders.js +3 -3
  19. package/build/cjs/src/modules/positions/positions.js +9 -0
  20. package/build/cjs/src/modules/utils/utils.js +3 -3
  21. package/build/cjs/src/prebuilt/hashedKinkModelMarketRatesKeys.json +82 -0
  22. package/build/cjs/src/prebuilt/hashedMarketConfigKeys.json +512 -0
  23. package/build/cjs/src/prebuilt/hashedMarketValuesKeys.json +152 -0
  24. package/build/cjs/src/types/subsquid.js +193 -1
  25. package/build/cjs/src/types/swapStrategy.js +2 -0
  26. package/build/cjs/src/types/trade.js +1 -0
  27. package/build/cjs/src/utils/__tests__/numbers.spec.js +17 -9
  28. package/build/cjs/src/utils/__tests__/orderTransactions/decreaseOrders.spec.js +2 -0
  29. package/build/cjs/src/utils/__tests__/orderTransactions/exchangeRouterMulticall.spec.js +2 -0
  30. package/build/cjs/src/utils/__tests__/orderTransactions/increaseOrders.spec.js +4 -0
  31. package/build/cjs/src/utils/__tests__/orderTransactions/swapOrders.spec.js +1 -0
  32. package/build/cjs/src/utils/__tests__/prices.spec.js +3 -2
  33. package/build/cjs/src/utils/__tests__/uiFeeReceiver.spec.js +19 -0
  34. package/build/cjs/src/utils/errors/transactionsErrors.js +9 -2
  35. package/build/cjs/src/utils/fees/executionFee.js +9 -1
  36. package/build/cjs/src/utils/numbers.js +52 -34
  37. package/build/cjs/src/utils/orderTransactions.js +3 -1
  38. package/build/cjs/src/utils/orders.js +8 -2
  39. package/build/cjs/src/utils/prices.js +1 -1
  40. package/build/cjs/src/utils/swap/botanixStaking.js +90 -0
  41. package/build/cjs/src/utils/swap/buildSwapStrategy.js +224 -0
  42. package/build/cjs/src/utils/swap/externalSwapPath.js +41 -0
  43. package/build/cjs/src/utils/swap/externalSwapQuoteByPath.js +27 -0
  44. package/build/cjs/src/utils/swap/swapValues.js +288 -9
  45. package/build/cjs/src/utils/tokens.js +10 -1
  46. package/build/cjs/src/utils/trade/amounts.js +89 -41
  47. package/build/cjs/src/utils/trade/trade.js +2 -2
  48. package/build/cjs/src/utils/twap/uiFeeReceiver.js +26 -6
  49. package/build/esm/src/abis/ClaimHandler.json +439 -0
  50. package/build/esm/src/abis/StBTC.json +1225 -0
  51. package/build/esm/src/abis/SyntheticsReader.json +480 -19
  52. package/build/esm/src/abis/index.js +4 -0
  53. package/build/esm/src/configs/__tests__/markets.spec.js +1 -1
  54. package/build/esm/src/configs/__tests__/tokens.spec.js +3 -2
  55. package/build/esm/src/configs/batch.js +13 -1
  56. package/build/esm/src/configs/chains.js +56 -5
  57. package/build/esm/src/configs/contracts.js +67 -69
  58. package/build/esm/src/configs/dataStore.js +9 -0
  59. package/build/esm/src/configs/express.js +5 -3
  60. package/build/esm/src/configs/markets.js +73 -1
  61. package/build/esm/src/configs/oracleKeeper.js +18 -29
  62. package/build/esm/src/configs/tokens.js +186 -2
  63. package/build/esm/src/index.js +3 -3
  64. package/build/esm/src/modules/orders/helpers.js +21 -13
  65. package/build/esm/src/modules/orders/helpers.spec.js +1 -1
  66. package/build/esm/src/modules/orders/orders.js +3 -3
  67. package/build/esm/src/modules/positions/positions.js +9 -0
  68. package/build/esm/src/modules/utils/utils.js +3 -3
  69. package/build/esm/src/prebuilt/hashedKinkModelMarketRatesKeys.json +82 -0
  70. package/build/esm/src/prebuilt/hashedMarketConfigKeys.json +512 -0
  71. package/build/esm/src/prebuilt/hashedMarketValuesKeys.json +152 -0
  72. package/build/esm/src/types/subsquid.js +192 -0
  73. package/build/esm/src/types/swapStrategy.js +1 -0
  74. package/build/esm/src/types/trade.js +1 -0
  75. package/build/esm/src/utils/__tests__/numbers.spec.js +18 -10
  76. package/build/esm/src/utils/__tests__/orderTransactions/decreaseOrders.spec.js +2 -0
  77. package/build/esm/src/utils/__tests__/orderTransactions/exchangeRouterMulticall.spec.js +2 -0
  78. package/build/esm/src/utils/__tests__/orderTransactions/increaseOrders.spec.js +4 -0
  79. package/build/esm/src/utils/__tests__/orderTransactions/swapOrders.spec.js +1 -0
  80. package/build/esm/src/utils/__tests__/prices.spec.js +3 -2
  81. package/build/esm/src/utils/__tests__/uiFeeReceiver.spec.js +20 -1
  82. package/build/esm/src/utils/errors/transactionsErrors.js +9 -2
  83. package/build/esm/src/utils/fees/executionFee.js +11 -3
  84. package/build/esm/src/utils/numbers.js +50 -31
  85. package/build/esm/src/utils/orderTransactions.js +3 -1
  86. package/build/esm/src/utils/orders.js +8 -2
  87. package/build/esm/src/utils/prices.js +1 -1
  88. package/build/esm/src/utils/swap/botanixStaking.js +83 -0
  89. package/build/esm/src/utils/swap/buildSwapStrategy.js +219 -0
  90. package/build/esm/src/utils/swap/externalSwapPath.js +37 -0
  91. package/build/esm/src/utils/swap/externalSwapQuoteByPath.js +23 -0
  92. package/build/esm/src/utils/swap/swapValues.js +287 -8
  93. package/build/esm/src/utils/tokens.js +7 -0
  94. package/build/esm/src/utils/trade/amounts.js +89 -41
  95. package/build/esm/src/utils/trade/trade.js +2 -2
  96. package/build/esm/src/utils/twap/uiFeeReceiver.js +24 -5
  97. package/build/types/src/abis/index.d.ts +1 -1
  98. package/build/types/src/configs/batch.d.ts +2 -1
  99. package/build/types/src/configs/chains.d.ts +20 -37
  100. package/build/types/src/configs/contracts.d.ts +62 -63
  101. package/build/types/src/configs/dataStore.d.ts +5 -0
  102. package/build/types/src/configs/express.d.ts +1 -0
  103. package/build/types/src/configs/markets.d.ts +2 -1
  104. package/build/types/src/configs/oracleKeeper.d.ts +2 -3
  105. package/build/types/src/configs/tokens.d.ts +1 -0
  106. package/build/types/src/index.d.ts +1 -1
  107. package/build/types/src/modules/base.d.ts +1 -1
  108. package/build/types/src/modules/orders/helpers.d.ts +10 -2
  109. package/build/types/src/modules/orders/orders.d.ts +10 -1
  110. package/build/types/src/types/orders.d.ts +1 -1
  111. package/build/types/src/types/sdk.d.ts +2 -1
  112. package/build/types/src/types/subsquid.d.ts +691 -0
  113. package/build/types/src/types/swapStrategy.d.ts +33 -0
  114. package/build/types/src/types/tokens.d.ts +6 -0
  115. package/build/types/src/types/trade.d.ts +19 -4
  116. package/build/types/src/utils/multicall.d.ts +1 -1
  117. package/build/types/src/utils/numbers.d.ts +8 -3
  118. package/build/types/src/utils/orderTransactions.d.ts +2 -3
  119. package/build/types/src/utils/prices.d.ts +1 -1
  120. package/build/types/src/utils/swap/botanixStaking.d.ts +11 -0
  121. package/build/types/src/utils/swap/buildSwapStrategy.d.ts +22 -0
  122. package/build/types/src/utils/swap/externalSwapPath.d.ts +13 -0
  123. package/build/types/src/utils/swap/externalSwapQuoteByPath.d.ts +6 -0
  124. package/build/types/src/utils/swap/swapValues.d.ts +10 -3
  125. package/build/types/src/utils/tokens.d.ts +2 -0
  126. package/build/types/src/utils/trade/amounts.d.ts +5 -2
  127. package/build/types/src/utils/twap/uiFeeReceiver.d.ts +13 -0
  128. package/package.json +1 -1
@@ -16,16 +16,23 @@ const TX_ERROR_PATTERNS = {
16
16
  [TxErrorType.UserDenied]: [
17
17
  { msg: "User denied transaction signature" },
18
18
  { msg: "User rejected" },
19
+ { msg: "User cancelled" },
20
+ { msg: "Cancelled" },
21
+ { msg: "Cancelled by user" },
19
22
  { msg: "user rejected action" },
20
23
  { msg: "ethers-user-denied" },
21
- { msg: "User canceled" },
24
+ { msg: "Action cancelled by user" },
22
25
  { msg: "Signing aborted by user" },
23
26
  ],
24
27
  [TxErrorType.Slippage]: [
25
28
  { msg: "Router: mark price lower than limit" },
26
29
  { msg: "Router: mark price higher than limit" },
27
30
  ],
28
- [TxErrorType.NetworkChanged]: [{ msg: "network changed" }, { msg: "Invalid network" }],
31
+ [TxErrorType.NetworkChanged]: [
32
+ { msg: "network changed" },
33
+ { msg: "Invalid network" },
34
+ { msg: "chainId should be same" },
35
+ ],
29
36
  [TxErrorType.Expired]: [{ msg: "Request expired" }],
30
37
  [TxErrorType.RpcError]: [
31
38
  // @see https://eips.ethereum.org/EIPS/eip-1474#error-codes
@@ -1,9 +1,10 @@
1
- import { getExcessiveExecutionFee, getHighExecutionFee } from "../../configs/chains";
1
+ import { getExcessiveExecutionFee, getHighExecutionFee, MIN_EXECUTION_FEE_USD } from "../../configs/chains";
2
2
  import { USD_DECIMALS } from "../../configs/factors";
3
3
  import { NATIVE_TOKEN_ADDRESS } from "../../configs/tokens";
4
4
  import { DecreasePositionSwapType } from "../../types/orders";
5
+ import { bigMath } from "../bigmath";
5
6
  import { applyFactor, expandDecimals } from "../numbers";
6
- import { convertBetweenTokens, convertToUsd, getTokenData } from "../tokens";
7
+ import { convertBetweenTokens, convertToTokenAmount, convertToUsd, getTokenData } from "../tokens";
7
8
  export function getExecutionFee(chainId, gasLimits,
8
9
  // TODO optimize we only need the native token data
9
10
  tokensData, estimatedGasLimit, gasPrice, oraclePriceCount, numberOfParts) {
@@ -16,7 +17,14 @@ tokensData, estimatedGasLimit, gasPrice, oraclePriceCount, numberOfParts) {
16
17
  const multiplierFactor = gasLimits.estimatedFeeMultiplierFactor;
17
18
  const gasLimit = baseGasLimit + applyFactor(estimatedGasLimit, multiplierFactor);
18
19
  // #endregion
19
- const feeTokenAmount = gasLimit * gasPrice * BigInt(numberOfParts ?? 1);
20
+ // avoid botanix gas spikes when chain is not actively used
21
+ const minGasCostUsd = MIN_EXECUTION_FEE_USD[chainId];
22
+ const minGasCost = convertToTokenAmount(minGasCostUsd, nativeToken.decimals, nativeToken.prices.minPrice);
23
+ let feeTokenAmountPerExecution = gasLimit * gasPrice;
24
+ if (minGasCost) {
25
+ feeTokenAmountPerExecution = bigMath.max(feeTokenAmountPerExecution, minGasCost);
26
+ }
27
+ const feeTokenAmount = feeTokenAmountPerExecution * BigInt(numberOfParts ?? 1);
20
28
  const feeUsd = convertToUsd(feeTokenAmount, nativeToken.decimals, nativeToken.prices.minPrice);
21
29
  const isFeeHigh = feeUsd > expandDecimals(getHighExecutionFee(chainId), USD_DECIMALS);
22
30
  const isFeeVeryHigh = feeUsd > expandDecimals(getExcessiveExecutionFee(chainId), USD_DECIMALS);
@@ -127,7 +127,8 @@ export function formatPercentage(percentage, opts = {}) {
127
127
  return `${sign}${formatAmount(bigMath.abs(percentage), bps ? 2 : PERCENT_PRECISION_DECIMALS, displayDecimals)}%`;
128
128
  }
129
129
  export function formatTokenAmount(amount, tokenDecimals, symbol, opts = {}) {
130
- const { displayDecimals = 4, showAllSignificant = false, fallbackToZero = false, useCommas = false, minThreshold = "0", maxThreshold, } = opts;
130
+ const { showAllSignificant = false, fallbackToZero = false, useCommas = false, minThreshold = "0", maxThreshold, } = opts;
131
+ const displayDecimals = opts.displayDecimals ?? (opts.isStable ? 2 : 4);
131
132
  const symbolStr = symbol ? ` ${symbol}` : "";
132
133
  if (typeof amount !== "bigint" || !tokenDecimals) {
133
134
  if (fallbackToZero) {
@@ -147,7 +148,7 @@ export function formatTokenAmount(amount, tokenDecimals, symbol, opts = {}) {
147
148
  else {
148
149
  const exceedingInfo = getLimitedDisplay(amount, tokenDecimals, { maxThreshold, minThreshold });
149
150
  const symbol = exceedingInfo.symbol ? `${exceedingInfo.symbol} ` : "";
150
- amountStr = `${symbol}${sign}${formatAmount(exceedingInfo.value, tokenDecimals, displayDecimals, useCommas)}`;
151
+ amountStr = `${symbol}${sign}${formatAmount(exceedingInfo.value, tokenDecimals, displayDecimals, useCommas, undefined)}`;
151
152
  }
152
153
  return `${amountStr}${symbolStr}`;
153
154
  }
@@ -223,14 +224,20 @@ export function formatAmountHuman(amount, tokenDecimals, showDollar = false, dis
223
224
  }
224
225
  return `${isNegative ? "-" : ""}${sign}${absN.toFixed(displayDecimals)}`;
225
226
  }
226
- export function formatBalanceAmount(amount, tokenDecimals, tokenSymbol, showZero = false, toExponential = true) {
227
+ export function formatBalanceAmount(amount, tokenDecimals, tokenSymbol, { showZero = false, toExponential = true, isStable = false, } = {}) {
227
228
  if (amount === undefined)
228
229
  return "-";
229
230
  if (amount === 0n) {
230
231
  if (showZero === true) {
231
232
  if (tokenSymbol) {
233
+ if (isStable) {
234
+ return `0.00 ${tokenSymbol}`;
235
+ }
232
236
  return `0.0000 ${tokenSymbol}`;
233
237
  }
238
+ if (isStable) {
239
+ return "0.00";
240
+ }
234
241
  return "0.0000";
235
242
  }
236
243
  return "-";
@@ -238,14 +245,15 @@ export function formatBalanceAmount(amount, tokenDecimals, tokenSymbol, showZero
238
245
  const absAmount = bigMath.abs(amount);
239
246
  const absAmountFloat = bigintToNumber(absAmount, tokenDecimals);
240
247
  let value = "";
248
+ const baseDecimals = isStable ? 2 : 4;
241
249
  if (absAmountFloat >= 1)
242
- value = formatAmount(amount, tokenDecimals, 4, true);
250
+ value = formatAmount(amount, tokenDecimals, baseDecimals, true);
243
251
  else if (absAmountFloat >= 0.1)
244
- value = formatAmount(amount, tokenDecimals, 5, true);
252
+ value = formatAmount(amount, tokenDecimals, baseDecimals + 1, true);
245
253
  else if (absAmountFloat >= 0.01)
246
- value = formatAmount(amount, tokenDecimals, 6, true);
254
+ value = formatAmount(amount, tokenDecimals, baseDecimals + 2, true);
247
255
  else if (absAmountFloat >= 0.001)
248
- value = formatAmount(amount, tokenDecimals, 7, true);
256
+ value = formatAmount(amount, tokenDecimals, baseDecimals + 3, true);
249
257
  else if (absAmountFloat >= 1e-8)
250
258
  value = formatAmount(amount, tokenDecimals, 8, true);
251
259
  else {
@@ -262,15 +270,6 @@ export function formatBalanceAmount(amount, tokenDecimals, tokenSymbol, showZero
262
270
  }
263
271
  return value;
264
272
  }
265
- export function formatBalanceAmountWithUsd(amount, amountUsd, tokenDecimals, tokenSymbol, showZero = false) {
266
- if (showZero === false && amount === 0n) {
267
- return "-";
268
- }
269
- const value = formatBalanceAmount(amount, tokenDecimals, tokenSymbol, showZero);
270
- const usd = formatUsd(amountUsd);
271
- // Regular space
272
- return `${value} (${usd})`;
273
- }
274
273
  export function formatFactor(factor) {
275
274
  if (factor == 0n) {
276
275
  return "0";
@@ -542,26 +541,46 @@ export function deserializeBigIntsInObject(obj) {
542
541
  }
543
542
  return result;
544
543
  }
545
- export function calculateDisplayDecimals(price, decimals = USD_DECIMALS, visualMultiplier = 1) {
544
+ export function calculateDisplayDecimals(price, decimals = USD_DECIMALS, visualMultiplier = 1, isStable = false) {
546
545
  if (price === undefined || price === 0n)
547
546
  return 2;
548
547
  const priceNumber = bigintToNumber(bigMath.abs(price) * BigInt(visualMultiplier), decimals);
549
548
  if (isNaN(priceNumber))
550
549
  return 2;
551
- if (priceNumber >= 1000)
552
- return 2;
553
- if (priceNumber >= 100)
554
- return 3;
555
- if (priceNumber >= 1)
556
- return 4;
557
- if (priceNumber >= 0.1)
558
- return 5;
559
- if (priceNumber >= 0.01)
560
- return 6;
561
- if (priceNumber >= 0.0001)
562
- return 7;
563
- if (priceNumber >= 0.00001)
564
- return 8;
550
+ if (isStable) {
551
+ if (priceNumber >= 0.1)
552
+ return 2;
553
+ if (priceNumber >= 0.01)
554
+ return 3;
555
+ if (priceNumber >= 0.001)
556
+ return 4;
557
+ if (priceNumber >= 0.0001)
558
+ return 5;
559
+ if (priceNumber >= 0.00001)
560
+ return 6;
561
+ if (priceNumber >= 0.000001)
562
+ return 7;
563
+ if (priceNumber >= 0.0000001)
564
+ return 8;
565
+ if (priceNumber >= 0.00000001)
566
+ return 9;
567
+ }
568
+ else {
569
+ if (priceNumber >= 1000)
570
+ return 2;
571
+ if (priceNumber >= 100)
572
+ return 3;
573
+ if (priceNumber >= 1)
574
+ return 4;
575
+ if (priceNumber >= 0.1)
576
+ return 5;
577
+ if (priceNumber >= 0.01)
578
+ return 6;
579
+ if (priceNumber >= 0.0001)
580
+ return 7;
581
+ if (priceNumber >= 0.00001)
582
+ return 8;
583
+ }
565
584
  return 9;
566
585
  }
567
586
  export function clamp(value, min, max) {
@@ -171,6 +171,9 @@ export function buildTwapOrdersPayloads(p, twapParams) {
171
171
  referralCode: params.referralCode,
172
172
  autoCancel: params.autoCancel,
173
173
  allowedSlippage: 0,
174
+ ...(params.expectedOutputAmount !== undefined && {
175
+ expectedOutputAmount: params.expectedOutputAmount / BigInt(twapParams.numberOfParts),
176
+ }),
174
177
  payTokenAmount: params.payTokenAmount / BigInt(twapParams.numberOfParts),
175
178
  executionFeeAmount: params.executionFeeAmount / BigInt(twapParams.numberOfParts),
176
179
  validFromTime: getTwapValidFromTime(twapParams.duration, twapParams.numberOfParts, i),
@@ -361,7 +364,6 @@ export function buildTokenTransfersParamsForIncreaseOrSwap({ chainId, receiver,
361
364
  * */
362
365
  initialCollateralTokenAddress = convertTokenAddress(chainId, externalSwapQuote.outTokenAddress, "wrapped");
363
366
  initialCollateralDeltaAmount = 0n;
364
- swapPath = [];
365
367
  externalCalls = getExternalCallsPayload({
366
368
  chainId,
367
369
  account: receiver,
@@ -158,7 +158,10 @@ export function getOrderInfo(p) {
158
158
  shouldApplyPriceImpact: true,
159
159
  isAtomicSwap: false,
160
160
  });
161
- const triggerThresholdType = getOrderThresholdType(order.orderType, order.isLong);
161
+ let triggerThresholdType;
162
+ if (!isMarketOrderType(order.orderType)) {
163
+ triggerThresholdType = getOrderThresholdType(order.orderType, order.isLong);
164
+ }
162
165
  const orderInfo = {
163
166
  ...order,
164
167
  swapPathStats,
@@ -176,7 +179,10 @@ export function getOrderInfo(p) {
176
179
  }
177
180
  }
178
181
  export function isVisibleOrder(orderType) {
179
- return isLimitOrderType(orderType) || isTriggerDecreaseOrderType(orderType) || isLimitSwapOrderType(orderType);
182
+ return (isLimitOrderType(orderType) ||
183
+ isTriggerDecreaseOrderType(orderType) ||
184
+ isLimitSwapOrderType(orderType) ||
185
+ isMarketOrderType(orderType));
180
186
  }
181
187
  export function isOrderForPosition(order, positionKey) {
182
188
  const { account, marketAddress, collateralAddress, isLong } = parsePositionKey(positionKey);
@@ -33,7 +33,7 @@ export function getOrderThresholdType(orderType, isLong) {
33
33
  if (orderType === OrderType.StopLossDecrease) {
34
34
  return isLong ? TriggerThresholdType.Below : TriggerThresholdType.Above;
35
35
  }
36
- throw new Error("Invalid trigger order type");
36
+ return undefined;
37
37
  }
38
38
  export function getAcceptablePriceInfo(p) {
39
39
  const { marketInfo, isIncrease, isLong, indexPrice, sizeDeltaUsd, maxNegativePriceImpactBps } = p;
@@ -0,0 +1,83 @@
1
+ import { encodeFunctionData } from "viem";
2
+ import StBTCABI from "../../abis/StBTC.json";
3
+ import { BOTANIX } from "../../configs/chains";
4
+ import { getContract } from "../../configs/contracts";
5
+ import { ExternalSwapAggregator } from "../../types/trade";
6
+ import { bigMath } from "../bigmath";
7
+ import { BASIS_POINTS_DIVISOR_BIGINT, getBasisPoints } from "../numbers";
8
+ import { AVAILABLE_BOTANIX_DEPOSIT_PAIRS, AVAILABLE_BOTANIX_WITHDRAW_PAIRS } from "./externalSwapPath";
9
+ import { convertToUsd, getMidPrice, getTokenData } from "../tokens";
10
+ const COEF_REDUCER = getBasisPoints(1n, 10000n);
11
+ export const getBotanixStakingExternalSwapQuote = ({ tokenInAddress, tokenOutAddress, amountIn, gasPrice, receiverAddress, tokensData, assetsPerShare, }) => {
12
+ const inTokenData = getTokenData(tokensData, tokenInAddress);
13
+ const outTokenData = getTokenData(tokensData, tokenOutAddress);
14
+ const assetsPerShareRate = getBasisPoints(assetsPerShare, 10n ** 18n) - COEF_REDUCER;
15
+ const sharesPerAssetRate = getBasisPoints(10n ** 18n, assetsPerShare) - COEF_REDUCER;
16
+ if (!inTokenData || !outTokenData) {
17
+ return undefined;
18
+ }
19
+ if (AVAILABLE_BOTANIX_DEPOSIT_PAIRS.some((pair) => pair.from === tokenInAddress && pair.to === tokenOutAddress)) {
20
+ const priceIn = getMidPrice(inTokenData.prices);
21
+ const priceOut = bigMath.mulDiv(priceIn, sharesPerAssetRate, BASIS_POINTS_DIVISOR_BIGINT);
22
+ const usdIn = convertToUsd(amountIn, inTokenData.decimals, priceIn);
23
+ const amountOut = amountIn > 0n ? bigMath.mulDiv(amountIn, sharesPerAssetRate, BASIS_POINTS_DIVISOR_BIGINT) - gasPrice : 0n;
24
+ const usdOut = amountOut > 0n ? convertToUsd(amountOut, outTokenData.decimals, priceOut) : 0n;
25
+ return {
26
+ aggregator: ExternalSwapAggregator.BotanixStaking,
27
+ inTokenAddress: tokenInAddress,
28
+ outTokenAddress: tokenOutAddress,
29
+ receiver: receiverAddress,
30
+ amountIn,
31
+ amountOut,
32
+ usdIn: usdIn,
33
+ usdOut: usdOut,
34
+ priceIn,
35
+ priceOut,
36
+ feesUsd: gasPrice,
37
+ needSpenderApproval: true,
38
+ txnData: {
39
+ to: getContract(BOTANIX, "StBTC"),
40
+ data: encodeFunctionData({
41
+ abi: StBTCABI.abi,
42
+ functionName: "deposit",
43
+ args: [amountIn, receiverAddress],
44
+ }),
45
+ value: 0n,
46
+ estimatedGas: gasPrice,
47
+ estimatedExecutionFee: gasPrice,
48
+ },
49
+ };
50
+ }
51
+ if (AVAILABLE_BOTANIX_WITHDRAW_PAIRS.some((pair) => pair.from === tokenInAddress && pair.to === tokenOutAddress)) {
52
+ const priceIn = getMidPrice(inTokenData.prices);
53
+ const priceOut = bigMath.mulDiv(priceIn, assetsPerShareRate, BASIS_POINTS_DIVISOR_BIGINT);
54
+ const usdIn = convertToUsd(amountIn, inTokenData.decimals, priceIn);
55
+ const amountOut = amountIn > 0n ? bigMath.mulDiv(amountIn, assetsPerShareRate, BASIS_POINTS_DIVISOR_BIGINT) - gasPrice : 0n;
56
+ const usdOut = amountOut > 0n ? convertToUsd(amountOut, outTokenData.decimals, priceOut) : 0n;
57
+ return {
58
+ aggregator: ExternalSwapAggregator.BotanixStaking,
59
+ inTokenAddress: tokenInAddress,
60
+ outTokenAddress: tokenOutAddress,
61
+ receiver: receiverAddress,
62
+ amountIn,
63
+ amountOut,
64
+ usdIn: usdIn,
65
+ usdOut: usdOut,
66
+ priceIn,
67
+ priceOut,
68
+ feesUsd: gasPrice,
69
+ needSpenderApproval: true,
70
+ txnData: {
71
+ to: getContract(BOTANIX, "StBTC"),
72
+ data: encodeFunctionData({
73
+ abi: StBTCABI.abi,
74
+ functionName: "withdraw",
75
+ args: [amountIn, receiverAddress, getContract(BOTANIX, "ExternalHandler")],
76
+ }),
77
+ value: 0n,
78
+ estimatedGas: gasPrice,
79
+ estimatedExecutionFee: gasPrice,
80
+ },
81
+ };
82
+ }
83
+ };
@@ -0,0 +1,219 @@
1
+ import { bigMath } from "../bigmath";
2
+ import { convertToTokenAmount, convertToUsd, getIsEquivalentTokens, getIsStake, getIsUnstake, getMidPrice, } from "../tokens";
3
+ import { getAvailableExternalSwapPaths } from "./externalSwapPath";
4
+ import { getExternalSwapQuoteByPath } from "./externalSwapQuoteByPath";
5
+ import { createFindSwapPath } from "./swapPath";
6
+ /*
7
+ Order/Priority of getting swap strategy:
8
+ 1. Check if it needs a swap and return noSwap if tokens are equivalent, stake or unstake [noSwap]
9
+ 2. Check if there is a swap path stats for the internal swap quote and return internalSwap if there is [internalSwap]
10
+ 3. Check if there is a combined swap strategy and return combinedSwap if there is [combinedSwap]
11
+ 4. Return defaultSwapStrategy (noSwap) if there is no other swap strategy [noSwap]
12
+ */
13
+ export function buildSwapStrategy({ amountIn, tokenIn, tokenOut, marketsInfoData, chainId, swapOptimizationOrder, externalSwapQuoteParams, }) {
14
+ const priceIn = tokenIn.prices.minPrice;
15
+ const usdIn = convertToUsd(amountIn, tokenIn.decimals, priceIn);
16
+ if (amountIn < 0n) {
17
+ amountIn = 0n;
18
+ }
19
+ const defaultSwapStrategy = {
20
+ type: "noSwap",
21
+ externalSwapQuote: undefined,
22
+ swapPathStats: undefined,
23
+ amountIn,
24
+ amountOut: convertToTokenAmount(usdIn, tokenOut.decimals, tokenOut.prices.maxPrice),
25
+ usdIn,
26
+ usdOut: usdIn,
27
+ priceIn,
28
+ priceOut: tokenOut.prices.maxPrice,
29
+ feesUsd: 0n,
30
+ };
31
+ if (getIsEquivalentTokens(tokenIn, tokenOut) || getIsStake(tokenIn, tokenOut) || getIsUnstake(tokenIn, tokenOut)) {
32
+ return defaultSwapStrategy;
33
+ }
34
+ const findSwapPath = createFindSwapPath({
35
+ chainId,
36
+ fromTokenAddress: tokenIn.address,
37
+ toTokenAddress: tokenOut.address,
38
+ marketsInfoData,
39
+ isExpressFeeSwap: false,
40
+ });
41
+ const swapPathStats = findSwapPath(usdIn, { order: swapOptimizationOrder });
42
+ if (swapPathStats) {
43
+ return {
44
+ type: "internalSwap",
45
+ swapPathStats,
46
+ externalSwapQuote: undefined,
47
+ amountIn,
48
+ amountOut: swapPathStats.amountOut,
49
+ usdIn: usdIn,
50
+ usdOut: swapPathStats.usdOut,
51
+ priceIn: priceIn,
52
+ priceOut: tokenOut.prices.maxPrice,
53
+ feesUsd: usdIn - swapPathStats.usdOut,
54
+ };
55
+ }
56
+ const availableExternalSwapPaths = getAvailableExternalSwapPaths({ chainId, fromTokenAddress: tokenIn.address });
57
+ const suitableSwapPath = availableExternalSwapPaths.find((path) => {
58
+ const findSwapPath = createFindSwapPath({
59
+ chainId,
60
+ fromTokenAddress: path.outTokenAddress,
61
+ toTokenAddress: tokenOut.address,
62
+ marketsInfoData,
63
+ isExpressFeeSwap: false,
64
+ });
65
+ const swapPathStats = findSwapPath(usdIn);
66
+ return Boolean(swapPathStats);
67
+ });
68
+ if (suitableSwapPath && suitableSwapPath.outTokenAddress !== tokenOut.address) {
69
+ const externalSwapQuoteForCombinedSwap = getExternalSwapQuoteByPath({
70
+ amountIn,
71
+ externalSwapPath: suitableSwapPath,
72
+ externalSwapQuoteParams,
73
+ });
74
+ const findSwapPathForSuitableSwapPath = createFindSwapPath({
75
+ chainId,
76
+ fromTokenAddress: suitableSwapPath.outTokenAddress,
77
+ toTokenAddress: tokenOut.address,
78
+ marketsInfoData,
79
+ isExpressFeeSwap: false,
80
+ });
81
+ const swapPathStatsForCombinedSwap = externalSwapQuoteForCombinedSwap
82
+ ? findSwapPathForSuitableSwapPath(externalSwapQuoteForCombinedSwap.usdOut)
83
+ : undefined;
84
+ return externalSwapQuoteForCombinedSwap && swapPathStatsForCombinedSwap
85
+ ? {
86
+ type: "combinedSwap",
87
+ externalSwapQuote: externalSwapQuoteForCombinedSwap,
88
+ swapPathStats: swapPathStatsForCombinedSwap,
89
+ amountIn,
90
+ amountOut: swapPathStatsForCombinedSwap.amountOut,
91
+ usdIn: externalSwapQuoteForCombinedSwap.usdIn,
92
+ usdOut: swapPathStatsForCombinedSwap.usdOut,
93
+ priceIn: externalSwapQuoteForCombinedSwap.priceIn,
94
+ priceOut: tokenOut.prices.maxPrice,
95
+ feesUsd: externalSwapQuoteForCombinedSwap.usdIn - swapPathStatsForCombinedSwap.usdOut,
96
+ }
97
+ : defaultSwapStrategy;
98
+ }
99
+ return defaultSwapStrategy;
100
+ }
101
+ // Used for getting swap amounts by to value
102
+ export function buildReverseSwapStrategy({ amountOut, tokenIn, tokenOut, marketsInfoData, chainId, externalSwapQuoteParams, swapOptimizationOrder, }) {
103
+ const priceIn = getMidPrice(tokenIn.prices);
104
+ const priceOut = getMidPrice(tokenOut.prices);
105
+ const preferredUsdOut = convertToUsd(amountOut, tokenOut.decimals, getMidPrice(tokenOut.prices));
106
+ const approximateAmountIn = convertToTokenAmount(preferredUsdOut, tokenIn.decimals, getMidPrice(tokenIn.prices));
107
+ const approximateUsdIn = preferredUsdOut;
108
+ const defaultSwapStrategy = {
109
+ type: "noSwap",
110
+ externalSwapQuote: undefined,
111
+ swapPathStats: undefined,
112
+ amountIn: approximateAmountIn,
113
+ amountOut: amountOut,
114
+ usdIn: approximateUsdIn,
115
+ usdOut: preferredUsdOut,
116
+ priceIn,
117
+ priceOut,
118
+ feesUsd: 0n,
119
+ };
120
+ if (getIsEquivalentTokens(tokenIn, tokenOut) || getIsStake(tokenIn, tokenOut) || getIsUnstake(tokenIn, tokenOut)) {
121
+ return defaultSwapStrategy;
122
+ }
123
+ const findSwapPath = createFindSwapPath({
124
+ chainId,
125
+ fromTokenAddress: tokenIn.address,
126
+ toTokenAddress: tokenOut.address,
127
+ marketsInfoData,
128
+ isExpressFeeSwap: false,
129
+ });
130
+ const approximateSwapPathStats = findSwapPath(approximateUsdIn, { order: swapOptimizationOrder });
131
+ if (approximateSwapPathStats) {
132
+ // Increase or decrease usdIn the same way preferred usdOut is different from swapStrategy.usdOut
133
+ // preferred_in / approximate_in = preferred_out / approximate_out
134
+ // preferred_in = approximate_in * preferred_out / approximate_out
135
+ const adjustedUsdIn = approximateSwapPathStats.usdOut > 0
136
+ ? bigMath.mulDiv(approximateUsdIn, preferredUsdOut, approximateSwapPathStats.usdOut)
137
+ : 0n;
138
+ const adjustedAmountIn = convertToTokenAmount(adjustedUsdIn, tokenIn.decimals, getMidPrice(tokenIn.prices));
139
+ const adjustedSwapPathStats = findSwapPath(adjustedUsdIn, { order: swapOptimizationOrder });
140
+ if (adjustedSwapPathStats) {
141
+ return {
142
+ type: "internalSwap",
143
+ swapPathStats: adjustedSwapPathStats,
144
+ externalSwapQuote: undefined,
145
+ amountIn: adjustedAmountIn,
146
+ amountOut: adjustedSwapPathStats.amountOut,
147
+ usdIn: adjustedUsdIn,
148
+ usdOut: adjustedSwapPathStats.usdOut,
149
+ priceIn: priceIn,
150
+ priceOut: priceOut,
151
+ feesUsd: adjustedUsdIn - adjustedSwapPathStats.usdOut,
152
+ };
153
+ }
154
+ }
155
+ const availableExternalSwapPaths = getAvailableExternalSwapPaths({ chainId, fromTokenAddress: tokenIn.address });
156
+ const suitableSwapPath = availableExternalSwapPaths.find((path) => {
157
+ if (path.outTokenAddress !== tokenOut.address)
158
+ return false;
159
+ const findSwapPath = createFindSwapPath({
160
+ chainId,
161
+ fromTokenAddress: tokenIn.address,
162
+ toTokenAddress: path.inTokenAddress,
163
+ marketsInfoData,
164
+ isExpressFeeSwap: false,
165
+ });
166
+ const swapPathStats = findSwapPath(approximateUsdIn);
167
+ return Boolean(swapPathStats);
168
+ });
169
+ if (suitableSwapPath) {
170
+ const approximateExternalSwapQuoteForCombinedSwap = getExternalSwapQuoteByPath({
171
+ amountIn: approximateAmountIn,
172
+ externalSwapPath: suitableSwapPath,
173
+ externalSwapQuoteParams,
174
+ });
175
+ if (!approximateExternalSwapQuoteForCombinedSwap) {
176
+ return defaultSwapStrategy;
177
+ }
178
+ const findSwapPathForSuitableSwapPath = createFindSwapPath({
179
+ chainId,
180
+ fromTokenAddress: tokenIn.address,
181
+ toTokenAddress: suitableSwapPath.inTokenAddress,
182
+ marketsInfoData,
183
+ isExpressFeeSwap: false,
184
+ });
185
+ const approximateSwapPathStatsForCombinedSwap = findSwapPathForSuitableSwapPath(approximateExternalSwapQuoteForCombinedSwap.usdOut);
186
+ if (!approximateSwapPathStatsForCombinedSwap) {
187
+ return defaultSwapStrategy;
188
+ }
189
+ const adjustedUsdIn = approximateSwapPathStatsForCombinedSwap.usdOut > 0
190
+ ? bigMath.mulDiv(approximateUsdIn, preferredUsdOut, approximateSwapPathStatsForCombinedSwap.usdOut)
191
+ : 0n;
192
+ const adjustedAmountIn = convertToTokenAmount(adjustedUsdIn, tokenIn.decimals, getMidPrice(tokenIn.prices));
193
+ const adjustedExternalSwapQuoteForCombinedSwap = getExternalSwapQuoteByPath({
194
+ amountIn: adjustedAmountIn,
195
+ externalSwapPath: suitableSwapPath,
196
+ externalSwapQuoteParams,
197
+ });
198
+ if (!adjustedExternalSwapQuoteForCombinedSwap) {
199
+ return defaultSwapStrategy;
200
+ }
201
+ const adjustedSwapPathStatsForCombinedSwap = findSwapPathForSuitableSwapPath(adjustedExternalSwapQuoteForCombinedSwap.usdOut);
202
+ if (!adjustedSwapPathStatsForCombinedSwap) {
203
+ return defaultSwapStrategy;
204
+ }
205
+ return {
206
+ type: "combinedSwap",
207
+ externalSwapQuote: adjustedExternalSwapQuoteForCombinedSwap,
208
+ swapPathStats: adjustedSwapPathStatsForCombinedSwap,
209
+ amountIn: adjustedAmountIn,
210
+ amountOut: adjustedSwapPathStatsForCombinedSwap.amountOut,
211
+ usdIn: adjustedExternalSwapQuoteForCombinedSwap.usdIn,
212
+ usdOut: adjustedSwapPathStatsForCombinedSwap.usdOut,
213
+ priceIn: adjustedExternalSwapQuoteForCombinedSwap.priceIn,
214
+ priceOut: priceOut,
215
+ feesUsd: adjustedExternalSwapQuoteForCombinedSwap.usdIn - adjustedSwapPathStatsForCombinedSwap.usdOut,
216
+ };
217
+ }
218
+ return defaultSwapStrategy;
219
+ }
@@ -0,0 +1,37 @@
1
+ import { BOTANIX } from "../../configs/chains";
2
+ import { NATIVE_TOKEN_ADDRESS, getTokenBySymbol } from "../../configs/tokens";
3
+ import { ExternalSwapAggregator } from "../../types/trade";
4
+ const BBTC_ADDRESS = NATIVE_TOKEN_ADDRESS;
5
+ const PBTC_ADDRESS = getTokenBySymbol(BOTANIX, "PBTC").address;
6
+ const STBTC_ADDRESS = getTokenBySymbol(BOTANIX, "STBTC").address;
7
+ export const AVAILABLE_BOTANIX_DEPOSIT_PAIRS = [
8
+ {
9
+ from: BBTC_ADDRESS,
10
+ to: STBTC_ADDRESS,
11
+ },
12
+ {
13
+ from: PBTC_ADDRESS,
14
+ to: STBTC_ADDRESS,
15
+ },
16
+ ];
17
+ export const AVAILABLE_BOTANIX_WITHDRAW_PAIRS = [
18
+ {
19
+ from: STBTC_ADDRESS,
20
+ to: PBTC_ADDRESS,
21
+ },
22
+ ];
23
+ const getBotanixStakingExternalSwapPaths = ({ fromTokenAddress }) => {
24
+ return [...AVAILABLE_BOTANIX_DEPOSIT_PAIRS, ...AVAILABLE_BOTANIX_WITHDRAW_PAIRS]
25
+ .filter((pair) => pair.from === fromTokenAddress)
26
+ .map((pair) => ({
27
+ aggregator: ExternalSwapAggregator.BotanixStaking,
28
+ inTokenAddress: pair.from,
29
+ outTokenAddress: pair.to,
30
+ }));
31
+ };
32
+ export const getAvailableExternalSwapPaths = ({ chainId, fromTokenAddress, }) => {
33
+ if (chainId === BOTANIX) {
34
+ return getBotanixStakingExternalSwapPaths({ fromTokenAddress });
35
+ }
36
+ return [];
37
+ };
@@ -0,0 +1,23 @@
1
+ import { ExternalSwapAggregator } from "../../types/trade";
2
+ import { getBotanixStakingExternalSwapQuote } from "./botanixStaking";
3
+ export const getExternalSwapQuoteByPath = ({ amountIn, externalSwapPath, externalSwapQuoteParams, }) => {
4
+ if (amountIn === undefined ||
5
+ externalSwapQuoteParams.gasPrice === undefined ||
6
+ externalSwapQuoteParams.tokensData === undefined ||
7
+ externalSwapQuoteParams.botanixStakingAssetsPerShare === undefined ||
8
+ externalSwapQuoteParams.receiverAddress === undefined) {
9
+ return undefined;
10
+ }
11
+ if (externalSwapPath.aggregator === ExternalSwapAggregator.BotanixStaking) {
12
+ return getBotanixStakingExternalSwapQuote({
13
+ tokenInAddress: externalSwapPath.inTokenAddress,
14
+ tokenOutAddress: externalSwapPath.outTokenAddress,
15
+ amountIn,
16
+ gasPrice: externalSwapQuoteParams.gasPrice,
17
+ receiverAddress: externalSwapQuoteParams.receiverAddress,
18
+ tokensData: externalSwapQuoteParams.tokensData,
19
+ assetsPerShare: externalSwapQuoteParams.botanixStakingAssetsPerShare,
20
+ });
21
+ }
22
+ return undefined;
23
+ };