@haneullabs/deepbook-v3 0.1.0

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 (378) hide show
  1. package/CHANGELOG.md +984 -0
  2. package/README.md +1 -0
  3. package/dist/cjs/client.d.ts +861 -0
  4. package/dist/cjs/client.js +1982 -0
  5. package/dist/cjs/client.js.map +7 -0
  6. package/dist/cjs/contracts/deepbook/account.d.ts +105 -0
  7. package/dist/cjs/contracts/deepbook/account.js +163 -0
  8. package/dist/cjs/contracts/deepbook/account.js.map +7 -0
  9. package/dist/cjs/contracts/deepbook/balance_manager.d.ts +268 -0
  10. package/dist/cjs/contracts/deepbook/balance_manager.js +361 -0
  11. package/dist/cjs/contracts/deepbook/balance_manager.js.map +7 -0
  12. package/dist/cjs/contracts/deepbook/balances.d.ts +10 -0
  13. package/dist/cjs/contracts/deepbook/balances.js +35 -0
  14. package/dist/cjs/contracts/deepbook/balances.js.map +7 -0
  15. package/dist/cjs/contracts/deepbook/big_vector.d.ts +62 -0
  16. package/dist/cjs/contracts/deepbook/big_vector.js +80 -0
  17. package/dist/cjs/contracts/deepbook/big_vector.js.map +7 -0
  18. package/dist/cjs/contracts/deepbook/book.d.ts +34 -0
  19. package/dist/cjs/contracts/deepbook/book.js +50 -0
  20. package/dist/cjs/contracts/deepbook/book.js.map +7 -0
  21. package/dist/cjs/contracts/deepbook/constants.d.ts +176 -0
  22. package/dist/cjs/contracts/deepbook/constants.js +338 -0
  23. package/dist/cjs/contracts/deepbook/constants.js.map +7 -0
  24. package/dist/cjs/contracts/deepbook/deep_price.d.ts +60 -0
  25. package/dist/cjs/contracts/deepbook/deep_price.js +87 -0
  26. package/dist/cjs/contracts/deepbook/deep_price.js.map +7 -0
  27. package/dist/cjs/contracts/deepbook/deps/std/type_name.d.ts +14 -0
  28. package/dist/cjs/contracts/deepbook/deps/std/type_name.js +42 -0
  29. package/dist/cjs/contracts/deepbook/deps/std/type_name.js.map +7 -0
  30. package/dist/cjs/contracts/deepbook/deps/sui/bag.d.ts +33 -0
  31. package/dist/cjs/contracts/deepbook/deps/sui/bag.js +47 -0
  32. package/dist/cjs/contracts/deepbook/deps/sui/bag.js.map +7 -0
  33. package/dist/cjs/contracts/deepbook/deps/sui/balance.d.ts +9 -0
  34. package/dist/cjs/contracts/deepbook/deps/sui/balance.js +33 -0
  35. package/dist/cjs/contracts/deepbook/deps/sui/balance.js.map +7 -0
  36. package/dist/cjs/contracts/deepbook/deps/sui/object.d.ts +5 -0
  37. package/dist/cjs/contracts/deepbook/deps/sui/object.js +33 -0
  38. package/dist/cjs/contracts/deepbook/deps/sui/object.js.map +7 -0
  39. package/dist/cjs/contracts/deepbook/deps/sui/table.d.ts +28 -0
  40. package/dist/cjs/contracts/deepbook/deps/sui/table.js +47 -0
  41. package/dist/cjs/contracts/deepbook/deps/sui/table.js.map +7 -0
  42. package/dist/cjs/contracts/deepbook/deps/sui/vec_map.d.ts +27 -0
  43. package/dist/cjs/contracts/deepbook/deps/sui/vec_map.js +45 -0
  44. package/dist/cjs/contracts/deepbook/deps/sui/vec_map.js.map +7 -0
  45. package/dist/cjs/contracts/deepbook/deps/sui/vec_set.d.ts +15 -0
  46. package/dist/cjs/contracts/deepbook/deps/sui/vec_set.js +35 -0
  47. package/dist/cjs/contracts/deepbook/deps/sui/vec_set.js.map +7 -0
  48. package/dist/cjs/contracts/deepbook/deps/sui/versioned.d.ts +7 -0
  49. package/dist/cjs/contracts/deepbook/deps/sui/versioned.js +45 -0
  50. package/dist/cjs/contracts/deepbook/deps/sui/versioned.js.map +7 -0
  51. package/dist/cjs/contracts/deepbook/ewma.d.ts +17 -0
  52. package/dist/cjs/contracts/deepbook/ewma.js +39 -0
  53. package/dist/cjs/contracts/deepbook/ewma.js.map +7 -0
  54. package/dist/cjs/contracts/deepbook/fill.d.ts +153 -0
  55. package/dist/cjs/contracts/deepbook/fill.js +251 -0
  56. package/dist/cjs/contracts/deepbook/fill.js.map +7 -0
  57. package/dist/cjs/contracts/deepbook/governance.d.ts +63 -0
  58. package/dist/cjs/contracts/deepbook/governance.js +79 -0
  59. package/dist/cjs/contracts/deepbook/governance.js.map +7 -0
  60. package/dist/cjs/contracts/deepbook/history.d.ts +60 -0
  61. package/dist/cjs/contracts/deepbook/history.js +78 -0
  62. package/dist/cjs/contracts/deepbook/history.js.map +7 -0
  63. package/dist/cjs/contracts/deepbook/math.d.ts +94 -0
  64. package/dist/cjs/contracts/deepbook/math.js +132 -0
  65. package/dist/cjs/contracts/deepbook/math.js.map +7 -0
  66. package/dist/cjs/contracts/deepbook/order.d.ts +135 -0
  67. package/dist/cjs/contracts/deepbook/order.js +218 -0
  68. package/dist/cjs/contracts/deepbook/order.js.map +7 -0
  69. package/dist/cjs/contracts/deepbook/order_info.d.ts +296 -0
  70. package/dist/cjs/contracts/deepbook/order_info.js +386 -0
  71. package/dist/cjs/contracts/deepbook/order_info.js.map +7 -0
  72. package/dist/cjs/contracts/deepbook/order_query.d.ts +85 -0
  73. package/dist/cjs/contracts/deepbook/order_query.js +96 -0
  74. package/dist/cjs/contracts/deepbook/order_query.js.map +7 -0
  75. package/dist/cjs/contracts/deepbook/pool.d.ts +1218 -0
  76. package/dist/cjs/contracts/deepbook/pool.js +1236 -0
  77. package/dist/cjs/contracts/deepbook/pool.js.map +7 -0
  78. package/dist/cjs/contracts/deepbook/registry.d.ts +134 -0
  79. package/dist/cjs/contracts/deepbook/registry.js +182 -0
  80. package/dist/cjs/contracts/deepbook/registry.js.map +7 -0
  81. package/dist/cjs/contracts/deepbook/state.d.ts +117 -0
  82. package/dist/cjs/contracts/deepbook/state.js +104 -0
  83. package/dist/cjs/contracts/deepbook/state.js.map +7 -0
  84. package/dist/cjs/contracts/deepbook/trade_params.d.ts +7 -0
  85. package/dist/cjs/contracts/deepbook/trade_params.js +35 -0
  86. package/dist/cjs/contracts/deepbook/trade_params.js.map +7 -0
  87. package/dist/cjs/contracts/deepbook/vault.d.ts +30 -0
  88. package/dist/cjs/contracts/deepbook/vault.js +65 -0
  89. package/dist/cjs/contracts/deepbook/vault.js.map +7 -0
  90. package/dist/cjs/contracts/utils/index.d.ts +25 -0
  91. package/dist/cjs/contracts/utils/index.js +148 -0
  92. package/dist/cjs/contracts/utils/index.js.map +7 -0
  93. package/dist/cjs/index.d.ts +23 -0
  94. package/dist/cjs/index.js +81 -0
  95. package/dist/cjs/index.js.map +7 -0
  96. package/dist/cjs/package.json +4 -0
  97. package/dist/cjs/pyth/PriceServiceConnection.d.ts +26 -0
  98. package/dist/cjs/pyth/PriceServiceConnection.js +68 -0
  99. package/dist/cjs/pyth/PriceServiceConnection.js.map +7 -0
  100. package/dist/cjs/pyth/pyth-helpers.d.ts +7 -0
  101. package/dist/cjs/pyth/pyth-helpers.js +36 -0
  102. package/dist/cjs/pyth/pyth-helpers.js.map +7 -0
  103. package/dist/cjs/pyth/pyth.d.ts +65 -0
  104. package/dist/cjs/pyth/pyth.js +269 -0
  105. package/dist/cjs/pyth/pyth.js.map +7 -0
  106. package/dist/cjs/transactions/balanceManager.d.ts +168 -0
  107. package/dist/cjs/transactions/balanceManager.js +384 -0
  108. package/dist/cjs/transactions/balanceManager.js.map +7 -0
  109. package/dist/cjs/transactions/deepbook.d.ts +477 -0
  110. package/dist/cjs/transactions/deepbook.js +1335 -0
  111. package/dist/cjs/transactions/deepbook.js.map +7 -0
  112. package/dist/cjs/transactions/deepbookAdmin.d.ts +105 -0
  113. package/dist/cjs/transactions/deepbookAdmin.js +334 -0
  114. package/dist/cjs/transactions/deepbookAdmin.js.map +7 -0
  115. package/dist/cjs/transactions/flashLoans.d.ts +56 -0
  116. package/dist/cjs/transactions/flashLoans.js +124 -0
  117. package/dist/cjs/transactions/flashLoans.js.map +7 -0
  118. package/dist/cjs/transactions/governance.d.ts +42 -0
  119. package/dist/cjs/transactions/governance.js +135 -0
  120. package/dist/cjs/transactions/governance.js.map +7 -0
  121. package/dist/cjs/transactions/marginAdmin.d.ts +133 -0
  122. package/dist/cjs/transactions/marginAdmin.js +393 -0
  123. package/dist/cjs/transactions/marginAdmin.js.map +7 -0
  124. package/dist/cjs/transactions/marginLiquidations.d.ts +61 -0
  125. package/dist/cjs/transactions/marginLiquidations.js +173 -0
  126. package/dist/cjs/transactions/marginLiquidations.js.map +7 -0
  127. package/dist/cjs/transactions/marginMaintainer.d.ts +80 -0
  128. package/dist/cjs/transactions/marginMaintainer.js +251 -0
  129. package/dist/cjs/transactions/marginMaintainer.js.map +7 -0
  130. package/dist/cjs/transactions/marginManager.d.ts +236 -0
  131. package/dist/cjs/transactions/marginManager.js +688 -0
  132. package/dist/cjs/transactions/marginManager.js.map +7 -0
  133. package/dist/cjs/transactions/marginPool.d.ts +134 -0
  134. package/dist/cjs/transactions/marginPool.js +330 -0
  135. package/dist/cjs/transactions/marginPool.js.map +7 -0
  136. package/dist/cjs/transactions/marginRegistry.d.ts +94 -0
  137. package/dist/cjs/transactions/marginRegistry.js +221 -0
  138. package/dist/cjs/transactions/marginRegistry.js.map +7 -0
  139. package/dist/cjs/transactions/marginTPSL.d.ts +93 -0
  140. package/dist/cjs/transactions/marginTPSL.js +286 -0
  141. package/dist/cjs/transactions/marginTPSL.js.map +7 -0
  142. package/dist/cjs/transactions/poolProxy.d.ts +104 -0
  143. package/dist/cjs/transactions/poolProxy.js +435 -0
  144. package/dist/cjs/transactions/poolProxy.js.map +7 -0
  145. package/dist/cjs/types/bcs.d.ts +5 -0
  146. package/dist/cjs/types/bcs.js +33 -0
  147. package/dist/cjs/types/bcs.js.map +7 -0
  148. package/dist/cjs/types/index.d.ts +218 -0
  149. package/dist/cjs/types/index.js +38 -0
  150. package/dist/cjs/types/index.js.map +7 -0
  151. package/dist/cjs/utils/config.d.ts +65 -0
  152. package/dist/cjs/utils/config.js +144 -0
  153. package/dist/cjs/utils/config.js.map +7 -0
  154. package/dist/cjs/utils/constants.d.ts +76 -0
  155. package/dist/cjs/utils/constants.js +382 -0
  156. package/dist/cjs/utils/constants.js.map +7 -0
  157. package/dist/cjs/utils/errors.d.ts +42 -0
  158. package/dist/cjs/utils/errors.js +70 -0
  159. package/dist/cjs/utils/errors.js.map +7 -0
  160. package/dist/cjs/utils/validation.d.ts +50 -0
  161. package/dist/cjs/utils/validation.js +67 -0
  162. package/dist/cjs/utils/validation.js.map +7 -0
  163. package/dist/esm/client.d.ts +861 -0
  164. package/dist/esm/client.js +1967 -0
  165. package/dist/esm/client.js.map +7 -0
  166. package/dist/esm/contracts/deepbook/account.d.ts +105 -0
  167. package/dist/esm/contracts/deepbook/account.js +133 -0
  168. package/dist/esm/contracts/deepbook/account.js.map +7 -0
  169. package/dist/esm/contracts/deepbook/balance_manager.d.ts +268 -0
  170. package/dist/esm/contracts/deepbook/balance_manager.js +331 -0
  171. package/dist/esm/contracts/deepbook/balance_manager.js.map +7 -0
  172. package/dist/esm/contracts/deepbook/balances.d.ts +10 -0
  173. package/dist/esm/contracts/deepbook/balances.js +15 -0
  174. package/dist/esm/contracts/deepbook/balances.js.map +7 -0
  175. package/dist/esm/contracts/deepbook/big_vector.d.ts +62 -0
  176. package/dist/esm/contracts/deepbook/big_vector.js +50 -0
  177. package/dist/esm/contracts/deepbook/big_vector.js.map +7 -0
  178. package/dist/esm/contracts/deepbook/book.d.ts +34 -0
  179. package/dist/esm/contracts/deepbook/book.js +20 -0
  180. package/dist/esm/contracts/deepbook/book.js.map +7 -0
  181. package/dist/esm/contracts/deepbook/constants.d.ts +176 -0
  182. package/dist/esm/contracts/deepbook/constants.js +318 -0
  183. package/dist/esm/contracts/deepbook/constants.js.map +7 -0
  184. package/dist/esm/contracts/deepbook/deep_price.d.ts +60 -0
  185. package/dist/esm/contracts/deepbook/deep_price.js +67 -0
  186. package/dist/esm/contracts/deepbook/deep_price.js.map +7 -0
  187. package/dist/esm/contracts/deepbook/deps/std/type_name.d.ts +14 -0
  188. package/dist/esm/contracts/deepbook/deps/std/type_name.js +22 -0
  189. package/dist/esm/contracts/deepbook/deps/std/type_name.js.map +7 -0
  190. package/dist/esm/contracts/deepbook/deps/sui/bag.d.ts +33 -0
  191. package/dist/esm/contracts/deepbook/deps/sui/bag.js +17 -0
  192. package/dist/esm/contracts/deepbook/deps/sui/bag.js.map +7 -0
  193. package/dist/esm/contracts/deepbook/deps/sui/balance.d.ts +9 -0
  194. package/dist/esm/contracts/deepbook/deps/sui/balance.js +13 -0
  195. package/dist/esm/contracts/deepbook/deps/sui/balance.js.map +7 -0
  196. package/dist/esm/contracts/deepbook/deps/sui/object.d.ts +5 -0
  197. package/dist/esm/contracts/deepbook/deps/sui/object.js +13 -0
  198. package/dist/esm/contracts/deepbook/deps/sui/object.js.map +7 -0
  199. package/dist/esm/contracts/deepbook/deps/sui/table.d.ts +28 -0
  200. package/dist/esm/contracts/deepbook/deps/sui/table.js +17 -0
  201. package/dist/esm/contracts/deepbook/deps/sui/table.js.map +7 -0
  202. package/dist/esm/contracts/deepbook/deps/sui/vec_map.d.ts +27 -0
  203. package/dist/esm/contracts/deepbook/deps/sui/vec_map.js +25 -0
  204. package/dist/esm/contracts/deepbook/deps/sui/vec_map.js.map +7 -0
  205. package/dist/esm/contracts/deepbook/deps/sui/vec_set.d.ts +15 -0
  206. package/dist/esm/contracts/deepbook/deps/sui/vec_set.js +15 -0
  207. package/dist/esm/contracts/deepbook/deps/sui/vec_set.js.map +7 -0
  208. package/dist/esm/contracts/deepbook/deps/sui/versioned.d.ts +7 -0
  209. package/dist/esm/contracts/deepbook/deps/sui/versioned.js +15 -0
  210. package/dist/esm/contracts/deepbook/deps/sui/versioned.js.map +7 -0
  211. package/dist/esm/contracts/deepbook/ewma.d.ts +17 -0
  212. package/dist/esm/contracts/deepbook/ewma.js +19 -0
  213. package/dist/esm/contracts/deepbook/ewma.js.map +7 -0
  214. package/dist/esm/contracts/deepbook/fill.d.ts +153 -0
  215. package/dist/esm/contracts/deepbook/fill.js +221 -0
  216. package/dist/esm/contracts/deepbook/fill.js.map +7 -0
  217. package/dist/esm/contracts/deepbook/governance.d.ts +63 -0
  218. package/dist/esm/contracts/deepbook/governance.js +49 -0
  219. package/dist/esm/contracts/deepbook/governance.js.map +7 -0
  220. package/dist/esm/contracts/deepbook/history.d.ts +60 -0
  221. package/dist/esm/contracts/deepbook/history.js +48 -0
  222. package/dist/esm/contracts/deepbook/history.js.map +7 -0
  223. package/dist/esm/contracts/deepbook/math.d.ts +94 -0
  224. package/dist/esm/contracts/deepbook/math.js +112 -0
  225. package/dist/esm/contracts/deepbook/math.js.map +7 -0
  226. package/dist/esm/contracts/deepbook/order.d.ts +135 -0
  227. package/dist/esm/contracts/deepbook/order.js +188 -0
  228. package/dist/esm/contracts/deepbook/order.js.map +7 -0
  229. package/dist/esm/contracts/deepbook/order_info.d.ts +296 -0
  230. package/dist/esm/contracts/deepbook/order_info.js +356 -0
  231. package/dist/esm/contracts/deepbook/order_info.js.map +7 -0
  232. package/dist/esm/contracts/deepbook/order_query.d.ts +85 -0
  233. package/dist/esm/contracts/deepbook/order_query.js +66 -0
  234. package/dist/esm/contracts/deepbook/order_query.js.map +7 -0
  235. package/dist/esm/contracts/deepbook/pool.d.ts +1218 -0
  236. package/dist/esm/contracts/deepbook/pool.js +1206 -0
  237. package/dist/esm/contracts/deepbook/pool.js.map +7 -0
  238. package/dist/esm/contracts/deepbook/registry.d.ts +134 -0
  239. package/dist/esm/contracts/deepbook/registry.js +152 -0
  240. package/dist/esm/contracts/deepbook/registry.js.map +7 -0
  241. package/dist/esm/contracts/deepbook/state.d.ts +117 -0
  242. package/dist/esm/contracts/deepbook/state.js +74 -0
  243. package/dist/esm/contracts/deepbook/state.js.map +7 -0
  244. package/dist/esm/contracts/deepbook/trade_params.d.ts +7 -0
  245. package/dist/esm/contracts/deepbook/trade_params.js +15 -0
  246. package/dist/esm/contracts/deepbook/trade_params.js.map +7 -0
  247. package/dist/esm/contracts/deepbook/vault.d.ts +30 -0
  248. package/dist/esm/contracts/deepbook/vault.js +35 -0
  249. package/dist/esm/contracts/deepbook/vault.js.map +7 -0
  250. package/dist/esm/contracts/utils/index.d.ts +25 -0
  251. package/dist/esm/contracts/utils/index.js +128 -0
  252. package/dist/esm/contracts/utils/index.js.map +7 -0
  253. package/dist/esm/index.d.ts +23 -0
  254. package/dist/esm/index.js +81 -0
  255. package/dist/esm/index.js.map +7 -0
  256. package/dist/esm/package.json +4 -0
  257. package/dist/esm/pyth/PriceServiceConnection.d.ts +26 -0
  258. package/dist/esm/pyth/PriceServiceConnection.js +38 -0
  259. package/dist/esm/pyth/PriceServiceConnection.js.map +7 -0
  260. package/dist/esm/pyth/pyth-helpers.d.ts +7 -0
  261. package/dist/esm/pyth/pyth-helpers.js +16 -0
  262. package/dist/esm/pyth/pyth-helpers.js.map +7 -0
  263. package/dist/esm/pyth/pyth.d.ts +65 -0
  264. package/dist/esm/pyth/pyth.js +249 -0
  265. package/dist/esm/pyth/pyth.js.map +7 -0
  266. package/dist/esm/transactions/balanceManager.d.ts +168 -0
  267. package/dist/esm/transactions/balanceManager.js +364 -0
  268. package/dist/esm/transactions/balanceManager.js.map +7 -0
  269. package/dist/esm/transactions/deepbook.d.ts +477 -0
  270. package/dist/esm/transactions/deepbook.js +1321 -0
  271. package/dist/esm/transactions/deepbook.js.map +7 -0
  272. package/dist/esm/transactions/deepbookAdmin.d.ts +105 -0
  273. package/dist/esm/transactions/deepbookAdmin.js +314 -0
  274. package/dist/esm/transactions/deepbookAdmin.js.map +7 -0
  275. package/dist/esm/transactions/flashLoans.d.ts +56 -0
  276. package/dist/esm/transactions/flashLoans.js +104 -0
  277. package/dist/esm/transactions/flashLoans.js.map +7 -0
  278. package/dist/esm/transactions/governance.d.ts +42 -0
  279. package/dist/esm/transactions/governance.js +115 -0
  280. package/dist/esm/transactions/governance.js.map +7 -0
  281. package/dist/esm/transactions/marginAdmin.d.ts +133 -0
  282. package/dist/esm/transactions/marginAdmin.js +373 -0
  283. package/dist/esm/transactions/marginAdmin.js.map +7 -0
  284. package/dist/esm/transactions/marginLiquidations.d.ts +61 -0
  285. package/dist/esm/transactions/marginLiquidations.js +153 -0
  286. package/dist/esm/transactions/marginLiquidations.js.map +7 -0
  287. package/dist/esm/transactions/marginMaintainer.d.ts +80 -0
  288. package/dist/esm/transactions/marginMaintainer.js +231 -0
  289. package/dist/esm/transactions/marginMaintainer.js.map +7 -0
  290. package/dist/esm/transactions/marginManager.d.ts +236 -0
  291. package/dist/esm/transactions/marginManager.js +668 -0
  292. package/dist/esm/transactions/marginManager.js.map +7 -0
  293. package/dist/esm/transactions/marginPool.d.ts +134 -0
  294. package/dist/esm/transactions/marginPool.js +310 -0
  295. package/dist/esm/transactions/marginPool.js.map +7 -0
  296. package/dist/esm/transactions/marginRegistry.d.ts +94 -0
  297. package/dist/esm/transactions/marginRegistry.js +201 -0
  298. package/dist/esm/transactions/marginRegistry.js.map +7 -0
  299. package/dist/esm/transactions/marginTPSL.d.ts +93 -0
  300. package/dist/esm/transactions/marginTPSL.js +266 -0
  301. package/dist/esm/transactions/marginTPSL.js.map +7 -0
  302. package/dist/esm/transactions/poolProxy.d.ts +104 -0
  303. package/dist/esm/transactions/poolProxy.js +415 -0
  304. package/dist/esm/transactions/poolProxy.js.map +7 -0
  305. package/dist/esm/types/bcs.d.ts +5 -0
  306. package/dist/esm/types/bcs.js +13 -0
  307. package/dist/esm/types/bcs.js.map +7 -0
  308. package/dist/esm/types/index.d.ts +218 -0
  309. package/dist/esm/types/index.js +18 -0
  310. package/dist/esm/types/index.js.map +7 -0
  311. package/dist/esm/utils/config.d.ts +65 -0
  312. package/dist/esm/utils/config.js +135 -0
  313. package/dist/esm/utils/config.js.map +7 -0
  314. package/dist/esm/utils/constants.d.ts +76 -0
  315. package/dist/esm/utils/constants.js +362 -0
  316. package/dist/esm/utils/constants.js.map +7 -0
  317. package/dist/esm/utils/errors.d.ts +42 -0
  318. package/dist/esm/utils/errors.js +50 -0
  319. package/dist/esm/utils/errors.js.map +7 -0
  320. package/dist/esm/utils/validation.d.ts +50 -0
  321. package/dist/esm/utils/validation.js +47 -0
  322. package/dist/esm/utils/validation.js.map +7 -0
  323. package/dist/tsconfig.esm.tsbuildinfo +1 -0
  324. package/dist/tsconfig.tsbuildinfo +1 -0
  325. package/package.json +63 -0
  326. package/src/client.ts +2451 -0
  327. package/src/contracts/deepbook/account.ts +199 -0
  328. package/src/contracts/deepbook/balance_manager.ts +532 -0
  329. package/src/contracts/deepbook/balances.ts +19 -0
  330. package/src/contracts/deepbook/big_vector.ts +74 -0
  331. package/src/contracts/deepbook/book.ts +24 -0
  332. package/src/contracts/deepbook/constants.ts +458 -0
  333. package/src/contracts/deepbook/deep_price.ts +84 -0
  334. package/src/contracts/deepbook/deps/std/type_name.ts +23 -0
  335. package/src/contracts/deepbook/deps/sui/bag.ts +41 -0
  336. package/src/contracts/deepbook/deps/sui/balance.ts +18 -0
  337. package/src/contracts/deepbook/deps/sui/object.ts +14 -0
  338. package/src/contracts/deepbook/deps/sui/table.ts +36 -0
  339. package/src/contracts/deepbook/deps/sui/vec_map.ts +33 -0
  340. package/src/contracts/deepbook/deps/sui/vec_set.ts +22 -0
  341. package/src/contracts/deepbook/deps/sui/versioned.ts +13 -0
  342. package/src/contracts/deepbook/ewma.ts +26 -0
  343. package/src/contracts/deepbook/fill.ts +336 -0
  344. package/src/contracts/deepbook/governance.ts +52 -0
  345. package/src/contracts/deepbook/history.ts +51 -0
  346. package/src/contracts/deepbook/math.ts +210 -0
  347. package/src/contracts/deepbook/order.ts +269 -0
  348. package/src/contracts/deepbook/order_info.ts +513 -0
  349. package/src/contracts/deepbook/order_query.ts +115 -0
  350. package/src/contracts/deepbook/pool.ts +2269 -0
  351. package/src/contracts/deepbook/registry.ts +242 -0
  352. package/src/contracts/deepbook/state.ts +74 -0
  353. package/src/contracts/deepbook/trade_params.ts +16 -0
  354. package/src/contracts/deepbook/vault.ts +37 -0
  355. package/src/contracts/utils/index.ts +184 -0
  356. package/src/index.ts +95 -0
  357. package/src/pyth/PriceServiceConnection.ts +48 -0
  358. package/src/pyth/pyth-helpers.ts +23 -0
  359. package/src/pyth/pyth.ts +305 -0
  360. package/src/transactions/balanceManager.ts +399 -0
  361. package/src/transactions/deepbook.ts +1519 -0
  362. package/src/transactions/deepbookAdmin.ts +332 -0
  363. package/src/transactions/flashLoans.ts +123 -0
  364. package/src/transactions/governance.ts +123 -0
  365. package/src/transactions/marginAdmin.ts +396 -0
  366. package/src/transactions/marginLiquidations.ts +175 -0
  367. package/src/transactions/marginMaintainer.ts +280 -0
  368. package/src/transactions/marginManager.ts +708 -0
  369. package/src/transactions/marginPool.ts +339 -0
  370. package/src/transactions/marginRegistry.ts +212 -0
  371. package/src/transactions/marginTPSL.ts +296 -0
  372. package/src/transactions/poolProxy.ts +438 -0
  373. package/src/types/bcs.ts +8 -0
  374. package/src/types/index.ts +255 -0
  375. package/src/utils/config.ts +177 -0
  376. package/src/utils/constants.ts +374 -0
  377. package/src/utils/errors.ts +67 -0
  378. package/src/utils/validation.ts +91 -0
