@mento-protocol/mento-sdk 3.2.6 → 3.2.7

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 (302) hide show
  1. package/package.json +7 -1
  2. package/dist/cache/routes.d.ts +0 -13
  3. package/dist/cache/routes.js +0 -14649
  4. package/dist/cache/tokens.d.ts +0 -68
  5. package/dist/cache/tokens.js +0 -488
  6. package/dist/core/abis/activePool.d.ts +0 -2
  7. package/dist/core/abis/activePool.js +0 -14
  8. package/dist/core/abis/addressesRegistry.d.ts +0 -2
  9. package/dist/core/abis/addressesRegistry.js +0 -26
  10. package/dist/core/abis/bipoolmanager.d.ts +0 -34
  11. package/dist/core/abis/bipoolmanager.js +0 -72
  12. package/dist/core/abis/borrowerOperations.d.ts +0 -9
  13. package/dist/core/abis/borrowerOperations.js +0 -89
  14. package/dist/core/abis/breakerbox.d.ts +0 -13
  15. package/dist/core/abis/breakerbox.js +0 -8
  16. package/dist/core/abis/broker.d.ts +0 -2
  17. package/dist/core/abis/broker.js +0 -9
  18. package/dist/core/abis/erc20.d.ts +0 -9
  19. package/dist/core/abis/erc20.js +0 -21
  20. package/dist/core/abis/fpmm.d.ts +0 -270
  21. package/dist/core/abis/fpmm.js +0 -49
  22. package/dist/core/abis/fpmmFactory.d.ts +0 -85
  23. package/dist/core/abis/fpmmFactory.js +0 -26
  24. package/dist/core/abis/hintHelpers.d.ts +0 -2
  25. package/dist/core/abis/hintHelpers.js +0 -14
  26. package/dist/core/abis/index.d.ts +0 -22
  27. package/dist/core/abis/index.js +0 -38
  28. package/dist/core/abis/liquidityStrategy.d.ts +0 -132
  29. package/dist/core/abis/liquidityStrategy.js +0 -10
  30. package/dist/core/abis/multiTroveGetter.d.ts +0 -8
  31. package/dist/core/abis/multiTroveGetter.js +0 -15
  32. package/dist/core/abis/priceFeed.d.ts +0 -7
  33. package/dist/core/abis/priceFeed.js +0 -16
  34. package/dist/core/abis/pricingmodule.d.ts +0 -2
  35. package/dist/core/abis/pricingmodule.js +0 -6
  36. package/dist/core/abis/reserve.d.ts +0 -3
  37. package/dist/core/abis/reserve.js +0 -18
  38. package/dist/core/abis/router.d.ts +0 -521
  39. package/dist/core/abis/router.js +0 -45
  40. package/dist/core/abis/sortedTroves.d.ts +0 -2
  41. package/dist/core/abis/sortedTroves.js +0 -15
  42. package/dist/core/abis/systemParams.d.ts +0 -2
  43. package/dist/core/abis/systemParams.js +0 -14
  44. package/dist/core/abis/troveManager.d.ts +0 -2
  45. package/dist/core/abis/troveManager.js +0 -27
  46. package/dist/core/abis/troveNFT.d.ts +0 -2
  47. package/dist/core/abis/troveNFT.js +0 -9
  48. package/dist/core/abis/virtualPool.d.ts +0 -50
  49. package/dist/core/abis/virtualPool.js +0 -11
  50. package/dist/core/abis/virtualPoolFactory.d.ts +0 -59
  51. package/dist/core/abis/virtualPoolFactory.js +0 -17
  52. package/dist/core/constants/addresses.d.ts +0 -18
  53. package/dist/core/constants/addresses.js +0 -113
  54. package/dist/core/constants/borrowConstants.d.ts +0 -10
  55. package/dist/core/constants/borrowConstants.js +0 -16
  56. package/dist/core/constants/borrowRegistries.d.ts +0 -7
  57. package/dist/core/constants/borrowRegistries.js +0 -34
  58. package/dist/core/constants/chainId.d.ts +0 -7
  59. package/dist/core/constants/chainId.js +0 -11
  60. package/dist/core/constants/contractNames.d.ts +0 -21
  61. package/dist/core/constants/contractNames.js +0 -24
  62. package/dist/core/constants/index.d.ts +0 -6
  63. package/dist/core/constants/index.js +0 -22
  64. package/dist/core/errors/base.d.ts +0 -8
  65. package/dist/core/errors/base.js +0 -17
  66. package/dist/core/errors/index.d.ts +0 -4
  67. package/dist/core/errors/index.js +0 -20
  68. package/dist/core/errors/oracle.d.ts +0 -9
  69. package/dist/core/errors/oracle.js +0 -15
  70. package/dist/core/errors/router.d.ts +0 -14
  71. package/dist/core/errors/router.js +0 -24
  72. package/dist/core/types/borrow.d.ts +0 -87
  73. package/dist/core/types/borrow.js +0 -3
  74. package/dist/core/types/contractAddresses.d.ts +0 -42
  75. package/dist/core/types/contractAddresses.js +0 -3
  76. package/dist/core/types/index.d.ts +0 -10
  77. package/dist/core/types/index.js +0 -26
  78. package/dist/core/types/liquidity.d.ts +0 -194
  79. package/dist/core/types/liquidity.js +0 -3
  80. package/dist/core/types/pool.d.ts +0 -208
  81. package/dist/core/types/pool.js +0 -14
  82. package/dist/core/types/provider.d.ts +0 -45
  83. package/dist/core/types/provider.js +0 -3
  84. package/dist/core/types/route.d.ts +0 -62
  85. package/dist/core/types/route.js +0 -3
  86. package/dist/core/types/token.d.ts +0 -21
  87. package/dist/core/types/token.js +0 -3
  88. package/dist/core/types/tradingLimits.d.ts +0 -91
  89. package/dist/core/types/tradingLimits.js +0 -3
  90. package/dist/core/types/tradingMode.d.ts +0 -24
  91. package/dist/core/types/tradingMode.js +0 -31
  92. package/dist/core/types/transaction.d.ts +0 -45
  93. package/dist/core/types/transaction.js +0 -3
  94. package/dist/esm/cache/routes.js +0 -14644
  95. package/dist/esm/cache/tokens.js +0 -480
  96. package/dist/esm/core/abis/activePool.js +0 -10
  97. package/dist/esm/core/abis/addressesRegistry.js +0 -22
  98. package/dist/esm/core/abis/bipoolmanager.js +0 -68
  99. package/dist/esm/core/abis/borrowerOperations.js +0 -85
  100. package/dist/esm/core/abis/breakerbox.js +0 -4
  101. package/dist/esm/core/abis/broker.js +0 -5
  102. package/dist/esm/core/abis/erc20.js +0 -17
  103. package/dist/esm/core/abis/fpmm.js +0 -45
  104. package/dist/esm/core/abis/fpmmFactory.js +0 -22
  105. package/dist/esm/core/abis/hintHelpers.js +0 -10
  106. package/dist/esm/core/abis/index.js +0 -21
  107. package/dist/esm/core/abis/liquidityStrategy.js +0 -6
  108. package/dist/esm/core/abis/multiTroveGetter.js +0 -11
  109. package/dist/esm/core/abis/priceFeed.js +0 -12
  110. package/dist/esm/core/abis/pricingmodule.js +0 -2
  111. package/dist/esm/core/abis/reserve.js +0 -14
  112. package/dist/esm/core/abis/router.js +0 -41
  113. package/dist/esm/core/abis/sortedTroves.js +0 -11
  114. package/dist/esm/core/abis/systemParams.js +0 -10
  115. package/dist/esm/core/abis/troveManager.js +0 -23
  116. package/dist/esm/core/abis/troveNFT.js +0 -5
  117. package/dist/esm/core/abis/virtualPool.js +0 -7
  118. package/dist/esm/core/abis/virtualPoolFactory.js +0 -13
  119. package/dist/esm/core/constants/addresses.js +0 -107
  120. package/dist/esm/core/constants/borrowConstants.js +0 -12
  121. package/dist/esm/core/constants/borrowRegistries.js +0 -29
  122. package/dist/esm/core/constants/chainId.js +0 -7
  123. package/dist/esm/core/constants/contractNames.js +0 -20
  124. package/dist/esm/core/constants/index.js +0 -5
  125. package/dist/esm/core/errors/base.js +0 -12
  126. package/dist/esm/core/errors/index.js +0 -3
  127. package/dist/esm/core/errors/oracle.js +0 -10
  128. package/dist/esm/core/errors/router.js +0 -18
  129. package/dist/esm/core/types/borrow.js +0 -1
  130. package/dist/esm/core/types/contractAddresses.js +0 -1
  131. package/dist/esm/core/types/index.js +0 -9
  132. package/dist/esm/core/types/liquidity.js +0 -1
  133. package/dist/esm/core/types/pool.js +0 -10
  134. package/dist/esm/core/types/provider.js +0 -1
  135. package/dist/esm/core/types/route.js +0 -1
  136. package/dist/esm/core/types/token.js +0 -1
  137. package/dist/esm/core/types/tradingLimits.js +0 -1
  138. package/dist/esm/core/types/tradingMode.js +0 -26
  139. package/dist/esm/core/types/transaction.js +0 -1
  140. package/dist/esm/index.js +0 -139
  141. package/dist/esm/package.json +0 -1
  142. package/dist/esm/services/borrow/BorrowService.js +0 -455
  143. package/dist/esm/services/borrow/borrowHelpers.js +0 -3
  144. package/dist/esm/services/borrow/borrowMath.js +0 -127
  145. package/dist/esm/services/borrow/index.js +0 -3
  146. package/dist/esm/services/borrow/internal/borrowApprovalService.js +0 -48
  147. package/dist/esm/services/borrow/internal/borrowContextStore.js +0 -35
  148. package/dist/esm/services/borrow/internal/borrowErc20.js +0 -38
  149. package/dist/esm/services/borrow/internal/borrowHints.js +0 -27
  150. package/dist/esm/services/borrow/internal/borrowPositionParser.js +0 -82
  151. package/dist/esm/services/borrow/internal/borrowReadService.js +0 -271
  152. package/dist/esm/services/borrow/internal/borrowRegistryReader.js +0 -108
  153. package/dist/esm/services/borrow/internal/borrowTransactionService.js +0 -271
  154. package/dist/esm/services/borrow/internal/borrowTypes.js +0 -1
  155. package/dist/esm/services/borrow/internal/borrowValidation.js +0 -89
  156. package/dist/esm/services/index.js +0 -8
  157. package/dist/esm/services/liquidity/LiquidityService.js +0 -163
  158. package/dist/esm/services/liquidity/basicLiquidity.js +0 -162
  159. package/dist/esm/services/liquidity/index.js +0 -1
  160. package/dist/esm/services/liquidity/liquidityHelpers.js +0 -95
  161. package/dist/esm/services/liquidity/rebalance.js +0 -59
  162. package/dist/esm/services/liquidity/zapHelpers.js +0 -120
  163. package/dist/esm/services/liquidity/zapIn.js +0 -112
  164. package/dist/esm/services/liquidity/zapOut.js +0 -248
  165. package/dist/esm/services/pools/PoolService.js +0 -204
  166. package/dist/esm/services/pools/index.js +0 -1
  167. package/dist/esm/services/pools/poolDetails.js +0 -209
  168. package/dist/esm/services/pools/poolDiscovery.js +0 -112
  169. package/dist/esm/services/pools/rebalancePreview.js +0 -181
  170. package/dist/esm/services/quotes/QuoteService.js +0 -85
  171. package/dist/esm/services/quotes/index.js +0 -1
  172. package/dist/esm/services/routes/RouteService.js +0 -268
  173. package/dist/esm/services/routes/index.js +0 -1
  174. package/dist/esm/services/swap/SwapService.js +0 -247
  175. package/dist/esm/services/swap/index.js +0 -1
  176. package/dist/esm/services/tokens/index.js +0 -1
  177. package/dist/esm/services/tokens/tokenService.js +0 -285
  178. package/dist/esm/services/trading/TradingLimitsService.js +0 -154
  179. package/dist/esm/services/trading/TradingService.js +0 -222
  180. package/dist/esm/services/trading/index.js +0 -2
  181. package/dist/esm/utils/chainConfig.js +0 -118
  182. package/dist/esm/utils/costUtils.js +0 -56
  183. package/dist/esm/utils/deadline.js +0 -22
  184. package/dist/esm/utils/index.js +0 -9
  185. package/dist/esm/utils/multicall.js +0 -47
  186. package/dist/esm/utils/pathEncoder.js +0 -69
  187. package/dist/esm/utils/rateFeed.js +0 -23
  188. package/dist/esm/utils/retry.js +0 -24
  189. package/dist/esm/utils/routeUtils.js +0 -361
  190. package/dist/esm/utils/routes.js +0 -2
  191. package/dist/esm/utils/sortUtils.js +0 -33
  192. package/dist/esm/utils/tokens.js +0 -2
  193. package/dist/esm/utils/tradingLimits.js +0 -163
  194. package/dist/esm/utils/validation.js +0 -30
  195. package/dist/index.d.ts +0 -101
  196. package/dist/index.js +0 -158
  197. package/dist/services/borrow/BorrowService.d.ts +0 -381
  198. package/dist/services/borrow/BorrowService.js +0 -460
  199. package/dist/services/borrow/borrowHelpers.d.ts +0 -4
  200. package/dist/services/borrow/borrowHelpers.js +0 -13
  201. package/dist/services/borrow/borrowMath.d.ts +0 -21
  202. package/dist/services/borrow/borrowMath.js +0 -137
  203. package/dist/services/borrow/index.d.ts +0 -4
  204. package/dist/services/borrow/index.js +0 -20
  205. package/dist/services/borrow/internal/borrowApprovalService.d.ts +0 -14
  206. package/dist/services/borrow/internal/borrowApprovalService.js +0 -53
  207. package/dist/services/borrow/internal/borrowContextStore.d.ts +0 -11
  208. package/dist/services/borrow/internal/borrowContextStore.js +0 -40
  209. package/dist/services/borrow/internal/borrowErc20.d.ts +0 -5
  210. package/dist/services/borrow/internal/borrowErc20.js +0 -43
  211. package/dist/services/borrow/internal/borrowHints.d.ts +0 -7
  212. package/dist/services/borrow/internal/borrowHints.js +0 -31
  213. package/dist/services/borrow/internal/borrowPositionParser.d.ts +0 -4
  214. package/dist/services/borrow/internal/borrowPositionParser.js +0 -87
  215. package/dist/services/borrow/internal/borrowReadService.d.ts +0 -31
  216. package/dist/services/borrow/internal/borrowReadService.js +0 -276
  217. package/dist/services/borrow/internal/borrowRegistryReader.d.ts +0 -5
  218. package/dist/services/borrow/internal/borrowRegistryReader.js +0 -113
  219. package/dist/services/borrow/internal/borrowTransactionService.d.ts +0 -23
  220. package/dist/services/borrow/internal/borrowTransactionService.js +0 -276
  221. package/dist/services/borrow/internal/borrowTypes.d.ts +0 -15
  222. package/dist/services/borrow/internal/borrowTypes.js +0 -3
  223. package/dist/services/borrow/internal/borrowValidation.d.ts +0 -14
  224. package/dist/services/borrow/internal/borrowValidation.js +0 -104
  225. package/dist/services/index.d.ts +0 -9
  226. package/dist/services/index.js +0 -25
  227. package/dist/services/liquidity/LiquidityService.d.ts +0 -139
  228. package/dist/services/liquidity/LiquidityService.js +0 -168
  229. package/dist/services/liquidity/basicLiquidity.d.ts +0 -11
  230. package/dist/services/liquidity/basicLiquidity.js +0 -172
  231. package/dist/services/liquidity/index.d.ts +0 -2
  232. package/dist/services/liquidity/index.js +0 -18
  233. package/dist/services/liquidity/liquidityHelpers.d.ts +0 -19
  234. package/dist/services/liquidity/liquidityHelpers.js +0 -104
  235. package/dist/services/liquidity/rebalance.d.ts +0 -6
  236. package/dist/services/liquidity/rebalance.js +0 -64
  237. package/dist/services/liquidity/zapHelpers.d.ts +0 -66
  238. package/dist/services/liquidity/zapHelpers.js +0 -129
  239. package/dist/services/liquidity/zapIn.d.ts +0 -18
  240. package/dist/services/liquidity/zapIn.js +0 -119
  241. package/dist/services/liquidity/zapOut.d.ts +0 -9
  242. package/dist/services/liquidity/zapOut.js +0 -255
  243. package/dist/services/pools/PoolService.d.ts +0 -69
  244. package/dist/services/pools/PoolService.js +0 -209
  245. package/dist/services/pools/index.d.ts +0 -2
  246. package/dist/services/pools/index.js +0 -18
  247. package/dist/services/pools/poolDetails.d.ts +0 -13
  248. package/dist/services/pools/poolDetails.js +0 -216
  249. package/dist/services/pools/poolDiscovery.d.ts +0 -12
  250. package/dist/services/pools/poolDiscovery.js +0 -117
  251. package/dist/services/pools/rebalancePreview.d.ts +0 -5
  252. package/dist/services/pools/rebalancePreview.js +0 -186
  253. package/dist/services/quotes/QuoteService.d.ts +0 -51
  254. package/dist/services/quotes/QuoteService.js +0 -91
  255. package/dist/services/quotes/index.d.ts +0 -2
  256. package/dist/services/quotes/index.js +0 -18
  257. package/dist/services/routes/RouteService.d.ts +0 -117
  258. package/dist/services/routes/RouteService.js +0 -306
  259. package/dist/services/routes/index.d.ts +0 -2
  260. package/dist/services/routes/index.js +0 -18
  261. package/dist/services/swap/SwapService.d.ts +0 -198
  262. package/dist/services/swap/SwapService.js +0 -252
  263. package/dist/services/swap/index.d.ts +0 -2
  264. package/dist/services/swap/index.js +0 -18
  265. package/dist/services/tokens/index.d.ts +0 -2
  266. package/dist/services/tokens/index.js +0 -18
  267. package/dist/services/tokens/tokenService.d.ts +0 -55
  268. package/dist/services/tokens/tokenService.js +0 -290
  269. package/dist/services/trading/TradingLimitsService.d.ts +0 -38
  270. package/dist/services/trading/TradingLimitsService.js +0 -159
  271. package/dist/services/trading/TradingService.d.ts +0 -115
  272. package/dist/services/trading/TradingService.js +0 -227
  273. package/dist/services/trading/index.d.ts +0 -3
  274. package/dist/services/trading/index.js +0 -19
  275. package/dist/utils/chainConfig.d.ts +0 -16
  276. package/dist/utils/chainConfig.js +0 -123
  277. package/dist/utils/costUtils.d.ts +0 -12
  278. package/dist/utils/costUtils.js +0 -60
  279. package/dist/utils/deadline.d.ts +0 -21
  280. package/dist/utils/deadline.js +0 -26
  281. package/dist/utils/index.d.ts +0 -10
  282. package/dist/utils/index.js +0 -26
  283. package/dist/utils/multicall.d.ts +0 -30
  284. package/dist/utils/multicall.js +0 -52
  285. package/dist/utils/pathEncoder.d.ts +0 -34
  286. package/dist/utils/pathEncoder.js +0 -73
  287. package/dist/utils/rateFeed.d.ts +0 -18
  288. package/dist/utils/rateFeed.js +0 -27
  289. package/dist/utils/retry.d.ts +0 -12
  290. package/dist/utils/retry.js +0 -28
  291. package/dist/utils/routeUtils.d.ts +0 -295
  292. package/dist/utils/routeUtils.js +0 -371
  293. package/dist/utils/routes.d.ts +0 -3
  294. package/dist/utils/routes.js +0 -8
  295. package/dist/utils/sortUtils.d.ts +0 -24
  296. package/dist/utils/sortUtils.js +0 -39
  297. package/dist/utils/tokens.d.ts +0 -2
  298. package/dist/utils/tokens.js +0 -13
  299. package/dist/utils/tradingLimits.d.ts +0 -41
  300. package/dist/utils/tradingLimits.js +0 -171
  301. package/dist/utils/validation.d.ts +0 -19
  302. package/dist/utils/validation.js +0 -34
