@shapeshiftoss/swapper 17.6.7 → 17.6.8

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 (219) hide show
  1. package/dist/cjs/.tsbuildinfo +1 -1
  2. package/dist/cjs/constants.js +42 -24
  3. package/dist/cjs/cowswap-utils/constants.js +1 -0
  4. package/dist/cjs/cowswap-utils/index.js +2 -0
  5. package/dist/cjs/index.d.ts +2 -0
  6. package/dist/cjs/index.js +2 -0
  7. package/dist/cjs/swappers/AvnuSwapper/AvnuSwapper.d.ts +2 -0
  8. package/dist/cjs/swappers/AvnuSwapper/AvnuSwapper.js +7 -0
  9. package/dist/cjs/swappers/AvnuSwapper/endpoints.d.ts +2 -0
  10. package/dist/cjs/swappers/AvnuSwapper/endpoints.js +181 -0
  11. package/dist/cjs/swappers/AvnuSwapper/index.d.ts +1 -0
  12. package/dist/cjs/swappers/AvnuSwapper/index.js +5 -0
  13. package/dist/cjs/swappers/AvnuSwapper/swapperApi/getTradeQuote.d.ts +3 -0
  14. package/dist/cjs/swappers/AvnuSwapper/swapperApi/getTradeQuote.js +142 -0
  15. package/dist/cjs/swappers/AvnuSwapper/swapperApi/getTradeRate.d.ts +3 -0
  16. package/dist/cjs/swappers/AvnuSwapper/swapperApi/getTradeRate.js +120 -0
  17. package/dist/cjs/swappers/AvnuSwapper/types.d.ts +2 -0
  18. package/dist/cjs/swappers/AvnuSwapper/types.js +2 -0
  19. package/dist/cjs/swappers/AvnuSwapper/utils/constants.d.ts +5 -0
  20. package/dist/cjs/swappers/AvnuSwapper/utils/constants.js +11 -0
  21. package/dist/cjs/swappers/AvnuSwapper/utils/helpers.d.ts +7 -0
  22. package/dist/cjs/swappers/AvnuSwapper/utils/helpers.js +21 -0
  23. package/dist/cjs/swappers/ButterSwap/swapperApi/getTradeQuote.test.js +2 -0
  24. package/dist/cjs/swappers/ButterSwap/swapperApi/getTradeRate.test.js +4 -0
  25. package/dist/cjs/swappers/ButterSwap/utils/helpers.js +1 -0
  26. package/dist/cjs/swappers/CetusSwapper/endpoints.js +33 -27
  27. package/dist/cjs/swappers/CetusSwapper/swapperApi/getCetusTradeData.d.ts +24 -0
  28. package/dist/cjs/swappers/CetusSwapper/swapperApi/getCetusTradeData.js +79 -0
  29. package/dist/cjs/swappers/CetusSwapper/swapperApi/getTradeQuote.js +44 -69
  30. package/dist/cjs/swappers/CetusSwapper/swapperApi/getTradeRate.js +49 -65
  31. package/dist/cjs/swappers/CetusSwapper/utils/constants.d.ts +1 -0
  32. package/dist/cjs/swappers/CetusSwapper/utils/constants.js +2 -1
  33. package/dist/cjs/swappers/CetusSwapper/utils/helpers.d.ts +6 -11
  34. package/dist/cjs/swappers/CetusSwapper/utils/helpers.js +41 -96
  35. package/dist/cjs/swappers/JupiterSwapper/utils/helpers.d.ts +0 -2
  36. package/dist/cjs/swappers/MayachainSwapper/generated/generatedTradableAssetMap.json +1 -0
  37. package/dist/cjs/swappers/NearIntentsSwapper/NearIntentsSwapper.js +2 -0
  38. package/dist/cjs/swappers/NearIntentsSwapper/endpoints.js +68 -0
  39. package/dist/cjs/swappers/NearIntentsSwapper/swapperApi/getTradeQuote.js +30 -0
  40. package/dist/cjs/swappers/NearIntentsSwapper/swapperApi/getTradeRate.js +53 -5
  41. package/dist/cjs/swappers/NearIntentsSwapper/types.d.ts +1 -1
  42. package/dist/cjs/swappers/NearIntentsSwapper/types.js +8 -0
  43. package/dist/cjs/swappers/NearIntentsSwapper/utils/helpers/helpers.js +28 -8
  44. package/dist/cjs/swappers/PortalsSwapper/constants.js +1 -1
  45. package/dist/cjs/swappers/PortalsSwapper/endpoints.js +92 -1
  46. package/dist/cjs/swappers/PortalsSwapper/getPortalsTradeQuote/getPortalsTradeQuote.js +29 -17
  47. package/dist/cjs/swappers/PortalsSwapper/getPortalsTradeRate/getPortalsTradeRate.js +21 -17
  48. package/dist/cjs/swappers/PortalsSwapper/types.js +1 -0
  49. package/dist/cjs/swappers/PortalsSwapper/utils/fetchAxelarscanStatus.d.ts +9 -0
  50. package/dist/cjs/swappers/PortalsSwapper/utils/fetchAxelarscanStatus.js +52 -0
  51. package/dist/cjs/swappers/PortalsSwapper/utils/fetchPortalsTradeOrder.d.ts +1 -0
  52. package/dist/cjs/swappers/PortalsSwapper/utils/fetchSquidStatus.d.ts +9 -0
  53. package/dist/cjs/swappers/PortalsSwapper/utils/fetchSquidStatus.js +57 -0
  54. package/dist/cjs/swappers/RelaySwapper/constant.js +3 -0
  55. package/dist/cjs/swappers/RelaySwapper/utils/fetchRelayTrade.js +1 -1
  56. package/dist/cjs/swappers/RelaySwapper/utils/getTrade.js +16 -1
  57. package/dist/cjs/swappers/RelaySwapper/utils/relayTokenToAssetId.js +20 -0
  58. package/dist/cjs/swappers/RelaySwapper/utils/types.d.ts +13 -4
  59. package/dist/cjs/swappers/RelaySwapper/utils/types.js +5 -1
  60. package/dist/cjs/swappers/SunioSwapper/SunioSwapper.d.ts +2 -0
  61. package/dist/cjs/swappers/SunioSwapper/SunioSwapper.js +7 -0
  62. package/dist/cjs/swappers/SunioSwapper/endpoints.d.ts +2 -0
  63. package/dist/cjs/swappers/SunioSwapper/endpoints.js +131 -0
  64. package/dist/cjs/swappers/SunioSwapper/getSunioTradeQuote/getSunioTradeQuote.d.ts +3 -0
  65. package/dist/cjs/swappers/SunioSwapper/getSunioTradeQuote/getSunioTradeQuote.js +8 -0
  66. package/dist/cjs/swappers/SunioSwapper/getSunioTradeRate/getSunioTradeRate.d.ts +3 -0
  67. package/dist/cjs/swappers/SunioSwapper/getSunioTradeRate/getSunioTradeRate.js +8 -0
  68. package/dist/cjs/swappers/SunioSwapper/index.d.ts +4 -0
  69. package/dist/cjs/swappers/SunioSwapper/index.js +23 -0
  70. package/dist/cjs/swappers/SunioSwapper/types.d.ts +22 -0
  71. package/dist/cjs/swappers/SunioSwapper/types.js +12 -0
  72. package/dist/cjs/swappers/SunioSwapper/utils/abi.d.ts +48 -0
  73. package/dist/cjs/swappers/SunioSwapper/utils/abi.js +28 -0
  74. package/dist/cjs/swappers/SunioSwapper/utils/buildSwapRouteParameters.d.ts +14 -0
  75. package/dist/cjs/swappers/SunioSwapper/utils/buildSwapRouteParameters.js +32 -0
  76. package/dist/cjs/swappers/SunioSwapper/utils/buildSwapTransaction.d.ts +11 -0
  77. package/dist/cjs/swappers/SunioSwapper/utils/buildSwapTransaction.js +57 -0
  78. package/dist/cjs/swappers/SunioSwapper/utils/constants.d.ts +6 -0
  79. package/dist/cjs/swappers/SunioSwapper/utils/constants.js +16 -0
  80. package/dist/cjs/swappers/SunioSwapper/utils/fetchFromSunio.d.ts +11 -0
  81. package/dist/cjs/swappers/SunioSwapper/utils/fetchFromSunio.js +45 -0
  82. package/dist/cjs/swappers/SunioSwapper/utils/getQuoteOrRate.d.ts +4 -0
  83. package/dist/cjs/swappers/SunioSwapper/utils/getQuoteOrRate.js +203 -0
  84. package/dist/cjs/swappers/SunioSwapper/utils/helpers/helpers.d.ts +4 -0
  85. package/dist/cjs/swappers/SunioSwapper/utils/helpers/helpers.js +22 -0
  86. package/dist/cjs/swappers/SunioSwapper/utils/sunioService.d.ts +6 -0
  87. package/dist/cjs/swappers/SunioSwapper/utils/sunioService.js +18 -0
  88. package/dist/cjs/swappers/ThorchainSwapper/ThorchainSwapper.js +3 -0
  89. package/dist/cjs/swappers/ThorchainSwapper/endpoints.js +2 -0
  90. package/dist/cjs/swappers/ThorchainSwapper/generated/generatedTradableAssetMap.json +2 -2
  91. package/dist/cjs/swappers/utils/helpers/helpers.js +7 -0
  92. package/dist/cjs/thorchain-utils/getL1RateOrQuote.js +80 -3
  93. package/dist/cjs/thorchain-utils/index.d.ts +1 -0
  94. package/dist/cjs/thorchain-utils/index.js +2 -1
  95. package/dist/cjs/thorchain-utils/tron/getThorTxData.d.ts +12 -0
  96. package/dist/cjs/thorchain-utils/tron/getThorTxData.js +14 -0
  97. package/dist/cjs/thorchain-utils/tron/getTronTransactionFees.d.ts +2 -0
  98. package/dist/cjs/thorchain-utils/tron/getTronTransactionFees.js +65 -0
  99. package/dist/cjs/thorchain-utils/tron/getUnsignedTronTransaction.d.ts +3 -0
  100. package/dist/cjs/thorchain-utils/tron/getUnsignedTronTransaction.js +35 -0
  101. package/dist/cjs/thorchain-utils/tron/index.d.ts +3 -0
  102. package/dist/cjs/thorchain-utils/tron/index.js +19 -0
  103. package/dist/cjs/types.d.ts +74 -9
  104. package/dist/cjs/types.js +2 -0
  105. package/dist/cjs/utils/tenderly/simulate.d.ts +6 -1
  106. package/dist/cjs/utils/tenderly/simulate.js +22 -2
  107. package/dist/cjs/utils/tenderly/types.d.ts +21 -0
  108. package/dist/cjs/utils.d.ts +9 -3
  109. package/dist/cjs/utils.js +53 -1
  110. package/dist/esm/.tsbuildinfo +1 -1
  111. package/dist/esm/constants.js +18 -0
  112. package/dist/esm/cowswap-utils/constants.js +1 -0
  113. package/dist/esm/cowswap-utils/index.js +2 -0
  114. package/dist/esm/index.d.ts +2 -0
  115. package/dist/esm/index.js +2 -0
  116. package/dist/esm/swappers/AvnuSwapper/AvnuSwapper.d.ts +2 -0
  117. package/dist/esm/swappers/AvnuSwapper/AvnuSwapper.js +4 -0
  118. package/dist/esm/swappers/AvnuSwapper/endpoints.d.ts +2 -0
  119. package/dist/esm/swappers/AvnuSwapper/endpoints.js +178 -0
  120. package/dist/esm/swappers/AvnuSwapper/index.d.ts +1 -0
  121. package/dist/esm/swappers/AvnuSwapper/index.js +1 -0
  122. package/dist/esm/swappers/AvnuSwapper/swapperApi/getTradeQuote.d.ts +3 -0
  123. package/dist/esm/swappers/AvnuSwapper/swapperApi/getTradeQuote.js +138 -0
  124. package/dist/esm/swappers/AvnuSwapper/swapperApi/getTradeRate.d.ts +3 -0
  125. package/dist/esm/swappers/AvnuSwapper/swapperApi/getTradeRate.js +116 -0
  126. package/dist/esm/swappers/AvnuSwapper/types.d.ts +2 -0
  127. package/dist/esm/swappers/AvnuSwapper/types.js +1 -0
  128. package/dist/esm/swappers/AvnuSwapper/utils/constants.d.ts +5 -0
  129. package/dist/esm/swappers/AvnuSwapper/utils/constants.js +7 -0
  130. package/dist/esm/swappers/AvnuSwapper/utils/helpers.d.ts +7 -0
  131. package/dist/esm/swappers/AvnuSwapper/utils/helpers.js +17 -0
  132. package/dist/esm/swappers/ButterSwap/swapperApi/getTradeQuote.test.js +2 -0
  133. package/dist/esm/swappers/ButterSwap/swapperApi/getTradeRate.test.js +4 -0
  134. package/dist/esm/swappers/ButterSwap/utils/helpers.js +1 -0
  135. package/dist/esm/swappers/CetusSwapper/endpoints.js +28 -22
  136. package/dist/esm/swappers/CetusSwapper/swapperApi/getCetusTradeData.d.ts +24 -0
  137. package/dist/esm/swappers/CetusSwapper/swapperApi/getCetusTradeData.js +75 -0
  138. package/dist/esm/swappers/CetusSwapper/swapperApi/getTradeQuote.js +44 -69
  139. package/dist/esm/swappers/CetusSwapper/swapperApi/getTradeRate.js +50 -66
  140. package/dist/esm/swappers/CetusSwapper/utils/constants.d.ts +1 -0
  141. package/dist/esm/swappers/CetusSwapper/utils/constants.js +1 -0
  142. package/dist/esm/swappers/CetusSwapper/utils/helpers.d.ts +6 -11
  143. package/dist/esm/swappers/CetusSwapper/utils/helpers.js +37 -67
  144. package/dist/esm/swappers/JupiterSwapper/utils/helpers.d.ts +0 -2
  145. package/dist/esm/swappers/MayachainSwapper/generated/generatedTradableAssetMap.json +1 -0
  146. package/dist/esm/swappers/NearIntentsSwapper/NearIntentsSwapper.js +3 -1
  147. package/dist/esm/swappers/NearIntentsSwapper/endpoints.js +68 -0
  148. package/dist/esm/swappers/NearIntentsSwapper/swapperApi/getTradeQuote.js +30 -0
  149. package/dist/esm/swappers/NearIntentsSwapper/swapperApi/getTradeRate.js +54 -6
  150. package/dist/esm/swappers/NearIntentsSwapper/types.d.ts +1 -1
  151. package/dist/esm/swappers/NearIntentsSwapper/types.js +8 -0
  152. package/dist/esm/swappers/NearIntentsSwapper/utils/helpers/helpers.js +29 -9
  153. package/dist/esm/swappers/PortalsSwapper/constants.js +1 -1
  154. package/dist/esm/swappers/PortalsSwapper/endpoints.js +92 -1
  155. package/dist/esm/swappers/PortalsSwapper/getPortalsTradeQuote/getPortalsTradeQuote.js +30 -18
  156. package/dist/esm/swappers/PortalsSwapper/getPortalsTradeRate/getPortalsTradeRate.js +21 -17
  157. package/dist/esm/swappers/PortalsSwapper/types.js +1 -0
  158. package/dist/esm/swappers/PortalsSwapper/utils/fetchAxelarscanStatus.d.ts +9 -0
  159. package/dist/esm/swappers/PortalsSwapper/utils/fetchAxelarscanStatus.js +47 -0
  160. package/dist/esm/swappers/PortalsSwapper/utils/fetchPortalsTradeOrder.d.ts +1 -0
  161. package/dist/esm/swappers/PortalsSwapper/utils/fetchSquidStatus.d.ts +9 -0
  162. package/dist/esm/swappers/PortalsSwapper/utils/fetchSquidStatus.js +52 -0
  163. package/dist/esm/swappers/RelaySwapper/constant.js +5 -2
  164. package/dist/esm/swappers/RelaySwapper/utils/fetchRelayTrade.js +1 -1
  165. package/dist/esm/swappers/RelaySwapper/utils/getTrade.js +18 -3
  166. package/dist/esm/swappers/RelaySwapper/utils/relayTokenToAssetId.js +20 -0
  167. package/dist/esm/swappers/RelaySwapper/utils/types.d.ts +13 -4
  168. package/dist/esm/swappers/RelaySwapper/utils/types.js +3 -0
  169. package/dist/esm/swappers/SunioSwapper/SunioSwapper.d.ts +2 -0
  170. package/dist/esm/swappers/SunioSwapper/SunioSwapper.js +4 -0
  171. package/dist/esm/swappers/SunioSwapper/endpoints.d.ts +2 -0
  172. package/dist/esm/swappers/SunioSwapper/endpoints.js +128 -0
  173. package/dist/esm/swappers/SunioSwapper/getSunioTradeQuote/getSunioTradeQuote.d.ts +3 -0
  174. package/dist/esm/swappers/SunioSwapper/getSunioTradeQuote/getSunioTradeQuote.js +4 -0
  175. package/dist/esm/swappers/SunioSwapper/getSunioTradeRate/getSunioTradeRate.d.ts +3 -0
  176. package/dist/esm/swappers/SunioSwapper/getSunioTradeRate/getSunioTradeRate.js +4 -0
  177. package/dist/esm/swappers/SunioSwapper/index.d.ts +4 -0
  178. package/dist/esm/swappers/SunioSwapper/index.js +4 -0
  179. package/dist/esm/swappers/SunioSwapper/types.d.ts +22 -0
  180. package/dist/esm/swappers/SunioSwapper/types.js +9 -0
  181. package/dist/esm/swappers/SunioSwapper/utils/abi.d.ts +48 -0
  182. package/dist/esm/swappers/SunioSwapper/utils/abi.js +25 -0
  183. package/dist/esm/swappers/SunioSwapper/utils/buildSwapRouteParameters.d.ts +14 -0
  184. package/dist/esm/swappers/SunioSwapper/utils/buildSwapRouteParameters.js +28 -0
  185. package/dist/esm/swappers/SunioSwapper/utils/buildSwapTransaction.d.ts +11 -0
  186. package/dist/esm/swappers/SunioSwapper/utils/buildSwapTransaction.js +53 -0
  187. package/dist/esm/swappers/SunioSwapper/utils/constants.d.ts +6 -0
  188. package/dist/esm/swappers/SunioSwapper/utils/constants.js +13 -0
  189. package/dist/esm/swappers/SunioSwapper/utils/fetchFromSunio.d.ts +11 -0
  190. package/dist/esm/swappers/SunioSwapper/utils/fetchFromSunio.js +41 -0
  191. package/dist/esm/swappers/SunioSwapper/utils/getQuoteOrRate.d.ts +4 -0
  192. package/dist/esm/swappers/SunioSwapper/utils/getQuoteOrRate.js +199 -0
  193. package/dist/esm/swappers/SunioSwapper/utils/helpers/helpers.d.ts +4 -0
  194. package/dist/esm/swappers/SunioSwapper/utils/helpers/helpers.js +16 -0
  195. package/dist/esm/swappers/SunioSwapper/utils/sunioService.d.ts +6 -0
  196. package/dist/esm/swappers/SunioSwapper/utils/sunioService.js +14 -0
  197. package/dist/esm/swappers/ThorchainSwapper/ThorchainSwapper.js +3 -0
  198. package/dist/esm/swappers/ThorchainSwapper/endpoints.js +3 -1
  199. package/dist/esm/swappers/ThorchainSwapper/generated/generatedTradableAssetMap.json +2 -2
  200. package/dist/esm/swappers/utils/helpers/helpers.js +9 -2
  201. package/dist/esm/thorchain-utils/getL1RateOrQuote.js +81 -4
  202. package/dist/esm/thorchain-utils/index.d.ts +1 -0
  203. package/dist/esm/thorchain-utils/index.js +1 -0
  204. package/dist/esm/thorchain-utils/tron/getThorTxData.d.ts +12 -0
  205. package/dist/esm/thorchain-utils/tron/getThorTxData.js +10 -0
  206. package/dist/esm/thorchain-utils/tron/getTronTransactionFees.d.ts +2 -0
  207. package/dist/esm/thorchain-utils/tron/getTronTransactionFees.js +61 -0
  208. package/dist/esm/thorchain-utils/tron/getUnsignedTronTransaction.d.ts +3 -0
  209. package/dist/esm/thorchain-utils/tron/getUnsignedTronTransaction.js +31 -0
  210. package/dist/esm/thorchain-utils/tron/index.d.ts +3 -0
  211. package/dist/esm/thorchain-utils/tron/index.js +3 -0
  212. package/dist/esm/types.d.ts +74 -9
  213. package/dist/esm/types.js +2 -0
  214. package/dist/esm/utils/tenderly/simulate.d.ts +6 -1
  215. package/dist/esm/utils/tenderly/simulate.js +20 -1
  216. package/dist/esm/utils/tenderly/types.d.ts +21 -0
  217. package/dist/esm/utils.d.ts +9 -3
  218. package/dist/esm/utils.js +50 -1
  219. package/package.json +9 -8