package/src/client.ts ADDED
@@ -0,0 +1,2451 @@
1
+ // Copyright (c) Mysten Labs, Inc.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ import { bcs } from '@haneullabs/haneul/bcs';
4
+ import { Account, Order, OrderDeepPrice, VecSet } from './types/bcs.js';
5
+ import type { HaneulClient } from '@haneullabs/haneul/client';
6
+ import { Transaction } from '@haneullabs/haneul/transactions';
7
+ import { normalizeHaneulAddress } from '@haneullabs/haneul/utils';
8
+
9
+ import { BalanceManagerContract } from './transactions/balanceManager.js';
10
+ import { DeepBookContract } from './transactions/deepbook.js';
11
+ import { DeepBookAdminContract } from './transactions/deepbookAdmin.js';
12
+ import { FlashLoanContract } from './transactions/flashLoans.js';
13
+ import { GovernanceContract } from './transactions/governance.js';
14
+ import type {
15
+ BalanceManager,
16
+ Environment,
17
+ MarginManager,
18
+ CanPlaceLimitOrderParams,
19
+ CanPlaceMarketOrderParams,
20
+ } from './types/index.js';
21
+ import {
22
+ DEEP_SCALAR,
23
+ DeepBookConfig,
24
+ FLOAT_SCALAR,
25
+ PRICE_INFO_OBJECT_MAX_AGE_MS,
26
+ } from './utils/config.js';
27
+ import type { CoinMap, PoolMap } from './utils/constants.js';
28
+ import { MarginAdminContract } from './transactions/marginAdmin.js';
29
+ import { MarginMaintainerContract } from './transactions/marginMaintainer.js';
30
+ import { MarginPoolContract } from './transactions/marginPool.js';
31
+ import { MarginManagerContract } from './transactions/marginManager.js';
32
+ import { MarginRegistryContract } from './transactions/marginRegistry.js';
33
+ import { MarginLiquidationsContract } from './transactions/marginLiquidations.js';
34
+ import { HaneulPriceServiceConnection } from './pyth/pyth.js';
35
+ import { HaneulPythClient } from './pyth/pyth.js';
36
+ import { PoolProxyContract } from './transactions/poolProxy.js';
37
+ import { MarginTPSLContract } from './transactions/marginTPSL.js';
38
+
39
+ /**
40
+ * DeepBookClient class for managing DeepBook operations.
41
+ */
42
+ export class DeepBookClient {
43
+ client: HaneulClient;
44
+ #config: DeepBookConfig;
45
+ #address: string;
46
+ balanceManager: BalanceManagerContract;
47
+ deepBook: DeepBookContract;
48
+ deepBookAdmin: DeepBookAdminContract;
49
+ flashLoans: FlashLoanContract;
50
+ governance: GovernanceContract;
51
+ marginAdmin: MarginAdminContract;
52
+ marginMaintainer: MarginMaintainerContract;
53
+ marginPool: MarginPoolContract;
54
+ marginManager: MarginManagerContract;
55
+ marginRegistry: MarginRegistryContract;
56
+ marginLiquidations: MarginLiquidationsContract;
57
+ poolProxy: PoolProxyContract;
58
+ marginTPSL: MarginTPSLContract;
59
+
60
+ /**
61
+ * @param {HaneulClient} client HaneulClient instance
62
+ * @param {string} address Address of the client
63
+ * @param {Environment} env Environment configuration
64
+ * @param {Object.<string, BalanceManager>} [balanceManagers] Optional initial BalanceManager map
65
+ * @param {Object.<string, MarginManager>} [marginManagers] Optional initial MarginManager map
66
+ * @param {CoinMap} [coins] Optional initial CoinMap
67
+ * @param {PoolMap} [pools] Optional initial PoolMap
68
+ * @param {string} [adminCap] Optional admin capability
69
+ * @param {string} [marginAdminCap] Optional margin admin capability
70
+ * @param {string} [marginMaintainerCap] Optional margin maintainer capability
71
+ */
72
+ constructor({
73
+ client,
74
+ address,
75
+ env,
76
+ balanceManagers,
77
+ marginManagers,
78
+ coins,
79
+ pools,
80
+ adminCap,
81
+ marginAdminCap,
82
+ marginMaintainerCap,
83
+ }: {
84
+ client: HaneulClient;
85
+ address: string;
86
+ env: Environment;
87
+ balanceManagers?: { [key: string]: BalanceManager };
88
+ marginManagers?: { [key: string]: MarginManager };
89
+ coins?: CoinMap;
90
+ pools?: PoolMap;
91
+ adminCap?: string;
92
+ marginAdminCap?: string;
93
+ marginMaintainerCap?: string;
94
+ }) {
95
+ this.client = client;
96
+ this.#address = normalizeHaneulAddress(address);
97
+ this.#config = new DeepBookConfig({
98
+ address: this.#address,
99
+ env,
100
+ balanceManagers,
101
+ marginManagers,
102
+ coins,
103
+ pools,
104
+ adminCap,
105
+ marginAdminCap,
106
+ marginMaintainerCap,
107
+ });
108
+ this.balanceManager = new BalanceManagerContract(this.#config);
109
+ this.deepBook = new DeepBookContract(this.#config);
110
+ this.deepBookAdmin = new DeepBookAdminContract(this.#config);
111
+ this.flashLoans = new FlashLoanContract(this.#config);
112
+ this.governance = new GovernanceContract(this.#config);
113
+ this.marginAdmin = new MarginAdminContract(this.#config);
114
+ this.marginMaintainer = new MarginMaintainerContract(this.#config);
115
+ this.marginPool = new MarginPoolContract(this.#config);
116
+ this.marginManager = new MarginManagerContract(this.#config);
117
+ this.marginRegistry = new MarginRegistryContract(this.#config);
118
+ this.marginLiquidations = new MarginLiquidationsContract(this.#config);
119
+ this.poolProxy = new PoolProxyContract(this.#config);
120
+ this.marginTPSL = new MarginTPSLContract(this.#config);
121
+ }
122
+
123
+ /**
124
+ * @description Check the balance of a balance manager for a specific coin
125
+ * @param {string} managerKey Key of the balance manager
126
+ * @param {string} coinKey Key of the coin
127
+ * @returns {Promise<{ coinType: string, balance: number }>} An object with coin type and balance
128
+ */
129
+ async checkManagerBalance(managerKey: string, coinKey: string) {
130
+ const tx = new Transaction();
131
+ const coin = this.#config.getCoin(coinKey);
132
+
133
+ tx.add(this.balanceManager.checkManagerBalance(managerKey, coinKey));
134
+ const res = await this.client.devInspectTransactionBlock({
135
+ sender: this.#address,
136
+ transactionBlock: tx,
137
+ });
138
+
139
+ const bytes = res.results![0].returnValues![0][0];
140
+ const parsed_balance = bcs.U64.parse(new Uint8Array(bytes));
141
+ const balanceNumber = Number(parsed_balance);
142
+ const adjusted_balance = balanceNumber / coin.scalar;
143
+
144
+ return {
145
+ coinType: coin.type,
146
+ balance: Number(adjusted_balance.toFixed(9)),
147
+ };
148
+ }
149
+
150
+ /**
151
+ * @description Check if a pool is whitelisted
152
+ * @param {string} poolKey Key of the pool
153
+ * @returns {Promise<boolean>} Boolean indicating if the pool is whitelisted
154
+ */
155
+ async whitelisted(poolKey: string) {
156
+ const tx = new Transaction();
157
+
158
+ tx.add(this.deepBook.whitelisted(poolKey));
159
+ const res = await this.client.devInspectTransactionBlock({
160
+ sender: normalizeHaneulAddress(this.#address),
161
+ transactionBlock: tx,
162
+ });
163
+
164
+ const bytes = res.results![0].returnValues![0][0];
165
+ const whitelisted = bcs.Bool.parse(new Uint8Array(bytes));
166
+
167
+ return whitelisted;
168
+ }
169
+
170
+ /**
171
+ * @description Get the quote quantity out for a given base quantity
172
+ * @param {string} poolKey Key of the pool
173
+ * @param {number} baseQuantity Base quantity to convert
174
+ * @returns {Promise<{ baseQuantity: number, baseOut: number, quoteOut: number, deepRequired: number }>}
175
+ * An object with base quantity, base out, quote out, and deep required for the dry run
176
+ */
177
+ async getQuoteQuantityOut(poolKey: string, baseQuantity: number) {
178
+ const tx = new Transaction();
179
+ const pool = this.#config.getPool(poolKey);
180
+ const baseScalar = this.#config.getCoin(pool.baseCoin).scalar;
181
+ const quoteScalar = this.#config.getCoin(pool.quoteCoin).scalar;
182
+
183
+ tx.add(this.deepBook.getQuoteQuantityOut(poolKey, baseQuantity));
184
+ const res = await this.client.devInspectTransactionBlock({
185
+ sender: normalizeHaneulAddress(this.#address),
186
+ transactionBlock: tx,
187
+ });
188
+
189
+ const baseOut = Number(bcs.U64.parse(new Uint8Array(res.results![0].returnValues![0][0])));
190
+ const quoteOut = Number(bcs.U64.parse(new Uint8Array(res.results![0].returnValues![1][0])));
191
+ const deepRequired = Number(bcs.U64.parse(new Uint8Array(res.results![0].returnValues![2][0])));
192
+
193
+ return {
194
+ baseQuantity,
195
+ baseOut: Number((baseOut / baseScalar).toFixed(9)),
196
+ quoteOut: Number((quoteOut / quoteScalar).toFixed(9)),
197
+ deepRequired: Number((deepRequired / DEEP_SCALAR).toFixed(9)),
198
+ };
199
+ }
200
+
201
+ /**
202
+ * @description Get the base quantity out for a given quote quantity
203
+ * @param {string} poolKey Key of the pool
204
+ * @param {number} quoteQuantity Quote quantity to convert
205
+ * @returns {Promise<{ quoteQuantity: number, baseOut: number, quoteOut: number, deepRequired: number }>}
206
+ * An object with quote quantity, base out, quote out, and deep required for the dry run
207
+ */
208
+ async getBaseQuantityOut(poolKey: string, quoteQuantity: number) {
209
+ const tx = new Transaction();
210
+ const pool = this.#config.getPool(poolKey);
211
+ const baseScalar = this.#config.getCoin(pool.baseCoin).scalar;
212
+ const quoteScalar = this.#config.getCoin(pool.quoteCoin).scalar;
213
+
214
+ tx.add(this.deepBook.getBaseQuantityOut(poolKey, quoteQuantity));
215
+ const res = await this.client.devInspectTransactionBlock({
216
+ sender: normalizeHaneulAddress(this.#address),
217
+ transactionBlock: tx,
218
+ });
219
+
220
+ const baseOut = Number(bcs.U64.parse(new Uint8Array(res.results![0].returnValues![0][0])));
221
+ const quoteOut = Number(bcs.U64.parse(new Uint8Array(res.results![0].returnValues![1][0])));
222
+ const deepRequired = Number(bcs.U64.parse(new Uint8Array(res.results![0].returnValues![2][0])));
223
+
224
+ return {
225
+ quoteQuantity: quoteQuantity,
226
+ baseOut: Number((baseOut / baseScalar).toFixed(9)),
227
+ quoteOut: Number((quoteOut / quoteScalar).toFixed(9)),
228
+ deepRequired: Number((deepRequired / DEEP_SCALAR).toFixed(9)),
229
+ };
230
+ }
231
+
232
+ /**
233
+ * @description Get the output quantities for given base and quote quantities. Only one quantity can be non-zero
234
+ * @param {string} poolKey Key of the pool
235
+ * @param {number} baseQuantity Base quantity to convert
236
+ * @param {number} quoteQuantity Quote quantity to convert
237
+ * @returns {Promise<{ baseQuantity: number, quoteQuantity: number, baseOut: number, quoteOut: number, deepRequired: number }>}
238
+ * An object with base quantity, quote quantity, base out, quote out, and deep required for the dry run
239
+ */
240
+ async getQuantityOut(poolKey: string, baseQuantity: number, quoteQuantity: number) {
241
+ const tx = new Transaction();
242
+ const pool = this.#config.getPool(poolKey);
243
+ const baseScalar = this.#config.getCoin(pool.baseCoin).scalar;
244
+ const quoteScalar = this.#config.getCoin(pool.quoteCoin).scalar;
245
+
246
+ tx.add(this.deepBook.getQuantityOut(poolKey, baseQuantity, quoteQuantity));
247
+ const res = await this.client.devInspectTransactionBlock({
248
+ sender: normalizeHaneulAddress(this.#address),
249
+ transactionBlock: tx,
250
+ });
251
+
252
+ const baseOut = Number(bcs.U64.parse(new Uint8Array(res.results![0].returnValues![0][0])));
253
+ const quoteOut = Number(bcs.U64.parse(new Uint8Array(res.results![0].returnValues![1][0])));
254
+ const deepRequired = Number(bcs.U64.parse(new Uint8Array(res.results![0].returnValues![2][0])));
255
+
256
+ return {
257
+ baseQuantity,
258
+ quoteQuantity,
259
+ baseOut: Number((baseOut / baseScalar).toFixed(9)),
260
+ quoteOut: Number((quoteOut / quoteScalar).toFixed(9)),
261
+ deepRequired: Number((deepRequired / DEEP_SCALAR).toFixed(9)),
262
+ };
263
+ }
264
+
265
+ /**
266
+ * @description Get open orders for a balance manager in a pool
267
+ * @param {string} poolKey Key of the pool
268
+ * @param {string} managerKey Key of the balance manager
269
+ * @returns {Promise<Array>} An array of open order IDs
270
+ */
271
+ async accountOpenOrders(poolKey: string, managerKey: string) {
272
+ const tx = new Transaction();
273
+
274
+ tx.add(this.deepBook.accountOpenOrders(poolKey, managerKey));
275
+ const res = await this.client.devInspectTransactionBlock({
276
+ sender: normalizeHaneulAddress(this.#address),
277
+ transactionBlock: tx,
278
+ });
279
+
280
+ const order_ids = res.results![0].returnValues![0][0];
281
+
282
+ return VecSet(bcs.u128()).parse(new Uint8Array(order_ids)).contents;
283
+ }
284
+
285
+ /**
286
+ * @description Get the order information for a specific order in a pool
287
+ * @param {string} poolKey Key of the pool
288
+ * @param {string} orderId Order ID
289
+ * @returns {Promise<Object>} A promise that resolves to an object containing the order information
290
+ */
291
+ async getOrder(poolKey: string, orderId: string) {
292
+ const tx = new Transaction();
293
+
294
+ tx.add(this.deepBook.getOrder(poolKey, orderId));
295
+ const res = await this.client.devInspectTransactionBlock({
296
+ sender: normalizeHaneulAddress(this.#address),
297
+ transactionBlock: tx,
298
+ });
299
+
300
+ try {
301
+ const orderInformation = res.results![0].returnValues![0][0];
302
+ return Order.parse(new Uint8Array(orderInformation));
303
+ } catch {
304
+ return null;
305
+ }
306
+ }
307
+
308
+ /**
309
+ * @description Get the order information for a specific order in a pool, with normalized price
310
+ * @param {string} poolKey Key of the pool
311
+ * @param {string} orderId Order ID
312
+ * @returns {Promise<Object>} A promise that resolves to an object containing the order information with normalized price
313
+ */
314
+ async getOrderNormalized(poolKey: string, orderId: string) {
315
+ const tx = new Transaction();
316
+ tx.add(this.deepBook.getOrder(poolKey, orderId));
317
+ const res = await this.client.devInspectTransactionBlock({
318
+ sender: normalizeHaneulAddress(this.#address),
319
+ transactionBlock: tx,
320
+ });
321
+
322
+ try {
323
+ const orderInformation = res.results![0].returnValues![0][0];
324
+ const orderInfo = Order.parse(new Uint8Array(orderInformation));
325
+
326
+ if (!orderInfo) {
327
+ return null;
328
+ }
329
+ const baseCoin = this.#config.getCoin(this.#config.getPool(poolKey).baseCoin);
330
+ const quoteCoin = this.#config.getCoin(this.#config.getPool(poolKey).quoteCoin);
331
+ const { isBid, price: rawPrice } = this.decodeOrderId(BigInt(orderInfo.order_id));
332
+ const normalizedPrice = (rawPrice * baseCoin.scalar) / quoteCoin.scalar / FLOAT_SCALAR;
333
+
334
+ const normalizedOrderInfo = {
335
+ ...orderInfo,
336
+ quantity: String((Number(orderInfo.quantity) / baseCoin.scalar).toFixed(9)),
337
+ filled_quantity: String((Number(orderInfo.filled_quantity) / baseCoin.scalar).toFixed(9)),
338
+ order_deep_price: {
339
+ ...orderInfo.order_deep_price,
340
+ deep_per_asset: String(
341
+ (Number(orderInfo.order_deep_price.deep_per_asset) / DEEP_SCALAR).toFixed(9),
342
+ ),
343
+ },
344
+ isBid,
345
+ normalized_price: normalizedPrice.toFixed(9),
346
+ };
347
+ return normalizedOrderInfo;
348
+ } catch {
349
+ return null;
350
+ }
351
+ }
352
+
353
+ /**
354
+ * @description Retrieves information for multiple specific orders in a pool.
355
+ * @param {string} poolKey - The key identifying the pool from which to retrieve order information.
356
+ * @param {string[]} orderIds - List of order IDs to retrieve information for.
357
+ * @returns {Promise<Object[] | null>} A promise that resolves to an array of order objects, each containing details such as
358
+ * balance manager ID, order ID, client order ID, quantity, filled quantity, fee information, order price, epoch, status,
359
+ * and expiration timestamp. Returns `null` if the retrieval fails.
360
+ */
361
+ async getOrders(poolKey: string, orderIds: string[]) {
362
+ const tx = new Transaction();
363
+
364
+ tx.add(this.deepBook.getOrders(poolKey, orderIds));
365
+ const res = await this.client.devInspectTransactionBlock({
366
+ sender: normalizeHaneulAddress(this.#address),
367
+ transactionBlock: tx,
368
+ });
369
+
370
+ try {
371
+ const orderInformation = res.results![0].returnValues![0][0];
372
+ return bcs.vector(Order).parse(new Uint8Array(orderInformation));
373
+ } catch {
374
+ return null;
375
+ }
376
+ }
377
+
378
+ /**
379
+ * @description Get level 2 order book specifying range of price
380
+ * @param {string} poolKey Key of the pool
381
+ * @param {number} priceLow Lower bound of the price range
382
+ * @param {number} priceHigh Upper bound of the price range
383
+ * @param {boolean} isBid Whether to get bid or ask orders
384
+ * @returns {Promise<{ prices: Array<number>, quantities: Array<number> }>}
385
+ * An object with arrays of prices and quantities
386
+ */
387
+ async getLevel2Range(poolKey: string, priceLow: number, priceHigh: number, isBid: boolean) {
388
+ const tx = new Transaction();
389
+ const pool = this.#config.getPool(poolKey);
390
+ const baseCoin = this.#config.getCoin(pool.baseCoin);
391
+ const quoteCoin = this.#config.getCoin(pool.quoteCoin);
392
+
393
+ tx.add(this.deepBook.getLevel2Range(poolKey, priceLow, priceHigh, isBid));
394
+ const res = await this.client.devInspectTransactionBlock({
395
+ sender: normalizeHaneulAddress(this.#address),
396
+ transactionBlock: tx,
397
+ });
398
+
399
+ const prices = res.results![0].returnValues![0][0];
400
+ const parsed_prices = bcs.vector(bcs.u64()).parse(new Uint8Array(prices));
401
+ const quantities = res.results![0].returnValues![1][0];
402
+ const parsed_quantities = bcs.vector(bcs.u64()).parse(new Uint8Array(quantities));
403
+
404
+ return {
405
+ prices: parsed_prices.map((price) =>
406
+ Number(((Number(price) / FLOAT_SCALAR / quoteCoin.scalar) * baseCoin.scalar).toFixed(9)),
407
+ ),
408
+ quantities: parsed_quantities.map((price) =>
409
+ Number((Number(price) / baseCoin.scalar).toFixed(9)),
410
+ ),
411
+ };
412
+ }
413
+
414
+ /**
415
+ * @description Get level 2 order book ticks from mid-price for a pool
416
+ * @param {string} poolKey Key of the pool
417
+ * @param {number} ticks Number of ticks from mid-price
418
+ * @returns {Promise<{ bid_prices: Array<number>, bid_quantities: Array<number>, ask_prices: Array<number>, ask_quantities: Array<number> }>}
419
+ * An object with arrays of prices and quantities
420
+ */
421
+ async getLevel2TicksFromMid(poolKey: string, ticks: number) {
422
+ const tx = new Transaction();
423
+ const pool = this.#config.getPool(poolKey);
424
+ const baseCoin = this.#config.getCoin(pool.baseCoin);
425
+ const quoteCoin = this.#config.getCoin(pool.quoteCoin);
426
+
427
+ tx.add(this.deepBook.getLevel2TicksFromMid(poolKey, ticks));
428
+ const res = await this.client.devInspectTransactionBlock({
429
+ sender: normalizeHaneulAddress(this.#address),
430
+ transactionBlock: tx,
431
+ });
432
+
433
+ const bid_prices = res.results![0].returnValues![0][0];
434
+ const bid_parsed_prices = bcs.vector(bcs.u64()).parse(new Uint8Array(bid_prices));
435
+ const bid_quantities = res.results![0].returnValues![1][0];
436
+ const bid_parsed_quantities = bcs.vector(bcs.u64()).parse(new Uint8Array(bid_quantities));
437
+
438
+ const ask_prices = res.results![0].returnValues![2][0];
439
+ const ask_parsed_prices = bcs.vector(bcs.u64()).parse(new Uint8Array(ask_prices));
440
+ const ask_quantities = res.results![0].returnValues![3][0];
441
+ const ask_parsed_quantities = bcs.vector(bcs.u64()).parse(new Uint8Array(ask_quantities));
442
+
443
+ return {
444
+ bid_prices: bid_parsed_prices.map((price) =>
445
+ Number(((Number(price) / FLOAT_SCALAR / quoteCoin.scalar) * baseCoin.scalar).toFixed(9)),
446
+ ),
447
+ bid_quantities: bid_parsed_quantities.map((quantity) =>
448
+ Number((Number(quantity) / baseCoin.scalar).toFixed(9)),
449
+ ),
450
+ ask_prices: ask_parsed_prices.map((price) =>
451
+ Number(((Number(price) / FLOAT_SCALAR / quoteCoin.scalar) * baseCoin.scalar).toFixed(9)),
452
+ ),
453
+ ask_quantities: ask_parsed_quantities.map((quantity) =>
454
+ Number((Number(quantity) / baseCoin.scalar).toFixed(9)),
455
+ ),
456
+ };
457
+ }
458
+
459
+ /**
460
+ * @description Get the vault balances for a pool
461
+ * @param {string} poolKey Key of the pool
462
+ * @returns {Promise<{ base: number, quote: number, deep: number }>}
463
+ * An object with base, quote, and deep balances in the vault
464
+ */
465
+ async vaultBalances(poolKey: string) {
466
+ const tx = new Transaction();
467
+ const pool = this.#config.getPool(poolKey);
468
+ const baseScalar = this.#config.getCoin(pool.baseCoin).scalar;
469
+ const quoteScalar = this.#config.getCoin(pool.quoteCoin).scalar;
470
+
471
+ tx.add(this.deepBook.vaultBalances(poolKey));
472
+ const res = await this.client.devInspectTransactionBlock({
473
+ sender: normalizeHaneulAddress(this.#address),
474
+ transactionBlock: tx,
475
+ });
476
+
477
+ const baseInVault = Number(bcs.U64.parse(new Uint8Array(res.results![0].returnValues![0][0])));
478
+ const quoteInVault = Number(bcs.U64.parse(new Uint8Array(res.results![0].returnValues![1][0])));
479
+ const deepInVault = Number(bcs.U64.parse(new Uint8Array(res.results![0].returnValues![2][0])));
480
+
481
+ return {
482
+ base: Number((baseInVault / baseScalar).toFixed(9)),
483
+ quote: Number((quoteInVault / quoteScalar).toFixed(9)),
484
+ deep: Number((deepInVault / DEEP_SCALAR).toFixed(9)),
485
+ };
486
+ }
487
+
488
+ /**
489
+ * @description Get the pool ID by asset types
490
+ * @param {string} baseType Type of the base asset
491
+ * @param {string} quoteType Type of the quote asset
492
+ * @returns {Promise<string>} The address of the pool
493
+ */
494
+ async getPoolIdByAssets(baseType: string, quoteType: string) {
495
+ const tx = new Transaction();
496
+ tx.add(this.deepBook.getPoolIdByAssets(baseType, quoteType));
497
+
498
+ const res = await this.client.devInspectTransactionBlock({
499
+ sender: normalizeHaneulAddress(this.#address),
500
+ transactionBlock: tx,
501
+ });
502
+
503
+ const address = bcs.Address.parse(new Uint8Array(res.results![0].returnValues![0][0]));
504
+
505
+ return address;
506
+ }
507
+
508
+ /**
509
+ * @description Get the mid price for a pool
510
+ * @param {string} poolKey Key of the pool
511
+ * @returns {Promise<number>} The mid price
512
+ */
513
+ async midPrice(poolKey: string) {
514
+ const tx = new Transaction();
515
+ const pool = this.#config.getPool(poolKey);
516
+ tx.add(this.deepBook.midPrice(poolKey));
517
+
518
+ const baseCoin = this.#config.getCoin(pool.baseCoin);
519
+ const quoteCoin = this.#config.getCoin(pool.quoteCoin);
520
+
521
+ const res = await this.client.devInspectTransactionBlock({
522
+ sender: normalizeHaneulAddress(this.#address),
523
+ transactionBlock: tx,
524
+ });
525
+
526
+ const bytes = res.results![0].returnValues![0][0];
527
+ const parsed_mid_price = Number(bcs.U64.parse(new Uint8Array(bytes)));
528
+ const adjusted_mid_price =
529
+ (parsed_mid_price * baseCoin.scalar) / quoteCoin.scalar / FLOAT_SCALAR;
530
+
531
+ return Number(adjusted_mid_price.toFixed(9));
532
+ }
533
+
534
+ /**
535
+ * @description Get the trade parameters for a given pool, including taker fee, maker fee, and stake required.
536
+ * @param {string} poolKey Key of the pool
537
+ * @returns {Promise<{ takerFee: number, makerFee: number, stakeRequired: number }>}
538
+ */
539
+ async poolTradeParams(poolKey: string) {
540
+ const tx = new Transaction();
541
+
542
+ tx.add(this.deepBook.poolTradeParams(poolKey));
543
+ const res = await this.client.devInspectTransactionBlock({
544
+ sender: normalizeHaneulAddress(this.#address),
545
+ transactionBlock: tx,
546
+ });
547
+
548
+ const takerFee = Number(bcs.U64.parse(new Uint8Array(res.results![0].returnValues![0][0])));
549
+ const makerFee = Number(bcs.U64.parse(new Uint8Array(res.results![0].returnValues![1][0])));
550
+ const stakeRequired = Number(
551
+ bcs.U64.parse(new Uint8Array(res.results![0].returnValues![2][0])),
552
+ );
553
+
554
+ return {
555
+ takerFee: Number(takerFee / FLOAT_SCALAR),
556
+ makerFee: Number(makerFee / FLOAT_SCALAR),
557
+ stakeRequired: Number(stakeRequired / DEEP_SCALAR),
558
+ };
559
+ }
560
+
561
+ /**
562
+ * @description Get the trade parameters for a given pool, including tick size, lot size, and min size.
563
+ * @param {string} poolKey Key of the pool
564
+ * @returns {Promise<{ tickSize: number, lotSize: number, minSize: number }>}
565
+ */
566
+ async poolBookParams(poolKey: string) {
567
+ const tx = new Transaction();
568
+ const pool = this.#config.getPool(poolKey);
569
+ const baseScalar = this.#config.getCoin(pool.baseCoin).scalar;
570
+ const quoteScalar = this.#config.getCoin(pool.quoteCoin).scalar;
571
+
572
+ tx.add(this.deepBook.poolBookParams(poolKey));
573
+ const res = await this.client.devInspectTransactionBlock({
574
+ sender: normalizeHaneulAddress(this.#address),
575
+ transactionBlock: tx,
576
+ });
577
+
578
+ const tickSize = Number(bcs.U64.parse(new Uint8Array(res.results![0].returnValues![0][0])));
579
+ const lotSize = Number(bcs.U64.parse(new Uint8Array(res.results![0].returnValues![1][0])));
580
+ const minSize = Number(bcs.U64.parse(new Uint8Array(res.results![0].returnValues![2][0])));
581
+
582
+ return {
583
+ tickSize: Number((tickSize * baseScalar) / quoteScalar / FLOAT_SCALAR),
584
+ lotSize: Number(lotSize / baseScalar),
585
+ minSize: Number(minSize / baseScalar),
586
+ };
587
+ }
588
+
589
+ /**
590
+ * @description Get the account information for a given pool and balance manager
591
+ * @param {string} poolKey Key of the pool
592
+ * @param {string} managerKey The key of the BalanceManager
593
+ * @returns {Promise<Object>} A promise that resolves to an object containing the account information
594
+ */
595
+ async account(poolKey: string, managerKey: string) {
596
+ const tx = new Transaction();
597
+ const pool = this.#config.getPool(poolKey);
598
+ const baseScalar = this.#config.getCoin(pool.baseCoin).scalar;
599
+ const quoteScalar = this.#config.getCoin(pool.quoteCoin).scalar;
600
+
601
+ tx.add(this.deepBook.account(poolKey, managerKey));
602
+ const res = await this.client.devInspectTransactionBlock({
603
+ sender: normalizeHaneulAddress(this.#address),
604
+ transactionBlock: tx,
605
+ });
606
+
607
+ const accountInformation = res.results![0].returnValues![0][0];
608
+ const accountInfo = Account.parse(new Uint8Array(accountInformation));
609
+
610
+ return {
611
+ epoch: accountInfo.epoch,
612
+ open_orders: accountInfo.open_orders,
613
+ taker_volume: Number(accountInfo.taker_volume) / baseScalar,
614
+ maker_volume: Number(accountInfo.maker_volume) / baseScalar,
615
+ active_stake: Number(accountInfo.active_stake) / DEEP_SCALAR,
616
+ inactive_stake: Number(accountInfo.inactive_stake) / DEEP_SCALAR,
617
+ created_proposal: accountInfo.created_proposal,
618
+ voted_proposal: accountInfo.voted_proposal,
619
+ unclaimed_rebates: {
620
+ base: Number(accountInfo.unclaimed_rebates.base) / baseScalar,
621
+ quote: Number(accountInfo.unclaimed_rebates.quote) / quoteScalar,
622
+ deep: Number(accountInfo.unclaimed_rebates.deep) / DEEP_SCALAR,
623
+ },
624
+ settled_balances: {
625
+ base: Number(accountInfo.settled_balances.base) / baseScalar,
626
+ quote: Number(accountInfo.settled_balances.quote) / quoteScalar,
627
+ deep: Number(accountInfo.settled_balances.deep) / DEEP_SCALAR,
628
+ },
629
+ owed_balances: {
630
+ base: Number(accountInfo.owed_balances.base) / baseScalar,
631
+ quote: Number(accountInfo.owed_balances.quote) / quoteScalar,
632
+ deep: Number(accountInfo.owed_balances.deep) / DEEP_SCALAR,
633
+ },
634
+ };
635
+ }
636
+
637
+ /**
638
+ * @description Get the locked balances for a pool and balance manager
639
+ * @param {string} poolKey Key of the pool
640
+ * @param {string} managerKey The key of the BalanceManager
641
+ * @returns {Promise<{ base: number, quote: number, deep: number }>}
642
+ * An object with base, quote, and deep locked for the balance manager in the pool
643
+ */
644
+ async lockedBalance(poolKey: string, balanceManagerKey: string) {
645
+ const tx = new Transaction();
646
+ const pool = this.#config.getPool(poolKey);
647
+ const baseScalar = this.#config.getCoin(pool.baseCoin).scalar;
648
+ const quoteScalar = this.#config.getCoin(pool.quoteCoin).scalar;
649
+
650
+ tx.add(this.deepBook.lockedBalance(poolKey, balanceManagerKey));
651
+ const res = await this.client.devInspectTransactionBlock({
652
+ sender: normalizeHaneulAddress(this.#address),
653
+ transactionBlock: tx,
654
+ });
655
+
656
+ const baseLocked = Number(bcs.U64.parse(new Uint8Array(res.results![0].returnValues![0][0])));
657
+ const quoteLocked = Number(bcs.U64.parse(new Uint8Array(res.results![0].returnValues![1][0])));
658
+ const deepLocked = Number(bcs.U64.parse(new Uint8Array(res.results![0].returnValues![2][0])));
659
+
660
+ return {
661
+ base: Number((baseLocked / baseScalar).toFixed(9)),
662
+ quote: Number((quoteLocked / quoteScalar).toFixed(9)),
663
+ deep: Number((deepLocked / DEEP_SCALAR).toFixed(9)),
664
+ };
665
+ }
666
+
667
+ /**
668
+ * @description Get the DEEP price conversion for a pool
669
+ * @param {string} poolKey Key of the pool
670
+ * @returns {Promise<{ asset_is_base: bool, deep_per_quote: number }>} Deep price conversion
671
+ */
672
+ async getPoolDeepPrice(poolKey: string) {
673
+ const tx = new Transaction();
674
+ const pool = this.#config.getPool(poolKey);
675
+ tx.add(this.deepBook.getPoolDeepPrice(poolKey));
676
+
677
+ const baseCoin = this.#config.getCoin(pool.baseCoin);
678
+ const quoteCoin = this.#config.getCoin(pool.quoteCoin);
679
+ const deepCoin = this.#config.getCoin('DEEP');
680
+
681
+ const res = await this.client.devInspectTransactionBlock({
682
+ sender: normalizeHaneulAddress(this.#address),
683
+ transactionBlock: tx,
684
+ });
685
+
686
+ const poolDeepPriceBytes = res.results![0].returnValues![0][0];
687
+ const poolDeepPrice = OrderDeepPrice.parse(new Uint8Array(poolDeepPriceBytes));
688
+
689
+ if (poolDeepPrice.asset_is_base) {
690
+ return {
691
+ asset_is_base: poolDeepPrice.asset_is_base,
692
+ deep_per_base:
693
+ ((Number(poolDeepPrice.deep_per_asset) / FLOAT_SCALAR) * baseCoin.scalar) /
694
+ deepCoin.scalar,
695
+ };
696
+ } else {
697
+ return {
698
+ asset_is_base: poolDeepPrice.asset_is_base,
699
+ deep_per_quote:
700
+ ((Number(poolDeepPrice.deep_per_asset) / FLOAT_SCALAR) * quoteCoin.scalar) /
701
+ deepCoin.scalar,
702
+ };
703
+ }
704
+ }
705
+
706
+ /**
707
+ * @description Decode the order ID to get bid/ask status, price, and orderId
708
+ * @param {bigint} encodedOrderId Encoded order ID
709
+ * @returns {Object} Object containing isBid, price, and orderId
710
+ */
711
+ decodeOrderId(encodedOrderId: bigint): { isBid: boolean; price: number; orderId: number } {
712
+ const isBid = encodedOrderId >> 127n === 0n;
713
+ const price = Number((encodedOrderId >> 64n) & ((1n << 63n) - 1n));
714
+ const orderId = Number(encodedOrderId & ((1n << 64n) - 1n));
715
+
716
+ return { isBid, price, orderId };
717
+ }
718
+
719
+ /**
720
+ * @description Get all balance manager IDs for a given owner
721
+ * @param {string} owner The owner address to get balance manager IDs for
722
+ * @returns {Promise<string[]>} Array of balance manager ID strings
723
+ */
724
+ async getBalanceManagerIds(owner: string): Promise<string[]> {
725
+ const tx = new Transaction();
726
+ tx.add(this.deepBook.getBalanceManagerIds(owner));
727
+
728
+ const res = await this.client.devInspectTransactionBlock({
729
+ sender: normalizeHaneulAddress(this.#address),
730
+ transactionBlock: tx,
731
+ });
732
+
733
+ const bytes = res.results![0].returnValues![0][0];
734
+ const vecOfAddresses = bcs.vector(bcs.Address).parse(new Uint8Array(bytes));
735
+
736
+ return vecOfAddresses.map((id: string) => normalizeHaneulAddress(id));
737
+ }
738
+
739
+ /**
740
+ * @description Get the owner of the referral (DeepBookPoolReferral)
741
+ * @param {string} referral The ID of the referral to get the owner of
742
+ * @returns {Promise<string>} The owner of the referral
743
+ */
744
+ async balanceManagerReferralOwner(referral: string) {
745
+ const tx = new Transaction();
746
+ tx.add(this.balanceManager.balanceManagerReferralOwner(referral));
747
+
748
+ const res = await this.client.devInspectTransactionBlock({
749
+ sender: normalizeHaneulAddress(this.#address),
750
+ transactionBlock: tx,
751
+ });
752
+
753
+ if (res.error || !res.results || res.results.length === 0) {
754
+ throw new Error(`Failed to get referral owner: ${res.error || 'No results returned'}`);
755
+ }
756
+
757
+ const bytes = res.results[0].returnValues![0][0];
758
+ const owner = bcs.Address.parse(new Uint8Array(bytes));
759
+
760
+ return owner;
761
+ }
762
+
763
+ /**
764
+ * @description Get the referral balances for a pool and referral (DeepBookPoolReferral)
765
+ * @param {string} poolKey Key of the pool
766
+ * @param {string} referral The referral ID to get balances for
767
+ * @returns {Promise<{ base: number, quote: number, deep: number }>} Object with base, quote, and deep balances
768
+ */
769
+ async getPoolReferralBalances(
770
+ poolKey: string,
771
+ referral: string,
772
+ ): Promise<{ base: number; quote: number; deep: number }> {
773
+ const tx = new Transaction();
774
+ const pool = this.#config.getPool(poolKey);
775
+ const baseScalar = this.#config.getCoin(pool.baseCoin).scalar;
776
+ const quoteScalar = this.#config.getCoin(pool.quoteCoin).scalar;
777
+
778
+ tx.add(this.deepBook.getPoolReferralBalances(poolKey, referral));
779
+
780
+ const res = await this.client.devInspectTransactionBlock({
781
+ sender: normalizeHaneulAddress(this.#address),
782
+ transactionBlock: tx,
783
+ });
784
+
785
+ // The function returns three u64 values: (base, quote, deep)
786
+ const baseBytes = res.results![0].returnValues![0][0];
787
+ const quoteBytes = res.results![0].returnValues![1][0];
788
+ const deepBytes = res.results![0].returnValues![2][0];
789
+
790
+ const baseBalance = Number(bcs.U64.parse(new Uint8Array(baseBytes)));
791
+ const quoteBalance = Number(bcs.U64.parse(new Uint8Array(quoteBytes)));
792
+ const deepBalance = Number(bcs.U64.parse(new Uint8Array(deepBytes)));
793
+
794
+ return {
795
+ base: baseBalance / baseScalar,
796
+ quote: quoteBalance / quoteScalar,
797
+ deep: deepBalance / DEEP_SCALAR,
798
+ };
799
+ }
800
+
801
+ /**
802
+ * @description Get the pool ID associated with a referral (DeepBookPoolReferral)
803
+ * @param {string} referral The referral (DeepBookPoolReferral) to get the pool ID for
804
+ * @returns {Promise<string>} The pool ID
805
+ */
806
+ async balanceManagerReferralPoolId(referral: string): Promise<string> {
807
+ const tx = new Transaction();
808
+
809
+ tx.add(this.balanceManager.balanceManagerReferralPoolId(referral));
810
+
811
+ const res = await this.client.devInspectTransactionBlock({
812
+ sender: normalizeHaneulAddress(this.#address),
813
+ transactionBlock: tx,
814
+ });
815
+
816
+ const bytes = res.results![0].returnValues![0][0];
817
+ const poolId = bcs.Address.parse(new Uint8Array(bytes));
818
+
819
+ return normalizeHaneulAddress(poolId);
820
+ }
821
+
822
+ /**
823
+ * @description Get the multiplier for a referral (DeepBookPoolReferral)
824
+ * @param {string} poolKey Key of the pool
825
+ * @param {string} referral The referral (DeepBookPoolReferral) to get the multiplier for
826
+ * @returns {Promise<number>} The multiplier value
827
+ */
828
+ async poolReferralMultiplier(poolKey: string, referral: string): Promise<number> {
829
+ const tx = new Transaction();
830
+
831
+ tx.add(this.deepBook.poolReferralMultiplier(poolKey, referral));
832
+
833
+ const res = await this.client.devInspectTransactionBlock({
834
+ sender: normalizeHaneulAddress(this.#address),
835
+ transactionBlock: tx,
836
+ });
837
+
838
+ const bytes = res.results![0].returnValues![0][0];
839
+ const multiplier = Number(bcs.U64.parse(new Uint8Array(bytes)));
840
+
841
+ return multiplier / FLOAT_SCALAR;
842
+ }
843
+
844
+ /**
845
+ * @description Get the referral ID from a balance manager for a specific pool
846
+ * @param {string} managerKey Key of the balance manager
847
+ * @param {string} poolKey Key of the pool to get the referral for
848
+ * @returns {Promise<string | null>} The referral ID or null if not set
849
+ */
850
+ async getBalanceManagerReferralId(managerKey: string, poolKey: string): Promise<string | null> {
851
+ const tx = new Transaction();
852
+ tx.add(this.balanceManager.getBalanceManagerReferralId(managerKey, poolKey));
853
+
854
+ const res = await this.client.devInspectTransactionBlock({
855
+ sender: normalizeHaneulAddress(this.#address),
856
+ transactionBlock: tx,
857
+ });
858
+
859
+ try {
860
+ const bytes = res.results![0].returnValues![0][0];
861
+ const optionId = bcs.option(bcs.Address).parse(new Uint8Array(bytes));
862
+ if (optionId === null) {
863
+ return null;
864
+ }
865
+ return normalizeHaneulAddress(optionId);
866
+ } catch {
867
+ return null;
868
+ }
869
+ }
870
+
871
+ async getPriceInfoObject(tx: Transaction, coinKey: string): Promise<string> {
872
+ const currentTime = Date.now();
873
+ const priceInfoObjectAge = (await this.getPriceInfoObjectAge(coinKey)) * 1000;
874
+ if (currentTime - priceInfoObjectAge < PRICE_INFO_OBJECT_MAX_AGE_MS) {
875
+ return await this.#config.getCoin(coinKey).priceInfoObjectId!;
876
+ }
877
+
878
+ // Initialize connection to the Haneul Price Service
879
+ const endpoint =
880
+ this.#config.env === 'testnet'
881
+ ? 'https://hermes-beta.pyth.network'
882
+ : 'https://hermes.pyth.network';
883
+ const connection = new HaneulPriceServiceConnection(endpoint);
884
+
885
+ // List of price feed IDs
886
+ const priceIDs = [
887
+ this.#config.getCoin(coinKey).feed!, // ASSET/USD price ID
888
+ ];
889
+
890
+ // Fetch price feed update data
891
+ const priceUpdateData = await connection.getPriceFeedsUpdateData(priceIDs);
892
+
893
+ // Initialize Sui Client and Pyth Client
894
+ const wormholeStateId = this.#config.pyth.wormholeStateId;
895
+ const pythStateId = this.#config.pyth.pythStateId;
896
+
897
+ const client = new HaneulPythClient(this.client, pythStateId, wormholeStateId);
898
+
899
+ return (await client.updatePriceFeeds(tx, priceUpdateData, priceIDs))[0]; // returns priceInfoObjectIds
900
+ }
901
+
902
+ /**
903
+ * @description Get the age of the price info object for a specific coin
904
+ * @param {string} coinKey Key of the coin
905
+ * @returns {Promise<string>} The arrival time of the price info object
906
+ */
907
+ async getPriceInfoObjectAge(coinKey: string) {
908
+ const priceInfoObjectId = this.#config.getCoin(coinKey).priceInfoObjectId!;
909
+ const res = await this.client.getObject({
910
+ id: priceInfoObjectId,
911
+ options: {
912
+ showContent: true,
913
+ },
914
+ });
915
+
916
+ if (!res.data?.content) {
917
+ throw new Error(`Price info object not found for ${coinKey}`);
918
+ }
919
+
920
+ // Type guard to check if content has fields property
921
+ if ('fields' in res.data.content) {
922
+ const fields = res.data.content.fields as any;
923
+ return fields.price_info?.fields?.arrival_time;
924
+ } else {
925
+ throw new Error(`Invalid price info object structure for ${coinKey}`);
926
+ }
927
+ }
928
+
929
+ // === Margin Pool View Methods ===
930
+
931
+ /**
932
+ * @description Get the margin pool ID
933
+ * @param {string} coinKey The key to identify the margin pool
934
+ * @returns {Promise<string>} The margin pool ID
935
+ */
936
+ async getMarginPoolId(coinKey: string): Promise<string> {
937
+ const tx = new Transaction();
938
+ tx.add(this.marginPool.getId(coinKey));
939
+
940
+ const res = await this.client.devInspectTransactionBlock({
941
+ sender: normalizeHaneulAddress(this.#address),
942
+ transactionBlock: tx,
943
+ });
944
+
945
+ const bytes = res.results![0].returnValues![0][0];
946
+ return bcs.Address.parse(new Uint8Array(bytes));
947
+ }
948
+
949
+ /**
950
+ * @description Check if a deepbook pool is allowed for borrowing from margin pool
951
+ * @param {string} coinKey The key to identify the margin pool
952
+ * @param {string} deepbookPoolId The ID of the deepbook pool
953
+ * @returns {Promise<boolean>} Whether the deepbook pool is allowed
954
+ */
955
+ async isDeepbookPoolAllowed(coinKey: string, deepbookPoolId: string): Promise<boolean> {
956
+ const tx = new Transaction();
957
+ tx.add(this.marginPool.deepbookPoolAllowed(coinKey, deepbookPoolId));
958
+
959
+ const res = await this.client.devInspectTransactionBlock({
960
+ sender: normalizeHaneulAddress(this.#address),
961
+ transactionBlock: tx,
962
+ });
963
+
964
+ const bytes = res.results![0].returnValues![0][0];
965
+ return bcs.bool().parse(new Uint8Array(bytes));
966
+ }
967
+
968
+ /**
969
+ * @description Get the total supply amount in the margin pool
970
+ * @param {string} coinKey The key to identify the margin pool
971
+ * @param {number} decimals Number of decimal places to show (default: 6)
972
+ * @returns {Promise<string>} The total supply amount as a string
973
+ */
974
+ async getMarginPoolTotalSupply(coinKey: string, decimals: number = 6): Promise<string> {
975
+ const tx = new Transaction();
976
+ tx.add(this.marginPool.totalSupply(coinKey));
977
+
978
+ const res = await this.client.devInspectTransactionBlock({
979
+ sender: normalizeHaneulAddress(this.#address),
980
+ transactionBlock: tx,
981
+ });
982
+
983
+ const bytes = res.results![0].returnValues![0][0];
984
+ const rawAmount = BigInt(bcs.U64.parse(new Uint8Array(bytes)));
985
+ const coin = this.#config.getCoin(coinKey);
986
+ return this.#formatTokenAmount(rawAmount, coin.scalar, decimals);
987
+ }
988
+
989
+ /**
990
+ * @description Get the total supply shares in the margin pool
991
+ * @param {string} coinKey The key to identify the margin pool
992
+ * @param {number} decimals Number of decimal places to show (default: 6)
993
+ * @returns {Promise<string>} The total supply shares as a string
994
+ */
995
+ async getMarginPoolSupplyShares(coinKey: string, decimals: number = 6): Promise<string> {
996
+ const tx = new Transaction();
997
+ tx.add(this.marginPool.supplyShares(coinKey));
998
+
999
+ const res = await this.client.devInspectTransactionBlock({
1000
+ sender: normalizeHaneulAddress(this.#address),
1001
+ transactionBlock: tx,
1002
+ });
1003
+
1004
+ const bytes = res.results![0].returnValues![0][0];
1005
+ const rawShares = BigInt(bcs.U64.parse(new Uint8Array(bytes)));
1006
+ const coin = this.#config.getCoin(coinKey);
1007
+ return this.#formatTokenAmount(rawShares, coin.scalar, decimals);
1008
+ }
1009
+
1010
+ /**
1011
+ * @description Get the total borrow amount in the margin pool
1012
+ * @param {string} coinKey The key to identify the margin pool
1013
+ * @param {number} decimals Number of decimal places to show (default: 6)
1014
+ * @returns {Promise<string>} The total borrow amount as a string
1015
+ */
1016
+ async getMarginPoolTotalBorrow(coinKey: string, decimals: number = 6): Promise<string> {
1017
+ const tx = new Transaction();
1018
+ tx.add(this.marginPool.totalBorrow(coinKey));
1019
+
1020
+ const res = await this.client.devInspectTransactionBlock({
1021
+ sender: normalizeHaneulAddress(this.#address),
1022
+ transactionBlock: tx,
1023
+ });
1024
+
1025
+ const bytes = res.results![0].returnValues![0][0];
1026
+ const rawAmount = BigInt(bcs.U64.parse(new Uint8Array(bytes)));
1027
+ const coin = this.#config.getCoin(coinKey);
1028
+ return this.#formatTokenAmount(rawAmount, coin.scalar, decimals);
1029
+ }
1030
+
1031
+ /**
1032
+ * @description Get the total borrow shares in the margin pool
1033
+ * @param {string} coinKey The key to identify the margin pool
1034
+ * @param {number} decimals Number of decimal places to show (default: 6)
1035
+ * @returns {Promise<string>} The total borrow shares as a string
1036
+ */
1037
+ async getMarginPoolBorrowShares(coinKey: string, decimals: number = 6): Promise<string> {
1038
+ const tx = new Transaction();
1039
+ tx.add(this.marginPool.borrowShares(coinKey));
1040
+
1041
+ const res = await this.client.devInspectTransactionBlock({
1042
+ sender: normalizeHaneulAddress(this.#address),
1043
+ transactionBlock: tx,
1044
+ });
1045
+
1046
+ const bytes = res.results![0].returnValues![0][0];
1047
+ const rawShares = BigInt(bcs.U64.parse(new Uint8Array(bytes)));
1048
+ const coin = this.#config.getCoin(coinKey);
1049
+ return this.#formatTokenAmount(rawShares, coin.scalar, decimals);
1050
+ }
1051
+
1052
+ /**
1053
+ * @description Get the last update timestamp of the margin pool
1054
+ * @param {string} coinKey The key to identify the margin pool
1055
+ * @returns {Promise<number>} The last update timestamp in milliseconds
1056
+ */
1057
+ async getMarginPoolLastUpdateTimestamp(coinKey: string): Promise<number> {
1058
+ const tx = new Transaction();
1059
+ tx.add(this.marginPool.lastUpdateTimestamp(coinKey));
1060
+
1061
+ const res = await this.client.devInspectTransactionBlock({
1062
+ sender: normalizeHaneulAddress(this.#address),
1063
+ transactionBlock: tx,
1064
+ });
1065
+
1066
+ const bytes = res.results![0].returnValues![0][0];
1067
+ return Number(bcs.U64.parse(new Uint8Array(bytes)));
1068
+ }
1069
+
1070
+ /**
1071
+ * @description Get the supply cap of the margin pool
1072
+ * @param {string} coinKey The key to identify the margin pool
1073
+ * @param {number} decimals Number of decimal places to show (default: 6)
1074
+ * @returns {Promise<string>} The supply cap as a string
1075
+ */
1076
+ async getMarginPoolSupplyCap(coinKey: string, decimals: number = 6): Promise<string> {
1077
+ const tx = new Transaction();
1078
+ tx.add(this.marginPool.supplyCap(coinKey));
1079
+
1080
+ const res = await this.client.devInspectTransactionBlock({
1081
+ sender: normalizeHaneulAddress(this.#address),
1082
+ transactionBlock: tx,
1083
+ });
1084
+
1085
+ const bytes = res.results![0].returnValues![0][0];
1086
+ const rawAmount = BigInt(bcs.U64.parse(new Uint8Array(bytes)));
1087
+ const coin = this.#config.getCoin(coinKey);
1088
+ return this.#formatTokenAmount(rawAmount, coin.scalar, decimals);
1089
+ }
1090
+
1091
+ /**
1092
+ * @description Get the max utilization rate of the margin pool
1093
+ * @param {string} coinKey The key to identify the margin pool
1094
+ * @returns {Promise<number>} The max utilization rate (as a decimal, e.g., 0.95 for 95%)
1095
+ */
1096
+ async getMarginPoolMaxUtilizationRate(coinKey: string): Promise<number> {
1097
+ const tx = new Transaction();
1098
+ tx.add(this.marginPool.maxUtilizationRate(coinKey));
1099
+
1100
+ const res = await this.client.devInspectTransactionBlock({
1101
+ sender: normalizeHaneulAddress(this.#address),
1102
+ transactionBlock: tx,
1103
+ });
1104
+
1105
+ const bytes = res.results![0].returnValues![0][0];
1106
+ const rawRate = Number(bcs.U64.parse(new Uint8Array(bytes)));
1107
+ return rawRate / FLOAT_SCALAR;
1108
+ }
1109
+
1110
+ /**
1111
+ * @description Get the protocol spread of the margin pool
1112
+ * @param {string} coinKey The key to identify the margin pool
1113
+ * @returns {Promise<number>} The protocol spread (as a decimal)
1114
+ */
1115
+ async getMarginPoolProtocolSpread(coinKey: string): Promise<number> {
1116
+ const tx = new Transaction();
1117
+ tx.add(this.marginPool.protocolSpread(coinKey));
1118
+
1119
+ const res = await this.client.devInspectTransactionBlock({
1120
+ sender: normalizeHaneulAddress(this.#address),
1121
+ transactionBlock: tx,
1122
+ });
1123
+
1124
+ const bytes = res.results![0].returnValues![0][0];
1125
+ const rawSpread = Number(bcs.U64.parse(new Uint8Array(bytes)));
1126
+ return rawSpread / FLOAT_SCALAR;
1127
+ }
1128
+
1129
+ /**
1130
+ * @description Get the minimum borrow amount for the margin pool
1131
+ * @param {string} coinKey The key to identify the margin pool
1132
+ * @param {number} decimals Number of decimal places to show (default: 6)
1133
+ * @returns {Promise<string>} The minimum borrow amount as a string
1134
+ */
1135
+ async getMarginPoolMinBorrow(coinKey: string, decimals: number = 6): Promise<string> {
1136
+ const tx = new Transaction();
1137
+ tx.add(this.marginPool.minBorrow(coinKey));
1138
+
1139
+ const res = await this.client.devInspectTransactionBlock({
1140
+ sender: normalizeHaneulAddress(this.#address),
1141
+ transactionBlock: tx,
1142
+ });
1143
+
1144
+ const bytes = res.results![0].returnValues![0][0];
1145
+ const rawAmount = BigInt(bcs.U64.parse(new Uint8Array(bytes)));
1146
+ const coin = this.#config.getCoin(coinKey);
1147
+ return this.#formatTokenAmount(rawAmount, coin.scalar, decimals);
1148
+ }
1149
+
1150
+ /**
1151
+ * @description Get the current interest rate of the margin pool
1152
+ * @param {string} coinKey The key to identify the margin pool
1153
+ * @returns {Promise<number>} The current interest rate (as a decimal)
1154
+ */
1155
+ async getMarginPoolInterestRate(coinKey: string): Promise<number> {
1156
+ const tx = new Transaction();
1157
+ tx.add(this.marginPool.interestRate(coinKey));
1158
+
1159
+ const res = await this.client.devInspectTransactionBlock({
1160
+ sender: normalizeHaneulAddress(this.#address),
1161
+ transactionBlock: tx,
1162
+ });
1163
+
1164
+ const bytes = res.results![0].returnValues![0][0];
1165
+ const rawRate = Number(bcs.U64.parse(new Uint8Array(bytes)));
1166
+ return rawRate / FLOAT_SCALAR;
1167
+ }
1168
+
1169
+ /**
1170
+ * @description Get user supply shares for a supplier cap
1171
+ * @param {string} coinKey The key to identify the margin pool
1172
+ * @param {string} supplierCapId The ID of the supplier cap
1173
+ * @param {number} decimals Number of decimal places to show (default: 6)
1174
+ * @returns {Promise<string>} The user's supply shares as a string
1175
+ */
1176
+ async getUserSupplyShares(
1177
+ coinKey: string,
1178
+ supplierCapId: string,
1179
+ decimals: number = 6,
1180
+ ): Promise<string> {
1181
+ const tx = new Transaction();
1182
+ tx.add(this.marginPool.userSupplyShares(coinKey, supplierCapId));
1183
+
1184
+ const res = await this.client.devInspectTransactionBlock({
1185
+ sender: normalizeHaneulAddress(this.#address),
1186
+ transactionBlock: tx,
1187
+ });
1188
+
1189
+ const bytes = res.results![0].returnValues![0][0];
1190
+ const rawShares = BigInt(bcs.U64.parse(new Uint8Array(bytes)));
1191
+ const coin = this.#config.getCoin(coinKey);
1192
+ return this.#formatTokenAmount(rawShares, coin.scalar, decimals);
1193
+ }
1194
+
1195
+ /**
1196
+ * @description Get user supply amount for a supplier cap
1197
+ * @param {string} coinKey The key to identify the margin pool
1198
+ * @param {string} supplierCapId The ID of the supplier cap
1199
+ * @param {number} decimals Number of decimal places to show (default: 6)
1200
+ * @returns {Promise<string>} The user's supply amount as a string
1201
+ */
1202
+ async getUserSupplyAmount(
1203
+ coinKey: string,
1204
+ supplierCapId: string,
1205
+ decimals: number = 6,
1206
+ ): Promise<string> {
1207
+ const tx = new Transaction();
1208
+ tx.add(this.marginPool.userSupplyAmount(coinKey, supplierCapId));
1209
+
1210
+ const res = await this.client.devInspectTransactionBlock({
1211
+ sender: normalizeHaneulAddress(this.#address),
1212
+ transactionBlock: tx,
1213
+ });
1214
+
1215
+ const bytes = res.results![0].returnValues![0][0];
1216
+ const rawAmount = BigInt(bcs.U64.parse(new Uint8Array(bytes)));
1217
+ const coin = this.#config.getCoin(coinKey);
1218
+ return this.#formatTokenAmount(rawAmount, coin.scalar, decimals);
1219
+ }
1220
+
1221
+ // === Margin Manager Read-Only Functions ===
1222
+
1223
+ /**
1224
+ * @description Get the owner address of a margin manager
1225
+ * @param {string} marginManagerKey The key to identify the margin manager
1226
+ * @returns {Promise<string>} The owner address
1227
+ */
1228
+ async getMarginManagerOwner(marginManagerKey: string): Promise<string> {
1229
+ const manager = this.#config.getMarginManager(marginManagerKey);
1230
+ const tx = new Transaction();
1231
+ tx.add(this.marginManager.ownerByPoolKey(manager.poolKey, manager.address));
1232
+
1233
+ const res = await this.client.devInspectTransactionBlock({
1234
+ sender: normalizeHaneulAddress(this.#address),
1235
+ transactionBlock: tx,
1236
+ });
1237
+
1238
+ const bytes = res.results![0].returnValues![0][0];
1239
+ return normalizeHaneulAddress(bcs.Address.parse(new Uint8Array(bytes)));
1240
+ }
1241
+
1242
+ /**
1243
+ * @description Get the DeepBook pool ID associated with a margin manager
1244
+ * @param {string} marginManagerKey The key to identify the margin manager
1245
+ * @returns {Promise<string>} The DeepBook pool ID
1246
+ */
1247
+ async getMarginManagerDeepbookPool(marginManagerKey: string): Promise<string> {
1248
+ const manager = this.#config.getMarginManager(marginManagerKey);
1249
+ const tx = new Transaction();
1250
+ tx.add(this.marginManager.deepbookPool(manager.poolKey, manager.address));
1251
+
1252
+ const res = await this.client.devInspectTransactionBlock({
1253
+ sender: normalizeHaneulAddress(this.#address),
1254
+ transactionBlock: tx,
1255
+ });
1256
+
1257
+ const bytes = res.results![0].returnValues![0][0];
1258
+ return normalizeHaneulAddress(bcs.Address.parse(new Uint8Array(bytes)));
1259
+ }
1260
+
1261
+ /**
1262
+ * @description Get the margin pool ID (if any) associated with a margin manager
1263
+ * @param {string} marginManagerKey The key to identify the margin manager
1264
+ * @returns {Promise<string | null>} The margin pool ID or null if no active loan
1265
+ */
1266
+ async getMarginManagerMarginPoolId(marginManagerKey: string): Promise<string | null> {
1267
+ const manager = this.#config.getMarginManager(marginManagerKey);
1268
+ const tx = new Transaction();
1269
+ tx.add(this.marginManager.marginPoolId(manager.poolKey, manager.address));
1270
+
1271
+ const res = await this.client.devInspectTransactionBlock({
1272
+ sender: normalizeHaneulAddress(this.#address),
1273
+ transactionBlock: tx,
1274
+ });
1275
+
1276
+ const bytes = res.results![0].returnValues![0][0];
1277
+ const option = bcs.option(bcs.Address).parse(new Uint8Array(bytes));
1278
+ return option ? normalizeHaneulAddress(option) : null;
1279
+ }
1280
+
1281
+ /**
1282
+ * @description Get borrowed shares for both base and quote assets
1283
+ * @param {string} marginManagerKey The key to identify the margin manager
1284
+ * @returns {Promise<{baseShares: string, quoteShares: string}>} The borrowed shares
1285
+ */
1286
+ async getMarginManagerBorrowedShares(
1287
+ marginManagerKey: string,
1288
+ ): Promise<{ baseShares: string; quoteShares: string }> {
1289
+ const manager = this.#config.getMarginManager(marginManagerKey);
1290
+ const tx = new Transaction();
1291
+ tx.add(this.marginManager.borrowedShares(manager.poolKey, manager.address));
1292
+
1293
+ const res = await this.client.devInspectTransactionBlock({
1294
+ sender: normalizeHaneulAddress(this.#address),
1295
+ transactionBlock: tx,
1296
+ });
1297
+
1298
+ const baseBytes = res.results![0].returnValues![0][0];
1299
+ const quoteBytes = res.results![0].returnValues![1][0];
1300
+ const baseShares = bcs.U64.parse(new Uint8Array(baseBytes)).toString();
1301
+ const quoteShares = bcs.U64.parse(new Uint8Array(quoteBytes)).toString();
1302
+
1303
+ return { baseShares, quoteShares };
1304
+ }
1305
+
1306
+ /**
1307
+ * @description Get borrowed base shares
1308
+ * @param {string} marginManagerKey The key to identify the margin manager
1309
+ * @returns {Promise<string>} The borrowed base shares
1310
+ */
1311
+ async getMarginManagerBorrowedBaseShares(marginManagerKey: string): Promise<string> {
1312
+ const manager = this.#config.getMarginManager(marginManagerKey);
1313
+ const tx = new Transaction();
1314
+ tx.add(this.marginManager.borrowedBaseShares(manager.poolKey, manager.address));
1315
+
1316
+ const res = await this.client.devInspectTransactionBlock({
1317
+ sender: normalizeHaneulAddress(this.#address),
1318
+ transactionBlock: tx,
1319
+ });
1320
+
1321
+ const bytes = res.results![0].returnValues![0][0];
1322
+ return bcs.U64.parse(new Uint8Array(bytes)).toString();
1323
+ }
1324
+
1325
+ /**
1326
+ * @description Get borrowed quote shares
1327
+ * @param {string} marginManagerKey The key to identify the margin manager
1328
+ * @returns {Promise<string>} The borrowed quote shares
1329
+ */
1330
+ async getMarginManagerBorrowedQuoteShares(marginManagerKey: string): Promise<string> {
1331
+ const manager = this.#config.getMarginManager(marginManagerKey);
1332
+ const tx = new Transaction();
1333
+ tx.add(this.marginManager.borrowedQuoteShares(manager.poolKey, manager.address));
1334
+
1335
+ const res = await this.client.devInspectTransactionBlock({
1336
+ sender: normalizeHaneulAddress(this.#address),
1337
+ transactionBlock: tx,
1338
+ });
1339
+
1340
+ const bytes = res.results![0].returnValues![0][0];
1341
+ return bcs.U64.parse(new Uint8Array(bytes)).toString();
1342
+ }
1343
+
1344
+ /**
1345
+ * @description Check if margin manager has base asset debt
1346
+ * @param {string} marginManagerKey The key to identify the margin manager
1347
+ * @returns {Promise<boolean>} True if has base debt, false otherwise
1348
+ */
1349
+ async getMarginManagerHasBaseDebt(marginManagerKey: string): Promise<boolean> {
1350
+ const manager = this.#config.getMarginManager(marginManagerKey);
1351
+ const tx = new Transaction();
1352
+ tx.add(this.marginManager.hasBaseDebt(manager.poolKey, manager.address));
1353
+
1354
+ const res = await this.client.devInspectTransactionBlock({
1355
+ sender: normalizeHaneulAddress(this.#address),
1356
+ transactionBlock: tx,
1357
+ });
1358
+
1359
+ const bytes = res.results![0].returnValues![0][0];
1360
+ return bcs.bool().parse(new Uint8Array(bytes));
1361
+ }
1362
+
1363
+ /**
1364
+ * @description Get the balance manager ID for a margin manager
1365
+ * @param {string} marginManagerKey The key to identify the margin manager
1366
+ * @returns {Promise<string>} The balance manager ID
1367
+ */
1368
+ async getMarginManagerBalanceManagerId(marginManagerKey: string): Promise<string> {
1369
+ const manager = this.#config.getMarginManager(marginManagerKey);
1370
+ const tx = new Transaction();
1371
+ tx.add(this.marginManager.balanceManager(manager.poolKey, manager.address));
1372
+
1373
+ const res = await this.client.devInspectTransactionBlock({
1374
+ sender: normalizeHaneulAddress(this.#address),
1375
+ transactionBlock: tx,
1376
+ });
1377
+
1378
+ const bytes = res.results![0].returnValues![0][0];
1379
+ return normalizeHaneulAddress(bcs.Address.parse(new Uint8Array(bytes)));
1380
+ }
1381
+
1382
+ /**
1383
+ * @description Calculate assets (base and quote) for a margin manager
1384
+ * @param {string} marginManagerKey The key to identify the margin manager
1385
+ * @param {number} decimals Number of decimal places to show (default: 6)
1386
+ * @returns {Promise<{baseAsset: string, quoteAsset: string}>} The base and quote assets
1387
+ */
1388
+ async getMarginManagerAssets(
1389
+ marginManagerKey: string,
1390
+ decimals: number = 6,
1391
+ ): Promise<{ baseAsset: string; quoteAsset: string }> {
1392
+ const manager = this.#config.getMarginManager(marginManagerKey);
1393
+ const tx = new Transaction();
1394
+ tx.add(this.marginManager.calculateAssets(manager.poolKey, manager.address));
1395
+
1396
+ const res = await this.client.devInspectTransactionBlock({
1397
+ sender: normalizeHaneulAddress(this.#address),
1398
+ transactionBlock: tx,
1399
+ });
1400
+
1401
+ const baseBytes = res.results![0].returnValues![0][0];
1402
+ const quoteBytes = res.results![0].returnValues![1][0];
1403
+ const pool = this.#config.getPool(manager.poolKey);
1404
+ const baseCoin = this.#config.getCoin(pool.baseCoin);
1405
+ const quoteCoin = this.#config.getCoin(pool.quoteCoin);
1406
+
1407
+ const baseAsset = this.#formatTokenAmount(
1408
+ BigInt(bcs.U64.parse(new Uint8Array(baseBytes))),
1409
+ baseCoin.scalar,
1410
+ decimals,
1411
+ );
1412
+ const quoteAsset = this.#formatTokenAmount(
1413
+ BigInt(bcs.U64.parse(new Uint8Array(quoteBytes))),
1414
+ quoteCoin.scalar,
1415
+ decimals,
1416
+ );
1417
+
1418
+ return { baseAsset, quoteAsset };
1419
+ }
1420
+
1421
+ /**
1422
+ * @description Calculate debts (base and quote) for a margin manager
1423
+ * NOTE: This function automatically determines whether to use base or quote margin pool
1424
+ * based on hasBaseDebt. You don't need to specify the debt coin type.
1425
+ * @param {string} marginManagerKey The key to identify the margin manager
1426
+ * @param {number} decimals Number of decimal places to show (default: 6)
1427
+ * @returns {Promise<{baseDebt: string, quoteDebt: string}>} The base and quote debts
1428
+ */
1429
+ async getMarginManagerDebts(
1430
+ marginManagerKey: string,
1431
+ decimals: number = 6,
1432
+ ): Promise<{ baseDebt: string; quoteDebt: string }> {
1433
+ // First check if the margin manager has base debt
1434
+ const hasBaseDebt = await this.getMarginManagerHasBaseDebt(marginManagerKey);
1435
+
1436
+ // Get the manager and pool configuration
1437
+ const manager = this.#config.getMarginManager(marginManagerKey);
1438
+ const pool = this.#config.getPool(manager.poolKey);
1439
+ const debtCoinKey = hasBaseDebt ? pool.baseCoin : pool.quoteCoin;
1440
+
1441
+ // Now call calculateDebts with the correct debt coin
1442
+ const tx = new Transaction();
1443
+ tx.add(this.marginManager.calculateDebts(manager.poolKey, debtCoinKey, manager.address));
1444
+
1445
+ const res = await this.client.devInspectTransactionBlock({
1446
+ sender: normalizeHaneulAddress(this.#address),
1447
+ transactionBlock: tx,
1448
+ });
1449
+
1450
+ // Check if the transaction failed
1451
+ if (!res.results || !res.results[0] || !res.results[0].returnValues) {
1452
+ throw new Error(
1453
+ `Failed to get margin manager debts: ${res.effects?.status?.error || 'Unknown error'}`,
1454
+ );
1455
+ }
1456
+
1457
+ // The Move function returns a tuple (u64, u64), so returnValues has 2 elements
1458
+ const baseBytes = res.results[0].returnValues[0][0];
1459
+ const quoteBytes = res.results[0].returnValues[1][0];
1460
+ const debtCoin = this.#config.getCoin(debtCoinKey);
1461
+
1462
+ const baseDebt = this.#formatTokenAmount(
1463
+ BigInt(bcs.U64.parse(new Uint8Array(baseBytes))),
1464
+ debtCoin.scalar,
1465
+ decimals,
1466
+ );
1467
+ const quoteDebt = this.#formatTokenAmount(
1468
+ BigInt(bcs.U64.parse(new Uint8Array(quoteBytes))),
1469
+ debtCoin.scalar,
1470
+ decimals,
1471
+ );
1472
+
1473
+ return { baseDebt, quoteDebt };
1474
+ }
1475
+
1476
+ /**
1477
+ * @description Get comprehensive state information for a margin manager
1478
+ * @param {string} marginManagerKey The key to identify the margin manager
1479
+ * @param {number} decimals Number of decimal places to show (default: 6)
1480
+ * @returns {Promise<{
1481
+ * managerId: string,
1482
+ * deepbookPoolId: string,
1483
+ * riskRatio: number,
1484
+ * baseAsset: string,
1485
+ * quoteAsset: string,
1486
+ * baseDebt: string,
1487
+ * quoteDebt: string,
1488
+ * basePythPrice: string,
1489
+ * basePythDecimals: number,
1490
+ * quotePythPrice: string,
1491
+ * quotePythDecimals: number
1492
+ * }>} Comprehensive margin manager state
1493
+ */
1494
+ async getMarginManagerState(
1495
+ marginManagerKey: string,
1496
+ decimals: number = 6,
1497
+ ): Promise<{
1498
+ managerId: string;
1499
+ deepbookPoolId: string;
1500
+ riskRatio: number;
1501
+ baseAsset: string;
1502
+ quoteAsset: string;
1503
+ baseDebt: string;
1504
+ quoteDebt: string;
1505
+ basePythPrice: string;
1506
+ basePythDecimals: number;
1507
+ quotePythPrice: string;
1508
+ quotePythDecimals: number;
1509
+ currentPrice: bigint;
1510
+ lowestTriggerAbovePrice: bigint;
1511
+ highestTriggerBelowPrice: bigint;
1512
+ }> {
1513
+ const manager = this.#config.getMarginManager(marginManagerKey);
1514
+ const tx = new Transaction();
1515
+ tx.add(this.marginManager.managerState(manager.poolKey, manager.address));
1516
+
1517
+ const res = await this.client.devInspectTransactionBlock({
1518
+ sender: normalizeHaneulAddress(this.#address),
1519
+ transactionBlock: tx,
1520
+ });
1521
+
1522
+ // Check if the transaction failed
1523
+ if (!res.results || !res.results[0] || !res.results[0].returnValues) {
1524
+ throw new Error(
1525
+ `Failed to get margin manager state: ${res.effects?.status?.error || 'Unknown error'}`,
1526
+ );
1527
+ }
1528
+
1529
+ const pool = this.#config.getPool(manager.poolKey);
1530
+ const baseCoin = this.#config.getCoin(pool.baseCoin);
1531
+ const quoteCoin = this.#config.getCoin(pool.quoteCoin);
1532
+
1533
+ // Parse all 11 return values
1534
+ const managerId = normalizeHaneulAddress(
1535
+ bcs.Address.parse(new Uint8Array(res.results[0].returnValues[0][0])),
1536
+ );
1537
+ const deepbookPoolId = normalizeHaneulAddress(
1538
+ bcs.Address.parse(new Uint8Array(res.results[0].returnValues[1][0])),
1539
+ );
1540
+ const riskRatio =
1541
+ Number(bcs.U64.parse(new Uint8Array(res.results[0].returnValues[2][0]))) / FLOAT_SCALAR;
1542
+ const baseAsset = this.#formatTokenAmount(
1543
+ BigInt(bcs.U64.parse(new Uint8Array(res.results[0].returnValues[3][0]))),
1544
+ baseCoin.scalar,
1545
+ decimals,
1546
+ );
1547
+ const quoteAsset = this.#formatTokenAmount(
1548
+ BigInt(bcs.U64.parse(new Uint8Array(res.results[0].returnValues[4][0]))),
1549
+ quoteCoin.scalar,
1550
+ decimals,
1551
+ );
1552
+ const baseDebt = this.#formatTokenAmount(
1553
+ BigInt(bcs.U64.parse(new Uint8Array(res.results[0].returnValues[5][0]))),
1554
+ baseCoin.scalar,
1555
+ decimals,
1556
+ );
1557
+ const quoteDebt = this.#formatTokenAmount(
1558
+ BigInt(bcs.U64.parse(new Uint8Array(res.results[0].returnValues[6][0]))),
1559
+ quoteCoin.scalar,
1560
+ decimals,
1561
+ );
1562
+ const basePythPrice = bcs.U64.parse(new Uint8Array(res.results[0].returnValues[7][0]));
1563
+ const basePythDecimals = Number(
1564
+ bcs.u8().parse(new Uint8Array(res.results[0].returnValues[8][0])),
1565
+ );
1566
+ const quotePythPrice = bcs.U64.parse(new Uint8Array(res.results[0].returnValues[9][0]));
1567
+ const quotePythDecimals = Number(
1568
+ bcs.u8().parse(new Uint8Array(res.results[0].returnValues[10][0])),
1569
+ );
1570
+ const currentPrice = BigInt(bcs.U64.parse(new Uint8Array(res.results[0].returnValues[11][0])));
1571
+ const lowestTriggerAbovePrice = BigInt(
1572
+ bcs.U64.parse(new Uint8Array(res.results[0].returnValues[12][0])),
1573
+ );
1574
+ const highestTriggerBelowPrice = BigInt(
1575
+ bcs.U64.parse(new Uint8Array(res.results[0].returnValues[13][0])),
1576
+ );
1577
+
1578
+ return {
1579
+ managerId,
1580
+ deepbookPoolId,
1581
+ riskRatio,
1582
+ baseAsset,
1583
+ quoteAsset,
1584
+ baseDebt,
1585
+ quoteDebt,
1586
+ basePythPrice: basePythPrice.toString(),
1587
+ basePythDecimals,
1588
+ quotePythPrice: quotePythPrice.toString(),
1589
+ quotePythDecimals,
1590
+ currentPrice,
1591
+ lowestTriggerAbovePrice,
1592
+ highestTriggerBelowPrice,
1593
+ };
1594
+ }
1595
+
1596
+ /**
1597
+ * @description Get the base asset balance of a margin manager
1598
+ * @param {string} marginManagerKey The key to identify the margin manager
1599
+ * @param {number} decimals Number of decimal places to show (default: 6)
1600
+ * @returns {Promise<string>} The base asset balance
1601
+ */
1602
+ async getMarginManagerBaseBalance(
1603
+ marginManagerKey: string,
1604
+ decimals: number = 9,
1605
+ ): Promise<string> {
1606
+ const manager = this.#config.getMarginManager(marginManagerKey);
1607
+ const tx = new Transaction();
1608
+ tx.add(this.marginManager.baseBalance(manager.poolKey, manager.address));
1609
+
1610
+ const res = await this.client.devInspectTransactionBlock({
1611
+ sender: normalizeHaneulAddress(this.#address),
1612
+ transactionBlock: tx,
1613
+ });
1614
+
1615
+ // Check if the transaction failed
1616
+ if (!res.results || !res.results[0] || !res.results[0].returnValues) {
1617
+ throw new Error(
1618
+ `Failed to get margin manager base balance: ${res.effects?.status?.error || 'Unknown error'}`,
1619
+ );
1620
+ }
1621
+
1622
+ const bytes = res.results[0].returnValues[0][0];
1623
+ const pool = this.#config.getPool(manager.poolKey);
1624
+ const baseCoin = this.#config.getCoin(pool.baseCoin);
1625
+
1626
+ return this.#formatTokenAmount(
1627
+ BigInt(bcs.U64.parse(new Uint8Array(bytes))),
1628
+ baseCoin.scalar,
1629
+ decimals,
1630
+ );
1631
+ }
1632
+
1633
+ /**
1634
+ * @description Get the quote asset balance of a margin manager
1635
+ * @param {string} marginManagerKey The key to identify the margin manager
1636
+ * @param {number} decimals Number of decimal places to show (default: 6)
1637
+ * @returns {Promise<string>} The quote asset balance
1638
+ */
1639
+ async getMarginManagerQuoteBalance(
1640
+ marginManagerKey: string,
1641
+ decimals: number = 9,
1642
+ ): Promise<string> {
1643
+ const manager = this.#config.getMarginManager(marginManagerKey);
1644
+ const tx = new Transaction();
1645
+ tx.add(this.marginManager.quoteBalance(manager.poolKey, manager.address));
1646
+
1647
+ const res = await this.client.devInspectTransactionBlock({
1648
+ sender: normalizeHaneulAddress(this.#address),
1649
+ transactionBlock: tx,
1650
+ });
1651
+
1652
+ // Check if the transaction failed
1653
+ if (!res.results || !res.results[0] || !res.results[0].returnValues) {
1654
+ throw new Error(
1655
+ `Failed to get margin manager quote balance: ${res.effects?.status?.error || 'Unknown error'}`,
1656
+ );
1657
+ }
1658
+
1659
+ const bytes = res.results[0].returnValues[0][0];
1660
+ const pool = this.#config.getPool(manager.poolKey);
1661
+ const quoteCoin = this.#config.getCoin(pool.quoteCoin);
1662
+
1663
+ return this.#formatTokenAmount(
1664
+ BigInt(bcs.U64.parse(new Uint8Array(bytes))),
1665
+ quoteCoin.scalar,
1666
+ decimals,
1667
+ );
1668
+ }
1669
+
1670
+ /**
1671
+ * @description Get the DEEP token balance of a margin manager
1672
+ * @param {string} marginManagerKey The key to identify the margin manager
1673
+ * @param {number} decimals Number of decimal places to show (default: 6)
1674
+ * @returns {Promise<string>} The DEEP token balance
1675
+ */
1676
+ async getMarginManagerDeepBalance(
1677
+ marginManagerKey: string,
1678
+ decimals: number = 6,
1679
+ ): Promise<string> {
1680
+ const manager = this.#config.getMarginManager(marginManagerKey);
1681
+ const tx = new Transaction();
1682
+ tx.add(this.marginManager.deepBalance(manager.poolKey, manager.address));
1683
+
1684
+ const res = await this.client.devInspectTransactionBlock({
1685
+ sender: normalizeHaneulAddress(this.#address),
1686
+ transactionBlock: tx,
1687
+ });
1688
+
1689
+ // Check if the transaction failed
1690
+ if (!res.results || !res.results[0] || !res.results[0].returnValues) {
1691
+ throw new Error(
1692
+ `Failed to get margin manager DEEP balance: ${res.effects?.status?.error || 'Unknown error'}`,
1693
+ );
1694
+ }
1695
+
1696
+ const bytes = res.results[0].returnValues[0][0];
1697
+ const deepCoin = this.#config.getCoin('DEEP');
1698
+
1699
+ return this.#formatTokenAmount(
1700
+ BigInt(bcs.U64.parse(new Uint8Array(bytes))),
1701
+ deepCoin.scalar,
1702
+ decimals,
1703
+ );
1704
+ }
1705
+
1706
+ // === Margin TPSL (Take Profit / Stop Loss) Read-Only Functions ===
1707
+
1708
+ /**
1709
+ * @description Get all conditional order IDs for a margin manager
1710
+ * @param {string} marginManagerKey The key to identify the margin manager
1711
+ * @returns {Promise<string[]>} Array of conditional order IDs
1712
+ */
1713
+ async getConditionalOrderIds(marginManagerKey: string): Promise<string[]> {
1714
+ const manager = this.#config.getMarginManager(marginManagerKey);
1715
+ const tx = new Transaction();
1716
+ tx.add(this.marginTPSL.conditionalOrderIds(manager.poolKey, manager.address));
1717
+
1718
+ const res = await this.client.devInspectTransactionBlock({
1719
+ sender: normalizeHaneulAddress(this.#address),
1720
+ transactionBlock: tx,
1721
+ });
1722
+
1723
+ if (!res.results || !res.results[0] || !res.results[0].returnValues) {
1724
+ throw new Error(
1725
+ `Failed to get conditional order IDs: ${res.effects?.status?.error || 'Unknown error'}`,
1726
+ );
1727
+ }
1728
+
1729
+ const bytes = res.results[0].returnValues[0][0];
1730
+ const orderIds = bcs.vector(bcs.u64()).parse(new Uint8Array(bytes));
1731
+ return orderIds.map((id) => id.toString());
1732
+ }
1733
+
1734
+ /**
1735
+ * @description Get the lowest trigger price for trigger_above orders
1736
+ * Returns MAX_U64 if there are no trigger_above orders
1737
+ * @param {string} marginManagerKey The key to identify the margin manager
1738
+ * @returns {Promise<bigint>} The lowest trigger above price
1739
+ */
1740
+ async getLowestTriggerAbovePrice(marginManagerKey: string): Promise<bigint> {
1741
+ const manager = this.#config.getMarginManager(marginManagerKey);
1742
+ const tx = new Transaction();
1743
+ tx.add(this.marginTPSL.lowestTriggerAbovePrice(manager.poolKey, manager.address));
1744
+
1745
+ const res = await this.client.devInspectTransactionBlock({
1746
+ sender: normalizeHaneulAddress(this.#address),
1747
+ transactionBlock: tx,
1748
+ });
1749
+
1750
+ if (!res.results || !res.results[0] || !res.results[0].returnValues) {
1751
+ throw new Error(
1752
+ `Failed to get lowest trigger above price: ${res.effects?.status?.error || 'Unknown error'}`,
1753
+ );
1754
+ }
1755
+
1756
+ const bytes = res.results[0].returnValues[0][0];
1757
+ return BigInt(bcs.U64.parse(new Uint8Array(bytes)));
1758
+ }
1759
+
1760
+ /**
1761
+ * @description Get the highest trigger price for trigger_below orders
1762
+ * Returns 0 if there are no trigger_below orders
1763
+ * @param {string} marginManagerKey The key to identify the margin manager
1764
+ * @returns {Promise<bigint>} The highest trigger below price
1765
+ */
1766
+ async getHighestTriggerBelowPrice(marginManagerKey: string): Promise<bigint> {
1767
+ const manager = this.#config.getMarginManager(marginManagerKey);
1768
+ const tx = new Transaction();
1769
+ tx.add(this.marginTPSL.highestTriggerBelowPrice(manager.poolKey, manager.address));
1770
+
1771
+ const res = await this.client.devInspectTransactionBlock({
1772
+ sender: normalizeHaneulAddress(this.#address),
1773
+ transactionBlock: tx,
1774
+ });
1775
+
1776
+ if (!res.results || !res.results[0] || !res.results[0].returnValues) {
1777
+ throw new Error(
1778
+ `Failed to get highest trigger below price: ${res.effects?.status?.error || 'Unknown error'}`,
1779
+ );
1780
+ }
1781
+
1782
+ const bytes = res.results[0].returnValues[0][0];
1783
+ return BigInt(bcs.U64.parse(new Uint8Array(bytes)));
1784
+ }
1785
+
1786
+ // === Margin Registry Functions ===
1787
+
1788
+ /**
1789
+ * @description Check if a deepbook pool is enabled for margin trading
1790
+ * @param {string} poolKey The key to identify the pool
1791
+ * @returns {Promise<boolean>} True if the pool is enabled for margin trading
1792
+ */
1793
+ async isPoolEnabledForMargin(poolKey: string): Promise<boolean> {
1794
+ const tx = new Transaction();
1795
+ tx.add(this.marginRegistry.poolEnabled(poolKey));
1796
+
1797
+ const res = await this.client.devInspectTransactionBlock({
1798
+ sender: normalizeHaneulAddress(this.#address),
1799
+ transactionBlock: tx,
1800
+ });
1801
+
1802
+ const bytes = res.results![0].returnValues![0][0];
1803
+ return bcs.Bool.parse(new Uint8Array(bytes));
1804
+ }
1805
+
1806
+ /**
1807
+ * @description Get the margin manager IDs for a given owner address
1808
+ * @param {string} owner The owner address
1809
+ * @returns {Promise<string[]>} Array of margin manager IDs
1810
+ */
1811
+ async getMarginManagerIdsForOwner(owner: string): Promise<string[]> {
1812
+ const tx = new Transaction();
1813
+ tx.add(this.marginRegistry.getMarginManagerIds(owner));
1814
+
1815
+ const res = await this.client.devInspectTransactionBlock({
1816
+ sender: normalizeHaneulAddress(this.#address),
1817
+ transactionBlock: tx,
1818
+ });
1819
+
1820
+ const bytes = res.results![0].returnValues![0][0];
1821
+ const vecSet = VecSet(bcs.Address).parse(new Uint8Array(bytes));
1822
+ return vecSet.contents.map((id) => normalizeHaneulAddress(id));
1823
+ }
1824
+
1825
+ /**
1826
+ * @description Get the base margin pool ID for a deepbook pool
1827
+ * @param {string} poolKey The key to identify the pool
1828
+ * @returns {Promise<string>} The base margin pool ID
1829
+ */
1830
+ async getBaseMarginPoolId(poolKey: string): Promise<string> {
1831
+ const tx = new Transaction();
1832
+ tx.add(this.marginRegistry.baseMarginPoolId(poolKey));
1833
+
1834
+ const res = await this.client.devInspectTransactionBlock({
1835
+ sender: normalizeHaneulAddress(this.#address),
1836
+ transactionBlock: tx,
1837
+ });
1838
+
1839
+ const bytes = res.results![0].returnValues![0][0];
1840
+ const id = bcs.Address.parse(new Uint8Array(bytes));
1841
+ return '0x' + id;
1842
+ }
1843
+
1844
+ /**
1845
+ * @description Get the quote margin pool ID for a deepbook pool
1846
+ * @param {string} poolKey The key to identify the pool
1847
+ * @returns {Promise<string>} The quote margin pool ID
1848
+ */
1849
+ async getQuoteMarginPoolId(poolKey: string): Promise<string> {
1850
+ const tx = new Transaction();
1851
+ tx.add(this.marginRegistry.quoteMarginPoolId(poolKey));
1852
+
1853
+ const res = await this.client.devInspectTransactionBlock({
1854
+ sender: normalizeHaneulAddress(this.#address),
1855
+ transactionBlock: tx,
1856
+ });
1857
+
1858
+ const bytes = res.results![0].returnValues![0][0];
1859
+ const id = bcs.Address.parse(new Uint8Array(bytes));
1860
+ return '0x' + id;
1861
+ }
1862
+
1863
+ /**
1864
+ * @description Get the minimum withdraw risk ratio for a deepbook pool
1865
+ * @param {string} poolKey The key to identify the pool
1866
+ * @returns {Promise<number>} The minimum withdraw risk ratio as a decimal (e.g., 1.5 for 150%)
1867
+ */
1868
+ async getMinWithdrawRiskRatio(poolKey: string): Promise<number> {
1869
+ const tx = new Transaction();
1870
+ tx.add(this.marginRegistry.minWithdrawRiskRatio(poolKey));
1871
+
1872
+ const res = await this.client.devInspectTransactionBlock({
1873
+ sender: normalizeHaneulAddress(this.#address),
1874
+ transactionBlock: tx,
1875
+ });
1876
+
1877
+ const bytes = res.results![0].returnValues![0][0];
1878
+ const ratio = Number(bcs.U64.parse(new Uint8Array(bytes)));
1879
+ return ratio / FLOAT_SCALAR;
1880
+ }
1881
+
1882
+ /**
1883
+ * @description Get the minimum borrow risk ratio for a deepbook pool
1884
+ * @param {string} poolKey The key to identify the pool
1885
+ * @returns {Promise<number>} The minimum borrow risk ratio as a decimal (e.g., 1.25 for 125%)
1886
+ */
1887
+ async getMinBorrowRiskRatio(poolKey: string): Promise<number> {
1888
+ const tx = new Transaction();
1889
+ tx.add(this.marginRegistry.minBorrowRiskRatio(poolKey));
1890
+
1891
+ const res = await this.client.devInspectTransactionBlock({
1892
+ sender: normalizeHaneulAddress(this.#address),
1893
+ transactionBlock: tx,
1894
+ });
1895
+
1896
+ const bytes = res.results![0].returnValues![0][0];
1897
+ const ratio = Number(bcs.U64.parse(new Uint8Array(bytes)));
1898
+ return ratio / FLOAT_SCALAR;
1899
+ }
1900
+
1901
+ /**
1902
+ * @description Get the liquidation risk ratio for a deepbook pool
1903
+ * @param {string} poolKey The key to identify the pool
1904
+ * @returns {Promise<number>} The liquidation risk ratio as a decimal (e.g., 1.125 for 112.5%)
1905
+ */
1906
+ async getLiquidationRiskRatio(poolKey: string): Promise<number> {
1907
+ const tx = new Transaction();
1908
+ tx.add(this.marginRegistry.liquidationRiskRatio(poolKey));
1909
+
1910
+ const res = await this.client.devInspectTransactionBlock({
1911
+ sender: normalizeHaneulAddress(this.#address),
1912
+ transactionBlock: tx,
1913
+ });
1914
+
1915
+ const bytes = res.results![0].returnValues![0][0];
1916
+ const ratio = Number(bcs.U64.parse(new Uint8Array(bytes)));
1917
+ return ratio / FLOAT_SCALAR;
1918
+ }
1919
+
1920
+ /**
1921
+ * @description Get the target liquidation risk ratio for a deepbook pool
1922
+ * @param {string} poolKey The key to identify the pool
1923
+ * @returns {Promise<number>} The target liquidation risk ratio as a decimal (e.g., 1.25 for 125%)
1924
+ */
1925
+ async getTargetLiquidationRiskRatio(poolKey: string): Promise<number> {
1926
+ const tx = new Transaction();
1927
+ tx.add(this.marginRegistry.targetLiquidationRiskRatio(poolKey));
1928
+
1929
+ const res = await this.client.devInspectTransactionBlock({
1930
+ sender: normalizeHaneulAddress(this.#address),
1931
+ transactionBlock: tx,
1932
+ });
1933
+
1934
+ const bytes = res.results![0].returnValues![0][0];
1935
+ const ratio = Number(bcs.U64.parse(new Uint8Array(bytes)));
1936
+ return ratio / FLOAT_SCALAR;
1937
+ }
1938
+
1939
+ /**
1940
+ * @description Get the user liquidation reward for a deepbook pool
1941
+ * @param {string} poolKey The key to identify the pool
1942
+ * @returns {Promise<number>} The user liquidation reward as a decimal (e.g., 0.05 for 5%)
1943
+ */
1944
+ async getUserLiquidationReward(poolKey: string): Promise<number> {
1945
+ const tx = new Transaction();
1946
+ tx.add(this.marginRegistry.userLiquidationReward(poolKey));
1947
+
1948
+ const res = await this.client.devInspectTransactionBlock({
1949
+ sender: normalizeHaneulAddress(this.#address),
1950
+ transactionBlock: tx,
1951
+ });
1952
+
1953
+ const bytes = res.results![0].returnValues![0][0];
1954
+ const reward = Number(bcs.U64.parse(new Uint8Array(bytes)));
1955
+ return reward / FLOAT_SCALAR;
1956
+ }
1957
+
1958
+ /**
1959
+ * @description Get the pool liquidation reward for a deepbook pool
1960
+ * @param {string} poolKey The key to identify the pool
1961
+ * @returns {Promise<number>} The pool liquidation reward as a decimal (e.g., 0.05 for 5%)
1962
+ */
1963
+ async getPoolLiquidationReward(poolKey: string): Promise<number> {
1964
+ const tx = new Transaction();
1965
+ tx.add(this.marginRegistry.poolLiquidationReward(poolKey));
1966
+
1967
+ const res = await this.client.devInspectTransactionBlock({
1968
+ sender: normalizeHaneulAddress(this.#address),
1969
+ transactionBlock: tx,
1970
+ });
1971
+
1972
+ const bytes = res.results![0].returnValues![0][0];
1973
+ const reward = Number(bcs.U64.parse(new Uint8Array(bytes)));
1974
+ return reward / FLOAT_SCALAR;
1975
+ }
1976
+
1977
+ /**
1978
+ * @description Get all allowed maintainer cap IDs
1979
+ * @returns {Promise<string[]>} Array of allowed maintainer cap IDs
1980
+ */
1981
+ async getAllowedMaintainers(): Promise<string[]> {
1982
+ const tx = new Transaction();
1983
+ tx.add(this.marginRegistry.allowedMaintainers());
1984
+
1985
+ const res = await this.client.devInspectTransactionBlock({
1986
+ sender: normalizeHaneulAddress(this.#address),
1987
+ transactionBlock: tx,
1988
+ });
1989
+
1990
+ const bytes = res.results![0].returnValues![0][0];
1991
+ const vecSet = VecSet(bcs.Address).parse(new Uint8Array(bytes));
1992
+ return vecSet.contents.map((id) => normalizeHaneulAddress(id));
1993
+ }
1994
+
1995
+ /**
1996
+ * @description Get all allowed pause cap IDs
1997
+ * @returns {Promise<string[]>} Array of allowed pause cap IDs
1998
+ */
1999
+ async getAllowedPauseCaps(): Promise<string[]> {
2000
+ const tx = new Transaction();
2001
+ tx.add(this.marginRegistry.allowedPauseCaps());
2002
+
2003
+ const res = await this.client.devInspectTransactionBlock({
2004
+ sender: normalizeHaneulAddress(this.#address),
2005
+ transactionBlock: tx,
2006
+ });
2007
+
2008
+ const bytes = res.results![0].returnValues![0][0];
2009
+ const vecSet = VecSet(bcs.Address).parse(new Uint8Array(bytes));
2010
+ return vecSet.contents.map((id) => normalizeHaneulAddress(id));
2011
+ }
2012
+
2013
+ /**
2014
+ * @description Check if a pool is a stable pool
2015
+ * @param {string} poolKey Key of the pool
2016
+ * @returns {Promise<boolean>} Whether the pool is a stable pool
2017
+ */
2018
+ async stablePool(poolKey: string): Promise<boolean> {
2019
+ const tx = new Transaction();
2020
+ tx.add(this.deepBook.stablePool(poolKey));
2021
+
2022
+ const res = await this.client.devInspectTransactionBlock({
2023
+ sender: normalizeHaneulAddress(this.#address),
2024
+ transactionBlock: tx,
2025
+ });
2026
+
2027
+ const bytes = res.results![0].returnValues![0][0];
2028
+ return bcs.bool().parse(new Uint8Array(bytes));
2029
+ }
2030
+
2031
+ /**
2032
+ * @description Check if a pool is registered
2033
+ * @param {string} poolKey Key of the pool
2034
+ * @returns {Promise<boolean>} Whether the pool is registered
2035
+ */
2036
+ async registeredPool(poolKey: string): Promise<boolean> {
2037
+ const tx = new Transaction();
2038
+ tx.add(this.deepBook.registeredPool(poolKey));
2039
+
2040
+ const res = await this.client.devInspectTransactionBlock({
2041
+ sender: normalizeHaneulAddress(this.#address),
2042
+ transactionBlock: tx,
2043
+ });
2044
+
2045
+ const bytes = res.results![0].returnValues![0][0];
2046
+ return bcs.bool().parse(new Uint8Array(bytes));
2047
+ }
2048
+
2049
+ /**
2050
+ * @description Get the quote quantity out using input token as fee
2051
+ * @param {string} poolKey Key of the pool
2052
+ * @param {number} baseQuantity Base quantity
2053
+ * @returns {Promise<{baseQuantity: number, baseOut: number, quoteOut: number, deepRequired: number}>}
2054
+ */
2055
+ async getQuoteQuantityOutInputFee(poolKey: string, baseQuantity: number) {
2056
+ const tx = new Transaction();
2057
+ const pool = this.#config.getPool(poolKey);
2058
+ const baseScalar = this.#config.getCoin(pool.baseCoin).scalar;
2059
+ const quoteScalar = this.#config.getCoin(pool.quoteCoin).scalar;
2060
+
2061
+ tx.add(this.deepBook.getQuoteQuantityOutInputFee(poolKey, baseQuantity));
2062
+ const res = await this.client.devInspectTransactionBlock({
2063
+ sender: normalizeHaneulAddress(this.#address),
2064
+ transactionBlock: tx,
2065
+ });
2066
+
2067
+ const baseOut = Number(bcs.U64.parse(new Uint8Array(res.results![0].returnValues![0][0])));
2068
+ const quoteOut = Number(bcs.U64.parse(new Uint8Array(res.results![0].returnValues![1][0])));
2069
+ const deepRequired = Number(bcs.U64.parse(new Uint8Array(res.results![0].returnValues![2][0])));
2070
+
2071
+ return {
2072
+ baseQuantity,
2073
+ baseOut: Number((baseOut / baseScalar).toFixed(9)),
2074
+ quoteOut: Number((quoteOut / quoteScalar).toFixed(9)),
2075
+ deepRequired: Number((deepRequired / DEEP_SCALAR).toFixed(9)),
2076
+ };
2077
+ }
2078
+
2079
+ /**
2080
+ * @description Get the base quantity out using input token as fee
2081
+ * @param {string} poolKey Key of the pool
2082
+ * @param {number} quoteQuantity Quote quantity
2083
+ * @returns {Promise<{quoteQuantity: number, baseOut: number, quoteOut: number, deepRequired: number}>}
2084
+ */
2085
+ async getBaseQuantityOutInputFee(poolKey: string, quoteQuantity: number) {
2086
+ const tx = new Transaction();
2087
+ const pool = this.#config.getPool(poolKey);
2088
+ const baseScalar = this.#config.getCoin(pool.baseCoin).scalar;
2089
+ const quoteScalar = this.#config.getCoin(pool.quoteCoin).scalar;
2090
+
2091
+ tx.add(this.deepBook.getBaseQuantityOutInputFee(poolKey, quoteQuantity));
2092
+ const res = await this.client.devInspectTransactionBlock({
2093
+ sender: normalizeHaneulAddress(this.#address),
2094
+ transactionBlock: tx,
2095
+ });
2096
+
2097
+ const baseOut = Number(bcs.U64.parse(new Uint8Array(res.results![0].returnValues![0][0])));
2098
+ const quoteOut = Number(bcs.U64.parse(new Uint8Array(res.results![0].returnValues![1][0])));
2099
+ const deepRequired = Number(bcs.U64.parse(new Uint8Array(res.results![0].returnValues![2][0])));
2100
+
2101
+ return {
2102
+ quoteQuantity,
2103
+ baseOut: Number((baseOut / baseScalar).toFixed(9)),
2104
+ quoteOut: Number((quoteOut / quoteScalar).toFixed(9)),
2105
+ deepRequired: Number((deepRequired / DEEP_SCALAR).toFixed(9)),
2106
+ };
2107
+ }
2108
+
2109
+ /**
2110
+ * @description Get the quantity out using input token as fee
2111
+ * @param {string} poolKey Key of the pool
2112
+ * @param {number} baseQuantity Base quantity
2113
+ * @param {number} quoteQuantity Quote quantity
2114
+ * @returns {Promise<{baseQuantity: number, quoteQuantity: number, baseOut: number, quoteOut: number, deepRequired: number}>}
2115
+ */
2116
+ async getQuantityOutInputFee(poolKey: string, baseQuantity: number, quoteQuantity: number) {
2117
+ const tx = new Transaction();
2118
+ const pool = this.#config.getPool(poolKey);
2119
+ const baseScalar = this.#config.getCoin(pool.baseCoin).scalar;
2120
+ const quoteScalar = this.#config.getCoin(pool.quoteCoin).scalar;
2121
+
2122
+ tx.add(this.deepBook.getQuantityOutInputFee(poolKey, baseQuantity, quoteQuantity));
2123
+ const res = await this.client.devInspectTransactionBlock({
2124
+ sender: normalizeHaneulAddress(this.#address),
2125
+ transactionBlock: tx,
2126
+ });
2127
+
2128
+ const baseOut = Number(bcs.U64.parse(new Uint8Array(res.results![0].returnValues![0][0])));
2129
+ const quoteOut = Number(bcs.U64.parse(new Uint8Array(res.results![0].returnValues![1][0])));
2130
+ const deepRequired = Number(bcs.U64.parse(new Uint8Array(res.results![0].returnValues![2][0])));
2131
+
2132
+ return {
2133
+ baseQuantity,
2134
+ quoteQuantity,
2135
+ baseOut: Number((baseOut / baseScalar).toFixed(9)),
2136
+ quoteOut: Number((quoteOut / quoteScalar).toFixed(9)),
2137
+ deepRequired: Number((deepRequired / DEEP_SCALAR).toFixed(9)),
2138
+ };
2139
+ }
2140
+
2141
+ /**
2142
+ * @description Get the base quantity needed to receive target quote quantity
2143
+ * @param {string} poolKey Key of the pool
2144
+ * @param {number} targetQuoteQuantity Target quote quantity
2145
+ * @param {boolean} payWithDeep Whether to pay fees with DEEP
2146
+ * @returns {Promise<{baseIn: number, quoteOut: number, deepRequired: number}>}
2147
+ */
2148
+ async getBaseQuantityIn(poolKey: string, targetQuoteQuantity: number, payWithDeep: boolean) {
2149
+ const tx = new Transaction();
2150
+ const pool = this.#config.getPool(poolKey);
2151
+ const baseScalar = this.#config.getCoin(pool.baseCoin).scalar;
2152
+ const quoteScalar = this.#config.getCoin(pool.quoteCoin).scalar;
2153
+
2154
+ tx.add(this.deepBook.getBaseQuantityIn(poolKey, targetQuoteQuantity, payWithDeep));
2155
+ const res = await this.client.devInspectTransactionBlock({
2156
+ sender: normalizeHaneulAddress(this.#address),
2157
+ transactionBlock: tx,
2158
+ });
2159
+
2160
+ const baseIn = Number(bcs.U64.parse(new Uint8Array(res.results![0].returnValues![0][0])));
2161
+ const quoteOut = Number(bcs.U64.parse(new Uint8Array(res.results![0].returnValues![1][0])));
2162
+ const deepRequired = Number(bcs.U64.parse(new Uint8Array(res.results![0].returnValues![2][0])));
2163
+
2164
+ return {
2165
+ baseIn: Number((baseIn / baseScalar).toFixed(9)),
2166
+ quoteOut: Number((quoteOut / quoteScalar).toFixed(9)),
2167
+ deepRequired: Number((deepRequired / DEEP_SCALAR).toFixed(9)),
2168
+ };
2169
+ }
2170
+
2171
+ /**
2172
+ * @description Get the quote quantity needed to receive target base quantity
2173
+ * @param {string} poolKey Key of the pool
2174
+ * @param {number} targetBaseQuantity Target base quantity
2175
+ * @param {boolean} payWithDeep Whether to pay fees with DEEP
2176
+ * @returns {Promise<{baseOut: number, quoteIn: number, deepRequired: number}>}
2177
+ */
2178
+ async getQuoteQuantityIn(poolKey: string, targetBaseQuantity: number, payWithDeep: boolean) {
2179
+ const tx = new Transaction();
2180
+ const pool = this.#config.getPool(poolKey);
2181
+ const baseScalar = this.#config.getCoin(pool.baseCoin).scalar;
2182
+ const quoteScalar = this.#config.getCoin(pool.quoteCoin).scalar;
2183
+
2184
+ tx.add(this.deepBook.getQuoteQuantityIn(poolKey, targetBaseQuantity, payWithDeep));
2185
+ const res = await this.client.devInspectTransactionBlock({
2186
+ sender: normalizeHaneulAddress(this.#address),
2187
+ transactionBlock: tx,
2188
+ });
2189
+
2190
+ const baseOut = Number(bcs.U64.parse(new Uint8Array(res.results![0].returnValues![0][0])));
2191
+ const quoteIn = Number(bcs.U64.parse(new Uint8Array(res.results![0].returnValues![1][0])));
2192
+ const deepRequired = Number(bcs.U64.parse(new Uint8Array(res.results![0].returnValues![2][0])));
2193
+
2194
+ return {
2195
+ baseOut: Number((baseOut / baseScalar).toFixed(9)),
2196
+ quoteIn: Number((quoteIn / quoteScalar).toFixed(9)),
2197
+ deepRequired: Number((deepRequired / DEEP_SCALAR).toFixed(9)),
2198
+ };
2199
+ }
2200
+
2201
+ /**
2202
+ * @description Get account order details for a balance manager
2203
+ * @param {string} poolKey Key of the pool
2204
+ * @param {string} managerKey Key of the balance manager
2205
+ * @returns {Promise<Array>} Array of order details
2206
+ */
2207
+ async getAccountOrderDetails(poolKey: string, managerKey: string) {
2208
+ const tx = new Transaction();
2209
+ tx.add(this.deepBook.getAccountOrderDetails(poolKey, managerKey));
2210
+
2211
+ const res = await this.client.devInspectTransactionBlock({
2212
+ sender: normalizeHaneulAddress(this.#address),
2213
+ transactionBlock: tx,
2214
+ });
2215
+
2216
+ try {
2217
+ const orderInformation = res.results![0].returnValues![0][0];
2218
+ return bcs.vector(Order).parse(new Uint8Array(orderInformation));
2219
+ } catch {
2220
+ return [];
2221
+ }
2222
+ }
2223
+
2224
+ /**
2225
+ * @description Get the DEEP required for an order
2226
+ * @param {string} poolKey Key of the pool
2227
+ * @param {number} baseQuantity Base quantity
2228
+ * @param {number} price Price
2229
+ * @returns {Promise<{deepRequiredTaker: number, deepRequiredMaker: number}>}
2230
+ */
2231
+ async getOrderDeepRequired(poolKey: string, baseQuantity: number, price: number) {
2232
+ const tx = new Transaction();
2233
+ tx.add(this.deepBook.getOrderDeepRequired(poolKey, baseQuantity, price));
2234
+
2235
+ const res = await this.client.devInspectTransactionBlock({
2236
+ sender: normalizeHaneulAddress(this.#address),
2237
+ transactionBlock: tx,
2238
+ });
2239
+
2240
+ const deepRequiredTaker = Number(
2241
+ bcs.U64.parse(new Uint8Array(res.results![0].returnValues![0][0])),
2242
+ );
2243
+ const deepRequiredMaker = Number(
2244
+ bcs.U64.parse(new Uint8Array(res.results![0].returnValues![1][0])),
2245
+ );
2246
+
2247
+ return {
2248
+ deepRequiredTaker: Number((deepRequiredTaker / DEEP_SCALAR).toFixed(9)),
2249
+ deepRequiredMaker: Number((deepRequiredMaker / DEEP_SCALAR).toFixed(9)),
2250
+ };
2251
+ }
2252
+
2253
+ /**
2254
+ * @description Check if account exists for a balance manager
2255
+ * @param {string} poolKey Key of the pool
2256
+ * @param {string} managerKey Key of the balance manager
2257
+ * @returns {Promise<boolean>} Whether account exists
2258
+ */
2259
+ async accountExists(poolKey: string, managerKey: string): Promise<boolean> {
2260
+ const tx = new Transaction();
2261
+ tx.add(this.deepBook.accountExists(poolKey, managerKey));
2262
+
2263
+ const res = await this.client.devInspectTransactionBlock({
2264
+ sender: normalizeHaneulAddress(this.#address),
2265
+ transactionBlock: tx,
2266
+ });
2267
+
2268
+ const bytes = res.results![0].returnValues![0][0];
2269
+ return bcs.bool().parse(new Uint8Array(bytes));
2270
+ }
2271
+
2272
+ /**
2273
+ * @description Get the next epoch trade parameters
2274
+ * @param {string} poolKey Key of the pool
2275
+ * @returns {Promise<{takerFee: number, makerFee: number, stakeRequired: number}>}
2276
+ */
2277
+ async poolTradeParamsNext(poolKey: string) {
2278
+ const tx = new Transaction();
2279
+ tx.add(this.deepBook.poolTradeParamsNext(poolKey));
2280
+
2281
+ const res = await this.client.devInspectTransactionBlock({
2282
+ sender: normalizeHaneulAddress(this.#address),
2283
+ transactionBlock: tx,
2284
+ });
2285
+
2286
+ const takerFee = Number(bcs.U64.parse(new Uint8Array(res.results![0].returnValues![0][0])));
2287
+ const makerFee = Number(bcs.U64.parse(new Uint8Array(res.results![0].returnValues![1][0])));
2288
+ const stakeRequired = Number(
2289
+ bcs.U64.parse(new Uint8Array(res.results![0].returnValues![2][0])),
2290
+ );
2291
+
2292
+ return {
2293
+ takerFee: takerFee / FLOAT_SCALAR,
2294
+ makerFee: makerFee / FLOAT_SCALAR,
2295
+ stakeRequired: stakeRequired / DEEP_SCALAR,
2296
+ };
2297
+ }
2298
+
2299
+ /**
2300
+ * @description Get the quorum for a pool
2301
+ * @param {string} poolKey Key of the pool
2302
+ * @returns {Promise<number>} The quorum amount in DEEP
2303
+ */
2304
+ async quorum(poolKey: string): Promise<number> {
2305
+ const tx = new Transaction();
2306
+ tx.add(this.deepBook.quorum(poolKey));
2307
+
2308
+ const res = await this.client.devInspectTransactionBlock({
2309
+ sender: normalizeHaneulAddress(this.#address),
2310
+ transactionBlock: tx,
2311
+ });
2312
+
2313
+ const bytes = res.results![0].returnValues![0][0];
2314
+ const quorum = Number(bcs.U64.parse(new Uint8Array(bytes)));
2315
+ return quorum / DEEP_SCALAR;
2316
+ }
2317
+
2318
+ /**
2319
+ * @description Get the pool ID
2320
+ * @param {string} poolKey Key of the pool
2321
+ * @returns {Promise<string>} The pool ID
2322
+ */
2323
+ async poolId(poolKey: string): Promise<string> {
2324
+ const tx = new Transaction();
2325
+ tx.add(this.deepBook.poolId(poolKey));
2326
+
2327
+ const res = await this.client.devInspectTransactionBlock({
2328
+ sender: normalizeHaneulAddress(this.#address),
2329
+ transactionBlock: tx,
2330
+ });
2331
+
2332
+ const bytes = res.results![0].returnValues![0][0];
2333
+ return normalizeHaneulAddress(bcs.Address.parse(new Uint8Array(bytes)));
2334
+ }
2335
+
2336
+ /**
2337
+ * @description Check if a limit order can be placed
2338
+ * @param {CanPlaceLimitOrderParams} params Parameters for checking limit order placement
2339
+ * @returns {Promise<boolean>} Whether order can be placed
2340
+ */
2341
+ async canPlaceLimitOrder(params: CanPlaceLimitOrderParams): Promise<boolean> {
2342
+ const tx = new Transaction();
2343
+ tx.add(this.deepBook.canPlaceLimitOrder(params));
2344
+
2345
+ const res = await this.client.devInspectTransactionBlock({
2346
+ sender: normalizeHaneulAddress(this.#address),
2347
+ transactionBlock: tx,
2348
+ });
2349
+
2350
+ const bytes = res.results![0].returnValues![0][0];
2351
+ return bcs.bool().parse(new Uint8Array(bytes));
2352
+ }
2353
+
2354
+ /**
2355
+ * @description Check if a market order can be placed
2356
+ * @param {CanPlaceMarketOrderParams} params Parameters for checking market order placement
2357
+ * @returns {Promise<boolean>} Whether order can be placed
2358
+ */
2359
+ async canPlaceMarketOrder(params: CanPlaceMarketOrderParams): Promise<boolean> {
2360
+ const tx = new Transaction();
2361
+ tx.add(this.deepBook.canPlaceMarketOrder(params));
2362
+
2363
+ const res = await this.client.devInspectTransactionBlock({
2364
+ sender: normalizeHaneulAddress(this.#address),
2365
+ transactionBlock: tx,
2366
+ });
2367
+
2368
+ const bytes = res.results![0].returnValues![0][0];
2369
+ return bcs.bool().parse(new Uint8Array(bytes));
2370
+ }
2371
+
2372
+ /**
2373
+ * @description Check if market order params are valid
2374
+ * @param {string} poolKey Key of the pool
2375
+ * @param {number} quantity Quantity
2376
+ * @returns {Promise<boolean>} Whether params are valid
2377
+ */
2378
+ async checkMarketOrderParams(poolKey: string, quantity: number): Promise<boolean> {
2379
+ const tx = new Transaction();
2380
+ tx.add(this.deepBook.checkMarketOrderParams(poolKey, quantity));
2381
+
2382
+ const res = await this.client.devInspectTransactionBlock({
2383
+ sender: normalizeHaneulAddress(this.#address),
2384
+ transactionBlock: tx,
2385
+ });
2386
+
2387
+ const bytes = res.results![0].returnValues![0][0];
2388
+ return bcs.bool().parse(new Uint8Array(bytes));
2389
+ }
2390
+
2391
+ /**
2392
+ * @description Check if limit order params are valid
2393
+ * @param {string} poolKey Key of the pool
2394
+ * @param {number} price Price
2395
+ * @param {number} quantity Quantity
2396
+ * @param {number} expireTimestamp Expiration timestamp
2397
+ * @returns {Promise<boolean>} Whether params are valid
2398
+ */
2399
+ async checkLimitOrderParams(
2400
+ poolKey: string,
2401
+ price: number,
2402
+ quantity: number,
2403
+ expireTimestamp: number,
2404
+ ): Promise<boolean> {
2405
+ const tx = new Transaction();
2406
+ tx.add(this.deepBook.checkLimitOrderParams(poolKey, price, quantity, expireTimestamp));
2407
+
2408
+ const res = await this.client.devInspectTransactionBlock({
2409
+ sender: normalizeHaneulAddress(this.#address),
2410
+ transactionBlock: tx,
2411
+ });
2412
+
2413
+ const bytes = res.results![0].returnValues![0][0];
2414
+ return bcs.bool().parse(new Uint8Array(bytes));
2415
+ }
2416
+
2417
+ /**
2418
+ * @description Helper function to format token amounts without floating point errors
2419
+ * @param {bigint} rawAmount The raw amount as bigint
2420
+ * @param {number} scalar The token scalar (e.g., 1000000000 for 9 decimals)
2421
+ * @param {number} decimals Number of decimal places to show
2422
+ * @returns {string} Formatted amount as string
2423
+ */
2424
+ #formatTokenAmount(rawAmount: bigint, scalar: number, decimals: number): string {
2425
+ const scalarBigInt = BigInt(scalar);
2426
+ const integerPart = rawAmount / scalarBigInt;
2427
+ const fractionalPart = rawAmount % scalarBigInt;
2428
+
2429
+ // If no fractional part, return just the integer
2430
+ if (fractionalPart === 0n) {
2431
+ return integerPart.toString();
2432
+ }
2433
+
2434
+ // Convert fractional part to string with leading zeros
2435
+ const scalarDigits = scalar.toString().length - 1;
2436
+ const fractionalStr = fractionalPart.toString().padStart(scalarDigits, '0');
2437
+
2438
+ // Truncate to desired decimal places
2439
+ const truncated = fractionalStr.slice(0, decimals);
2440
+
2441
+ // Remove trailing zeros for cleaner output
2442
+ const trimmed = truncated.replace(/0+$/, '');
2443
+
2444
+ // If nothing left after trimming, return just integer
2445
+ if (!trimmed) {
2446
+ return integerPart.toString();
2447
+ }
2448
+
2449
+ return `${integerPart}.${trimmed}`;
2450
+ }
2451
+ }