@@ -1,247 +0,0 @@
1
- import { encodeFunctionData } from 'viem';
2
- import { ROUTER_ABI, ERC20_ABI } from '../../core/abis';
3
- import { getContractAddress } from '../../core/constants';
4
- import { encodeRoutePath } from '../../utils/pathEncoder';
5
- import { validateAddress } from '../../utils/validation';
6
- import { retryOperation } from '../../utils';
7
- import { getAmountOutForRoute } from '../quotes/QuoteService';
8
- /**
9
- * Service for building token swap transactions on the Mento protocol.
10
- * Returns transaction parameters that can be executed by any wallet.
11
- */
12
- export class SwapService {
13
- constructor(publicClient, chainId, routeService, quoteService) {
14
- this.publicClient = publicClient;
15
- this.chainId = chainId;
16
- this.routeService = routeService;
17
- this.quoteService = quoteService;
18
- }
19
- /**
20
- * Builds a complete swap transaction including approval if needed.
21
- * This is the recommended method for most use cases.
22
- *
23
- * @param tokenIn - The address of the input token (e.g., '0x765DE816845861e75A25fCA122bb6898B8B1282a')
24
- * @param tokenOut - The address of the output token (e.g., '0x471EcE3750Da237f93B8E339c536989b8978a438')
25
- * @param amountIn - The amount of input tokens (in wei/smallest unit)
26
- * @param recipient - The address to receive the output tokens
27
- * @param owner - The address that owns the input tokens (needed to check allowance)
28
- * @param options - Swap configuration options (slippage, deadline)
29
- * @param route - Optional pre-fetched route for better performance
30
- * @returns Combined transaction with approval (if needed) and swap params
31
- * @throws {Error} 'amountIn must be greater than zero' - if amountIn <= 0
32
- * @throws {Error} 'Slippage tolerance cannot be negative' - if slippageTolerance < 0
33
- * @throws {Error} 'Slippage tolerance exceeds maximum' - if slippageTolerance > 20%
34
- * @throws {Error} 'Deadline must be in the future' - if deadline is not a future timestamp
35
- * @throws {Error} Invalid address - if any address parameter is not a valid Ethereum address
36
- * @throws {RouteNotFoundError} If no trading route exists between the token pair
37
- *
38
- * @example
39
- * ```typescript
40
- * const { approval, swap } = await mento.swap.buildSwapTransaction(
41
- * '0x765DE816845861e75A25fCA122bb6898B8B1282a', // USDm
42
- * '0x471EcE3750Da237f93B8E339c536989b8978a438', // CELO
43
- * parseUnits('100', 18),
44
- * '0x742d35Cc6634C0532925a3b844Bc454e4438f44e', // recipient
45
- * '0x123...', // owner
46
- * { slippageTolerance: 0.5, deadline: deadlineFromMinutes(5) }
47
- * )
48
- *
49
- * // Execute approval if needed
50
- * if (approval) {
51
- * await walletClient.sendTransaction(approval)
52
- * }
53
- *
54
- * // Execute swap
55
- * await walletClient.sendTransaction(swap.params)
56
- * ```
57
- */
58
- async buildSwapTransaction(tokenIn, tokenOut, amountIn, recipient, owner, options, route) {
59
- const prepared = await this.prepareSwap({
60
- amountIn,
61
- deadline: options.deadline,
62
- owner,
63
- recipient,
64
- route,
65
- slippageTolerance: options.slippageTolerance,
66
- tokenIn,
67
- tokenOut,
68
- });
69
- if (!prepared.params) {
70
- throw new Error('Swap params were not prepared');
71
- }
72
- return {
73
- approval: prepared.approval ?? null,
74
- swap: {
75
- params: prepared.params,
76
- route: prepared.route,
77
- routerRoutes: prepared.routerRoutes,
78
- amountIn,
79
- amountOutMin: prepared.amountOutMin,
80
- expectedAmountOut: prepared.expectedAmountOut,
81
- deadline: options.deadline,
82
- },
83
- };
84
- }
85
- /**
86
- * Builds swap transaction parameters without executing the transaction.
87
- * Does NOT check or handle token approval - use buildSwapTransaction for that.
88
- *
89
- * @param tokenIn - The address of the input token (e.g., '0x765DE816845861e75A25fCA122bb6898B8B1282a')
90
- * @param tokenOut - The address of the output token (e.g., '0x471EcE3750Da237f93B8E339c536989b8978a438')
91
- * @param amountIn - The amount of input tokens (in wei/smallest unit)
92
- * @param recipient - The address to receive the output tokens
93
- * @param options - Swap configuration options (slippage, deadline)
94
- * @param route - Optional pre-fetched route for better performance
95
- * @returns Detailed swap parameters including transaction data
96
- * @throws {Error} 'amountIn must be greater than zero' - if amountIn <= 0
97
- * @throws {Error} 'Slippage tolerance cannot be negative' - if slippageTolerance < 0
98
- * @throws {Error} 'Slippage tolerance exceeds maximum' - if slippageTolerance > 20%
99
- * @throws {Error} 'Deadline must be in the future' - if deadline is not a future timestamp
100
- * @throws {Error} Invalid address - if any address parameter is not a valid Ethereum address
101
- * @throws {RouteNotFoundError} If no trading route exists between the token pair
102
- *
103
- * @example
104
- * ```typescript
105
- * const swapDetails = await mento.swap.buildSwapParams(
106
- * '0x765DE816845861e75A25fCA122bb6898B8B1282a', // USDm
107
- * '0x471EcE3750Da237f93B8E339c536989b8978a438', // CELO
108
- * parseUnits('100', 18),
109
- * '0x742d35Cc6634C0532925a3b844Bc454e4438f44e', // recipient
110
- * { slippageTolerance: 0.5, deadline: deadlineFromMinutes(5) }
111
- * )
112
- *
113
- * // Execute with any wallet (assumes approval already granted)
114
- * await walletClient.sendTransaction(swapDetails.params)
115
- * ```
116
- */
117
- async buildSwapParams(tokenIn, tokenOut, amountIn, recipient, options, route) {
118
- const prepared = await this.prepareSwap({
119
- amountIn,
120
- deadline: options.deadline,
121
- recipient,
122
- route,
123
- slippageTolerance: options.slippageTolerance,
124
- tokenIn,
125
- tokenOut,
126
- });
127
- if (!prepared.params) {
128
- throw new Error('Swap params were not prepared');
129
- }
130
- return {
131
- params: prepared.params,
132
- route: prepared.route,
133
- routerRoutes: prepared.routerRoutes,
134
- amountIn,
135
- amountOutMin: prepared.amountOutMin,
136
- expectedAmountOut: prepared.expectedAmountOut,
137
- deadline: options.deadline,
138
- };
139
- }
140
- async prepareSwap(input) {
141
- this.validateAmountIn(input.amountIn);
142
- validateAddress(input.tokenIn, 'tokenIn');
143
- validateAddress(input.tokenOut, 'tokenOut');
144
- if (input.recipient) {
145
- validateAddress(input.recipient, 'recipient');
146
- }
147
- if (input.owner) {
148
- validateAddress(input.owner, 'owner');
149
- }
150
- if (input.deadline !== undefined && input.deadline <= BigInt(Date.now()) / 1000n) {
151
- throw new Error('Deadline must be in the future');
152
- }
153
- const route = input.route ?? await this.routeService.findRoute(input.tokenIn, input.tokenOut);
154
- const routerRoutes = encodeRoutePath(route.path, input.tokenIn, input.tokenOut);
155
- const expectedAmountOut = await getAmountOutForRoute(this.publicClient, this.chainId, input.tokenIn, input.tokenOut, input.amountIn, route);
156
- const amountOutMin = this.calculateMinAmountOut(expectedAmountOut, input.slippageTolerance);
157
- const prepared = {
158
- route,
159
- routerRoutes,
160
- expectedAmountOut,
161
- amountOutMin,
162
- };
163
- if (input.owner) {
164
- const currentAllowance = await this.getAllowance(input.tokenIn, input.owner);
165
- prepared.approval = currentAllowance < input.amountIn
166
- ? this.buildApprovalParams(input.tokenIn, input.amountIn)
167
- : null;
168
- }
169
- if (input.recipient && input.deadline !== undefined) {
170
- const routerAddress = getContractAddress(this.chainId, 'Router');
171
- const data = this.encodeSwapCall(input.amountIn, amountOutMin, routerRoutes, input.recipient, input.deadline);
172
- prepared.params = {
173
- to: routerAddress,
174
- data,
175
- value: '0',
176
- };
177
- }
178
- return prepared;
179
- }
180
- /**
181
- * Builds approval transaction params for the Router to spend tokenIn
182
- * @private
183
- */
184
- buildApprovalParams(tokenIn, amount) {
185
- const routerAddress = getContractAddress(this.chainId, 'Router');
186
- const data = encodeFunctionData({
187
- abi: ERC20_ABI,
188
- functionName: 'approve',
189
- args: [routerAddress, amount],
190
- });
191
- return { to: tokenIn, data, value: '0' };
192
- }
193
- /**
194
- * Gets current allowance for the Router contract
195
- * @private
196
- */
197
- async getAllowance(tokenIn, owner) {
198
- const routerAddress = getContractAddress(this.chainId, 'Router');
199
- return retryOperation(() => this.publicClient.readContract({
200
- address: tokenIn,
201
- abi: ERC20_ABI,
202
- functionName: 'allowance',
203
- args: [owner, routerAddress],
204
- }));
205
- }
206
- /**
207
- * Validates that the input amount is strictly positive.
208
- * @private
209
- */
210
- validateAmountIn(amountIn) {
211
- if (amountIn <= 0n) {
212
- throw new Error('amountIn must be greater than zero');
213
- }
214
- }
215
- /**
216
- * Calculates minimum output amount after applying slippage tolerance
217
- * @param amountOut - Expected output amount
218
- * @param slippageTolerance - Slippage tolerance as percentage (e.g., 0.5 for 0.5%)
219
- * @returns Minimum acceptable output amount
220
- * @throws Error if slippage tolerance is invalid
221
- * @private
222
- */
223
- calculateMinAmountOut(amountOut, slippageTolerance) {
224
- const MAX_SLIPPAGE_TOLERANCE = 20; // 20% max
225
- if (slippageTolerance < 0) {
226
- throw new Error('Slippage tolerance cannot be negative');
227
- }
228
- if (slippageTolerance > MAX_SLIPPAGE_TOLERANCE) {
229
- throw new Error(`Slippage tolerance ${slippageTolerance}% exceeds maximum of ${MAX_SLIPPAGE_TOLERANCE}%. ` +
230
- 'High slippage makes transactions vulnerable to sandwich attacks.');
231
- }
232
- const basisPoints = BigInt(Math.floor(slippageTolerance * 100));
233
- const slippageMultiplier = 10000n - basisPoints;
234
- return (amountOut * slippageMultiplier) / 10000n;
235
- }
236
- /**
237
- * Encodes the swapExactTokensForTokens function call
238
- * @private
239
- */
240
- encodeSwapCall(amountIn, amountOutMin, routes, recipient, deadline) {
241
- return encodeFunctionData({
242
- abi: ROUTER_ABI,
243
- functionName: 'swapExactTokensForTokens',
244
- args: [amountIn, amountOutMin, routes, recipient, deadline],
245
- });
246
- }
247
- }
@@ -1 +0,0 @@
1
- export * from './SwapService';
@@ -1 +0,0 @@
1
- export * from './tokenService';
@@ -1,285 +0,0 @@
1
- import { RESERVE_ABI, RESERVE_V2_ABI, BIPOOL_MANAGER_ABI, ERC20_ABI } from '../../core/abis';
2
- import { getContractAddress, tryGetContractAddress, ChainId, RESERVE, BIPOOLMANAGER, } from '../../core/constants';
3
- import { retryOperation } from '../../utils';
4
- import { multicall } from '../../utils/multicall';
5
- /**
6
- * Chains that use ReserveV2 (v3) instead of the legacy Reserve contract.
7
- */
8
- const RESERVE_V2_CHAINS = new Set([ChainId.MONAD_TESTNET, ChainId.MONAD]);
9
- export class TokenService {
10
- constructor(publicClient, chainId) {
11
- this.publicClient = publicClient;
12
- this.chainId = chainId;
13
- this.tokenMetadataCache = new Map();
14
- }
15
- isReserveV2() {
16
- return RESERVE_V2_CHAINS.has(this.chainId);
17
- }
18
- /**
19
- * Get token metadata (name, symbol, decimals)
20
- * @param address - Token contract address
21
- * @returns Token metadata
22
- */
23
- async getTokenMetadata(address) {
24
- const cacheKey = address.toLowerCase();
25
- const cached = this.tokenMetadataCache.get(cacheKey);
26
- if (cached) {
27
- return cached;
28
- }
29
- const [metadata] = await this.getTokenMetadataBatch([address]);
30
- this.tokenMetadataCache.set(cacheKey, metadata);
31
- return metadata;
32
- }
33
- async getTokenMetadataBatch(addresses) {
34
- if (addresses.length === 0) {
35
- return [];
36
- }
37
- const results = new Array(addresses.length);
38
- const missing = [];
39
- for (const [index, address] of addresses.entries()) {
40
- const cached = this.tokenMetadataCache.get(address.toLowerCase());
41
- if (cached) {
42
- results[index] = cached;
43
- continue;
44
- }
45
- missing.push({ address, index });
46
- }
47
- if (missing.length === 0) {
48
- return results;
49
- }
50
- const multicallResults = await multicall(this.publicClient, missing.flatMap(({ address }) => ([
51
- {
52
- address: address,
53
- abi: ERC20_ABI,
54
- functionName: 'name',
55
- args: [],
56
- },
57
- {
58
- address: address,
59
- abi: ERC20_ABI,
60
- functionName: 'symbol',
61
- args: [],
62
- },
63
- {
64
- address: address,
65
- abi: ERC20_ABI,
66
- functionName: 'decimals',
67
- args: [],
68
- },
69
- ])), { allowFailure: true });
70
- const hydrated = await Promise.all(missing.map(async ({ address }, index) => {
71
- const resultOffset = index * 3;
72
- const name = multicallResults[resultOffset];
73
- const symbol = multicallResults[resultOffset + 1];
74
- const decimals = multicallResults[resultOffset + 2];
75
- if (name?.status === 'success' &&
76
- symbol?.status === 'success' &&
77
- decimals?.status === 'success') {
78
- return {
79
- name: name.result,
80
- symbol: symbol.result,
81
- decimals: Number(decimals.result),
82
- };
83
- }
84
- return this.readTokenMetadataWithRetry(address);
85
- }));
86
- for (const [index, metadata] of hydrated.entries()) {
87
- const address = missing[index].address;
88
- this.tokenMetadataCache.set(address.toLowerCase(), metadata);
89
- results[missing[index].index] = metadata;
90
- }
91
- return results;
92
- }
93
- async readTokenMetadataWithRetry(address) {
94
- const [name, symbol, decimals] = await Promise.all([
95
- retryOperation(() => this.publicClient.readContract({
96
- address: address,
97
- abi: ERC20_ABI,
98
- functionName: 'name',
99
- args: [],
100
- })),
101
- retryOperation(() => this.publicClient.readContract({
102
- address: address,
103
- abi: ERC20_ABI,
104
- functionName: 'symbol',
105
- args: [],
106
- })),
107
- retryOperation(() => this.publicClient.readContract({
108
- address: address,
109
- abi: ERC20_ABI,
110
- functionName: 'decimals',
111
- args: [],
112
- })),
113
- ]);
114
- return {
115
- name: name,
116
- symbol: symbol,
117
- decimals: Number(decimals),
118
- };
119
- }
120
- /**
121
- * Get total supply of a token
122
- * @param address - Token contract address
123
- * @returns Total supply as string
124
- */
125
- async getTotalSupply(address) {
126
- const [totalSupply] = await this.getTotalSupplyBatch([address]);
127
- return totalSupply;
128
- }
129
- async getTotalSupplyBatch(addresses) {
130
- if (addresses.length === 0) {
131
- return [];
132
- }
133
- const results = await multicall(this.publicClient, addresses.map((address) => ({
134
- address: address,
135
- abi: ERC20_ABI,
136
- functionName: 'totalSupply',
137
- args: [],
138
- })), { allowFailure: true });
139
- return Promise.all(addresses.map(async (address, index) => {
140
- const result = results[index];
141
- if (result?.status === 'success') {
142
- return result.result.toString();
143
- }
144
- return this.readTotalSupplyWithRetry(address);
145
- }));
146
- }
147
- async readTotalSupplyWithRetry(address) {
148
- const totalSupply = await retryOperation(() => this.publicClient.readContract({
149
- address: address,
150
- abi: ERC20_ABI,
151
- functionName: 'totalSupply',
152
- args: [],
153
- }));
154
- return totalSupply.toString();
155
- }
156
- async getCollateralStatusBatch(reserveAddress, addresses) {
157
- if (addresses.length === 0) {
158
- return [];
159
- }
160
- const results = await multicall(this.publicClient, addresses.map((address) => ({
161
- address: reserveAddress,
162
- abi: RESERVE_ABI,
163
- functionName: 'isCollateralAsset',
164
- args: [address],
165
- })), { allowFailure: true });
166
- return Promise.all(addresses.map(async (address, index) => {
167
- const result = results[index];
168
- if (result?.status === 'success') {
169
- return result.result;
170
- }
171
- return this.readCollateralStatusWithRetry(reserveAddress, address);
172
- }));
173
- }
174
- async readCollateralStatusWithRetry(reserveAddress, address) {
175
- return retryOperation(() => this.publicClient.readContract({
176
- address: reserveAddress,
177
- abi: RESERVE_ABI,
178
- functionName: 'isCollateralAsset',
179
- args: [address],
180
- }));
181
- }
182
- /**
183
- * Get stable token addresses from the Reserve contract.
184
- * Uses getStableAssets() on ReserveV2, getTokens() on legacy Reserve.
185
- */
186
- async getStableTokenAddresses(reserveAddress) {
187
- if (this.isReserveV2()) {
188
- return (await this.publicClient.readContract({
189
- address: reserveAddress,
190
- abi: RESERVE_V2_ABI,
191
- functionName: 'getStableAssets',
192
- args: [],
193
- }));
194
- }
195
- return (await this.publicClient.readContract({
196
- address: reserveAddress,
197
- abi: RESERVE_ABI,
198
- functionName: 'getTokens',
199
- args: [],
200
- }));
201
- }
202
- /**
203
- * Get all stable tokens from the Reserve contract.
204
- * Returns the actual on-chain ERC20 totalSupply values without adjustments.
205
- * @param includeSupply - Whether to fetch total supply
206
- * @returns Array of stable tokens
207
- */
208
- async getStableTokens(includeSupply = true) {
209
- const reserveAddress = getContractAddress(this.chainId, RESERVE);
210
- const tokenAddresses = await this.getStableTokenAddresses(reserveAddress);
211
- const [metadataList, totalSupplies] = await Promise.all([
212
- this.getTokenMetadataBatch(tokenAddresses),
213
- includeSupply ? this.getTotalSupplyBatch(tokenAddresses) : Promise.resolve(tokenAddresses.map(() => '0')),
214
- ]);
215
- const tokens = tokenAddresses.map((address, index) => ({
216
- address,
217
- ...metadataList[index],
218
- totalSupply: totalSupplies[index],
219
- }));
220
- return tokens;
221
- }
222
- /**
223
- * Get all collateral assets.
224
- * On ReserveV2 chains, queries the reserve directly.
225
- * On legacy chains, discovers collateral via BiPoolManager exchanges.
226
- * @returns Array of collateral assets
227
- */
228
- async getCollateralAssets() {
229
- if (this.isReserveV2()) {
230
- return this.getCollateralAssetsV2();
231
- }
232
- return this.getCollateralAssetsLegacy();
233
- }
234
- /**
235
- * Get collateral assets directly from ReserveV2.
236
- */
237
- async getCollateralAssetsV2() {
238
- const reserveAddress = getContractAddress(this.chainId, RESERVE);
239
- const collateralAddresses = (await retryOperation(() => this.publicClient.readContract({
240
- address: reserveAddress,
241
- abi: RESERVE_V2_ABI,
242
- functionName: 'getCollateralAssets',
243
- args: [],
244
- })));
245
- const metadataList = await this.getTokenMetadataBatch(collateralAddresses);
246
- const assets = collateralAddresses.map((address, index) => ({
247
- address,
248
- ...metadataList[index],
249
- }));
250
- return assets;
251
- }
252
- /**
253
- * Get collateral assets from legacy Reserve via BiPoolManager exchanges.
254
- */
255
- async getCollateralAssetsLegacy() {
256
- const biPoolManagerAddress = tryGetContractAddress(this.chainId, BIPOOLMANAGER);
257
- if (!biPoolManagerAddress) {
258
- return [];
259
- }
260
- const reserveAddress = getContractAddress(this.chainId, RESERVE);
261
- // Get all exchanges to find unique token addresses
262
- const exchanges = (await retryOperation(() => this.publicClient.readContract({
263
- address: biPoolManagerAddress,
264
- abi: BIPOOL_MANAGER_ABI,
265
- functionName: 'getExchanges',
266
- })));
267
- // Extract unique token addresses from exchanges
268
- const uniqueAddresses = new Set();
269
- for (const exchange of exchanges) {
270
- exchange.assets.forEach((address) => uniqueAddresses.add(address));
271
- }
272
- const addresses = Array.from(uniqueAddresses);
273
- const [collateralStatuses, metadataList] = await Promise.all([
274
- this.getCollateralStatusBatch(reserveAddress, addresses),
275
- this.getTokenMetadataBatch(addresses),
276
- ]);
277
- const results = addresses.map((address, index) => {
278
- if (!collateralStatuses[index]) {
279
- return null;
280
- }
281
- return { address, ...metadataList[index] };
282
- });
283
- return results.filter((asset) => asset !== null);
284
- }
285
- }
@@ -1,154 +0,0 @@
1
- import { PoolType } from '../../core/types';
2
- import { FPMM_ABI, BROKER_ABI } from '../../core/abis';
3
- import { tryGetContractAddress } from '../../core/constants';
4
- import { computeLimitId, calculateTradingLimitsV1, calculateTradingLimitsV2, hasConfiguredLimitsV1, hasConfiguredLimitsV2, } from '../../utils/tradingLimits';
5
- /**
6
- * Service for querying trading limits from the Mento protocol.
7
- * Supports both FPMM pools (TradingLimitsV2) and Virtual pools (TradingLimitsV1).
8
- */
9
- export class TradingLimitsService {
10
- constructor(publicClient, chainId) {
11
- this.publicClient = publicClient;
12
- this.chainId = chainId;
13
- }
14
- /**
15
- * Get trading limits for a pool.
16
- * Returns an array of TradingLimit objects for each configured limit.
17
- *
18
- * @param pool - The pool to get trading limits for
19
- * @returns Array of TradingLimit objects with maxIn/maxOut/until
20
- */
21
- async getPoolTradingLimits(pool) {
22
- if (pool.poolType === PoolType.FPMM) {
23
- return this.getFPMMTradingLimits(pool);
24
- }
25
- else {
26
- return this.getVirtualPoolTradingLimits(pool);
27
- }
28
- }
29
- /**
30
- * Get trading limits for an FPMM pool.
31
- * FPMM pools use TradingLimitsV2 with fixed timeframes.
32
- */
33
- async getFPMMTradingLimits(pool) {
34
- const limits = [];
35
- // Get trading limits for both tokens
36
- const [token0Limits, token1Limits] = await Promise.all([
37
- this.getFPMMTokenLimits(pool.poolAddr, pool.token0),
38
- this.getFPMMTokenLimits(pool.poolAddr, pool.token1),
39
- ]);
40
- limits.push(...token0Limits);
41
- limits.push(...token1Limits);
42
- return limits;
43
- }
44
- /**
45
- * Get trading limits for a specific token in an FPMM pool.
46
- */
47
- async getFPMMTokenLimits(poolAddr, token) {
48
- try {
49
- const result = await this.publicClient.readContract({
50
- address: poolAddr,
51
- abi: FPMM_ABI,
52
- functionName: 'getTradingLimits',
53
- args: [token],
54
- });
55
- // Result is a tuple: [config, state]
56
- const [configTuple, stateTuple] = result;
57
- const config = {
58
- limit0: configTuple.limit0,
59
- limit1: configTuple.limit1,
60
- decimals: configTuple.decimals,
61
- };
62
- const state = {
63
- lastUpdated0: Number(stateTuple.lastUpdated0),
64
- lastUpdated1: Number(stateTuple.lastUpdated1),
65
- netflow0: stateTuple.netflow0,
66
- netflow1: stateTuple.netflow1,
67
- };
68
- if (!hasConfiguredLimitsV2(config)) {
69
- return [];
70
- }
71
- return calculateTradingLimitsV2(config, state, token);
72
- }
73
- catch {
74
- // Token may not have limits configured, or invalid token
75
- return [];
76
- }
77
- }
78
- /**
79
- * Get trading limits for a Virtual pool.
80
- * Virtual pools use TradingLimitsV1 via the Broker contract.
81
- */
82
- async getVirtualPoolTradingLimits(pool) {
83
- if (!pool.exchangeId) {
84
- return [];
85
- }
86
- const limits = [];
87
- // Get trading limits for both tokens
88
- const [token0Limits, token1Limits] = await Promise.all([
89
- this.getVirtualPoolTokenLimits(pool.exchangeId, pool.token0),
90
- this.getVirtualPoolTokenLimits(pool.exchangeId, pool.token1),
91
- ]);
92
- limits.push(...token0Limits);
93
- limits.push(...token1Limits);
94
- return limits;
95
- }
96
- /**
97
- * Get trading limits for a specific token in a Virtual pool.
98
- */
99
- async getVirtualPoolTokenLimits(exchangeId, token) {
100
- const brokerAddr = tryGetContractAddress(this.chainId, 'Broker');
101
- if (!brokerAddr) {
102
- return [];
103
- }
104
- const limitId = computeLimitId(exchangeId, token);
105
- try {
106
- // Fetch config and state in parallel
107
- const [configResult, stateResult] = await Promise.all([
108
- this.publicClient.readContract({
109
- address: brokerAddr,
110
- abi: BROKER_ABI,
111
- functionName: 'tradingLimitsConfig',
112
- args: [limitId],
113
- }),
114
- this.publicClient.readContract({
115
- address: brokerAddr,
116
- abi: BROKER_ABI,
117
- functionName: 'tradingLimitsState',
118
- args: [limitId],
119
- }),
120
- ]);
121
- // Parse config result
122
- const configTuple = configResult;
123
- const config = {
124
- timestep0: Number(configTuple[0]),
125
- timestep1: Number(configTuple[1]),
126
- limit0: configTuple[2],
127
- limit1: configTuple[3],
128
- limitGlobal: configTuple[4],
129
- flags: Number(configTuple[5]),
130
- };
131
- // Parse state result
132
- const stateTuple = stateResult;
133
- const state = {
134
- lastUpdated0: Number(stateTuple[0]),
135
- lastUpdated1: Number(stateTuple[1]),
136
- netflow0: stateTuple[2],
137
- netflow1: stateTuple[3],
138
- netflowGlobal: stateTuple[4],
139
- };
140
- // Only return limits if configured
141
- if (!hasConfiguredLimitsV1(config)) {
142
- return [];
143
- }
144
- // Get token decimals (V1 uses 0 decimals internally, but we track token decimals for display)
145
- // For now, return 0 as the reference - consumers should query token decimals separately
146
- const tokenDecimals = 0; // V1 stores values with 0 decimal precision
147
- return calculateTradingLimitsV1(config, state, token, tokenDecimals);
148
- }
149
- catch {
150
- // Trading limits may not be configured for this token
151
- return [];
152
- }
153
- }
154
- }