@@ -1,8 +1,14 @@
1
+ import { getProvidersExcluding } from '@cetusprotocol/aggregator-sdk';
2
+ import { Transaction } from '@cetusprotocol/aggregator-sdk/node_modules/@mysten/sui/transactions';
1
3
  import { TxStatus } from '@shapeshiftoss/unchained-client';
4
+ import { bnOrZero } from '@shapeshiftoss/utils';
5
+ import { getDefaultSlippageDecimalPercentageForSwapper } from '../../constants.js';
6
+ import { SwapperName } from '../../types.js';
2
7
  import { checkSuiSwapStatus, getExecutableTradeStep, isExecutableTradeQuote } from '../../utils.js';
3
8
  import { getTradeQuote } from './swapperApi/getTradeQuote.js';
4
9
  import { getTradeRate } from './swapperApi/getTradeRate.js';
5
- import { calculateAmountLimit, calculateSwapAmounts, determineSwapDirection, findBestPool, getCetusSDK, getCoinType, } from './utils/helpers.js';
10
+ import { PYTH_DEPENDENT_PROVIDERS } from './utils/constants.js';
11
+ import { findBestRoute, getAggregatorClient, getCoinType, getSuiClient } from './utils/helpers.js';
6
12
  export const cetusApi = {
7
13
  getTradeQuote: (input, deps) => {
8
14
  return getTradeQuote(input, deps);
@@ -10,36 +16,35 @@ export const cetusApi = {
10
16
  getTradeRate: (input, deps) => {
11
17
  return getTradeRate(input, deps);
12
18
  },
13
- getUnsignedSuiTransaction: async ({ stepIndex, tradeQuote, from, assertGetSuiChainAdapter, }) => {
19
+ getUnsignedSuiTransaction: async ({ stepIndex, tradeQuote, from, assertGetSuiChainAdapter, config, }) => {
14
20
  if (!isExecutableTradeQuote(tradeQuote))
15
21
  throw new Error('Unable to execute a trade rate quote');
16
22
  const step = getExecutableTradeStep(tradeQuote, stepIndex);
17
23
  const { accountNumber, sellAsset, buyAsset, sellAmountIncludingProtocolFeesCryptoBaseUnit } = step;
18
24
  const adapter = assertGetSuiChainAdapter(sellAsset.chainId);
19
- const sdk = await getCetusSDK();
20
- sdk.senderAddress = from;
25
+ const rpcUrl = config.VITE_SUI_NODE_URL;
26
+ const client = getAggregatorClient(rpcUrl);
27
+ const suiClient = getSuiClient(rpcUrl);
21
28
  const sellCoinType = getCoinType(sellAsset);
22
29
  const buyCoinType = getCoinType(buyAsset);
23
- const pool = await findBestPool(sdk, sellCoinType, buyCoinType);
24
- if (!pool) {
25
- throw new Error(`No liquidity pool found for ${sellAsset.symbol}/${buyAsset.symbol}`);
30
+ // Exclude Pyth-dependent providers to avoid oracle failures
31
+ const providersWithoutPyth = getProvidersExcluding(PYTH_DEPENDENT_PROVIDERS);
32
+ const routerData = await findBestRoute(client, sellCoinType, buyCoinType, sellAmountIncludingProtocolFeesCryptoBaseUnit, providersWithoutPyth);
33
+ if (!routerData) {
34
+ throw new Error(`No route found for ${sellAsset.symbol}/${buyAsset.symbol}`);
26
35
  }
27
- const swapResult = await calculateSwapAmounts(sdk, pool, sellAsset, buyAsset, sellAmountIncludingProtocolFeesCryptoBaseUnit);
28
- if (!swapResult) {
29
- throw new Error(`Failed to calculate swap for ${sellAsset.symbol}/${buyAsset.symbol}`);
30
- }
31
- const a2b = determineSwapDirection(pool, sellCoinType, buyCoinType);
32
- const amountLimit = calculateAmountLimit(swapResult.estimatedAmountOut, tradeQuote.slippageTolerancePercentageDecimal, true);
33
- const tx = await sdk.Swap.createSwapTransactionPayload({
34
- pool_id: pool.poolAddress,
35
- coinTypeA: pool.coinTypeA,
36
- coinTypeB: pool.coinTypeB,
37
- a2b,
38
- by_amount_in: true,
39
- amount: sellAmountIncludingProtocolFeesCryptoBaseUnit,
40
- amount_limit: amountLimit,
36
+ const slippage = bnOrZero(tradeQuote.slippageTolerancePercentageDecimal ??
37
+ getDefaultSlippageDecimalPercentageForSwapper(SwapperName.Cetus)).toNumber();
38
+ const txb = new Transaction();
39
+ txb.setSender(from);
40
+ await client.fastRouterSwap({
41
+ router: routerData,
42
+ slippage,
43
+ txb,
44
+ refreshAllCoins: true,
41
45
  });
42
- const transactionBytes = await tx.build({ client: adapter.getSuiClient() });
46
+ const transactionJson = await txb.toJSON({ client: suiClient });
47
+ const transactionBytes = await txb.build({ client: suiClient });
43
48
  const intentMessage = new Uint8Array(3 + transactionBytes.length);
44
49
  intentMessage[0] = 0;
45
50
  intentMessage[1] = 0;
@@ -56,6 +61,7 @@ export const cetusApi = {
56
61
  return {
57
62
  addressNList,
58
63
  intentMessageBytes: intentMessage,
64
+ transactionJson,
59
65
  };
60
66
  },
61
67
  getSuiTransactionFees: ({ tradeQuote, stepIndex }) => {
@@ -0,0 +1,24 @@
1
+ import type { RouterDataV3 } from '@cetusprotocol/aggregator-sdk';
2
+ import type { AssetId } from '@shapeshiftoss/caip';
3
+ import type { Asset } from '@shapeshiftoss/types';
4
+ import type { Result } from '@sniptt/monads';
5
+ import type { ProtocolFee, SwapErrorRight, SwapperDeps } from '../../../types.js';
6
+ type CetusTradeDataInput = {
7
+ sellAsset: Asset;
8
+ buyAsset: Asset;
9
+ receiveAddress: string | undefined;
10
+ sellAmountIncludingProtocolFeesCryptoBaseUnit: string;
11
+ };
12
+ type CetusTradeData = {
13
+ buyAmountAfterFeesCryptoBaseUnit: string;
14
+ rate: string;
15
+ addressForFeeEstimate: string;
16
+ sellCoinType: string;
17
+ buyCoinType: string;
18
+ routerData: RouterDataV3;
19
+ protocolFees: Record<AssetId, ProtocolFee>;
20
+ adapter: ReturnType<SwapperDeps['assertGetSuiChainAdapter']>;
21
+ rpcUrl: string;
22
+ };
23
+ export declare const getCetusTradeData: (input: CetusTradeDataInput, deps: SwapperDeps) => Promise<Result<CetusTradeData, SwapErrorRight>>;
24
+ export {};
@@ -0,0 +1,75 @@
1
+ import { getProvidersExcluding } from '@cetusprotocol/aggregator-sdk';
2
+ import { suiAssetId } from '@shapeshiftoss/caip';
3
+ import { Err, Ok } from '@sniptt/monads';
4
+ import { TradeQuoteError } from '../../../types.js';
5
+ import { getInputOutputRate, makeSwapErrorRight } from '../../../utils.js';
6
+ import { isSupportedChainId, PYTH_DEPENDENT_PROVIDERS } from '../utils/constants.js';
7
+ import { findBestRoute, getAggregatorClient, getCoinType } from '../utils/helpers.js';
8
+ export const getCetusTradeData = async (input, deps) => {
9
+ const { sellAsset, buyAsset, receiveAddress, sellAmountIncludingProtocolFeesCryptoBaseUnit } = input;
10
+ const { assetsById } = deps;
11
+ if (!isSupportedChainId(sellAsset.chainId)) {
12
+ return Err(makeSwapErrorRight({
13
+ message: `unsupported chainId`,
14
+ code: TradeQuoteError.UnsupportedChain,
15
+ details: { chainId: sellAsset.chainId },
16
+ }));
17
+ }
18
+ if (!isSupportedChainId(buyAsset.chainId)) {
19
+ return Err(makeSwapErrorRight({
20
+ message: `unsupported chainId`,
21
+ code: TradeQuoteError.UnsupportedChain,
22
+ details: { chainId: buyAsset.chainId },
23
+ }));
24
+ }
25
+ const suiAsset = assetsById[suiAssetId];
26
+ if (!suiAsset) {
27
+ return Err(makeSwapErrorRight({
28
+ message: `suiAsset is required`,
29
+ code: TradeQuoteError.InternalError,
30
+ }));
31
+ }
32
+ try {
33
+ const adapter = deps.assertGetSuiChainAdapter(sellAsset.chainId);
34
+ const rpcUrl = deps.config.VITE_SUI_NODE_URL;
35
+ const client = getAggregatorClient(rpcUrl);
36
+ const sellCoinType = getCoinType(sellAsset);
37
+ const buyCoinType = getCoinType(buyAsset);
38
+ // Exclude Pyth-dependent providers to avoid oracle failures
39
+ const providersWithoutPyth = getProvidersExcluding(PYTH_DEPENDENT_PROVIDERS);
40
+ const routerData = await findBestRoute(client, sellCoinType, buyCoinType, sellAmountIncludingProtocolFeesCryptoBaseUnit, providersWithoutPyth);
41
+ if (!routerData) {
42
+ return Err(makeSwapErrorRight({
43
+ message: `No route found for ${sellAsset.symbol}/${buyAsset.symbol}`,
44
+ code: TradeQuoteError.NoRouteFound,
45
+ }));
46
+ }
47
+ const buyAmountAfterFeesCryptoBaseUnit = routerData.amountOut.toString();
48
+ const rate = getInputOutputRate({
49
+ sellAmountCryptoBaseUnit: sellAmountIncludingProtocolFeesCryptoBaseUnit,
50
+ buyAmountCryptoBaseUnit: buyAmountAfterFeesCryptoBaseUnit,
51
+ sellAsset,
52
+ buyAsset,
53
+ });
54
+ const dummyAddress = '0x0000000000000000000000000000000000000000000000000000000000000000';
55
+ const addressForFeeEstimate = receiveAddress ?? dummyAddress;
56
+ const protocolFees = {};
57
+ return Ok({
58
+ buyAmountAfterFeesCryptoBaseUnit,
59
+ rate,
60
+ addressForFeeEstimate,
61
+ sellCoinType,
62
+ buyCoinType,
63
+ routerData,
64
+ protocolFees,
65
+ adapter,
66
+ rpcUrl,
67
+ });
68
+ }
69
+ catch (error) {
70
+ return Err(makeSwapErrorRight({
71
+ message: error instanceof Error ? error.message : 'Unknown error getting Cetus data',
72
+ code: TradeQuoteError.QueryFailed,
73
+ }));
74
+ }
75
+ };
@@ -1,79 +1,55 @@
1
- import { suiAssetId } from '@shapeshiftoss/caip';
2
- import { Err, Ok } from '@sniptt/monads';
1
+ import { Transaction } from '@cetusprotocol/aggregator-sdk/node_modules/@mysten/sui/transactions';
2
+ import { bnOrZero } from '@shapeshiftoss/utils';
3
+ import { Err } from '@sniptt/monads';
3
4
  import { v4 as uuid } from 'uuid';
5
+ import { getDefaultSlippageDecimalPercentageForSwapper } from '../../../constants.js';
4
6
  import { SwapperName, TradeQuoteError } from '../../../types.js';
5
- import { getInputOutputRate, makeSwapErrorRight } from '../../../utils.js';
6
- import { isSupportedChainId } from '../utils/constants.js';
7
- import { calculateSwapAmounts, findBestPool, getCetusSDK, getCoinType } from '../utils/helpers.js';
7
+ import { makeSwapErrorRight } from '../../../utils.js';
8
+ import { getAggregatorClient, getSuiClient } from '../utils/helpers.js';
9
+ import { getCetusTradeData } from './getCetusTradeData.js';
8
10
  export const getTradeQuote = async (input, deps) => {
9
11
  const { sellAsset, buyAsset, receiveAddress, accountNumber, sellAmountIncludingProtocolFeesCryptoBaseUnit: sellAmount, affiliateBps, slippageTolerancePercentageDecimal, } = input;
10
- const { assetsById } = deps;
11
12
  if (accountNumber === undefined) {
12
13
  return Err(makeSwapErrorRight({
13
14
  message: `accountNumber is required`,
14
15
  code: TradeQuoteError.InternalError,
15
16
  }));
16
17
  }
17
- if (!isSupportedChainId(sellAsset.chainId)) {
18
- return Err(makeSwapErrorRight({
19
- message: `unsupported chainId`,
20
- code: TradeQuoteError.UnsupportedChain,
21
- details: { chainId: sellAsset.chainId },
22
- }));
23
- }
24
- if (!isSupportedChainId(buyAsset.chainId)) {
25
- return Err(makeSwapErrorRight({
26
- message: `unsupported chainId`,
27
- code: TradeQuoteError.UnsupportedChain,
28
- details: { chainId: buyAsset.chainId },
29
- }));
30
- }
31
- const suiAsset = assetsById[suiAssetId];
32
- if (!suiAsset) {
33
- return Err(makeSwapErrorRight({
34
- message: `suiAsset is required`,
35
- code: TradeQuoteError.InternalError,
36
- }));
37
- }
18
+ const tradeDataResult = await getCetusTradeData({
19
+ sellAsset,
20
+ buyAsset,
21
+ receiveAddress,
22
+ sellAmountIncludingProtocolFeesCryptoBaseUnit: sellAmount,
23
+ }, deps);
24
+ if (tradeDataResult.isErr())
25
+ return Err(tradeDataResult.unwrapErr());
26
+ const { buyAmountAfterFeesCryptoBaseUnit, rate, addressForFeeEstimate, routerData, protocolFees, rpcUrl, } = tradeDataResult.unwrap();
38
27
  try {
39
- const sdk = await getCetusSDK();
40
- const sellCoinType = getCoinType(sellAsset);
41
- const buyCoinType = getCoinType(buyAsset);
42
- const pool = await findBestPool(sdk, sellCoinType, buyCoinType);
43
- if (!pool) {
44
- return Err(makeSwapErrorRight({
45
- message: `No liquidity pool found for ${sellAsset.symbol}/${buyAsset.symbol}`,
46
- code: TradeQuoteError.NoRouteFound,
47
- }));
48
- }
49
- const swapResult = await calculateSwapAmounts(sdk, pool, sellAsset, buyAsset, sellAmount);
50
- if (!swapResult) {
51
- return Err(makeSwapErrorRight({
52
- message: `Failed to calculate swap for ${sellAsset.symbol}/${buyAsset.symbol}`,
53
- code: TradeQuoteError.QueryFailed,
54
- }));
55
- }
56
- const buyAmountAfterFeesCryptoBaseUnit = swapResult.estimatedAmountOut;
57
- const rate = getInputOutputRate({
58
- sellAmountCryptoBaseUnit: sellAmount,
59
- buyAmountCryptoBaseUnit: buyAmountAfterFeesCryptoBaseUnit,
60
- sellAsset,
61
- buyAsset,
28
+ // Build the actual Cetus swap transaction to get accurate gas estimation
29
+ const client = getAggregatorClient(rpcUrl);
30
+ const suiClient = getSuiClient(rpcUrl);
31
+ const slippage = bnOrZero(slippageTolerancePercentageDecimal ??
32
+ getDefaultSlippageDecimalPercentageForSwapper(SwapperName.Cetus)).toNumber();
33
+ const txb = new Transaction();
34
+ txb.setSender(addressForFeeEstimate);
35
+ await client.fastRouterSwap({
36
+ router: routerData,
37
+ slippage,
38
+ txb,
39
+ refreshAllCoins: true,
62
40
  });
63
- const adapter = deps.assertGetSuiChainAdapter(sellAsset.chainId);
64
- const dummyAddress = '0x0000000000000000000000000000000000000000000000000000000000000000';
65
- const addressForFeeEstimate = receiveAddress ?? dummyAddress;
66
- const getFeeDataInput = {
67
- to: addressForFeeEstimate,
68
- value: sellAmount,
69
- chainSpecific: {
70
- from: addressForFeeEstimate,
71
- tokenId: getCoinType(sellAsset),
72
- },
73
- };
74
- const feeData = await adapter.getFeeData(getFeeDataInput);
75
- const protocolFees = {};
76
- const quotes = [];
41
+ const transactionBytes = await txb.build({ client: suiClient });
42
+ const dryRunResult = await suiClient.dryRunTransactionBlock({
43
+ transactionBlock: transactionBytes,
44
+ });
45
+ const computationCost = BigInt(dryRunResult.effects.gasUsed.computationCost);
46
+ const storageCost = BigInt(dryRunResult.effects.gasUsed.storageCost);
47
+ const storageRebate = BigInt(dryRunResult.effects.gasUsed.storageRebate);
48
+ const netStorageCost = storageCost > storageRebate ? storageCost - storageRebate : 0n;
49
+ const estimatedGas = computationCost + netStorageCost;
50
+ const txFee = estimatedGas.toString();
51
+ const gasBudget = ((estimatedGas * 120n) / 100n).toString();
52
+ const gasPrice = await suiClient.getReferenceGasPrice();
77
53
  const tradeQuote = {
78
54
  id: uuid(),
79
55
  quoteOrRate: 'quote',
@@ -90,10 +66,10 @@ export const getTradeQuote = async (input, deps) => {
90
66
  sellAmountIncludingProtocolFeesCryptoBaseUnit: sellAmount,
91
67
  feeData: {
92
68
  protocolFees,
93
- networkFeeCryptoBaseUnit: feeData.fast.txFee,
69
+ networkFeeCryptoBaseUnit: txFee,
94
70
  chainSpecific: {
95
- gasBudget: feeData.fast.chainSpecific.gasBudget,
96
- gasPrice: feeData.fast.chainSpecific.gasPrice,
71
+ gasBudget,
72
+ gasPrice: gasPrice.toString(),
97
73
  },
98
74
  },
99
75
  rate,
@@ -105,8 +81,7 @@ export const getTradeQuote = async (input, deps) => {
105
81
  },
106
82
  ],
107
83
  };
108
- quotes.push(tradeQuote);
109
- return Ok(quotes);
84
+ return tradeDataResult.map(() => [tradeQuote]);
110
85
  }
111
86
  catch (error) {
112
87
  console.error(error);
@@ -1,72 +1,57 @@
1
- import { suiAssetId } from '@shapeshiftoss/caip';
2
- import { Err, Ok } from '@sniptt/monads';
1
+ import { Transaction } from '@cetusprotocol/aggregator-sdk/node_modules/@mysten/sui/transactions';
2
+ import { bnOrZero } from '@shapeshiftoss/utils';
3
+ import { Err } from '@sniptt/monads';
3
4
  import { v4 as uuid } from 'uuid';
5
+ import { getDefaultSlippageDecimalPercentageForSwapper } from '../../../constants.js';
4
6
  import { SwapperName, TradeQuoteError } from '../../../types.js';
5
- import { getInputOutputRate, makeSwapErrorRight } from '../../../utils.js';
6
- import { isSupportedChainId } from '../utils/constants.js';
7
- import { calculateSwapAmounts, findBestPool, getCetusSDK, getCoinType } from '../utils/helpers.js';
7
+ import { makeSwapErrorRight } from '../../../utils.js';
8
+ import { getAggregatorClient, getSuiClient } from '../utils/helpers.js';
9
+ import { getCetusTradeData } from './getCetusTradeData.js';
8
10
  export const getTradeRate = async (input, deps) => {
9
11
  const { sellAsset, buyAsset, receiveAddress, sellAmountIncludingProtocolFeesCryptoBaseUnit: sellAmount, affiliateBps, slippageTolerancePercentageDecimal, } = input;
10
- const { assetsById } = deps;
11
- if (!isSupportedChainId(sellAsset.chainId)) {
12
- return Err(makeSwapErrorRight({
13
- message: `unsupported chainId`,
14
- code: TradeQuoteError.UnsupportedChain,
15
- details: { chainId: sellAsset.chainId },
16
- }));
17
- }
18
- if (!isSupportedChainId(buyAsset.chainId)) {
19
- return Err(makeSwapErrorRight({
20
- message: `unsupported chainId`,
21
- code: TradeQuoteError.UnsupportedChain,
22
- details: { chainId: buyAsset.chainId },
23
- }));
24
- }
25
- const suiAsset = assetsById[suiAssetId];
26
- if (!suiAsset) {
27
- return Err(makeSwapErrorRight({
28
- message: `suiAsset is required`,
29
- code: TradeQuoteError.UnknownError,
30
- }));
31
- }
12
+ const tradeDataResult = await getCetusTradeData({
13
+ sellAsset,
14
+ buyAsset,
15
+ receiveAddress,
16
+ sellAmountIncludingProtocolFeesCryptoBaseUnit: sellAmount,
17
+ }, deps);
18
+ if (tradeDataResult.isErr())
19
+ return Err(tradeDataResult.unwrapErr());
20
+ const { buyAmountAfterFeesCryptoBaseUnit, rate, addressForFeeEstimate, routerData, protocolFees, rpcUrl, } = tradeDataResult.unwrap();
32
21
  try {
33
- const sdk = await getCetusSDK();
34
- const sellCoinType = getCoinType(sellAsset);
35
- const buyCoinType = getCoinType(buyAsset);
36
- const pool = await findBestPool(sdk, sellCoinType, buyCoinType);
37
- if (!pool) {
38
- return Err(makeSwapErrorRight({
39
- message: `No liquidity pool found for ${sellAsset.symbol}/${buyAsset.symbol}`,
40
- code: TradeQuoteError.NoRouteFound,
41
- }));
42
- }
43
- const swapResult = await calculateSwapAmounts(sdk, pool, sellAsset, buyAsset, sellAmount);
44
- if (!swapResult) {
45
- return Err(makeSwapErrorRight({
46
- message: `Failed to calculate swap for ${sellAsset.symbol}/${buyAsset.symbol}`,
47
- code: TradeQuoteError.QueryFailed,
48
- }));
49
- }
50
- const buyAmountAfterFeesCryptoBaseUnit = swapResult.estimatedAmountOut;
51
- const rate = getInputOutputRate({
52
- sellAmountCryptoBaseUnit: sellAmount,
53
- buyAmountCryptoBaseUnit: buyAmountAfterFeesCryptoBaseUnit,
54
- sellAsset,
55
- buyAsset,
56
- });
57
- const adapter = deps.assertGetSuiChainAdapter(sellAsset.chainId);
58
- const dummyAddress = '0x0000000000000000000000000000000000000000000000000000000000000000';
59
- const addressForFeeEstimate = receiveAddress ?? dummyAddress;
60
- const { fast: feeDataFast } = await adapter.getFeeData({
61
- to: addressForFeeEstimate,
62
- value: sellAmount,
63
- chainSpecific: {
64
- from: addressForFeeEstimate,
65
- tokenId: getCoinType(sellAsset),
66
- },
22
+ // Build the actual Cetus swap transaction to get accurate gas estimation
23
+ const client = getAggregatorClient(rpcUrl);
24
+ const suiClient = getSuiClient(rpcUrl);
25
+ const slippage = bnOrZero(slippageTolerancePercentageDecimal ??
26
+ getDefaultSlippageDecimalPercentageForSwapper(SwapperName.Cetus)).toNumber();
27
+ const txb = new Transaction();
28
+ txb.setSender(addressForFeeEstimate);
29
+ await client.fastRouterSwap({
30
+ router: routerData,
31
+ slippage,
32
+ txb,
33
+ refreshAllCoins: true,
67
34
  });
68
- const protocolFees = {};
69
- const rates = [];
35
+ const txFee = await (async () => {
36
+ try {
37
+ const transactionBytes = await txb.build({ client: suiClient });
38
+ const dryRunResult = await suiClient.dryRunTransactionBlock({
39
+ transactionBlock: transactionBytes,
40
+ });
41
+ const computationCost = BigInt(dryRunResult.effects.gasUsed.computationCost);
42
+ const storageCost = BigInt(dryRunResult.effects.gasUsed.storageCost);
43
+ const storageRebate = BigInt(dryRunResult.effects.gasUsed.storageRebate);
44
+ const netStorageCost = storageCost > storageRebate ? storageCost - storageRebate : 0n;
45
+ const estimatedGas = computationCost + netStorageCost;
46
+ return estimatedGas.toString();
47
+ }
48
+ catch (error) {
49
+ if (error instanceof Error && error.message.includes('Not enough coins of type')) {
50
+ return undefined;
51
+ }
52
+ throw error;
53
+ }
54
+ })();
70
55
  const tradeRate = {
71
56
  id: uuid(),
72
57
  quoteOrRate: 'rate',
@@ -83,7 +68,7 @@ export const getTradeRate = async (input, deps) => {
83
68
  sellAmountIncludingProtocolFeesCryptoBaseUnit: sellAmount,
84
69
  feeData: {
85
70
  protocolFees,
86
- networkFeeCryptoBaseUnit: feeDataFast.txFee,
71
+ networkFeeCryptoBaseUnit: txFee,
87
72
  },
88
73
  rate,
89
74
  source: SwapperName.Cetus,
@@ -94,8 +79,7 @@ export const getTradeRate = async (input, deps) => {
94
79
  },
95
80
  ],
96
81
  };
97
- rates.push(tradeRate);
98
- return Ok(rates);
82
+ return tradeDataResult.map(() => [tradeRate]);
99
83
  }
100
84
  catch (error) {
101
85
  return Err(makeSwapErrorRight({
@@ -1,3 +1,4 @@
1
1
  import type { ChainId } from '@shapeshiftoss/caip';
2
2
  export declare const SUPPORTED_CETUS_CHAIN_IDS: readonly ChainId[];
3
3
  export declare const isSupportedChainId: (chainId: ChainId) => chainId is ChainId;
4
+ export declare const PYTH_DEPENDENT_PROVIDERS: string[];
@@ -3,3 +3,4 @@ export const SUPPORTED_CETUS_CHAIN_IDS = [suiChainId];
3
3
  export const isSupportedChainId = (chainId) => {
4
4
  return SUPPORTED_CETUS_CHAIN_IDS.includes(chainId);
5
5
  };
6
+ export const PYTH_DEPENDENT_PROVIDERS = ['HAEDALPMM', 'HAEDALHMMV2', 'METASTABLE'];
@@ -1,13 +1,8 @@
1
- import type { CetusClmmSDK, Pool } from '@cetusprotocol/cetus-sui-clmm-sdk';
1
+ import type { RouterDataV3 } from '@cetusprotocol/aggregator-sdk';
2
+ import { AggregatorClient } from '@cetusprotocol/aggregator-sdk';
3
+ import { SuiClient } from '@cetusprotocol/aggregator-sdk/node_modules/@mysten/sui/client';
2
4
  import type { Asset } from '@shapeshiftoss/types';
3
- export declare const getCetusSDK: () => Promise<CetusClmmSDK>;
5
+ export declare const getAggregatorClient: (rpcUrl: string) => AggregatorClient;
6
+ export declare const getSuiClient: (rpcUrl: string) => SuiClient;
4
7
  export declare const getCoinType: (asset: Asset) => string;
5
- export declare const determineSwapDirection: (pool: Pool, sellCoinType: string, buyCoinType: string) => boolean;
6
- export declare const calculateAmountLimit: (estimatedAmount: string, slippageTolerancePercentageDecimal: string | undefined, isBuyAmount: boolean) => string;
7
- export declare const findBestPool: (sdk: CetusClmmSDK, sellCoinType: string, buyCoinType: string) => Promise<Pool | undefined>;
8
- export type CalculateSwapResult = {
9
- estimatedAmountOut: string;
10
- estimatedAmountIn: string;
11
- estimatedFeeAmount: string;
12
- };
13
- export declare const calculateSwapAmounts: (sdk: CetusClmmSDK, pool: Pool, sellAsset: Asset, buyAsset: Asset, sellAmount: string) => Promise<CalculateSwapResult | undefined>;
8
+ export declare const findBestRoute: (client: AggregatorClient, sellCoinType: string, buyCoinType: string, sellAmountCryptoBaseUnit: string, providers?: string[]) => Promise<RouterDataV3 | undefined>;
@@ -1,12 +1,27 @@
1
+ import { AggregatorClient, Env } from '@cetusprotocol/aggregator-sdk';
2
+ import { SuiClient } from '@cetusprotocol/aggregator-sdk/node_modules/@mysten/sui/client';
1
3
  import { fromAssetId } from '@shapeshiftoss/caip';
2
- import { bn, bnOrZero } from '@shapeshiftoss/utils';
3
- let sdkInstance;
4
- export const getCetusSDK = async () => {
5
- if (!sdkInstance) {
6
- const { initMainnetSDK } = await import('@cetusprotocol/cetus-sui-clmm-sdk');
7
- sdkInstance = initMainnetSDK();
4
+ let suiClientInstance;
5
+ let aggregatorClientInstance;
6
+ let currentRpcUrl;
7
+ export const getAggregatorClient = (rpcUrl) => {
8
+ if (!aggregatorClientInstance || !suiClientInstance || currentRpcUrl !== rpcUrl) {
9
+ suiClientInstance = new SuiClient({ url: rpcUrl });
10
+ aggregatorClientInstance = new AggregatorClient({
11
+ client: suiClientInstance,
12
+ env: Env.Mainnet,
13
+ signer: '0x0',
14
+ });
15
+ currentRpcUrl = rpcUrl;
16
+ }
17
+ return aggregatorClientInstance;
18
+ };
19
+ export const getSuiClient = (rpcUrl) => {
20
+ if (!suiClientInstance || currentRpcUrl !== rpcUrl) {
21
+ suiClientInstance = new SuiClient({ url: rpcUrl });
22
+ currentRpcUrl = rpcUrl;
8
23
  }
9
- return sdkInstance;
24
+ return suiClientInstance;
10
25
  };
11
26
  export const getCoinType = (asset) => {
12
27
  const { assetReference, assetNamespace } = fromAssetId(asset.assetId);
@@ -17,70 +32,25 @@ export const getCoinType = (asset) => {
17
32
  // For other tokens, the assetReference should be the full coin type
18
33
  return assetReference;
19
34
  };
20
- export const determineSwapDirection = (pool, sellCoinType, buyCoinType) => {
21
- if (pool.coinTypeA === sellCoinType && pool.coinTypeB === buyCoinType) {
22
- return true;
23
- }
24
- if (pool.coinTypeA === buyCoinType && pool.coinTypeB === sellCoinType) {
25
- return false;
26
- }
27
- throw new Error('Pool does not match the swap pair');
28
- };
29
- export const calculateAmountLimit = (estimatedAmount, slippageTolerancePercentageDecimal, isBuyAmount) => {
30
- if (!slippageTolerancePercentageDecimal) {
31
- return estimatedAmount;
32
- }
33
- const slippageFactor = bn(1).minus(slippageTolerancePercentageDecimal);
34
- if (isBuyAmount) {
35
- return bnOrZero(estimatedAmount).times(slippageFactor).toFixed(0);
36
- }
37
- const maxSlippageFactor = bn(1).plus(slippageTolerancePercentageDecimal);
38
- return bnOrZero(estimatedAmount).times(maxSlippageFactor).toFixed(0);
39
- };
40
- export const findBestPool = async (sdk, sellCoinType, buyCoinType) => {
41
- const pools = await sdk.Pool.getPoolByCoins([sellCoinType, buyCoinType]);
42
- if (!pools || pools.length === 0) {
43
- return undefined;
44
- }
45
- const poolWithLiquidity = pools.find(pool => {
46
- const hasLiquidity = pool.liquidity && bnOrZero(pool.liquidity).gt(0);
47
- return hasLiquidity;
35
+ export const findBestRoute = async (client, sellCoinType, buyCoinType, sellAmountCryptoBaseUnit, providers) => {
36
+ const routerData = await client.findRouters({
37
+ from: sellCoinType,
38
+ target: buyCoinType,
39
+ amount: sellAmountCryptoBaseUnit,
40
+ byAmountIn: true,
41
+ ...(providers && { providers }),
48
42
  });
49
- if (!poolWithLiquidity) {
50
- console.warn('[Cetus] No pools with liquidity found for', sellCoinType, buyCoinType, {
51
- totalPools: pools.length,
52
- pools: pools.map(p => ({ id: p.poolAddress, liquidity: p.liquidity })),
53
- });
43
+ if (!routerData) {
44
+ console.warn('[Cetus Aggregator] No route found for', sellCoinType, buyCoinType);
45
+ return undefined;
54
46
  }
55
- return poolWithLiquidity;
56
- };
57
- export const calculateSwapAmounts = async (sdk, pool, sellAsset, buyAsset, sellAmount) => {
58
- const sellCoinType = getCoinType(sellAsset);
59
- const buyCoinType = getCoinType(buyAsset);
60
- const a2b = determineSwapDirection(pool, sellCoinType, buyCoinType);
61
- const decimalsA = pool.coinTypeA === sellCoinType ? sellAsset.precision : buyAsset.precision;
62
- const decimalsB = pool.coinTypeA === sellCoinType ? buyAsset.precision : sellAsset.precision;
63
- const preSwapParams = {
64
- pool,
65
- currentSqrtPrice: pool.current_sqrt_price,
66
- coinTypeA: pool.coinTypeA,
67
- coinTypeB: pool.coinTypeB,
68
- decimalsA,
69
- decimalsB,
70
- a2b,
71
- byAmountIn: true,
72
- amount: sellAmount,
73
- };
74
- const preSwapResult = await sdk.Swap.preswap(preSwapParams);
75
- if (!preSwapResult) {
47
+ if (routerData.insufficientLiquidity) {
48
+ console.warn('[Cetus Aggregator] Insufficient liquidity for', sellCoinType, buyCoinType);
76
49
  return undefined;
77
50
  }
78
- if (preSwapResult.estimatedAmountOut === '0' || preSwapResult.estimatedAmountOut === '') {
51
+ if (routerData.error) {
52
+ console.warn('[Cetus Aggregator] Error finding route:', routerData.error);
79
53
  return undefined;
80
54
  }
81
- return {
82
- estimatedAmountOut: preSwapResult.estimatedAmountOut,
83
- estimatedAmountIn: preSwapResult.estimatedAmountIn,
84
- estimatedFeeAmount: preSwapResult.estimatedFeeAmount,
85
- };
55
+ return routerData;
86
56
  };
@@ -1,5 +1,3 @@
1
- /// <reference types="node" />
2
- /// <reference types="node" />
3
1
  import type { QuoteResponse, SwapInstructionsResponse } from '@jup-ag/api';
4
2
  import type { ChainId } from '@shapeshiftoss/caip';
5
3
  import type { solana } from '@shapeshiftoss/chain-adapters';
@@ -21,5 +21,6 @@
21
21
  "ETH.USDT-0XDAC17F958D2EE523A2206206994597C13D831EC7": "eip155:1/erc20:0xdac17f958d2ee523a2206206994597c13d831ec7",
22
22
  "ETH.WSTETH-0X7F39C581F595B53C5CB19BD0B3F8DA6C935E2CA0": "eip155:1/erc20:0x7f39c581f595b53c5cb19bd0b3f8da6c935e2ca0",
23
23
  "THOR.RUNE": "cosmos:thorchain-1/slip44:931",
24
+ "ZEC.ZEC": "bip122:00040fe8ec8471911baa1db1266ea15d/slip44:133",
24
25
  "MAYA.CACAO": "cosmos:mayachain-mainnet-v1/slip44:931"
25
26
  }